Skip to content

feat(cli): CLI improvements — CLI_IMPROVEMENTS_PLAN (C1, C6–C9, D1–D6)#220

Open
lookinway wants to merge 22 commits into
mainfrom
feat/cli-c1-self-documenting-api
Open

feat(cli): CLI improvements — CLI_IMPROVEMENTS_PLAN (C1, C6–C9, D1–D6)#220
lookinway wants to merge 22 commits into
mainfrom
feat/cli-c1-self-documenting-api

Conversation

@lookinway
Copy link
Copy Markdown
Collaborator

@lookinway lookinway commented May 15, 2026

Полная реализация плана CLI_IMPROVEMENTS_PLAN.md (перенос лучших практик из Notion CLI). Одна ветка, по одному коммиту на пункт.

Готово на 100% (Фаза 1 + Фаза 2)

Пункт Коммит Суть
C1 ca2417a Самодокументируемый pachca api: ls / --describe / --spec / --docs (флагман)
C6 ac8cb1c pachca api --data '{json}' — инлайн JSON-тело
D0/D1 1ba3df6 cli.mdx (590 строк) → 8 страниц Get started / Guides / Reference + прогрессия аудиторий + редиректы
D6 3524698 Overview — мягкая развилка terminal-first
D4 f54b31f ai-agents.mdx: CLI-подсекция под C1 (цикл самопознания вместо --help)
D3 b47c77e Единый источник глобальных флагов: baseFlagsglobal-flags.json (было 4 расходящихся места)
D2 8ac6c18 Авто-страница Commands: общий manifest.ts, commands.json, флаги/аргументы по секциям
D5 dec25da Аудит: все CLI-страницы в llms.txt/llms-full.txt (авто через навигацию)
C7 51bf31b --plain — именованный TSV-режим вывода
C8 8e6bc6e PACHCA_HOME — override каталога конфига (guarded)
C9 5676769 Autocomplete: fish (не работал) → powershell (работает) — фикс доки
релиз b1e29f4 Changelog 2026.5.2 + releases.json + updates.mdx

Отклонены планом (не делались): C2, C3, C4, C5, D7.

Релиз 2026.5.2

  • changelog.json2026.5.2 (15 мая 2026): C1/C6/C7/C8 (user-facing). CHANGELOG.md регенерируется на build. diff-endpoints.ts уважает ручные записи (CI не перетрёт при публикации).
  • Версия: CalVer YYYY.M.patch вычисляется CI при публикации (следующая = 2026.5.2, т.к. на npm уже 2026.5.0/2026.5.1). package.json остаётся 0.0.0 намеренно — publish-воркфлоу подставляет версию. Больше нигде не пинится.
  • releases.json + updates.mdx — запись от 2026-05-15 (для таймлайна обновлений в доке). D*/C9 (docs-only) в CLI-changelog не попадают — корректно.

Гарантии

  • Каждый коммит: npx turbo build 26/26 ✅ + npx turbo check 19/19 ✅ (1915 тестов CLI green).
  • CLI-код строго аддитивен; C8 guarded (без переменной путь байт-в-байт прежний).
  • Антидубль: C1/D2/D3 переиспользуют существующие генераторы.
  • Ноль raw-MDX-протечек в сгенерированных .md/llms*.txt.
  • CLI_IMPROVEMENTS_PLAN.md — чек-листы проставлены, статус «реализовано 100%».

🤖 Generated with Claude Code

…ec / --docs)

Make the CLI describe the API against its own spec, so agents need not load
docs into context or hit the dev site — they ask the CLI for exactly the
method they need and call it.

- `pachca api ls [--json]` — list every endpoint (METHOD PATH SUMMARY SCOPE)
- `pachca api <M> <path> --describe` — compact reference (params, body,
  scope, equivalent typed command, doc link)
