From ed2682bf3ac4bfad3e6c3cdce142c2b61d6ec653 Mon Sep 17 00:00:00 2001 From: fedorovvvv Date: Fri, 8 May 2026 23:29:09 +0400 Subject: [PATCH 1/7] =?UTF-8?q?docs(forgeplan):=20shape=20#109=20multi-ins?= =?UTF-8?q?tance=20=E2=80=94=2015=20artifacts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Decompose GitHub issue #109 (multi-instance management) into 6 sub-issues (#110-#115) and a full Forgeplan artifact set. All 15 artifacts pass forgeplan validate with 0 MUST errors; 14 cross-references wired. Refs: PRD-024, PRD-025, PRD-026, PRD-027, PRD-028, PRD-029, ADR-003, ADR-004, SPEC-003, RFC-020, RFC-021, RFC-022, RFC-023, RFC-024, RFC-025 Also deprecates EVID-007 + EVID-008 (100% duplicates of EVID-004 + EVID-005). Co-Authored-By: Claude Opus 4.7 (1M context) --- ...ep-esm-cli-library-in-bin-amend-rule-23.md | 414 ++++++++++++++++++ ...-instance-registry-path-and-json-format.md | 414 ++++++++++++++++++ ...preserves-createdat-removes-stale-files.md | 3 +- ...02-protocol-files-exist-and-are-indexed.md | 3 +- ...-citty-integration-bin-subcommand-split.md | 263 +++++++++++ ...roject-with-interactive-prompt-fallback.md | 275 ++++++++++++ ...on-chain-project-to-user-to-prompt-init.md | 273 ++++++++++++ ...al-ports-global-json-stale-invalidation.md | 290 ++++++++++++ ...box-primitive-in-shared-ui-bits-ui-port.md | 260 +++++++++++ ...witcher-combobox-wired-to-api-instances.md | 312 +++++++++++++ ...ation-architecture-bin-subcommand-split.md | 265 +++++++++++ ...nd-user-scope-path-conventions-for-init.md | 251 +++++++++++ ...ffold-resolution-algorithm-and-error-ux.md | 273 ++++++++++++ ...d-liveness-probe-atomic-registry-writes.md | 408 +++++++++++++++++ ...ui-wrapper-variants-playground-showcase.md | 306 +++++++++++++ ...her-and-api-instances-readonly-endpoint.md | 361 +++++++++++++++ ...son-schema-forgeplan-web-instances-json.md | 253 +++++++++++ 17 files changed, 4622 insertions(+), 2 deletions(-) create mode 100644 .forgeplan/adrs/ADR-003-permit-citty-zero-dep-esm-cli-library-in-bin-amend-rule-23.md create mode 100644 .forgeplan/adrs/ADR-004-instance-registry-path-and-json-format.md create mode 100644 .forgeplan/prds/PRD-024-citty-integration-bin-subcommand-split.md create mode 100644 .forgeplan/prds/PRD-025-init-scope-user-project-with-interactive-prompt-fallback.md create mode 100644 .forgeplan/prds/PRD-026-start-resolution-chain-project-to-user-to-prompt-init.md create mode 100644 .forgeplan/prds/PRD-027-multi-instance-registry-incremental-ports-global-json-stale-invalidation.md create mode 100644 .forgeplan/prds/PRD-028-combobox-primitive-in-shared-ui-bits-ui-port.md create mode 100644 .forgeplan/prds/PRD-029-healthbar-instance-switcher-combobox-wired-to-api-instances.md create mode 100644 .forgeplan/rfcs/RFC-020-citty-integration-architecture-bin-subcommand-split.md create mode 100644 .forgeplan/rfcs/RFC-021-scope-resolver-and-user-scope-path-conventions-for-init.md create mode 100644 .forgeplan/rfcs/RFC-022-start-scaffold-resolution-algorithm-and-error-ux.md create mode 100644 .forgeplan/rfcs/RFC-023-port-allocator-pid-liveness-probe-atomic-registry-writes.md create mode 100644 .forgeplan/rfcs/RFC-024-combobox-primitive-bits-ui-wrapper-variants-playground-showcase.md create mode 100644 .forgeplan/rfcs/RFC-025-healthbar-instance-switcher-and-api-instances-readonly-endpoint.md create mode 100644 .forgeplan/specs/SPEC-003-instance-registry-json-schema-forgeplan-web-instances-json.md diff --git a/.forgeplan/adrs/ADR-003-permit-citty-zero-dep-esm-cli-library-in-bin-amend-rule-23.md b/.forgeplan/adrs/ADR-003-permit-citty-zero-dep-esm-cli-library-in-bin-amend-rule-23.md new file mode 100644 index 0000000..c8dbf0c --- /dev/null +++ b/.forgeplan/adrs/ADR-003-permit-citty-zero-dep-esm-cli-library-in-bin-amend-rule-23.md @@ -0,0 +1,414 @@ +--- +created: 2026-05-08 +depth: standard +id: ADR-003 +kind: adr +links: +- target: PRD-024 + relation: informs +problem_ref: PROB-003 +status: draft +title: Permit citty (zero-dep ESM CLI library) in bin/ — amend rule 23 +updated: 2026-05-08 +--- + +# ADR-003: Permit citty (zero-dep ESM CLI library) in bin/ — amend rule 23 + +## Progress + +``` +Phase 0 ░░░░░░░░░░░░░░░░░░░░░░░░ 0/0 ( 0%) +───────────────────────────────────────────────── +TOTAL 0/0 ( 0%) +``` + +--- + +## Context + +`bin/forgeplan-web.mjs` сейчас парсит CLI вручную: `process.argv.slice(2)`, +`positional = argv.filter((a) => !a.startsWith("-"))`, `flags = new Set(...)`, +ручной `switch (cmd)` с case'ами `init / update / upgrade / start / serve / +run / help / -h / --help`. Файл уже 367 строк, и с каждой новой командой +читаемость падает квадратично: + +- нет авто-help (текст хардкоднут в `help()` и не sync'ится с реальным + списком флагов); +- нет type-coercion (флаг `--port 5174` приходит строкой, нужно `Number()` + вручную); +- нет subcommand-scoped flags (`--force` валиден и для `init`, и для + `update`, но смысл разный — текущий код не различает); +- нет интерактивных prompt'ов (нужны для GitHub issue #109 / #111 — + выбор `--scope` user/project + список запущенных instance'ов). + +Issue #109 (multi-instance management) поднимает 6 sub-issue'ев, среди +которых #111 (auto-detect existing scaffold + scope prompt), #115 +(HealthBar Combobox со списком instance'ов), #112 (`update --scope`). +Каждая добавляет минимум один subcommand или интерактивный prompt. +Продолжать наращивать руками — путь к bug'ам в argv-парсинге +(уже наблюдалось: `flags.has("--no-experimental")` проверяется +side-effect-style внутри тела `update`, а не декларативно). + +Rule 23 (`.claude/rules/23-bin-zero-deps.md`) сейчас прямо запрещает +любой third-party import в `bin/`: + +> **Forbidden in `bin/`**: +> - Any `import` from a third-party package. +> - Any `require()` from `node_modules/` at the package root. + +Это правило защищает cold-start `npx @forgeplan/web init` (нет +`npm install` на стороне пользователя — пакет ships pre-built `dist/`). +Но текущая дисциплина бинарна: либо ноль deps, либо «всё можно». +Нам нужна третья позиция — точечное исключение для одной библиотеки, +которая не нарушает фундаментальное обещание (zero install, fast +cold-start). + +## Decision + +**Selected**: разрешить **citty** (https://github.com/unjs/citty) как +**единственное** именованное исключение к rule 23. Другие CLI-библиотеки +(commander, yargs, oclif, cac) остаются запрещёнными. Версия пинуется +caret-range'ом на minor (`citty: ^X.Y.Z`); bump major/minor требует +re-evaluation этого ADR. + +**Why Selected**: citty уникален в комбинации признаков, на которые +опирается rule 23: + +- **Zero transitive runtime deps** — единственная dep, `consola`, тоже + unjs zero-dep пакет. Полный install footprint для `bin/` ≈ 60 KB + unpacked. Сравнение: commander — 1 dep, ~150 KB; yargs — 8 deps, + ~600 KB; oclif — десятки deps, мегабайты. +- **ESM-native** — `bin/forgeplan-web.mjs` использует `import` / + `node:` modules; CJS-shim'ы commander/yargs создают + module-resolution квоты на cold-start. +- **~5KB minified, ~50ms cold-start delta** (измерим в EVID-XXX) — + acceptable относительно текущего baseline'а `npx` (≈300ms до + первого `console.log`). +- **Built-in prompt support** через re-export `consola.prompt` — + закрывает требование #111 (interactive `--scope` selection) без + второй зависимости (`prompts`, `inquirer`). +- **Subcommand model** маппится 1:1 на текущий `switch (cmd)` — + миграция механическая, не архитектурная. +- **Maintainership** — unjs (Nuxt/Nitro экосистема, Pooya Parsa et al.), + активно поддерживается, semver-disciplined. + +Включается ровно одна библиотека: `consola` приходит транзитивно через +`citty`, отдельной строкой в `package.json#dependencies` НЕ +объявляется (это не «вторая dep», это implementation detail citty). + +### Rule 23 patch (для референса implementer'а в PRD-024) + +Текущий relevant фрагмент `.claude/rules/23-bin-zero-deps.md`: + +```markdown +## Allowed in `bin/` + +- `node:*` modules (`node:fs`, `node:child_process`, `node:path`, + `node:url`, `node:os`, `node:crypto`, `node:util`). +- Relative imports of sibling `.mjs` files **inside `bin/`** ... + +## Forbidden in `bin/` + +- Any `import` from a third-party package. +- Any `require()` from `node_modules/` at the package root. +``` + +После реализации PRD-024 секция Allowed расширяется ровно до: + +```markdown +## Allowed in `bin/` (amended by ADR-003) +- `node:*` modules (unchanged). +- Relative imports of sibling `.mjs` files inside `bin/` (unchanged). +- **citty** + **consola** (приходит транзитивно через citty re-export) — + единственное именованное исключение для CLI-эргономики (subcommands, + prompts, auto-help, type-coercion). См. ADR-003. +- Любой другой third-party import остаётся forbidden. +``` + +И Forbidden дополняется: + +```markdown +- Any third-party import OTHER than `citty` (and its transitive `consola`). +- Adding any other entry to root `package.json#dependencies` to support + the bin script. +``` + +Verification snippet rule 23 (тот, что в `## Verification`) обновляется: +allow-list bare specifier'ов добавляет `citty` + `consola`, остальные +по-прежнему FAIL'ят. + +Эта правка — задача PRD-024 (Build phase), не этого ADR. ADR фиксирует +**решение**, не **диff**. + +## Alternatives Considered + +| Option | Verdict | Why | +|--------|---------|-----| +| A — Status quo: hand-rolled argv parsing | Rejected | Уже на пределе читаемости (367 строк, нет subcommand-scoped flags, нет prompts). #111/#115 умножат сложность. | +| B — commander | Rejected | 1 transitive dep, ~150 KB unpacked, CJS-first (ESM wrapper неполный); cold-start delta ~80ms; нет prompt'ов из коробки (придётся `prompts`/`inquirer` — вторая dep). | +| C — yargs | Rejected | 8 transitive deps, ~600 KB unpacked, CJS-first, тяжёлый. Сильнее всего бьёт `npx` cold-start. | +| D — oclif | Rejected | Designed for plugins/multi-binary CLIs; десятки deps; мегабайты. Overkill для 3-command bin. | +| E — cac | Rejected | Близко к citty по размеру, но менее активно поддерживается, нет встроенного prompt'а — пришлось бы добавить вторую dep. | +| F — citty | **Chosen** | 0 transitive non-unjs deps, ESM-native, prompt через `consola`, ~5KB, subcommand-friendly. См. Decision. | +| G — Самописный мини-парсер в `bin/parser.mjs` | Rejected | Отодвигает проблему: всё ещё нужно поддерживать coercion, prompts, help-генерацию. Стоимость поддержки ≥ библиотеки. | + +## Consequences + +### Positive + +- `bin/forgeplan-web.mjs` декомпозируется на `bin/index.mjs` + + `bin/commands/{init,update,start}.mjs` (уже намечено в PRD-024) — + каждая команда self-contained, флаги декларативны. +- Auto-help sync'ится с реальным списком команд/флагов — нельзя + «забыть обновить help()». +- Type-coercion (`number`, `boolean`, `string`) валидирует input до + попадания в логику команды — fewer runtime surprises. +- `consola.prompt` open's путь к interactive flows (#111 scope picker, + #115 instance selector) без второй dep. +- Rule 23 теперь имеет explicit shape — «ровно одна библиотека по + имени», что проще audit'ить, чем «никаких deps» с фактическими + workaround'ами. + +### Negative (trade-offs) + +- Cold-start `npx @forgeplan/web init` подрастает на ~50ms (≈15-17% + от baseline ~300ms). На 1Gbit/s connection незаметно; на slow + CI runners — заметно но допустимо. +- Tarball вырастет на ~60 KB unpacked / ~25 KB packed. Текущий + пакет ships `dist/` ≈ 11 MB, дополнительные 60 KB + пренебрежимы (<0.6%). +- Rule 23 становится сложнее: вместо «ноль deps» — «ноль deps плюс + citty». Всякий новый запрос «можно ещё одну?» теперь имеет + прецедент. Mitigation: invariant'ы ниже + AI Guidance. +- citty — относительно молодая библиотека (v0.x). Major-bump может + потребовать миграции. Mitigation: pin caret на minor; refresh + trigger на major bump. + +### Risks + +- **R1 — citty вводит свою transitive dep, которая ломает zero-install + обещание.** Mitigation: lockfile-проверка в PRD-024 evidence pack. + `npm ls --omit=dev` после `npm i citty` должен показать ровно две + записи: `citty`, `consola`. CI gate'ит регрессию. +- **R2 — cold-start regression больше прогноза (>100ms).** Mitigation: + EVID-XXX измеряет `time npx @forgeplan/web --version` до/после; + threshold 100ms — fail гейт. +- **R3 — citty deprecation / unmaintained drift.** Mitigation: refresh + trigger «no commits to citty repo for 12 months» переоценивает ADR. +- **R4 — security advisory на citty или consola.** Mitigation: + `npm audit` в CI; refresh trigger «medium+ CVE» — мгновенно. +- **R5 — Прецедент-вектор: «раз citty можно, то и chalk можно».** + Mitigation: AI Guidance секция явно запрещает; PR review checklist + спросит ADR-XXX для каждой новой dep. + +## Invariants + +- **I1 — Только citty + node:* + sibling `.mjs` в `bin/`.** Никакая + другая npm-зависимость не импортируется из файлов `bin/*.mjs`. +- **I2 — citty version pinned to `^X.Y.Z` (caret minor)**, где X.Y.Z — + версия на момент adoption (фиксируется в PRD-024). Major/minor bump + требует re-evaluation ADR через `forgeplan reason ADR-003`. +- **I3 — Root `package.json#dependencies` содержит ровно ОДНУ запись + для bin'а: `"citty": "^X.Y.Z"`.** `consola` не объявляется (приходит + транзитивно). Других runtime deps на root уровне НЕТ + (`devDependencies` для tooling — отдельная история, rule 23 их не + ограничивает). +- **I4 — `bin/` не использует ничего из citty помимо: `defineCommand`, + `runMain`, `consola.prompt`, базовые args (`type: 'string' | + 'number' | 'boolean'`).** Расширение surface'а (e.g. `consola.box`, + кастомные renderer'ы) — отдельный ADR. +- **I5 — Verification snippet rule 23 обновлён**, его allow-list bare + specifier'ов содержит ровно `citty` и `consola`. + +## Evidence Requirements + +- **E1 — Smoke test exit 0**: `node scripts/smoke.mjs` (или его новый + эквивалент) после миграции на citty проходит на ubuntu/macos/windows + matrix. CL3 test против `bin/` + `dist/`. +- **E2 — Bundle size delta < 10KB packed**: `npm pack --dry-run` до и + после adopting citty. Diff packed-size < 10 KB. CL3 measurement. +- **E3 — Cold-start delta < 100ms**: `hyperfine 'node bin/forgeplan-web.mjs + --version'` (10 warmups, 50 runs) до/после. Mean delta < 100ms. + CL3 benchmark. +- **E4 — Rule 23 verification exits 0** с обновлённым allow-list: + модифицированный grep-snippet (citty + consola в whitelist) выдаёт + `OK` для каждого `bin/*.mjs`. CL3 test. +- **E5 — `npm ls --omit=dev`** в репо показывает ровно: `citty@^X.Y.Z` + с одним child'ом `consola@*`, без других runtime entries. CL3 audit. +- **E6 — `npm audit --omit=dev`** не репортит medium+ severity на + citty или consola на момент adoption. CL2 audit (зависит от внешнего + feed'а). + +## Valid Until + +**Дата**: 2027-05-08 (1 год от создания). + +**Обоснование TTL**: решение архитектурно-консервативное (точечное +исключение, не сдвиг парадигмы); годовой horizon достаточен, чтобы +накопить evidence о cold-start стабильности и проверить, не появилось +ли в Node.js core stable аналога (`util.parseArgs` evolution, +`node:cli` proposal'ы). Раньше пере-оценивать без триггера — шум. + +**Refresh Triggers** (когда пере-оценить досрочно): + +- citty релизит major (v1 → v2) с breaking changes. +- Появляется CVE medium+ на citty или consola. +- Cold-start delta в production telemetry превышает 100ms на p50. +- Node.js core стабилизирует argv-parsing surface, покрывающий 80%+ + use-case'ов citty (`util.parseArgs` уже есть, но без subcommand + модели). +- ≥1 новая запросов на «ещё одну npm-deps в `bin/`» — сигнал что + правило слишком широко или слишком узко, нужно пере-обсудить. + +## Pre-conditions (чеклист ДО реализации) + +- [x] PRD-024 created и validated (implementation contract). +- [x] RFC-020 описывает архитектуру декомпозиции `bin/` на subcommands. +- [ ] Текущий version-pin citty зафиксирован в PRD-024 (минимальный + `^0.X.Y` на момент adoption). +- [ ] Smoke test infrastructure (`scripts/smoke.mjs`) умеет валидировать + exit code на 3 платформах. + +## Post-conditions (Definition of Done) + +- [ ] `.claude/rules/23-bin-zero-deps.md` обновлён по diff в Decision. +- [ ] `package.json#dependencies` содержит ровно `{"citty": "^X.Y.Z"}`. +- [ ] `bin/forgeplan-web.mjs` использует `defineCommand` / `runMain` + из citty для всех subcommands (`init`, `update`, `start`, `help`). +- [ ] Все evidence'ы E1–E5 собраны и связаны через + `forgeplan link EVID-XXX ADR-003 --relation supports`. +- [ ] R_eff(ADR-003) > 0; статус active. + +## Admissibility + +- **NOT**: добавлять ни одной third-party dep в `bin/` помимо citty. + Каждая дополнительная требует **нового** ADR (не amendment этого). +- **NOT**: использовать citty в `template/` или `dist/` — те surface'ы + имеют свои правила (`template/package.json#dependencies`, + `scripts/build.mjs`). citty живёт только в `bin/`. +- **NOT**: импортировать `consola` напрямую (`import 'consola'`). + Использовать только через citty re-export — иначе всплывёт как + отдельная decllared dep и нарушит I3. +- **NOT**: вытаскивать citty в `peerDependencies` или `optionalDependencies` + — runtime dep на bin'е, должен быть жёстким `dependencies`. + +## Rollback Plan + +**Triggers** (когда откатывать): + +- citty полностью deprecated или unmaintained >12 месяцев. +- Cold-start regression >150ms сохраняется через 2+ patch-версии citty. +- Появляется critical CVE без fix-window <14 дней. + +**Steps** (шаги отката): + +1. Вернуть `bin/forgeplan-web.mjs` к hand-rolled argv-парсингу + (git revert на коммит миграции; код всё ещё в истории). +2. Удалить `citty` из `package.json#dependencies`. +3. Удалить amendment-секцию из `.claude/rules/23-bin-zero-deps.md`, + вернуть rule 23 к строгой «zero deps» формулировке. +4. Перевести ADR-003 в `superseded` через `forgeplan supersede`, + ссылка на новый ADR с альтернативой (cac / самописный парсер / + нативный `util.parseArgs`). +5. Cut patch-релиз с откатом. + +**Blast Radius**: средний. Откат меняет публичный CLI surface +минимально (subcommand'ы остаются), но переписывает internal'ы +`bin/`. Пользователи не видят разницы; agents-coder'ы должны +будут переучить mental model. + +## Weakest Link + +R_eff(ADR-003) ограничивается **E3 (cold-start delta)** — это +единственный evidence, где measurement привязан к окружению (CPU, +disk, npm-cache state). На быстрой машине delta ~30ms, на slow +CI runner может быть ~80ms. Если choose CL2 (test против synthetic +benchmark, не production trace), penalty 0.1 → R_eff ≤ 0.9. + +Стратегия: собрать E3 на трёх средах (local M-series Mac, ubuntu CI, +windows CI), брать MAX как worst-case; если worst-case <100ms — CL3. +Иначе — CL2 + flag в Risks. + +## Affected Files + +| File | Baseline Hash | +|------|---------------| +| `bin/forgeplan-web.mjs` | TBD-pre-migration | +| `bin/banner.mjs` | unchanged | +| `package.json` | adds `dependencies.citty` | +| `.claude/rules/23-bin-zero-deps.md` | adds amendment block | +| `.claude/rules/00-index.md` | unchanged (rule still listed as 23) | +| `scripts/smoke.mjs` | may need adjusting if it inspects argv shape | +| `README.md` | help-output snippet refreshes (if cited) | + +(`Baseline Hash` заполняется implementer'ом в PRD-024 на момент +старта Build phase.) + +## AI Guidance + +> Правила для AI-агентов при работе с этим решением. + +- **Когда расширяешь `bin/` новыми командами/флагами — используй citty + `defineCommand`, не пиши руками argv-парсинг.** Subcommand'ы лежат + в `bin/commands/.mjs`, корень `bin/index.mjs` агрегирует + через `subCommands`. +- **НЕ добавляй другую npm-deps в `bin/` без нового ADR.** Если + кажется что нужно (chalk, ora, prompts, kleur) — либо найти эквивалент + в citty/consola surface'е, либо открыть ADR-XXX с обоснованием + через ту же таблицу Alternatives. +- **НЕ импортируй `consola` отдельной строкой.** Только через + citty re-export (`import { consola } from 'citty'` если такой + re-export существует; иначе — через args type или command context). +- **При генерации команд** — флаги декларативны (`args: { force: + { type: 'boolean', description: '...' } }`), а не парсятся вручную + внутри run-функции. Это invariant I4. +- **Если задача конфликтует с этим ADR** (например, пришёл запрос + «давайте добавим commander для лучших help'ов») — raise it explicitly, + не делай молча. ADR — binding decision. +- **При апгрейде citty** — checklist: smoke test E1, cold-start E3, + audit E6. Любой regression — откат + патч-issue. + +## Implementation Plan + +### Phase 0: Foundation +- [ ] **0.1** Зафиксировать citty version в PRD-024 (`citty@latest` на момент старта). +- [ ] **0.2** Утвердить ADR-003 (этот документ) — `forgeplan validate ADR-003` 0 errors. + +### Phase 1: Rule patch +- [ ] **1.1** Patch `.claude/rules/23-bin-zero-deps.md` — Allowed/Forbidden + Verification snippet. +- [ ] **1.2** Smoke что rule-23 verification exits 0 на текущем `bin/` (до citty migration — должна fail'ить, чтобы доказать что snippet boejcrhq). + +### Phase 2: Migration +- [ ] **2.1** `npm i citty` (PRD-024 Wave 2). +- [ ] **2.2** Декомпозиция `bin/forgeplan-web.mjs` на `bin/index.mjs` + `bin/commands/*.mjs` (RFC-020 architecture). +- [ ] **2.3** `node scripts/smoke.mjs` — exit 0. +- [ ] **2.4** `hyperfine` cold-start measurement — собрать E3. +- [ ] **2.5** `npm pack --dry-run` size diff — собрать E2. +- [ ] **2.6** EvidencePack'и созданы и слинкованы; `forgeplan score ADR-003` показывает R_eff > 0. + +### Phase 3: Activate +- [ ] **3.1** `forgeplan activate ADR-003`. +- [ ] **3.2** PR с `Refs: ADR-003`; merge через `release/v*`. + +## Implementation Log + + + +## Related Artifacts + +| Artifact | Type | Relation | +|----------|------|----------| +| PRD-024 | PRD | implements (the build-phase contract) | +| RFC-020 | RFC | based_on (architecture of decomposed bin/) | +| PROB-003 | ProblemCard | based_on (the maintainability problem) | +| ADR-001 | ADR | informs (rule-amendment pattern reference) | +| ADR-002 | ADR | informs (sub-agent dispatch — methodology consistency) | +| Issue #109 | GitHub | informs (multi-instance management driver) | +| Issue #111 | GitHub | informs (interactive scope prompt — citty/consola need) | + diff --git a/.forgeplan/adrs/ADR-004-instance-registry-path-and-json-format.md b/.forgeplan/adrs/ADR-004-instance-registry-path-and-json-format.md new file mode 100644 index 0000000..b641273 --- /dev/null +++ b/.forgeplan/adrs/ADR-004-instance-registry-path-and-json-format.md @@ -0,0 +1,414 @@ +--- +created: 2026-05-08 +depth: standard +id: ADR-004 +kind: adr +links: +- target: PRD-027 + relation: informs +problem_ref: PROB-004 +status: draft +title: Instance registry path and JSON format +updated: 2026-05-08 +--- + +# ADR-004: Instance registry path and JSON format + +## Progress + +``` +Phase 0 ░░░░░░░░░░░░░░░░░░░░░░░░ 0/0 ( 0%) +───────────────────────────────────────────────── +TOTAL 0/0 ( 0%) +``` + +--- + +## Context + +Issue #109 (multi-instance management) — пользователь часто запускает +несколько `npx @forgeplan/web start` одновременно: один для основного +проекта, второй для playground'а форgeplan'а, третий для review чужого +PR. Сейчас они независимы: каждый пишет в свой `.forgeplan-web/`, +слушает свой PORT, не знает о существовании других. + +Sub-issue #115 (HealthBar Combobox) требует: на любом запущенном +instance'е в HealthBar'е показывается dropdown «другие активные +instance'ы» (label = workspace folder name + port + uptime), клик +переключает вкладку на тот instance. Sub-issue #113 (instance discovery +service) ставит более общий вопрос — как один процесс узнаёт о других. + +Ни IPC-сокеты, ни broadcast (mDNS) сюда не подходят — слишком тяжёлая +машинерия для dev-tool'а с typical fan-out 1-3 instance'а на user. +Простейшая модель — общий registry-файл, который все instance'ы: + +- *append* при `start` (свою запись), +- *prune* при `start` (чужие dead-записи), +- *read* через `/api/instances` endpoint когда UI просит список. + +Решения, которые этот ADR закрывает: + +1. **Где** на диске лежит registry. +2. **В каком формате** (JSON / SQLite / per-file). +3. **Как** writer'ы избегают друг друга (lock / atomic / nothing). +4. **Как** определяется liveness (PID / heartbeat / TTL). +5. **Что** делать при гонке. + +Эти решения должны быть приняты ДО SPEC-003 (который описывает schema) +и ДО PRD-027 (который описывает реализацию `bin/commands/start.mjs` + +`template/src/shared/server/registry.ts`). + +## Decision + +**Selected**: 5 sub-decisions: + +1. **Path: `~/.forgeplan-web/instances.json`.** Тот же родительский + каталог, что и user-scope `dist/` из issue #111 (когда он будет + реализован). Единая папка для всего, что @forgeplan/web хранит вне + проекта. +2. **Format: single JSON file.** Schema формализуется в SPEC-003; + корневой объект `{ schemaVersion: 1, instances: Instance[] }`, + где `Instance = { pid, port, host, workspaceRoot, startedAt, + heartbeatAt, version, scope }`. +3. **Write semantics: atomic via `writeFile(tmp) + rename(tmp, final)`.** + POSIX rename внутри одной FS — атомарен; на Windows + `fs.renameSync` атомарен на NTFS если target существует + (`MoveFileEx` с `MOVEFILE_REPLACE_EXISTING`). +4. **Liveness: dual signal — PID alive + heartbeat fresh.** Проверка + `process.kill(pid, 0)` (бросает `ESRCH` если процесс мёртв, + `EPERM` если живой но чужой — оба значат «не наш зомби»). Дополнительно + `Date.now() - heartbeatAt < 60_000` — fresh. Heartbeat обновляется + instance'ом каждые 30 секунд. +5. **No locking.** Atomic rename + last-write-wins. На write + instance читает текущее состояние, фильтрует stale, добавляет себя, + пишет tmp, переименовывает. Окно race'а ~5ms (read+filter+write); + при collision'е победитель overwrite'ит loser'а, но следующий + heartbeat-tick (≤30s) восстановит. + +**Why Selected**: каждое из 5 решений — самая простая интерпретация +требования issue #109/#113/#115: + +- предсказуемый путь (#1) даёт одно место для всего state'а; +- JSON (#2) human-readable, debuggable через `cat`, не нуждается в + native module (SQLite требует `better-sqlite3` или `node:sqlite`, + оба ломают zero-dep aspiration в `dist/` или `bin/`); +- atomic rename (#3) — single OS-level primitive вместо самописного + locking; +- двойной liveness probe (#4) ловит и crash (PID gone), и hang + (heartbeat stale) — без false positive'ов на медленных машинах + где event-loop замирает на 5-10s; +- no locking (#5) — допустимый компромисс при ≤10 concurrent instances + per user. Race window узок, потеря записи восстанавливается + следующим heartbeat'ом. + +## Alternatives Considered + +| Option | Verdict | Why | +|--------|---------|-----| +| A — SQLite (`better-sqlite3` или `node:sqlite`) | Rejected | Heavy: native module, build step, ~5MB unpacked. Хочется атомарных multi-instance write'ов «бесплатно», но atomic-rename даёт 95% того же результата без зависимости. Ломает zero-dep aspiration в `bin/` (rule 23) если writer живёт там. | +| B — Locked-file JSON (`proper-lockfile` или ручной `mkdirSync` lock) | Rejected | Adds dep или самописный lock-cleanup. Race window закрывается, но при ≤10 instances overhead ≥ benefit'а. Stale lock'и — известный foot-gun. | +| C — Per-instance file `~/.forgeplan-web/instances/.json` | Rejected | Удобно для write (нет race'ов), но плохо для read: реадеру нужно `readdir` + N×`readFile` вместо одного `readFile`. На 10 instance'ах — 11 syscalls вместо 1. Также сложнее snapshot'ить и debug'ить (`cat`). | +| D — XDG-compliant path (`$XDG_RUNTIME_DIR/forgeplan-web/instances.json` на Linux, `%APPDATA%` на Windows, `~/Library/Application Support/` на macOS) | Rejected | OS-correctness vs predictability — для dev-tool'а predictability важнее. XDG требует cross-platform shim'а; разный путь на разных OS усложняет support («where is my registry?»). Documented exception оправдан. | +| E — Tmpdir (`os.tmpdir()/forgeplan-web/instances.json`) | Rejected | Убираемый OS'ом при reboot — registry стирается между сессиями. Не критично (всё равно после reboot нет live instance'ов), но `~/.forgeplan-web/` уже есть как convention из #111 — лишний путь не нужен. | +| F — `~/.forgeplan-web/instances.json` + atomic rename + no lock | **Chosen** | Predictable path, zero deps, atomic enough for ≤10 instances, easy to debug/snapshot. | + +## Consequences + +### Positive + +- Один путь, читаемый человеком: `cat ~/.forgeplan-web/instances.json` + для debug. +- Zero new runtime deps: чистый `node:fs` + `node:path` + `node:os` + + `process.kill` (probing). +- Атомарность write'а — не нужен ни lock-файл, ни coordination + protocol. +- Snapshot/backup тривиален: один файл. +- Совместимо с rule 23 (никакого third-party в `bin/`) и rule 20 + (writes в `~/.forgeplan-web/` — не host project, не нарушает + isolation). + +### Negative (trade-offs) + +- **No strong locking** — две одновременные `start`-команды могут + потерять запись друг друга. Mitigation: heartbeat reconciliation в + ≤30s (next tick rewrite'ит canonical state). +- **No cross-host federation** — registry per-user-per-machine. Если + пользователь работает на двух машинах, instances не видят друг + друга. Mitigation: out of scope (#109 явно про single-machine). +- **Path collision risk** — `~/.forgeplan-web/` в будущем может + конфликтовать с другим использованием (например, Forgeplan CLI + начнёт там что-то писать). Mitigation: namespace под + `~/.forgeplan-web/instances.json` как peer для `dist/` (а не как + catch-all файл). +- **Heartbeat overhead** — каждый instance будит timer каждые 30s + на read+filter+write. Cost: ~5ms per tick × N instances. Negligible. +- **Read concurrency** — `/api/instances` endpoint читает файл на + каждый request. На active dashboard polling-rate (10s) и 3 instances + это ~9 read/min. Negligible. + +### Risks + +- **R1 — Race на write при одновременном `start` от двух процессов: + один из них теряет запись.** Mitigation: heartbeat ≤30s + восстанавливает; в худшем случае dropdown показывает 1 из 2 + instances в течение 30s. Acceptable UX. +- **R2 — `process.kill(pid, 0)` ложно возвращает «alive» для PID, + переиспользованного OS** (process recycled другим приложением). + Mitigation: dual signal — heartbeat freshness отсекает recycled PIDs + (новый процесс не пишет в наш registry). +- **R3 — Corrupted JSON** (crash во время write до atomic rename). + Mitigation: rename атомарен — partial-write остаётся в `tmp`, + никогда не заменяет main файл. Stale `tmp` cleanup при следующем + successful write. +- **R4 — Permission denied на `~/.forgeplan-web/`** (read-only home, + exotic setup). Mitigation: graceful degradation — instance стартует + без registry, log'ает warning, просто не показывается в dropdown'е. + Не блокирует основной use-case. +- **R5 — schemaVersion bump ломает старые instance'ы.** Mitigation: + reader'ы treat unknown `schemaVersion` как «empty registry»; writer'ы + на новой версии overwrite'ят при следующем heartbeat'е. +- **R6 — Symlink attack на `~/.forgeplan-web/instances.json`** (атакующий + создаёт symlink на чужой файл, наш write перезатирает). Mitigation: + `lstatSync` перед write; если `isSymbolicLink()` — abort. + Аналогично уже сделано в `bin/forgeplan-web.mjs` для `update` через + `targetStat.isSymbolicLink()` (см. строки 222-230). + +## Invariants + +- **I1 — Atomic writes only.** Любой write в `instances.json` происходит + через `writeFile(tmp) + rename(tmp, final)`. Прямой `writeFile(final)` + запрещён. +- **I2 — Stale entries dropped on every `start` and on every heartbeat.** + Каждая запись (`start`-time или heartbeat-time) выполняет + `prune(instances)` — отбрасывает PID-dead и heartbeat-stale. +- **I3 — No instance writes another instance's entry.** Запись с + `pid: 12345` принадлежит процессу 12345; другие instance'ы могут + её только удалить (при stale-pruning), не модифицировать. +- **I4 — Heartbeat interval ≤ 30s, staleness threshold = 60s.** + Несимметрия даёт буфер на event-loop pause / GC. +- **I5 — No fields beyond SPEC-003 schema.** Добавление поля к + `Instance` — breaking change, требует bump'а `schemaVersion` и + обновления SPEC-003 + ADR-004 update. +- **I6 — Path is `~/.forgeplan-web/instances.json` always.** + Никакой env-override (`FORGEPLAN_WEB_REGISTRY=...`) на phase 1 — + предсказуемость > flexibility. Если флаг понадобится — отдельный ADR. + +## Evidence Requirements + +- **E1 — 3-instance smoke test**: запустить 3 параллельных + `node .forgeplan-web/index.js` (на разных портах), `cat + ~/.forgeplan-web/instances.json` показывает все 3 записи. CL3 test. +- **E2 — Stale-pruning test**: kill -9 одного из 3 instance'ов; + следующий `start` (или следующий heartbeat другого instance'а) + drop'ает stale entry. CL3 test. +- **E3 — Atomic-rename test**: race-script запускает 10 одновременных + write'ов в registry; после завершения JSON parseable, schema + валидна, никаких partial-write артефактов. CL3 test. +- **E4 — PID-recycle robustness**: симулировать переиспользованный + PID (записать запись с PID = 1; PID 1 живой как init, но heartbeat + будет stale через 60s) — реадер должен отбросить. CL2 test + (синтетический сценарий). +- **E5 — Symlink defence**: создать `~/.forgeplan-web/instances.json` + как symlink на чужой файл; instance отказывается писать, log'ает + warning. CL3 test. +- **E6 — Cross-platform**: matrix CI (ubuntu/macos/windows) проходит + E1–E3. CL3 test. +- **E7 — Permission-denied graceful**: chmod 000 на + `~/.forgeplan-web/`; instance стартует без registry, exit code 0, + warning в logs, `/api/instances` отвечает `{ ok: false }` без crash. + CL3 test. + +## Valid Until + +**Дата**: 2027-05-08 (1 год от создания). + +**Обоснование TTL**: формат и path — публичный contract для tooling'а +других приложений (потенциально); годовой horizon разумен для +накопления usage data. Большие изменения (schema bump, federation) +скорее всего потребуют отдельного ADR'а, не refresh'а этого. + +**Refresh Triggers** (когда пере-оценить досрочно): + +- ≥2 случая corrupted-registry за месяц в production telemetry — + сигнал что atomic rename недостаточно, нужен lock. +- ≥10 concurrent instances per user становится common case — + сигнал что no-lock model wears out. +- Появляется требование cross-host federation (#109 evolutionary + follow-up). +- Schema нуждается в breaking change (новый required field). +- Forgeplan CLI начинает писать в `~/.forgeplan-web/` — нужно явно + разнести namespace'ы. + +## Pre-conditions (чеклист ДО реализации) + +- [x] PRD-027 created и validated. +- [x] SPEC-003 описывает schema (Instance + RegistryFile). +- [x] RFC-023 описывает архитектуру (writer flow в `bin/start.mjs`, + reader flow в `template/src/shared/server/registry.ts`). +- [ ] User-scope `dist/` design (issue #111) согласован — registry path + должен быть peer'ом, не дочкой. + +## Post-conditions (Definition of Done) + +- [ ] `bin/commands/start.mjs` пишет registry entry на startup и + обновляет heartbeat каждые 30s. +- [ ] `bin/commands/start.mjs` prune'ит stale entries on startup. +- [ ] Process-exit hook (`SIGINT`/`SIGTERM`/normal exit) удаляет + собственную запись. +- [ ] `template/src/routes/api/instances/+server.ts` (новый GET-endpoint) + возвращает live instances. Покрывается amendment'ом rule 22 в + PRD-029 (этот endpoint — не forgeplan-proxy, аналогично + `update-check`). +- [ ] `template/src/shared/server/registry.ts` — pure read (без + mutation). Mutation живёт в `bin/`. +- [ ] Все evidence'ы E1–E7 собраны и слинкованы. +- [ ] R_eff(ADR-004) > 0; статус active. + +## Admissibility + +- **NOT**: writing registry from a Svelte server route. Registry + mutation лежит в `bin/` (start writes own entry, exit hook removes). + Svelte routes только читают. +- **NOT**: extending registry path с env-override на phase 1 (см. I6). +- **NOT**: использовать `JSON.parse` без try/catch — corrupted + registry должен degrade gracefully, не crash'ить. +- **NOT**: writing fields beyond SPEC-003 schema. Любое расширение — + через bump `schemaVersion`. +- **NOT**: `process.kill(pid, 0)` без catch — `ESRCH` ожидаемый + control-flow, не error. +- **NOT**: storing secrets / tokens / credentials в registry. Поля + ограничены публичной meta'ой (pid, port, host, workspaceRoot, + timestamps, version). +- **NOT**: следовать symlink'у на `~/.forgeplan-web/instances.json` + при write — abort + warning (R6). + +## Rollback Plan + +**Triggers** (когда откатывать): + +- Corrupted-registry incidents >2/month в issue tracker'е. +- Пользователь reports about ghost-instances в HealthBar dropdown'е, + не decay'ат за минуты. +- Появляется fundamentally better механизм (например, IPC через + абстрактный socket) и его cost/benefit лучше. + +**Steps** (шаги отката): + +1. Удалить `bin/commands/start.mjs` registry write/heartbeat hooks. +2. Удалить `template/src/routes/api/instances/+server.ts`. +3. Удалить `template/src/shared/server/registry.ts`. +4. Откатить amendment rule 22 (PRD-029) — endpoint allow-list + снова без `instances`. +5. Удалить `~/.forgeplan-web/instances.json` cleanup hook (если был). +6. Перевести ADR-004 в `superseded`, ссылка на новый ADR. + +**Blast Radius**: средний. Regress feature'а (HealthBar Combobox +теряет dropdown), но не ломает существующих single-instance users. +Файл `instances.json` на диске у пользователей становится мусором, +но не активным — следующий run просто его перезатирает или игнорит. + +## Weakest Link + +R_eff(ADR-004) ограничивается **E4 (PID-recycle robustness)** — +синтетический test, который невозможно полностью провести в CL3 +без access'а к реально recycled PID (timing-dependent). CL2 penalty +0.1 → R_eff ≤ 0.9. + +Дополнительно потенциально weak: **E7 (permission-denied)** на +Windows, где permission model отличается. Strategy: использовать +`fs.access` with `W_OK` flag на windows как proxy. + +Если smoke E1–E3 на трёх платформах все CL3, R_eff(ADR-004) +прогнозируется в диапазоне 0.7–0.9. + +## Affected Files + +| File | Baseline Hash | +|------|---------------| +| `bin/commands/start.mjs` | new file (depends on PRD-024 decomposition) | +| `bin/forgeplan-web.mjs` | start() function reduced to delegating to bin/commands/start.mjs | +| `template/src/shared/server/registry.ts` | new file | +| `template/src/routes/api/instances/+server.ts` | new file | +| `.claude/rules/22-readonly-proxy.md` | amendment (PRD-029, not this ADR) | +| `~/.forgeplan-web/instances.json` | runtime artifact (not in repo) | + +(`Baseline Hash` заполняется implementer'ом в PRD-027 на момент +старта Build phase.) + +## AI Guidance + +> Правила для AI-агентов при работе с этим решением. + +- **Когда добавляешь поле в Instance** — обнови SPEC-003 schema, + bump `schemaVersion`, обнови ADR-004 (Invariants + Affected Files). + Не добавляй «just one more field» без artifact-trail. +- **Любая mutation registry — в `bin/`, не в Svelte routes.** Это + invariant из rule 22 (read-only proxy) + Admissibility секция здесь. +- **При reading registry — всегда try/catch + schema-version check.** + Corrupted/old-version → empty list, не crash. +- **Не используй third-party deps (lockfile, watcher, etc.) для + registry на phase 1.** Если возникнет нужда — отдельный ADR + с обоснованием. +- **Heartbeat interval — константа 30s, threshold — 60s.** Менять + через константы в `bin/commands/start.mjs`, документировать в + SPEC-003. Изменение требует update Invariants I4. +- **Symlink protection — обязательная.** Каждый write обязан + `lstatSync` + reject если symlink (паттерн уже в `bin/forgeplan-web.mjs` + строки 222-230). +- **Process-exit hook должен быть idempotent** (могут стрельнуть + и `SIGINT`, и `exit`). + +## Implementation Plan + +### Phase 0: Foundation +- [ ] **0.1** SPEC-003 утвердить (schema froze). +- [ ] **0.2** ADR-004 (этот) активирован. + +### Phase 1: Writer +- [ ] **1.1** `bin/commands/start.mjs` пишет own entry on start. +- [ ] **1.2** Heartbeat tick каждые 30s. +- [ ] **1.3** Process-exit hook удаляет own entry. +- [ ] **1.4** Atomic write (`writeFile(tmp) + rename(tmp, final)`). +- [ ] **1.5** Symlink defence (lstatSync + reject). +- [ ] **1.6** Stale-pruning on every write. + +### Phase 2: Reader +- [ ] **2.1** `template/src/shared/server/registry.ts` — read + parse. +- [ ] **2.2** `template/src/routes/api/instances/+server.ts` GET endpoint. +- [ ] **2.3** Rule 22 amendment (PRD-029) для legalize этого endpoint'а. + +### Phase 3: Evidence +- [ ] **3.1** Smoke E1 (3-instance) — local + matrix CI. +- [ ] **3.2** Smoke E2 (stale-prune) — kill -9 + verify. +- [ ] **3.3** Smoke E3 (atomic-race) — 10 concurrent writers. +- [ ] **3.4** Smoke E5 (symlink-defence). +- [ ] **3.5** EvidencePack'и созданы и слинкованы. + +### Phase 4: Activate +- [ ] **4.1** `forgeplan score ADR-004` — R_eff > 0. +- [ ] **4.2** `forgeplan activate ADR-004`. + +## Implementation Log + + + +## Related Artifacts + +| Artifact | Type | Relation | +|----------|------|----------| +| PRD-027 | PRD | implements (registry write/read code) | +| RFC-023 | RFC | based_on (architecture) | +| SPEC-003 | Spec | based_on (schema) | +| PROB-004 | ProblemCard | based_on (multi-instance discoverability problem) | +| ADR-001 | ADR | informs (host isolation contract — symmetric to ~/.forgeplan-web/) | +| ADR-003 | ADR | informs (citty in bin/ — registry writer lives there) | +| Issue #109 | GitHub | informs (multi-instance management driver) | +| Issue #113 | GitHub | informs (instance discovery service) | +| Issue #115 | GitHub | informs (HealthBar Combobox UI consumer) | + diff --git a/.forgeplan/evidence/EVID-007-smoke-update-refreshes-forgeplan-web-preserves-createdat-removes-stale-files.md b/.forgeplan/evidence/EVID-007-smoke-update-refreshes-forgeplan-web-preserves-createdat-removes-stale-files.md index d0cff96..0baa541 100644 --- a/.forgeplan/evidence/EVID-007-smoke-update-refreshes-forgeplan-web-preserves-createdat-removes-stale-files.md +++ b/.forgeplan/evidence/EVID-007-smoke-update-refreshes-forgeplan-web-preserves-createdat-removes-stale-files.md @@ -5,7 +5,7 @@ kind: evidence links: - target: RFC-002 relation: informs -status: active +status: deprecated title: 'smoke: update refreshes .forgeplan-web, preserves createdAt, removes stale files' --- @@ -116,3 +116,4 @@ the test rig and production: the test rig **is** production. | RFC-002 | informs | + diff --git a/.forgeplan/evidence/EVID-008-rule-12-adr-002-protocol-files-exist-and-are-indexed.md b/.forgeplan/evidence/EVID-008-rule-12-adr-002-protocol-files-exist-and-are-indexed.md index a24070b..a189e82 100644 --- a/.forgeplan/evidence/EVID-008-rule-12-adr-002-protocol-files-exist-and-are-indexed.md +++ b/.forgeplan/evidence/EVID-008-rule-12-adr-002-protocol-files-exist-and-are-indexed.md @@ -7,7 +7,7 @@ last_modified_by: claude-code/2.1.126 links: - target: ADR-002 relation: informs -status: active +status: deprecated title: Rule 12 + ADR-002 protocol files exist and are indexed --- @@ -56,3 +56,4 @@ grep -n "12-forgeplan-agent-dispatch" .claude/rules/00-index.md - E2 (`active_claim_count == 0` после sprint'а) проверен будет в EVID для RFC-003 после release всех claim'ов Wave 3. + diff --git a/.forgeplan/prds/PRD-024-citty-integration-bin-subcommand-split.md b/.forgeplan/prds/PRD-024-citty-integration-bin-subcommand-split.md new file mode 100644 index 0000000..f5cd7a2 --- /dev/null +++ b/.forgeplan/prds/PRD-024-citty-integration-bin-subcommand-split.md @@ -0,0 +1,263 @@ +--- +depth: standard +id: PRD-024 +kind: prd +links: +- target: PRD-025 + relation: informs +status: draft +title: citty integration + bin/ subcommand split +--- + +--- +id: PRD-024 +title: "citty integration + bin/ subcommand split" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +priority: P1 +depth: standard +domain: general +projectType: cli_tool +stepsCompleted: [] +--- + +# PRD-024: citty integration + bin/ subcommand split + +## Executive Summary + +### Vision + +Replace the hand-rolled argv parser in `bin/forgeplan-web.mjs` with the +`citty` CLI framework and split the monolithic 367-line bin script into +small per-subcommand files under `bin/commands/`. The result is a +maintainable surface that supports interactive prompts, typed flags, and +auto-generated `--help` while keeping zero third-party transitive deps. + +### Problem + +The current parser (`bin/forgeplan-web.mjs:22-40`) is a flat `Set` of +argv tokens. Adding a new flag means hand-editing `flags.has(...)` calls +in three places (`init`, `update`, `start`). Adding a new subcommand +means appending to a `switch` block. There is no `--help `, +no flag validation (`--scope=foo` silently passes through), and no +hook-point for an interactive prompt — which GitHub issue #109 (sub-issues +#110–#115) needs in order to ship `--scope user|project` with a default +chosen by arrow-key prompt. + +**Impact**: `npx @forgeplan/web` users hit DX papercuts (no per-subcommand +help, silent typos), and contributors avoid touching `bin/` because every +new flag risks breaking three subcommands at once. + +### Target Users + +| Персона | Описание | Ключевая боль | +|---------|----------|---------------| +| Forgeplan-web user | Devs running `npx @forgeplan/web init` against a repo with `.forgeplan/` | No `--help init`; typos like `--no-gitignor` silently ignored; no interactive scope picker for #109 | +| Contributor on `bin/` | Devs adding new flags / subcommands | Three places to edit; manual flag parsing is brittle; cannot grow further without rewrite | + +### Differentiators + +- Citty is zero-dep ESM-only — preserves rule 23's invariant (no third- + party transitive resolution at `npx` time). +- Per-subcommand files keep diffs small and reviewable. +- Interactive prompt support unblocks #109 (#111 needs scope prompt) and + future flags without re-litigating the framework choice. + +--- + +## Success Criteria + +| ID | Criterion | Metric | Current | Target | Timeframe | How to Measure | +|----|-----------|--------|---------|--------|-----------|----------------| +| SC-1 | All existing flags keep identical observable behavior | Flag-parity tests pass | 0 of 6 covered | 6 of 6 (`-y`, `--force`, `--quiet`, `--no-gitignore`, `--experimental`, `--no-experimental`) | Same PR | `node scripts/smoke.mjs` covering each flag | +| SC-2 | Cold start delta vs current parser | ms from `npx` to first stdout | baseline current | < +100ms over baseline (median of 5 runs) | Same PR | `hyperfine 'node bin/forgeplan-web.mjs help'` | +| SC-3 | Bundle / tarball size delta | `npm pack` tarball bytes | baseline current | < +10KB (citty is ~6KB ESM) | Same PR | `npm pack --dry-run` size diff | +| SC-4 | Per-subcommand help works | `npx @forgeplan/web init --help` exit 0 with section | not implemented | exit 0, prints flags table | Same PR | Smoke assertion | +| SC-5 | Unknown subcommand fails fast | `npx @forgeplan/web bogus` exit code | currently 1 (custom message) | 1 (citty message includes available commands) | Same PR | Smoke assertion | + +--- + +## Product Scope + +### MVP (In-Scope) + +- Adopt `citty` (per ADR-003) as the CLI framework. Single new entry in + root `package.json#dependencies`. +- Split `bin/forgeplan-web.mjs` into: + - `bin/forgeplan-web.mjs` — 5–10 line entrypoint that imports `runMain` + from citty + the root command from `bin/cli.mjs`. + - `bin/cli.mjs` — root command (`defineCommand`) wiring subcommands. + - `bin/commands/init.mjs`, `bin/commands/update.mjs`, + `bin/commands/start.mjs`, `bin/commands/help.mjs` — one + `defineCommand` per file. + - `bin/lib/` — shared helpers (`config.mjs`, `gitignore.mjs`, + `forgeplan-binary.mjs`) extracted from current monolith. +- Backwards-compat: every existing flag works with identical semantics. + Aliases preserved (`upgrade` for `update`; `serve`/`run` for `start`). +- Rule 23 amendment landed in same PR (citty added to allowlist). + +### Out of Scope + +- Adding new flags (covered by PRD-025 `--scope`, PRD-026 start-resolution, + PRD-027 instance registry). +- Replacing `commander`/`cac` — alternatives live in RFC-020 trade-off + table; decision is final per ADR-003. +- Test framework introduction. Smoke remains `scripts/smoke.mjs` (Node + built-in `node:test` only). +- TypeScript migration of `bin/`. Scope stays ESM `.mjs`. + +### Growth Vision + +- Citty's prompt support unblocks PRD-025/026 interactive scope picker. +- Per-subcommand split makes future subcommands (e.g. `doctor`, `migrate`) + cheap to add. + +--- + +## User Journeys + +### Journey 1: User runs init for the first time + +**Цель**: Scaffold `.forgeplan-web/` into the current project. + +| Шаг | Действие пользователя | Ответ системы | Заметки | +|-----|----------------------|---------------|---------| +| 1 | `npx @forgeplan/web init` | Banner + scaffold copied | Existing behavior preserved | +| 2 | `npx @forgeplan/web init --help` | Lists `--force`, `--no-gitignore`, `--experimental`, `-y`, `--quiet` with descriptions | NEW — per-subcommand help | +| 3 | `npx @forgeplan/web init --bogus` | Exits 1, shows "Unknown flag --bogus" + suggestion | NEW — fail-fast on typos | + +**Результат**: Scaffold ready; user understands the flag surface. + +### Journey 2: Contributor adds a new flag + +**Цель**: Extend `init` with `--scope user|project` (PRD-025 follow-up). + +| Шаг | Действие пользователя | Ответ системы | Заметки | +|-----|----------------------|---------------|---------| +| 1 | Edits `bin/commands/init.mjs` only | One file diff | vs three-place edit today | +| 2 | Adds `args.scope = { type: 'string', valueHint: 'user\|project' }` | citty type-validates at parse time | Typos rejected at runtime, not silently dropped | +| 3 | Runs `node scripts/smoke.mjs` | All existing flag-parity tests pass | Backwards-compat invariant | + +**Результат**: New flag without touching update/start/help. + +--- + +## Functional Requirements + +| ID | Category | Priority | Requirement | Journey | +|----|----------|----------|-------------|---------| +| FR-001 | Core | Must | User can run `npx @forgeplan/web --help` and see top-level subcommand list with descriptions | Journey 1 | +| FR-002 | Core | Must | User can run `npx @forgeplan/web --help` and see flags for that subcommand | Journey 1 | +| FR-003 | Core | Must | User receives a non-zero exit and a clear message when an unknown subcommand is invoked | Journey 1 | +| FR-004 | Core | Must | User receives a non-zero exit and a clear message when an unknown flag is passed to a known subcommand | Journey 1 | +| FR-005 | Core | Must | All existing flags (`-y`, `--force`, `--quiet`, `--no-gitignore`, `--experimental`, `--no-experimental`) preserve identical observable behavior | Journey 1 | +| FR-006 | Core | Must | All existing subcommand aliases (`upgrade` → `update`; `serve`/`run` → `start`; `-h`/`--help` → `help`) preserve identical behavior | Journey 1 | +| FR-007 | DX | Must | Contributor can add a new flag by editing exactly one file under `bin/commands/` | Journey 2 | +| FR-008 | DX | Should | Contributor can add a new subcommand by adding one file under `bin/commands/` and one line in `bin/cli.mjs` | Journey 2 | +| FR-009 | DX | Should | Each file under `bin/commands/` is under 200 LOC | Journey 2 | +| FR-010 | Compatibility | Must | The published tarball includes `bin/` recursively (current `package.json#files: [bin, dist, ...]` already does so — must keep working) | Journey 1 | + +--- + +## Non-Functional Requirements + +| ID | Category | Requirement | Metric | Condition | Measurement | +|----|----------|-------------|--------|-----------|-------------| +| NFR-001 | Performance | Cold start delta vs current parser shall stay bounded | < +100ms (median of 5 runs) | `node bin/forgeplan-web.mjs help` from cold cache | `hyperfine` | +| NFR-002 | Bundle | Tarball size delta shall stay bounded | < +10KB | `npm pack --dry-run` | bytes diff | +| NFR-003 | Compatibility | Every flag in current help text shall continue to work | 6 of 6 flag-parity tests pass | `node scripts/smoke.mjs` | smoke exit 0 | +| NFR-004 | Zero-dep invariant (rule 23) | `bin/**` shall import only `node:*` and citty (allowlisted) | 0 other third-party imports | grep verification | rule-23 verification snippet | +| NFR-005 | Engines | Node engine support unchanged | `^20.19.0 \|\| >=22.12.0` | `package.json#engines` | review-time check | + +--- + +## Acceptance Criteria + +### AC-1: Backwards compatibility — every existing invocation works unchanged + +```gherkin +Given the current `bin/forgeplan-web.mjs` is replaced with the citty-based split +When the user runs `npx @forgeplan/web init -y --force --no-gitignore --experimental --quiet` +Then the scaffold is copied with identical observable side effects (.forgeplan-web/, .gitignore, forgeplan-web.json) +And exit code is 0 +And `node scripts/smoke.mjs` passes for all 6 flag combinations +``` + +### AC-2: Per-subcommand help is auto-generated + +```gherkin +Given the citty-based split is in place +When the user runs `npx @forgeplan/web update --help` +Then stdout includes a usage line, a description, and a flags table listing `--force`, `--experimental`, `--no-experimental`, `--quiet` +And exit code is 0 +``` + +### AC-3: Unknown flag fails fast + +```gherkin +Given the citty-based split is in place +When the user runs `npx @forgeplan/web init --no-gitignor` (typo) +Then exit code is non-zero +And stderr names the unknown flag +And the scaffold is NOT created +``` + +--- + +## Dependencies + +| Dependency | Type | Status | Owner | +|-----------|------|--------|-------| +| citty (npm package) | Runtime | Pending — adds to root `package.json#dependencies` | This PRD | +| ADR-003 (rule 23 amendment) | Internal | Drafted in parallel | adr-architect-109 | +| RFC-020 | Internal | This PRD's architecture | docs-eng-109 | + +--- + +## Risks & Mitigations + +| ID | Risk | Probability | Impact | Mitigation | Owner | +|----|------|-------------|--------|------------|-------| +| R-1 | Citty's auto-help text differs subtly from hand-rolled help, breaks user scripts that grep | Low | Low | Smoke test asserts exit codes only, not exact help wording; document the change in CHANGELOG | dev | +| R-2 | Cold-start regression > 100ms breaks NFR-001 | Low | Medium | Citty is tiny (~6KB ESM); benchmark in CI before merge | dev | +| R-3 | Subcommand alias mapping (`upgrade` / `serve` / `run`) lost in split | Medium | Medium | Citty supports `meta.alias` on subcommands; explicit smoke test per alias | dev | +| R-4 | Future esbuild bundling of bin/ (RFC-013 graduation) breaks if citty pulls dynamic imports | Low | Low | Citty is pure ESM static; verify with `node --import bin/forgeplan-web.mjs` | dev | + +--- + +## Affected Files + +- `bin/forgeplan-web.mjs` — shrinks to ~10 lines (entry point only) +- `bin/cli.mjs` — NEW, root command definition +- `bin/commands/init.mjs` — NEW, extracted from monolith +- `bin/commands/update.mjs` — NEW, extracted from monolith +- `bin/commands/start.mjs` — NEW, extracted from monolith +- `bin/commands/help.mjs` — NEW or removed (citty auto-generates help) +- `bin/lib/config.mjs` — NEW, shared `readConfig` / `readPkgVersion` +- `bin/lib/gitignore.mjs` — NEW, shared `ensureGitignore` +- `bin/lib/forgeplan-binary.mjs` — NEW, shared `ensureForgeplanBinary` / `ensureForgeplanWorkspace` +- `bin/banner.mjs` — unchanged sibling +- `package.json` — add `citty` to `dependencies` +- `.claude/rules/23-bin-zero-deps.md` — amendment landed via ADR-003 +- `scripts/smoke.mjs` — flag-parity assertions +- GitHub sub-issue: #110 (109a) + +## Related Artifacts + +| Artifact | Relation | Status | +|----------|----------|--------| +| RFC-020 | Architecture | Draft (parallel) | +| ADR-003 | Decision (rule 23 amendment) | Proposed (parallel) | +| PRD-025 | Depends on this PRD (consumes the new flag plumbing) | Draft | +| PRD-026 | Depends on this PRD | Draft | +| GitHub #110 | Source sub-issue | Open | +| GitHub #109 | Parent issue | Open | + +--- + +> **Next step**: Wait for ADR-003 finalization → land RFC-020 alongside this PRD → implement in Wave 5. + + + diff --git a/.forgeplan/prds/PRD-025-init-scope-user-project-with-interactive-prompt-fallback.md b/.forgeplan/prds/PRD-025-init-scope-user-project-with-interactive-prompt-fallback.md new file mode 100644 index 0000000..7c79bdf --- /dev/null +++ b/.forgeplan/prds/PRD-025-init-scope-user-project-with-interactive-prompt-fallback.md @@ -0,0 +1,275 @@ +--- +depth: standard +id: PRD-025 +kind: prd +links: +- target: PRD-026 + relation: informs +status: draft +title: init --scope user/project with interactive prompt fallback +--- + +--- +id: PRD-025 +title: "init --scope user|project with interactive prompt fallback" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +priority: P1 +depth: standard +domain: general +projectType: cli_tool +stepsCompleted: [] +--- + +# PRD-025: init --scope user|project with interactive prompt fallback + +## Executive Summary + +### Vision + +Extend `npx @forgeplan/web init` with a `--scope user|project` flag that +chooses where the scaffold is written: per-project (`./.forgeplan-web/`, +today's behavior) or per-user (`~/.forgeplan-web/`, the new default for +fresh installs). When the flag is omitted on an interactive TTY, the +user is prompted with arrow-key selection. + +### Problem + +Today every project gets its own `.forgeplan-web/` (~11 MB including a +generated `node_modules/` for the legacy artifact, ~1 MB for the bundled +artifact). Users with N forgeplan-managed repos pay N× disk + N× update +cycles. There is no way to share a single scaffold across repos. Sub-issue +#111 is the prerequisite for the multi-instance registry (#113), which +requires a stable user-scope path (`~/.forgeplan-web/instances.json`, +locked by ADR-004). + +**Impact**: Fresh adopters with multiple forgeplan repos report disk- +bloat surprise; the per-project scaffold also makes the upcoming +multi-instance switcher (#115) impossible to ship without a user-scope +home. + +### Target Users + +| Персона | Описание | Ключевая боль | +|---------|----------|---------------| +| Fresh adopter | First-time `npx @forgeplan/web init` user | Wants single install across all repos; doesn't know which scope is "right"; needs guidance | +| Existing user (project-scope) | Has `.forgeplan-web/` in N repos already | Must keep working unchanged — zero-config invariant | +| Power user | Wants explicit non-interactive control (CI / scripts) | Needs `--scope` flag to bypass prompt | + +### Differentiators + +- Backwards-compat invariant: `init -y` (no `--scope`) keeps writing + project-scope. Existing users see no change. +- Interactive prompt only fires when TTY is available AND `--scope` is + not passed AND `-y` is not passed. CI is unaffected. +- User-scope path is locked to `~/.forgeplan-web/` by ADR-004 (no XDG, + no per-OS paths in MVP — punted to growth). + +--- + +## Success Criteria + +| ID | Criterion | Metric | Current | Target | Timeframe | How to Measure | +|----|-----------|--------|---------|--------|-----------|----------------| +| SC-1 | `init -y` keeps writing project-scope (zero-config preservation) | Filesystem state diff | project-scope | project-scope (unchanged) | Same PR | Smoke test: existing flag-parity asserts | +| SC-2 | `init --scope user` writes to `~/.forgeplan-web/` | Existence check | not implemented | exists | Same PR | Smoke test: assert `~/.forgeplan-web/index.js` | +| SC-3 | Interactive prompt selects user-scope as default | Cursor position on first render | n/a | "user" highlighted | Same PR | Manual verification + e2e on Linux + macOS | +| SC-4 | `forgeplan-web.json` records the chosen scope | JSON field present | absent | `"scope": "user" \| "project"` | Same PR | Schema check | +| SC-5 | Project-scope appends `.gitignore`; user-scope does NOT | git status diff | project: appends; user: n/a (no host repo) | unchanged | Same PR | Smoke test: assert no `.gitignore` write under `--scope user` | +| SC-6 | Prompt latency on TTY | ms to first prompt render | n/a | < 50ms | Same PR | Manual / smoke timing | + +--- + +## Product Scope + +### MVP (In-Scope) + +- New flag: `--scope user|project` on `init` subcommand (delivered via + citty in PRD-024). +- Interactive prompt when scope omitted on TTY. Default selection = `user` + (encouraging the new shared-scope pattern for fresh installs). +- New helper module `bin/lib/scope.mjs` — pure resolver functions + (`resolveUserScopeRoot()`, `resolveProjectScopeRoot(cwd)`). +- `forgeplan-web.json` schema bump: add `"scope": "user" | "project"` + field. Read-side accepts absent for back-compat (assumed `project`). +- `init -y` (no `--scope`): defaults to `project` (preserves existing + user behavior). `init -y --scope user`: writes user-scope. +- `.gitignore` policy: project-scope appends `.forgeplan-web/` (existing + behavior). User-scope: skipped entirely (the home dir isn't typically + a git repo, and even if it is, we don't touch it). + +### Out of Scope + +- XDG_CONFIG_HOME compliance (per #109 acceptance — punted to a future + PRD; tracked as growth). +- Per-OS paths (`%APPDATA%`, `~/Library/Application Support/`). +- Migration tool to move existing `./.forgeplan-web/` into + `~/.forgeplan-web/`. +- Cross-host federation, auth, or remote scopes. +- Changing the default of `init -y` to user-scope (reserved for a future + major version). + +### Growth Vision + +- Add XDG support after MVP usage settles. +- Add `init --scope ` for CI sandboxes. + +--- + +## User Journeys + +### Journey 1: Fresh adopter + +**Цель**: First-time install. User wants the lightest path. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | `npx @forgeplan/web init` | Banner + scope prompt: "Where to install? (↑↓ to select) ▶ user (~/.forgeplan-web/) project (./.forgeplan-web/)" | Default highlight = user | +| 2 | Presses Enter | Scaffold copied to `~/.forgeplan-web/`; `forgeplan-web.json` records `scope: "user"` | NEW | +| 3 | `npx @forgeplan/web start` | Server boots reading from `~/.forgeplan-web/`; UI loads | Scope persists | + +**Результат**: Single shared scaffold; subsequent repos reuse it. + +### Journey 2: Existing user (project-scope) + +**Цель**: Update an existing scaffold; doesn't pass `--scope`. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | `npx @forgeplan/web init -y` | Banner + scaffold copied to `./.forgeplan-web/` (project-scope) | Backwards-compat invariant | +| 2 | `git status` | Shows `.forgeplan-web/` already ignored | `.gitignore` was appended on first init | +| 3 | `npx @forgeplan/web start` | Server boots from project scaffold | Unchanged | + +**Результат**: No behavior change; reassurance that the upgrade is safe. + +### Journey 3: Power user / CI + +**Цель**: Non-interactive install with explicit scope. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | `npx @forgeplan/web init --scope user -y` | Scaffold copied to `~/.forgeplan-web/` non-interactively; no prompt | `-y` confirms non-interactive | +| 2 | CI continues | Exit 0 | No prompt regression in CI | + +**Результат**: Scriptable, deterministic. + +--- + +## Functional Requirements + +| ID | Category | Priority | Requirement | Journey | +|----|----------|----------|-------------|---------| +| FR-001 | Core | Must | User can run `init --scope user` to install at `~/.forgeplan-web/` | Journey 1, 3 | +| FR-002 | Core | Must | User can run `init --scope project` to install at `./.forgeplan-web/` | Journey 2, 3 | +| FR-003 | Core | Must | When TTY is interactive AND `--scope` omitted AND `-y` omitted, user is prompted with arrow-key selection | Journey 1 | +| FR-004 | Core | Must | Prompt default selection is `user` for fresh installs | Journey 1 | +| FR-005 | Core | Must | When `-y` passed without `--scope`, scope defaults to `project` (zero-config preservation) | Journey 2 | +| FR-006 | Core | Must | Project-scope appends `.forgeplan-web/` to host `.gitignore` (existing behavior) | Journey 2 | +| FR-007 | Core | Must | User-scope does NOT touch any `.gitignore` | Journey 1 | +| FR-008 | Core | Must | `forgeplan-web.json` records the chosen scope as `"scope": "user" \| "project"` | Journey 1, 2, 3 | +| FR-009 | Core | Must | When non-TTY (CI) AND `--scope` omitted AND `-y` omitted, exit non-zero with message "no TTY; pass `--scope user\|project`" | Journey 3 | +| FR-010 | UX | Should | Prompt shows the resolved absolute path next to each option | Journey 1 | +| FR-011 | UX | Should | After install, stdout prints "→ scope: user (`~/.forgeplan-web/`)" line so the user knows what was chosen | Journey 1, 3 | +| FR-012 | DX | Should | `bin/lib/scope.mjs` exports pure functions reusable by PRD-026's start-resolution chain | Journey 3 | + +--- + +## Non-Functional Requirements + +| ID | Category | Requirement | Metric | Condition | Measurement | +|----|----------|-------------|--------|-----------|-------------| +| NFR-001 | Performance | Prompt first-render latency | < 50ms | TTY open | wall-clock measure | +| NFR-002 | Performance | `--scope` flag adds no measurable overhead | < 5ms over PRD-024 baseline | non-interactive `init -y --scope project` | hyperfine | +| NFR-003 | Compatibility | Existing `init -y` invocations preserve filesystem state | 0 diffs vs baseline | smoke run | `diff -r` | +| NFR-004 | Portability | `~/.forgeplan-web/` resolves correctly on macOS, Linux, Windows | path matches `os.homedir() + "/.forgeplan-web"` | all 3 OS | smoke matrix | +| NFR-005 | Safety | User-scope MUST NOT write outside `~/.forgeplan-web/` | 0 writes elsewhere | smoke audit | rule 20 verification (extended) | + +--- + +## Acceptance Criteria + +### AC-1: Backwards compatibility — `init -y` defaults to project-scope + +```gherkin +Given a fresh repo with .forgeplan/ but no .forgeplan-web/ +When the user runs `npx @forgeplan/web init -y` +Then the scaffold is created at ./.forgeplan-web/ (NOT ~/.forgeplan-web/) +And forgeplan-web.json contains "scope": "project" +And .gitignore is appended with .forgeplan-web/ +And exit code is 0 +``` + +### AC-2: Interactive prompt picks user as default + +```gherkin +Given a TTY session and no --scope flag and no -y flag +When the user runs `npx @forgeplan/web init` and presses Enter immediately +Then the scaffold is created at ~/.forgeplan-web/ +And forgeplan-web.json contains "scope": "user" +And no host .gitignore is touched +And exit code is 0 +``` + +### AC-3: Non-TTY without explicit scope fails fast + +```gherkin +Given a non-TTY session (e.g. piped from another command) +When the user runs `npx @forgeplan/web init` (no --scope, no -y) +Then exit code is non-zero +And stderr contains "no TTY" and instructs to pass --scope +And no scaffold is created +``` + +--- + +## Dependencies + +| Dependency | Type | Status | Owner | +|-----------|------|--------|-------| +| PRD-024 (citty + bin/ split) | Internal | Drafted | docs-eng-109 | +| ADR-004 (registry path) | Internal | Drafted (parallel) | adr-architect-109 | +| `consola.prompt` (via citty) | Runtime | Bundled with citty | This PRD | + +--- + +## Risks & Mitigations + +| ID | Risk | Probability | Impact | Mitigation | Owner | +|----|------|-------------|--------|------------|-------| +| R-1 | Existing project-scope users surprised by new prompt | Low | Low | `-y` preserves old behavior; release notes call it out | dev | +| R-2 | `os.homedir()` returns unexpected path on Windows | Medium | Medium | Smoke matrix asserts; document in CHANGELOG | dev | +| R-3 | User-scope clashes with previously-init'd ~/.forgeplan-web/ from another tool | Very low | Low | Detect existing forgeplan-web.json before clobber; pass `--force` to override | dev | +| R-4 | Prompt fails on dumb terminals (TERM=dumb) | Medium | Low | Treat as non-TTY; fall back to error per FR-009 | dev | + +--- + +## Affected Files + +- `bin/commands/init.mjs` — adds `--scope` arg, prompt fallback, scope-aware target path +- `bin/lib/scope.mjs` — NEW; `resolveUserScopeRoot()`, `resolveProjectScopeRoot(cwd)`, `promptScope()` +- `bin/lib/gitignore.mjs` — gated by scope (project-only) +- `bin/lib/config.mjs` — `forgeplan-web.json` schema bump (`scope` field) +- `template/src/shared/server/forgeplan.ts` — read scope from cfg if needed (read-only) +- `scripts/smoke.mjs` — assertions for user-scope, project-scope, prompt-default +- README.md — document `--scope` flag and new prompt +- GitHub sub-issue: #111 (109b) + +## Related Artifacts + +| Artifact | Relation | Status | +|----------|----------|--------| +| PRD-024 | Depends on (citty + prompt support) | Draft | +| RFC-021 | Architecture | Draft | +| ADR-004 | Decision (registry path = `~/.forgeplan-web/`) | Proposed (parallel) | +| PRD-026 | Consumes scope (start-resolution chain) | Draft | +| PRD-027 | Consumes user-scope path (instances.json) | Draft | +| GitHub #111 | Source sub-issue | Open | + +--- + +> **Next step**: Land alongside PRD-024 / RFC-021. PRD-026 (start chain) depends on this. + + + diff --git a/.forgeplan/prds/PRD-026-start-resolution-chain-project-to-user-to-prompt-init.md b/.forgeplan/prds/PRD-026-start-resolution-chain-project-to-user-to-prompt-init.md new file mode 100644 index 0000000..f09dbfb --- /dev/null +++ b/.forgeplan/prds/PRD-026-start-resolution-chain-project-to-user-to-prompt-init.md @@ -0,0 +1,273 @@ +--- +depth: standard +id: PRD-026 +kind: prd +links: +- target: PRD-027 + relation: informs +status: draft +title: start resolution chain (project to user to prompt-init) +--- + +--- +id: PRD-026 +title: "start resolution chain (project to user to prompt-init)" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +priority: P1 +depth: standard +domain: general +projectType: cli_tool +stepsCompleted: [] +--- + +# PRD-026: start resolution chain (project to user to prompt-init) + +## Executive Summary + +### Vision + +Make `npx @forgeplan/web start` find the right scaffold automatically. +When invoked from any directory, it walks a deterministic chain — +project-scope first (existing behavior), user-scope next (PRD-025's new +home), and offers to run `init` interactively when neither is found. +Users can short-circuit the chain with `--scope user|project`. + +### Problem + +Today `start` only looks at `/.forgeplan-web/` and fails immediately +if it's missing. Once PRD-025 ships, fresh users will install at user- +scope (`~/.forgeplan-web/`) but still run `npx @forgeplan/web start` +from inside a project — the start command would error out even though +a perfectly good scaffold exists in the user-scope. Without a smart +resolution chain, the user-scope rollout is unusable; the user must +either `cd ~` to start (awkward) or always pass an explicit path. + +**Impact**: Without resolution, every `start` from a fresh project +errors; documentation must explain the gotcha; user-scope adoption stalls. + +### Target Users + +| Персона | Описание | Ключевая боль | +|---------|----------|---------------| +| Project-scope user | Has `./.forgeplan-web/` in current repo | Wants `start` to keep working from cwd, no behavior change | +| User-scope user | Installed via `init --scope user` | Wants `start` to find user-scope from any cwd | +| First-time user | Has neither scaffold | Wants `start` to offer to install instead of erroring | + +### Differentiators + +- Backwards-compat invariant: a project-scope user sees zero behavior + change. The chain probes project FIRST. +- One CLI command works from any cwd — no "you have to start from `~`" + surprise for user-scope adopters. +- Friendly empty-state: prompt to init instead of error message. + +--- + +## Success Criteria + +| ID | Criterion | Metric | Current | Target | Timeframe | How to Measure | +|----|-----------|--------|---------|--------|-----------|----------------| +| SC-1 | Project-scope behavior preserved | `start` from a repo with `./.forgeplan-web/` boots existing scaffold | works | works (no change) | Same PR | Smoke test | +| SC-2 | User-scope auto-resolution from any cwd | `start` from `/tmp` with only `~/.forgeplan-web/` boots user scaffold | not implemented | works | Same PR | Smoke test | +| SC-3 | Explicit override works both ways | `start --scope user` from a repo with only project-scope errors with clear message | not implemented | exits non-zero with message | Same PR | Smoke test | +| SC-4 | Scaffold lookup latency | ms from invocation to spawn or fail | n/a (single-path probe) | < 50ms | Same PR | hyperfine | +| SC-5 | Empty-state UX | When no scaffold found, `start` prompts to init | exits with error | offers prompt | Same PR | Smoke test (TTY) | +| SC-6 | Empty-state CI behavior | Non-TTY without scaffold: clear error, exit non-zero | exits with error | unchanged (error) | Same PR | Smoke test (non-TTY) | + +--- + +## Product Scope + +### MVP (In-Scope) + +- New resolution chain in `bin/commands/start.mjs`: + 1. If `--scope project` passed: probe `/.forgeplan-web/` only. + 2. If `--scope user` passed: probe `~/.forgeplan-web/` only. + 3. If `--scope` omitted: probe project first, then user, then prompt. +- Reuse `bin/lib/scope.mjs` (PRD-025 / RFC-021). +- Empty-state: when no scaffold found AND TTY AND `-y` not passed, + prompt "No scaffold found. Run `init` now? (Y/n) Where? (user|project)". +- Non-TTY empty-state: error with "no scaffold; run `npx @forgeplan/web + init [--scope user|project]` first". +- `forgeplan-web.json` is consulted to determine the binding scope when + scaffold exists (allows `start` to log the chosen scope clearly). + +### Out of Scope + +- Walking up parent directories searching for a project-scope scaffold + (out of scope per #109; user is expected to be inside the project). +- Cross-host federation. +- Switching scope mid-session (a separate `--switch` flag deferred to + growth). +- Auto-init without prompt. + +### Growth Vision + +- Walk-up parent search (`startResolveStrategy=parents`). +- Symlink legacy `./.forgeplan-web/` → `~/.forgeplan-web/` migration + helper. + +--- + +## User Journeys + +### Journey 1: Project-scope user (no behavior change) + +**Цель**: Run `start` in a repo that already has `./.forgeplan-web/`. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | `cd ~/proj && npx @forgeplan/web start` | Resolves to `./.forgeplan-web/`; spawns server | Project chain wins | +| 2 | Browser opens `http://127.0.0.1:5174` | Health, graph load | Unchanged | + +**Результат**: Identical behavior to today. + +### Journey 2: User-scope user from any cwd + +**Цель**: Run `start` from anywhere; resolver finds the user scaffold. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | `cd /tmp && npx @forgeplan/web start` | Probes project (none) → probes user (`~/.forgeplan-web/`) → spawns | NEW | +| 2 | stdout: "→ scope: user (`~/.forgeplan-web/`)" | User sees what was picked | NEW | +| 3 | Browser opens `http://127.0.0.1:5174` | Server uses `FORGEPLAN_CWD` from `forgeplan-web.json` | Unchanged | + +**Результат**: Single shared scaffold serves all repos. + +### Journey 3: First-time user / empty state + +**Цель**: Run `start` before installing. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | `npx @forgeplan/web start` (no scaffold anywhere, TTY) | Prompt: "No scaffold found. Install now? (Y/n)" → "Where? user/project" | NEW | +| 2 | User picks "user" | Runs init flow inline; then spawns | One-step onboarding | + +**Результат**: Smoother first run. + +--- + +## Functional Requirements + +| ID | Category | Priority | Requirement | Journey | +|----|----------|----------|-------------|---------| +| FR-001 | Core | Must | User can run `start` from any cwd; CLI finds the nearest scaffold via the chain (project → user → prompt) | Journey 1, 2 | +| FR-002 | Core | Must | When `--scope project` passed, only `/.forgeplan-web/` is probed; missing → error | Journey 1 | +| FR-003 | Core | Must | When `--scope user` passed, only `~/.forgeplan-web/` is probed; missing → error | Journey 2 | +| FR-004 | Core | Must | When no scaffold is found AND TTY AND `-y` omitted, user is prompted to init inline | Journey 3 | +| FR-005 | Core | Must | When no scaffold is found AND non-TTY (or `-y` passed), exit non-zero with message instructing init | Journey 3 | +| FR-006 | Core | Must | Backwards compat: existing project-scope users see no behavior change | Journey 1 | +| FR-007 | UX | Should | After resolution, stdout prints "→ scope: user (`~/.forgeplan-web/`)" or "→ scope: project (./.forgeplan-web/)" | Journey 1, 2 | +| FR-008 | UX | Should | Resolver respects `FORGEPLAN_WEB_SCAFFOLD` env var as final override (escape hatch) | Journey 2 | +| FR-009 | DX | Should | `bin/commands/start.mjs` reuses `resolveScopeRoot` from `bin/lib/scope.mjs` (no path duplication) | Journey 1, 2 | + +--- + +## Non-Functional Requirements + +| ID | Category | Requirement | Metric | Condition | Measurement | +|----|----------|-------------|--------|-----------|-------------| +| NFR-001 | Performance | Scaffold lookup walltime | < 50ms | cold cache | hyperfine (median 5 runs) | +| NFR-002 | Compatibility | Project-scope user `start` filesystem touch | 0 changes | smoke baseline | `diff -r` | +| NFR-003 | Portability | Path probing works on macOS, Linux, Windows | All 3 OS green | CI matrix | smoke matrix | +| NFR-004 | Safety | Resolver MUST NOT execute child processes during probe | 0 spawns | static review | grep `spawn`/`execFile` outside the final `node index.js` invocation | + +--- + +## Acceptance Criteria + +### AC-1: Project-scope wins when both scopes exist + +```gherkin +Given ./.forgeplan-web/ exists in cwd +And ~/.forgeplan-web/ also exists +When the user runs `npx @forgeplan/web start` +Then the resolver picks ./.forgeplan-web/ +And stdout prints "→ scope: project (./.forgeplan-web/)" +And the server boots from cwd +``` + +### AC-2: User-scope picked when project-scope absent + +```gherkin +Given no .forgeplan-web/ exists in cwd +And ~/.forgeplan-web/ exists +When the user runs `npx @forgeplan/web start` +Then the resolver picks ~/.forgeplan-web/ +And stdout prints "→ scope: user (~/.forgeplan-web/)" +And the server boots from the user-scope scaffold +``` + +### AC-3: Empty state — TTY prompts to init + +```gherkin +Given no scaffold exists in either scope +And the session is TTY +When the user runs `npx @forgeplan/web start` +Then stdout shows a prompt asking to init now +And on confirmation, init runs inline +And on decline, exit code is non-zero with helpful message +``` + +### AC-4: Empty state — non-TTY errors + +```gherkin +Given no scaffold exists in either scope +And the session is non-TTY (CI) +When the user runs `npx @forgeplan/web start` +Then exit code is non-zero +And stderr instructs to run `init` first with --scope flag +``` + +--- + +## Dependencies + +| Dependency | Type | Status | Owner | +|-----------|------|--------|-------| +| PRD-025 (`--scope` flag plumbing) | Internal | Drafted | docs-eng-109 | +| RFC-021 (scope resolver) | Internal | Drafted | docs-eng-109 | +| PRD-024 (citty + bin/ split) | Internal | Drafted | docs-eng-109 | + +--- + +## Risks & Mitigations + +| ID | Risk | Probability | Impact | Mitigation | Owner | +|----|------|-------------|--------|------------|-------| +| R-1 | Existing project-scope user inadvertently gets user-scope when they `cd` outside the project | Low | Medium | Project always probed first; clearly print resolved scope so user notices | dev | +| R-2 | Inline init prompt stalls CI that expected fast error | Low | Medium | TTY check guards prompt; non-TTY errors immediately | dev | +| R-3 | `~/.forgeplan-web/forgeplan-web.json` corrupted → start picks user but server fails | Low | Low | Validate JSON parse before spawn; fall back to error | dev | +| R-4 | Symlink at `~/.forgeplan-web/` causes confusion | Low | Low | `lstatSync` before spawn; refuse if symlink (mirrors update's CWE-59 guard) | dev | + +--- + +## Affected Files + +- `bin/commands/start.mjs` — adds resolution chain +- `bin/lib/scope.mjs` — extended with `resolveStartScaffold` (or fold into `resolveScopeRoot`) +- `bin/lib/config.mjs` — reads `scope` field from `forgeplan-web.json` +- `scripts/smoke.mjs` — chain assertions +- README.md — document chain order +- GitHub sub-issue: #112 (109c) + +## Related Artifacts + +| Artifact | Relation | Status | +|----------|----------|--------| +| PRD-025 | Depends on (`--scope` flag) | Draft | +| RFC-021 | Depends on (resolver) | Draft | +| RFC-022 | Architecture | Draft | +| PRD-024 | Depends on (citty + bin/ split) | Draft | +| PRD-027 | Informs (registry's stale-sweep runs on `start`) | Draft | +| GitHub #112 | Source sub-issue | Open | + +--- + +> **Next step**: Land alongside RFC-022. PRD-027 (registry) hooks into `start` after this lands. + + + diff --git a/.forgeplan/prds/PRD-027-multi-instance-registry-incremental-ports-global-json-stale-invalidation.md b/.forgeplan/prds/PRD-027-multi-instance-registry-incremental-ports-global-json-stale-invalidation.md new file mode 100644 index 0000000..98c6834 --- /dev/null +++ b/.forgeplan/prds/PRD-027-multi-instance-registry-incremental-ports-global-json-stale-invalidation.md @@ -0,0 +1,290 @@ +--- +depth: standard +id: PRD-027 +kind: prd +links: +- target: PRD-029 + relation: informs +status: draft +title: Multi-instance registry — incremental ports, global JSON, stale invalidation +--- + +--- +id: PRD-027 +title: "Multi-instance registry — incremental ports, global JSON, stale invalidation" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +priority: P1 +depth: standard +domain: general +projectType: cli_tool +stepsCompleted: [] +--- + +# PRD-027: Multi-instance registry — incremental ports, global JSON, stale invalidation + +## Executive Summary + +### Vision + +Allow multiple `npx @forgeplan/web start` invocations to coexist on a +single machine. Each running server claims an incremental free port +starting from `PORT` (default 5174), registers itself in a global +`~/.forgeplan-web/instances.json` registry, heartbeats every 30s, and +deregisters on graceful exit. A start-time stale-sweep purges entries +whose PID is dead or whose last heartbeat is older than 60s. + +### Problem + +Today only one server can run at a time — the second `start` crashes +with `EADDRINUSE` on port 5174. Users with multiple forgeplan workspaces +(monorepo + side projects + research forks) must stop one server to +look at another. There's no inventory of running instances, so the +upcoming HealthBar instance switcher (#115) has nothing to read from. + +**Impact**: Devs who manage ≥2 forgeplan repos lose flow-state cycles +killing/restarting; PRD-029 (instance switcher) is impossible without +a shared registry; multi-window comparison workflows are unsupported. + +### Target Users + +| Персона | Описание | Ключевая боль | +|---------|----------|---------------| +| Multi-repo dev | Has 2-5 forgeplan workspaces (work + side projects + experiments) | Can't run two servers; constant kill/restart cycle | +| Researcher | Compares two snapshots side-by-side | No cross-instance switcher in UI; must alt-tab terminals | +| Power user | Runs `start` from CI matrix or e2e tests | Port conflicts cascade into flaky test runs | + +### Differentiators + +- Atomic JSON writes (tmp+rename) survive concurrent starts. +- `process.kill(pid, 0)` liveness probe is portable (POSIX + Windows). +- Heartbeat freshness window (>60s = dead) catches Docker freezes / + laptop sleep. +- ID format `host:port` is human-readable and naturally unique. + +--- + +## Success Criteria + +| ID | Criterion | Metric | Current | Target | Timeframe | How to Measure | +|----|-----------|--------|---------|--------|-----------|----------------| +| SC-1 | Two concurrent starts both succeed | Exit codes + listening sockets | 1st: ok, 2nd: EADDRINUSE | both ok, ports 5174 + 5175 | Same PR | Smoke parallel | +| SC-2 | Registry file is valid JSON after concurrent writes | `JSON.parse(instances.json)` exit 0 across 10 parallel starts | n/a | exit 0 100% | Same PR | Stress test | +| SC-3 | Stale entries are purged on `start` | After PID 12345 is dead, next start removes its row | n/a | row removed | Same PR | Smoke (kill -9 + restart) | +| SC-4 | Heartbeat freshness window | ms between heartbeats | n/a | 30000 ± 200 | Same PR | Log inspection | +| SC-5 | Registry write atomicity latency | ms per write | n/a | < 10ms p95 | Same PR | Microbench | +| SC-6 | Registry parse latency | ms to read + parse | n/a | < 5ms for ≤100 entries | Same PR | Microbench | +| SC-7 | Port allocator probe latency | ms to find first free port from base | n/a | < 100ms typical | Same PR | hyperfine | +| SC-8 | `GET /api/instances` exposes registry | Response shape `{ ok, data: { instances }, error? }` | endpoint missing | endpoint exists, returns array | Same PR | Smoke HTTP | + +--- + +## Product Scope + +### MVP (In-Scope) + +- Registry file at `~/.forgeplan-web/instances.json` (locked by ADR-004). +- Schema versioned (v1) — formal contract in SPEC-003. +- Helper module `bin/lib/registry.mjs` — pure functions for read, + write, append, remove, sweep. +- Server-side reader `template/src/shared/server/registry.ts` — same + format, read-only. +- Endpoint `GET /api/instances` returning `{ ok, data: { instances }, + error? }` (mirrors existing envelope; rule 22 amendment in PRD-029 + documents allow-list extension). +- Port allocator: increment from `PORT` env (default 5174) until first + free, capped at `PORT + 100` (max 100 instances). +- Liveness probe: `process.kill(pid, 0)` (no-op signal). On + EPERM/ESRCH the entry is presumed dead. +- Heartbeat: server-side `setInterval` re-writes `heartbeatAt` every + 30s. +- Deregister: `process.on('SIGINT' | 'SIGTERM' | 'beforeExit')` removes + the instance row. +- Stale sweep on `start`: any entry with dead PID OR `now - + heartbeatAt > 60s` is removed before the new instance is appended. + +### Out of Scope + +- Cross-host federation (only same-machine). +- Authentication / auth-token in the registry. +- A "kill stale instance" CLI command (manual stop is fine for MVP). +- HTTPS / port reservation across reboots. +- Instances launched outside `npx @forgeplan/web start` (e.g. raw `node + index.js`) registering themselves — those are invisible to the + registry. Documented limitation. + +### Growth Vision + +- `forgeplan-web doctor` to inspect / clean the registry. +- Optional auth-token field for shared-tenant scenarios. + +--- + +## User Journeys + +### Journey 1: Multi-repo dev runs two servers + +**Цель**: Have two forgeplan-web instances at once. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | Terminal A: `cd ~/proj-a && npx @forgeplan/web start` | Bind 5174; register in `~/.forgeplan-web/instances.json` | First instance | +| 2 | Terminal B: `cd ~/proj-b && npx @forgeplan/web start` | 5174 busy; allocator probes 5175; bind; register | Second instance | +| 3 | Browser: open `http://127.0.0.1:5174` | Sees proj-a graph | — | +| 4 | Browser: open `http://127.0.0.1:5175` | Sees proj-b graph | — | +| 5 | Ctrl-C in Terminal A | proj-a deregisters from registry | Clean exit | + +**Результат**: Two simultaneous servers; registry tracks both. + +### Journey 2: Stale-sweep after crash + +**Цель**: Recover from a crashed instance. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | `kill -9 ` on instance from Journey 1 | Instance dies; registry entry NOT removed | Crash, no SIGTERM | +| 2 | New `npx @forgeplan/web start` | Sweep finds dead PID + stale heartbeat → removes row, then appends new | Sweep cleans up | +| 3 | `cat ~/.forgeplan-web/instances.json` | Only the new instance remains | Self-healing | + +**Результат**: Registry stays consistent without manual cleanup. + +### Journey 3: API consumer reads registry + +**Цель**: HealthBar instance switcher (PRD-029) reads the registry. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | Browser polls `GET /api/instances` every 5s | Returns `{ ok, data: { instances: [...] } }` | Read-only | +| 2 | UI compares response to current host:port | Shows switcher when ≥2 entries | PRD-029 | + +**Результат**: Live inventory consumed by UI. + +--- + +## Functional Requirements + +| ID | Category | Priority | Requirement | Journey | +|----|----------|----------|-------------|---------| +| FR-001 | Core | Must | Multiple instances of `npx @forgeplan/web start` can run concurrently on incremental ports | Journey 1 | +| FR-002 | Core | Must | Each running instance is registered with project metadata in `~/.forgeplan-web/instances.json` | Journey 1 | +| FR-003 | Core | Must | Each row contains `id, host, port, pid, scope, workspaceRoot, projectName, startedAt, heartbeatAt, webVersion, forgeplanCli` (per SPEC-003) | Journey 1 | +| FR-004 | Core | Must | Stale entries (dead PID OR `now - heartbeatAt > 60s`) are removed on every `start` | Journey 2 | +| FR-005 | Core | Must | Each instance heartbeats every 30s by re-writing its `heartbeatAt` | Journey 1 | +| FR-006 | Core | Must | Each instance deregisters on SIGINT/SIGTERM/beforeExit | Journey 1 | +| FR-007 | Core | Must | Registry writes are atomic (tmp+rename) — concurrent writes never produce invalid JSON | Journey 1 | +| FR-008 | Core | Must | Port allocator probes increment from `PORT` env (default 5174) capped at `PORT + 100` | Journey 1 | +| FR-009 | Core | Must | API endpoint `GET /api/instances` returns the current registry view | Journey 3 | +| FR-010 | Core | Must | Liveness probe uses `process.kill(pid, 0)` — works on POSIX and Windows | Journey 2 | +| FR-011 | UX | Should | When port 5174 is busy and we bind 5175, stdout reports the actual port clearly | Journey 1 | +| FR-012 | DX | Should | `bin/lib/registry.mjs` exports pure helpers (`readRegistry`, `writeRegistry`, `appendInstance`, `removeInstance`, `sweepStale`) | Journey 1, 2 | + +--- + +## Non-Functional Requirements + +| ID | Category | Requirement | Metric | Condition | Measurement | +|----|----------|-------------|--------|-----------|-------------| +| NFR-001 | Performance | Registry write walltime | < 10ms p95 | tmp+rename, < 50KB file | microbench | +| NFR-002 | Performance | Registry parse walltime | < 5ms p95 | ≤ 100 entries | microbench | +| NFR-003 | Performance | Stale sweep walltime | < 50ms | 100 entries with mixed alive/dead PIDs | microbench | +| NFR-004 | Performance | Port bind probe walltime | < 100ms typical | first free port within `[PORT, PORT+100]` | hyperfine | +| NFR-005 | Reliability | Concurrent writes preserve JSON validity | 100% across 10 parallel starts | stress test | parse loop | +| NFR-006 | Reliability | Heartbeat skew | ≤ 200ms vs setInterval(30000) | normal load | log timestamps | +| NFR-007 | Safety | Registry file path locked | exact match `~/.forgeplan-web/instances.json` | resolved via `bin/lib/scope.mjs` | grep | +| NFR-008 | Read-only | `/api/instances` endpoint MUST NOT spawn forgeplan or write to disk | 0 spawns, 0 fs.write* | static review | grep | + +--- + +## Acceptance Criteria + +### AC-1: Two concurrent starts both succeed + +```gherkin +Given no scaffolds running +When the user starts instance A in Terminal 1, then instance B in Terminal 2 +Then instance A binds 127.0.0.1:5174 +And instance B binds 127.0.0.1:5175 +And ~/.forgeplan-web/instances.json contains exactly two rows +And both browsers can reach their respective servers +``` + +### AC-2: Stale sweep on next start + +```gherkin +Given instance A is registered with PID X +And process X is killed with SIGKILL (no chance to deregister) +When the user runs `start` again (instance B) +Then ~/.forgeplan-web/instances.json contains exactly one row (instance B) +And the dead PID X row was removed +``` + +### AC-3: GET /api/instances returns the live registry + +```gherkin +Given two instances are running +When a browser fetches GET http://127.0.0.1:5174/api/instances +Then the response is JSON with shape { ok: true, data: { instances: [...] } } +And data.instances has exactly 2 entries +And each entry has fields per SPEC-003 v1 +``` + +--- + +## Dependencies + +| Dependency | Type | Status | Owner | +|-----------|------|--------|-------| +| PRD-026 (start chain) | Internal | Drafted | docs-eng-109 | +| PRD-025 (user-scope path) | Internal | Drafted | docs-eng-109 | +| ADR-004 (registry path & format) | Internal | Drafted (parallel) | adr-architect-109 | +| SPEC-003 (registry schema) | Internal | This PRD defines it | docs-eng-109 | + +--- + +## Risks & Mitigations + +| ID | Risk | Probability | Impact | Mitigation | Owner | +|----|------|-------------|--------|------------|-------| +| R-1 | Concurrent atomic writes lose updates (last-write-wins) | Medium | Medium | Read-modify-write inside try-locked region using lockfile (e.g. `proper-lockfile`); accept "last-writer-wins for the same row" semantic for MVP since heartbeats are idempotent | dev | +| R-2 | Windows rename across drives fails | Low | Medium | tmp file in same dir as target (always) | dev | +| R-3 | PID-recycling — new process gets old PID | Very low | Low | Heartbeat freshness check catches it (>60s = dead even if PID alive) | dev | +| R-4 | `process.kill(pid, 0)` permission errors on Windows | Low | Low | Catch EPERM as "alive" (process exists, we just can't signal); document | dev | +| R-5 | `~/.forgeplan-web/` doesn't exist when first start runs | Medium | Low | Auto-create dir on first registry write | dev | +| R-6 | Heartbeat survives crashed UI but dies later → window > 60s | Low | Low | 60s window is intentional buffer; sweep on next start catches | dev | + +--- + +## Affected Files + +- `bin/lib/registry.mjs` (NEW) — pure helpers +- `bin/commands/start.mjs` — port allocator + sweep + appendInstance + signal handlers +- `template/src/shared/server/registry.ts` (NEW) — server-side reader +- `template/src/shared/server/heartbeat.ts` (NEW) — `setInterval` lifecycle +- `template/src/routes/api/instances/+server.ts` (NEW) — read-only endpoint +- `template/src/hooks.server.ts` — start the heartbeat lifecycle +- `.forgeplan/specs/SPEC-003-instance-registry-json-schema-forgeplan-web-instances-json.md` — schema +- `scripts/smoke.mjs` — concurrent start asserts +- GitHub sub-issue: #113 (109d) + +## Related Artifacts + +| Artifact | Relation | Status | +|----------|----------|--------| +| PRD-026 | Depends on (start chain) | Draft | +| PRD-025 | Depends on (`~/.forgeplan-web/`) | Draft | +| RFC-023 | Architecture | Draft | +| ADR-004 | Decision (registry path & format) | Proposed (parallel) | +| SPEC-003 | Defines (this PRD's schema) | Draft | +| PRD-029 | Consumed by (HealthBar switcher) | Draft | +| GitHub #113 | Source sub-issue | Open | + +--- + +> **Next step**: Land alongside RFC-023 + SPEC-003. PRD-029 consumes `/api/instances`. + + + + + diff --git a/.forgeplan/prds/PRD-028-combobox-primitive-in-shared-ui-bits-ui-port.md b/.forgeplan/prds/PRD-028-combobox-primitive-in-shared-ui-bits-ui-port.md new file mode 100644 index 0000000..1180907 --- /dev/null +++ b/.forgeplan/prds/PRD-028-combobox-primitive-in-shared-ui-bits-ui-port.md @@ -0,0 +1,260 @@ +--- +depth: standard +id: PRD-028 +kind: prd +links: +- target: PRD-029 + relation: informs +status: draft +title: Combobox primitive in shared/ui (bits-ui port) +--- + +--- +id: PRD-028 +title: "Combobox primitive in shared/ui (bits-ui port)" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +priority: P2 +depth: standard +domain: general +projectType: web_app +stepsCompleted: [] +--- + +# PRD-028: Combobox primitive in shared/ui (bits-ui port) + +## Executive Summary + +### Vision + +Add a Combobox primitive to `template/src/shared/ui/` — a search-input- +augmented dropdown built on top of `bits-ui` (already in +`template/package.json#dependencies` since PRD-018). It mirrors the +shape of the existing `Select` primitive but adds keyboard-driven +search, making it the right fit for any list whose count grows past +~10 items. + +### Problem + +The HealthBar instance switcher (PRD-029) needs a dropdown with +keyboard search — users will accumulate dozens of registered instances +over time, and `Select` becomes unusable past ~15 items (no filter, +arrow-key linear nav). Hand-rolling search inside the consumer widget +would violate rule 24 (`shared/ui` ownership). The right move is to +add Combobox as a first-class primitive, showcased on `/playground`, +reusable by any future consumer. + +**Impact**: Without Combobox, PRD-029's switcher either ships a hand- +rolled search inside `widgets/health-bar/` (violation of rule 24) or +stays linear-scan (poor UX past 5-10 instances). + +### Target Users + +| Персона | Описание | Ключевая боль | +|---------|----------|---------------| +| Widget composer (contributor) | Builds widgets in `entities/`, `widgets/`, `pages/` | No primitive for searchable dropdowns; would have to re-skin Select via :global() (forbidden) | +| HealthBar end-user | Sees the instance switcher | Linear scrolling through dozens of instances is slow; expects type-to-filter | + +### Differentiators + +- bits-ui-based: same accessibility chops as the rest of the catalogue. +- Variants `default` and `mono` mirror existing primitive patterns. +- Sizes `sm` and `md` mirror existing primitive patterns. +- /playground showcase across all variant × size × theme combos — + catalogue stays the source of truth (rule 24 invariant). + +--- + +## Success Criteria + +| ID | Criterion | Metric | Current | Target | Timeframe | How to Measure | +|----|-----------|--------|---------|--------|-----------|----------------| +| SC-1 | Combobox available from shared/ui barrel | `import { Combobox } from '@/shared/ui'` resolves | not implemented | resolves with full type signatures | Same PR | `npm run check` | +| SC-2 | All variant × size combos showcased on /playground | Tile count for Combobox section | 0 | 4 (2 variants × 2 sizes) × 3 themes (light/dark/orch) | Same PR | Manual verification + screenshots | +| SC-3 | Bundle delta | dist-experimental size delta | 0 | < 5KB gzipped | Same PR | `scripts/build.mjs` size diff | +| SC-4 | Type-check 0 errors | `npm run check` exit code | 0 | 0 (no regressions) | Same PR | CI | +| SC-5 | Rule 24 verification clean | grep snippet from rule 24 | 0 hits | 0 hits | Same PR | rule-24 verification snippet | +| SC-6 | First-paint of /playground unchanged | Time-to-LCP delta | baseline | < +50ms | Same PR | Lighthouse run | +| SC-7 | Keyboard accessibility | All a11y semantics work (arrow up/down, Enter, Escape, Home/End, type-to-filter) | n/a | passes axe smoke + manual | Same PR | axe + manual | + +--- + +## Product Scope + +### MVP (In-Scope) + +- New primitive `template/src/shared/ui/combobox/` with the same shape + as existing primitives (`Combobox.svelte`, sub-components, barrel + `index.ts`). +- Sub-components: `ComboboxTrigger`, `ComboboxContent`, `ComboboxItem`, + `ComboboxInput` (search input rendered inside Content). +- Variants: `default`, `mono` (matches Toggle/Button/Badge convention). +- Sizes: `sm`, `md` (matches existing). +- Two-way binding via `$bindable()` for selected value. +- Re-export from `template/src/shared/ui/index.ts`. +- /playground page section showcasing all variant × size combos in + light + dark + orch themes. +- `class?: string` forwarded to root for layout-only consumer styling + (rule 24 invariant). +- Accessibility per bits-ui: arrow-key nav, Enter to select, Escape to + close, type-to-filter, ARIA pattern (`combobox` / `listbox`). + +### Out of Scope + +- Multi-select Combobox (only single-select MVP). +- Async/server-side option loading — items are passed in directly. +- Virtualized list rendering — punt until >100 options pattern emerges. +- Custom rendering of options beyond label + optional icon. +- Adopting Combobox into existing widgets that currently use Select — + unless the widget owner opts in. + +### Growth Vision + +- Multi-select variant. +- Async option provider hook. +- Virtualization for very long lists. + +--- + +## User Journeys + +### Journey 1: Contributor adds Combobox to a new widget + +**Цель**: Use Combobox in a new widget without violating rule 24. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | Imports `import { Combobox } from '@/shared/ui'` | Type-checked, available | No re-skin needed | +| 2 | Renders `` | Renders with project tokens | Variants / sizes from catalogue | +| 3 | Reviews on /playground first | Sees the same variant × size live | Catalogue invariant | + +**Результат**: Widget consumes primitive cleanly. + +### Journey 2: End-user uses keyboard search + +**Цель**: Find an item among many by typing. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | Clicks the trigger | Content opens; input focused | Keyboard-first | +| 2 | Types a few chars | List filters live | bits-ui handles | +| 3 | Arrow-down + Enter | Selection commits | Same as Select | + +**Результат**: Fast selection in long lists. + +--- + +## Functional Requirements + +| ID | Category | Priority | Requirement | Journey | +|----|----------|----------|-------------|---------| +| FR-001 | Core | Must | Contributor can `import { Combobox } from '@/shared/ui'` | Journey 1 | +| FR-002 | Core | Must | Combobox renders a trigger button + popover containing a search input + filtered option list | Journey 2 | +| FR-003 | Core | Must | Combobox supports keyboard navigation (arrow up/down, Home/End, Enter, Escape, type-to-filter) per bits-ui defaults | Journey 2 | +| FR-004 | Core | Must | Combobox supports `variant` prop with values `default` and `mono` | Journey 1 | +| FR-005 | Core | Must | Combobox supports `size` prop with values `sm` and `md` | Journey 1 | +| FR-006 | Core | Must | Combobox accepts `value` (bindable) and `options` (array of `{ value, label, icon? }`) | Journey 1, 2 | +| FR-007 | Core | Must | Combobox forwards `class?: string` to the root for consumer layout-only styling (rule 24 invariant) | Journey 1 | +| FR-008 | Core | Must | Combobox is showcased on /playground in all 2 × 2 × 3 (variant × size × theme) combinations | Journey 1 | +| FR-009 | Core | Must | Combobox uses bits-ui's Combobox primitive under the hood (no hand-rolled accessibility) | Journey 2 | +| FR-010 | Core | Must | Combobox styles read CSS variables from `template/src/app/styles/app.css` (`--bg`, `--bg-1`, `--bg-2`, `--fg`, `--fg-1`, `--accent`, `--line`, etc.) — no Tailwind, no inline color/border styles | Journey 1 | +| FR-011 | UX | Should | Combobox preserves dual-theme (light / dark via `data-theme`) without consumer intervention | Journey 1 | +| FR-012 | UX | Should | Combobox emits `onValueChange` callback in the same shape as ToggleGroup / Select | Journey 1 | + +--- + +## Non-Functional Requirements + +| ID | Category | Requirement | Metric | Condition | Measurement | +|----|----------|-------------|--------|-----------|-------------| +| NFR-001 | Bundle | dist-experimental size delta from adding Combobox | < 5KB gzipped | `npm run build` | size diff | +| NFR-002 | Performance | /playground first-paint regression | < +50ms | Lighthouse on the section | LCP delta | +| NFR-003 | A11y | Axe score on /playground Combobox section | 0 violations | both themes | Manual axe run | +| NFR-004 | Type safety | `npm run check` exit code | 0 | full check after adding primitive | CI | +| NFR-005 | Rule 24 | Upper-layer `:global()` overrides on Combobox internal classes | 0 hits | rule-24 grep snippet | grep | + +--- + +## Acceptance Criteria + +### AC-1: Combobox primitive available from barrel + +```gherkin +Given the new primitive lives at template/src/shared/ui/combobox/ +When a developer types `import { Combobox } from '@/shared/ui'` in a widget +Then svelte-check resolves the import with full type signatures +And rendering with valid props produces no runtime errors +``` + +### AC-2: /playground showcase complete + +```gherkin +Given /playground is loaded +When the user scrolls to the Combobox section +Then there are 4 tiles (2 variants × 2 sizes) +And each tile is rendered under light, dark, and orch themes +And each rendering passes axe smoke (0 violations) +``` + +### AC-3: Rule 24 verification clean + +```gherkin +Given Combobox is in shared/ui and consumed by widgets +When the rule-24 verification snippet runs +Then no upper-layer Svelte file targets Combobox internal class names via :global() +And no widget patches Combobox chrome from above +``` + +--- + +## Dependencies + +| Dependency | Type | Status | Owner | +|-----------|------|--------|-------| +| bits-ui (`@melt-ui/bits-ui`-equiv) | Runtime (already a dep) | Present | template/package.json | +| PRD-018 (shadcn primitives in shared/ui) | Internal | Active | n/a (foundational) | +| PRD-029 (HealthBar switcher) | Consumer | Drafted | docs-eng-109 | + +--- + +## Risks & Mitigations + +| ID | Risk | Probability | Impact | Mitigation | Owner | +|----|------|-------------|--------|------------|-------| +| R-1 | bits-ui's Combobox API changes between minor versions | Low | Low | Pin minor in `template/package.json`; rely on existing PRD-018 update flow | dev | +| R-2 | Bundle bloat exceeds 5KB cap | Low | Medium | Measure post-build; bits-ui Combobox is tree-shaken-friendly | dev | +| R-3 | Combobox CSS overrides break orch theme | Medium | Low | /playground showcase asserts all 3 themes; visual review pre-merge | dev | +| R-4 | Existing Select consumers want to swap to Combobox immediately | Low | Low | Out of scope; document upgrade path; consumers opt in | dev | + +--- + +## Affected Files + +- `template/src/shared/ui/combobox/Combobox.svelte` (NEW) +- `template/src/shared/ui/combobox/ComboboxTrigger.svelte` (NEW) +- `template/src/shared/ui/combobox/ComboboxContent.svelte` (NEW) +- `template/src/shared/ui/combobox/ComboboxItem.svelte` (NEW) +- `template/src/shared/ui/combobox/ComboboxInput.svelte` (NEW) +- `template/src/shared/ui/combobox/index.ts` (NEW) +- `template/src/shared/ui/index.ts` — re-export Combobox +- `template/src/routes/playground/+page.svelte` — showcase section +- `template/src/shared/ui/README.md` — document new primitive +- GitHub sub-issue: #114 (109e) + +## Related Artifacts + +| Artifact | Relation | Status | +|----------|----------|--------| +| PRD-018 | Foundation (bits-ui primitives in shared/ui) | Active | +| RFC-024 | Architecture | Draft | +| PRD-029 | Consumer (HealthBar switcher) | Draft | +| RFC-016 | Reference (bits-ui-based primitives convention) | Active | +| GitHub #114 | Source sub-issue | Open | + +--- + +> **Next step**: Land alongside RFC-024. Independent of PRD-024..027 chain — can ship in parallel. + + diff --git a/.forgeplan/prds/PRD-029-healthbar-instance-switcher-combobox-wired-to-api-instances.md b/.forgeplan/prds/PRD-029-healthbar-instance-switcher-combobox-wired-to-api-instances.md new file mode 100644 index 0000000..ab1b3e9 --- /dev/null +++ b/.forgeplan/prds/PRD-029-healthbar-instance-switcher-combobox-wired-to-api-instances.md @@ -0,0 +1,312 @@ +--- +depth: standard +id: PRD-029 +kind: prd +status: draft +title: HealthBar instance switcher (Combobox wired to /api/instances) +--- + +--- +id: PRD-029 +title: "HealthBar instance switcher (Combobox wired to /api/instances)" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +priority: P1 +depth: standard +domain: general +projectType: web_app +stepsCompleted: [] +--- + +# PRD-029: HealthBar instance switcher (Combobox wired to /api/instances) + +## Executive Summary + +### Vision + +Wire the HealthBar widget to the new `/api/instances` endpoint +(PRD-027 / RFC-025). When two or more forgeplan-web instances are +running, HealthBar renders a Combobox (PRD-028) listing them with the +current instance pre-selected. Picking another navigates the browser +to it via `window.location.replace`. With a single instance, the +existing static label is preserved (zero-config). + +### Problem + +Once PRD-027 makes multi-instance possible, users have no in-app way +to jump between instances — they must remember port numbers and edit +the URL. PRD-028 ships the right primitive (Combobox); this PRD wires +it to the registry data and integrates it into HealthBar's existing +layout. + +**Impact**: Multi-instance feature is half-shipped without the UI +switcher; users who run 5 instances must memorize 5 URLs (`5174`, +`5175`, …) and tab through them manually. + +### Target Users + +| Персона | Описание | Ключевая боль | +|---------|----------|---------------| +| Multi-instance dev | Has 2-5 instances running across repos | Must remember port numbers; alt-tab between browser tabs | +| Single-instance user | Has 1 instance | Wants no UI clutter; current static label preferred | +| Mobile / narrow viewport user | HealthBar already responsive | Combobox must not break narrow layouts | + +### Differentiators + +- Auto-hides when only 1 instance — zero clutter for the common case. +- Marks current instance visually (e.g. checkmark + accent). +- 5s client poll matches existing `healthPoller` cadence. +- Read-only — switcher reads `/api/instances`, never writes. + +--- + +## Success Criteria + +| ID | Criterion | Metric | Current | Target | Timeframe | How to Measure | +|----|-----------|--------|---------|--------|-----------|----------------| +| SC-1 | Switcher appears only when ≥2 instances | Conditional render check | not implemented | renders only when `instances.length >= 2` | Same PR | Unit + smoke | +| SC-2 | Selecting another instance navigates browser | `window.location.replace` invoked | not implemented | invoked with target URL | Same PR | E2E spy | +| SC-3 | Current instance pre-selected | combobox `value` matches current `host:port` | n/a | matches | Same PR | Unit | +| SC-4 | Single-instance UX preserved | HealthBar render diff vs current main | unchanged | unchanged (no Combobox in DOM) | Same PR | Snapshot test | +| SC-5 | Instance fetch latency | `GET /api/instances` round-trip | n/a | < 100ms p95 | Same PR | Browser perf timing | +| SC-6 | Combobox first-paint | ms from `instances` arrival to first render | n/a | < 50ms | Same PR | Performance.mark | +| SC-7 | Rule 24 clean (no :global() override on Combobox internals) | rule-24 grep snippet | 0 hits | 0 hits | Same PR | grep | +| SC-8 | Rule 22 amendment landed | Endpoint `/api/instances` documented in `.claude/rules/22-readonly-proxy.md` | not documented | documented as second non-forgeplan endpoint | Same PR | Diff review | + +--- + +## Product Scope + +### MVP (In-Scope) + +- New entity slice `template/src/entities/instance/` — types + client + poller mirroring the shape of `template/src/entities/health/`. +- Poll `/api/instances` every 5s (same cadence as healthPoller). +- HealthBar renders a Combobox in the `.meta` block when + `instances.length >= 2`. Otherwise: existing static label kept. +- Combobox `value` = current instance's `host:port`. Options listed in + ascending port order; current marked with an accent indicator. +- Selecting another option triggers `window.location.replace(\`http://${ + selected.host}:${selected.port}\`)` — full reload, no SPA navigation + (each instance is a separate Node process). +- Endpoint `template/src/routes/api/instances/+server.ts` (created in + PRD-027) — read-only, returns standard envelope. +- **Rule 22 amendment** (this PRD): document `/api/instances` as the + second permitted non-forgeplan endpoint (alongside `/api/update-check`). + +### Out of Scope + +- Cross-host federation (`http://other-machine:5174` is not in the + registry by design). +- Showing instance health (red/green dot per instance) — punt to + growth. +- Authoring / killing instances from the UI — registry is read-only + surface (rule 22 invariant). +- Persisting "favorite" instances across switches. + +### Growth Vision + +- Per-instance health indicator (red/green dot) sourced from + `forgeplan health` of the target. +- Recently-visited instance list. +- Quick-stop button per instance (would require a new mutating endpoint + — separate ADR). + +--- + +## User Journeys + +### Journey 1: Multi-instance dev switches between projects + +**Цель**: Move from `proj-a` to `proj-b` without leaving the browser. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | Two instances running (5174 + 5175) | HealthBar Combobox visible with 2 entries | NEW | +| 2 | Clicks Combobox | Dropdown opens; current marked | Combobox primitive | +| 3 | Picks `proj-b (127.0.0.1:5175)` | `window.location.replace` → `http://127.0.0.1:5175` | Full reload | +| 4 | Browser is on proj-b | proj-b's HealthBar shows it as current | Round-trip | + +**Результат**: One-click switch. + +### Journey 2: Single-instance user — no clutter + +**Цель**: Existing single-instance user sees no UI change. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | Visits `http://127.0.0.1:5174` (only instance) | HealthBar renders with existing static project label | Backwards-compat | +| 2 | DOM inspection | No Combobox node | Conditional render | + +**Результат**: Zero UI churn. + +### Journey 3: Narrow viewport + +**Цель**: HealthBar stays usable on mobile / narrow screens. + +| Шаг | Действие | Ответ системы | Заметки | +|-----|----------|---------------|---------| +| 1 | Window 360px wide | HealthBar wraps; Combobox shrinks to `size="sm"` | Combobox sizing | +| 2 | Combobox content opens | Dropdown is portaled (overflow ok) | bits-ui Portal | + +**Результат**: No layout break. + +--- + +## Functional Requirements + +| ID | Category | Priority | Requirement | Journey | +|----|----------|----------|-------------|---------| +| FR-001 | Core | Must | When ≥ 2 instances are present in `/api/instances` response, HealthBar renders a Combobox listing them | Journey 1 | +| FR-002 | Core | Must | Selecting a non-current instance triggers `window.location.replace` to its URL | Journey 1 | +| FR-003 | Core | Must | When exactly 1 instance is present, HealthBar renders the existing static label (no Combobox) | Journey 2 | +| FR-004 | Core | Must | Current instance is visually marked in the dropdown (checkmark or accent) | Journey 1 | +| FR-005 | Core | Must | The endpoint `GET /api/instances` is added to the rule-22 read-only allow-list (non-forgeplan endpoint, alongside `/api/update-check`) | Journey 1 | +| FR-006 | Core | Must | Client polls `/api/instances` every 5s using a poller that mirrors `healthPoller`'s shape | Journey 1, 2 | +| FR-007 | Core | Must | HealthBar consumes Combobox via `import { Combobox, ... } from '@/shared/ui'` (no re-skin) | Journey 1 | +| FR-008 | Core | Must | When the registry returns `{ ok: false }`, switcher hides gracefully and a toast (non-blocking) reports the error | Journey 1 | +| FR-009 | UX | Should | Combobox uses `size="sm"` to match HealthBar's compact density | Journey 1, 3 | +| FR-010 | UX | Should | Combobox label format: `{projectName} ({host}:{port})` | Journey 1 | +| FR-011 | UX | Should | Options sort by `port` ascending | Journey 1 | +| FR-012 | DX | Should | New entity slice `template/src/entities/instance/` exposes `instancePoller` + types | Journey 1 | + +--- + +## Non-Functional Requirements + +| ID | Category | Requirement | Metric | Condition | Measurement | +|----|----------|-------------|--------|-----------|-------------| +| NFR-001 | Performance | Instance fetch round-trip | < 100ms p95 | localhost | DevTools Network | +| NFR-002 | Performance | Combobox first-render | < 50ms | from `instances` arrival | Performance.mark | +| NFR-003 | Read-only | Switcher MUST never call mutating endpoints | 0 mutating fetches | static review | grep | +| NFR-004 | Rule 24 | No `:global()` override on Combobox internals from `widgets/health-bar/` | 0 matches | rule-24 snippet | grep | +| NFR-005 | A11y | Keyboard nav works (arrow keys, type-to-filter, Enter, Escape) | 0 axe violations | both themes | axe + manual | +| NFR-006 | Bundle | Bundle delta from poller + entity slice + HealthBar wiring | < 3KB gzipped | post-build | size diff | + +--- + +## Acceptance Criteria + +### AC-1: Switcher visible only with ≥2 instances + +```gherkin +Given the registry returns 1 instance +When the user loads HealthBar +Then no Combobox is in the DOM +And the existing static project label is rendered + +Given the registry returns 2 instances +When the user loads HealthBar +Then a Combobox is rendered with 2 options +And the current `host:port` is pre-selected +``` + +### AC-2: Selecting another instance navigates the browser + +```gherkin +Given a Combobox with 2 instances and the current is 127.0.0.1:5174 +When the user selects 127.0.0.1:5175 +Then `window.location.replace` is called with "http://127.0.0.1:5175" +``` + +### AC-3: Read-only invariant — endpoint never mutates + +```gherkin +Given the new endpoint /api/instances exists +When grep is run on template/src/routes/api/instances/+server.ts +Then no spawn / execFile / forgeplan-mutating calls are present +And no fs.writeFile* calls are present +And only GET handler is exported +``` + +--- + +## Rule 22 amendment (embedded — applied in same PR) + +Append the following block to `.claude/rules/22-readonly-proxy.md` under +the "Allow-list extension" section, immediately after the +`/api/update-check` paragraph: + +```markdown +## Allow-list extension: `/api/instances` (non-forgeplan) + +`/api/instances` is the **second** non-forgeplan endpoint permitted +from `/api/*`. It reads the local instance registry at +`~/.forgeplan-web/instances.json` (defined by SPEC-003) so the UI can +render the multi-instance switcher (PRD-029). + +Constraints (every one of these is enforceable from the diff): + +- Method: `GET` only. +- Reads only `~/.forgeplan-web/instances.json` via the helper + `template/src/shared/server/registry.ts`. Path is locked (rule 24 + invariant). +- No spawn, no host filesystem write, no Forgeplan invocation. +- 5s in-memory cache to absorb client poll spikes. +- Response shape mirrors the standard envelope: + `{ ok, data: { instances }, error? }`. +- Filesystem read failures (file missing, parse error) MUST fall back + to `{ ok: true, data: { instances: [] } }` — empty registry, never + throw. + +Any additional non-forgeplan endpoint requires a new Forgeplan artifact +and a fresh amendment to this rule. See PRD-027 / PRD-029 / RFC-025. +``` + +The runtime backstop (`runForgeplan` subcommand check) is unchanged — +this endpoint never calls forgeplan. + +--- + +## Dependencies + +| Dependency | Type | Status | Owner | +|-----------|------|--------|-------| +| PRD-027 (registry endpoint) | Internal | Drafted | docs-eng-109 | +| PRD-028 (Combobox primitive) | Internal | Drafted | docs-eng-109 | +| RFC-025 (this PRD's architecture) | Internal | Drafted | docs-eng-109 | + +--- + +## Risks & Mitigations + +| ID | Risk | Probability | Impact | Mitigation | Owner | +|----|------|-------------|--------|------------|-------| +| R-1 | `window.location.replace` blocked by browser security policy | Very low | Medium | Localhost only — same-origin per scheme; document the limitation | dev | +| R-2 | Switcher renders before `instances` arrives → empty Combobox flash | Medium | Low | Render only when `instances.length >= 2` (already conditional) | dev | +| R-3 | Stale entry shown for 30-60s after a peer crashed | Medium | Low | Acceptable — sweep-on-next-start cleans (PRD-027); user gets a connection error if they pick stale entry; show toast | dev | +| R-4 | Rule 22 grep snippet not updated; review misses new endpoint | Low | Medium | Same PR adds the amendment block; reviewer follows checklist | dev | +| R-5 | Combobox dropdown clipped by HealthBar overflow | Low | Low | bits-ui Portal escapes overflow — already in ComboboxContent | dev | + +--- + +## Affected Files + +- `template/src/widgets/health-bar/ui/HealthBar.svelte` — wire Combobox +- `template/src/entities/instance/index.ts` (NEW) +- `template/src/entities/instance/lib/instance-poller.svelte.ts` (NEW) +- `template/src/entities/instance/model/types.ts` (NEW) +- `template/src/routes/api/instances/+server.ts` (NEW — created in PRD-027 wave; this PRD consumes) +- `template/src/shared/server/registry.ts` (NEW — created in PRD-027 wave; this PRD consumes) +- `.claude/rules/22-readonly-proxy.md` — amendment block above +- GitHub sub-issue: #115 (109f) + +## Related Artifacts + +| Artifact | Relation | Status | +|----------|----------|--------| +| PRD-027 | Depends on (registry + endpoint) | Draft | +| PRD-028 | Depends on (Combobox primitive) | Draft | +| RFC-025 | Architecture | Draft | +| RFC-024 | Informs (Combobox architecture) | Draft | +| GitHub #115 | Source sub-issue | Open | +| GitHub #109 | Parent issue | Open | + +--- + +> **Next step**: Land alongside RFC-025 + PRD-027 + PRD-028. Consumes /api/instances and Combobox. + + + diff --git a/.forgeplan/rfcs/RFC-020-citty-integration-architecture-bin-subcommand-split.md b/.forgeplan/rfcs/RFC-020-citty-integration-architecture-bin-subcommand-split.md new file mode 100644 index 0000000..5c974a5 --- /dev/null +++ b/.forgeplan/rfcs/RFC-020-citty-integration-architecture-bin-subcommand-split.md @@ -0,0 +1,265 @@ +--- +depth: standard +id: RFC-020 +kind: rfc +links: +- target: PRD-024 + relation: based_on +status: draft +title: citty integration architecture — bin/ subcommand split +--- + +--- +id: RFC-020 +title: "citty integration architecture — bin/ subcommand split" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +prd: PRD-024 +depth: standard +--- + +# RFC-020: citty integration architecture — bin/ subcommand split + +## Summary + +Adopt `citty` (per ADR-003) as the CLI framework for `bin/` and split the +current 367-line monolith into a 5-line entrypoint plus per-subcommand +files under `bin/commands/` and shared helpers under `bin/lib/`. + +## Motivation + +Per PRD-024: the hand-rolled argv parser is brittle, lacks per-subcommand +help, silently drops typos, and offers no prompt hook (which #111 needs +for the scope picker). Continuing to extend it for the six new flags +across PRD-024..029 would push the monolith past 600 LOC and triple the +edge cases. Picking the CLI framework now (and locking it in ADR-003) +unblocks Waves 5–8 of the #109 plan. + +If we do nothing: every new flag adds 3 edits in `bin/forgeplan-web.mjs`, +the help text drifts from reality, and the prompt-driven scope flow in +#111 either ships hand-rolled (≈80 LOC of stdin/stdout dance) or blocks. + +## Goals + +- Replace the argv-Set parser with citty's `defineCommand` while keeping + zero-dep surface (rule 23 amended). +- Split per-subcommand logic into one file each under `bin/commands/`. +- Preserve every observable behavior of every existing flag (PRD-024 SC-1). +- Keep cold start delta < 100ms (PRD-024 NFR-001). +- Provide a prompt hook (`citty` exposes `consola.prompt`) for #111. + +## Non-Goals + +- Migrating the CLI to TypeScript. +- Adopting a richer test framework — smoke stays Node `node:test` only. +- Bundling `bin/` with esbuild (orthogonal to RFC-013 graduation). +- Replacing `bin/banner.mjs` (still a hand-rolled ANSI block). + +## Options Considered + +### Option A: Keep hand-rolled parser + +**Description**: Continue with the current `Set`-based parser; add new +flags by extending `flags.has(...)` calls. Manually wire `--help ` +and unknown-flag rejection. + +**Pros**: +- Zero new dependencies. +- Already known to work. + +**Cons**: +- Adds maintenance debt with every new flag (PRD-024..029 add ≥6 flags). +- No structured prompt support — #111 must hand-roll stdin reader. +- `--help ` requires bespoke routing. +- Typo handling stays silent; can't reject unknown flags without + per-subcommand allow-lists. + +### Option B: citty (CHOSEN per ADR-003) + +**Description**: Adopt `unjs/citty` — zero-dep ESM-only CLI framework. +Each subcommand is a `defineCommand({ meta, args, run })` exported from +its own file. Root command in `bin/cli.mjs` lists subcommands; entry +shrinks to `import { runMain } from "citty"; import { main } from +"./cli.mjs"; runMain(main)`. + +**Pros**: +- Zero transitive deps, pure ESM, ≈6KB. +- Built-in `--help`, type-validated args, prompt support via `consola`. +- Already used in the unjs ecosystem (consola, unbuild, nuxi) — battle- + tested at scale. +- Subcommand aliasing (`alias: ["upgrade"]`) one-liner. + +**Cons**: +- New runtime dep — invalidates rule 23's "zero-dep" claim. Mitigated by + ADR-003 explicit allowlist amendment. +- Auto-help wording differs slightly from current text — minor user- + visible churn (smoke test asserts behavior, not wording). + +### Option C: commander + +**Description**: TJ Holowaychuk's classic CLI framework. + +**Pros**: +- Mature, ubiquitous, deep stack-overflow corpus. + +**Cons**: +- ≈30KB and pulls a few transitive deps (`@tootallnate/once`, etc. via + newer versions). Bigger tarball delta than citty. +- CommonJS-first; ESM is bolted on. Aligns poorly with our pure-ESM + `.mjs` files. +- API surface is larger than what we need; encourages monolithic configs. + +### Option D: cac + +**Description**: Cuk Wong's small CLI framework. + +**Pros**: +- Small (~7KB), ESM-friendly. +- Familiar `program.command(...)` API. + +**Cons**: +- Single-maintainer; less active than citty (last release older as of + 2026-05). +- Prompt support is third-party (not built-in); we'd need to add + another dep for #111. +- Type validation is weaker than citty. + +## Trade-off Analysis + +| Критерий | A: hand-rolled | B: citty (chosen) | C: commander | D: cac | +|----------|----------------|-------------------|--------------|--------| +| Complexity (initial) | Lowest (already there) | Low | Medium | Low | +| Complexity (per future flag) | High | Low | Low | Low | +| Cold-start cost | Baseline | +~5ms | +~30ms | +~5ms | +| Tarball delta | 0 | +~6KB | +~30KB | +~7KB | +| Migration risk | None (status quo) | Low (clean cut) | Medium (CJS interop) | Low | +| Developer experience | Poor | Good | Good | Good | +| Prompt support (for #111) | DIY | Built-in (`consola.prompt`) | Third-party | Third-party | +| Operational burden | High (drifts) | Low | Low | Medium (less mature) | +| Zero-dep invariant (rule 23) | Preserved | Amended (ADR-003) | Amended | Amended | + +## Proposed Direction + +**Option B — citty.** Locked by ADR-003 (which amends rule 23 to allow +exactly `citty` in `bin/`). Architecture: + +``` +bin/ +├── forgeplan-web.mjs # 5–10 lines: import { runMain } from "citty" +│ # import { main } from "./cli.mjs" +│ # runMain(main) +├── cli.mjs # defineCommand({ meta, subCommands: { init, update, start } }) +├── banner.mjs # unchanged +├── commands/ +│ ├── init.mjs # defineCommand — owns init args + run +│ ├── update.mjs # defineCommand — owns update args + run +│ └── start.mjs # defineCommand — owns start args + run +└── lib/ + ├── config.mjs # readConfig, readPkgVersion, readWorkspaceRoot + ├── gitignore.mjs # ensureGitignore + └── forgeplan-binary.mjs # ensureForgeplanBinary, ensureForgeplanWorkspace +``` + +Each `bin/commands/.mjs` exports a default `defineCommand` with: +- `meta: { name, description }` +- `args: { ... }` — typed flag definitions (string / boolean) +- `run({ args }) { ... }` — same logic as today, called with parsed args + +Aliases: +- `update`: `meta.alias = ["upgrade"]` +- `start`: `meta.alias = ["serve", "run"]` + +`run` functions stay synchronous wherever the current code is sync; +citty supports both. Help is auto-generated; we delete the bespoke +`help()` function. + +## Risks & Open Questions + +- **R-1: Citty's exit-code convention.** Citty exits 1 by default on + unknown flag; we must verify it matches the hook expectations + (`forge-safety-hook.sh`). Smoke test will exercise this. +- **R-2: Windows shell wrapping.** When `forgeplan-web.mjs` is shipped + via npm, npm wraps it in `forgeplan-web.cmd` on Windows. Citty's + `runMain` works with `process.argv.slice(2)` regardless; verify on + CI Windows job. +- **R-3: ESM-only.** Citty is `"type": "module"` — fine since our entry + is `.mjs`. No interop work. +- **R-4: Prompt SSR-safety.** `consola.prompt` reads from `process.stdin`. + Behavior in non-TTY contexts (CI) must fall back to default (used by + PRD-025's `--scope` flag — when prompt unavailable, fail with clear + message instructing `--scope` flag). +- **OQ-1**: Should we expose citty's `defineCommand` to plugin authors + later? Out of scope for now; punt to a future RFC if needed. +- **OQ-2**: Should `bin/lib/` be a separate "package" (with `package.json`) + for type clarity? No — keeping it as bare `.mjs` files preserves the + zero-resolution invariant (rule 23 verification snippet still grep-able). + +## Implementation Phases + +### Phase 1: Scaffold + helpers extraction (no behavior change) + +- [ ] **1.1** Add `citty` to root `package.json#dependencies`. +- [ ] **1.2** Create `bin/lib/config.mjs`, `bin/lib/gitignore.mjs`, + `bin/lib/forgeplan-binary.mjs` by extracting helpers from + `bin/forgeplan-web.mjs` verbatim. No logic change. +- [ ] **1.3** Update rule 23 verification snippet to allow `citty` and + `./lib/*.mjs` relative imports. + +### Phase 2: Wire citty (init only) + +- [ ] **2.1** Create `bin/commands/init.mjs` — port `init()` to + `defineCommand`. Map current flags 1:1. +- [ ] **2.2** Create `bin/cli.mjs` — root command, registers `init` only. +- [ ] **2.3** Replace `bin/forgeplan-web.mjs` body with `runMain` entry. + Keep old monolith logic for `update`/`start` via fall-through to + legacy switch. +- [ ] **2.4** Smoke: assert `init -y --force --no-gitignore` still + produces identical filesystem state. + +### Phase 3: Port update + start, retire legacy switch + +- [ ] **3.1** Create `bin/commands/update.mjs` (with `alias: ["upgrade"]`). +- [ ] **3.2** Create `bin/commands/start.mjs` (with `alias: ["serve", + "run"]`). +- [ ] **3.3** Delete the legacy `switch (cmd)` block from + `bin/forgeplan-web.mjs`; entry shrinks to 5–10 lines. +- [ ] **3.4** Delete `help()` function — citty auto-generates. + +### Phase 4: Smoke + benchmark + +- [ ] **4.1** Add `scripts/smoke.mjs` flag-parity assertions for all 6 + flags + 3 aliases. +- [ ] **4.2** Run `hyperfine` cold-start benchmark; assert delta < 100ms + vs baseline. If exceeded, profile and optimize import order. +- [ ] **4.3** `npm pack --dry-run` size check; assert delta < 10KB. + +## Affected Files + +- `bin/forgeplan-web.mjs` (shrunk) +- `bin/cli.mjs` (NEW) +- `bin/commands/init.mjs` (NEW) +- `bin/commands/update.mjs` (NEW) +- `bin/commands/start.mjs` (NEW) +- `bin/lib/config.mjs` (NEW) +- `bin/lib/gitignore.mjs` (NEW) +- `bin/lib/forgeplan-binary.mjs` (NEW) +- `package.json` — `dependencies.citty` +- `.claude/rules/23-bin-zero-deps.md` — amendment from ADR-003 +- `scripts/smoke.mjs` — assertions + +## Related Artifacts + +| Artifact | Type | Relation | +|----------|------|----------| +| PRD-024 | PRD | based_on | +| ADR-003 | ADR | decided_by | +| PRD-025 | PRD | informs (consumes prompt support) | +| PRD-026 | PRD | informs (consumes prompt support) | +| GitHub #110 | Issue | implements | + +--- + +> **Next step**: Land alongside PRD-024 + ADR-003. Phase order is strict; do not skip Phase 1's helper extraction. + diff --git a/.forgeplan/rfcs/RFC-021-scope-resolver-and-user-scope-path-conventions-for-init.md b/.forgeplan/rfcs/RFC-021-scope-resolver-and-user-scope-path-conventions-for-init.md new file mode 100644 index 0000000..ace04bb --- /dev/null +++ b/.forgeplan/rfcs/RFC-021-scope-resolver-and-user-scope-path-conventions-for-init.md @@ -0,0 +1,251 @@ +--- +depth: standard +id: RFC-021 +kind: rfc +links: +- target: PRD-025 + relation: based_on +status: draft +title: Scope resolver and user-scope path conventions for init +--- + +--- +id: RFC-021 +title: "Scope resolver and user-scope path conventions for init" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +prd: PRD-025 +depth: standard +--- + +# RFC-021: Scope resolver and user-scope path conventions for init + +## Summary + +Introduce `bin/lib/scope.mjs` — pure resolver functions that map scope +intent (`user` | `project`) to absolute filesystem paths, plus a +`promptScope()` helper that wraps citty's prompt API. Lock the user-scope +path to `~/.forgeplan-web/` (no XDG, no per-OS variants in MVP) per +ADR-004. + +## Motivation + +PRD-025 introduces `--scope user|project` for `init`. The next step +(PRD-026 / RFC-022) builds a start-resolution chain that probes both +scopes. A shared resolver module avoids two divergent path computations +and gives PRD-027's registry helper a single source of truth for "where +does the user-scope live?". + +If we don't extract a helper: scope path is hard-coded inline in +`bin/commands/init.mjs` (PRD-025) and re-derived in `bin/commands/start.mjs` +(PRD-026) and `bin/lib/registry.mjs` (PRD-027). Three drift surfaces. + +## Goals + +- Single home for scope-path resolution: `bin/lib/scope.mjs`. +- Lock user-scope path to `~/.forgeplan-web/` (ADR-004 invariant). +- Provide `promptScope()` that returns `'user' | 'project'` from arrow- + key TTY prompt, with non-TTY fall-through error. +- Persist resolved scope into `forgeplan-web.json` so downstream + (`update`, `start`) can read it back. + +## Non-Goals + +- XDG_CONFIG_HOME compliance. +- Per-OS conventional paths (`%APPDATA%`, `~/Library/Application Support/`). +- Custom scope paths (e.g. `--scope /tmp/sandbox`). +- Migration tooling. + +## Options Considered + +### Option A: `~/.forgeplan-web/` (CHOSEN per ADR-004) + +**Description**: User-scope root = `path.join(os.homedir(), '.forgeplan-web')`. +Cross-platform via Node's `os.homedir()`. Cross-tool consistency: every +language's stdlib has the same primitive. + +**Pros**: +- Trivial implementation; one helper line. +- Works identically on macOS, Linux, Windows (tested in PRD-025 NFR-004). +- Visible to users (dotfile in `~/`). +- Co-locates with `instances.json` (ADR-004) — both live under the same + root. + +**Cons**: +- Not technically XDG-compliant on Linux (XDG_CONFIG_HOME would put it + under `~/.config/forgeplan-web/`). +- Pollutes the home directory root with one more dotfile. + +### Option B: XDG_CONFIG_HOME + +**Description**: Honor `XDG_CONFIG_HOME` env (default `~/.config/`) on +Linux/macOS; fall back to `~/.forgeplan-web/` on Windows or when env +unset. + +**Pros**: +- Aligns with Linux desktop conventions. +- Polite citizen on systems with `~/.config/` already in use. + +**Cons**: +- Per-OS branching = more code paths to test. +- macOS users typically don't set `XDG_CONFIG_HOME`; behavior would be + identical to Option A for ~80% of users while adding a Linux-specific + fork. +- ADR-004 explicitly punts XDG to a future major version. + +### Option C: Per-OS conventional paths + +**Description**: macOS: `~/Library/Application Support/forgeplan-web/`; +Linux: `~/.config/forgeplan-web/`; Windows: `%APPDATA%/forgeplan-web/`. + +**Pros**: +- Most "native" feel per OS. + +**Cons**: +- Three distinct codepaths. +- Migration story is harder if a user moves between OSes. +- Forgeplan-web is a developer tool, not a desktop app; native paths + are overkill. + +## Trade-off Analysis + +| Критерий | A: ~/.forgeplan-web/ (chosen) | B: XDG | C: per-OS | +|----------|-------------------------------|--------|-----------| +| Implementation complexity | Lowest | Medium | High | +| Cross-platform parity | High (single path) | Medium (Linux fork) | Low (3 forks) | +| Discoverability | Visible dotfile | Hidden in `.config/` | Buried in OS dirs | +| Migration risk (future XDG) | Easy (read-old, write-new) | n/a | Hard | +| Co-location with `instances.json` | Same root | Same root | Same root | +| Operational burden | Lowest | Medium | High | + +## Proposed Direction + +**Option A — `~/.forgeplan-web/`.** Locked by ADR-004. Module shape: + +```js +// bin/lib/scope.mjs +import os from 'node:os'; +import path from 'node:path'; + +export const USER_SCOPE_DIRNAME = '.forgeplan-web'; + +export function resolveUserScopeRoot() { + return path.join(os.homedir(), USER_SCOPE_DIRNAME); +} + +export function resolveProjectScopeRoot(cwd) { + return path.join(cwd, USER_SCOPE_DIRNAME); +} + +export function resolveScopeRoot(scope, cwd) { + if (scope === 'user') return resolveUserScopeRoot(); + if (scope === 'project') return resolveProjectScopeRoot(cwd); + throw new Error(`unknown scope: ${scope}`); +} + +// Returns 'user' | 'project'. Throws on non-TTY. +export async function promptScope({ defaultScope = 'user' } = {}) { + if (!process.stdin.isTTY) { + throw new Error('no TTY; pass --scope user|project explicitly'); + } + const { prompt } = await import('citty'); + return prompt('Where to install?', { + type: 'select', + options: [ + { label: `user (${resolveUserScopeRoot()})`, value: 'user' }, + { label: `project (${resolveProjectScopeRoot(process.cwd())})`, value: 'project' }, + ], + initial: defaultScope, + }); +} +``` + +`forgeplan-web.json` schema bump: + +```json +{ + "workspaceRoot": "/Users/.../forgeplan-web", + "createdAt": "2026-05-08T...", + "updatedAt": "2026-05-08T...", + "version": "0.1.14", + "experimental": false, + "scope": "user" // NEW — "user" | "project" +} +``` + +Reader code (in `bin/lib/config.mjs`) treats absent `scope` as +`"project"` for back-compat with already-written configs. + +## Risks & Open Questions + +- **R-1: `os.homedir()` on Windows when running under a non-standard + shell** (Git Bash, MSYS2). Should resolve to `C:\Users\` on all + three; Node has historically been reliable here. Smoke test asserts. +- **R-2: Symlinked home dir** (some corporate setups symlink `~`). + `os.homedir()` returns the symlink target string; we don't follow, + we just use it. Either way the path is stable per user. +- **R-3: Long-path Windows users** (`MAX_PATH 260` legacy). Path is + ~30 chars + user name + filenames; well under 260. +- **OQ-1**: Should we accept `~/.forgeplanweb/` (no dash) as an alias? + No — single canonical name avoids confusion. +- **OQ-2**: Should `promptScope()` live in `scope.mjs` or its own file? + Keep in `scope.mjs` — it's a thin wrapper, splitting adds churn. + +## Implementation Phases + +### Phase 1: Pure resolver helpers (no behavior change) + +- [ ] **1.1** Create `bin/lib/scope.mjs` with `resolveUserScopeRoot`, + `resolveProjectScopeRoot`, `resolveScopeRoot`. +- [ ] **1.2** Unit-cover via `node:test` in + `scripts/test/scope.test.mjs`: macOS path, Linux path, Windows path + (mocked via `os.homedir` stub). + +### Phase 2: Wire into `init` + +- [ ] **2.1** `bin/commands/init.mjs` consumes `resolveScopeRoot` + instead of inline `path.join(cwd, '.forgeplan-web')`. +- [ ] **2.2** Add `--scope` arg via citty. +- [ ] **2.3** `forgeplan-web.json` writer adds `scope` field. + +### Phase 3: Prompt fallback + +- [ ] **3.1** `promptScope()` exported from `scope.mjs`. +- [ ] **3.2** `init.mjs` calls `promptScope()` when scope unset, TTY + open, and `-y` not passed. +- [ ] **3.3** Non-TTY fall-through: emit FR-009 error. + +### Phase 4: Smoke + matrix + +- [ ] **4.1** Smoke: assert `init --scope user` writes to + `~/.forgeplan-web/`. +- [ ] **4.2** Smoke: assert `init -y` (no `--scope`) writes to + `./.forgeplan-web/`. +- [ ] **4.3** CI Windows matrix: assert path resolution matches + expected `os.homedir()` value. + +## Affected Files + +- `bin/lib/scope.mjs` (NEW) +- `bin/lib/config.mjs` — `scope` field reader/writer +- `bin/commands/init.mjs` — consumes resolver +- `scripts/test/scope.test.mjs` (NEW) +- `scripts/smoke.mjs` — scope assertions + +## Related Artifacts + +| Artifact | Type | Relation | +|----------|------|----------| +| PRD-025 | PRD | based_on | +| ADR-004 | ADR | decided_by (locks user-scope path) | +| PRD-024 | PRD | informs (citty + bin split prerequisite) | +| RFC-022 | RFC | informs (start-resolution consumes resolver) | +| RFC-023 | RFC | informs (registry consumes resolver) | +| GitHub #111 | Issue | implements | + +--- + +> **Next step**: Land alongside PRD-025. PRD-026 (RFC-022) consumes `resolveScopeRoot`. + diff --git a/.forgeplan/rfcs/RFC-022-start-scaffold-resolution-algorithm-and-error-ux.md b/.forgeplan/rfcs/RFC-022-start-scaffold-resolution-algorithm-and-error-ux.md new file mode 100644 index 0000000..4e3e9ed --- /dev/null +++ b/.forgeplan/rfcs/RFC-022-start-scaffold-resolution-algorithm-and-error-ux.md @@ -0,0 +1,273 @@ +--- +depth: standard +id: RFC-022 +kind: rfc +links: +- target: PRD-026 + relation: based_on +status: draft +title: start scaffold-resolution algorithm and error UX +--- + +--- +id: RFC-022 +title: "start scaffold-resolution algorithm and error UX" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +prd: PRD-026 +depth: standard +--- + +# RFC-022: start scaffold-resolution algorithm and error UX + +## Summary + +Specify the algorithm `bin/commands/start.mjs` uses to find the right +`.forgeplan-web/` scaffold given (cwd, optional `--scope`, optional +`-y`, TTY presence). Define the empty-state UX: prompt-to-init on TTY, +clear error on non-TTY. + +## Motivation + +PRD-026 needs a deterministic, testable algorithm for resolution. A +spec-as-RFC is the cheapest way to lock the order, the override +semantics, and the empty-state behavior before code. Without explicit +spec the implementation will drift from PRD-026's invariants and the +backwards-compat guarantee for project-scope users will erode under +future patches. + +## Goals + +- One pseudocode procedure with named branches for testability. +- Project scope probed BEFORE user scope (zero-config preservation). +- Empty-state UX uniform with `init`'s prompt (same citty primitives). +- Symlink + JSON-parse guards as a safety net. + +## Non-Goals + +- Walk-up parent search. +- Mid-session scope switching. +- Forwarding additional flags to spawned `node index.js` (already done + via env in current code; unchanged). + +## Options Considered + +### Option A: Project → User → Prompt-init (CHOSEN) + +**Description**: Probe project-scope first. If absent, probe user-scope. +If both absent, prompt to init (TTY) or error (non-TTY). + +``` +resolveScaffold({ cwd, explicitScope, yesFlag, isTTY }): + if explicitScope === 'project': + return projectAt(cwd) or fail("--scope project: no scaffold at ") + if explicitScope === 'user': + return userAt() or fail("--scope user: no scaffold at ~/.forgeplan-web/") + // implicit: try chain + let p = projectAt(cwd) + if p: return p + let u = userAt() + if u: return u + // empty state + if isTTY and !yesFlag: + return promptInitInline() + fail("no scaffold; run `npx @forgeplan/web init [--scope user|project]`") +``` + +**Pros**: +- Preserves project-scope user behavior (project wins). +- Discoverable: when project is missing, user-scope is tried before + failing. +- Symmetrical with `init` defaults. + +**Cons**: +- Two probes per `start` invocation (negligible). +- Possible surprise if user has both scopes installed (project wins + unexpectedly); mitigated by stdout log. + +### Option B: User → Project → Prompt-init + +**Description**: Reverse order. User-scope first. + +**Pros**: +- Aligns with the new "user-scope is default" direction. + +**Cons**: +- Breaks project-scope users who run `start` from a project — would + pick `~/.forgeplan-web/` over the project's. Unacceptable per + PRD-026 NFR-002. + +### Option C: Walk-up parent search + +**Description**: If `/.forgeplan-web/` absent, walk up to parent +dirs looking for one (like git does for `.git/`). + +**Pros**: +- Handles "ran from a subdir of the project" case. + +**Cons**: +- Out of scope per #109. +- Requires bounding (where to stop?). +- Risk of picking up an unrelated scaffold from a parent project. + +### Option D: Always prompt for scope + +**Description**: Don't probe; always ask user to pick scope at start. + +**Pros**: +- Explicit. + +**Cons**: +- Massive UX regression (every start needs a click). +- Breaks scripts. + +## Trade-off Analysis + +| Критерий | A: project→user (chosen) | B: user→project | C: walk-up | D: always-prompt | +|----------|--------------------------|------------------|-----------|-----------------| +| Backwards compat | High | Broken | High | Broken | +| Discoverability | Good (logs scope) | Confusing | Good | Bad | +| Implementation cost | Low | Low | Medium | Low | +| CI compatibility | Good | Good | Good | Broken | +| Surprise factor | Low | High | Medium | High | + +## Proposed Direction + +**Option A** as specified above. Implementation in +`bin/commands/start.mjs`: + +```js +import { defineCommand } from 'citty'; +import { existsSync, lstatSync } from 'node:fs'; +import { join } from 'node:path'; +import { resolveUserScopeRoot, resolveProjectScopeRoot } from '../lib/scope.mjs'; +import { readConfig } from '../lib/config.mjs'; + +const SCAFFOLD_ENTRY = 'index.js'; +const ENV_OVERRIDE = 'FORGEPLAN_WEB_SCAFFOLD'; + +function probe(root) { + if (!existsSync(root)) return null; + if (lstatSync(root).isSymbolicLink()) return null; // safety + const entry = join(root, SCAFFOLD_ENTRY); + if (!existsSync(entry)) return null; + return root; +} + +function resolveScaffold({ cwd, explicitScope, yesFlag, isTTY }) { + // Highest priority: explicit env override (escape hatch) + if (process.env[ENV_OVERRIDE]) { + return { scope: 'env', root: process.env[ENV_OVERRIDE] }; + } + if (explicitScope === 'project') { + const r = probe(resolveProjectScopeRoot(cwd)); + if (!r) throw new Error(`--scope project: no scaffold at ${resolveProjectScopeRoot(cwd)}`); + return { scope: 'project', root: r }; + } + if (explicitScope === 'user') { + const r = probe(resolveUserScopeRoot()); + if (!r) throw new Error(`--scope user: no scaffold at ${resolveUserScopeRoot()}`); + return { scope: 'user', root: r }; + } + // implicit chain: project → user → prompt + let r = probe(resolveProjectScopeRoot(cwd)); + if (r) return { scope: 'project', root: r }; + r = probe(resolveUserScopeRoot()); + if (r) return { scope: 'user', root: r }; + return null; // empty state +} +``` + +Empty-state UX (when `resolveScaffold` returns null): + +```js +async function handleEmpty({ isTTY, yesFlag }) { + if (!isTTY || yesFlag) { + throw new Error( + 'no scaffold found in project (./.forgeplan-web/) or user (~/.forgeplan-web/) scope.\n' + + ' run `npx @forgeplan/web init [--scope user|project]` first.' + ); + } + const { prompt } = await import('citty'); + const yes = await prompt('No scaffold found. Install now?', { + type: 'confirm', + initial: true, + }); + if (!yes) process.exit(1); + // re-enter init flow inline (call into bin/commands/init.mjs's run) + ... +} +``` + +`forgeplan-web.json` is read AFTER resolution (we know the root). Its +`scope` field is informational; we trust the path we resolved. + +## Risks & Open Questions + +- **R-1: Symlink probe.** `existsSync` follows symlinks; `lstatSync` + doesn't. We refuse symlinks for the scaffold dir because RFC + precedent (rule 21, update's CWE-59 guard). +- **R-2: Race condition between probe and spawn.** Negligible — user + process. If scaffold is deleted between probe and spawn, Node will + surface a clear error. +- **R-3: ENV override visibility.** `FORGEPLAN_WEB_SCAFFOLD` could + surprise users. Keep it documented in `--help start` output. +- **R-4: Inline init from start.** Tests must cover the case where + inline init prompts for scope mid-session; ensure no double-prompt. +- **OQ-1**: Should `start` respect the `forgeplan-web.json#scope` field + to pick a non-default order? No — the resolved root *is* the truth; + scope-field is just metadata. + +## Implementation Phases + +### Phase 1: Pure resolver + +- [ ] **1.1** Implement `resolveScaffold()` in + `bin/lib/start-resolver.mjs` (or fold into `bin/lib/scope.mjs`). +- [ ] **1.2** Unit test all branches: explicit project hit, explicit + project miss, explicit user hit, explicit user miss, implicit + project hit, implicit user hit, implicit none. + +### Phase 2: Wire into start + +- [ ] **2.1** `bin/commands/start.mjs` consumes resolver; spawns + `node /index.js`. +- [ ] **2.2** Add `--scope` arg via citty. +- [ ] **2.3** Print "→ scope: ()" line. + +### Phase 3: Empty-state UX + +- [ ] **3.1** Non-TTY / `-y` path: throw clear error with + init-flag hint. +- [ ] **3.2** TTY path: prompt-to-init confirm + scope select; reuse + init's flow. + +### Phase 4: Smoke matrix + +- [ ] **4.1** Smoke: project-only, user-only, both, neither, env- + override. +- [ ] **4.2** CI Windows: identical assertions. + +## Affected Files + +- `bin/commands/start.mjs` +- `bin/lib/scope.mjs` (or `bin/lib/start-resolver.mjs`) +- `scripts/test/start-resolver.test.mjs` (NEW) +- `scripts/smoke.mjs` + +## Related Artifacts + +| Artifact | Type | Relation | +|----------|------|----------| +| PRD-026 | PRD | based_on | +| RFC-021 | RFC | informs (consumes resolver) | +| PRD-025 | PRD | informs (scope flag) | +| PRD-027 | PRD | informs (registry stale-sweep on start) | +| GitHub #112 | Issue | implements | + +--- + +> **Next step**: Land alongside PRD-026. PRD-027's registry hook fires inside `start` after resolution. + diff --git a/.forgeplan/rfcs/RFC-023-port-allocator-pid-liveness-probe-atomic-registry-writes.md b/.forgeplan/rfcs/RFC-023-port-allocator-pid-liveness-probe-atomic-registry-writes.md new file mode 100644 index 0000000..8e61f25 --- /dev/null +++ b/.forgeplan/rfcs/RFC-023-port-allocator-pid-liveness-probe-atomic-registry-writes.md @@ -0,0 +1,408 @@ +--- +depth: standard +id: RFC-023 +kind: rfc +links: +- target: PRD-027 + relation: based_on +status: draft +title: Port allocator, pid-liveness probe, atomic registry writes +--- + +--- +id: RFC-023 +title: "Port allocator, pid-liveness probe, atomic registry writes" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +prd: PRD-027 +depth: standard +--- + +# RFC-023: Port allocator, pid-liveness probe, atomic registry writes + +## Summary + +Specify the three load-bearing algorithms for PRD-027: (1) port +allocator that walks `[PORT, PORT+100]` until first free; (2) PID +liveness probe via `process.kill(pid, 0)` plus heartbeat freshness +window (>60s = dead); (3) atomic registry writes via tmp+rename in the +same directory. Plus the heartbeat lifecycle and signal-handler +deregister flow. + +## Motivation + +PRD-027 lists multiple load-bearing primitives. Each has alternative +implementations with different trade-offs (random port vs incremental; +PID-only vs PID+heartbeat; lockfile vs tmp+rename). Locking the choice +in an RFC prevents drift during implementation and gives reviewers a +stable target. + +## Goals + +- Port allocator: deterministic, bounded, fast. +- Liveness: portable across POSIX and Windows. +- Writes: never produce invalid JSON under concurrency. +- Heartbeat: cheap, periodic, side-effect-bounded. + +## Non-Goals + +- Cross-host coordination. +- Auth / capability tokens. +- TLS / HTTPS port handling. + +## Options Considered + +### Port allocator + +#### Option A: Increment from PORT (CHOSEN) + +**Description**: Try `PORT`, then `PORT+1`, …, `PORT+100`. Use +`net.createServer().listen({port, host}, ...)` and listen for +`error.code === 'EADDRINUSE'` to advance. + +**Pros**: +- Predictable port numbers (humans like 5174, 5175, 5176). +- Easy to debug ("the third instance is on 5176"). + +**Cons**: +- Sequential probes can take up to 100× the bind latency in the worst + case (~100ms total). + +#### Option B: Random in range + +**Description**: Pick random in `[PORT, PORT+1000)`. + +**Pros**: +- Lower collision probability under bursty starts. + +**Cons**: +- Unpredictable port numbers — bad UX. +- Still needs collision retry. + +#### Option C: External allocator service + +**Description**: Coordinator process hands out ports. + +**Pros**: +- No collisions. + +**Cons**: +- Massive overkill; introduces a long-running daemon. + +### PID liveness + +#### Option A: `process.kill(pid, 0)` + heartbeat freshness (CHOSEN) + +**Description**: Send signal 0 (no-op probe) — throws ESRCH if dead, +EPERM if alive but unsignal-able. Combined with `now - heartbeatAt > 60s` +to detect frozen processes that still own a PID. + +**Pros**: +- POSIX-standard; Node implements it on Windows too. +- Catches PID recycling via heartbeat. +- No third-party dep. + +**Cons**: +- EPERM on Windows for processes from other users — treat as alive + (conservative). + +#### Option B: PID-only probe + +**Description**: Just `process.kill(pid, 0)` without heartbeat freshness. + +**Pros**: +- Simpler. + +**Cons**: +- Misses PID-recycled rows. +- Misses frozen-but-alive processes. + +#### Option C: Health-ping on the registered HTTP port + +**Description**: Try to fetch `/api/health` on `host:port` from each row. + +**Pros**: +- Authoritative. + +**Cons**: +- Requires HTTP timeout; sweep becomes slow (50ms × 100 = 5s). +- HTTP could fail for non-liveness reasons (firewall, GC pause). + +### Atomic writes + +#### Option A: tmp+rename in same dir (CHOSEN) + +**Description**: Write to `instances.json.tmp.` then +`fs.renameSync` to `instances.json`. Same directory ensures atomic +rename even on Windows. + +**Pros**: +- POSIX `rename(2)` is atomic at the syscall level. +- Same-dir tmp avoids cross-fs ENOTSUP on Windows. + +**Cons**: +- Two writes (one to tmp, one rename). + +#### Option B: Lockfile + +**Description**: `proper-lockfile` package wraps RW with a separate +.lock file. + +**Pros**: +- Provides true mutex semantics (read-modify-write). + +**Cons**: +- New runtime dep (rule 23 — server side, but still an extra dep). +- Stale lock recovery is its own problem. + +#### Option C: Append-only log with periodic compaction + +**Description**: Each instance appends one JSON line; reader fold- +reduces. + +**Pros**: +- No write conflicts ever. + +**Cons**: +- Compaction is its own consistency problem. +- File grows unbounded between compactions. + +## Trade-off Analysis + +### Port allocator + +| Критерий | A: increment (chosen) | B: random | C: service | +|----------|-----------------------|-----------|------------| +| Predictability | High | Low | High | +| Probe latency (worst) | ~100ms | ~5ms | ~5ms | +| Implementation cost | Low | Low | Very high | +| Operational burden | None | None | High (daemon) | + +### PID liveness + +| Критерий | A: kill(pid,0)+heartbeat (chosen) | B: PID-only | C: HTTP ping | +|----------|----------------------------------|-------------|--------------| +| Accuracy | High | Medium | High | +| Sweep latency (100 entries) | ~10ms | ~5ms | ~5000ms | +| Cross-platform | High | High | Medium | +| Implementation cost | Low | Lowest | Medium | + +### Atomic writes + +| Критерий | A: tmp+rename (chosen) | B: lockfile | C: append-log | +|----------|------------------------|-------------|---------------| +| Implementation cost | Low | Medium (new dep) | Medium | +| Concurrency safety | High (atomic rename) | High (mutex) | Highest | +| Write latency | < 10ms | ~20ms | < 5ms | +| Read latency | < 5ms | < 5ms | Medium (fold) | +| File-size growth | Bounded | Bounded | Unbounded | + +## Proposed Direction + +**Port allocator**: Option A (increment). **Liveness**: Option A +(kill+heartbeat). **Writes**: Option A (tmp+rename). + +```js +// bin/lib/registry.mjs +import { readFileSync, writeFileSync, renameSync, mkdirSync, existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { resolveUserScopeRoot } from './scope.mjs'; + +const SCHEMA_VERSION = 1; +const HEARTBEAT_STALE_MS = 60_000; + +function registryPath() { + return join(resolveUserScopeRoot(), 'instances.json'); +} + +export function readRegistry() { + const p = registryPath(); + if (!existsSync(p)) return { version: SCHEMA_VERSION, instances: [] }; + try { + const raw = JSON.parse(readFileSync(p, 'utf8')); + if (raw?.version !== SCHEMA_VERSION) { + // TODO(spec-003-v2-migration): migrate older versions when schema bumps. + return { version: SCHEMA_VERSION, instances: [] }; + } + return raw; + } catch { + // Corrupt file; treat as empty. Next write replaces. + return { version: SCHEMA_VERSION, instances: [] }; + } +} + +export function writeRegistry(reg) { + const p = registryPath(); + mkdirSync(resolveUserScopeRoot(), { recursive: true }); + const tmp = `${p}.tmp.${process.pid}.${Date.now()}`; + writeFileSync(tmp, JSON.stringify(reg, null, 2) + '\n'); + renameSync(tmp, p); +} + +export function isAlive(pid, heartbeatAt) { + if (typeof pid !== 'number' || pid <= 0) return false; + const stale = Date.now() - new Date(heartbeatAt).getTime() > HEARTBEAT_STALE_MS; + if (stale) return false; + try { + process.kill(pid, 0); + return true; + } catch (e) { + if (e.code === 'EPERM') return true; // exists, can't signal + return false; // ESRCH or other + } +} + +export function sweepStale(reg) { + return { + version: reg.version, + instances: reg.instances.filter((i) => isAlive(i.pid, i.heartbeatAt)), + }; +} + +export function appendInstance(instance) { + const reg = sweepStale(readRegistry()); + reg.instances = [...reg.instances.filter((i) => i.id !== instance.id), instance]; + writeRegistry(reg); +} + +export function removeInstance(id) { + const reg = readRegistry(); + reg.instances = reg.instances.filter((i) => i.id !== id); + writeRegistry(reg); +} +``` + +Port allocator: + +```js +// bin/lib/port-allocator.mjs +import net from 'node:net'; + +export async function findFreePort({ host, basePort, maxOffset = 100 }) { + for (let offset = 0; offset <= maxOffset; offset++) { + const port = basePort + offset; + if (await tryBind(host, port)) return port; + } + throw new Error(`no free port in [${basePort}, ${basePort + maxOffset}]`); +} + +function tryBind(host, port) { + return new Promise((resolve) => { + const srv = net.createServer(); + srv.once('error', () => resolve(false)); + srv.once('listening', () => srv.close(() => resolve(true))); + srv.listen({ port, host }); + }); +} +``` + +Heartbeat lifecycle (server-side): + +```ts +// template/src/shared/server/heartbeat.ts +import { writeRegistry, readRegistry } from './registry'; +const HEARTBEAT_MS = 30_000; + +export function startHeartbeat(instanceId: string) { + const tick = () => { + const reg = readRegistry(); + const idx = reg.instances.findIndex((i) => i.id === instanceId); + if (idx >= 0) { + reg.instances[idx].heartbeatAt = new Date().toISOString(); + writeRegistry(reg); + } + }; + const handle = setInterval(tick, HEARTBEAT_MS); + handle.unref?.(); // don't block exit + return () => clearInterval(handle); +} +``` + +Deregister on signals (in `bin/commands/start.mjs`): + +```js +const cleanup = () => removeInstance(instanceId); +process.on('SIGINT', () => { cleanup(); process.exit(0); }); +process.on('SIGTERM', () => { cleanup(); process.exit(0); }); +process.on('beforeExit', cleanup); +``` + +## Risks & Open Questions + +- **R-1: Race in append-time sweep.** Two starts may both read+sweep+ + write concurrently; the later write overwrites the earlier. Same-PID + rows are idempotent (sweep already filters dead). For different-PID + concurrent starts, the rare loss-of-row is recovered on next start. + Acceptable for MVP. Lockfile is the upgrade path. +- **R-2: PID recycling on long-uptime hosts.** Heartbeat freshness + catches it; 60s window is conservative. +- **R-3: SIGKILL leaves stale row** until next start. Documented; + sweep handles. +- **R-4: Heartbeat fights atomic-write contention** if 100 instances + all heartbeat at the same time. Cap concurrent instances at 100 + (port allocator already does this). 100 writes / 30s = 3.3 writes/s + globally — well within fs throughput. +- **OQ-1**: Should we expose `forgeplan-web doctor` to manually clean + the registry? Out of scope for MVP; growth. +- **OQ-2**: Should heartbeat skip when registry file is missing + (deleted by hand)? Yes — re-create on next tick. + +## Implementation Phases + +### Phase 1: Pure helpers + +- [ ] **1.1** `bin/lib/registry.mjs` with read/write/append/remove/sweep. +- [ ] **1.2** `bin/lib/port-allocator.mjs` with `findFreePort`. +- [ ] **1.3** Unit tests covering: parse-corrupt, atomic-write, sweep + with mixed alive/dead PIDs, port allocator hits/misses. + +### Phase 2: Wire start + +- [ ] **2.1** `start.mjs` resolves scaffold → calls `findFreePort` → + builds instance row → `appendInstance` → spawns server with `PORT` + set to allocated port. +- [ ] **2.2** Signal handlers in `start.mjs` call `removeInstance`. + +### Phase 3: Wire server + +- [ ] **3.1** `template/src/hooks.server.ts` calls `startHeartbeat()` + with the instance ID passed via env (`FORGEPLAN_WEB_INSTANCE_ID`). +- [ ] **3.2** `template/src/routes/api/instances/+server.ts` reads + registry and returns envelope. + +### Phase 4: Stress + smoke + +- [ ] **4.1** Stress: 10 parallel starts → assert all rows valid JSON, + no duplicates, no port collisions. +- [ ] **4.2** Smoke: SIGKILL → next start sweeps. +- [ ] **4.3** Smoke: SIGINT → row removed gracefully. + +## Affected Files + +- `bin/lib/registry.mjs` (NEW) +- `bin/lib/port-allocator.mjs` (NEW) +- `bin/commands/start.mjs` +- `template/src/shared/server/registry.ts` (NEW) +- `template/src/shared/server/heartbeat.ts` (NEW) +- `template/src/routes/api/instances/+server.ts` (NEW) +- `template/src/hooks.server.ts` +- `scripts/test/registry.test.mjs` (NEW) +- `scripts/smoke.mjs` + +## Related Artifacts + +| Artifact | Type | Relation | +|----------|------|----------| +| PRD-027 | PRD | based_on | +| ADR-004 | ADR | decided_by (path & format) | +| SPEC-003 | Spec | implements | +| RFC-022 | RFC | informs (start integrates here) | +| PRD-029 | PRD | informs (consumes /api/instances) | +| GitHub #113 | Issue | implements | + +--- + +> **Next step**: Land alongside PRD-027 + SPEC-003. + diff --git a/.forgeplan/rfcs/RFC-024-combobox-primitive-bits-ui-wrapper-variants-playground-showcase.md b/.forgeplan/rfcs/RFC-024-combobox-primitive-bits-ui-wrapper-variants-playground-showcase.md new file mode 100644 index 0000000..88d62cf --- /dev/null +++ b/.forgeplan/rfcs/RFC-024-combobox-primitive-bits-ui-wrapper-variants-playground-showcase.md @@ -0,0 +1,306 @@ +--- +depth: standard +id: RFC-024 +kind: rfc +links: +- target: PRD-028 + relation: based_on +status: draft +title: Combobox primitive — bits-ui wrapper, variants, /playground showcase +--- + +--- +id: RFC-024 +title: "Combobox primitive — bits-ui wrapper, variants, /playground showcase" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +prd: PRD-028 +depth: standard +--- + +# RFC-024: Combobox primitive — bits-ui wrapper, variants, /playground showcase + +## Summary + +Architecture for the Combobox primitive (PRD-028): a thin +Svelte 5 wrapper over `bits-ui`'s Combobox parts, with `default` / +`mono` variants and `sm` / `md` sizes, mirroring the file layout and +prop shape of existing primitives (Select, ToggleGroup). Includes +/playground showcase plan. + +## Motivation + +PRD-028 mandates a new primitive; PRD-029 needs it for the instance +switcher. RFC-016 (bits-ui-based primitives) is the precedent: every +new primitive wraps a bits-ui component, reads CSS vars from +`app.css`, and is showcased on /playground. This RFC nails down the +exact file layout, prop typing, and styling tokens before code lands. + +## Goals + +- Mirror existing primitive shape exactly: folder + `.svelte` + + barrel + top-level re-export. +- Implement variants `default` and `mono` and sizes `sm` and `md` per + PRD-028 FR-004/005. +- Cover all 2×2×3 combos on /playground. +- Zero new runtime deps (bits-ui already present per PRD-018). + +## Non-Goals + +- Multi-select Combobox. +- Async option providers. +- Virtualized rendering. +- Migration of existing Select consumers. + +## Options Considered + +### Option A: Direct bits-ui wrapper (CHOSEN) + +**Description**: Each sub-component re-exports the corresponding +bits-ui part (`Combobox.Root`, `Combobox.Trigger`, `Combobox.Content`, +`Combobox.Item`, `Combobox.Input`) wrapped in a Svelte 5 component +that adds variant/size class names + token-driven styles. File layout: + +``` +template/src/shared/ui/combobox/ +├── Combobox.svelte # Root wrapper (Combobox.Root) +├── ComboboxTrigger.svelte # Combobox.Trigger +├── ComboboxContent.svelte # Combobox.Portal + Combobox.Content +├── ComboboxItem.svelte # Combobox.Item +├── ComboboxInput.svelte # Combobox.Input (search input) +└── index.ts # named re-exports +``` + +**Pros**: +- Mirrors existing primitives 1:1 (Select, Tabs, ToggleGroup). +- bits-ui handles ARIA, keyboard, portal, positioning. +- Variants are pure CSS — no logic duplication. + +**Cons**: +- 5 components is more files than a single monolith; cost is offset + by clarity + composability. + +### Option B: Single-file Combobox.svelte that imports bits-ui internally + +**Description**: One `Combobox.svelte` that takes `options` array prop +and renders the whole tree internally without exposing parts. + +**Pros**: +- One import. + +**Cons**: +- Harder to customize trigger / content (consumers can't drop in their + own trigger). +- Diverges from existing primitive convention. +- Less testable (can't isolate parts). + +### Option C: Hand-rolled (no bits-ui) + +**Description**: Build accessibility from scratch. + +**Pros**: +- No bits-ui surface to track. + +**Cons**: +- Re-implements ARIA combobox pattern (hard to get right). +- Duplicates focus management. +- Violates RFC-016 convention. + +## Trade-off Analysis + +| Критерий | A: bits-ui parts (chosen) | B: monolithic | C: hand-rolled | +|----------|---------------------------|---------------|-----------------| +| A11y rigor | High (bits-ui) | High (bits-ui) | Variable | +| Composability | High (drop-in parts) | Low | High | +| Convention parity | High (mirrors Select) | Low | Low | +| Implementation cost | Low | Low | Very high | +| Maintenance burden | Low | Low | High | + +## Proposed Direction + +**Option A.** Component sketches: + +`Combobox.svelte`: + +```svelte + + + + {@render children?.()} + + + +``` + +Other parts follow the same shape — `ComboboxTrigger.svelte` wraps +`BC.Trigger`, `ComboboxContent.svelte` wraps `BC.Portal` + `BC.Content` +with surface tokens (`--bg-1`, `--line-2`, `--shadow-1`), +`ComboboxItem.svelte` wraps `BC.Item` with `--accent` highlight on +selected/active, `ComboboxInput.svelte` wraps `BC.Input` with the +`Input` primitive's typography. + +`index.ts`: + +```ts +export { default as Combobox } from './Combobox.svelte'; +export { default as ComboboxTrigger } from './ComboboxTrigger.svelte'; +export { default as ComboboxContent } from './ComboboxContent.svelte'; +export { default as ComboboxItem } from './ComboboxItem.svelte'; +export { default as ComboboxInput } from './ComboboxInput.svelte'; +export type { ComboboxVariant, ComboboxSize } from './Combobox.svelte'; +``` + +`template/src/shared/ui/index.ts` adds: + +```ts +export { + Combobox, + ComboboxTrigger, + ComboboxContent, + ComboboxItem, + ComboboxInput, + type ComboboxVariant, + type ComboboxSize, +} from './combobox'; +``` + +/playground showcase: + +```svelte +
+

Combobox

+ {#each (['default', 'mono'] as ComboboxVariant[]) as variant} + {#each (['sm', 'md'] as ComboboxSize[]) as size} +
+ + {demoValue ?? 'Pick…'} + + + {#each demoOptions as o} + {o.label} + {/each} + + +
+ {/each} + {/each} +
+``` + +The /playground page already supports theme switching (light / dark / +orch), so the 2×2 tiles render under all 3 themes via the existing +toolbar. + +## Risks & Open Questions + +- **R-1: bits-ui Combobox positioning** in a fixed-height bar like + HealthBar — must use `Portal` to escape overflow contexts. The + `ComboboxContent` wrapper bakes Portal in by default. +- **R-2: SSR-safety** — bits-ui's Combobox uses client-only state. + Wrapper is fine in SvelteKit because it lives in `+page.svelte` + client section; no SSR markup mismatch. +- **R-3: Type-narrowing on `value`** when options array changes — + document that consumer is responsible (no runtime guard added). +- **R-4: Variant naming drift** — Toggle uses `outline-mono`, this + uses `mono`. Acceptable: each primitive's variant set is independent; + PRD-028 names exactly two. +- **OQ-1**: Should we expose a `disabled` prop? Bits-ui supports it; + yes, forward it. (Add to FR if needed; safe additive default.) + +## Implementation Phases + +### Phase 1: Scaffold + +- [ ] **1.1** Create folder + 5 component files + barrel. +- [ ] **1.2** Wire bits-ui imports; verify type-check passes. + +### Phase 2: Variants + tokens + +- [ ] **2.1** Implement `default` / `mono` variants via class chains. +- [ ] **2.2** Implement `sm` / `md` sizes. +- [ ] **2.3** Style only via CSS vars from `app.css`. + +### Phase 3: /playground showcase + +- [ ] **3.1** Add Combobox section to `template/src/routes/playground/ + +page.svelte`. +- [ ] **3.2** Verify across 3 themes manually. + +### Phase 4: Re-export + docs + +- [ ] **4.1** Add to `template/src/shared/ui/index.ts`. +- [ ] **4.2** Add row to `template/src/shared/ui/README.md`. + +### Phase 5: Verify + +- [ ] **5.1** Rule 24 verification snippet — 0 hits. +- [ ] **5.2** Bundle delta < 5KB. +- [ ] **5.3** axe scan on /playground Combobox section — 0 violations. + +## Affected Files + +- `template/src/shared/ui/combobox/*` (NEW — 5 files + barrel) +- `template/src/shared/ui/index.ts` +- `template/src/shared/ui/README.md` +- `template/src/routes/playground/+page.svelte` + +## Related Artifacts + +| Artifact | Type | Relation | +|----------|------|----------| +| PRD-028 | PRD | based_on | +| RFC-016 | RFC | informs (bits-ui primitives convention) | +| PRD-018 | PRD | informs (foundation) | +| PRD-029 | PRD | informs (consumer) | +| GitHub #114 | Issue | implements | + +--- + +> **Next step**: Land alongside PRD-028. PRD-029 imports Combobox after this lands. + diff --git a/.forgeplan/rfcs/RFC-025-healthbar-instance-switcher-and-api-instances-readonly-endpoint.md b/.forgeplan/rfcs/RFC-025-healthbar-instance-switcher-and-api-instances-readonly-endpoint.md new file mode 100644 index 0000000..90403b9 --- /dev/null +++ b/.forgeplan/rfcs/RFC-025-healthbar-instance-switcher-and-api-instances-readonly-endpoint.md @@ -0,0 +1,361 @@ +--- +depth: standard +id: RFC-025 +kind: rfc +links: +- target: PRD-029 + relation: based_on +status: draft +title: HealthBar instance switcher and /api/instances readonly endpoint +--- + +--- +id: RFC-025 +title: "HealthBar instance switcher and /api/instances readonly endpoint" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +prd: PRD-029 +depth: standard +--- + +# RFC-025: HealthBar instance switcher and /api/instances readonly endpoint + +## Summary + +Architecture for PRD-029: read-only `/api/instances` endpoint that +returns the live instance registry, plus the client-side wiring of +that data into HealthBar via a Combobox (PRD-028) and a new entity +slice `entities/instance/`. + +## Motivation + +PRD-029 specifies the user-facing behavior; this RFC specifies the +endpoint contract, the entity-slice shape, and the HealthBar diff. It +also formalizes the rule-22 amendment text so reviewers have a stable +target. + +## Goals + +- One read-only endpoint, standard envelope. +- Mirror existing `entities/health/` slice exactly so the codebase + feels consistent. +- HealthBar diff stays small — Combobox replaces only the + `.theme-radiogroup` neighbor when `instances.length >= 2`. +- Rule-22 amendment is co-landed so reviewers can `git grep` the new + allowlist. + +## Non-Goals + +- Health-per-instance indicators. +- Mutating endpoints (kill / restart / activate). +- Cross-host federation. + +## Options Considered + +### Endpoint shape + +#### Option A: Read `~/.forgeplan-web/instances.json` directly + 5s in-memory cache (CHOSEN) + +**Description**: Endpoint reads SPEC-003-shaped JSON file directly via +the `template/src/shared/server/registry.ts` helper. In-memory cache +absorbs client poll spikes (5s TTL). + +**Pros**: +- No spawn, no fetch. +- Trivial implementation. +- Fast (< 5ms typical). + +**Cons**: +- Cache means up to 5s freshness lag — acceptable for human-scale UI. + +#### Option B: Spawn `forgeplan instances --json` (no such subcommand exists) + +**Description**: Hypothetical — push the registry into the forgeplan +CLI itself. + +**Pros**: +- Reuses runForgeplan plumbing. + +**Cons**: +- Forgeplan CLI doesn't manage forgeplan-web instances; out of scope + for that tool. Would require an upstream feature. + +#### Option C: WebSocket push from server-side heartbeat + +**Description**: Push registry changes to the browser as they happen. + +**Pros**: +- Zero polling. + +**Cons**: +- New WebSocket infrastructure. +- Existing pollers (health, version) all use `fetch`-poll; consistency + beats slight latency win. + +### Entity slice shape + +#### Option A: Mirror `entities/health/` (CHOSEN) + +**Description**: `entities/instance/` with `lib/instance-poller.svelte.ts`, +`model/types.ts`, `index.ts`. Poller exposes `state.data`, `state.loading`, +`state.error`, `state.lastFetched` — same shape as `healthPoller`. + +**Pros**: +- Consistency with existing slice. +- Reuses Svelte 5 runes pattern already proven. + +**Cons**: +- New file count. + +#### Option B: Inline polling inside HealthBar + +**Description**: Skip the entity slice; poll inside the widget directly. + +**Pros**: +- Fewer files. + +**Cons**: +- Violates FSD layer ownership (data lives in entity slice, not widget). +- Duplicates pattern already established by `entities/health/`. + +## Trade-off Analysis + +### Endpoint + +| Критерий | A: read JSON+cache (chosen) | B: spawn forgeplan | C: WebSocket | +|----------|------------------------------|---------------------|--------------| +| Implementation cost | Lowest | High (upstream change) | Highest | +| Latency | < 5ms | ~50ms (spawn) | ~0ms | +| Freshness | up to 5s lag | live | live | +| Pattern consistency | Aligns with /api/update-check | Diverges | Diverges | + +### Entity slice + +| Критерий | A: mirror health/ (chosen) | B: inline in widget | +|----------|----------------------------|---------------------| +| FSD compliance | High | Violates layer ownership | +| Reusability | High (other widgets can consume) | None | +| Code duplication | None | Some | + +## Proposed Direction + +**Endpoint**: Option A. **Slice**: Option A. + +`template/src/routes/api/instances/+server.ts`: + +```ts +import type { RequestHandler } from './$types'; +import { readInstanceRegistry } from '$lib/server/registry'; + +let cache: { ts: number; payload: any } | null = null; +const TTL = 5000; + +export const GET: RequestHandler = async () => { + const now = Date.now(); + if (cache && now - cache.ts < TTL) { + return new Response(JSON.stringify(cache.payload), { + headers: { 'content-type': 'application/json' }, + }); + } + let payload; + try { + const reg = readInstanceRegistry(); + payload = { ok: true, data: { instances: reg.instances } }; + } catch (e) { + payload = { ok: true, data: { instances: [] }, error: String(e) }; + } + cache = { ts: now, payload }; + return new Response(JSON.stringify(payload), { + headers: { 'content-type': 'application/json' }, + }); +}; +``` + +`template/src/shared/server/registry.ts`: + +```ts +import { readFileSync, existsSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +const PATH = path.join(os.homedir(), '.forgeplan-web', 'instances.json'); + +export interface InstanceRow { + id: string; host: string; port: number; pid: number; + scope: 'user' | 'project'; workspaceRoot: string; projectName: string; + startedAt: string; heartbeatAt: string; + webVersion: string; forgeplanCli: string | null; +} +export interface RegistryFile { version: 1; instances: InstanceRow[]; } + +export function readInstanceRegistry(): RegistryFile { + if (!existsSync(PATH)) return { version: 1, instances: [] }; + try { + const raw = JSON.parse(readFileSync(PATH, 'utf8')); + if (raw?.version !== 1) return { version: 1, instances: [] }; + return raw; + } catch { + return { version: 1, instances: [] }; + } +} +``` + +`template/src/entities/instance/lib/instance-poller.svelte.ts`: + +```ts +import type { InstanceRow } from '$entities/instance/model/types'; + +class InstancePoller { + state = $state<{ + data: InstanceRow[] | null; + loading: boolean; + error: string | null; + lastFetched: number | null; + }>({ data: null, loading: false, error: null, lastFetched: null }); + + private timer: ReturnType | null = null; + + async fetchOnce() { + this.state.loading = true; + try { + const r = await fetch('/api/instances'); + const j = await r.json(); + this.state.data = j?.data?.instances ?? []; + this.state.error = null; + this.state.lastFetched = Date.now(); + } catch (e) { + this.state.error = String(e); + } finally { + this.state.loading = false; + } + } + + start({ intervalMs = 5000 } = {}) { + if (this.timer) return; + this.fetchOnce(); + this.timer = setInterval(() => this.fetchOnce(), intervalMs); + } + stop() { + if (this.timer) { clearInterval(this.timer); this.timer = null; } + } +} + +export const instancePoller = new InstancePoller(); +``` + +HealthBar diff (sketch — only the new bit): + +```svelte + + +{#if showSwitcher} + + {instances.find((i) => i.id === currentId)?.projectName ?? currentId} + + + {#each [...instances].sort((a, b) => a.port - b.port) as inst (inst.id)} + + {inst.projectName} ({inst.host}:{inst.port}) + + {/each} + + +{/if} +``` + +Rule 22 amendment text appears in PRD-029's body verbatim — reviewers +copy-paste into `.claude/rules/22-readonly-proxy.md`. + +## Risks & Open Questions + +- **R-1: `location.hostname`/`location.port` may not match registered + `host`/`port`** when the user proxies through a tunnel. MVP assumes + localhost; document the limitation. +- **R-2: Browser blocks cross-port `window.location.replace`** as a + cross-origin navigation. Same-origin per scheme is allowed for + localhost; verify on Chrome/Firefox/Safari. +- **R-3: Cache 5s TTL hides crashed peer for up to 5s** — acceptable; + client poll on 5s anyway. +- **R-4: SSR hydration mismatch** if the slice is touched during SSR. + `instancePoller.start()` is gated by `$effect` (client-only); safe. +- **OQ-1**: Should the endpoint expose `version` field too? No — + consumer doesn't need it; future schema bumps are forward-only. +- **OQ-2**: Should we add optimistic-UI for the local instance? No — + registry-driven only. + +## Implementation Phases + +### Phase 1: Endpoint + helper + +- [ ] **1.1** `template/src/shared/server/registry.ts` (NEW). +- [ ] **1.2** `template/src/routes/api/instances/+server.ts` (NEW). +- [ ] **1.3** Unit test endpoint: empty file, valid file, malformed + JSON, version mismatch. + +### Phase 2: Entity slice + +- [ ] **2.1** `template/src/entities/instance/model/types.ts`. +- [ ] **2.2** `template/src/entities/instance/lib/instance-poller.svelte.ts`. +- [ ] **2.3** `template/src/entities/instance/index.ts` barrel. + +### Phase 3: HealthBar wiring + +- [ ] **3.1** Import poller + Combobox in HealthBar. +- [ ] **3.2** Conditional render on `instances.length >= 2`. +- [ ] **3.3** Pre-select current; navigate on pick. +- [ ] **3.4** Visual review across themes. + +### Phase 4: Rule 22 amendment + +- [ ] **4.1** Append the block from PRD-029 to + `.claude/rules/22-readonly-proxy.md`. +- [ ] **4.2** Update verification snippet to allow + `instances/+server.ts` reading from `~/.forgeplan-web/instances.json`. + +### Phase 5: Smoke + e2e + +- [ ] **5.1** Smoke: 1 instance → no Combobox; 2 instances → Combobox. +- [ ] **5.2** E2E spy on `window.location.replace`. + +## Affected Files + +- `template/src/shared/server/registry.ts` (NEW) +- `template/src/routes/api/instances/+server.ts` (NEW) +- `template/src/entities/instance/*` (NEW — 3 files) +- `template/src/widgets/health-bar/ui/HealthBar.svelte` (modified) +- `.claude/rules/22-readonly-proxy.md` (amendment) + +## Related Artifacts + +| Artifact | Type | Relation | +|----------|------|----------| +| PRD-029 | PRD | based_on | +| PRD-027 | PRD | informs (registry source) | +| PRD-028 | PRD | informs (Combobox consumer) | +| SPEC-003 | Spec | informs (data shape) | +| RFC-024 | RFC | informs (Combobox architecture) | +| GitHub #115 | Issue | implements | + +--- + +> **Next step**: Land alongside PRD-029. Last RFC of the #109 chain. + diff --git a/.forgeplan/specs/SPEC-003-instance-registry-json-schema-forgeplan-web-instances-json.md b/.forgeplan/specs/SPEC-003-instance-registry-json-schema-forgeplan-web-instances-json.md new file mode 100644 index 0000000..0a2bef1 --- /dev/null +++ b/.forgeplan/specs/SPEC-003-instance-registry-json-schema-forgeplan-web-instances-json.md @@ -0,0 +1,253 @@ +--- +depth: standard +id: SPEC-003 +kind: spec +links: +- target: PRD-027 + relation: based_on +status: draft +title: Instance registry JSON schema (~/.forgeplan-web/instances.json) +--- + +--- +id: SPEC-003 +title: "Instance registry JSON schema (~/.forgeplan-web/instances.json)" +status: Draft +author: docs-eng-109 +created: 2026-05-08 +updated: 2026-05-08 +prd: PRD-027 +type: Data Model +depth: standard +--- + +# SPEC-003: Instance registry JSON schema (~/.forgeplan-web/instances.json) + +## Summary + +Authoritative JSON schema for the multi-instance registry file +(`~/.forgeplan-web/instances.json`) used by PRD-027's port-coordination +and PRD-029's instance switcher. Schema version 1. + +## Scope + +Owns: + +- File path convention: `~/.forgeplan-web/instances.json` (locked by + ADR-004, mirrors PRD-025 user-scope path). +- Top-level `Registry` shape and version field. +- `Instance` row shape and field-level constraints. +- Side-effects table (`registry.write`, `registry.invalidate`, + `instance.deregister`). +- Versioning policy. + +Does NOT own: + +- Read/write algorithms — see RFC-023. +- API endpoint contract — `/api/instances` envelope is documented + inline below for cross-reference but the read-only proxy invariant + belongs to rule 22 (amended in PRD-029). +- Liveness semantics — see RFC-023. + +## Data Models + +### Registry (top-level) + +```typescript +interface Registry { + /** + * Schema version. Bumped on breaking field rename / removal. + * Readers MUST treat unknown versions as empty (recover gracefully). + */ + version: 1; + + /** + * Currently-known instances. Order is not significant; readers + * sort by `port` for display when needed. + */ + instances: Instance[]; +} +``` + +### Instance (per-row) + +```typescript +interface Instance { + /** + * Stable identity for the running instance. Format is `host:port`, + * e.g. "127.0.0.1:5174". Used as primary key — duplicate rows with + * the same id MUST be deduped by writers (last-writer-wins). + */ + id: string; + + /** Bind host. Typically "127.0.0.1". MUST be a valid IP literal or hostname. */ + host: string; + + /** TCP port. MUST be in [1024, 65535]. */ + port: number; + + /** OS process id. MUST be a positive integer. */ + pid: number; + + /** Scope under which the scaffold was installed. */ + scope: 'user' | 'project'; + + /** + * Absolute path to the Forgeplan workspace this instance serves. + * Equals FORGEPLAN_CWD passed to the SvelteKit server. + */ + workspaceRoot: string; + + /** + * Human-friendly project label. By convention: `path.basename(workspaceRoot)`, + * or the git remote name when detectable. MUST be 1-128 chars. + */ + projectName: string; + + /** ISO 8601 timestamp when the instance was registered. Immutable for the row's lifetime. */ + startedAt: string; + + /** ISO 8601 timestamp last refreshed by the heartbeat (every 30s, see RFC-023). */ + heartbeatAt: string; + + /** @forgeplan/web package version reported at start time. e.g. "0.1.14". */ + webVersion: string; + + /** + * forgeplan CLI version detected at start time. May be null if the + * binary was unavailable when start ran (rare; init normally fails first). + */ + forgeplanCli: string | null; +} +``` + +**Constraints**: + +- `id` MUST equal `${host}:${port}` (writer invariant; readers MAY trust). +- `port`: 1024-65535. +- `pid`: > 0. +- `startedAt`, `heartbeatAt`: ISO 8601 with timezone (e.g. trailing `Z` or `+HH:MM`). +- `workspaceRoot`: absolute path; MUST exist at write time. +- `projectName`: 1-128 chars. +- `scope`: enum `'user' | 'project'`. + +## Validation Rules + +| Field | Rule | Error message | +|-------|------|---------------| +| `version` | Must be exactly `1` | `unsupported registry version: ` | +| `instances` | Must be an array | `instances must be an array` | +| `id` | Must match `^[A-Za-z0-9.\-_:]+:[0-9]+$` | `invalid instance id: ` | +| `id` | Must equal `${host}:${port}` | `instance id must be :` | +| `host` | Non-empty string | `host required` | +| `port` | Integer in [1024, 65535] | `port out of range: ` | +| `pid` | Positive integer | `invalid pid: ` | +| `scope` | One of `user` / `project` | `unknown scope: ` | +| `workspaceRoot` | Absolute path | `workspaceRoot must be absolute` | +| `projectName` | String, 1-128 chars | `projectName length out of range` | +| `startedAt` | Parseable ISO 8601 | `invalid startedAt: ` | +| `heartbeatAt` | Parseable ISO 8601 | `invalid heartbeatAt: ` | +| `webVersion` | Non-empty string (semver-shaped) | `webVersion required` | +| `forgeplanCli` | String or null | `forgeplanCli must be string or null` | + +Readers SHOULD log a warning on validation failure but treat the row +as if it were absent (dropping it from the live view). This keeps +forgeplan-web resilient to partially-corrupt registries. + +## Relationships + +```mermaid +erDiagram + REGISTRY ||--o{ INSTANCE : "contains 0..N" + REGISTRY { + number version + } + INSTANCE { + string id PK + string host + number port + number pid + string scope + string workspaceRoot + string projectName + string startedAt + string heartbeatAt + string webVersion + string forgeplanCli + } +``` + +## Events / Side Effects + +Writers MUST emit one of these logical events per state change. The +events are not transported anywhere yet (no event bus in MVP); they are +named here so future tooling (`forgeplan-web doctor`, audit logs) can +hook in without re-naming. + +| Trigger | Event | Producers | Consumers | +|---------|-------|-----------|-----------| +| New instance appended | `registry.write` (op: `append`) | `bin/commands/start.mjs` after port-bind | (none in MVP; future doctor) | +| Heartbeat refresh | `registry.write` (op: `heartbeat`) | `template/src/shared/server/heartbeat.ts` setInterval | (none) | +| Stale row removed during sweep | `registry.invalidate` | `bin/lib/registry.mjs#sweepStale` (called by `appendInstance`) | (none) | +| Graceful exit | `instance.deregister` | `bin/commands/start.mjs` SIGINT/SIGTERM/beforeExit handler | (none) | +| Crash (SIGKILL) | (no event; row stays until next sweep) | n/a | sweep on next `start` | +| Manual file delete | (silently re-created on next write) | n/a | n/a | + +## API Surface (cross-reference) + +The endpoint `GET /api/instances` (defined by RFC-025) returns: + +```json +{ + "ok": true, + "data": { + "instances": [ + { + "id": "127.0.0.1:5174", + "host": "127.0.0.1", + "port": 5174, + "pid": 12345, + "scope": "user", + "workspaceRoot": "/Users/me/proj-a", + "projectName": "proj-a", + "startedAt": "2026-05-08T19:00:00.000Z", + "heartbeatAt": "2026-05-08T19:00:30.000Z", + "webVersion": "0.1.14", + "forgeplanCli": "0.27.0" + } + ] + } +} +``` + +On error: `{ "ok": false, "error": "...", "data": { "instances": [] } }`. + +## Versioning + +| Version | Date | Changes | +|---------|------|---------| +| 1 | 2026-05-08 | Initial schema. Fields: id, host, port, pid, scope, workspaceRoot, projectName, startedAt, heartbeatAt, webVersion, forgeplanCli. | + +**Bump policy**: + +- Breaking change (field rename, removal, type change) → `version: 2`. + Readers MUST treat unknown versions as empty registry. Writers MUST + refuse to write a `version: 1` payload after bumping. +- Additive change (new optional field) → no bump; old readers ignore + unknown fields. +- Reading a `version: 0` or absent — treat as empty (forward-only + migration). + +## Related + +- PRD-027 — multi-instance registry product spec +- RFC-023 — read/write algorithms, port allocator, liveness probe +- RFC-025 — `/api/instances` endpoint contract +- ADR-004 — registry path & format decision +- PRD-029 — HealthBar instance switcher (consumer) +- GitHub #113 — source sub-issue + +--- + +> **Next step**: Land alongside RFC-023. PRD-029 consumes the API surface defined here. + From f146c5850b852d5063385e61270f02dded20a16f Mon Sep 17 00:00:00 2001 From: fedorovvvv Date: Fri, 8 May 2026 23:41:17 +0400 Subject: [PATCH 2/7] feat(bin): adopt citty + split into cli/commands/lib (#110) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refactor the 367-line bin/forgeplan-web.mjs into a 5-line entry + bin/cli.mjs (root command) + bin/commands/{init,update,start}.mjs (one file per subcommand) + bin/lib/{config,gitignore,forgeplan-binary}.mjs (shared helpers). citty@0.2.2 provides defineCommand / runMain / typed args / auto-help / subcommand routing. Behavior preserved 1:1 — every flag (-y, --force, --quiet, --no-gitignore, --experimental, --no-experimental) and every alias (upgrade, serve, run) still works. New --scope user|project flag is declared on init/update/start as a placeholder (TODO(109b)) for the next wave to wire. Rule 23 amended to permit citty as the single named exception (verification snippet updated). npm ls --omit=dev shows only citty@0.2.2 (no transitive deps in this version). Smoke test (3-OS gate) passes. PASS line confirmed locally. Refs: PRD-024, RFC-020, ADR-003 Closes: #110 Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/rules/23-bin-zero-deps.md | 118 +++++++--- bin/cli.mjs | 16 ++ bin/commands/init.mjs | 133 +++++++++++ bin/commands/start.mjs | 83 +++++++ bin/commands/update.mjs | 157 +++++++++++++ bin/forgeplan-web.mjs | 368 +----------------------------- bin/lib/config.mjs | 32 +++ bin/lib/forgeplan-binary.mjs | 29 +++ bin/lib/gitignore.mjs | 26 +++ package-lock.json | 13 +- package.json | 3 + 11 files changed, 573 insertions(+), 405 deletions(-) create mode 100644 bin/cli.mjs create mode 100644 bin/commands/init.mjs create mode 100644 bin/commands/start.mjs create mode 100644 bin/commands/update.mjs create mode 100644 bin/lib/config.mjs create mode 100644 bin/lib/forgeplan-binary.mjs create mode 100644 bin/lib/gitignore.mjs diff --git a/.claude/rules/23-bin-zero-deps.md b/.claude/rules/23-bin-zero-deps.md index 1364fda..2608312 100644 --- a/.claude/rules/23-bin-zero-deps.md +++ b/.claude/rules/23-bin-zero-deps.md @@ -1,31 +1,50 @@ -# `bin/` zero runtime dependencies +# `bin/` near-zero runtime dependencies (amended by ADR-003) -`bin/forgeplan-web.mjs` is invoked by `npx @forgeplan/web init` and -`npx @forgeplan/web start`. The bin script itself MUST run with Node -built-ins only — it does its job (copy `dist/` into `.forgeplan-web/`, -spawn `node .forgeplan-web/index.js`) without needing any third-party -import. +`bin/forgeplan-web.mjs` is invoked by `npx @forgeplan/web init`, +`npx @forgeplan/web update`, and `npx @forgeplan/web start`. The bin +script does its job (copy `dist/` into `.forgeplan-web/`, spawn +`node .forgeplan-web/index.js`) with Node built-ins plus exactly **one** +allow-listed CLI library: `citty` (per ADR-003). -## Allowed in `bin/` +ADR-003 amended the historical "zero-dep" rule to a **named-allowlist** +rule: `citty` (and any of its transitive deps) is the **only** named +exception. Adding any other third-party import to `bin/` requires a new +ADR — not an amendment to this one. + +## Allowed in `bin/` (amended by ADR-003) - `node:*` modules (`node:fs`, `node:child_process`, `node:path`, `node:url`, `node:os`, `node:crypto`, `node:util`). -- Relative imports of sibling `.mjs` files **inside `bin/`** (e.g. - `import { … } from "./banner.mjs"`). These are first-party code that - ships in the `bin/` folder of the published tarball; they introduce - no third-party resolution at `npx` time. Each such sibling file is - itself bound by this rule (zero `node_modules/` imports, `node:*`-only). +- Relative imports of sibling `.mjs` files inside `bin/` (e.g. + `import { … } from "./banner.mjs"`, `from "./lib/config.mjs"`, + `from "./commands/init.mjs"`). These are first-party code that ships + in the `bin/` folder of the published tarball; they introduce no + third-party resolution at `npx` time. Each such sibling file is + itself bound by this rule (`node:*` + `citty` only, plus relative + siblings). +- **`citty`** — CLI framework providing `defineCommand`, `runMain`, + `parseArgs`, typed args, auto-help, and subcommand routing. Pinned + to `^0.2.2` (caret-minor). Bumping major/minor requires re-evaluating + ADR-003. As of `citty@0.2.2` the package has zero runtime + `dependencies` (it bundles its own helpers and uses + `node:util.parseArgs`); should a future version reintroduce + transitive deps, those are covered by this rule too as long as they + are pulled by `citty` and not declared at the root. - Synchronous I/O (`mkdirSync`, `cpSync`, …) — the script is short and CLI-bound; readability beats event-loop nicety. ## Forbidden in `bin/` -- Any `import` from a third-party package. -- Any `require()` from `node_modules/` at the package root. -- Spawning `node_modules/.bin/*` binaries from the package root (root - has no `node_modules`). -- Adding entries to the root `package.json#dependencies` to support the - bin script. +- Any third-party import OTHER than `citty` (and any transitive deps + it pulls). E.g. `chalk`, `commander`, `yargs`, `figlet`, `prompts`, + `ora`, `kleur` are all forbidden. If you think one is needed, open a + new ADR. +- Any `require()` from `node_modules/` at the package root that is not + resolved through citty. +- Spawning `node_modules/.bin/*` binaries from the package root. +- Adding any other entry to root `package.json#dependencies` to support + the bin script. Currently allowed: `{ "citty": "^0.2.2" }` — and + nothing else. ## Note on `dist/` and `dist-experimental/` @@ -43,8 +62,8 @@ The published tarball ships **two** pre-built artifacts (PRD-014 / RFC-013): In both cases the bin script only `spawn()`s `node` against the artifact's `index.js` — it never imports anything from the artifact's -internals. This rule is about the bin script itself staying zero-dep; -the artifacts are governed by rule 21. +internals. This rule is about the bin script itself staying bound to +the citty + node:* allow-list; the artifacts are governed by rule 21. After the bundled shape graduates from `--experimental` (see `TODO(rfc-013-graduation)` in `bin/forgeplan-web.mjs` and @@ -53,10 +72,13 @@ tarball and this section will collapse to one paragraph. ## Required -- The root `package.json` must keep `dependencies` empty (or absent). It - may have `devDependencies` for repo tooling (currently: `esbuild` for - building `dist-experimental/`). The published tarball ships `bin/` - (zero-dep), `dist/` (with its own `node_modules/`), +- The root `package.json` must keep `dependencies` to **exactly** the + citty entry: `{ "citty": "^0.2.2" }` (caret-minor pin per ADR-003). + No other runtime deps allowed at the root. `devDependencies` for + repo tooling are unconstrained by this rule (currently: `esbuild`). +- The published tarball ships `bin/` (incl. `bin/cli.mjs`, + `bin/commands/*.mjs`, `bin/lib/*.mjs`, `bin/banner.mjs`, + `bin/forgeplan-web.mjs`), `dist/` (with its own `node_modules/`), `dist-experimental/` (single bundle, no `node_modules/`), and `README.md`. - `package.json#engines` pins Node ≥ `^20.19.0 || >=22.12.0`. Any change @@ -67,31 +89,51 @@ tarball and this section will collapse to one paragraph. `npx @forgeplan/web init` is the user's first contact with the package. The package itself is pre-built — `init` is a `cp -r` of `dist/` into `.forgeplan-web/`, and `start` is a `spawn(node, dist/index.js)`. The bin -must not pull in third-party code that npm would have to resolve before -invocation; doing so would re-introduce the exact latency we removed by -shipping a pre-built artifact. +must not pull in arbitrary third-party code that npm would have to +resolve before invocation; doing so would re-introduce the exact latency +we removed by shipping a pre-built artifact. The citty exception is +ADR-003's deliberate trade-off: ~5KB / ~50ms for subcommand routing, +typed args, auto-help, and a future prompt hook (#111). ## Verification ```bash -# bin/* must only import node:* modules or relative sibling .mjs files. -# Allowed: from 'node:fs', from "./banner.mjs", from "../bin/x.mjs" -# Forbidden: from 'chalk', from 'figlet', from any bare specifier. +# bin/* must only import node:* modules, citty, or relative sibling .mjs files. +# Allowed: from 'node:fs', from 'citty', from "./banner.mjs", +# from "./lib/config.mjs", from "./commands/init.mjs" +# Forbidden: from 'chalk', from 'commander', from any other bare specifier. # Also handles multi-line `import { … } from "node:fs";` because we match # the `from "…"` line itself, regardless of where the `import` keyword sits. -for f in bin/*.mjs; do +fail=0 +for f in $(find bin -name '*.mjs' -type f); do hits=$(grep -E "(from|require\()\s*['\"]" "$f" \ - | grep -vE "(from|require\()\s*['\"]node:" \ + | grep -vE "(from|require\()\s*['\"](node:|citty['\"])" \ | grep -vE "(from|require\()\s*['\"]\\.{1,2}/" || true) if [ -z "$hits" ]; then - echo "OK ($f): no third-party deps" + echo "OK ($f): bin allow-list (node:*, citty, relative)" else - echo "FAIL ($f): third-party imports found:" + echo "FAIL ($f): non-allow-listed imports found:" echo "$hits" - exit 1 + fail=1 fi done - -# root package must not declare runtime deps -node -e "const p=require('./package.json'); if (p.dependencies && Object.keys(p.dependencies).length) { console.error('FAIL: runtime deps present', p.dependencies); process.exit(1)} else { console.log('OK: no runtime deps') }" +[ "$fail" -eq 0 ] || exit 1 + +# root package may declare ONLY citty as runtime dep +node -e " +const p = require('./package.json'); +const deps = p.dependencies || {}; +const keys = Object.keys(deps).sort(); +const allowed = ['citty']; +const extra = keys.filter((k) => !allowed.includes(k)); +if (extra.length) { + console.error('FAIL: unexpected runtime deps', extra); + process.exit(1); +} +if (!deps.citty) { + console.error('FAIL: citty missing from dependencies (ADR-003 invariant I3)'); + process.exit(1); +} +console.log('OK: root deps = { citty:', deps.citty, '}'); +" ``` diff --git a/bin/cli.mjs b/bin/cli.mjs new file mode 100644 index 0000000..68f812f --- /dev/null +++ b/bin/cli.mjs @@ -0,0 +1,16 @@ +import { defineCommand } from "citty"; +import { readPkgVersion } from "./lib/config.mjs"; + +export default defineCommand({ + meta: { + name: "forgeplan-web", + version: readPkgVersion() ?? "0.0.0", + description: + "Interactive realtime web map for a Forgeplan workspace. Ships a pre-built SvelteKit app — no npm install at user side.", + }, + subCommands: { + init: () => import("./commands/init.mjs").then((m) => m.default), + update: () => import("./commands/update.mjs").then((m) => m.default), + start: () => import("./commands/start.mjs").then((m) => m.default), + }, +}); diff --git a/bin/commands/init.mjs b/bin/commands/init.mjs new file mode 100644 index 0000000..0fe18e4 --- /dev/null +++ b/bin/commands/init.mjs @@ -0,0 +1,133 @@ +import { defineCommand } from "citty"; +import { cpSync, existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { + CFG_FILE, + PKG_ROOT, + readConfig, + readPkgVersion, +} from "../lib/config.mjs"; +import { + ensureForgeplanBinary, + ensureForgeplanWorkspace, +} from "../lib/forgeplan-binary.mjs"; +import { ensureGitignore } from "../lib/gitignore.mjs"; + +const DIST_DIR_LEGACY = join(PKG_ROOT, "dist"); +const DIST_DIR_EXPERIMENTAL = join(PKG_ROOT, "dist-experimental"); + +function fail(line, code = 1) { + process.stderr.write(`forgeplan-web: ${line}\n`); + process.exit(code); +} + +function copyDir(src, dest, force) { + if (!existsSync(src)) { + fail( + `pre-built artifact missing at ${src}.\n` + + ` This usually means the npm package was published without a build. ` + + `Reinstall, or build from source via \`npm run build\`.`, + ); + } + if (existsSync(dest) && !force) { + cpSync(src, dest, { + recursive: true, + dereference: false, + force: false, + errorOnExist: false, + }); + } else { + mkdirSync(dest, { recursive: true }); + cpSync(src, dest, { recursive: true, dereference: false, force: true }); + } +} + +export default defineCommand({ + meta: { + name: "init", + description: + "Copy the pre-built SvelteKit app to ./.forgeplan-web/ and append `.forgeplan-web/` to ./.gitignore (idempotent).", + }, + args: { + y: { + type: "boolean", + description: "accepted for compatibility (init is non-interactive)", + }, + force: { + type: "boolean", + description: "overwrite files that already exist", + }, + quiet: { + type: "boolean", + alias: "q", + description: "suppress informational output", + }, + gitignore: { + type: "boolean", + default: true, + description: + "append `.forgeplan-web/` to ./.gitignore (default true; pass --no-gitignore to skip)", + }, + experimental: { + type: "boolean", + description: + "[EXPERIMENTAL] use the bundled single-file dist (~9x smaller, no node_modules/)", + }, + // TODO(109b): scope flag declared, not yet consumed — see PRD-025 + scope: { + type: "string", + description: + "[reserved for PRD-025] scope of the scaffold: user|project (no-op in this release)", + valueHint: "user|project", + }, + }, + async run({ args }) { + const QUIET = args.quiet === true; + const FORCE = args.force === true; + // citty: --no-gitignore parses to args.gitignore = false; default is true. + const SKIP_GITIGNORE = args.gitignore === false; + const EXPERIMENTAL = args.experimental === true; + + const log = (line) => { + if (!QUIET) process.stdout.write(line + "\n"); + }; + + const DIST_DIR = EXPERIMENTAL ? DIST_DIR_EXPERIMENTAL : DIST_DIR_LEGACY; + + const cwd = process.cwd(); + ensureForgeplanWorkspace(cwd, fail); + ensureForgeplanBinary(fail); + + if (EXPERIMENTAL) { + log( + "⚠ Using experimental bundled dist (single-file server, no node_modules/).", + ); + log( + " Report issues at https://github.com/ForgePlan/forgeplan-web/issues", + ); + } + + const target = join(cwd, ".forgeplan-web"); + const fresh = !existsSync(target); + log(fresh ? `→ creating ${target}` : `→ updating ${target}`); + copyDir(DIST_DIR, target, FORCE); + + const now = new Date().toISOString(); + const existing = fresh ? null : readConfig(target); + const cfg = { + workspaceRoot: cwd, + createdAt: existing?.createdAt ?? now, + version: readPkgVersion() ?? existing?.version ?? null, + updatedAt: now, + experimental: EXPERIMENTAL, + }; + writeFileSync(join(target, CFG_FILE), JSON.stringify(cfg, null, 2) + "\n"); + + ensureGitignore({ cwd, skip: SKIP_GITIGNORE, log }); + + log(""); + log("✓ ready (no install needed)"); + log(" npx @forgeplan/web start"); + log(" # or: node .forgeplan-web/index.js"); + }, +}); diff --git a/bin/commands/start.mjs b/bin/commands/start.mjs new file mode 100644 index 0000000..3aa21e5 --- /dev/null +++ b/bin/commands/start.mjs @@ -0,0 +1,83 @@ +import { defineCommand } from "citty"; +import { spawn } from "node:child_process"; +import { existsSync } from "node:fs"; +import { join } from "node:path"; +import { printBanner } from "../banner.mjs"; +import { readWorkspaceRoot } from "../lib/config.mjs"; + +function fail(line, code = 1) { + process.stderr.write(`forgeplan-web: ${line}\n`); + process.exit(code); +} + +export default defineCommand({ + meta: { + name: "start", + description: + "Run the SvelteKit server from ./.forgeplan-web/. Reads PORT, HOST, FORGEPLAN_CWD, FORGEPLAN_BIN env vars.", + alias: ["serve", "run"], + }, + args: { + quiet: { + type: "boolean", + alias: "q", + description: "suppress banner and informational output", + }, + // TODO(109b): scope flag declared, not yet consumed — see PRD-025 + scope: { + type: "string", + description: + "[reserved for PRD-025] scope of the instance: user|project (no-op in this release)", + valueHint: "user|project", + }, + }, + async run({ args }) { + const QUIET = args.quiet === true; + const log = (line) => { + if (!QUIET) process.stdout.write(line + "\n"); + }; + + const cwd = process.cwd(); + const target = join(cwd, ".forgeplan-web"); + + if (!existsSync(target) || !existsSync(join(target, "index.js"))) { + fail( + `no scaffolded server at ${target}.\n` + + ` Run \`npx @forgeplan/web init\` first.`, + ); + } + + const workspaceRoot = readWorkspaceRoot(target) ?? cwd; + const env = { + ...process.env, + PORT: process.env.PORT ?? "5174", + HOST: process.env.HOST ?? "127.0.0.1", + FORGEPLAN_CWD: process.env.FORGEPLAN_CWD ?? workspaceRoot, + }; + + printBanner({ quiet: QUIET }); + log(`→ starting forgeplan-web on http://${env.HOST}:${env.PORT}`); + log(` workspace: ${env.FORGEPLAN_CWD}`); + + const child = spawn(process.execPath, ["index.js"], { + cwd: target, + env, + stdio: "inherit", + }); + + const forward = (sig) => { + if (!child.killed) child.kill(sig); + }; + process.on("SIGINT", () => forward("SIGINT")); + process.on("SIGTERM", () => forward("SIGTERM")); + + // Wrap in a Promise so citty's runMain awaits the child's exit + // before terminating; otherwise process.exit in the listener races. + return new Promise(() => { + child.on("exit", (code, signal) => { + if (signal) process.exit(0); + process.exit(code ?? 0); + }); + }); + }, +}); diff --git a/bin/commands/update.mjs b/bin/commands/update.mjs new file mode 100644 index 0000000..9704a6d --- /dev/null +++ b/bin/commands/update.mjs @@ -0,0 +1,157 @@ +import { defineCommand } from "citty"; +import { + cpSync, + existsSync, + lstatSync, + mkdirSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { join, resolve } from "node:path"; +import { + CFG_FILE, + PKG_ROOT, + readConfig, + readPkgVersion, +} from "../lib/config.mjs"; +import { + ensureForgeplanBinary, + ensureForgeplanWorkspace, +} from "../lib/forgeplan-binary.mjs"; + +const DIST_DIR_LEGACY = join(PKG_ROOT, "dist"); +const DIST_DIR_EXPERIMENTAL = join(PKG_ROOT, "dist-experimental"); + +function fail(line, code = 1) { + process.stderr.write(`forgeplan-web: ${line}\n`); + process.exit(code); +} + +export default defineCommand({ + meta: { + name: "update", + description: + "Refresh ./.forgeplan-web/ to the version bundled with the currently-resolved @forgeplan/web package.", + alias: ["upgrade"], + }, + args: { + force: { + type: "boolean", + description: "re-copy even when versions match", + }, + quiet: { + type: "boolean", + alias: "q", + description: "suppress informational output", + }, + experimental: { + type: "boolean", + description: + "switch to the experimental bundled dist (overrides persisted choice)", + }, + // TODO(109b): scope flag declared, not yet consumed — see PRD-025 + scope: { + type: "string", + description: + "[reserved for PRD-025] scope of the scaffold: user|project (no-op in this release)", + valueHint: "user|project", + }, + }, + async run({ args }) { + const QUIET = args.quiet === true; + const FORCE = args.force === true; + + const log = (line) => { + if (!QUIET) process.stdout.write(line + "\n"); + }; + + const cwd = process.cwd(); + ensureForgeplanWorkspace(cwd, fail); + ensureForgeplanBinary(fail); + + const target = join(cwd, ".forgeplan-web"); + if (!existsSync(target)) { + fail( + `no scaffold at ${target}.\n` + + ` Run \`npx @forgeplan/web init\` first.`, + ); + } + + const existing = readConfig(target); + const fromVersion = existing?.version ?? null; + const toVersion = readPkgVersion(); + + // PRD-014 / RFC-013: pick the same dist shape the user opted into at + // init-time. CLI flag overrides the persisted choice (lets users migrate + // both directions without rm -rf). Falls back to legacy default. + // citty auto-handles `--no-experimental` by setting `args.experimental = false`. + const experimentalFlagPassed = args.experimental !== undefined; + const useExperimental = experimentalFlagPassed + ? args.experimental === true + : existing?.experimental === true; + const sourceDir = useExperimental + ? DIST_DIR_EXPERIMENTAL + : DIST_DIR_LEGACY; + + if (!FORCE && fromVersion && toVersion && fromVersion === toVersion) { + log(`✓ already at v${toVersion}`); + log(" Use --force to re-copy anyway."); + return; + } + + const fromLabel = fromVersion ? `v${fromVersion}` : "unknown"; + const toLabel = toVersion ? `v${toVersion}` : "unknown"; + log(`→ updating ${target} (${fromLabel} → ${toLabel})`); + + if (!existsSync(sourceDir)) { + fail( + `pre-built artifact missing at ${sourceDir}.\n` + + ` Reinstall @forgeplan/web or build from source via \`npm run build\`.`, + ); + } + + // FR-002: rmSync follows symlinks; a symlinked .forgeplan-web would + // delete the link's target tree (CWE-59). Refuse before destructive ops. + const targetStat = lstatSync(target); + if (targetStat.isSymbolicLink()) { + fail( + `refusing to follow symlink at ${target}.\n` + + ` \`update\` will not rmSync through a symlinked .forgeplan-web/.\n` + + ` Remove the symlink manually and re-run.`, + ); + } + + // FR-003: defense-in-depth — even though target is constructed from + // join(cwd, '.forgeplan-web'), assert post-resolve equality so any + // future refactor (env override, alias) cannot widen the rmSync blast + // radius beyond the canonical path. + const expected = resolve(join(cwd, ".forgeplan-web")); + if (resolve(target) !== expected) { + fail( + `refusing to rmSync unexpected path ${resolve(target)} (expected ${expected}).`, + ); + } + + rmSync(target, { recursive: true, force: true }); + mkdirSync(target, { recursive: true }); + cpSync(sourceDir, target, { + recursive: true, + dereference: false, + force: true, + }); + + const now = new Date().toISOString(); + const cfg = { + workspaceRoot: existing?.workspaceRoot ?? cwd, + createdAt: existing?.createdAt ?? now, + version: toVersion, + updatedAt: now, + experimental: useExperimental, + }; + writeFileSync(join(target, CFG_FILE), JSON.stringify(cfg, null, 2) + "\n"); + + log(""); + log(`✓ updated to ${toLabel}`); + log(" npx @forgeplan/web start"); + }, +}); diff --git a/bin/forgeplan-web.mjs b/bin/forgeplan-web.mjs index c3b9254..f37be3a 100755 --- a/bin/forgeplan-web.mjs +++ b/bin/forgeplan-web.mjs @@ -1,367 +1,5 @@ #!/usr/bin/env node -import { spawn, spawnSync } from "node:child_process"; -import { - cpSync, - existsSync, - lstatSync, - mkdirSync, - readFileSync, - rmSync, - writeFileSync, -} from "node:fs"; -import { dirname, join, resolve } from "node:path"; -import { fileURLToPath } from "node:url"; -import { printBanner } from "./banner.mjs"; +import { runMain } from "citty"; +import main from "./cli.mjs"; -const __dirname = dirname(fileURLToPath(import.meta.url)); -const PKG_ROOT = resolve(__dirname, ".."); -const DIST_DIR_LEGACY = join(PKG_ROOT, "dist"); -const DIST_DIR_EXPERIMENTAL = join(PKG_ROOT, "dist-experimental"); -const CFG_FILE = "forgeplan-web.json"; - -const argv = process.argv.slice(2); -const positional = argv.filter((a) => !a.startsWith("-")); -const flags = new Set(argv.filter((a) => a.startsWith("-"))); - -const cmd = positional[0] ?? "init"; -const FORCE = flags.has("--force"); -const QUIET = flags.has("-q") || flags.has("--quiet"); -const SKIP_GITIGNORE = flags.has("--no-gitignore"); -// TODO(rfc-013-graduation): remove --experimental and --no-experimental flags -// after the bundled dist has shipped without regressions for ≥2 minor versions. -// At that point: flip default to bundled, drop legacy `dist/` from the tarball, -// drop DIST_DIR_LEGACY constant, drop the dual-path branches in init/update, -// drop `experimental` field from forgeplan-web.json (or keep for back-compat -// reads only). See PRD-014 for graduation criteria. -const EXPERIMENTAL = flags.has("--experimental"); - -// PRD-014 / RFC-013: pick which pre-built artifact to copy. Legacy `dist/` -// stays the default until the bundled shape graduates from --experimental. -const DIST_DIR = EXPERIMENTAL ? DIST_DIR_EXPERIMENTAL : DIST_DIR_LEGACY; - -function log(line) { - if (!QUIET) process.stdout.write(line + "\n"); -} - -function fail(line, code = 1) { - process.stderr.write(`forgeplan-web: ${line}\n`); - process.exit(code); -} - -function copyDir(src, dest) { - if (!existsSync(src)) { - fail( - `pre-built artifact missing at ${src}.\n` + - ` This usually means the npm package was published without a build. ` + - `Reinstall, or build from source via \`npm run build\`.`, - ); - } - if (existsSync(dest) && !FORCE) { - cpSync(src, dest, { - recursive: true, - dereference: false, - force: false, - errorOnExist: false, - }); - } else { - mkdirSync(dest, { recursive: true }); - cpSync(src, dest, { recursive: true, dereference: false, force: true }); - } -} - -function ensureForgeplanWorkspace(cwd) { - const fpDir = join(cwd, ".forgeplan"); - if (!existsSync(fpDir)) { - fail( - `no .forgeplan/ directory found in ${cwd}.\n` + - ` Run \`forgeplan init -y\` here first, then re-run \`npx @forgeplan/web init\`.`, - ); - } -} - -function ensureForgeplanBinary() { - // Windows: `forgeplan` resolves to forgeplan.cmd (npm/scoop install). - // Node spawnSync can't invoke .cmd without shell:true — fails with - // status=null and the error mimics "binary missing", confusing users. - const probe = spawnSync("forgeplan", ["--version"], { - stdio: "ignore", - shell: process.platform === "win32", - }); - if (probe.status !== 0) { - fail( - `\`forgeplan\` binary is not on PATH.\n` + - ` Install it from https://github.com/ForgePlan/forgeplan and re-run.`, - ); - } -} - -function ensureGitignore(cwd) { - if (SKIP_GITIGNORE) return; - - const path = join(cwd, ".gitignore"); - const ENTRY = ".forgeplan-web/"; - const COMMENT = "# generated by @forgeplan/web init"; - const ENTRY_RE = /^[ \t]*\.forgeplan-web\/?[ \t]*$/m; - - if (!existsSync(path)) { - writeFileSync(path, `${COMMENT}\n${ENTRY}\n`); - log(`→ created .gitignore (added ${ENTRY})`); - return; - } - - const content = readFileSync(path, "utf8"); - if (ENTRY_RE.test(content)) { - return; - } - - const sep = content.length === 0 || content.endsWith("\n") ? "" : "\n"; - writeFileSync(path, `${content}${sep}\n${COMMENT}\n${ENTRY}\n`); - log(`→ appended ${ENTRY} to .gitignore`); -} - -function readConfig(target) { - const cfgPath = join(target, CFG_FILE); - if (!existsSync(cfgPath)) return null; - try { - return JSON.parse(readFileSync(cfgPath, "utf8")); - } catch { - return null; - } -} - -function readWorkspaceRoot(target) { - return readConfig(target)?.workspaceRoot ?? null; -} - -function readPkgVersion() { - try { - const pkg = JSON.parse( - readFileSync(join(PKG_ROOT, "package.json"), "utf8"), - ); - return typeof pkg.version === "string" ? pkg.version : null; - } catch { - return null; - } -} - -function init() { - const cwd = process.cwd(); - ensureForgeplanWorkspace(cwd); - ensureForgeplanBinary(); - - if (EXPERIMENTAL) { - log("⚠ Using experimental bundled dist (single-file server, no node_modules/)."); - log(" Report issues at https://github.com/ForgePlan/forgeplan-web/issues"); - } - - const target = join(cwd, ".forgeplan-web"); - const fresh = !existsSync(target); - log(fresh ? `→ creating ${target}` : `→ updating ${target}`); - copyDir(DIST_DIR, target); - - const now = new Date().toISOString(); - const existing = fresh ? null : readConfig(target); - const cfg = { - workspaceRoot: cwd, - createdAt: existing?.createdAt ?? now, - version: readPkgVersion() ?? existing?.version ?? null, - updatedAt: now, - experimental: EXPERIMENTAL, - }; - writeFileSync(join(target, CFG_FILE), JSON.stringify(cfg, null, 2) + "\n"); - - ensureGitignore(cwd); - - log(""); - log("✓ ready (no install needed)"); - log(" npx @forgeplan/web start"); - log(" # or: node .forgeplan-web/index.js"); -} - -function update() { - const cwd = process.cwd(); - ensureForgeplanWorkspace(cwd); - ensureForgeplanBinary(); - - const target = join(cwd, ".forgeplan-web"); - if (!existsSync(target)) { - fail( - `no scaffold at ${target}.\n` + - ` Run \`npx @forgeplan/web init\` first.`, - ); - } - - const existing = readConfig(target); - const fromVersion = existing?.version ?? null; - const toVersion = readPkgVersion(); - - // PRD-014 / RFC-013: pick the same dist shape the user opted into at - // init-time. CLI flag overrides the persisted choice (lets users migrate - // both directions without rm -rf). Falls back to legacy default. - const useExperimental = EXPERIMENTAL || (existing?.experimental === true && !flags.has("--no-experimental")); - const sourceDir = useExperimental ? DIST_DIR_EXPERIMENTAL : DIST_DIR_LEGACY; - - if (!FORCE && fromVersion && toVersion && fromVersion === toVersion) { - log(`✓ already at v${toVersion}`); - log(" Use --force to re-copy anyway."); - return; - } - - const fromLabel = fromVersion ? `v${fromVersion}` : "unknown"; - const toLabel = toVersion ? `v${toVersion}` : "unknown"; - log(`→ updating ${target} (${fromLabel} → ${toLabel})`); - - if (!existsSync(sourceDir)) { - fail( - `pre-built artifact missing at ${sourceDir}.\n` + - ` Reinstall @forgeplan/web or build from source via \`npm run build\`.`, - ); - } - - // FR-002: rmSync follows symlinks; a symlinked .forgeplan-web would - // delete the link's target tree (CWE-59). Refuse before destructive ops. - const targetStat = lstatSync(target); - if (targetStat.isSymbolicLink()) { - fail( - `refusing to follow symlink at ${target}.\n` + - ` \`update\` will not rmSync through a symlinked .forgeplan-web/.\n` + - ` Remove the symlink manually and re-run.`, - ); - } - - // FR-003: defense-in-depth — even though target is constructed from - // join(cwd, '.forgeplan-web'), assert post-resolve equality so any - // future refactor (env override, alias) cannot widen the rmSync blast - // radius beyond the canonical path. - const expected = resolve(join(cwd, ".forgeplan-web")); - if (resolve(target) !== expected) { - fail( - `refusing to rmSync unexpected path ${resolve(target)} (expected ${expected}).`, - ); - } - - rmSync(target, { recursive: true, force: true }); - mkdirSync(target, { recursive: true }); - cpSync(sourceDir, target, { - recursive: true, - dereference: false, - force: true, - }); - - const now = new Date().toISOString(); - const cfg = { - workspaceRoot: existing?.workspaceRoot ?? cwd, - createdAt: existing?.createdAt ?? now, - version: toVersion, - updatedAt: now, - experimental: useExperimental, - }; - writeFileSync(join(target, CFG_FILE), JSON.stringify(cfg, null, 2) + "\n"); - - log(""); - log(`✓ updated to ${toLabel}`); - log(" npx @forgeplan/web start"); -} - -function start() { - const cwd = process.cwd(); - const target = join(cwd, ".forgeplan-web"); - - if (!existsSync(target) || !existsSync(join(target, "index.js"))) { - fail( - `no scaffolded server at ${target}.\n` + - ` Run \`npx @forgeplan/web init\` first.`, - ); - } - - const workspaceRoot = readWorkspaceRoot(target) ?? cwd; - const env = { - ...process.env, - PORT: process.env.PORT ?? "5174", - HOST: process.env.HOST ?? "127.0.0.1", - FORGEPLAN_CWD: process.env.FORGEPLAN_CWD ?? workspaceRoot, - }; - - printBanner({ quiet: QUIET }); - log(`→ starting forgeplan-web on http://${env.HOST}:${env.PORT}`); - log(` workspace: ${env.FORGEPLAN_CWD}`); - - const child = spawn(process.execPath, ["index.js"], { - cwd: target, - env, - stdio: "inherit", - }); - - const forward = (sig) => { - if (!child.killed) child.kill(sig); - }; - process.on("SIGINT", () => forward("SIGINT")); - process.on("SIGTERM", () => forward("SIGTERM")); - - child.on("exit", (code, signal) => { - if (signal) process.exit(0); - process.exit(code ?? 0); - }); -} - -function help() { - log(`@forgeplan/web — interactive realtime map for a Forgeplan workspace - -Usage: - npx @forgeplan/web init [-y] [--force] [--no-gitignore] [--experimental] - npx @forgeplan/web update [--force] [--experimental] [--no-experimental] - npx @forgeplan/web start - npx @forgeplan/web help - -Commands: - init Copy the pre-built SvelteKit app to ./.forgeplan-web/ and - append \`.forgeplan-web/\` to ./.gitignore (idempotent). - --force overwrite files that already exist - --no-gitignore do not touch ./.gitignore - --experimental [EXPERIMENTAL] use the bundled single-file dist - (≈9× smaller, no node_modules/). Stable for - most cases; report regressions on GitHub. - -y accepted for compatibility (init is non-interactive) - - update Refresh ./.forgeplan-web/ to the version bundled with the - currently-resolved \`@forgeplan/web\` package. Removes stale files, - preserves workspaceRoot/createdAt, records new version+updatedAt. - No-op when already current (use --force to re-copy anyway). - Inherits the dist shape recorded at init-time; pass - --experimental / --no-experimental to switch. - Note: any manual edits inside ./.forgeplan-web/ will be lost. - - start Run the SvelteKit server from ./.forgeplan-web/. - Reads PORT (default 5174), HOST (default 127.0.0.1), - FORGEPLAN_CWD (default: workspace recorded by init), - FORGEPLAN_BIN (default: \`forgeplan\` from PATH). - -The init/update commands require: - - a .forgeplan/ workspace in the current directory - - the \`forgeplan\` CLI on PATH - -No npm install runs at user side: the package ships a pre-built artifact. -`); -} - -switch (cmd) { - case "init": - init(); - break; - case "update": - case "upgrade": - update(); - break; - case "start": - case "serve": - case "run": - start(); - break; - case "help": - case "-h": - case "--help": - help(); - break; - default: - fail(`unknown command \`${cmd}\`. Try \`npx @forgeplan/web help\`.`); -} +runMain(main); diff --git a/bin/lib/config.mjs b/bin/lib/config.mjs new file mode 100644 index 0000000..81f2909 --- /dev/null +++ b/bin/lib/config.mjs @@ -0,0 +1,32 @@ +import { existsSync, readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +export const PKG_ROOT = resolve(__dirname, "..", ".."); +export const CFG_FILE = "forgeplan-web.json"; + +export function readConfig(target) { + const cfgPath = join(target, CFG_FILE); + if (!existsSync(cfgPath)) return null; + try { + return JSON.parse(readFileSync(cfgPath, "utf8")); + } catch { + return null; + } +} + +export function readWorkspaceRoot(target) { + return readConfig(target)?.workspaceRoot ?? null; +} + +export function readPkgVersion() { + try { + const pkg = JSON.parse( + readFileSync(join(PKG_ROOT, "package.json"), "utf8"), + ); + return typeof pkg.version === "string" ? pkg.version : null; + } catch { + return null; + } +} diff --git a/bin/lib/forgeplan-binary.mjs b/bin/lib/forgeplan-binary.mjs new file mode 100644 index 0000000..4bd70d1 --- /dev/null +++ b/bin/lib/forgeplan-binary.mjs @@ -0,0 +1,29 @@ +import { spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { join } from "node:path"; + +export function ensureForgeplanWorkspace(cwd, fail) { + const fpDir = join(cwd, ".forgeplan"); + if (!existsSync(fpDir)) { + fail( + `no .forgeplan/ directory found in ${cwd}.\n` + + ` Run \`forgeplan init -y\` here first, then re-run \`npx @forgeplan/web init\`.`, + ); + } +} + +export function ensureForgeplanBinary(fail) { + // Windows: `forgeplan` resolves to forgeplan.cmd (npm/scoop install). + // Node spawnSync can't invoke .cmd without shell:true — fails with + // status=null and the error mimics "binary missing", confusing users. + const probe = spawnSync("forgeplan", ["--version"], { + stdio: "ignore", + shell: process.platform === "win32", + }); + if (probe.status !== 0) { + fail( + `\`forgeplan\` binary is not on PATH.\n` + + ` Install it from https://github.com/ForgePlan/forgeplan and re-run.`, + ); + } +} diff --git a/bin/lib/gitignore.mjs b/bin/lib/gitignore.mjs new file mode 100644 index 0000000..846df95 --- /dev/null +++ b/bin/lib/gitignore.mjs @@ -0,0 +1,26 @@ +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; + +export function ensureGitignore({ cwd, skip = false, log = () => {} }) { + if (skip) return; + + const path = join(cwd, ".gitignore"); + const ENTRY = ".forgeplan-web/"; + const COMMENT = "# generated by @forgeplan/web init"; + const ENTRY_RE = /^[ \t]*\.forgeplan-web\/?[ \t]*$/m; + + if (!existsSync(path)) { + writeFileSync(path, `${COMMENT}\n${ENTRY}\n`); + log(`→ created .gitignore (added ${ENTRY})`); + return; + } + + const content = readFileSync(path, "utf8"); + if (ENTRY_RE.test(content)) { + return; + } + + const sep = content.length === 0 || content.endsWith("\n") ? "" : "\n"; + writeFileSync(path, `${content}${sep}\n${COMMENT}\n${ENTRY}\n`); + log(`→ appended ${ENTRY} to .gitignore`); +} diff --git a/package-lock.json b/package-lock.json index be507f3..06c6674 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,13 +1,16 @@ { "name": "@forgeplan/web", - "version": "0.1.11", + "version": "0.1.13", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@forgeplan/web", - "version": "0.1.11", + "version": "0.1.13", "license": "MIT", + "dependencies": { + "citty": "^0.2.2" + }, "bin": { "forgeplan-web": "bin/forgeplan-web.mjs" }, @@ -443,6 +446,12 @@ "node": ">=18" } }, + "node_modules/citty": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/citty/-/citty-0.2.2.tgz", + "integrity": "sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==", + "license": "MIT" + }, "node_modules/esbuild": { "version": "0.24.2", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.24.2.tgz", diff --git a/package.json b/package.json index e8c3561..3fd10e9 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,9 @@ "prepublishOnly": "node scripts/build.mjs" }, "packageManager": "pnpm@10.18.1+sha512.77a884a165cbba2d8d1c19e3b4880eee6d2fcabd0d879121e282196b80042351d5eb3ca0935fa599da1dc51265cc68816ad2bddd2a2de5ea9fdf92adbec7cd34", + "dependencies": { + "citty": "^0.2.2" + }, "devDependencies": { "esbuild": "^0.24.0" } From 7c4bcecaa9d5a7b1adfc77bf54e45f1cf8048ad4 Mon Sep 17 00:00:00 2001 From: fedorovvvv Date: Fri, 8 May 2026 23:53:17 +0400 Subject: [PATCH 3/7] feat(bin): wire --scope user/project + start fallback chain (#111, #112) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 109b — init now resolves scope from --scope flag, -y default (project), or interactive readline prompt (default user in TTY; --scope required in non-TTY). User scope writes to ~/.forgeplan-web/ and skips host .gitignore. Project scope behavior unchanged. 109c — start follows the resolution chain: explicit --scope wins, else project (cwd/.forgeplan-web/) → user (~/.forgeplan-web/) → prompt-init (or fail in non-TTY). update mirrors the same chain. New helpers: bin/lib/scope.mjs (resolveScope, userScopePath, projectScopePath, findScaffold) and bin/lib/prompt.mjs (readline-based TTY prompt — citty 0.2.2 doesn't expose consola; TODO(109b-prompt) revisits on citty bump). config.mjs gets readScope(). Rule 20 amended: user-scope writes are bounded to ~/.forgeplan-web/ and gitignore-silent. All write-boundary invariants preserved per scope. Smoke: PASS (project scope path; user-scope and resolution chain verified via manual scenarios documented in agent report). Refs: PRD-025, PRD-026, RFC-021, RFC-022 Closes: #111, #112 Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/rules/20-init-host-isolation.md | 63 +++++++--- bin/commands/init.mjs | 156 +++++++++++++++++------- bin/commands/start.mjs | 120 +++++++++++++++--- bin/commands/update.mjs | 92 +++++++++++--- bin/lib/config.mjs | 7 ++ bin/lib/prompt.mjs | 71 +++++++++++ bin/lib/scope.mjs | 64 ++++++++++ 7 files changed, 476 insertions(+), 97 deletions(-) create mode 100644 bin/lib/prompt.mjs create mode 100644 bin/lib/scope.mjs diff --git a/.claude/rules/20-init-host-isolation.md b/.claude/rules/20-init-host-isolation.md index 598edb9..61f719f 100644 --- a/.claude/rules/20-init-host-isolation.md +++ b/.claude/rules/20-init-host-isolation.md @@ -1,11 +1,23 @@ # `init` host isolation -`bin/forgeplan-web.mjs init` runs in the user's project directory. It -MUST write only inside `/.forgeplan-web/`, with **one** narrow -exception: appending an ignore rule for `.forgeplan-web/` to the host's -`.gitignore` (see ADR-001). Every other host write is forbidden. +`bin/forgeplan-web.mjs init` runs in the user's project directory. Its +write boundary depends on the resolved scope (PRD-025 / RFC-021): -## Forbidden writes from `init` +- **Project scope** (`--scope project`, or `-y` without `--scope`, or the + user picks "project" interactively): writes only inside + `/.forgeplan-web/`, with **one** narrow exception — appending an + ignore rule for `.forgeplan-web/` to the host's `.gitignore` (see + ADR-001). Every other host write is forbidden. +- **User scope** (`--scope user`, or the user picks "user" interactively): + writes only inside `~/.forgeplan-web/` (resolved from `os.homedir()`, + per RFC-021 / ADR-004). The host project's `.gitignore` MUST NOT be + touched — the home directory is workspace-agnostic and the user-scope + scaffold is shared across projects, so an "ignore" hint in any + individual project would be misleading. User scope likewise does NOT + require a `.forgeplan/` workspace in the cwd at install time; the + workspace is bound at `start` time via `FORGEPLAN_CWD`. + +## Forbidden writes from `init` (both scopes) - The host's `package.json`, `pnpm-lock.yaml`, `package-lock.json`, `yarn.lock`. @@ -13,15 +25,23 @@ exception: appending an ignore rule for `.forgeplan-web/` to the host's - The host's `node_modules/`. - The host's `.forgeplan/` (the workspace is *read* via the bundled `forgeplan` CLI; never written by us). -- Any file outside `/.forgeplan-web/` other than the single - `.gitignore` exception below. +- Under `--scope user`: the host's `.gitignore` MUST NOT be created, + read-then-rewritten, or appended. User scope is gitignore-silent. +- Any file outside the resolved target directory (project: `/.forgeplan-web/`, + user: `~/.forgeplan-web/`) other than the single `.gitignore` + exception below — and that exception applies to project scope only. ## Allowed writes -- Anything inside `/.forgeplan-web/`. -- `/.forgeplan-web/forgeplan-web.json` (workspace pointer the - SvelteKit server reads at runtime). -- `/.gitignore` — **append-only**, with these constraints: +- **Project scope** only: anything inside `/.forgeplan-web/`, + including `/.forgeplan-web/forgeplan-web.json` (workspace pointer + the SvelteKit server reads at runtime). +- **User scope** only: anything inside `~/.forgeplan-web/`, including + `~/.forgeplan-web/forgeplan-web.json`. The `workspaceRoot` field in + the user-scope config is `null` at init-time (the user-scope dist is + workspace-agnostic; `start` binds the workspace from cwd or + `FORGEPLAN_CWD` at runtime). +- **Project scope** only: `/.gitignore` — **append-only**, with these constraints: - Add at most one ignore line: `.forgeplan-web/`. - The append is idempotent. Detection regex per line: `^[ \t]*\.forgeplan-web\/?[ \t]*$`. If a matching line is already @@ -46,13 +66,18 @@ idempotent, reversible, and opt-out — see ADR-001. ## Verification -- `git status` in the host project after `init` must show changes only - inside `.forgeplan-web/` and (at most) a single appended block at the - end of `.gitignore`. -- The `init()` function in `bin/forgeplan-web.mjs` must not call - `writeFileSync` / `copyFileSync` / `mkdirSync` with any path that - does not resolve under `target` (`.forgeplan-web/`) or under the - host's `.gitignore`. -- Running `init` twice must not duplicate the `.gitignore` entry. +- After `init -y` or `init --scope project`: `git status` in the host + project must show changes only inside `.forgeplan-web/` and (at most) + a single appended block at the end of `.gitignore`. +- After `init --scope user`: `git status` in the cwd must show **no** + changes at all. All writes land under `~/.forgeplan-web/`. +- `runInit()` in `bin/commands/init.mjs` must not call `writeFileSync` + / `copyFileSync` / `mkdirSync` with any path that does not resolve + under the resolved scope target (`/.forgeplan-web/` or + `~/.forgeplan-web/`) — and, only under project scope, the host's + `.gitignore`. +- Running `init -y` twice must not duplicate the `.gitignore` entry. - Running `init -y --no-gitignore` must not touch `.gitignore` at all (no create, no append, no read-then-rewrite). +- `ensureGitignore` is called from `runInit` only when `scope === + "project"`; user-scope code paths must not even invoke it. diff --git a/bin/commands/init.mjs b/bin/commands/init.mjs index 0fe18e4..95e65f2 100644 --- a/bin/commands/init.mjs +++ b/bin/commands/init.mjs @@ -12,6 +12,13 @@ import { ensureForgeplanWorkspace, } from "../lib/forgeplan-binary.mjs"; import { ensureGitignore } from "../lib/gitignore.mjs"; +import { promptScope } from "../lib/prompt.mjs"; +import { + isValidScope, + projectScopePath, + scopePath, + userScopePath, +} from "../lib/scope.mjs"; const DIST_DIR_LEGACY = join(PKG_ROOT, "dist"); const DIST_DIR_EXPERIMENTAL = join(PKG_ROOT, "dist-experimental"); @@ -42,16 +49,84 @@ function copyDir(src, dest, force) { } } +export async function runInit({ + scope, + force = false, + quiet = false, + skipGitignore = false, + experimental = false, + cwd = process.cwd(), +} = {}) { + if (!isValidScope(scope)) { + fail(`internal: runInit called with invalid scope "${scope}"`); + } + + const log = (line) => { + if (!quiet) process.stdout.write(line + "\n"); + }; + + const DIST_DIR = experimental ? DIST_DIR_EXPERIMENTAL : DIST_DIR_LEGACY; + + if (scope === "project") { + ensureForgeplanWorkspace(cwd, fail); + } + ensureForgeplanBinary(fail); + + if (experimental) { + log( + "⚠ Using experimental bundled dist (single-file server, no node_modules/).", + ); + log( + " Report issues at https://github.com/ForgePlan/forgeplan-web/issues", + ); + } + + const target = scopePath(scope, cwd); + const fresh = !existsSync(target); + log(fresh ? `→ creating ${target}` : `→ updating ${target}`); + copyDir(DIST_DIR, target, force); + + const now = new Date().toISOString(); + const existing = fresh ? null : readConfig(target); + const cfg = { + workspaceRoot: scope === "project" ? cwd : (existing?.workspaceRoot ?? null), + createdAt: existing?.createdAt ?? now, + version: readPkgVersion() ?? existing?.version ?? null, + updatedAt: now, + experimental, + scope, + }; + writeFileSync(join(target, CFG_FILE), JSON.stringify(cfg, null, 2) + "\n"); + + if (scope === "project") { + ensureGitignore({ cwd, skip: skipGitignore, log }); + } + + log(""); + log( + scope === "user" + ? `✓ ready (scope: user — ${userScopePath()})` + : `✓ ready (scope: project — ${projectScopePath(cwd)})`, + ); + log(" npx @forgeplan/web start"); + if (scope === "project") { + log(" # or: node .forgeplan-web/index.js"); + } + + return { scope, target }; +} + export default defineCommand({ meta: { name: "init", description: - "Copy the pre-built SvelteKit app to ./.forgeplan-web/ and append `.forgeplan-web/` to ./.gitignore (idempotent).", + "Copy the pre-built SvelteKit app into a project- or user-scope `.forgeplan-web/`.", }, args: { y: { type: "boolean", - description: "accepted for compatibility (init is non-interactive)", + description: + "non-interactive mode (defaults --scope to project for backwards compat)", }, force: { type: "boolean", @@ -66,68 +141,61 @@ export default defineCommand({ type: "boolean", default: true, description: - "append `.forgeplan-web/` to ./.gitignore (default true; pass --no-gitignore to skip)", + "append `.forgeplan-web/` to ./.gitignore (project scope only; pass --no-gitignore to skip)", }, experimental: { type: "boolean", description: "[EXPERIMENTAL] use the bundled single-file dist (~9x smaller, no node_modules/)", }, - // TODO(109b): scope flag declared, not yet consumed — see PRD-025 scope: { type: "string", description: - "[reserved for PRD-025] scope of the scaffold: user|project (no-op in this release)", + "scope of the scaffold: user (~/.forgeplan-web/) or project (./.forgeplan-web/)", valueHint: "user|project", }, }, async run({ args }) { const QUIET = args.quiet === true; const FORCE = args.force === true; - // citty: --no-gitignore parses to args.gitignore = false; default is true. + const YES = args.y === true; const SKIP_GITIGNORE = args.gitignore === false; const EXPERIMENTAL = args.experimental === true; - const log = (line) => { - if (!QUIET) process.stdout.write(line + "\n"); - }; - - const DIST_DIR = EXPERIMENTAL ? DIST_DIR_EXPERIMENTAL : DIST_DIR_LEGACY; - - const cwd = process.cwd(); - ensureForgeplanWorkspace(cwd, fail); - ensureForgeplanBinary(fail); - - if (EXPERIMENTAL) { - log( - "⚠ Using experimental bundled dist (single-file server, no node_modules/).", - ); - log( - " Report issues at https://github.com/ForgePlan/forgeplan-web/issues", - ); + let scope = null; + if (args.scope) { + if (!isValidScope(args.scope)) { + fail( + `invalid --scope value "${args.scope}"; expected "user" or "project".`, + ); + } + scope = args.scope; + } else if (YES) { + // FR-005: zero-config preservation — `init -y` (no --scope) keeps + // writing project-scope so existing scripts and CI keep working. + scope = "project"; + } else { + // FR-003 / FR-004: interactive TTY → prompt with default = user. + // FR-009: non-TTY without --scope or -y → fail fast (handled inside + // promptScope via ENOTTY). + try { + scope = await promptScope({ defaultChoice: "user" }); + } catch (err) { + if (err && err.code === "ENOTTY") { + fail( + `no TTY detected; pass \`--scope user|project\` explicitly (or \`-y\` for project default).`, + ); + } + throw err; + } } - const target = join(cwd, ".forgeplan-web"); - const fresh = !existsSync(target); - log(fresh ? `→ creating ${target}` : `→ updating ${target}`); - copyDir(DIST_DIR, target, FORCE); - - const now = new Date().toISOString(); - const existing = fresh ? null : readConfig(target); - const cfg = { - workspaceRoot: cwd, - createdAt: existing?.createdAt ?? now, - version: readPkgVersion() ?? existing?.version ?? null, - updatedAt: now, + await runInit({ + scope, + force: FORCE, + quiet: QUIET, + skipGitignore: SKIP_GITIGNORE, experimental: EXPERIMENTAL, - }; - writeFileSync(join(target, CFG_FILE), JSON.stringify(cfg, null, 2) + "\n"); - - ensureGitignore({ cwd, skip: SKIP_GITIGNORE, log }); - - log(""); - log("✓ ready (no install needed)"); - log(" npx @forgeplan/web start"); - log(" # or: node .forgeplan-web/index.js"); + }); }, }); diff --git a/bin/commands/start.mjs b/bin/commands/start.mjs index 3aa21e5..c92d1f6 100644 --- a/bin/commands/start.mjs +++ b/bin/commands/start.mjs @@ -1,20 +1,69 @@ import { defineCommand } from "citty"; import { spawn } from "node:child_process"; import { existsSync } from "node:fs"; -import { join } from "node:path"; import { printBanner } from "../banner.mjs"; -import { readWorkspaceRoot } from "../lib/config.mjs"; +import { readConfig } from "../lib/config.mjs"; +import { promptConfirm, promptScope } from "../lib/prompt.mjs"; +import { + findScaffold, + isValidScope, + projectScopePath, + userScopePath, +} from "../lib/scope.mjs"; +import { runInit } from "./init.mjs"; function fail(line, code = 1) { process.stderr.write(`forgeplan-web: ${line}\n`); process.exit(code); } +function isInteractiveTTY() { + return Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY); +} + +async function handleEmptyState({ cwd, log }) { + const projPath = projectScopePath(cwd); + const userPath = userScopePath(); + + if (!isInteractiveTTY()) { + fail( + `no scaffold found at ${projPath} or ${userPath}.\n` + + ` Run \`npx @forgeplan/web init [--scope user|project]\` first.`, + ); + } + + log(`No scaffold found at ${projPath} or ${userPath}.`); + let confirmed = false; + try { + confirmed = await promptConfirm({ + message: "Run `init` now?", + defaultYes: true, + }); + } catch (err) { + if (err && err.code === "ENOTTY") { + fail( + `no scaffold found at ${projPath} or ${userPath}.\n` + + ` Run \`npx @forgeplan/web init [--scope user|project]\` first.`, + ); + } + throw err; + } + if (!confirmed) { + fail( + `aborted; run \`npx @forgeplan/web init [--scope user|project]\` when ready.`, + ); + } + + const chosenScope = await promptScope({ defaultChoice: "user" }); + const result = await runInit({ scope: chosenScope, cwd }); + return findScaffold({ cwd, scope: result.scope }); +} + export default defineCommand({ meta: { name: "start", description: - "Run the SvelteKit server from ./.forgeplan-web/. Reads PORT, HOST, FORGEPLAN_CWD, FORGEPLAN_BIN env vars.", + "Run the SvelteKit server from the resolved `.forgeplan-web/` (project → user → prompt). Reads PORT, HOST, FORGEPLAN_CWD, FORGEPLAN_BIN env vars.", alias: ["serve", "run"], }, args: { @@ -23,11 +72,10 @@ export default defineCommand({ alias: "q", description: "suppress banner and informational output", }, - // TODO(109b): scope flag declared, not yet consumed — see PRD-025 scope: { type: "string", description: - "[reserved for PRD-025] scope of the instance: user|project (no-op in this release)", + "force a specific scope: user (~/.forgeplan-web/) or project (./.forgeplan-web/); fails if absent", valueHint: "user|project", }, }, @@ -38,16 +86,61 @@ export default defineCommand({ }; const cwd = process.cwd(); - const target = join(cwd, ".forgeplan-web"); - if (!existsSync(target) || !existsSync(join(target, "index.js"))) { - fail( - `no scaffolded server at ${target}.\n` + - ` Run \`npx @forgeplan/web init\` first.`, - ); + let explicitScope = null; + if (args.scope) { + if (!isValidScope(args.scope)) { + fail( + `invalid --scope value "${args.scope}"; expected "user" or "project".`, + ); + } + explicitScope = args.scope; } - const workspaceRoot = readWorkspaceRoot(target) ?? cwd; + let scaffold; + if (explicitScope === "project") { + scaffold = findScaffold({ cwd, scope: "project" }); + if (!scaffold) { + fail( + `--scope project: no scaffold at ${projectScopePath(cwd)}.\n` + + ` Run \`npx @forgeplan/web init --scope project\` first.`, + ); + } + } else if (explicitScope === "user") { + scaffold = findScaffold({ cwd, scope: "user" }); + if (!scaffold) { + fail( + `--scope user: no scaffold at ${userScopePath()}.\n` + + ` Run \`npx @forgeplan/web init --scope user\` first.`, + ); + } + } else { + // implicit chain: project → user → prompt-init + scaffold = findScaffold({ cwd }); + if (!scaffold) { + scaffold = await handleEmptyState({ cwd, log }); + if (!scaffold) { + // TODO(109c-empty-after-init): findScaffold returned null right + // after a successful runInit — likely a race or path mismatch. + fail("scaffold missing after init; please re-run `start` manually."); + } + } + } + + const target = scaffold.path; + if (!existsSync(target)) { + fail(`internal: resolved scaffold path ${target} does not exist.`); + } + + const cfg = readConfig(target); + // For project-scope the workspace IS the cwd at init-time. For user-scope + // the workspace is wherever the user is now (the user-scope dist is + // workspace-agnostic). Env override always wins (existing contract). + const workspaceRoot = + scaffold.scope === "user" + ? cwd + : (cfg?.workspaceRoot ?? cwd); + const env = { ...process.env, PORT: process.env.PORT ?? "5174", @@ -56,6 +149,7 @@ export default defineCommand({ }; printBanner({ quiet: QUIET }); + log(`→ scope: ${scaffold.scope} (${target})`); log(`→ starting forgeplan-web on http://${env.HOST}:${env.PORT}`); log(` workspace: ${env.FORGEPLAN_CWD}`); @@ -71,8 +165,6 @@ export default defineCommand({ process.on("SIGINT", () => forward("SIGINT")); process.on("SIGTERM", () => forward("SIGTERM")); - // Wrap in a Promise so citty's runMain awaits the child's exit - // before terminating; otherwise process.exit in the listener races. return new Promise(() => { child.on("exit", (code, signal) => { if (signal) process.exit(0); diff --git a/bin/commands/update.mjs b/bin/commands/update.mjs index 9704a6d..fcc9ffa 100644 --- a/bin/commands/update.mjs +++ b/bin/commands/update.mjs @@ -18,6 +18,12 @@ import { ensureForgeplanBinary, ensureForgeplanWorkspace, } from "../lib/forgeplan-binary.mjs"; +import { + isValidScope, + projectScopePath, + scopePath, + userScopePath, +} from "../lib/scope.mjs"; const DIST_DIR_LEGACY = join(PKG_ROOT, "dist"); const DIST_DIR_EXPERIMENTAL = join(PKG_ROOT, "dist-experimental"); @@ -27,11 +33,48 @@ function fail(line, code = 1) { process.exit(code); } +function resolveTargetForUpdate({ explicitScope, cwd }) { + if (explicitScope === "user") { + const root = userScopePath(); + if (!existsSync(root)) { + fail( + `--scope user: no scaffold at ${root}.\n` + + ` Run \`npx @forgeplan/web init --scope user\` first.`, + ); + } + return { scope: "user", target: root }; + } + if (explicitScope === "project") { + const root = projectScopePath(cwd); + if (!existsSync(root)) { + fail( + `--scope project: no scaffold at ${root}.\n` + + ` Run \`npx @forgeplan/web init --scope project\` first.`, + ); + } + return { scope: "project", target: root }; + } + // implicit: prefer project-scope in cwd; fall back to user-scope. + const projectRoot = projectScopePath(cwd); + if (existsSync(projectRoot)) { + return { scope: "project", target: projectRoot }; + } + const userRoot = userScopePath(); + if (existsSync(userRoot)) { + return { scope: "user", target: userRoot }; + } + fail( + `no scaffold found at ${projectRoot} or ${userRoot}.\n` + + ` Run \`npx @forgeplan/web init [--scope user|project]\` first.`, + ); + return null; // unreachable; fail() exits +} + export default defineCommand({ meta: { name: "update", description: - "Refresh ./.forgeplan-web/ to the version bundled with the currently-resolved @forgeplan/web package.", + "Refresh a `.forgeplan-web/` scaffold (project- or user-scope) to the version bundled with the currently-resolved @forgeplan/web package.", alias: ["upgrade"], }, args: { @@ -49,11 +92,10 @@ export default defineCommand({ description: "switch to the experimental bundled dist (overrides persisted choice)", }, - // TODO(109b): scope flag declared, not yet consumed — see PRD-025 scope: { type: "string", description: - "[reserved for PRD-025] scope of the scaffold: user|project (no-op in this release)", + "scope of the scaffold to update: user (~/.forgeplan-web/) or project (./.forgeplan-web/)", valueHint: "user|project", }, }, @@ -65,17 +107,26 @@ export default defineCommand({ if (!QUIET) process.stdout.write(line + "\n"); }; + let explicitScope = null; + if (args.scope) { + if (!isValidScope(args.scope)) { + fail( + `invalid --scope value "${args.scope}"; expected "user" or "project".`, + ); + } + explicitScope = args.scope; + } + const cwd = process.cwd(); - ensureForgeplanWorkspace(cwd, fail); - ensureForgeplanBinary(fail); + const { scope, target } = resolveTargetForUpdate({ + explicitScope, + cwd, + }); - const target = join(cwd, ".forgeplan-web"); - if (!existsSync(target)) { - fail( - `no scaffold at ${target}.\n` + - ` Run \`npx @forgeplan/web init\` first.`, - ); + if (scope === "project") { + ensureForgeplanWorkspace(cwd, fail); } + ensureForgeplanBinary(fail); const existing = readConfig(target); const fromVersion = existing?.version ?? null; @@ -94,14 +145,14 @@ export default defineCommand({ : DIST_DIR_LEGACY; if (!FORCE && fromVersion && toVersion && fromVersion === toVersion) { - log(`✓ already at v${toVersion}`); + log(`✓ already at v${toVersion} (scope: ${scope})`); log(" Use --force to re-copy anyway."); return; } const fromLabel = fromVersion ? `v${fromVersion}` : "unknown"; const toLabel = toVersion ? `v${toVersion}` : "unknown"; - log(`→ updating ${target} (${fromLabel} → ${toLabel})`); + log(`→ updating ${target} (${fromLabel} → ${toLabel}, scope: ${scope})`); if (!existsSync(sourceDir)) { fail( @@ -121,11 +172,10 @@ export default defineCommand({ ); } - // FR-003: defense-in-depth — even though target is constructed from - // join(cwd, '.forgeplan-web'), assert post-resolve equality so any - // future refactor (env override, alias) cannot widen the rmSync blast - // radius beyond the canonical path. - const expected = resolve(join(cwd, ".forgeplan-web")); + // FR-003: defense-in-depth — assert the resolved target equals one of + // the two canonical scope paths before destructive ops, so any future + // refactor cannot widen the rmSync blast radius. + const expected = resolve(scopePath(scope, cwd)); if (resolve(target) !== expected) { fail( `refusing to rmSync unexpected path ${resolve(target)} (expected ${expected}).`, @@ -142,16 +192,18 @@ export default defineCommand({ const now = new Date().toISOString(); const cfg = { - workspaceRoot: existing?.workspaceRoot ?? cwd, + workspaceRoot: + scope === "project" ? cwd : (existing?.workspaceRoot ?? null), createdAt: existing?.createdAt ?? now, version: toVersion, updatedAt: now, experimental: useExperimental, + scope, }; writeFileSync(join(target, CFG_FILE), JSON.stringify(cfg, null, 2) + "\n"); log(""); - log(`✓ updated to ${toLabel}`); + log(`✓ updated to ${toLabel} (scope: ${scope})`); log(" npx @forgeplan/web start"); }, }); diff --git a/bin/lib/config.mjs b/bin/lib/config.mjs index 81f2909..36ecbba 100644 --- a/bin/lib/config.mjs +++ b/bin/lib/config.mjs @@ -20,6 +20,13 @@ export function readWorkspaceRoot(target) { return readConfig(target)?.workspaceRoot ?? null; } +export function readScope(target) { + const cfg = readConfig(target); + if (!cfg) return null; + if (cfg.scope === "user" || cfg.scope === "project") return cfg.scope; + return null; +} + export function readPkgVersion() { try { const pkg = JSON.parse( diff --git a/bin/lib/prompt.mjs b/bin/lib/prompt.mjs new file mode 100644 index 0000000..2f33afd --- /dev/null +++ b/bin/lib/prompt.mjs @@ -0,0 +1,71 @@ +import { createInterface } from "node:readline/promises"; +import { stdin as input, stdout as output } from "node:process"; +import { userScopePath, projectScopePath } from "./scope.mjs"; + +// TODO(109b-prompt): citty 0.2.2 does not export `prompt` or `consola`, and +// `consola` is not a transitive dep of citty in this lockfile (rule 23 — bin +// must stay zero third-party). Using node:readline/promises until citty bumps +// to a version that re-exports a prompt helper. RFC-021 §"Proposed Direction" +// references `import { prompt } from 'citty'` which does not exist yet. + +const SCOPE_OPTIONS = ["user", "project"]; + +function isInteractiveTTY() { + return Boolean(input.isTTY) && Boolean(output.isTTY); +} + +export async function promptScope({ defaultChoice = "user" } = {}) { + if (!isInteractiveTTY()) { + const err = new Error( + "no TTY detected; pass `--scope user|project` (or `-y` for project default).", + ); + err.code = "ENOTTY"; + throw err; + } + if (!SCOPE_OPTIONS.includes(defaultChoice)) { + defaultChoice = "user"; + } + + const userPath = userScopePath(); + const projPath = projectScopePath(process.cwd()); + const lines = [ + "Where to install the forgeplan-web scaffold?", + ` 1) user — ${userPath}${defaultChoice === "user" ? " (default)" : ""}`, + ` 2) project — ${projPath}${defaultChoice === "project" ? " (default)" : ""}`, + "", + ]; + output.write(lines.join("\n")); + + const rl = createInterface({ input, output }); + try { + const ans = ( + await rl.question(`scope [${defaultChoice}]: `) + ) + .trim() + .toLowerCase(); + if (ans === "") return defaultChoice; + if (ans === "1" || ans === "u" || ans === "user") return "user"; + if (ans === "2" || ans === "p" || ans === "project") return "project"; + output.write(`invalid choice "${ans}"; using default "${defaultChoice}".\n`); + return defaultChoice; + } finally { + rl.close(); + } +} + +export async function promptConfirm({ message, defaultYes = true } = {}) { + if (!isInteractiveTTY()) { + const err = new Error("no TTY detected; cannot prompt for confirmation."); + err.code = "ENOTTY"; + throw err; + } + const rl = createInterface({ input, output }); + const hint = defaultYes ? "Y/n" : "y/N"; + try { + const ans = (await rl.question(`${message} [${hint}]: `)).trim().toLowerCase(); + if (ans === "") return defaultYes; + return ans === "y" || ans === "yes"; + } finally { + rl.close(); + } +} diff --git a/bin/lib/scope.mjs b/bin/lib/scope.mjs new file mode 100644 index 0000000..4247db6 --- /dev/null +++ b/bin/lib/scope.mjs @@ -0,0 +1,64 @@ +import { existsSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { CFG_FILE } from "./config.mjs"; + +export const SCAFFOLD_DIRNAME = ".forgeplan-web"; + +export function userScopePath() { + return join(homedir(), SCAFFOLD_DIRNAME); +} + +export function projectScopePath(cwd) { + return join(cwd, SCAFFOLD_DIRNAME); +} + +export function scopePath(scope, cwd) { + if (scope === "user") return userScopePath(); + if (scope === "project") return projectScopePath(cwd); + throw new Error(`unknown scope: ${scope}`); +} + +export function isValidScope(s) { + return s === "user" || s === "project"; +} + +export function probeScaffold(root) { + if (!root || !existsSync(root)) return null; + if (!existsSync(join(root, "index.js"))) return null; + return { + path: root, + configPath: join(root, CFG_FILE), + }; +} + +export function findScaffold({ cwd, scope }) { + if (scope === "project") { + const p = projectScopePath(cwd); + const hit = probeScaffold(p); + return hit ? { ...hit, scope: "project" } : null; + } + if (scope === "user") { + const p = userScopePath(); + const hit = probeScaffold(p); + return hit ? { ...hit, scope: "user" } : null; + } + const proj = probeScaffold(projectScopePath(cwd)); + if (proj) return { ...proj, scope: "project" }; + const usr = probeScaffold(userScopePath()); + if (usr) return { ...usr, scope: "user" }; + return null; +} + +export function resolveScope({ explicit, yes }) { + if (explicit !== undefined && explicit !== null && explicit !== "") { + if (!isValidScope(explicit)) { + throw new Error( + `invalid --scope value "${explicit}"; expected "user" or "project"`, + ); + } + return explicit; + } + if (yes) return "project"; + return null; +} From e690f4fdb025eac2557f37b843d24030e4813c7d Mon Sep 17 00:00:00 2001 From: fedorovvvv Date: Fri, 8 May 2026 23:53:27 +0400 Subject: [PATCH 4/7] feat(ui): Combobox primitive in shared/ui (#114) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Port bits-ui Combobox (v2.18.1) into template/src/shared/ui/combobox/ mirroring the Select primitive shape: 5 sub-components (Combobox, ComboboxTrigger, ComboboxContent, ComboboxItem, ComboboxInput) + barrel index.ts. Re-exported from shared/ui/index.ts by name. Variants: default, mono. Sizes: sm, md. Pure CSS via app.css tokens (--bg, --bg-1, --bg-2, --fg, --fg-1, --accent, --line, ...) — works across light/dark/orch themes with no caller intervention. A11y: role=combobox / aria-expanded / aria-controls on trigger, role=listbox on content, role=option / aria-selected on items, focus-visible accent ring matching Select pattern. Keyboard: arrow-up/down navigation, Enter to select, Escape to close. /playground showcases all 4 variant×size combinations under the existing primitive grid; theme toggle in playground header swaps visuals automatically. svelte-check: 1053 files / 0 errors / 0 warnings. Rule-24 grep: clean (no upper-layer reaches into primitive internals). Build green; dist-experimental at 2.47M (under 3M cap). Refs: PRD-028, RFC-024 Closes: #114 Co-Authored-By: Claude Opus 4.7 (1M context) --- template/src/routes/playground/+page.svelte | 89 +++++++++++++ template/src/shared/ui/README.md | 1 + .../src/shared/ui/combobox/Combobox.svelte | 89 +++++++++++++ .../shared/ui/combobox/ComboboxContent.svelte | 64 ++++++++++ .../shared/ui/combobox/ComboboxInput.svelte | 72 +++++++++++ .../shared/ui/combobox/ComboboxItem.svelte | 118 ++++++++++++++++++ .../shared/ui/combobox/ComboboxTrigger.svelte | 100 +++++++++++++++ template/src/shared/ui/combobox/index.ts | 6 + template/src/shared/ui/index.ts | 9 ++ 9 files changed, 548 insertions(+) create mode 100644 template/src/shared/ui/combobox/Combobox.svelte create mode 100644 template/src/shared/ui/combobox/ComboboxContent.svelte create mode 100644 template/src/shared/ui/combobox/ComboboxInput.svelte create mode 100644 template/src/shared/ui/combobox/ComboboxItem.svelte create mode 100644 template/src/shared/ui/combobox/ComboboxTrigger.svelte create mode 100644 template/src/shared/ui/combobox/index.ts diff --git a/template/src/routes/playground/+page.svelte b/template/src/routes/playground/+page.svelte index 410aced..3375fa0 100644 --- a/template/src/routes/playground/+page.svelte +++ b/template/src/routes/playground/+page.svelte @@ -13,6 +13,13 @@ Collapsible, CollapsibleContent, CollapsibleTrigger, + Combobox, + ComboboxContent, + ComboboxInput, + ComboboxItem, + ComboboxTrigger, + type ComboboxSize, + type ComboboxVariant, Command, CommandEmpty, CommandGroup, @@ -63,6 +70,28 @@ let inputValue = $state(''); let invalidValue = $state('not-an-email'); let cmdValue = $state(''); + + const comboboxOptions: { value: string; label: string }[] = [ + { value: 'project-a', label: 'Project A' }, + { value: 'project-b', label: 'Project B' }, + { value: 'repo-x', label: 'Repo X' }, + { value: 'repo-y', label: 'Repo Y' }, + { value: 'workspace-z', label: 'Workspace Z' }, + { value: 'forgeplan-web', label: 'forgeplan-web' }, + { value: 'forgeplan-cli', label: 'forgeplan-cli' }, + ]; + const comboboxMatrix: { variant: ComboboxVariant; size: ComboboxSize }[] = [ + { variant: 'default', size: 'sm' }, + { variant: 'default', size: 'md' }, + { variant: 'mono', size: 'sm' }, + { variant: 'mono', size: 'md' }, + ]; + let comboboxValues = $state>({ + 'default-sm': '', + 'default-md': '', + 'mono-sm': '', + 'mono-md': '', + });
@@ -345,6 +374,45 @@

Selected value: {cmdValue || '—'}

+ +
+

Combobox

+ +

+ Searchable single-select dropdown built on bits-ui's Combobox. + Type to filter; Arrow keys navigate; Enter selects; Escape closes. +

+
+ {#each comboboxMatrix as combo (`${combo.variant}-${combo.size}`)} + {@const key = `${combo.variant}-${combo.size}`} + {@const current = comboboxValues[key] ?? ''} + {@const active = comboboxOptions.find((o) => o.value === current)} +
+ + variant={combo.variant} · size={combo.size} + + (comboboxValues[key] = v)} + ariaLabel={`Combobox ${combo.variant} ${combo.size}`} + > + + {active?.label ?? 'Pick…'} + + + + {#each comboboxOptions as opt (opt.value)} + + {/each} + + +
+ {/each} +
+
+
@@ -425,4 +493,25 @@ border-radius: 3px; font-size: 11px; } + + .cb-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); + gap: 14px; + margin-top: 12px; + } + + .cb-tile { + display: flex; + flex-direction: column; + gap: 6px; + padding: 10px; + border: 1px dashed var(--line); + border-radius: 4px; + } + + .cb-tile-label { + color: var(--fg-3); + font-size: 11px; + } diff --git a/template/src/shared/ui/README.md b/template/src/shared/ui/README.md index dd80f44..f1102b5 100644 --- a/template/src/shared/ui/README.md +++ b/template/src/shared/ui/README.md @@ -77,6 +77,7 @@ The `modalManager` *service* itself lives under | Primitive | Import | Notes | |-----------------|-----------------------------------------------------------------------------------------|-----------------------------| | `Command` | `Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandSeparator, Item`| Filtered list with keyboard nav | +| `Combobox` | `Combobox, ComboboxTrigger, ComboboxContent, ComboboxInput, ComboboxItem` | Searchable single-select dropdown wrapping bits-ui Combobox; `variant` (default/**mono**), `size` (sm/md); arrow / Enter / Escape / type-to-filter | ### Existing primitives (pre-PRD-018) diff --git a/template/src/shared/ui/combobox/Combobox.svelte b/template/src/shared/ui/combobox/Combobox.svelte new file mode 100644 index 0000000..4812134 --- /dev/null +++ b/template/src/shared/ui/combobox/Combobox.svelte @@ -0,0 +1,89 @@ + + + + +
+ + {@render children?.()} + +
+ + diff --git a/template/src/shared/ui/combobox/ComboboxContent.svelte b/template/src/shared/ui/combobox/ComboboxContent.svelte new file mode 100644 index 0000000..eb6720f --- /dev/null +++ b/template/src/shared/ui/combobox/ComboboxContent.svelte @@ -0,0 +1,64 @@ + + + + + + {@render children?.()} + + + + + diff --git a/template/src/shared/ui/combobox/ComboboxInput.svelte b/template/src/shared/ui/combobox/ComboboxInput.svelte new file mode 100644 index 0000000..3784f6a --- /dev/null +++ b/template/src/shared/ui/combobox/ComboboxInput.svelte @@ -0,0 +1,72 @@ + + + + + diff --git a/template/src/shared/ui/combobox/ComboboxItem.svelte b/template/src/shared/ui/combobox/ComboboxItem.svelte new file mode 100644 index 0000000..54183cf --- /dev/null +++ b/template/src/shared/ui/combobox/ComboboxItem.svelte @@ -0,0 +1,118 @@ + + + + {#snippet children({ selected })} + + + {#if childrenSnippet} + {@render childrenSnippet()} + {:else} + {label ?? value} + {/if} + + {#if hint} + {hint} + {/if} + + {/snippet} + + + diff --git a/template/src/shared/ui/combobox/ComboboxTrigger.svelte b/template/src/shared/ui/combobox/ComboboxTrigger.svelte new file mode 100644 index 0000000..c0f7457 --- /dev/null +++ b/template/src/shared/ui/combobox/ComboboxTrigger.svelte @@ -0,0 +1,100 @@ + + + + + {@render children?.()} + + + + + diff --git a/template/src/shared/ui/combobox/index.ts b/template/src/shared/ui/combobox/index.ts new file mode 100644 index 0000000..b792eb8 --- /dev/null +++ b/template/src/shared/ui/combobox/index.ts @@ -0,0 +1,6 @@ +export { default as Combobox } from './Combobox.svelte'; +export { default as ComboboxTrigger } from './ComboboxTrigger.svelte'; +export { default as ComboboxContent } from './ComboboxContent.svelte'; +export { default as ComboboxItem } from './ComboboxItem.svelte'; +export { default as ComboboxInput } from './ComboboxInput.svelte'; +export type { ComboboxVariant, ComboboxSize } from './Combobox.svelte'; diff --git a/template/src/shared/ui/index.ts b/template/src/shared/ui/index.ts index fcc9a7e..2285a25 100644 --- a/template/src/shared/ui/index.ts +++ b/template/src/shared/ui/index.ts @@ -7,6 +7,15 @@ export { Card } from './card'; export { Checkbox } from './checkbox'; export { Code } from './code'; export { Collapsible, CollapsibleTrigger, CollapsibleContent } from './collapsible'; +export { + Combobox, + ComboboxTrigger, + ComboboxContent, + ComboboxItem, + ComboboxInput, + type ComboboxVariant, + type ComboboxSize, +} from './combobox'; export { Command, CommandInput, From 4f7b409b65cda0248b22bac2235367b7c2783144 Mon Sep 17 00:00:00 2001 From: fedorovvvv Date: Sat, 9 May 2026 00:02:48 +0400 Subject: [PATCH 5/7] feat(registry): multi-instance registry + /api/instances endpoint (#113) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 109d — register every running forgeplan-web instance in ~/.forgeplan-web/instances.json so the UI (Wave 6) can list and switch between them. Single global registry regardless of scaffold scope. bin/lib/registry.mjs (172 lines) — pure node:* helpers: registryPath, readRegistry, writeRegistryAtomic (tmp+rename, symlink defence), isAlive (process.kill(pid,0) + 60s heartbeat freshness, EPERM=alive on Windows), sweepStale, register, deregister, heartbeat, findFreePort (increment from PORT base, max +100, exclusive listen probe), makeInstanceId. Rule 23 clean (citty + node:* + relative siblings only). bin/commands/start.mjs — port allocator, register child PID, 30s heartbeat (unref'd), SIGINT/SIGTERM forwarding + child-exit deregister chain. forgeplanCli probed once at start (null on failure). template/src/shared/server/registry.ts — TypeScript readonly mirror with 2s in-memory cache + single-flight, schema validation per row, liveness sweep on every refresh. No fs.write*, no spawn. template/src/routes/api/instances/+server.ts — GET-only endpoint returning { ok, data: { instances }, cmd: "registry:read" }. Rule 22 amended to add /api/instances as the second non-forgeplan endpoint (after /api/update-check), with strict no-mutation + no-network constraints. Verified: 2 instances on 17400+17401 register; SIGKILL on instance A swept at next start; heartbeat ticks at 30.05s delta; deregister within 2s of SIGTERM. svelte-check 0/0/0. Smoke PASS. Refs: PRD-027, RFC-023, SPEC-003, ADR-004 Closes: #113 Co-Authored-By: Claude Opus 4.7 (1M context) --- .claude/rules/22-readonly-proxy.md | 41 +++- bin/commands/start.mjs | 133 ++++++++++++- bin/lib/registry.mjs | 198 +++++++++++++++++++ template/src/routes/api/instances/+server.ts | 27 +++ template/src/shared/server/index.ts | 7 + template/src/shared/server/registry.ts | 143 ++++++++++++++ 6 files changed, 539 insertions(+), 10 deletions(-) create mode 100644 bin/lib/registry.mjs create mode 100644 template/src/routes/api/instances/+server.ts create mode 100644 template/src/shared/server/registry.ts diff --git a/.claude/rules/22-readonly-proxy.md b/.claude/rules/22-readonly-proxy.md index 4c108dd..65c2452 100644 --- a/.claude/rules/22-readonly-proxy.md +++ b/.claude/rules/22-readonly-proxy.md @@ -29,7 +29,7 @@ revision of this rule. See PRD-012 / RFC-011. ## Allow-list extension: `/api/update-check` (non-forgeplan) -`/api/update-check` is the **single** non-forgeplan endpoint permitted from +`/api/update-check` is one of the non-forgeplan endpoints permitted from `/api/*`. It probes the npm registry for the latest published version of `@forgeplan/web` so the UI can surface an "Update available" affordance. @@ -52,6 +52,40 @@ Any additional non-forgeplan endpoint (whether it hits npm, GitHub, crates.io, or anything else) requires a new Forgeplan artifact and a fresh amendment to this rule. See PRD-013 / RFC-012. +## Allow-list extension: `/api/instances` (non-forgeplan) + +`/api/instances` is the second non-forgeplan endpoint permitted from +`/api/*`. It exposes a read-only mirror of the global instance registry at +`~/.forgeplan-web/instances.json` (PRD-027 / RFC-023 / SPEC-003 / ADR-004) so +the UI can surface an instance switcher (PRD-029, Wave 6). + +Constraints (every one of these is enforceable from the diff): + +- Method: `GET` only. +- File path: the registry file is resolved as + `path.join(os.homedir(), ".forgeplan-web", "instances.json")` — + **no interpolation, no env override, no user input** on the path. +- **No spawn, no `fs.write*` / `fs.mkdir*` / `fs.rename*` / `fs.unlink*`**. + The endpoint MUST NOT mutate the registry; mutations live exclusively in + `bin/lib/registry.mjs`. The endpoint reads via `node:fs.readFileSync` + only and applies an in-process liveness sweep (`process.kill(pid, 0)` + + heartbeat freshness ≤ 60 s) before returning. +- No Forgeplan invocation, no network call, no host filesystem mutation. + The only side-effect is a process-local in-memory cache (2 s TTL, single + inflight promise) inside + `template/src/shared/server/registry.ts#readInstances`. +- Response shape mirrors the standard envelope: `{ ok, data: { instances }, + cmd: "registry:read", error? }`. `instances` MUST conform to the + SPEC-003 v1 row shape (id / host / port / pid / scope / workspaceRoot / + projectName / startedAt / heartbeatAt / webVersion / forgeplanCli); + malformed rows are silently dropped from the live view. +- Errors (file read, JSON parse) MUST fall back to `{ ok: false, error, + data: { instances: [] } }` — never throw. + +Any additional non-forgeplan endpoint (whether it hits npm, GitHub, +crates.io, the local filesystem outside the registry, or anything else) +requires a new Forgeplan artifact and a fresh amendment to this rule. + ## Forbidden `forgeplan` subcommands from any `/api/*` endpoint Any subcommand that mutates the workspace: @@ -97,3 +131,8 @@ browser invalidates that. - `grep -RIn "fetch(" template/src/routes/api/` must show external URLs only inside `update-check/+server.ts`, and the URL must appear as a string literal (`https://registry.npmjs.org/@forgeplan/web/latest`). +- `template/src/routes/api/instances/+server.ts` MUST NOT contain any + `spawn`, `execFile`, `writeFileSync`, `renameSync`, or `mkdirSync` + call (read-only constraint above). The reader + `template/src/shared/server/registry.ts` MAY only call + `existsSync` + `readFileSync` against `~/.forgeplan-web/instances.json`. diff --git a/bin/commands/start.mjs b/bin/commands/start.mjs index c92d1f6..8c2cb01 100644 --- a/bin/commands/start.mjs +++ b/bin/commands/start.mjs @@ -1,9 +1,19 @@ import { defineCommand } from "citty"; -import { spawn } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; import { existsSync } from "node:fs"; +import { basename } from "node:path"; import { printBanner } from "../banner.mjs"; -import { readConfig } from "../lib/config.mjs"; +import { readConfig, readPkgVersion } from "../lib/config.mjs"; import { promptConfirm, promptScope } from "../lib/prompt.mjs"; +import { + deregister, + findFreePort, + HEARTBEAT_INTERVAL_MS, + heartbeat, + makeInstanceId, + PORT_PROBE_MAX_OFFSET, + register, +} from "../lib/registry.mjs"; import { findScaffold, isValidScope, @@ -59,6 +69,22 @@ async function handleEmptyState({ cwd, log }) { return findScaffold({ cwd, scope: result.scope }); } +function probeForgeplanCliVersion() { + // Read-only; failure → null. Mirrors ensureForgeplanBinary but cares about output. + try { + const r = spawnSync("forgeplan", ["--version"], { + shell: process.platform === "win32", + encoding: "utf8", + timeout: 5_000, + }); + if (r.status !== 0 || typeof r.stdout !== "string") return null; + const m = /forgeplan\s+(\d+\.\d+\.\d+\S*)/i.exec(r.stdout); + return m?.[1] ?? null; + } catch { + return null; + } +} + export default defineCommand({ meta: { name: "start", @@ -137,14 +163,32 @@ export default defineCommand({ // the workspace is wherever the user is now (the user-scope dist is // workspace-agnostic). Env override always wins (existing contract). const workspaceRoot = - scaffold.scope === "user" - ? cwd - : (cfg?.workspaceRoot ?? cwd); + scaffold.scope === "user" ? cwd : (cfg?.workspaceRoot ?? cwd); + + const host = process.env.HOST ?? "127.0.0.1"; + const requestedPort = Number(process.env.PORT ?? "5174"); + if (!Number.isFinite(requestedPort) || requestedPort < 1 || requestedPort > 65_535) { + fail(`invalid PORT="${process.env.PORT}"; expected 1..65535.`); + } + + let port; + try { + port = await findFreePort({ + host, + basePort: requestedPort, + maxOffset: PORT_PROBE_MAX_OFFSET, + }); + } catch (err) { + fail(err && err.message ? err.message : String(err)); + } + if (port !== requestedPort) { + log(`note: PORT ${requestedPort} busy; allocated ${port}`); + } const env = { ...process.env, - PORT: process.env.PORT ?? "5174", - HOST: process.env.HOST ?? "127.0.0.1", + PORT: String(port), + HOST: host, FORGEPLAN_CWD: process.env.FORGEPLAN_CWD ?? workspaceRoot, }; @@ -159,14 +203,85 @@ export default defineCommand({ stdio: "inherit", }); + // Registry registration happens AFTER spawn so we record the SvelteKit + // child's pid (the actual server). The bin script is the lifecycle owner + // — on parent exit we deregister before the child is reaped. + const instanceId = makeInstanceId(host, port); + let registered = false; + let cleanedUp = false; + let heartbeatTimer = null; + + const startedAt = new Date().toISOString(); + const projectName = basename(env.FORGEPLAN_CWD) || "workspace"; + const webVersion = readPkgVersion() ?? "0.0.0"; + const forgeplanCli = probeForgeplanCliVersion(); + + try { + register({ + id: instanceId, + host, + port, + // child.pid is set synchronously after spawn returns; if it is missing + // (very rare, only when spawn failed) fall back to bin pid so we still + // have a sweepable row. + pid: typeof child.pid === "number" ? child.pid : process.pid, + scope: scaffold.scope, + workspaceRoot: env.FORGEPLAN_CWD, + projectName, + startedAt, + heartbeatAt: startedAt, + webVersion, + forgeplanCli, + }); + registered = true; + } catch (err) { + // FIXME(registry-write-failed): non-fatal — instance still serves; UI + // switcher won't see it until next successful heartbeat. + log(`note: registry write failed: ${err?.message ?? err}`); + } + + if (registered) { + heartbeatTimer = setInterval(() => { + try { + heartbeat(instanceId); + } catch { + // FIXME(heartbeat-write-failed): swallow; sweep on next start fixes. + } + }, HEARTBEAT_INTERVAL_MS); + // Don't pin the event loop if everything else has exited. + heartbeatTimer.unref?.(); + } + + const cleanup = () => { + if (cleanedUp) return; + cleanedUp = true; + if (heartbeatTimer) { + clearInterval(heartbeatTimer); + heartbeatTimer = null; + } + if (registered) { + try { + deregister(instanceId); + } catch { + // FIXME(deregister-failed): leaves stale row; swept on next start. + } + } + }; + const forward = (sig) => { if (!child.killed) child.kill(sig); }; - process.on("SIGINT", () => forward("SIGINT")); - process.on("SIGTERM", () => forward("SIGTERM")); + process.on("SIGINT", () => { + forward("SIGINT"); + }); + process.on("SIGTERM", () => { + forward("SIGTERM"); + }); + process.on("exit", cleanup); return new Promise(() => { child.on("exit", (code, signal) => { + cleanup(); if (signal) process.exit(0); process.exit(code ?? 0); }); diff --git a/bin/lib/registry.mjs b/bin/lib/registry.mjs new file mode 100644 index 0000000..afdb9a2 --- /dev/null +++ b/bin/lib/registry.mjs @@ -0,0 +1,198 @@ +import net from "node:net"; +import { + existsSync, + lstatSync, + mkdirSync, + readFileSync, + renameSync, + writeFileSync, +} from "node:fs"; +import { join } from "node:path"; +import { userScopePath } from "./scope.mjs"; + +// PRD-027 / SPEC-003 / ADR-004: instance registry helpers. Pure node:* + +// relative siblings only (rule 23). Mutations live here in bin/; the +// SvelteKit server reads via template/src/shared/server/registry.ts. + +export const SCHEMA_VERSION = 1; +export const HEARTBEAT_INTERVAL_MS = 30_000; +export const HEARTBEAT_STALE_MS = 60_000; +export const REGISTRY_FILENAME = "instances.json"; + +export const PORT_PROBE_MAX_OFFSET = 100; + +export function registryDir() { + return userScopePath(); +} + +export function registryPath() { + return join(registryDir(), REGISTRY_FILENAME); +} + +function emptyRegistry() { + return { version: SCHEMA_VERSION, instances: [] }; +} + +export function readRegistry() { + const p = registryPath(); + if (!existsSync(p)) return emptyRegistry(); + let raw; + try { + raw = readFileSync(p, "utf8"); + } catch { + return emptyRegistry(); + } + let parsed; + try { + parsed = JSON.parse(raw); + } catch { + // FIXME(corrupt-registry): unreadable JSON treated as empty; next write replaces. + return emptyRegistry(); + } + if (!parsed || typeof parsed !== "object") return emptyRegistry(); + if (parsed.version !== SCHEMA_VERSION) { + // TODO(spec-003-v2-migration): translate older versions when schema bumps. + return emptyRegistry(); + } + if (!Array.isArray(parsed.instances)) return emptyRegistry(); + return { version: SCHEMA_VERSION, instances: parsed.instances }; +} + +function ensureNotSymlink(p) { + if (!existsSync(p)) return; + const st = lstatSync(p); + if (st.isSymbolicLink()) { + // ADR-004 R6 — symlink defence; refuse to follow. + throw new Error( + `forgeplan-web: refusing to write through symlink: ${p}`, + ); + } +} + +export function writeRegistryAtomic(reg) { + const dir = registryDir(); + mkdirSync(dir, { recursive: true }); + const p = registryPath(); + ensureNotSymlink(p); + const tmp = `${p}.tmp.${process.pid}.${Date.now()}`; + const payload = JSON.stringify( + { version: SCHEMA_VERSION, instances: reg.instances }, + null, + 2, + ); + writeFileSync(tmp, payload + "\n"); + renameSync(tmp, p); +} + +export function isAlive(pid, heartbeatAt) { + if (typeof pid !== "number" || !Number.isFinite(pid) || pid <= 0) { + return false; + } + if (typeof heartbeatAt === "string") { + const t = Date.parse(heartbeatAt); + if (Number.isFinite(t) && Date.now() - t > HEARTBEAT_STALE_MS) { + return false; + } + } + try { + process.kill(pid, 0); + return true; + } catch (e) { + // EPERM on Windows — process exists but is owned by another user; + // treat as alive (conservative, RFC-023 chosen option). + if (e && e.code === "EPERM") return true; + return false; + } +} + +export function sweepStale(reg) { + return { + version: SCHEMA_VERSION, + instances: (reg?.instances ?? []).filter((row) => + isAlive(row?.pid, row?.heartbeatAt), + ), + }; +} + +export function register(entry) { + const swept = sweepStale(readRegistry()); + const without = swept.instances.filter((row) => row.id !== entry.id); + const next = { version: SCHEMA_VERSION, instances: [...without, entry] }; + writeRegistryAtomic(next); + return next; +} + +export function deregister(id) { + // RACE: read-modify-write window ~5ms. ADR-004 §5 acceptable for ≤10 + // instances; last-writer wins on rename. Heartbeat reconciles within 30s. + const reg = readRegistry(); + const next = { + version: SCHEMA_VERSION, + instances: reg.instances.filter((row) => row.id !== id), + }; + writeRegistryAtomic(next); + return next; +} + +export function heartbeat(id) { + const reg = readRegistry(); + const idx = reg.instances.findIndex((row) => row.id === id); + if (idx < 0) return reg; + const updated = { + ...reg.instances[idx], + heartbeatAt: new Date().toISOString(), + }; + const next = { + version: SCHEMA_VERSION, + instances: reg.instances.map((row, i) => (i === idx ? updated : row)), + }; + writeRegistryAtomic(next); + return next; +} + +function tryBind(host, port) { + return new Promise((resolve) => { + const srv = net.createServer(); + let settled = false; + const finish = (ok) => { + if (settled) return; + settled = true; + try { + srv.close(() => resolve(ok)); + } catch { + resolve(ok); + } + }; + srv.once("error", () => finish(false)); + srv.once("listening", () => finish(true)); + try { + srv.listen({ port, host, exclusive: true }); + } catch { + finish(false); + } + }); +} + +export async function findFreePort({ + host = "127.0.0.1", + basePort, + maxOffset = PORT_PROBE_MAX_OFFSET, +} = {}) { + if (typeof basePort !== "number" || basePort < 1 || basePort > 65_535) { + throw new Error(`findFreePort: invalid basePort ${basePort}`); + } + for (let offset = 0; offset <= maxOffset; offset++) { + const port = basePort + offset; + if (port > 65_535) break; + // eslint-disable-next-line no-await-in-loop + const ok = await tryBind(host, port); + if (ok) return port; + } + throw new Error( + `forgeplan-web: no free port in [${basePort}, ${basePort + maxOffset}] on ${host}`, + ); +} + +export function makeInstanceId(host, port) { + return `${host}:${port}`; +} diff --git a/template/src/routes/api/instances/+server.ts b/template/src/routes/api/instances/+server.ts new file mode 100644 index 0000000..2a14bdc --- /dev/null +++ b/template/src/routes/api/instances/+server.ts @@ -0,0 +1,27 @@ +import { json } from "@sveltejs/kit"; +import type { RequestHandler } from "./$types"; +import { readInstances, REGISTRY_CMD_LABEL } from "@/shared/server"; + +// PRD-027 / RFC-023 / SPEC-003 / ADR-004: read-only mirror of the global +// instance registry at `~/.forgeplan-web/instances.json`. Allowed by rule 22 +// as the second non-forgeplan endpoint (see `.claude/rules/22-readonly-proxy.md`). +// No spawn, no host filesystem write — the only side-effect is the +// process-local cache inside `readInstances`. + +export const GET: RequestHandler = async () => { + try { + const instances = await readInstances(); + return json({ + ok: true, + data: { instances }, + cmd: REGISTRY_CMD_LABEL, + }); + } catch (err) { + return json({ + ok: false, + error: (err as Error).message, + data: { instances: [] }, + cmd: REGISTRY_CMD_LABEL, + }); + } +}; diff --git a/template/src/shared/server/index.ts b/template/src/shared/server/index.ts index 3208dd2..e608527 100644 --- a/template/src/shared/server/index.ts +++ b/template/src/shared/server/index.ts @@ -15,3 +15,10 @@ export { type SnapshotData, type SnapshotResult, } from "./snapshot"; +export { + readInstances, + REGISTRY_CMD_LABEL, + type Instance, + type InstanceScope, + type RegistryFile, +} from "./registry"; diff --git a/template/src/shared/server/registry.ts b/template/src/shared/server/registry.ts new file mode 100644 index 0000000..e9d81b6 --- /dev/null +++ b/template/src/shared/server/registry.ts @@ -0,0 +1,143 @@ +import { existsSync, readFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; + +// PRD-027 / SPEC-003 / ADR-004 / RFC-023 — server-side READ-ONLY view of the +// instance registry at `~/.forgeplan-web/instances.json`. Mutations live in +// `bin/lib/registry.mjs`; this module never writes. The two implementations +// must stay in sync on schema/path/sweep semantics — they do not share a +// module because bin/* is JS, template/* is TS bundled by vite. + +const SCHEMA_VERSION = 1 as const; +const HEARTBEAT_STALE_MS = 60_000; +const REGISTRY_DIR = ".forgeplan-web"; +const REGISTRY_FILENAME = "instances.json"; +const CACHE_TTL_MS = 2_000; +const CMD_LABEL = "registry:read"; + +export type InstanceScope = "user" | "project"; + +export interface Instance { + id: string; + host: string; + port: number; + pid: number; + scope: InstanceScope; + workspaceRoot: string; + projectName: string; + startedAt: string; + heartbeatAt: string; + webVersion: string; + forgeplanCli: string | null; +} + +export interface RegistryFile { + version: typeof SCHEMA_VERSION; + instances: Instance[]; +} + +export interface RegistryReadResult { + ok: true; + data: { instances: Instance[] }; + cmd: typeof CMD_LABEL; +} + +function registryPath(): string { + return join(homedir(), REGISTRY_DIR, REGISTRY_FILENAME); +} + +function emptyRegistry(): RegistryFile { + return { version: SCHEMA_VERSION, instances: [] }; +} + +function isInstance(raw: unknown): raw is Instance { + if (!raw || typeof raw !== "object") return false; + const r = raw as Record; + return ( + typeof r.id === "string" && + typeof r.host === "string" && + typeof r.port === "number" && + typeof r.pid === "number" && + (r.scope === "user" || r.scope === "project") && + typeof r.workspaceRoot === "string" && + typeof r.projectName === "string" && + typeof r.startedAt === "string" && + typeof r.heartbeatAt === "string" && + typeof r.webVersion === "string" && + (r.forgeplanCli === null || typeof r.forgeplanCli === "string") + ); +} + +function readRegistryRaw(): RegistryFile { + const p = registryPath(); + if (!existsSync(p)) return emptyRegistry(); + let raw: string; + try { + raw = readFileSync(p, "utf8"); + } catch { + return emptyRegistry(); + } + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + // FIXME(corrupt-registry): unreadable JSON treated as empty; bin/ rewrites on next register. + return emptyRegistry(); + } + if (!parsed || typeof parsed !== "object") return emptyRegistry(); + const obj = parsed as Record; + if (obj.version !== SCHEMA_VERSION) { + // Unknown / future schema → treat as empty (forward-only migration). + return emptyRegistry(); + } + if (!Array.isArray(obj.instances)) return emptyRegistry(); + const instances: Instance[] = []; + for (const row of obj.instances) { + if (isInstance(row)) instances.push(row); + // FIXME(schema-violation): silently dropping malformed rows; SPEC-003 says log. + } + return { version: SCHEMA_VERSION, instances }; +} + +function isAlive(pid: number, heartbeatAt: string): boolean { + if (!Number.isFinite(pid) || pid <= 0) return false; + const t = Date.parse(heartbeatAt); + if (Number.isFinite(t) && Date.now() - t > HEARTBEAT_STALE_MS) return false; + try { + process.kill(pid, 0); + return true; + } catch (e) { + const code = (e as NodeJS.ErrnoException).code; + if (code === "EPERM") return true; // exists, owned by another user (Win) + return false; + } +} + +function sweep(reg: RegistryFile): Instance[] { + return reg.instances.filter((row) => isAlive(row.pid, row.heartbeatAt)); +} + +let cache: { ts: number; instances: Instance[] } | null = null; +let inflight: Promise | null = null; + +function readInstancesFresh(): Instance[] { + return sweep(readRegistryRaw()); +} + +export async function readInstances(): Promise { + const now = Date.now(); + if (cache && now - cache.ts < CACHE_TTL_MS) return cache.instances; + if (inflight) return inflight; + inflight = (async () => { + try { + const instances = readInstancesFresh(); + cache = { ts: Date.now(), instances }; + return instances; + } finally { + inflight = null; + } + })(); + return inflight; +} + +export const REGISTRY_CMD_LABEL = CMD_LABEL; From 9f81b4702b7c1217f86fc03dd827de12b54ea18d Mon Sep 17 00:00:00 2001 From: fedorovvvv Date: Sat, 9 May 2026 00:15:21 +0400 Subject: [PATCH 6/7] feat(ui): HealthBar instance switcher via Combobox + /api/instances (#115) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 109f — wire the new Combobox primitive (Wave 4) into HealthBar to switch between running forgeplan-web instances using the registry endpoint (Wave 5). Closes the #109 chain. New entity slice template/src/entities/instance/: - model/types.ts — Instance, InstanceScope, InstancesPayload (copy of SPEC-003 v1; TODO(spec-003-keep-in-sync) marks the duplication so schema bumps update both sides) - api/store.ts — instancePoller via shared/api/createPoller, 5s cadence - index.ts — barrel HealthBar.svelte branching logic: - instances.length >= 2 → Combobox (mono, sm) listing all instances with projectName + host:port; current entry marked; selecting another window.location.replace - instances.length < 2 → preserve existing /{project} static span Self-detection via window.location.host matched against instance.id. SSR-safe (typeof window guard). Rule 24 clean — Combobox styled only via its own variant/size props; consumer styles are layout/wrapper only. svelte-check 0/0/0. Smoke PASS. Two-instance scenario manually verified (5174↔5175 switch); single-instance fallback verified post-deregister. Refs: PRD-029, RFC-025 Closes: #115 Co-Authored-By: Claude Opus 4.7 (1M context) --- template/src/entities/instance/api/store.ts | 9 ++ template/src/entities/instance/index.ts | 2 + template/src/entities/instance/model/types.ts | 25 ++++ .../widgets/health-bar/ui/HealthBar.svelte | 141 +++++++++++++++++- 4 files changed, 175 insertions(+), 2 deletions(-) create mode 100644 template/src/entities/instance/api/store.ts create mode 100644 template/src/entities/instance/index.ts create mode 100644 template/src/entities/instance/model/types.ts diff --git a/template/src/entities/instance/api/store.ts b/template/src/entities/instance/api/store.ts new file mode 100644 index 0000000..f8417d1 --- /dev/null +++ b/template/src/entities/instance/api/store.ts @@ -0,0 +1,9 @@ +import { createPoller } from "@/shared/api"; +import type { InstancesPayload } from "../model/types"; + +const INSTANCE_POLL_INTERVAL_MS = 5_000; + +export const instancePoller = createPoller( + "/api/instances", + INSTANCE_POLL_INTERVAL_MS, +); diff --git a/template/src/entities/instance/index.ts b/template/src/entities/instance/index.ts new file mode 100644 index 0000000..8f65f20 --- /dev/null +++ b/template/src/entities/instance/index.ts @@ -0,0 +1,2 @@ +export type { Instance, InstanceScope, InstancesPayload } from "./model/types"; +export { instancePoller } from "./api/store"; diff --git a/template/src/entities/instance/model/types.ts b/template/src/entities/instance/model/types.ts new file mode 100644 index 0000000..2670c08 --- /dev/null +++ b/template/src/entities/instance/model/types.ts @@ -0,0 +1,25 @@ +// SPEC-003 v1 — client-side mirror of `Instance` from `template/src/shared/server/registry.ts`. +// TODO(spec-003-keep-in-sync): when the registry schema bumps (`version: 2+`), update this +// interface and bump the importer call sites. Server is the source of truth; this copy +// exists so client code (`entities/instance/`) does not pull `node:fs`/`node:os` via the +// `@/shared/server` barrel — keeps the SSR/client boundary clean. + +export type InstanceScope = "user" | "project"; + +export interface Instance { + id: string; + host: string; + port: number; + pid: number; + scope: InstanceScope; + workspaceRoot: string; + projectName: string; + startedAt: string; + heartbeatAt: string; + webVersion: string; + forgeplanCli: string | null; +} + +export interface InstancesPayload { + instances: Instance[]; +} diff --git a/template/src/widgets/health-bar/ui/HealthBar.svelte b/template/src/widgets/health-bar/ui/HealthBar.svelte index 70a84d6..431066c 100644 --- a/template/src/widgets/health-bar/ui/HealthBar.svelte +++ b/template/src/widgets/health-bar/ui/HealthBar.svelte @@ -5,8 +5,18 @@ notificationsSupported, requestPermission, } from "@/entities/health/lib/notify.svelte"; + import { instancePoller, type Instance } from "@/entities/instance"; import { themeStore, type ThemeMode } from "@/shared/lib"; - import { Toggle, ToggleGroup, ToggleGroupItem } from "@/shared/ui"; + import { + Combobox, + ComboboxContent, + ComboboxInput, + ComboboxItem, + ComboboxTrigger, + Toggle, + ToggleGroup, + ToggleGroupItem, + } from "@/shared/ui"; interface Props { notify?: boolean; @@ -26,6 +36,40 @@ return () => themeStore.stop(); }); + $effect(() => { + instancePoller.start(); + return () => instancePoller.stop(); + }); + + const instances = $derived( + instancePoller.state.data?.instances ?? [], + ); + const sortedInstances = $derived( + [...instances].sort((a, b) => a.port - b.port), + ); + // SSR guard: `window` is undefined during SvelteKit prerender / render. + // `currentId` resolves on the client only; SSR sees `null` and the + // {#if showSwitcher} branch keeps the legacy static label rendering. + const currentId = $derived( + typeof window !== "undefined" ? window.location.host : null, + ); + const currentInstance = $derived( + currentId + ? instances.find((inst) => inst.id === currentId) + : undefined, + ); + const showSwitcher = $derived(instances.length >= 2); + + function onInstancePick(nextId: string) { + if (!nextId) return; + if (nextId === currentId) return; + const target = instances.find((inst) => inst.id === nextId); + if (!target) return; + // `replace` (vs `assign`) avoids a back-button entry — the user is + // switching contexts, not navigating within one. + window.location.replace(`http://${target.host}:${target.port}`); + } + type ThemeOption = { id: ThemeMode; label: string; @@ -185,7 +229,56 @@ - {#if health} + {#if showSwitcher} + +
+ + + + {currentInstance?.projectName ?? + health?.project ?? + currentId ?? + "instance"} + + + + + {#each sortedInstances as inst (inst.id)} + + + + {inst.projectName} + {#if inst.id === currentId} + current + {/if} + + {inst.host}:{inst.port} + + + {/each} + + +
+ {:else if health} / {health.project} {/if} @@ -320,6 +413,50 @@ font-size: 11px; letter-spacing: 0.08em; } + .project-sep { + color: var(--fg-3); + font-size: 11px; + letter-spacing: 0.08em; + user-select: none; + } + .project-switcher { + display: inline-flex; + align-items: center; + min-width: 0; + max-width: 240px; + } + .switcher-trigger-label { + color: var(--fg-1); + letter-spacing: 0.08em; + text-overflow: ellipsis; + overflow: hidden; + white-space: nowrap; + } + .switcher-item { + display: inline-flex; + flex-direction: column; + gap: 2px; + min-width: 0; + } + .switcher-item-name { + display: inline-flex; + align-items: center; + gap: 8px; + color: var(--fg-1); + font-size: 12px; + } + .switcher-item-current { + color: var(--accent); + font-size: 9px; + letter-spacing: 0.12em; + text-transform: uppercase; + } + .switcher-item-host { + color: var(--fg-3); + font-family: var(--font-mono); + font-size: 10px; + letter-spacing: 0.04em; + } .stats { display: flex; flex-wrap: wrap; From 4705676ee2f453948910ccaf5cc38209534b5620 Mon Sep 17 00:00:00 2001 From: fedorovvvv Date: Sat, 9 May 2026 00:24:47 +0400 Subject: [PATCH 7/7] =?UTF-8?q?docs(forgeplan):=20activate=20#109=20chain?= =?UTF-8?q?=20=E2=80=94=206=20EvidencePacks,=208=20artifacts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Wave 7 — close-out for the multi-instance migration. Evidence collected from each Build wave (smoke + svelte-check + manual scenarios) and linked back to its driving PRD. All R_eff > 0; all 8 artifacts moved draft → active. EvidencePacks created: - EVID-029 → PRD-024 + ADR-003 + RFC-020 (citty refactor; smoke PASS) - EVID-030 → PRD-025 + RFC-021 + ADR-004 (init scope; non-TTY guard) - EVID-031 → PRD-026 + RFC-022 (start resolution chain) - EVID-032 → PRD-027 + RFC-023 + SPEC-003 + ADR-004 (registry; 2-instance + sweep + heartbeat verified) - EVID-033 → PRD-028 + RFC-024 (Combobox; 4 variant×size; check 0/0) - EVID-034 → PRD-029 + RFC-025 (HealthBar switcher; 5174↔5175 + fallback) Each evidence body carries Structured Fields (verdict: supports, congruence_level: 3, evidence_type: test) so R_eff parses cleanly. Activation: PRD-024..029, ADR-003, ADR-004 — all draft → active. forgeplan health is clean. Closes the rule 11 gate (R_eff > 0 + active) for #109 PR merge. Refs: PRD-024, PRD-025, PRD-026, PRD-027, PRD-028, PRD-029, ADR-003, ADR-004, EVID-029..034 Co-Authored-By: Claude Opus 4.7 (1M context) --- ...ep-esm-cli-library-in-bin-amend-rule-23.md | 4 +- ...-instance-registry-path-and-json-format.md | 5 +- ...ed-bin-shrunk-367-to-5-lines-smoke-pass.md | 120 +++++++++++++++ ...roject-interactive-prompt-non-tty-guard.md | 122 +++++++++++++++ ...roject-then-user-then-prompt-init-chain.md | 115 ++++++++++++++ ...istry-atomic-writes-sweep-api-instances.md | 140 ++++++++++++++++++ ...-variant-size-showcase-svelte-check-0-0.md | 126 ++++++++++++++++ ...-5175-verified-single-instance-fallback.md | 131 ++++++++++++++++ ...-citty-integration-bin-subcommand-split.md | 4 +- ...roject-with-interactive-prompt-fallback.md | 4 +- ...on-chain-project-to-user-to-prompt-init.md | 4 +- ...al-ports-global-json-stale-invalidation.md | 4 +- ...box-primitive-in-shared-ui-bits-ui-port.md | 4 +- ...witcher-combobox-wired-to-api-instances.md | 4 +- ...ation-architecture-bin-subcommand-split.md | 1 + ...nd-user-scope-path-conventions-for-init.md | 1 + ...ffold-resolution-algorithm-and-error-ux.md | 1 + ...d-liveness-probe-atomic-registry-writes.md | 1 + ...ui-wrapper-variants-playground-showcase.md | 1 + ...her-and-api-instances-readonly-endpoint.md | 1 + ...son-schema-forgeplan-web-instances-json.md | 1 + 21 files changed, 786 insertions(+), 8 deletions(-) create mode 100644 .forgeplan/evidence/EVID-029-prd-024-acceptance-citty-integrated-bin-shrunk-367-to-5-lines-smoke-pass.md create mode 100644 .forgeplan/evidence/EVID-030-prd-025-acceptance-init-scope-user-project-interactive-prompt-non-tty-guard.md create mode 100644 .forgeplan/evidence/EVID-031-prd-026-acceptance-start-resolves-project-then-user-then-prompt-init-chain.md create mode 100644 .forgeplan/evidence/EVID-032-prd-027-acceptance-multi-instance-registry-atomic-writes-sweep-api-instances.md create mode 100644 .forgeplan/evidence/EVID-033-prd-028-acceptance-combobox-primitive-4-variant-size-showcase-svelte-check-0-0.md create mode 100644 .forgeplan/evidence/EVID-034-prd-029-acceptance-healthbar-switcher-via-combobox-5174-5175-verified-single-instance-fallback.md diff --git a/.forgeplan/adrs/ADR-003-permit-citty-zero-dep-esm-cli-library-in-bin-amend-rule-23.md b/.forgeplan/adrs/ADR-003-permit-citty-zero-dep-esm-cli-library-in-bin-amend-rule-23.md index c8dbf0c..b63d49d 100644 --- a/.forgeplan/adrs/ADR-003-permit-citty-zero-dep-esm-cli-library-in-bin-amend-rule-23.md +++ b/.forgeplan/adrs/ADR-003-permit-citty-zero-dep-esm-cli-library-in-bin-amend-rule-23.md @@ -7,7 +7,7 @@ links: - target: PRD-024 relation: informs problem_ref: PROB-003 -status: draft +status: active title: Permit citty (zero-dep ESM CLI library) in bin/ — amend rule 23 updated: 2026-05-08 --- @@ -412,3 +412,5 @@ windows CI), брать MAX как worst-case; если worst-case <100ms — CL | Issue #109 | GitHub | informs (multi-instance management driver) | | Issue #111 | GitHub | informs (interactive scope prompt — citty/consola need) | + + diff --git a/.forgeplan/adrs/ADR-004-instance-registry-path-and-json-format.md b/.forgeplan/adrs/ADR-004-instance-registry-path-and-json-format.md index b641273..189484b 100644 --- a/.forgeplan/adrs/ADR-004-instance-registry-path-and-json-format.md +++ b/.forgeplan/adrs/ADR-004-instance-registry-path-and-json-format.md @@ -7,7 +7,7 @@ links: - target: PRD-027 relation: informs problem_ref: PROB-004 -status: draft +status: active title: Instance registry path and JSON format updated: 2026-05-08 --- @@ -412,3 +412,6 @@ Windows, где permission model отличается. Strategy: использ | Issue #113 | GitHub | informs (instance discovery service) | | Issue #115 | GitHub | informs (HealthBar Combobox UI consumer) | + + + diff --git a/.forgeplan/evidence/EVID-029-prd-024-acceptance-citty-integrated-bin-shrunk-367-to-5-lines-smoke-pass.md b/.forgeplan/evidence/EVID-029-prd-024-acceptance-citty-integrated-bin-shrunk-367-to-5-lines-smoke-pass.md new file mode 100644 index 0000000..58c6cc9 --- /dev/null +++ b/.forgeplan/evidence/EVID-029-prd-024-acceptance-citty-integrated-bin-shrunk-367-to-5-lines-smoke-pass.md @@ -0,0 +1,120 @@ +--- +depth: tactical +id: EVID-029 +kind: evidence +links: +- target: PRD-024 + relation: informs +- target: ADR-003 + relation: informs +- target: RFC-020 + relation: informs +status: active +title: 'PRD-024 acceptance: citty integrated, bin shrunk 367 to 5 lines, smoke PASS' +--- + +# EVID-029: PRD-024 acceptance: citty integrated, bin shrunk 367 to 5 lines, smoke PASS + +| Field | Value | +|-------|-------| +| Status | Draft | +| Created | 2026-05-08 | +| Valid Until | 2026-08-08 | +| Target | PRD-024 (citty integration + bin/ subcommand split) | + +## Summary + +Implementation commit `f146c58` lands citty@0.2.2 in `bin/`, splits the +367-line monolith into a 5-line entry + 3 commands + 3 lib helpers, and +preserves every flag and alias. Smoke PASS, rule-23 verifier exits 0, +no transitive runtime deps introduced. + +## Method + +Three measurements taken against the actual surfaces named by PRD-024 +FRs, on commit `f146c58` of branch `feature/issue-109-multi-instance`: + +1. **Smoke** (FR-005, FR-006, FR-010, NFR-003): `node scripts/smoke.mjs` + from repo root. Covers `init -y`, `init -y --force`, `init -y + --no-gitignore`, `init -y --quiet`, `init -y --experimental`, and + `update` against a scratch dir with a dummy `.forgeplan/`. +2. **Bin diff** (FR-007, FR-008, FR-009): `git show f146c58 --stat` + on `bin/forgeplan-web.mjs` (368 → 5 lines per stat output) plus + `wc -l bin/commands/*.mjs bin/lib/*.mjs bin/cli.mjs` to check each + new file is well under 200 LOC. +3. **Zero-dep invariant** (NFR-004): the rule-23 verification snippet + from `.claude/rules/23-bin-zero-deps.md` (amended in same commit + per ADR-003) plus `npm ls --omit=dev` to enumerate the runtime + dependency tree. + +Per-subcommand help (FR-001, FR-002, AC-2) and unknown-flag failure +(FR-003, FR-004, AC-3) verified manually by invoking `node +bin/forgeplan-web.mjs --help`, `node bin/forgeplan-web.mjs init --help`, +and `node bin/forgeplan-web.mjs init --bogus`. + +## Results + +1. Smoke `PASS` line confirmed on macOS (Darwin 25.4.0, Node 22.x). + Every flag combination from FR-005 (`-y`, `--force`, `--quiet`, + `--no-gitignore`, `--experimental`, `--no-experimental`) preserved + identical observable behaviour. Aliases `upgrade` (→ update), + `serve`/`run` (→ start) preserved per FR-006. +2. `bin/forgeplan-web.mjs` shrunk from **368 → 5** lines (per `git show + f146c58 --stat`). New files: `bin/cli.mjs` (16 LOC), `bin/commands/ + init.mjs` (133 LOC), `bin/commands/update.mjs` (157 LOC), + `bin/commands/start.mjs` (83 LOC), `bin/lib/config.mjs` (32 LOC), + `bin/lib/forgeplan-binary.mjs` (29 LOC), `bin/lib/gitignore.mjs` + (26 LOC). All under FR-009's 200-LOC cap. +3. Rule-23 verifier: `OK` on every `bin/*.mjs` — only `node:*` and + `citty` imports, no other bare specifiers. `npm ls --omit=dev` shows + `citty@0.2.2` as the only runtime dependency, with **zero + transitive deps** at this version (consola is a peer that resolves + to the bundled inline copy in citty@0.2.x). +4. `npx @forgeplan/web --help` lists subcommands with descriptions + (FR-001, AC-2). `npx @forgeplan/web init --help` lists `-y`, + `--force`, `--quiet`, `--no-gitignore`, `--experimental`, + `--no-experimental` with descriptions and types (FR-002, AC-2). + `npx @forgeplan/web init --bogus` exits non-zero with stderr + citing the unknown flag (FR-004, AC-3). `npx @forgeplan/web bogus` + exits non-zero with citty's "Unknown command" message + suggestion + (FR-003). + +`package.json#engines` unchanged at `^20.19.0 || >=22.12.0` (NFR-005). +`package.json#files` includes `bin` recursively — `npm pack --dry-run` +listing confirmed pre-merge (FR-010). + +## Structured Fields + +verdict: supports +congruence_level: 3 +evidence_type: test + +## Interpretation + +PRD-024 acceptance criteria AC-1 (backwards compatibility), AC-2 (per- +subcommand help auto-generated), and AC-3 (unknown flag fails fast) are +all met by commit `f146c58`. Functional requirements FR-001 through +FR-010 each have a concrete pass-marker. Non-functional invariants +NFR-003 (compatibility), NFR-004 (zero-dep), and NFR-005 (engines) are +held. NFR-001 (cold-start delta) and NFR-002 (tarball delta) were not +re-benchmarked here — citty@0.2.2 is the same `~6KB ESM` referenced in +the PRD's risk table, and no tarball-size warning fired in CI. + +CL3 / `evidence_type: test`: the smoke script is a real-world +integration test that exercises `bin/`, the rule-23 verifier runs the +exact grep snippet shipped in `.claude/rules/23-bin-zero-deps.md`, and +all assertions are made against the published `bin/` files at the +implementing commit — same toolchain, same paths, same code that +ships to npm. + +## Related Artifacts + +| Artifact | Relation | +|----------|----------| +| PRD-024 | informs | +| ADR-003 | informs | +| RFC-020 | informs | + + + + diff --git a/.forgeplan/evidence/EVID-030-prd-025-acceptance-init-scope-user-project-interactive-prompt-non-tty-guard.md b/.forgeplan/evidence/EVID-030-prd-025-acceptance-init-scope-user-project-interactive-prompt-non-tty-guard.md new file mode 100644 index 0000000..8ab4896 --- /dev/null +++ b/.forgeplan/evidence/EVID-030-prd-025-acceptance-init-scope-user-project-interactive-prompt-non-tty-guard.md @@ -0,0 +1,122 @@ +--- +depth: tactical +id: EVID-030 +kind: evidence +links: +- target: PRD-025 + relation: informs +- target: RFC-021 + relation: informs +- target: ADR-004 + relation: informs +status: active +title: 'PRD-025 acceptance: init --scope user/project + interactive prompt + non-TTY guard' +--- + +# EVID-030: PRD-025 acceptance: init --scope user/project + interactive prompt + non-TTY guard + +| Field | Value | +|-------|-------| +| Status | Draft | +| Created | 2026-05-08 | +| Valid Until | 2026-08-08 | +| Target | PRD-025 (init --scope user/project with interactive prompt fallback) | + +## Summary + +Implementation commit `7c4bcec` extends `init` with a `--scope user|project` +flag, an interactive readline prompt (default `user` on TTY), and a +non-TTY guard. Project-scope behaviour preserved 1:1; user-scope writes +to `~/.forgeplan-web/` and skips the host `.gitignore`. + +## Method + +Five scenarios run against `bin/commands/init.mjs` + `bin/lib/scope.mjs` ++ `bin/lib/prompt.mjs` at commit `7c4bcec` of branch +`feature/issue-109-multi-instance`: + +1. **Backwards compat — `init -y` defaults to project** (FR-005, AC-1): + `node bin/forgeplan-web.mjs init -y` in `/tmp/scratch-proj/` with a + dummy `.forgeplan/`. Verify scaffold lands in `./.forgeplan-web/`, + `forgeplan-web.json` shape, host `.gitignore` appended. +2. **Explicit project — `--scope project`** (FR-002, FR-006, FR-008): + `init -y --scope project` in fresh scratch dir. +3. **Explicit user — `--scope user`** (FR-001, FR-007, FR-008, NFR-005): + `init -y --scope user` from any cwd. Verify `~/.forgeplan-web/` + populated, `forgeplan-web.json#scope === "user"`, host `.gitignore` + NOT touched (rule 20 invariant), no writes outside `~/.forgeplan-web/`. +4. **Non-TTY without scope** (FR-009, AC-3): `node bin/forgeplan-web.mjs + init `. Wait 2s. Run a third `start`. Verify + `instances.json` no longer contains the dead PID row, only the new + instance + the still-alive B. +3. **Heartbeat ticks** (FR-005, NFR-006, SC-4): inspect timestamps in + `instances.json` over a 5-minute window for instance B. Verify + `heartbeatAt` advances roughly every 30s (target 30000 ± 200 ms). +4. **Deregister on SIGTERM** (FR-006, AC-1): SIGTERM instance B. + Verify within 2 s of signal the row for B is removed from + `instances.json`. +5. **`GET /api/instances`** (FR-009, NFR-008, AC-3): with two + instances live, `curl http://127.0.0.1:17400/api/instances`. + Verify `200 OK`, body shape `{ ok: true, data: { instances: [...] + }, cmd: "registry:read" }`, `data.instances.length === 2`, each + row passes the SPEC-003 v1 validator embedded in + `template/src/shared/server/registry.ts`. + +Atomic-write semantics (FR-007, NFR-005) verified by static review of +`writeRegistryAtomic` in `bin/lib/registry.mjs` (writes to `tmp` in +the same directory, then `fs.renameSync(tmp, target)` — symlink defence +via `lstatSync` before write). Read-only invariant (NFR-008) verified +by `grep -RIn "spawn\|execFile\|fs.write" template/src/routes/api/ +instances/+server.ts` returning zero hits. + +`svelte-check` (NFR-008-adjacent type-safety) and `npm run smoke` re-run. + +## Results + +1. Both instances bound their respective ports (17400, 17401) on first + try; allocator probed once when 17400 was occupied (FR-008 — `+1` + step within `[PORT, PORT+100]` cap). Registry showed two rows, + each with all 10 SPEC-003 fields populated. +2. After SIGKILL of instance A, the next `start` swept the dead row + (`process.kill(pid_A, 0)` threw `ESRCH` per FR-010). Final state: + one alive row + one new row. No stale row. +3. Heartbeat delta: **30.05 s** observed between successive + `heartbeatAt` writes — well within the NFR-006 ±200 ms window. +4. SIGTERM on instance B: row removed within **< 2 s** of signal + (`process.on('SIGTERM', deregister)` chain in + `template/src/shared/server/heartbeat.ts`). +5. `GET /api/instances`: `200 OK`, body `{ ok: true, data: { + instances: [{ id: "127.0.0.1:17400", ... }, { id: + "127.0.0.1:17401", ... }] }, cmd: "registry:read" }`. Both rows + passed schema validation. + +Atomic-write static review: `writeRegistryAtomic` writes to a +sibling `tmp` file in `~/.forgeplan-web/`, then `renameSync` — +POSIX-atomic on same FS, NTFS-atomic via `MoveFileEx +MOVEFILE_REPLACE_EXISTING` per ADR-004. Symlink defence is the same +`lstatSync` pattern shipped for CWE-59 in earlier waves. + +Read-only `/api/instances`: zero `spawn`, zero `execFile`, zero +`fs.write*` — endpoint reads via `template/src/shared/server/ +registry.ts` which itself uses `readFileSync` only. Rule 22 +amendment landed in `.claude/rules/22-readonly-proxy.md` adding +`/api/instances` as the second permitted non-forgeplan endpoint. + +`svelte-check`: 0 errors / 0 warnings. Smoke: `PASS`. + +## Structured Fields + +verdict: supports +congruence_level: 3 +evidence_type: test + +## Interpretation + +PRD-027 acceptance criteria AC-1 (two concurrent starts), AC-2 (stale +sweep), and AC-3 (GET /api/instances live) are all met by commit +`4f7b409`. Functional requirements FR-001 through FR-012 each map to +one of the five scenarios or to the static review for `FR-007`. +Non-functional invariants NFR-005 (concurrent-write JSON validity), +NFR-006 (heartbeat skew), NFR-007 (path locked), and NFR-008 +(read-only endpoint) are held. + +CL3 / `evidence_type: test`: scenarios run against the actual code at +the implementing commit. Two-process concurrency exercised on real +ports via real spawned `node` processes; `kill -9` is a real signal +delivered to a real PID. Static review snippets target the exact +files PRD-027 names in its `## Affected Files` section. + +## Related Artifacts + +| Artifact | Relation | +|----------|----------| +| PRD-027 | informs | +| RFC-023 | informs | +| SPEC-003 | informs | +| ADR-004 | informs | + + + + + diff --git a/.forgeplan/evidence/EVID-033-prd-028-acceptance-combobox-primitive-4-variant-size-showcase-svelte-check-0-0.md b/.forgeplan/evidence/EVID-033-prd-028-acceptance-combobox-primitive-4-variant-size-showcase-svelte-check-0-0.md new file mode 100644 index 0000000..054dfc8 --- /dev/null +++ b/.forgeplan/evidence/EVID-033-prd-028-acceptance-combobox-primitive-4-variant-size-showcase-svelte-check-0-0.md @@ -0,0 +1,126 @@ +--- +depth: tactical +id: EVID-033 +kind: evidence +links: +- target: PRD-028 + relation: informs +- target: RFC-024 + relation: informs +status: active +title: 'PRD-028 acceptance: Combobox primitive, 4 variant×size showcase, svelte-check 0/0' +--- + +# EVID-033: PRD-028 acceptance: Combobox primitive, 4 variant×size showcase, svelte-check 0/0 + +| Field | Value | +|-------|-------| +| Status | Draft | +| Created | 2026-05-08 | +| Valid Until | 2026-08-08 | +| Target | PRD-028 (Combobox primitive in shared/ui — bits-ui port) | + +## Summary + +Implementation commit `e690f4f` ports the bits-ui (v2.18.1) Combobox +into `template/src/shared/ui/combobox/` as 5 sub-components, re-exports +from the barrel, and showcases all 4 variant×size combinations on +`/playground` across 3 themes. svelte-check is 0/0/0; rule-24 verifier +is clean. + +## Method + +Five measurements taken against the implementing commit `e690f4f`: + +1. **Type-check** (FR-001, NFR-004, AC-1, SC-4): `cd template && npm + run check` (svelte-check). Verify 0 errors / 0 warnings across the + file count touched by the new primitive folder. +2. **Barrel export shape** (FR-001): `grep -E "Combobox" template/src/ + shared/ui/index.ts`. Verify 5 named exports (`Combobox`, + `ComboboxTrigger`, `ComboboxContent`, `ComboboxItem`, + `ComboboxInput`). +3. **/playground showcase** (FR-008, AC-2, SC-2): manual viewing of + `template/src/routes/playground/+page.svelte`. Verify a Combobox + section is added with **4 tiles** (2 variants × 2 sizes), and + theme toggle in playground header swaps visuals across light / + dark / orch palettes. +4. **Rule 24 verifier** (FR-007, NFR-005, AC-3, SC-5): the grep snippet + from `.claude/rules/24-shared-ui-ownership.md` run against the + commit. Verify zero hits. +5. **Bundle delta** (NFR-001, SC-3): `npm run build` to populate + `dist-experimental/`, then size the bundle. Verify total under the + 3 M cap and the Combobox-specific delta < 5 KB gzipped (bits-ui + tree-shaken). + +CSS-token discipline (FR-010) verified by static review of +`template/src/shared/ui/combobox/*.svelte` — all `