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/.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/.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/.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..b63d49d --- /dev/null +++ b/.forgeplan/adrs/ADR-003-permit-citty-zero-dep-esm-cli-library-in-bin-amend-rule-23.md @@ -0,0 +1,416 @@ +--- +created: 2026-05-08 +depth: standard +id: ADR-003 +kind: adr +links: +- target: PRD-024 + relation: informs +problem_ref: PROB-003 +status: active +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..189484b --- /dev/null +++ b/.forgeplan/adrs/ADR-004-instance-registry-path-and-json-format.md @@ -0,0 +1,417 @@ +--- +created: 2026-05-08 +depth: standard +id: ADR-004 +kind: adr +links: +- target: PRD-027 + relation: informs +problem_ref: PROB-004 +status: active +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/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 ` +``` + +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..c4b97a1 --- /dev/null +++ b/.forgeplan/rfcs/RFC-025-healthbar-instance-switcher-and-api-instances-readonly-endpoint.md @@ -0,0 +1,362 @@ +--- +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..d7f2772 --- /dev/null +++ b/.forgeplan/specs/SPEC-003-instance-registry-json-schema-forgeplan-web-instances-json.md @@ -0,0 +1,254 @@ +--- +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. + + 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..95e65f2 --- /dev/null +++ b/bin/commands/init.mjs @@ -0,0 +1,201 @@ +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"; +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"); + +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 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 into a project- or user-scope `.forgeplan-web/`.", + }, + args: { + y: { + type: "boolean", + description: + "non-interactive mode (defaults --scope to project for backwards compat)", + }, + 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 (project scope only; pass --no-gitignore to skip)", + }, + experimental: { + type: "boolean", + description: + "[EXPERIMENTAL] use the bundled single-file dist (~9x smaller, no node_modules/)", + }, + scope: { + type: "string", + description: + "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; + const YES = args.y === true; + const SKIP_GITIGNORE = args.gitignore === false; + const EXPERIMENTAL = args.experimental === true; + + 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; + } + } + + await runInit({ + scope, + force: FORCE, + quiet: QUIET, + skipGitignore: SKIP_GITIGNORE, + experimental: EXPERIMENTAL, + }); + }, +}); diff --git a/bin/commands/start.mjs b/bin/commands/start.mjs new file mode 100644 index 0000000..8c2cb01 --- /dev/null +++ b/bin/commands/start.mjs @@ -0,0 +1,290 @@ +import { defineCommand } from "citty"; +import { spawn, spawnSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { basename } from "node:path"; +import { printBanner } from "../banner.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, + 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 }); +} + +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", + description: + "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: { + quiet: { + type: "boolean", + alias: "q", + description: "suppress banner and informational output", + }, + scope: { + type: "string", + description: + "force a specific scope: user (~/.forgeplan-web/) or project (./.forgeplan-web/); fails if absent", + 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(); + + let explicitScope = null; + if (args.scope) { + if (!isValidScope(args.scope)) { + fail( + `invalid --scope value "${args.scope}"; expected "user" or "project".`, + ); + } + explicitScope = args.scope; + } + + 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 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: String(port), + HOST: host, + FORGEPLAN_CWD: process.env.FORGEPLAN_CWD ?? workspaceRoot, + }; + + printBanner({ quiet: QUIET }); + log(`→ scope: ${scaffold.scope} (${target})`); + 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", + }); + + // 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("exit", cleanup); + + return new Promise(() => { + child.on("exit", (code, signal) => { + cleanup(); + 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..fcc9ffa --- /dev/null +++ b/bin/commands/update.mjs @@ -0,0 +1,209 @@ +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"; +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"); + +function fail(line, code = 1) { + process.stderr.write(`forgeplan-web: ${line}\n`); + 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 a `.forgeplan-web/` scaffold (project- or user-scope) 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)", + }, + scope: { + type: "string", + description: + "scope of the scaffold to update: user (~/.forgeplan-web/) or project (./.forgeplan-web/)", + 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"); + }; + + 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(); + const { scope, target } = resolveTargetForUpdate({ + explicitScope, + cwd, + }); + + if (scope === "project") { + ensureForgeplanWorkspace(cwd, fail); + } + ensureForgeplanBinary(fail); + + 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} (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}, scope: ${scope})`); + + 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 — 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}).`, + ); + } + + 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: + 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} (scope: ${scope})`); + 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..36ecbba --- /dev/null +++ b/bin/lib/config.mjs @@ -0,0 +1,39 @@ +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 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( + 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/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/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/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; +} 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" } 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/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/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/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; 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, 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;