- `pachca api <M> <path> --spec` — resolved OpenAPI fragment
- `pachca api <M> <path> --docs` — full markdown reference (same as
  public/api/*.md)

Implementation is strictly additive:
- api.ts intercepts raw `this.argv` BEFORE `this.parse(Api)` (the `method`
  arg is required+enum); the normal request path is untouched. Method is
  positional, so `--describe/--spec/--docs` are unambiguous by construction
  (no `-X` needed, unlike Notion's `ntn api`).
- New `src/api-introspect.ts` holds pure helpers (testable, thin runtime).
- generate-cli.ts emits `src/data/endpoints.json` at build time, reusing the
  apps/docs generators (parseOpenAPI / generateEndpointMarkdown / generateCLI
  / schemaToMarkdown) — heavy logic reused, ~zero new rendering code. JSON is
  minified (machine-only index, lazily loaded only for these subcommands).
- turbo `generate-cli` input widened to `apps/docs/lib/**` for correct cache
  invalidation of the newly cross-imported generators.
- Docs: new "Самоописание API" section in cli.mdx (+ regenerated cli.md /
  llms-full.txt); `api` command examples + description updated.
- Tests: tests/api-introspect.test.ts (10) — pure helpers, endpoints.json
  shape, runCommand integration (ls/--describe/--spec/not-found).

Plan: CLI_IMPROVEMENTS_PLAN.md added as the in-repo source of truth (Q6),
C1 checklist ticked.
@lookinway lookinway changed the title feat(cli): C1 — self-documenting pachca api (ls / --describe / --spec / --docs) feat(cli): CLI improvements — CLI_IMPROVEMENTS_PLAN (C1, C6–C9, D1–D6) May 15, 2026
lookinway added 21 commits May 15, 2026 18:17
Add a self-contained inline body flag, mirroring curl -d / httpie --raw /
stripe -d. Cleaner than `echo '{...}' | … --input -` for agents (no pipe,
no knowing `--input -`, no shell-quoting gymnastics).

- New `--data` flag; reuses the exact string → JSON → body path as
  `--input` (thin alias, not a parallel system).
- Mutual exclusivity with `-f/-F` and `--input`, next to the existing check.
- Invalid JSON → PACHCA_USAGE_ERROR, exit 2.
- Docs: line in cli.mdx "Прямые API-запросы" (+ regenerated cli.md /
  llms-full.txt); `api` command example added.
- Tests: tests/api-data.test.ts (4) — dry-run body, both mutex paths,
  invalid JSON.

turbo build 26/26, turbo check 19/19. CLI_IMPROVEMENTS_PLAN.md C6 ticked.
The 590-line monolith becomes 8 focused pages under /guides/cli/* with an
audience progression (terminal → agent) expressed by structure and words,
no icons (Q8).

Pages (content verbatim, nothing lost):
- Get started: overview, installation (incl. autocomplete/settings/doctor/
  upgrade), authentication
- Guides: api-requests (pachca api + C1 self-documentation), scripting
  (output/pagination/flags/exit codes/errors/env), files, workflows
- Reference: commands (CliCommands; D2 will enrich)

- tabs-config.ts: CLI becomes an accordion parent with 8 children
  (SDK/forms/n8n pattern); order encodes the Get started → Guides →
  Reference progression.
- redirects.ts: /guides/cli (+ .md) → /guides/cli/overview (accordion
  parent → first child pattern). Internal links updated (home, quickstart,
  workflows, cards.tsx icon map). ai-agents.mdx left for D4 (redirect
  covers it meanwhile).
- D0 audience progression (Q9, key places only, no icons): "Если вы в
  терминале…" / "Если подключаете агента…" in overview/installation/
  authentication; agent rationale in api-requests.
- Stale public/guides/cli.md removed; generators emit cli/*.md and pick up
  the new pages in llms.txt/llms-full.txt automatically (closes D5's
  mechanism).
- Multi-card grid uses <CardGroup> (mdx-expander expands it cleanly to a
  list); single compact npm card stays <CardRow>. Verified: zero raw-MDX
  leak in all generated cli/*.md.

turbo build 26/26, turbo check 19/19 (prettier OK on new MDX).
CLI_IMPROVEMENTS_PLAN.md D1 ticked.
Rework /guides/cli/overview into a soft fork, not an equal router:
- short tagline
- "Начните в терминале" — the primary, accented path: Steps
  Установка → Авторизация → Первые команды (terminal-first)
- "Следующий шаг: подключить агента" — lighter, inviting next-step
  → /guides/ai-agents (D4 hub), framed as an upgrade of the same tool,
  not a separate world
- 5 capability cards (CardGroup) into the guides
- text wall removed

Reuses existing CardRow/CardGroup/Card/Steps (no new components, no
icons — Q8). Fixed a generated-md gotcha: a non-compact single <Card>
in <CardRow> leaks raw (mdx-expander only converts standalone
<Card compact>); the agent invite is now compact (also the right
visual weight). Verified zero raw-MDX leak across all cli/*.md.

turbo build 26/26, turbo check 19/19. CLI_IMPROVEMENTS_PLAN.md D6 ticked.
Rewrite the CLI block of "Как подключить Пачку к агенту" around C1's
self-documentation instead of `--help`:

- Plain-language thesis (no jargon): the agent does not load docs into
  context or visit the site — the CLI describes the API itself; the
  agent asks for exactly the method it needs and calls it.
- Self-knowledge cycle example: api ls → api <M> <path> --describe →
  typed command with --no-input -o json.
- npx (why npx for an agent: no install, always latest).
- Token bootstrap: PACHCA_TOKEN / --token, nothing on disk, do not
  commit to the repo.
- Branching via exit codes + PACHCA_*_ERROR `type`.

The "5 ways" structure and positioning phrasing ("самый быстрый и
производительный способ") are preserved — only the CLI block is
strengthened. Card → /guides/cli/overview; a "mechanics" link →
/guides/cli/api-requests (no duplication: hub = thesis+example, CLI
pages = mechanics). Scenarios not duplicated.

turbo build 26/26, turbo check 19/19; ai-agents.md regenerates with no
raw-MDX leak. CLI_IMPROVEMENTS_PLAN.md D4 ticked.
Global flags were defined in 4 places that drifted (baseFlags, README
hardcode, guide table, introspect's manual Set): `--quiet` worded
differently, README missing --no-truncate/--no-color/--no-retry.

Now one source: BaseCommand.baseFlags.
- generate-cli.ts emits src/data/global-flags.json from baseFlags
  (structure: name/char/type/options/hidden) + a single RU description
  map (the only localized copy; baseFlags descriptions stay English for
  --help, Q1 keeps docs RU).
- generateReadme() builds the flags table from it (hardcoded array gone).
- introspect.ts baseFlagNames = Object.keys(BaseCommand.baseFlags)
  (manual Set gone; --plain from C7 will be picked up automatically).
  Byte-identical to the old 14-name Set; behavior unchanged.
- Guide: scripting.mdx hardcoded table → <GlobalFlags /> (new
  lib/cli-data.ts loader reading the committed JSON cwd-relative like
  parser.ts reads openapi.yaml; component registered in both maps +
  mdx-expander handler — verified clean expansion in generated md/llms).
- --quiet unified; --force documented as per-command (not global).
- turbo generate-cli input += src/base-command.ts.

turbo build 26/26, turbo check 19/19 (1901 tests incl. introspect).
CLI_IMPROVEMENTS_PLAN.md D3 ticked.
The docs Commands table showed only command + API method. Now it is
generated from oclif.manifest.json with full flags/args, grouped by
section, with a global-flags + env header.

Anti-duplication (one parsing logic, one data source):
- New src/lib/manifest.ts holds the manifest normalization
  (listCommandEntries / normalizeCommand / groupCommandsBySection).
- introspect.ts now calls it — output byte-identical (1905 tests green).
- scripts/emit-commands.ts (in the build chain, after `oclif manifest`)
  reuses the SAME manifest.ts to emit src/data/commands.json (27
  sections, 85 commands). Atomic write (tmp+rename): turbo runs the docs
  build in parallel with no ordering dep, so a concurrent reader must
  never see a partial file (this was the intermittent docs-build race).

Docs:
- lib/cli-data.ts gains getCliSections() — reads the committed JSON via
  a cwd-relative path (same pattern parser.ts uses for openapi.yaml; no
  cross-package TS import, no Next transpile fragility).
- <CliCommands /> rewritten: per-section, each command with its
  flags/args (name / type / required* / options / description),
  EndpointLink kept for API metadata (scope/plan/auth from OpenAPI).
- mdx-expander <CliCommands /> handler → compact per-section tables
  (HTML is rich; the .md/llms stays lean on purpose to not bloat
  llms-full.txt).
- commands.mdx header: <GlobalFlags /> (D3 source) + a link to env vars
  in Scripting (env not duplicated).
- turbo build outputs += src/data/commands.json; package.json build
  chain += emit-commands.

turbo build 26/26, turbo check 19/19 (1905 tests). No raw-MDX leak in
generated md/llms. CLI_IMPROVEMENTS_PLAN.md D2 ticked.
All 8 split CLI pages appear in llms.txt (index, once each) and
llms-full.txt (full bodies). generate-llms picked them up automatically
via navigation (D1) — no generator change needed, as the plan predicted.
The only legacy /guides/cli reference is a dated updates.mdx entry
(history not rewritten; the /guides/cli → overview redirect covers it).
ai-agents.mdx llms narrative remains consistent.

Audit-only; CLI_IMPROVEMENTS_PLAN.md D5 ticked.
`--plain` = TSV, no header, `id` column first, no color/truncation —
a discoverable named mode instead of the `--columns … --no-header -o csv`
incantation (the Notion `--plain` convention).

- output.ts: outputPlain — a variant of outputCsv (\t, no header, id-first
  when no explicit --columns, tab/newline in values collapsed to spaces so
  records stay one-per-line for cut/awk). outputData checks opts.plain
  before the format dispatch; json/yaml/csv/table untouched (additive).
- base-command.ts: `plain` baseFlag + getOutputOptions().plain → works for
  every command via output().
- Propagated automatically through D3 (single source = baseFlags):
  introspect baseFlagNames, global-flags.json, README table and
  <GlobalFlags /> all pick it up — only the RU description map needed a
  line.
- Tests: tests/output-plain.test.ts (7). Docs: "Плоский вывод" section
  in scripting.mdx.

turbo build 26/26, turbo check 19/19 (1912 tests). CLI_IMPROVEMENTS_PLAN.md
C7 ticked.
Add PACHCA_HOME as the highest-priority config directory override
(NOTION_HOME equivalent) — useful for isolating config in CI / tests /
agents.

- profiles.ts getConfigDir(): new branch FIRST, returning
  $PACHCA_HOME/pachca. Guarded — when PACHCA_HOME is unset the resolved
  path is byte-identical to before (XDG_CONFIG_HOME / LOCALAPPDATA / home
  logic untouched), so existing behavior is preserved.
- Tests: tests/profiles-home.test.ts (3) — regression "unset ⇒ XDG path
  unchanged", priority over XDG, write/read profile under $PACHCA_HOME.
- Docs: PACHCA_HOME row in the env-vars table (scripting.mdx).

turbo build 26/26, turbo check 19/19 (1915 tests). CLI_IMPROVEMENTS_PLAN.md
C8 ticked.
Audit: @oclif/plugin-autocomplete@3.2.42 supports only zsh/bash/
powershell (the `shell` arg's options). `pachca autocomplete fish`
actually ERRORS ("Expected fish to be one of: zsh, bash, powershell")
— the docs promised a shell that does not work. PowerShell IS
supported here because Pachca uses a space topicSeparator (the plugin
only blocks PowerShell when the separator is ':').

Documentation-only fix (no CLI code change — PowerShell already works
out of the box):
- installation.mdx: "bash, zsh и fish" → "bash, zsh и PowerShell";
  `autocomplete fish` → `autocomplete powershell`.
- README.template.md: same (README.md regenerates on build).
fish/elvish remain out of scope (unsupported by the v3 plugin); no
more false promises in the docs.

turbo build 26/26, turbo check 19/19 (1915 tests). CLI_IMPROVEMENTS_PLAN.md
C9 ticked.
Coordinated release entries for the CLI improvements (C1/C6/C7/C8 —
user-facing features only; D* are docs-site, C9 is a docs fix → not in
the CLI package changelog).

- packages/cli/src/data/changelog.json: prepend 2026.5.2 (15 мая 2026).
  CHANGELOG.md regenerates from it on build (verified). diff-endpoints.ts
  honors manual entries (skips auto-gen when the version already exists),
  so CI will keep this at publish.
- Version: CalVer YYYY.M.patch is computed by CI at publish (next =
  2026.5.2, since 2026.5.0/2026.5.1 are on npm). package.json stays
  0.0.0 by design — the publish workflow injects the version. Nothing
  else to bump.
- apps/docs/data/releases.json: prepend the cli 2026.5.2 release
  (ISO 2026-05-15) for the docs Updates timeline.
- apps/docs/content/updates.mdx: new <!-- update:2026-05-15 --> narrative
  entry (one marker per date; no HTTP badges — CLI features, not
  endpoints; per updates_format).
- installation.mdx: illustrative `doctor` output bumped to v2026.5.2.

turbo build 26/26, turbo check 19/19. No raw-MDX leak in generated
updates.md.
…учился"

The terms "самоописание API" and "против собственной спецификации" were
unclear, and "CLI научился" wrongly implied the CLI learned something —
we simply added new commands.

Reworded across all user-facing surfaces (updates.mdx, changelog.json,
releases.json, ai-agents.mdx, overview/api-requests/commands pages, the
`api` command --help description):
- plain framing: "В CLI добавлены команды, которые показывают список
  всех эндпоинтов и справку по каждому"
- the spec link explained instead of jargon: "данные генерируются из той
  же OpenAPI-спецификации, из которой собран CLI, поэтому всегда
  совпадают с актуальным API"
- headings: "Самоописание API" → "Список эндпоинтов и справка по API"

No behavior change. CHANGELOG.md / generated md / llms regenerate.
turbo build 26/26, turbo check 19/19.
The narrative duplicated the per-command/flag list that the CLI release
card (releases.json 2026.5.2) already renders below it in the same
timeline. Cut to two short paragraphs: what changed, why, and links.

turbo build 26/26, turbo check 19/19.
The only content dropped by the split was a 3-line illustrative output
table for `pachca users list` (trimmed during D6's text-wall pass).
Restored compactly in the 'Первые команды' step. Verified against the
original cli.mdx (origin/main): every other command, flag, table,
callout, JSON example, the pagination two-groups note, kebab-case
mapping, exit codes and error taxonomy are preserved; the global-flags
table is now <GlobalFlags/> (generated, more complete) and
`autocomplete fish` was intentionally replaced by powershell (C9).

turbo build 26/26, turbo check 19/19.
The split over-elevated the `pachca api` escape-hatch + endpoint
introspection and buried the typed commands — inverting the original
doc's emphasis (orig: "Команды" early at line 112, "Прямые API-запросы"
near the end at line 483). Market practice agrees: gh `gh api` is one
auxiliary command among ~50; Stripe documents resource commands as
PRIMARY and raw HTTP as "auxiliary shortcuts" after them. Notion leans
on `ntn api` only because its CLI is thin — not our model (60+ typed
commands from OpenAPI).

Rebalance (no behavior change, docs only):
- Nav reorder: Обзор → Установка → Авторизация → **Команды** →
  Сценарии → Скрипты и CI → Файлы → **Прямые запросы** (last).
  Команды moves up to the primary slot; the api page moves to the end.
- Rename "Запросы к API" → "Прямые запросы" (slug /api-requests kept;
  no redirect/link churn). H1 + frontmatter updated.
- api-requests.mdx reframed: opens with "основной способ — типизированные
  команды (см. Команды и Сценарии)"; `pachca api` explicitly
  "вспомогательная команда (escape hatch) для редких случаев". The
  endpoint-discovery section retitled "Если не знаете нужный эндпоинт"
  (a discovery aid, not a headline). Agent note demoted to a fallback.
- Overview cards reordered: Команды + Сценарии first, Прямые запросы
  last; api card relabeled "вспомогательный pachca api".
- ai-agents.mdx CLI block now leads with "агент работает теми же
  типизированными командами; готовые последовательности — Сценарии";
  api ls/--describe presented as on-demand discovery when the endpoint
  is unknown.
- Link labels "Запросы к API" → "Прямые запросы"; updates.mdx "подробнее"
  now points to Команды/Сценарии first.
- README.md regenerated (C9 fish→powershell propagation, was lagging).

turbo build 26/26, turbo check 19/19. No raw-MDX leak.
Addresses review feedback:

- Commands page width bug: <CliCommands/> FlagsArgs table now
  table-fixed with a 26/26/48 colgroup and break-words on all cells;
  removed whitespace-nowrap on the type cell. Long enum options (e.g.
  --event-key: user_login | user_logout | …) wrap inside their column
  instead of overflowing and overlapping the right-side TOC.
- Nav: Скрипты и CI moved above Сценарии
  (Обзор → Установка → Авторизация → Команды → Скрипты и CI →
  Сценарии → Файлы → Прямые запросы).
- Overview rewritten: drop "Начните в терминале" framing; show Быстрый
  старт (install/auth/first request) then an explicit "Два способа
  работы" section explaining (1) типизированные команды + `--help`,
  (2) `pachca api` + встроенный справочник по API (no docs site
  needed). Cards have NO icons, descriptions rewritten; agent invite
  folded into a card.
- Прямые запросы page: no longer opens with "основной способ —
  типизированные команды". Opens by stating pachca api does two things
  (direct HTTP request + built-in API reference, no docs site). Two
  clear sections: "Прямой HTTP-запрос" and "Встроенный справочник по
  API" (the built-in reference is now a first-class, explained part,
  not a lonely "если не знаете эндпоинт" heading).

turbo build 26/26, turbo check 19/19. No raw-MDX leak.
…headings

Per review: drop the "1./2." numbering, add an intro paragraph after
the heading, split into two ### subheadings (Типизированные команды /
Прямые запросы). Keeps the user's "Команда `pachca api`" phrasing style.

turbo build 26/26, turbo check 19/19.
…hca api"

Per review:
- "## Два способа работы" → "## Способы работы"
- intro "С API можно работать…" → "С CLI можно работать…" (you work
  with the CLI, not "with API")
- bare prose "`pachca api`" → "команда `pachca api`" (the intro line
  and the Прямые запросы card). Verified across all CLI pages +
  ai-agents: every noun-reference now reads "команда `pachca api`";
  command examples (`pachca api ls`, `pachca api POST …`) left bare,
  as intended.

turbo build 26/26, turbo check 19/19.
- Overview "Разделы" no longer lists "AI агенты": it's a separate
  top-level guide, not a CLI sub-section, and the relationship is
  one-way (ai-agents.mdx links here). Cards now = the 5 CLI sub-pages.
- ai-agents.mdx CLI block reviewed (reads well: command-first,
  Scenarios link, token/exit-codes, introspection as fallback). Fixed
  the pointer line for consistency: "Вспомогательная команда pachca api
  и поиск эндпоинтов" → "Команда `pachca api` (прямые запросы) и
  встроенный справочник по API" — matches the terminology used
  everywhere else.

turbo build 26/26, turbo check 19/19. No raw-MDX leak.
…code)

Card-specific: per review the Разделы card should match its siblings —
plain descriptive phrase, no leading "команда", no `pachca api` code
span. Now: "Прямой HTTP-запрос к любому методу и встроенный справочник
по API в терминале". Prose elsewhere keeps "команда `pachca api`".

turbo build 26/26, turbo check 19/19.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant