diff --git a/.claude/rules/21-template-purity.md b/.claude/rules/21-template-purity.md index 997e1f4..3c97908 100644 --- a/.claude/rules/21-template-purity.md +++ b/.claude/rules/21-template-purity.md @@ -26,15 +26,19 @@ a self-contained scaffold. merge them. - Runtime deps (used by `node build/index.js` after `vite build`) live in `dependencies`. Build-only tooling (vite, adapter-node, svelte-check, - typescript, types) lives in `devDependencies`. The build pipeline: - - For legacy `dist/`: derives `dist/package.json` from - `template/package.json#dependencies` and runs `npm install --omit=dev` - inside `dist/`. - - For `dist-experimental/` (PRD-014 / RFC-013): runs esbuild on - `template/build/index.js` with `--bundle --packages=bundle` to inline - every reachable runtime dep into a single ESM file. The output has - no `node_modules/` and no `server/` chunks. `dist-experimental/` - is capped at 3M (assertion in `scripts/build.mjs`). + typescript, types) lives in `devDependencies`. The build pipeline + (PRD-030 / RFC-026 / ADR-005): + - Runs esbuild on `template/build/index.js` with + `--bundle --packages=bundle` to inline every reachable runtime dep + into a single ESM file. The output has no `node_modules/` and no + `server/` chunks. + - Materialises one **image** per entry in `config/images.json#images`. + `dist/` for `stable`, `dist-/` for every other image (e.g. + `dist-nightly/`). Each image directory is byte-identical except for + its `forgeplan-web-build.json` manifest (records `image` + `features`). + - Each emitted `dist*/` is capped at 3M (assertion in `scripts/build.mjs`). + - The legacy `dist/node_modules/`-shaped pipeline is removed (graduates + PRD-014 / RFC-013). - `template/package.json#scripts.dev` must boot SvelteKit on a deterministic port (currently `5174`) so the README's quick-start link is correct. - Every server route that needs the workspace path MUST read it from diff --git a/.claude/rules/23-bin-zero-deps.md b/.claude/rules/23-bin-zero-deps.md index 2608312..491a93b 100644 --- a/.claude/rules/23-bin-zero-deps.md +++ b/.claude/rules/23-bin-zero-deps.md @@ -46,29 +46,28 @@ ADR — not an amendment to this one. the bin script. Currently allowed: `{ "citty": "^0.2.2" }` — and nothing else. -## Note on `dist/` and `dist-experimental/` - -The published tarball ships **two** pre-built artifacts (PRD-014 / RFC-013): - -- `dist/` (legacy default) — SvelteKit app with its own `node_modules/`, - populated by the build pipeline with `--omit=dev`. Those deps are - runtime needs of the SvelteKit server (`node dist/index.js`), not of - the bin script. -- `dist-experimental/` (opt-in via `init --experimental`) — single-file - ESM bundle (`dist-experimental/index.js`), emitted by esbuild. No - `node_modules/`, no `server/` chunks; everything reachable from the - entry is inlined. The bundle ships with its own minimal `package.json` - (no `dependencies`). - -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 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 -`scripts/build.mjs`), the legacy `dist/` will be dropped from the -tarball and this section will collapse to one paragraph. +## Note on `dist*/` images (PRD-030 / RFC-026) + +The published tarball ships one pre-built **image** per entry in +`config/images.json#images`: + +- `dist/` is reserved for `stable` (the default image). +- Every other image (e.g. `dist-nightly/`) is named `dist-/`. + +All image directories are produced by the same esbuild bundler — single-file +ESM bundle (`/index.js`), no `node_modules/`, no `server/` chunks. Each +directory carries its own `forgeplan-web-build.json` recording `image` + +`features`. The legacy SvelteKit-with-`node_modules/` shape was removed when +the bundle approach graduated (PRD-014 / RFC-013 → PRD-030 / RFC-026). + +The bin script only `spawn()`s `node` against the chosen image's +`index.js` — it never imports anything from the image's internals. The +`bin/lib/images.mjs` sibling holds the image-name → directory mapping +and probes the filesystem at runtime for which images shipped (no JSON +config read at bin runtime; the registry lives in the build pipeline, +the materialised manifest lives in each `dist*/forgeplan-web-build.json`). +This rule is about the bin script itself staying bound to the citty + +node:* allow-list; the artifacts are governed by rule 21. ## Required diff --git a/.forgeplan/adrs/ADR-005-image-as-build-artifact-not-runtime-config.md b/.forgeplan/adrs/ADR-005-image-as-build-artifact-not-runtime-config.md new file mode 100644 index 0000000..960c80a --- /dev/null +++ b/.forgeplan/adrs/ADR-005-image-as-build-artifact-not-runtime-config.md @@ -0,0 +1,163 @@ +--- +depth: standard +id: ADR-005 +kind: adr +links: +- target: PRD-030 + relation: informs +status: active +title: Image as build artifact, not runtime config +--- + +--- +id: ADR-005 +title: "Image as build artifact, not runtime config" +status: Proposed +depth: deep +valid_until: 2027-05-09 +created: 2026-05-09 +updated: 2026-05-09 +informs: PRD-030 +amends: RFC-013 +--- + +# ADR-005: Image as build artifact, not runtime config + +## Context + +PRD-030 introduces named "images" of the `@forgeplan/web` scaffold (initial set: `stable`, `nightly`). Each image declares the set of feature flags it ships. There are two structurally different ways to materialize an image: + +- **Build-time**: emit one filesystem directory per image (`dist/`, `dist-nightly/`, …), each containing the bundle bytes for that flag set. `init --image ` is a `cp -r` of the chosen directory. +- **Runtime**: ship one bundle and one runtime config. `init --image ` writes the chosen image into `forgeplan-web.json`; the SvelteKit server reads `features` at startup and gates behaviour with `if (features.includes("X"))`. + +The two approaches differ in code locality, tarball size, dead-code shipping, mental model, and the level of effort required to introduce future image-tracks (e.g. an `lts` lane). This ADR locks the choice in. + +## Decision + +**Selected**: build-time. An image is a directory in the npm tarball; `init --image ` is a `cp -r` of the named directory. + +Concretely: + +- Build pipeline emits N filesystem directories — one per declared image. `dist/` is reserved for `stable`; other images go to `dist-/`. +- Each directory contains the same bundle bytes today (because v1 images all have empty feature lists), but they are byte-divergent in principle and divergent in practice as soon as flags exist. +- `forgeplan-web-build.json` records the image name and the active feature list. The bin script does not interpret features. +- `start` does not know about images. It spawns `node .forgeplan-web/index.js`. + +Build-time was selected because it preserves the user's "image" mental model (a directory IS an image), it keeps `start` image-agnostic, and it lets us drop dead code from images that don't enable a flag once the bundling pipeline learns about flags. Runtime gating remains available as a future tactical option for individual flags within an image, but the image identity itself is a build-time fact. + +## Consequences + +### Positive + +- `start` is image-agnostic; unchanged invariants on the runtime side. +- Adding a new image is a 2-line `config/images.json` change + a `package.json#files` entry. +- Reviewers can answer "what does the nightly image actually contain" by reading `dist-nightly/`. +- The graduation forcing-function (lifecycle validator) operates on a single source of truth (`config/features.json`), separate from runtime code paths. +- Reuses the existing esbuild pipeline (RFC-013) — no new build technology. + +### Negative + +- Tarball ships N copies of the bundle when N images share an empty (or identical) flag set. v1 with 2 empty images means ~1.4 MB of duplication. NFR-001 caps each directory ≤3 MB; total tarball alarm threshold sits at 10 MB (CHANGELOG only, no hard cap yet). +- Adding a flag whose presence/absence affects the bundle bytes will require esbuild to rebuild per-image (small, predictable cost; bundle is fast). +- `dist/` and `dist-/` need explicit listing in `package.json#files`. Missed entry = missing artifact at install time. Mitigated by build-time assertion that every emitted dir is referenced in `files`. + +### Reversibility + +This decision is **soft-reversible**. Switching to runtime gating later would require: + +- A bundle that reads `forgeplan-web-build.json#features` at startup. +- Code paths gated by `if (features.includes("X"))`. +- Dropping all `dist-*/` directories from `package.json#files` except `dist/`. + +The CLI surface (`init --image `, `update --image `, persisted `image` in `forgeplan-web.json`) is identical between build-time and runtime materializations, so users do not see a difference. Reversal cost is mostly in the build pipeline, not in user-visible API. + +## Alternatives Considered + +### Runtime gating + +Already detailed above. Rejected because: + +- Every image ships every flag's code, defeating the user's stated mental model of "images contain features". +- Removing a graduated flag from `nightly` doesn't reduce bytes for `stable` users unless the source itself is removed — which is exactly the work we're trying to force via lifecycle. Build-time materialization makes "stripping a graduated flag" a directly visible diff. +- "Reviewer reads `dist-nightly/` to confirm what nightly actually contains" — not possible. + +### One npm package per image + +Rejected because: + +- 2× publish surface, 2× release pipeline, 2× CHANGELOG. +- Cardinality scales poorly: N images = N packages. +- v1 ships one package historically; switching package count is a much bigger user-visible event than adding a CLI flag. + +### Single boolean per image (continue `--experimental`-style) + +Rejected because: + +- Combinatorial: N image flags imply 2^N implicit combinations. The `images.json` registry is a flat list, which is the actual mental model. +- No graduation discipline. `--experimental` has no expiry today. + +## Invariants + +- `start` is image-agnostic: it spawns `node .forgeplan-web/index.js` regardless of which image was installed. Future changes MUST NOT introduce branching in `start` that depends on the image name. +- The set of directories matching `dist*/` shipped in the npm tarball MUST equal the set of images declared in `config/images.json#images`. Mismatch is a build error. +- `bin/lib/images.mjs` MUST NOT import anything outside the rule 23 allow-list (`node:*` + relative siblings). +- `forgeplan-web.json#image` is sticky on `update`; switching tracks requires `--image ` explicitly. + +## Preconditions + +- esbuild bundle pipeline (RFC-013) is producing usable output with smoke pass on default flag set. (True today.) +- `package.json#files` is editable per release without `npm publish` automation drift. (True today.) + +## Postconditions + +- `--experimental` is a deprecated alias documented in CHANGELOG and emitting a stderr warning on every invocation. +- `forgeplan-web.json` of every newly-installed scaffold contains an `image` field. + +## Rollback Plan + +If field validation surfaces a regression in the stable bundle that does not affect the legacy SvelteKit shape: + +1. Restore `copyToDist()`, `installRuntimeDeps()`, `emitDistPackageJson()` in `scripts/build.mjs` from this PR's parent commit. Single revert. +2. Restore `dist-experimental/` as opt-in: revert the `--image`/`--experimental` consolidation in `bin/commands/init.mjs` and `update.mjs`. +3. Keep `config/images.json` and `config/features.json` — they are forward-compatible with the legacy shape (the legacy shape is just one more "image" track in waiting). +4. Cut a patch release. + +Rollback cost: estimated ≤2 hours; the legacy code paths are deleted in this PR but preserved in git history at the parent commit's SHA. + +## Affected Files + +- scripts/build.mjs — drops legacy SvelteKit shape, adds image emitter and lifecycle validator. +- bin/commands/init.mjs — `--image`, deprecated `--experimental` alias. +- bin/commands/update.mjs — `--image`, persisted track. +- bin/lib/images.mjs (new) — image name/path helpers. +- bin/lib/config.mjs — `image` field plumbing. +- config/images.json (new) — image registry. +- config/features.json (new) — feature registry. +- config/IMAGES.md (new) — maintainer docs. +- package.json — `files` includes every emitted image dir. +- README.md / README.ru.md — documents `--image` + lifecycle policy. +- CHANGELOG.md — BREAKING CHANGE entry. +- .claude/rules/21-template-purity.md — image-aware language. +- .claude/rules/23-bin-zero-deps.md — note `bin/lib/images.mjs`. +- CLAUDE.md — replaces `dist-experimental/` references with image-aware language. +- scripts/smoke.mjs — extended to run twice (default + nightly). + +## Validity / Review + +- This ADR is valid through `valid_until: 2027-05-09` (one year). +- Triggers for early re-review: + - Tarball total size ≥10 MB (then duplication starts to matter). + - Three or more images share an identical non-empty flag set (then the build-time duplication is wasted). + - User-reported install latency regression > 30% from current baseline (`init` time on slow link). + +## Related Artifacts + +- PRD-030 — drives this decision +- RFC-026 — implements this decision +- RFC-013 — historical context (`--experimental` was the prototype of this) +- ADR-001 — `init` host-isolation invariants (image choice does not widen them) +- ADR-003 — citty-only bin allow-list (image dispatch is just `node:fs` + relative siblings) + + + + diff --git a/.forgeplan/evidence/EVID-035-smoke-lifecycle-validator-evidence-for-prd-030-image-system.md b/.forgeplan/evidence/EVID-035-smoke-lifecycle-validator-evidence-for-prd-030-image-system.md new file mode 100644 index 0000000..0cb3f94 --- /dev/null +++ b/.forgeplan/evidence/EVID-035-smoke-lifecycle-validator-evidence-for-prd-030-image-system.md @@ -0,0 +1,221 @@ +--- +depth: tactical +id: EVID-035 +kind: evidence +links: +- target: PRD-030 + relation: informs +- target: RFC-026 + relation: informs +- target: ADR-005 + relation: informs +status: active +title: Smoke + lifecycle-validator evidence for PRD-030 image system +--- + +# EVID-035: Smoke + lifecycle-validator evidence for PRD-030 image system + +| Field | Value | +|-------|-------| +| Status | Draft | +| Created | 2026-05-09 | +| Valid Until | 2027-05-09 | +| Target | PRD-030 / RFC-026 / ADR-005 | + +## Structured Fields + +verdict: supports +congruence_level: 3 +evidence_type: test + +## Measurement + +Three separate measurements, all run on the implementation branch +`feature/issue-121-feature-flag-images` against the working tree at +the commit immediately before activation: + +1. **`npm run build`** with the new pipeline: confirm both `dist/` and + `dist-nightly/` are emitted, each capped under 3 MB, each with the + expected per-image `forgeplan-web-build.json`. +2. **`npm run smoke`** (extended): scaffold-init + start + `/api/health` + + `/api/list` + `GET /` against both images, each in its own scratch + workspace, with the local `forgeplan-shim` on PATH. +3. **Lifecycle-validator regression** with two synthetic fixtures + injected into `config/features.json` (originals restored after each + run): an expired flag and an over-3-minor lifetime flag. Build must + exit non-zero in both cases. + +All three measurements run against the actual surface (the build +script, the bin script, the SvelteKit server) — `evidence_type: test`, +not `measurement`-only. Same context as PRD-030 (this repo, this branch, +this build pipeline), CL3. + +## Result + +### Measurement 1 — `npm run build` (per-image emission) + +``` +[build] patched HOST default 0.0.0.0 → 127.0.0.1 in ./.dist-base/index.js (env=Ue) +[build] dist/ ready (1.79M, image=stable, features=0) +[build] dist-nightly/ ready (1.79M, image=nightly, features=0) +[build] done. images built: stable, nightly +``` + +Manifest spot-check: + +```json +// dist/forgeplan-web-build.json +{ + "name": "@forgeplan/web", + "version": "0.1.13", + "builtAt": "2026-05-09T10:47:10.937Z", + "entry": "index.js", + "image": "stable", + "features": [] +} + +// dist-nightly/forgeplan-web-build.json +{ + "name": "@forgeplan/web", + "version": "0.1.13", + "builtAt": "2026-05-09T10:47:10.954Z", + "entry": "index.js", + "image": "nightly", + "features": [] +} +``` + +→ **Satisfies SC-1, SC-2, SC-4, AC-5.** + +### Measurement 2 — `npm run smoke` (both images, full HTTP path) + +``` +[smoke] dist/ + dist-nightly/ already built — reusing +[smoke] ==== image: stable ==== +[smoke] init -y (run 1) +✓ ready (... image: stable) +[smoke] forgeplan-web.json#image = stable; build manifest image=stable, features=[] +[smoke] gitignore: 1 match (preserved user content) +[smoke] init -y --force (run 2 — must be idempotent) +✓ ready (... image: stable) +[smoke] gitignore: still 1 match after second init (idempotent) +[smoke] start (PORT=15769) +[smoke] server is up +[smoke] /api/health: ok (project=shim) +[smoke] /api/list: ok (0 entries) +[smoke] GET /: ok (HTML returned) +[smoke] PASS (image=stable) + +[smoke] ==== image: nightly ==== +[smoke] init -y --image nightly (run 1) +⚠ Using image "nightly" (non-stable). Behaviour may change between releases. +✓ ready (... image: nightly) +[smoke] forgeplan-web.json#image = nightly; build manifest image=nightly, features=[] +[smoke] gitignore: 1 match (preserved user content) +[smoke] init -y --image nightly --force (run 2 — must be idempotent) +✓ ready (... image: nightly) +[smoke] gitignore: still 1 match after second init (idempotent) +[smoke] start (PORT=15717) +[smoke] server is up +[smoke] /api/health: ok (project=shim) +[smoke] /api/list: ok (0 entries) +[smoke] GET /: ok (HTML returned) +[smoke] PASS (image=nightly) + +[smoke] ALL IMAGES PASS +``` + +Smoke harness asserts (per image): + +- `.forgeplan-web/index.js` exists. +- `.forgeplan-web/node_modules/` does **not** exist (bundle shape, not legacy). +- `forgeplan-web.json#image` matches the requested image. +- `forgeplan-web-build.json#image` matches. +- `forgeplan-web-build.json#features` is an array. +- `.gitignore` contains exactly one `.forgeplan-web/` entry across two + `init` invocations (idempotency). +- All three HTTP endpoints return 200 + envelope `{ ok: true, ... }`. + +→ **Satisfies SC-1, SC-2, SC-6, AC-1, AC-2, NFR-002.** + +### Measurement 3 — `--experimental` deprecation alias + +Manual scratch-dir run: + +``` +$ node bin/forgeplan-web.mjs init -y --experimental --force +forgeplan-web: warning: --experimental is deprecated and will be removed in 0.3.0; use --image nightly instead. +⚠ Using image "nightly" (non-stable). Behaviour may change between releases. +→ creating /tmp/.../.forgeplan-web +→ created .gitignore (added .forgeplan-web/) + +✓ ready (scope: project — /tmp/.../.forgeplan-web, image: nightly) + +$ jq -r '.image' .forgeplan-web/forgeplan-web.json +nightly + +$ jq -r '.image' .forgeplan-web/forgeplan-web-build.json +nightly +``` + +→ **Satisfies SC-3, AC-3, FR-005, FR-006.** + +### Measurement 4 — lifecycle validator (expired + over-3-minor) + +Synthetic fixtures injected into `config/features.json` then reverted: + +``` +# Fixture: expiresIn (0.1.5) ≤ currentVersion (0.1.13) +[build] config error: config/features.json: feature "synthetic-expired-flag" \ + expired (expiresIn=0.1.5, currentVersion=0.1.13); remove from features.json \ + + every image's features array +exit 1 + +# Fixture: lifetime 0.5.0-0.1.0 > 3 minor +[build] config error: config/features.json: feature "synthetic-too-long-lived" \ + lifetime 0.5.0-0.1.0 exceeds 3 minor versions; graduate or drop it \ + (rule: PRD-030 NFR-005) +exit 1 +``` + +Both produce a single descriptive stderr line and a non-zero exit. + +→ **Satisfies SC-5, AC-4, NFR-005.** + +## Reproduction + +From the repo root, on `feature/issue-121-feature-flag-images`: + +```bash +npm run build # measurement 1 +npm run smoke # measurement 2 +# measurement 3: +SCRATCH=$(mktemp -d) && mkdir -p "$SCRATCH/.forgeplan" && \ + SHIM=$(mktemp -d) && \ + printf '#!/usr/bin/env sh\nexec %s %s "$@"\n' "$(which node)" \ + "$PWD/scripts/test/forgeplan-shim.mjs" > "$SHIM/forgeplan" && \ + chmod +x "$SHIM/forgeplan" && \ + cd "$SCRATCH" && \ + PATH="$SHIM:$PATH" node "$OLDPWD/bin/forgeplan-web.mjs" init -y --experimental --force +# measurement 4: +# Manually inject a synthetic flag with expiresIn ≤ package.json#version into +# config/features.json then run `node scripts/build.mjs`. +``` + +## Implication + +PRD-030's success criteria SC-1..SC-6 are all satisfied by direct test +against the actual build + bin + server surface. The image-as-build- +artifact decision (ADR-005) holds — `start` remained image-agnostic and +required no changes; bin script picked up the right directory via +`bin/lib/images.mjs#imagePath`. Lifecycle validator forces the user- +required ≤3-minor cap mechanically. The legacy `dist/`-with- +`node_modules/` shape is gone from the published tarball without any +change to the user-visible install UX. + +→ Score should advance the chain to `R_eff > 0` and unblock activation +of PRD-030, RFC-026, ADR-005. + + + + diff --git a/.forgeplan/prds/PRD-030-feature-flag-and-image-system-promote-experimental-bundle-to-stable-default.md b/.forgeplan/prds/PRD-030-feature-flag-and-image-system-promote-experimental-bundle-to-stable-default.md new file mode 100644 index 0000000..4e0a510 --- /dev/null +++ b/.forgeplan/prds/PRD-030-feature-flag-and-image-system-promote-experimental-bundle-to-stable-default.md @@ -0,0 +1,302 @@ +--- +depth: standard +id: PRD-030 +kind: prd +status: active +title: Feature-flag and image system; promote experimental bundle to stable default +--- + +--- +id: PRD-030 +title: "Feature-flag and image system; promote experimental bundle to stable default" +status: Draft +author: nikitafedorovvvvv@gmail.com +created: 2026-05-09 +updated: 2026-05-09 +priority: P1 +depth: deep +domain: general +projectType: cli_tool +stepsCompleted: [] +--- + +# PRD-030: Feature-flag and image system; promote experimental bundle to stable default + +## Executive Summary + +### Vision + +`@forgeplan/web` ships **multiple named "images" of the scaffold** (today: `stable` + `nightly`) chosen at `init` time via `--image `, with a config-driven feature-flag registry that forces every flag to graduate or expire within 2-3 minor releases. The legacy SvelteKit-with-`node_modules/` shape is dropped; the bundle approach (PRD-014 / RFC-013) becomes the single artifact form for every image. + +### Problem + +Two related issues compounded into one product-shape decision: + +1. **Experimental bundle has been opt-in too long.** PRD-014 / RFC-013 introduced `dist-experimental/` as a single-file esbuild bundle (~9× smaller than legacy `dist/`). It ships behind `init --experimental`. Smoke tests, sweeps, and field use across multiple minor versions show it is at least as reliable as the legacy shape, but `--experimental` keeps it opt-in. Users on the slow path keep paying ~14 MB of `dist/node_modules/` per `init` for no upside. +2. **No graduation discipline for shape variants.** The repo has accumulated one ad-hoc opt-in (`--experimental`) with no policy on (a) when it graduates, (b) how to ship a *second* parallel variant, (c) how to keep experimental flags from accreting indefinitely. The only switch today is a single boolean. Adding a third parallel shape (e.g. an LTS line, or a feature-preview lane) would mean adding another ad-hoc boolean to `init`, `update`, and `forgeplan-web.json`. + +**Impact**: + +- Default `init` users still get the 14 MB shape in v0.1.x, ~9× larger than necessary. +- Adding a new track means duplicating ad-hoc plumbing in three places, each of which is a chance to forget one. +- Experimental flags (`--experimental` is the prototype) can drift indefinitely with no forcing function for graduation. + +### Target Users + +| Persona | Описание | Ключевая боль | +|---------|----------|---------------| +| End user of `npx @forgeplan/web init` | Запускает в чужом репо, expects sensible default | Сейчас платит за legacy shape; не имеет выбора между «стабильный» и «бета» без знания внутренних флагов | +| Maintainer пакета | Шипит multiple варианты scaffold'а | Нет фреймворка: каждый новый вариант = новый ad-hoc булевый флаг + три места правки | +| Adventure-mode user | Хочет получить early-access функции до общего релиза | Нет канала "nightly" с чёткой политикой что-там-внутри | + +### Differentiators + +- **Single source of truth for what ships.** `config/images.json` + `config/features.json` describe every image and every flag; `scripts/build.mjs` reads them; bin script reads the resulting `forgeplan-web-build.json`. No flag definitions scattered across files. +- **Graduation is enforced, not requested.** The build pipeline fails when any flag is older than its declared `expiresIn` vs the current `package.json#version`. The forcing function is mechanical. +- **Backwards compatible at the install surface.** `init` without flags keeps working (defaults to `stable`); `init --experimental` keeps working for one minor release with a deprecation warning aliasing to `--image nightly`. `forgeplan-web.json` with `experimental: true` is migrated on next `update`. + +--- + +## Success Criteria + +| ID | Criterion | Metric | Current | Target | Timeframe | How to Measure | +|----|-----------|--------|---------|--------|-----------|----------------| +| SC-1 | Default `init` produces the bundle shape | `! test -d .forgeplan-web/node_modules` after `init -y` | dist/node_modules exists (~12 MB) | path absent | до merge в develop | scripts/smoke.mjs assertion | +| SC-2 | `init --image nightly` writes a distinct image record | `forgeplan-web.json#image == "nightly"` | n/a (no field) | exact match | до merge в develop | jq assertion in smoke output | +| SC-3 | `init --experimental` works with deprecation warning | stderr matches `/deprecated.*--image nightly/i` | warning absent | warning present, exit 0 | до merge в develop | smoke / manual check | +| SC-4 | All emitted image directories ≤3 MB | `du -sb dist*/` | 14 MB legacy | ≤3 MB each | до merge в develop | scripts/build.mjs assertion (existing cap) | +| SC-5 | Build fails when a flag's expiry < current version | exit code of build with seeded expired flag | n/a (no validator) | non-zero exit | до merge в develop | unit assertion in build pipeline (synthetic flag fixture) | +| SC-6 | `npm run smoke` passes against both images | exit 0 | passes for legacy only | exit 0 for `stable` and `nightly` | до merge в develop | scripts/smoke.mjs with `--image` arg | +| SC-7 | Forgeplan artifacts validated and `R_eff > 0` | `forgeplan score PRD-030` | 0 (artifact draft) | >0 | до merge в develop | forgeplan score | + +--- + +## Product Scope + +### MVP (In-Scope) + +- `config/images.json` — image registry. Schema: `{ "$schema": "...", "images": { "": { "description": "...", "features": ["", ...] } } }`. v1 ships `stable` and `nightly`, both with empty feature lists. +- `config/features.json` — feature registry. Schema per entry: `{ id, description, addedIn (semver), expiresIn (semver), owner, rollout: "alpha"|"beta"|"stable" }`. v1 ships an empty array — framework only. +- Migration of `dist-experimental/` shape to be the universal artifact for every image. Legacy `dist/` (SvelteKit + `node_modules/`) is dropped. +- `scripts/build.mjs` reads `config/`, validates feature lifecycle (no flag where `currentVersion >= expiresIn`), bundles once via esbuild, then copies to `dist/` (for `stable`) and `dist-/` (for every other image), each with its own `forgeplan-web-build.json` carrying `{ image, features }`. +- `bin/commands/init.mjs` — new `--image ` flag, default `stable`, validated against existing image directories. `--experimental` is kept as deprecated alias for `--image nightly` with a stderr warning. +- `bin/commands/update.mjs` — same `--image` plumbing. Reads persisted `image` from `forgeplan-web.json`. Migration: if `experimental: true` is found, treat as `image: nightly`. +- `forgeplan-web.json` gains an `image` field. The `experimental` boolean stays for one minor release for read-back compatibility, then is dropped. +- `package.json#files` enumerates `dist`, `dist-nightly` (and any future image dirs explicitly). +- README + rule 21 + rule 23 updated. + +### Out of Scope + +- Per-feature runtime gating in the SvelteKit app. Flags are declared and shipped — what they *do* is the responsibility of the feature-PR that adds them. v1 ships an empty registry. +- Dropping `--experimental` outright in this PR. Kept as deprecated alias for one minor release; removal scheduled for the release after that. +- Spec'ing a third image (e.g. `lts`). Framework supports it, but no `lts/` image ships in this PR. +- Pruning the legacy `dist/` rebuild path right away. The `copyToDist()` / `installRuntimeDeps()` / `emitDistPackageJson()` functions are removed in this PR — they are not kept on a fallback path. + +### Growth Vision + +- Per-image release cadence (e.g. `nightly` cut from every `develop` merge; `stable` cut on tagged releases only). +- A third `lts` or `preview` image once a real flag wants its own track. +- Telemetry (opt-in) on which image users pick — informs whether `nightly` is worth maintaining. + +--- + +## User Journeys + +### Journey 1: End user — first install on the new scheme + +**Цель пользователя**: scaffold the viewer into their project, no surprises. + +| Шаг | Действие пользователя | Ответ системы | Заметки | +|-----|----------------------|---------------|---------| +| 1 | `npx @forgeplan/web init -y` in repo with `.forgeplan/` | Copies `dist/` (= bundle shape, the new stable) to `.forgeplan-web/`; writes `forgeplan-web.json` with `image: "stable"` | No flag needed; default is the `stable` image | +| 2 | `npx @forgeplan/web start` | Spawns `node .forgeplan-web/index.js` | Same UX as today | +| 3 | Inspects `.forgeplan-web/forgeplan-web-build.json` | `{ name, builtAt, entry, image: "stable", features: [] }` | UI/server can read this to gate behaviour later | + +**Результат**: same install UX as today; smaller artifact; image is recorded in config. + +### Journey 2: Adventure user — opts into nightly + +**Цель пользователя**: try the next-track image even though no flags are turned on yet. + +| Шаг | Действие пользователя | Ответ системы | Заметки | +|-----|----------------------|---------------|---------| +| 1 | `npx @forgeplan/web init --image nightly` | Copies `dist-nightly/` to `.forgeplan-web/`; writes `forgeplan-web.json` with `image: "nightly"` | Today nightly == stable bytes-wise (no flags), but the image-track is recorded | +| 2 | Later: `npx @forgeplan/web update` | Resolves the persisted `image: "nightly"` and refreshes from `dist-nightly/` of the new package version | No `--image` flag needed on update — track is sticky | +| 3 | Switch back: `npx @forgeplan/web update --image stable` | Switches to `dist/` and rewrites `image: "stable"` in config | Both directions supported | + +**Результат**: the user can pick a track explicitly; track is sticky across `update`s; switching is one flag away. + +### Journey 3: Existing user with `experimental: true` config + +**Цель пользователя**: keep working without rerunning `init`. + +| Шаг | Действие пользователя | Ответ системы | Заметки | +|-----|----------------------|---------------|---------| +| 1 | Has `forgeplan-web.json` with `experimental: true` from a previous version | n/a | Pre-existing state | +| 2 | Runs `npx @forgeplan/web update` after upgrading the package | `update` reads `experimental: true`, treats as `image: nightly`, refreshes from `dist-nightly/`, writes `image: "nightly"` to config (drops `experimental`) | Migration is one-way and silent (single log line) | +| 3 | Runs `npx @forgeplan/web init --experimental` | Init runs with `image: nightly` and prints a deprecation warning to stderr pointing to `--image nightly` | Removed in 0.3.0 | + +**Результат**: existing users do nothing; first `update` migrates them; CLI flag removal is announced. + +--- + +## Functional Requirements + +| ID | Category | Priority | Requirement | Journey | +|----|----------|----------|-------------|---------| +| FR-001 | Core | Must | Maintainer can declare images and the flags they include via a single JSON config | Journey 1, 2 | +| FR-002 | Core | Must | Maintainer can declare a flag's lifecycle (`addedIn`, `expiresIn`) so the build pipeline enforces graduation | Journey 1 | +| FR-003 | Core | Must | End user can choose an image at install time via `--image `, with `stable` as the default | Journey 1, 2 | +| FR-004 | Core | Must | End user can switch images via `update --image `; the choice is sticky in `forgeplan-web.json` for subsequent updates | Journey 2 | +| FR-005 | Compatibility | Must | Existing user with `experimental: true` in config gets migrated to `image: "nightly"` on first `update` without re-running `init` | Journey 3 | +| FR-006 | Compatibility | Should | `init --experimental` keeps working for one minor release as deprecated alias for `--image nightly`, with a stderr warning | Journey 3 | +| FR-007 | Build | Must | Build pipeline emits `dist/` for `stable` and `dist-/` for every other image, each with its own `forgeplan-web-build.json` carrying `{ image, features }` | Journey 1, 2 | +| FR-008 | Build | Must | Build pipeline fails non-zero when any flag in any image has `expiresIn ≤ currentVersion` | Journey 1 (indirect — author surface) | +| FR-009 | Operability | Should | `start` does not need to know about images; it spawns whatever sits at `.forgeplan-web/index.js` | Journey 1, 2 | +| FR-010 | Documentation | Must | README documents `--image` + image lifecycle policy + flag-graduation policy | Journey 1, 2 | + +--- + +## Non-Functional Requirements + +| ID | Category | Requirement | Metric | Condition | Measurement | +|----|----------|-------------|--------|-----------|-------------| +| NFR-001 | Size | Each emitted image directory must fit | ≤3 MB | After `npm run build`, before publish | `du -sb dist*/` assertion in scripts/build.mjs | +| NFR-002 | Compatibility | `start` must succeed against any emitted image without configuration changes | exit 0 + /api/health 200 | scripts/smoke.mjs run with each image | smoke output | +| NFR-003 | Build determinism | Repeated `npm run build` must produce per-image directories with the same byte content modulo `builtAt` timestamp | byte-diff = `forgeplan-web-build.json` only | Two consecutive builds on same git SHA | `diff -r dist*/` excluding `forgeplan-web-build.json` | +| NFR-004 | Bin allow-list | `bin/` must remain bound to `node:*` + `citty` after the change | grep on bin/**/*.mjs | All bin files | rule 23 verification block | +| NFR-005 | Lifecycle | No flag can persist past `expiresIn` once a release crossing that version is being built | exit code of `npm run build` | Synthetic fixture flag with expired version | unit harness inside scripts/build.mjs (or scripts/test/) | + +--- + +## Acceptance Criteria + +### AC-1: default install produces bundle shape + +```gherkin +Given a clean scratch directory with a `.forgeplan/` workspace and `forgeplan` on PATH +When the user runs `npx @forgeplan/web init -y` +Then the directory `.forgeplan-web/` is created +And `.forgeplan-web/index.js` exists +And `.forgeplan-web/node_modules/` does NOT exist +And `.forgeplan-web/forgeplan-web.json` contains `"image": "stable"` +And `.forgeplan-web/forgeplan-web-build.json` contains `"image": "stable"` and `"features": []` +``` + +### AC-2: nightly image install records track + +```gherkin +Given a clean scratch directory with a `.forgeplan/` workspace +When the user runs `npx @forgeplan/web init --image nightly` +Then `.forgeplan-web/forgeplan-web.json` contains `"image": "nightly"` +And `.forgeplan-web/forgeplan-web-build.json` contains `"image": "nightly"` +And the start command spawns the server successfully on a free port +``` + +### AC-3: deprecated --experimental aliases to nightly + +```gherkin +Given a clean scratch directory with a `.forgeplan/` workspace +When the user runs `npx @forgeplan/web init --experimental` +Then the exit code is 0 +And stderr contains a deprecation message pointing to `--image nightly` +And `.forgeplan-web/forgeplan-web.json` contains `"image": "nightly"` +``` + +### AC-4: build fails on expired flag + +```gherkin +Given the build harness is invoked with a synthetic feature whose `expiresIn` precedes the current `package.json#version` +When `node scripts/build.mjs` runs +Then the exit code is non-zero +And stderr names the offending flag id and the expiry version +``` + +### AC-5: build emits per-image manifests + +```gherkin +Given `config/images.json` lists `stable` and `nightly` +When `npm run build` completes successfully +Then `dist/forgeplan-web-build.json` contains `"image": "stable"` and `"features": []` +And `dist-nightly/forgeplan-web-build.json` contains `"image": "nightly"` and `"features": []` +And neither directory contains a `node_modules/` subdirectory +``` + +--- + +## Dependencies + +| Dependency | Type | Status | Owner | +|-----------|------|--------|-------| +| `template/` SvelteKit build pipeline | Internal | Stable | maintainers | +| `esbuild` ^0.24 (devDep) | Internal | Pinned | maintainers | +| `citty` ^0.2.2 (runtime dep, ADR-003) | Internal | Pinned | maintainers | +| Forgeplan workspace | Methodology | Active | maintainers | + +--- + +## Risks & Mitigations + +| ID | Risk | Probability | Impact | Mitigation | Owner | +|----|------|-------------|--------|------------|-------| +| R-1 | Dropping legacy `dist/` shape regresses a user we didn't catch in smoke | Low | High | One-version overlap of `--experimental` alias + smoke against both images + EvidencePack capturing exit codes; revert path is one commit (restore `copyToDist` + `installRuntimeDeps`) | maintainers | +| R-2 | Build-time lifecycle validator becomes annoying (false positives during release-train freeze) | Medium | Medium | Validator compares against `package.json#version` only; release engineer can explicitly bump `expiresIn` in `config/features.json` as part of the freeze | maintainers | +| R-3 | `--experimental` deprecation removed too early, breaks scripts | Medium | Low | Keep alias for explicitly-named single minor release before removal; CHANGELOG entry; deprecation warning printed every invocation | maintainers | +| R-4 | `config/images.json` and `package.json#files` drift (a new image is built but not packed) | Medium | High | Build pipeline asserts that every image directory it emits is referenced in `package.json#files`; CI fails otherwise | maintainers | + +--- + +## Timeline + +| Milestone | Target Date | Description | +|-----------|-------------|-------------| +| PRD activated | 2026-05-09 | This document, evidence-linked | +| RFC-026 activated | 2026-05-09 | Architecture for build pipeline + bin plumbing | +| ADR-005 activated | 2026-05-09 | Image-as-build-artifact decision | +| Implementation merged to develop | 2026-05-09 | PR closing issue #121 | +| Released in next minor (≥ 0.2.0) | TBD | Standard release/v* cycle from develop → main | +| `--experimental` flag removed | one minor after release (≥ 0.3.0) | Per FR-006 commitment | + +--- + +## Stakeholders + +| Role | Name | Sign-off | +|------|------|----------| +| Product Owner | nikitafedorovvvvv@gmail.com | [x] | +| Engineering Lead | nikitafedorovvvvv@gmail.com | [x] | +| Design | n/a | [x] | +| QA | smoke.mjs (machine) | [x] | + +--- + +## Affected Files + +- scripts/build.mjs +- bin/commands/init.mjs +- bin/commands/update.mjs +- bin/lib/config.mjs +- bin/lib/images.mjs (new) +- config/images.json (new) +- config/features.json (new) +- config/IMAGES.md (new) +- package.json +- README.md +- README.ru.md +- CHANGELOG.md +- .claude/rules/21-template-purity.md +- .claude/rules/23-bin-zero-deps.md + +## Related Artifacts + +| Artifact | Relation | Status | +|----------|----------|--------| +| PRD-014 | informs (esbuild bundle origin) | active | +| RFC-013 | supersedes the `--experimental`-as-feature-flag scheme | active | +| RFC-026 | architecture for this PRD | this PR | +| ADR-005 | image-as-build-artifact (vs runtime) | this PR | +| EvidencePack (created by this PR) | smoke evidence for SC-1..SC-6 | this PR | + + + + diff --git a/.forgeplan/rfcs/RFC-026-image-manifest-and-build-pipeline-for-feature-flag-system-stable-nightly.md b/.forgeplan/rfcs/RFC-026-image-manifest-and-build-pipeline-for-feature-flag-system-stable-nightly.md new file mode 100644 index 0000000..445aa2f --- /dev/null +++ b/.forgeplan/rfcs/RFC-026-image-manifest-and-build-pipeline-for-feature-flag-system-stable-nightly.md @@ -0,0 +1,282 @@ +--- +depth: standard +id: RFC-026 +kind: rfc +links: +- target: PRD-030 + relation: informs +- target: ADR-005 + relation: informs +status: active +title: Image manifest and build-pipeline for feature-flag system (stable + nightly) +--- + +--- +id: RFC-026 +title: "Image manifest and build-pipeline for feature-flag system (stable + nightly)" +status: Draft +author: nikitafedorovvvvv@gmail.com +created: 2026-05-09 +updated: 2026-05-09 +prd: PRD-030 +depth: deep +informs: PRD-030 +amends: RFC-013 +--- + +# RFC-026: Image manifest and build-pipeline for feature-flag system (stable + nightly) + +## Summary + +Replace the single `--experimental` boolean with a config-driven multi-image pipeline: + +1. `config/images.json` lists every image (`stable`, `nightly`, …) and the flags each one ships. +2. `config/features.json` lists every flag with `addedIn` / `expiresIn` semver markers; build fails when any flag's `expiresIn ≤ currentVersion` or when the gap exceeds 3 minor versions. +3. `scripts/build.mjs` bundles `template/build/index.js` once via esbuild (already done today for `dist-experimental/`), then copies the bundle output into `dist/` (for `stable`) and `dist-/` (for every other image), each with its own `forgeplan-web-build.json` carrying `{ image, features }`. +4. `bin/commands/init.mjs` accepts `--image ` (default `stable`); `--experimental` becomes a deprecated alias for `--image nightly` for one minor release. +5. `bin/commands/update.mjs` reads the persisted `image` from `forgeplan-web.json` and refreshes from the matching `dist*/`. + +Legacy SvelteKit-with-`node_modules/` shape is dropped from the published tarball — graduating PRD-014 / RFC-013. + +## Motivation + +See PRD-030. Two pressures merge: + +- **Graduation of the bundle shape.** RFC-013 explicitly framed `dist-experimental/` as a temporary parallel artifact pending field validation. Validation is sufficient. Keeping the legacy `dist/` doubles the tarball size and the maintenance surface. +- **Need for >2 parallel tracks.** A single boolean (`experimental`) does not scale to a third or fourth image. We want a registry, not a series of ad-hoc booleans. + +The flag-lifecycle constraint (≤2-3 minor releases) comes from the user requirement: experimental flags must expire so nothing accretes silently. + +## Goals / Non-Goals + +### Goals + +- **G1**: `config/images.json` is the single source of truth for image membership (image → flags). +- **G2**: `config/features.json` is the single source of truth for flag metadata (`addedIn`, `expiresIn`, `rollout`). +- **G3**: `scripts/build.mjs` emits one directory per image; `dist/` is reserved for `stable`; other images go to `dist-/`. +- **G4**: Each emitted directory contains a `forgeplan-web-build.json` carrying `{ name, builtAt, entry, image, features }`. Bundle bytes are identical across images that share the same flag set; only the JSON differs. +- **G5**: `init` and `update` accept `--image `; `start` is image-agnostic. +- **G6**: Build pipeline fails fast on lifecycle violations (flag past `expiresIn` or beyond 3-minor window). +- **G7**: `--experimental` keeps working as deprecated alias for `--image nightly` for exactly one minor release. +- **G8**: `bin/` allow-list (rule 23: `node:* + citty + relative siblings`) unchanged. + +### Non-Goals + +- **NG1**: Per-image runtime gating logic. v1 ships with empty feature lists; what flags *do* is the next PR's problem. +- **NG2**: Telemetry on which image users pick. +- **NG3**: Custom adapter / replacing adapter-node. +- **NG4**: Minification / further size reduction beyond what RFC-013's bundle already does. +- **NG5**: A graduation-bot that rewrites `expiresIn`. Manual. + +## Options Considered + +### Option A (chosen): one bundle, multiple `dist*/` outputs, image declared in `forgeplan-web-build.json` + +Build SvelteKit once, bundle once via esbuild, then copy the bundle to N image-named directories. Each directory's `forgeplan-web-build.json` records the image name + feature list. The bytes of `index.js` / `client/` / `env.js` are identical across images that share the same flag set; only the manifest JSON differs. `package.json#files` enumerates each image directory. + +**Pro**: + +- Reuses the existing esbuild pipeline (RFC-013). +- `start` stays image-agnostic — it just spawns `index.js`. +- Adding an image is a 2-line change in `config/images.json` plus a `package.json#files` entry. +- Deterministic across builds (modulo `builtAt`). +- Backwards-compatible `dist/` path (so `init -y` users see no change in install output paths). + +**Con**: + +- Tarball ships duplicate bundle bytes when N images share an empty feature set. v1 with 2 empty images means ~1.4 MB of duplication. +- *Mitigation*: tarball size cap + future de-duplication step (out of scope for v1). + +### Option B (rejected): one bundle, runtime-only flags via `forgeplan-web.json` + +Single `dist/`. `init --image ` writes the chosen image into `forgeplan-web.json`; the runtime SvelteKit server reads it and gates behaviour with `if (features.includes("X"))`. + +**Pro**: + +- No duplication; one bundle for all images. + +**Con**: + +- All flag code paths ship in every install. A flag in `nightly` only is still bytes in every `stable` user's install. Doesn't fit the "image" mental model the user asked for. +- Removing a graduated flag from `nightly` doesn't reduce installed code size unless it's also removed from the source. +- Reviewer can't quickly see "what does the nightly image actually contain" — the answer is "all the code, gated at runtime." + +### Option C (rejected): one full `npm` package per image (e.g. `@forgeplan/web-nightly`) + +**Pro**: + +- Maximum isolation; each image is its own dependency. + +**Con**: + +- 2× publish surface, 2× release pipeline, 2× CHANGELOG. Disproportionate for what we have today. +- Doesn't compose to N images well (would need N packages). + +### Option D (rejected): keep `--experimental` boolean, add `--lts` boolean later + +**Pro**: + +- Smallest immediate diff. + +**Con**: + +- Combinatorial — N image flags = 2^N implicit combinations. Doesn't scale. +- No registry, no lifecycle, no graduation discipline. Punts on the user's actual requirement. + +## Architecture + +The system has four physical layers, all of which derive from one source of truth (`config/`): + +``` +config/ ← author-edited, source of truth + images.json (image → flags mapping) + features.json (flag metadata) + ↓ (read at build-time) +scripts/build.mjs ← validator + emitter + ├─ validateLifecycle(config, version) ← rule 11-style fail-fast + ├─ bundleBaseDist() ← esbuild, one shot + └─ emitImageDist(imageName, features) ← per-image cp + manifest write + ↓ (writes to filesystem) +dist/ forgeplan-web-build.json: { image: "stable", features: [] } +dist-nightly/ forgeplan-web-build.json: { image: "nightly", features: [] } + ↓ (packed in tarball via package.json#files) +@forgeplan/web@x.y.z (npm) + ↓ (npx) +bin/forgeplan-web.mjs ← reads --image, picks dist*/ + ├─ commands/init.mjs (--image , default stable) + ├─ commands/update.mjs (sticky --image from forgeplan-web.json) + └─ lib/images.mjs (imagePath, isValidImageName, listAvailableImages) + ↓ (cpSync) +/.forgeplan-web/ ← user's scaffold + forgeplan-web.json: { image: "stable", ... } + forgeplan-web-build.json: { image: "stable", features: [] } + index.js, client/, env.js, ... +``` + +**Invariant**: every directory listed in `package.json#files` matching `dist*/` is also listed in `config/images.json#images`, and vice versa. Build pipeline asserts this. + +**Invariant**: bin script never reads `config/` at runtime — the build pipeline materializes everything bin needs into `dist*/forgeplan-web-build.json`. + +## Implementation Phases + +### Phase 1 — Config and validator + +Files: + +- `config/images.json` — image registry (v1: `stable`, `nightly`, both with empty `features`). +- `config/features.json` — feature registry (v1: empty `features` array). +- `config/IMAGES.md` — human docs: how to add an image, how to add a flag, lifecycle policy. + +Validator (in `scripts/build.mjs`, run before any artifact emission): + +1. Parse both JSON files; validate schemas (string keys, arrays where required). +2. Read `package.json#version` (current). +3. For each entry in `features.json`: + - Assert `addedIn` and `expiresIn` are valid semvers and `expiresIn > addedIn`. + - Assert `currentVersion < expiresIn` (strict). If `>=`, fail with the offending flag id and target version. + - Assert `expiresIn` is at most 3 minor versions past `addedIn` (i.e. `parseSemver(expiresIn).minor - parseSemver(addedIn).minor ≤ 3`, allowing major bumps to reset). +4. For each entry in `images.json#images..features`: + - Assert every named flag exists in `features.json`. + +Failure → non-zero exit, single stderr line per violation. + +### Phase 2 — Build emission per image + +Refactor `scripts/build.mjs`: + +- Drop `installRuntimeDeps()`, `emitDistPackageJson()`, `copyToDist()`. Their only purpose was to produce the legacy SvelteKit shape. +- Rename `bundleExperimentalDist()` → `bundleBaseDist()`. Its output goes to a temp directory `dist-base/` (gitignored), or stays as a re-usable in-memory artifact. +- New `emitImageDist(imageName, features)`: + - Compute target: `dist/` if `imageName === "stable"`, else `dist-${imageName}/`. + - `rmSync(target)` then `cpSync(BUNDLE_BASE, target)`. + - Write `target/forgeplan-web-build.json` with `{ name: "@forgeplan/web", builtAt, entry: "index.js", image: imageName, features }`. + - `patchHostDefault(target)` (already proven on dist-experimental). + - Assert `du -sb target ≤ 3 MB`. +- Loop over `Object.entries(images.images)` and call `emitImageDist`. +- Drop `--skip-experimental`. Add `--only=` for partial rebuilds (devloop convenience). +- Sanity gate: `package.json#files` MUST include every emitted directory; build fails otherwise. + +### Phase 3 — Bin plumbing + +`bin/lib/images.mjs` (new): + +```js +// Exports: +// imageDirName(imageName) → "dist" | "dist-" +// imagePath(pkgRoot, imageName) → absolute path +// isValidImageName(name) → boolean (regex /^[a-z][a-z0-9-]*$/) +// listAvailableImages(pkgRoot) → ["stable", "nightly", ...] (probes filesystem) +``` + +`bin/commands/init.mjs`: + +- Replace `experimental` arg with `image: { type: "string", description: "image name (default: stable)", valueHint: "stable|nightly" }`. +- Keep `experimental` as a hidden alias arg; if `args.experimental === true && args.image == null`, set `image = "nightly"` and print stderr deprecation pointing to `--image nightly`. +- `runInit` takes `{ image: "stable" | "nightly" | ... }`. Resolves dir via `imagePath(PKG_ROOT, image)`. `existsSync(dir)` → fail otherwise. +- `forgeplan-web.json` writer adds `image` field. `experimental` field is no longer written. + +`bin/commands/update.mjs`: + +- Same `--image` plumbing. +- Migration block: when reading existing config, if `image` is missing but `experimental === true`, treat as `image: "nightly"`. Write the new shape on next save. + +`bin/lib/config.mjs`: + +- `readConfig` returns the new shape; downstream code uses `cfg.image ?? (cfg.experimental ? "nightly" : "stable")` for read-back compat. + +### Phase 4 — Docs and rules + +- README.md / README.ru.md: document `--image` + image lifecycle policy + flag-graduation policy (≤3 minor versions). +- `config/IMAGES.md`: detailed maintainer guide. +- Rule 21 (`template-purity`): replace "the bundle approach is opt-in" language with "the bundle approach is the single artifact form for every image; `dist/` for stable, `dist-/` for others." +- Rule 23 (`bin-zero-deps`): note `bin/lib/images.mjs` as a sibling module (allowed by rule); no new third-party deps. +- CLAUDE.md: replace `dist-experimental/` references with image-aware language; document `config/`. +- CHANGELOG: BREAKING CHANGE entry under Unreleased / next minor. + +### Phase 5 — Smoke and evidence + +- Extend `scripts/smoke.mjs` to run twice: once with default `init -y` and once with `init -y --image nightly`. Both must reach `exit 0` + `/api/health 200` + `/api/list 200` + `GET / 200`. +- EvidencePack with `## Structured Fields` (`verdict: supports`, `congruence_level: 3`, `evidence_type: test`) capturing both runs. +- Activate PRD-030 / RFC-026 / ADR-005 once `R_eff > 0`. + +## Risks and Mitigations + +| Risk | Probability | Impact | Mitigation | +|------|-------------|--------|------------| +| Bundle byte-duplication grows tarball materially as more images ship | Low | Medium | NFR-001 caps each `dist*/` ≤3 MB; alarm in CHANGELOG when total tarball >10 MB | +| Schema drift between `config/images.json` and `config/features.json` | Medium | Medium | Build-time validator (Phase 1) cross-references; test fixture exercises an unknown-flag-id case | +| Removing legacy SvelteKit shape surfaces a user we missed in smoke | Low | High | Smoke matrix on ubuntu/macos/windows + Node 20.19 / 22 (existing CI); revert path is a single commit | +| `--experimental` deprecation warning gets ignored | Medium | Low | Print on every invocation, not once; CHANGELOG entry; remove in announced minor | + +## Affected Files + +- scripts/build.mjs +- bin/commands/init.mjs +- bin/commands/update.mjs +- bin/lib/config.mjs +- bin/lib/images.mjs (new) +- config/images.json (new) +- config/features.json (new) +- config/IMAGES.md (new) +- package.json +- README.md +- README.ru.md +- CHANGELOG.md +- .claude/rules/21-template-purity.md +- .claude/rules/23-bin-zero-deps.md +- CLAUDE.md +- scripts/smoke.mjs (extended for --image) + +## Related Artifacts + +| Artifact | Relation | Status | +|----------|----------|--------| +| PRD-030 | informs | this PR | +| ADR-005 | informs (image-as-artifact decision) | this PR | +| PRD-014 | based_on (esbuild bundle motivation) | active | +| RFC-013 | amends (graduates `--experimental`) | active | +| ADR-003 | based_on (citty-only bin allow-list, unchanged) | active | + + + + diff --git a/.gitignore b/.gitignore index aa786d9..d3a07c3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,8 +8,10 @@ template/build/ template/dist/ # pre-built artifacts published to npm — regenerated by `npm run build` +# (one dist*/ per declared image in config/images.json — PRD-030 / RFC-026 / ADR-005) dist/ -dist-experimental/ +dist-*/ +.dist-base/ # scratch dev runs of `init` against this repo .forgeplan-web/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 919fe6e..08982bb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,50 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added (PRD-030 / RFC-026 / ADR-005 — feature-flag + image system) + +- **Multi-image scaffold pipeline** — `@forgeplan/web` now ships named + "images" of the scaffold. v1 ships two: `stable` (default) and `nightly`. + Each image is a `dist*/` directory in the npm tarball with its own + `forgeplan-web-build.json` manifest (image name + feature list). +- **`--image ` CLI flag** on `init` and `update`, default `stable`. + Choice is sticky in `forgeplan-web.json`. `update --image nightly` + switches tracks. +- **`config/images.json` + `config/features.json`** — single source of + truth for what images ship and what feature flags each image includes. + See [`config/IMAGES.md`](config/IMAGES.md) for the maintainer guide. +- **Build-time lifecycle validator** — `scripts/build.mjs` fails fast + when any feature flag has `expiresIn ≤ currentVersion` or when a + flag's lifetime exceeds 3 minor versions. Forces graduation. +- **Per-image smoke test** — `npm run smoke` exercises both `stable` + and `nightly`. + +### Changed (PRD-030 / RFC-026 — graduates PRD-014 / RFC-013) + +- **Bundle approach is now the universal artifact form for every + image.** The legacy SvelteKit-with-`node_modules/` shape (≈14 MB) is + removed from the published tarball. Every emitted `dist*/` is the + ~1.8 MB esbuild single-file bundle, capped at 3 MB. +- **`forgeplan-web.json` gains an `image` field**; existing scaffolds + with `experimental: true` are migrated to `image: "nightly"` on first + `update`. + +### Deprecated + +- **`--experimental` flag** on `init` and `update` — now a deprecated + alias for `--image nightly`. Prints a stderr warning on every + invocation. **Removed in 0.3.0.** + +### Removed (BREAKING — only relevant if you depend on internals) + +- `dist-experimental/` directory in the published tarball is replaced by + `dist-nightly/`. Users running `npx @forgeplan/web init` see no + change; consumers that pinned the directory name in scripts must + switch to `dist-nightly/`. +- Legacy build pipeline functions `installRuntimeDeps()`, + `emitDistPackageJson()`, `copyToDist()` removed from + `scripts/build.mjs`. + ## [0.1.13] - 2026-05-08 ### Added (PRD-018 / RFC-016 — shared/ui catalogue) diff --git a/CLAUDE.md b/CLAUDE.md index 0a0efbd..9a98d2f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,13 +11,16 @@ Four surfaces in this repo: - `bin/forgeplan-web.mjs` — Node ≥ 20.19 / 22.12 zero-dep CLI (init / start). - `template/` — SvelteKit source. **Repo-internal**, NOT published. -- `dist/` — pre-built SvelteKit app (`vite build` + `npm install --omit=dev`). - Generated by `scripts/build.mjs`. **Published**, copied verbatim into +- `dist/` — pre-built SvelteKit app for the `stable` image (`vite build` + + esbuild single-file bundle, ~1.8 MB, no `node_modules/`). Generated + by `scripts/build.mjs`. **Published**, copied verbatim into `.forgeplan-web/` by `init`. **Default** source for `init`. -- `dist-experimental/` — single-file ESM bundle (`vite build` + esbuild). - ≈9× smaller than legacy `dist/` (no `node_modules/`). **Published** but - opt-in: copied to `.forgeplan-web/` only when `init --experimental` is - passed. Will replace legacy `dist/` after graduation (PRD-014 / RFC-013). +- `dist-nightly/` (and any other `dist-/`) — same bundle shape + for non-default images. **Published**; copied to `.forgeplan-web/` + only when `init --image ` is passed. v1 ships only `nightly`. + Image registry: `config/images.json`. Feature-flag registry: + `config/features.json`. Lifecycle policy: `config/IMAGES.md`. See + PRD-030 / RFC-026 / ADR-005. Read this file, then `.claude/rules/00-index.md`, before planning any work. @@ -100,9 +103,15 @@ scripts/ build.mjs # vite build + emit dist/package.json + npm i --omit=dev dist/ # pre-built artifact (legacy default). Copied into .forgeplan-web/ # contains: index.js, handler.js, server/, client/, node_modules/, package.json -dist-experimental/ # pre-built artifact (esbuild single-file bundle, opt-in via - # `init --experimental`). PRD-014 / RFC-013. - # contains: index.js (single ESM bundle), env.js, client/, package.json +dist-nightly/ # pre-built artifact for the `nightly` image, same bundle + # shape as dist/. Opt-in via `init --image nightly`. + # PRD-030 / RFC-026 / ADR-005. + # contains: index.js (single ESM bundle), env.js, client/, + # package.json, forgeplan-web-build.json +config/ # image + feature-flag registries (PRD-030) + images.json # image name → flags + features.json # flag id → metadata (addedIn, expiresIn, owner, rollout) + IMAGES.md # maintainer guide .forgeplan/ # PRD/RFC/ADR/Spec/Epic + EvidencePacks (markdown) .claude/ rules/ # enforced rules @@ -116,15 +125,15 @@ package.json # publishable npm package — `@forgeplan/web`, files: [b `bin/forgeplan-web.mjs` runs in the user's project directory. `init` (1) verifies `.forgeplan/` exists and the `forgeplan` binary is on -`PATH`, (2) copies the package's bundled `dist/` (or `dist-experimental/` -when `--experimental` is passed) → `.forgeplan-web/` (skipping existing -files unless `--force`), (3) writes `forgeplan-web.json` with -`workspaceRoot`, `version`, `experimental` so the SvelteKit server knows -where to spawn `forgeplan` and `update` knows which shape to refresh into. -**No `npm install` runs at user side** — both artifacts are pre-built: -`dist/` ships `node_modules/` populated with `--omit=dev`, while -`dist-experimental/` ships a single esbuild bundle with all runtime deps -inlined (no `node_modules/`). `start` spawns `node .forgeplan-web/index.js` +`PATH`, (2) copies the package's bundled image (`dist/` for `stable` +by default, `dist-/` when `--image ` is passed) → +`.forgeplan-web/` (skipping existing files unless `--force`), +(3) writes `forgeplan-web.json` with `workspaceRoot`, `version`, +`image`, `scope` so the SvelteKit server knows where to spawn +`forgeplan` and `update` knows which image to refresh into. +**No `npm install` runs at user side** — every shipped image is a +self-contained esbuild bundle with all runtime deps inlined (no +`node_modules/`). `start` spawns `node .forgeplan-web/index.js` with `PORT`/`HOST`/`FORGEPLAN_CWD`/`FORGEPLAN_BIN` env (works against both shapes — `start` doesn't know which artifact was copied). The SvelteKit server exposes `/api/*` endpoints that `spawn` the host's diff --git a/README.md b/README.md index eeae0af..ec29fa0 100644 --- a/README.md +++ b/README.md @@ -98,17 +98,34 @@ Requires Node `^20.19.0 || >=22.12.0`, the `forgeplan` CLI on PATH, and a `.forgeplan/` workspace in the current directory. Full reference — [`docs/USAGE.md`](docs/USAGE.md). -### Experimental: lightweight bundled dist (≈9× smaller) +### Images: `stable` (default) and `nightly` ```bash -npx @forgeplan/web init -y --experimental +npx @forgeplan/web init -y # stable (default) +npx @forgeplan/web init -y --image nightly # pre-release track ``` -Copies a single-file esbuild bundle (~1.5 MB) into `.forgeplan-web/` -instead of the legacy 14 MB tree with `node_modules/`. Same CLI, same -endpoints, same envelope shape. Stable for most cases — opt-in until it -graduates as the default. Report regressions on -[GitHub Issues](https://github.com/ForgePlan/forgeplan-web/issues). +Every release ships two named **images** of the scaffold. The bytes are +the same self-contained ~1.8 MB single-file bundle (no `node_modules/`, +no `npm install` at user side); the difference is the feature-flag set +each image carries. v1 ships both images with **zero** flags — the +framework is in place for opt-in features without users-of-stable +paying for them. + +- **`stable`** — default for `init` / `update`. Ships only flags whose + rollout has reached stable. +- **`nightly`** — early-access track. Ships every flag, including + alpha/beta. Use when you want pre-release behaviour and don't mind + changes between minor versions. + +Switch tracks: `npx @forgeplan/web update --image `. The choice +is sticky — recorded in `forgeplan-web.json` for subsequent updates. + +`--experimental` is a deprecated alias for `--image nightly` (kept for +one minor release; removed in 0.3.0). + +See [`config/IMAGES.md`](config/IMAGES.md) for the maintainer's view of +how images and flags are declared. ## 60-Second Demo @@ -141,7 +158,7 @@ appear in seconds (after `forgeplan reindex`). | | | | :-------------------------- | :-------------------------------------------------------------------------------------------------------------------- | -| **📦 Zero install at user** | The package ships `dist/` with `node_modules/` baked in (or `dist-experimental/`, a ~1.5 MB single-file bundle, opt-in via `--experimental`). `init` is a `cp -r`. No `npm install` runs at user side. | +| **📦 Zero install at user** | The package ships one self-contained ~1.8 MB single-file bundle per declared image (`dist/` for `stable`, `dist-nightly/` for `nightly`). `init` is a `cp -r` — no `npm install` runs at user side. | | **🪟 Truly cross-platform** | Smoke matrix on `ubuntu-latest` / `macos-latest` / `windows-latest` × Node 22, green on every push since v0.1.3. | | **🔒 Read-only by design** | `/api/*` proxy invokes only read-only `forgeplan` subcommands (rule 22). The viewer **cannot mutate** your workspace. | | **🌐 Five graph views** | Force, Lanes, Matrix, Radial, Tree. Each picks a different question — flow, adjacency, hierarchy, parent/child. | diff --git a/bin/commands/init.mjs b/bin/commands/init.mjs index 95e65f2..8ca1793 100644 --- a/bin/commands/init.mjs +++ b/bin/commands/init.mjs @@ -12,6 +12,13 @@ import { ensureForgeplanWorkspace, } from "../lib/forgeplan-binary.mjs"; import { ensureGitignore } from "../lib/gitignore.mjs"; +import { + imagePath, + isValidImageName, + listAvailableImages, + NIGHTLY_IMAGE, + STABLE_IMAGE, +} from "../lib/images.mjs"; import { promptScope } from "../lib/prompt.mjs"; import { isValidScope, @@ -20,9 +27,6 @@ import { 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); @@ -51,40 +55,51 @@ function copyDir(src, dest, force) { export async function runInit({ scope, + image = STABLE_IMAGE, force = false, quiet = false, skipGitignore = false, - experimental = false, cwd = process.cwd(), } = {}) { if (!isValidScope(scope)) { fail(`internal: runInit called with invalid scope "${scope}"`); } + if (!isValidImageName(image)) { + fail( + `invalid --image value "${image}"; expected one of: ${ + listAvailableImages(PKG_ROOT).join(", ") || "stable" + }.`, + ); + } const log = (line) => { if (!quiet) process.stdout.write(line + "\n"); }; - const DIST_DIR = experimental ? DIST_DIR_EXPERIMENTAL : DIST_DIR_LEGACY; + const sourceDir = imagePath(PKG_ROOT, image); + if (!existsSync(sourceDir)) { + const available = listAvailableImages(PKG_ROOT); + fail( + `image "${image}" not bundled in this @forgeplan/web (looked for ${sourceDir}).\n` + + ` Available image(s): ${available.length > 0 ? available.join(", ") : "(none)"}.`, + ); + } if (scope === "project") { ensureForgeplanWorkspace(cwd, fail); } ensureForgeplanBinary(fail); - if (experimental) { - log( - "⚠ Using experimental bundled dist (single-file server, no node_modules/).", - ); + if (image !== STABLE_IMAGE) { log( - " Report issues at https://github.com/ForgePlan/forgeplan-web/issues", + `⚠ Using image "${image}" (non-stable). Behaviour may change between releases.`, ); } const target = scopePath(scope, cwd); const fresh = !existsSync(target); log(fresh ? `→ creating ${target}` : `→ updating ${target}`); - copyDir(DIST_DIR, target, force); + copyDir(sourceDir, target, force); const now = new Date().toISOString(); const existing = fresh ? null : readConfig(target); @@ -93,7 +108,7 @@ export async function runInit({ createdAt: existing?.createdAt ?? now, version: readPkgVersion() ?? existing?.version ?? null, updatedAt: now, - experimental, + image, scope, }; writeFileSync(join(target, CFG_FILE), JSON.stringify(cfg, null, 2) + "\n"); @@ -105,15 +120,15 @@ export async function runInit({ log(""); log( scope === "user" - ? `✓ ready (scope: user — ${userScopePath()})` - : `✓ ready (scope: project — ${projectScopePath(cwd)})`, + ? `✓ ready (scope: user — ${userScopePath()}, image: ${image})` + : `✓ ready (scope: project — ${projectScopePath(cwd)}, image: ${image})`, ); log(" npx @forgeplan/web start"); if (scope === "project") { log(" # or: node .forgeplan-web/index.js"); } - return { scope, target }; + return { scope, target, image }; } export default defineCommand({ @@ -143,10 +158,14 @@ export default defineCommand({ description: "append `.forgeplan-web/` to ./.gitignore (project scope only; pass --no-gitignore to skip)", }, + image: { + type: "string", + description: `image name (default: ${STABLE_IMAGE}); see config/IMAGES.md`, + valueHint: "stable|nightly", + }, experimental: { type: "boolean", - description: - "[EXPERIMENTAL] use the bundled single-file dist (~9x smaller, no node_modules/)", + description: `[DEPRECATED] alias for --image ${NIGHTLY_IMAGE}; will be removed in 0.3.0`, }, scope: { type: "string", @@ -162,6 +181,22 @@ export default defineCommand({ const SKIP_GITIGNORE = args.gitignore === false; const EXPERIMENTAL = args.experimental === true; + let image = STABLE_IMAGE; + if (typeof args.image === "string" && args.image.length > 0) { + if (!isValidImageName(args.image)) { + fail( + `invalid --image value "${args.image}"; expected lowercase kebab-case (e.g. "stable", "nightly").`, + ); + } + image = args.image; + } else if (EXPERIMENTAL) { + // TODO(0.3.0): drop --experimental alias entirely (PRD-030 / RFC-026 FR-006). + process.stderr.write( + `forgeplan-web: warning: --experimental is deprecated and will be removed in 0.3.0; use --image ${NIGHTLY_IMAGE} instead.\n`, + ); + image = NIGHTLY_IMAGE; + } + let scope = null; if (args.scope) { if (!isValidScope(args.scope)) { @@ -192,10 +227,10 @@ export default defineCommand({ await runInit({ scope, + image, force: FORCE, quiet: QUIET, skipGitignore: SKIP_GITIGNORE, - experimental: EXPERIMENTAL, }); }, }); diff --git a/bin/commands/update.mjs b/bin/commands/update.mjs index fcc9ffa..60ddbbf 100644 --- a/bin/commands/update.mjs +++ b/bin/commands/update.mjs @@ -18,6 +18,13 @@ import { ensureForgeplanBinary, ensureForgeplanWorkspace, } from "../lib/forgeplan-binary.mjs"; +import { + imagePath, + isValidImageName, + listAvailableImages, + NIGHTLY_IMAGE, + STABLE_IMAGE, +} from "../lib/images.mjs"; import { isValidScope, projectScopePath, @@ -25,9 +32,6 @@ import { 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); @@ -54,7 +58,6 @@ function resolveTargetForUpdate({ explicitScope, cwd }) { } 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 }; @@ -67,7 +70,19 @@ function resolveTargetForUpdate({ explicitScope, cwd }) { `no scaffold found at ${projectRoot} or ${userRoot}.\n` + ` Run \`npx @forgeplan/web init [--scope user|project]\` first.`, ); - return null; // unreachable; fail() exits + return null; +} + +function resolvePersistedImage(existingCfg) { + if (typeof existingCfg?.image === "string" && isValidImageName(existingCfg.image)) { + return existingCfg.image; + } + // FR-005: backwards-compat — older scaffolds wrote `experimental: true` + // before the --image flag existed. Treat as `nightly` and overwrite. + if (existingCfg?.experimental === true) { + return NIGHTLY_IMAGE; + } + return STABLE_IMAGE; } export default defineCommand({ @@ -87,10 +102,16 @@ export default defineCommand({ alias: "q", description: "suppress informational output", }, + image: { + type: "string", + description: + "switch to a specific image (default: keep persisted choice; new scaffolds: stable)", + valueHint: "stable|nightly", + }, experimental: { type: "boolean", description: - "switch to the experimental bundled dist (overrides persisted choice)", + "[DEPRECATED] alias for --image nightly; will be removed in 0.3.0", }, scope: { type: "string", @@ -132,35 +153,48 @@ export default defineCommand({ 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; + let image = resolvePersistedImage(existing); + if (typeof args.image === "string" && args.image.length > 0) { + if (!isValidImageName(args.image)) { + fail( + `invalid --image value "${args.image}"; expected lowercase kebab-case (e.g. "stable", "nightly").`, + ); + } + image = args.image; + } else if (args.experimental === true) { + // TODO(0.3.0): drop --experimental alias entirely (PRD-030 / RFC-026 FR-006). + process.stderr.write( + `forgeplan-web: warning: --experimental is deprecated and will be removed in 0.3.0; use --image ${NIGHTLY_IMAGE} instead.\n`, + ); + image = NIGHTLY_IMAGE; } - const fromLabel = fromVersion ? `v${fromVersion}` : "unknown"; - const toLabel = toVersion ? `v${toVersion}` : "unknown"; - log(`→ updating ${target} (${fromLabel} → ${toLabel}, scope: ${scope})`); - + const sourceDir = imagePath(PKG_ROOT, image); if (!existsSync(sourceDir)) { + const available = listAvailableImages(PKG_ROOT); fail( - `pre-built artifact missing at ${sourceDir}.\n` + - ` Reinstall @forgeplan/web or build from source via \`npm run build\`.`, + `image "${image}" not bundled in this @forgeplan/web (looked for ${sourceDir}).\n` + + ` Available image(s): ${available.length > 0 ? available.join(", ") : "(none)"}.`, ); } + const fromImage = existing?.image ?? (existing?.experimental ? NIGHTLY_IMAGE : null); + const sameVersion = + !FORCE && fromVersion && toVersion && fromVersion === toVersion; + const sameImage = !fromImage || fromImage === image; + if (sameVersion && sameImage) { + log(`✓ already at v${toVersion} (scope: ${scope}, image: ${image})`); + log(" Use --force to re-copy anyway."); + return; + } + + const fromLabel = fromVersion ? `v${fromVersion}` : "unknown"; + const toLabel = toVersion ? `v${toVersion}` : "unknown"; + const imageNote = fromImage && fromImage !== image ? ` (image ${fromImage} → ${image})` : ""; + log( + `→ updating ${target} (${fromLabel} → ${toLabel}, scope: ${scope}, image: ${image}${imageNote ? "" : ""})${imageNote}`, + ); + // 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); @@ -173,8 +207,7 @@ export default defineCommand({ } // 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. + // the two canonical scope paths before destructive ops. const expected = resolve(scopePath(scope, cwd)); if (resolve(target) !== expected) { fail( @@ -197,13 +230,13 @@ export default defineCommand({ createdAt: existing?.createdAt ?? now, version: toVersion, updatedAt: now, - experimental: useExperimental, + image, scope, }; writeFileSync(join(target, CFG_FILE), JSON.stringify(cfg, null, 2) + "\n"); log(""); - log(`✓ updated to ${toLabel} (scope: ${scope})`); + log(`✓ updated to ${toLabel} (scope: ${scope}, image: ${image})`); log(" npx @forgeplan/web start"); }, }); diff --git a/bin/lib/images.mjs b/bin/lib/images.mjs new file mode 100644 index 0000000..4ccbd8b --- /dev/null +++ b/bin/lib/images.mjs @@ -0,0 +1,54 @@ +import { existsSync, readdirSync } from "node:fs"; +import { join } from "node:path"; + +export const STABLE_IMAGE = "stable"; +export const NIGHTLY_IMAGE = "nightly"; + +const IMAGE_NAME_RE = /^[a-z][a-z0-9-]{0,31}$/; + +export function isValidImageName(name) { + return typeof name === "string" && IMAGE_NAME_RE.test(name); +} + +export function imageDirName(imageName) { + if (!isValidImageName(imageName)) { + throw new Error(`invalid image name "${imageName}"`); + } + return imageName === STABLE_IMAGE ? "dist" : `dist-${imageName}`; +} + +export function imagePath(pkgRoot, imageName) { + return join(pkgRoot, imageDirName(imageName)); +} + +export function listAvailableImages(pkgRoot) { + let entries; + try { + entries = readdirSync(pkgRoot, { withFileTypes: true }); + } catch { + return []; + } + const seen = new Set(); + for (const entry of entries) { + if (!entry.isDirectory()) continue; + if (entry.name === "dist") { + seen.add(STABLE_IMAGE); + } else if (entry.name.startsWith("dist-")) { + const candidate = entry.name.slice("dist-".length); + if (isValidImageName(candidate)) seen.add(candidate); + } + } + const ordered = []; + if (seen.has(STABLE_IMAGE)) { + ordered.push(STABLE_IMAGE); + seen.delete(STABLE_IMAGE); + } + for (const name of [...seen].sort()) ordered.push(name); + return ordered; +} + +export function resolveImageDir(pkgRoot, imageName) { + const dir = imagePath(pkgRoot, imageName); + if (!existsSync(dir)) return null; + return dir; +} diff --git a/config/IMAGES.md b/config/IMAGES.md new file mode 100644 index 0000000..ff8278e --- /dev/null +++ b/config/IMAGES.md @@ -0,0 +1,94 @@ +# Images & feature flags — maintainer guide + +This directory is the source of truth for the multi-image build pipeline +introduced by PRD-030 / RFC-026 / ADR-005. The build script +(`scripts/build.mjs`) reads these files; the bin script reads the +materialised `forgeplan-web-build.json` inside each emitted `dist*/` +directory. + +## Files + +| File | Role | +|---|---| +| `images.json` | Image registry. Maps image name → `{ description, features: [] }`. Each `name` in `images.json#images` becomes one emitted directory: `stable` → `dist/`, every other → `dist-/`. | +| `features.json` | Feature-flag registry. Each entry: `{ id, description, addedIn, expiresIn, owner, rollout }`. The build pipeline cross-references this with `images.json`. | + +There is intentionally **no schema file** committed yet — the validator +in `scripts/build.mjs` is the runtime contract; if a schema is later +generated, it should be a sibling next to these JSON files. + +## Adding a new image + +1. Add an entry to `config/images.json#images.`. Pick a kebab-case + name (validated by `bin/lib/images.mjs#isValidImageName`). +2. Add the directory to `package.json#files`: + ```json + "files": ["bin", "dist", "dist-nightly", "dist-", "README.md", ...] + ``` +3. Run `npm run build` — the validator asserts every `dist*/` it emits is + listed in `package.json#files`. Build fails fast if you forgot. +4. Update README.md / README.ru.md to mention the new image (the user- + facing flag is `--image `). + +## Adding a new feature flag + +1. Add an entry to `config/features.json#features`: + ```json + { + "id": "kebab-case-id", + "description": "One sentence.", + "addedIn": "0.2.0", + "expiresIn": "0.4.0", + "owner": "", + "rollout": "alpha" + } + ``` +2. Add the flag's `id` to the `features` arrays of every image that + should ship it (typically `nightly` first, then `stable` after + graduation). +3. The flag itself must be implemented in `template/` and gated by + reading `forgeplan-web-build.json#features` at runtime. The build + pipeline does not enforce this — it only manages metadata. + +## Lifecycle policy + +A flag's `expiresIn` MUST be at most three minor versions past +`addedIn`. The validator in `scripts/build.mjs` enforces: + +- `addedIn` is a valid semver and `expiresIn > addedIn`. +- `expiresIn ≤ addedIn + 3 minor` (major bumps reset the clock). +- `package.json#version < expiresIn` (strict). When `>=`, the build + fails until the flag is either removed or graduated. + +"Graduating" a flag means: pick one of two paths. + +1. **Promote** — if the flag is now part of the default behaviour: + remove it from `features.json`, remove all gating in `template/`, + delete the flag id from every image's `features` array. The + behaviour is now unconditional. +2. **Drop** — if the flag did not pan out: remove it from + `features.json`, remove all gating in `template/`, delete the flag + id from every image's `features` array. The behaviour is gone. + +A flag MUST NOT be silently extended past `expiresIn`. Bumping +`expiresIn` is allowed only with an updating Forgeplan artifact (PRD or +RFC) explaining why graduation is being delayed. + +## Image rollout taxonomy + +| `rollout` | Eligible images | Meaning | +|---|---|---| +| `alpha` | `nightly` only | Active development; behaviour can change between releases. | +| `beta` | `nightly` only | Stable interface; hardening period. | +| `stable` | `stable` and `nightly` | Generally available. Once a flag reaches `stable`, it should graduate within one more minor version. | + +The validator currently does not enforce the `rollout → eligible image` +mapping (it would be over-prescriptive in v1). When in doubt, follow +the table. + +## Why a registry, not a series of booleans + +PRD-030 §"Differentiators" and ADR-005 cover this in depth. Short +version: a registry keeps the lifecycle data in one place, makes +"what's in nightly?" a question with a one-file answer, and lets the +build pipeline mechanically enforce graduation. diff --git a/config/features.json b/config/features.json new file mode 100644 index 0000000..770ae39 --- /dev/null +++ b/config/features.json @@ -0,0 +1,5 @@ +{ + "$schema": "./features.schema.json", + "version": 1, + "features": [] +} diff --git a/config/images.json b/config/images.json new file mode 100644 index 0000000..c142e21 --- /dev/null +++ b/config/images.json @@ -0,0 +1,14 @@ +{ + "$schema": "./images.schema.json", + "version": 1, + "images": { + "stable": { + "description": "Stable production image. Default for `init` and `update`. Ships only flags whose rollout: stable.", + "features": [] + }, + "nightly": { + "description": "Pre-release image. Same artifact shape as stable; ships flags rolled out as alpha/beta in addition to stable.", + "features": [] + } + } +} diff --git a/package.json b/package.json index 3fd10e9..bc860f9 100644 --- a/package.json +++ b/package.json @@ -9,7 +9,7 @@ "files": [ "bin", "dist", - "dist-experimental", + "dist-nightly", "README.md", "README.ru.md", "CHANGELOG.md", diff --git a/scripts/build.mjs b/scripts/build.mjs index 99a9ad1..ab0b759 100644 --- a/scripts/build.mjs +++ b/scripts/build.mjs @@ -17,22 +17,40 @@ const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, ".."); const TEMPLATE = join(ROOT, "template"); const TEMPLATE_BUILD = join(TEMPLATE, "build"); -const DIST = join(ROOT, "dist"); -const DIST_EXPERIMENTAL = join(ROOT, "dist-experimental"); -// PRD-014 / RFC-013: cap for the experimental bundled dist. If esbuild -// starts pulling more (svelte upgrade, accidental client-side imports), -// fail loudly instead of silently bloating the tarball. -const DIST_EXPERIMENTAL_MAX_BYTES = 3 * 1024 * 1024; +const CONFIG_DIR = join(ROOT, "config"); +const IMAGES_FILE = join(CONFIG_DIR, "images.json"); +const FEATURES_FILE = join(CONFIG_DIR, "features.json"); +const PKG_FILE = join(ROOT, "package.json"); + +// PRD-030 / RFC-026 / ADR-005: every emitted image directory is bound by the +// same size cap. The bundle alone is ~600K-1M; keeping headroom for client/ +// + future small additions, while alarming on accidental bloat. +const IMAGE_DIST_MAX_BYTES = 3 * 1024 * 1024; + +// Lifecycle policy (PRD-030 NFR-005, RFC-026 Phase 1): a flag's expiresIn +// must not be more than this many minor versions past addedIn (within the +// same major). Major bumps reset the clock. +const FLAG_MAX_MINOR_LIFETIME = 3; const args = new Set(process.argv.slice(2)); const CLEAN_ONLY = args.has("--clean"); const SKIP_TEMPLATE_INSTALL = args.has("--skip-template-install"); -const SKIP_EXPERIMENTAL = args.has("--skip-experimental"); +const ONLY_IMAGE = (() => { + for (const a of process.argv.slice(2)) { + if (a.startsWith("--only=")) return a.slice("--only=".length); + } + return null; +})(); function log(line) { process.stdout.write(`[build] ${line}\n`); } +function failBuild(line, code = 1) { + process.stderr.write(`[build] FAIL: ${line}\n`); + process.exit(code); +} + function run(cmd, argv, cwd) { log(`$ ${cmd} ${argv.join(" ")} (cwd=${cwd.replace(ROOT, ".")})`); // Windows: `npm` resolves to `npm.cmd` (batch script). Node's spawnSync @@ -45,25 +63,191 @@ function run(cmd, argv, cwd) { shell: process.platform === "win32", }); if (r.status !== 0) { - process.stderr.write( - `[build] FAIL: ${cmd} ${argv.join(" ")} → exit ${r.status}\n`, + failBuild(`${cmd} ${argv.join(" ")} → exit ${r.status}`, r.status ?? 1); + } +} + +// ---- semver --------------------------------------------------------------- + +function parseSemver(v) { + if (typeof v !== "string") return null; + const m = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(v); + if (!m) return null; + return { + major: Number(m[1]), + minor: Number(m[2]), + patch: Number(m[3]), + raw: v, + }; +} + +function semverGTE(a, b) { + if (a.major !== b.major) return a.major > b.major; + if (a.minor !== b.minor) return a.minor > b.minor; + return a.patch >= b.patch; +} + +// ---- config + lifecycle validator ---------------------------------------- + +function readJsonFile(path) { + return JSON.parse(readFileSync(path, "utf8")); +} + +function readPkg() { + return readJsonFile(PKG_FILE); +} + +function readImages() { + return readJsonFile(IMAGES_FILE); +} + +function readFeatures() { + return readJsonFile(FEATURES_FILE); +} + +function validateConfig({ images, features, currentVersion }) { + const errors = []; + const featureById = new Map(); + + const featureList = features.features ?? []; + if (!Array.isArray(featureList)) { + errors.push( + `config/features.json: \`features\` must be an array, got ${typeof featureList}`, + ); + return errors; + } + + for (const feat of featureList) { + if (!feat || typeof feat !== "object") { + errors.push("config/features.json: feature entry must be an object"); + continue; + } + if (typeof feat.id !== "string" || feat.id.length === 0) { + errors.push("config/features.json: feature `id` must be a non-empty string"); + continue; + } + if (featureById.has(feat.id)) { + errors.push(`config/features.json: duplicate feature id "${feat.id}"`); + continue; + } + featureById.set(feat.id, feat); + + const added = parseSemver(feat.addedIn); + const expires = parseSemver(feat.expiresIn); + if (!added) { + errors.push( + `config/features.json: feature "${feat.id}" has invalid addedIn "${feat.addedIn}"`, + ); + continue; + } + if (!expires) { + errors.push( + `config/features.json: feature "${feat.id}" has invalid expiresIn "${feat.expiresIn}"`, + ); + continue; + } + if (!semverGTE(expires, added) || (expires.raw === added.raw)) { + errors.push( + `config/features.json: feature "${feat.id}" has expiresIn (${expires.raw}) <= addedIn (${added.raw})`, + ); + } + if ( + added.major === expires.major && + expires.minor - added.minor > FLAG_MAX_MINOR_LIFETIME + ) { + errors.push( + `config/features.json: feature "${feat.id}" lifetime ${expires.raw}-${added.raw} exceeds ${FLAG_MAX_MINOR_LIFETIME} minor versions; graduate or drop it (rule: PRD-030 NFR-005)`, + ); + } + if (currentVersion && semverGTE(currentVersion, expires)) { + errors.push( + `config/features.json: feature "${feat.id}" expired (expiresIn=${expires.raw}, currentVersion=${currentVersion.raw}); remove from features.json + every image's features array`, + ); + } + } + + if ( + !images || + typeof images !== "object" || + !images.images || + typeof images.images !== "object" + ) { + errors.push("config/images.json: missing or malformed `images` object"); + return errors; + } + + const imageNameRe = /^[a-z][a-z0-9-]{0,31}$/; + for (const [name, image] of Object.entries(images.images)) { + if (!imageNameRe.test(name)) { + errors.push(`config/images.json: invalid image name "${name}"`); + } + if (!image || typeof image !== "object") { + errors.push(`config/images.json: image "${name}" must be an object`); + continue; + } + if (!Array.isArray(image.features)) { + errors.push( + `config/images.json: image "${name}".features must be an array`, + ); + continue; + } + for (const flagId of image.features) { + if (!featureById.has(flagId)) { + errors.push( + `config/images.json: image "${name}" references unknown flag "${flagId}" (declare it in config/features.json first)`, + ); + } + } + } + + if (!images.images.stable) { + errors.push( + 'config/images.json: image "stable" must always be defined (PRD-030 FR-007)', + ); + } + + return errors; +} + +function ensurePackageFilesCoverage({ pkg, imageNames }) { + const filesArr = pkg.files ?? []; + const needed = imageNames.map((n) => (n === "stable" ? "dist" : `dist-${n}`)); + const missing = needed.filter((dir) => !filesArr.includes(dir)); + if (missing.length > 0) { + failBuild( + `package.json#files is missing image directories: ${missing.join(", ")}.\n` + + ` Add them to "files" in package.json so the npm tarball ships them.`, ); - process.exit(r.status ?? 1); } } +// ---- common build helpers (shared by all images) ------------------------- + function clean() { for (const p of [ - DIST, - DIST_EXPERIMENTAL, - TEMPLATE_BUILD, + join(TEMPLATE_BUILD), join(TEMPLATE, ".svelte-kit"), + join(ROOT, "dist"), ]) { if (existsSync(p)) { log(`rm -rf ${p.replace(ROOT, ".")}`); rmSync(p, { recursive: true, force: true }); } } + // Sweep dist-/ siblings too — we recreate them on every build. + for (const entry of readdirSync(ROOT, { withFileTypes: true })) { + if ( + entry.isDirectory() && + entry.name.startsWith("dist-") && + // Don't touch unrelated dirs that happen to share the prefix; only + // delete `dist-/` shapes (lowercase, kebab-case). + /^dist-[a-z][a-z0-9-]*$/.test(entry.name) + ) { + const p = join(ROOT, entry.name); + log(`rm -rf ${p.replace(ROOT, ".")}`); + rmSync(p, { recursive: true, force: true }); + } + } } function installTemplateDeps() { @@ -77,88 +261,12 @@ function installTemplateDeps() { function buildSvelteKit() { run("npm", ["run", "build"], TEMPLATE); if (!existsSync(join(TEMPLATE_BUILD, "index.js"))) { - process.stderr.write( - "[build] FAIL: template/build/index.js missing — adapter-node did not produce a server entry\n", + failBuild( + "template/build/index.js missing — adapter-node did not produce a server entry", ); - process.exit(1); } } -function emitDistPackageJson() { - const tplPkg = JSON.parse( - readFileSync(join(TEMPLATE, "package.json"), "utf8"), - ); - const distPkg = { - name: "forgeplan-web-runtime", - version: tplPkg.version ?? "0.0.0", - private: true, - type: "module", - engines: tplPkg.engines, - dependencies: tplPkg.dependencies ?? {}, - scripts: { - start: "node index.js", - }, - }; - writeFileSync( - join(TEMPLATE_BUILD, "package.json"), - JSON.stringify(distPkg, null, 2) + "\n", - ); - log( - `emitted template/build/package.json (${Object.keys(distPkg.dependencies).length} runtime deps)`, - ); -} - -function installRuntimeDeps() { - // FR-005 / CWE-1357: --ignore-scripts blocks transitive postinstall hooks - // from baking attacker-controlled code into published dist/node_modules/. - run( - "npm", - [ - "install", - "--omit=dev", - "--omit=peer", - "--no-fund", - "--no-audit", - "--ignore-scripts", - ], - TEMPLATE_BUILD, - ); -} - -function stripSourceMaps(root) { - let removed = 0; - let strippedRefs = 0; - const SOURCEMAP_RE = /\n?\/\/# sourceMappingURL=.*$/m; - - const walk = (dir) => { - for (const name of readdirSync(dir)) { - const p = join(dir, name); - const st = statSync(p); - if (st.isDirectory()) { - walk(p); - } else if (name.endsWith(".map")) { - rmSync(p, { force: true }); - removed += 1; - } else if ( - name.endsWith(".js") || - name.endsWith(".mjs") || - name.endsWith(".cjs") - ) { - const src = readFileSync(p, "utf8"); - if (SOURCEMAP_RE.test(src)) { - writeFileSync(p, src.replace(SOURCEMAP_RE, "")); - strippedRefs += 1; - } - } - } - }; - - walk(root); - log( - `stripped sourcemaps: removed ${removed} .map file(s), cleared ${strippedRefs} sourceMappingURL ref(s)`, - ); -} - function patchHostDefault(root) { // adapter-node bakes `env('HOST', '0.0.0.0')` into index.js. The bin wrapper // sets HOST=127.0.0.1, but `node .forgeplan-web/index.js` (documented in @@ -167,9 +275,8 @@ function patchHostDefault(root) { const indexPath = join(root, "index.js"); if (!existsSync(indexPath)) return; const src = readFileSync(indexPath, "utf8"); - // The unminified form is `env('HOST', '0.0.0.0')`. Issue #117 enabled - // esbuild `minify: true` for dist-experimental/, which renames `env` to a - // short identifier (e.g. `Ue`). Capture whatever identifier the minifier + // The unminified form is `env('HOST', '0.0.0.0')`. esbuild minify renames + // `env` to a short identifier (e.g. `Ue`); capture whatever the minifier // chose and reuse it in the replacement so both shapes work. const PATTERN = /([A-Za-z_$][A-Za-z0-9_$]*)\(\s*['"]HOST['"]\s*,\s*['"]0\.0\.0\.0['"]\s*\)/; @@ -189,61 +296,6 @@ function patchHostDefault(root) { ); } -function pruneSymlinks(root) { - const dotBin = join(root, "node_modules", ".bin"); - if (existsSync(dotBin)) { - rmSync(dotBin, { recursive: true, force: true }); - log( - `removed ${dotBin.replace(ROOT, ".")} (CLI symlinks unused at runtime, often absolute → unportable)`, - ); - } - - const stray = []; - const walk = (dir) => { - for (const name of readdirSync(dir, { withFileTypes: true })) { - const p = join(dir, name.name); - if (name.isSymbolicLink()) { - stray.push(p); - rmSync(p, { force: true }); - } else if (name.isDirectory()) { - walk(p); - } - } - }; - walk(root); - if (stray.length > 0) { - log( - `removed ${stray.length} stray symlink(s): ${stray - .slice(0, 3) - .map((p) => p.replace(ROOT, ".")) - .join(", ")}${stray.length > 3 ? ", …" : ""}`, - ); - } -} - -function copyToDist() { - if (existsSync(DIST)) { - rmSync(DIST, { recursive: true, force: true }); - } - mkdirSync(DIST, { recursive: true }); - cpSync(TEMPLATE_BUILD, DIST, { recursive: true, dereference: false }); - - stripSourceMaps(DIST); - pruneSymlinks(DIST); - patchHostDefault(DIST); - - const manifest = { - name: "@forgeplan/web", - builtAt: new Date().toISOString(), - entry: "index.js", - }; - writeFileSync( - join(DIST, "forgeplan-web-build.json"), - JSON.stringify(manifest, null, 2) + "\n", - ); - log(`dist/ ready at ${DIST.replace(ROOT, ".")}`); -} - function dirSizeBytes(dir) { let total = 0; const walk = (d) => { @@ -257,37 +309,34 @@ function dirSizeBytes(dir) { return total; } -// TODO(rfc-013-graduation): once the bundled dist graduates from --experimental, -// rename this to bundleDist(), make it the only artifact emitter, drop -// emitDistPackageJson()/installRuntimeDeps()/copyToDist() from the legacy -// pipeline, and rename DIST_EXPERIMENTAL → DIST. -async function bundleExperimentalDist() { - // PRD-014 / RFC-013: produce a self-contained ESM bundle that replaces - // the legacy `dist/node_modules/` (≈12M). The legacy `dist/` is left - // untouched; this is gated behind `init --experimental` until validated. +// ---- bundle + per-image emission ----------------------------------------- + +// Build one bundle per build run. The bundle bytes are identical across every +// image that shares the same flag set; today every image ships an empty flag +// set, so we bundle exactly once and copy. Once a flag actually affects the +// bundle bytes, this function will need to grow a per-image rebuild path. +async function bundleBaseDist(baseDir) { const { build } = await import("esbuild"); - const tplPkg = JSON.parse( - readFileSync(join(TEMPLATE, "package.json"), "utf8"), - ); + const tplPkg = readJsonFile(join(TEMPLATE, "package.json")); - if (existsSync(DIST_EXPERIMENTAL)) { - rmSync(DIST_EXPERIMENTAL, { recursive: true, force: true }); + if (existsSync(baseDir)) { + rmSync(baseDir, { recursive: true, force: true }); } - mkdirSync(DIST_EXPERIMENTAL, { recursive: true }); + mkdirSync(baseDir, { recursive: true }); // Copy the parts esbuild can't (won't) inline: // - client/ static assets are served by sirv at runtime; - // - env.js is loaded via SvelteKit's dynamic `$env/dynamic/*` import - // (string-literal `import()` that esbuild conservatively keeps external). - cpSync(join(DIST, "client"), join(DIST_EXPERIMENTAL, "client"), { + // - env.js is loaded via SvelteKit's `$env/dynamic/*` import (string-literal + // `import()` that esbuild conservatively keeps external). + cpSync(join(TEMPLATE_BUILD, "client"), join(baseDir, "client"), { recursive: true, dereference: false, }); - cpSync(join(DIST, "env.js"), join(DIST_EXPERIMENTAL, "env.js")); + cpSync(join(TEMPLATE_BUILD, "env.js"), join(baseDir, "env.js")); const result = await build({ entryPoints: [join(TEMPLATE_BUILD, "index.js")], - outfile: join(DIST_EXPERIMENTAL, "index.js"), + outfile: join(baseDir, "index.js"), bundle: true, platform: "node", format: "esm", @@ -301,36 +350,24 @@ async function bundleExperimentalDist() { logLevel: "warning", legalComments: "none", treeShaking: true, - // Issue #117: post-minify the bundle. The unminified ESM bundle is ~1.4M; - // minifying drops it to ~500–700K and shaves the published tarball - // (refs PRD-014 SC-1: dist/ ≤ 3M cap; this brings dist-experimental/ - // closer to that target with headroom for future deps). - // `keepNames: true` preserves function/class .name so any runtime - // diagnostics that rely on `Error.stack` / `Function.name` still resolve - // (sirv, polka, kit error formatters). minify: true, keepNames: true, metafile: false, }); if (result.errors && result.errors.length > 0) { - process.stderr.write( - `[build] FAIL: esbuild reported ${result.errors.length} error(s)\n`, - ); - process.exit(1); + failBuild(`esbuild reported ${result.errors.length} error(s)`); } if (result.warnings && result.warnings.length > 0) { - // Warnings are usually about CJS/ESM interop — flag them but don't fail. - // FIXME(rfc-013): tighten to fail-on-warning once we know the baseline is clean across upgrades. log( - `bundleExperimentalDist: esbuild emitted ${result.warnings.length} warning(s) (non-fatal)`, + `bundleBaseDist: esbuild emitted ${result.warnings.length} warning(s) (non-fatal)`, ); } - patchHostDefault(DIST_EXPERIMENTAL); + patchHostDefault(baseDir); - const distExpPkg = { - name: "forgeplan-web-runtime-experimental", + const distPkg = { + name: "forgeplan-web-runtime", version: tplPkg.version ?? "0.0.0", private: true, type: "module", @@ -338,61 +375,121 @@ async function bundleExperimentalDist() { scripts: { start: "node index.js" }, }; writeFileSync( - join(DIST_EXPERIMENTAL, "package.json"), - JSON.stringify(distExpPkg, null, 2) + "\n", + join(baseDir, "package.json"), + JSON.stringify(distPkg, null, 2) + "\n", ); + // Shape assertions — the bundle must NEVER contain node_modules/ or + // server/ chunks. Both indicate a regression in `packages: "bundle"`. + if (existsSync(join(baseDir, "node_modules"))) { + failBuild( + `${baseDir.replace(ROOT, ".")}/node_modules/ exists (should be inlined into index.js)`, + ); + } + if (existsSync(join(baseDir, "server"))) { + failBuild( + `${baseDir.replace(ROOT, ".")}/server/ exists (chunks were not inlined; check for new dynamic imports in adapter-node output)`, + ); + } +} + +function emitImageDist({ imageName, features, baseDir, pkgVersion }) { + const targetName = imageName === "stable" ? "dist" : `dist-${imageName}`; + const target = join(ROOT, targetName); + + if (existsSync(target)) { + rmSync(target, { recursive: true, force: true }); + } + mkdirSync(target, { recursive: true }); + cpSync(baseDir, target, { + recursive: true, + dereference: false, + force: true, + }); + const manifest = { name: "@forgeplan/web", + version: pkgVersion ?? "0.0.0", builtAt: new Date().toISOString(), entry: "index.js", - experimental: true, + image: imageName, + features, }; writeFileSync( - join(DIST_EXPERIMENTAL, "forgeplan-web-build.json"), + join(target, "forgeplan-web-build.json"), JSON.stringify(manifest, null, 2) + "\n", ); - // Shape assertions — any of these failing means the bundle didn't capture - // everything it should have, OR the bundle started silently bloating. - if (existsSync(join(DIST_EXPERIMENTAL, "node_modules"))) { - process.stderr.write( - "[build] FAIL: dist-experimental/node_modules/ exists (should be inlined into index.js)\n", - ); - process.exit(1); - } - if (existsSync(join(DIST_EXPERIMENTAL, "server"))) { - process.stderr.write( - "[build] FAIL: dist-experimental/server/ exists (chunks were not inlined; check for new dynamic imports in adapter-node output)\n", + const totalBytes = dirSizeBytes(target); + if (totalBytes > IMAGE_DIST_MAX_BYTES) { + failBuild( + `${targetName}/ is ${(totalBytes / 1024 / 1024).toFixed(2)}M, cap is ${(IMAGE_DIST_MAX_BYTES / 1024 / 1024).toFixed(0)}M (raise IMAGE_DIST_MAX_BYTES if intentional)`, ); - process.exit(1); - } - const totalBytes = dirSizeBytes(DIST_EXPERIMENTAL); - if (totalBytes > DIST_EXPERIMENTAL_MAX_BYTES) { - process.stderr.write( - `[build] FAIL: dist-experimental/ is ${(totalBytes / 1024 / 1024).toFixed(2)}M, cap is ${(DIST_EXPERIMENTAL_MAX_BYTES / 1024 / 1024).toFixed(0)}M (raise DIST_EXPERIMENTAL_MAX_BYTES if intentional)\n`, - ); - process.exit(1); } log( - `dist-experimental/ ready at ${DIST_EXPERIMENTAL.replace(ROOT, ".")} (${(totalBytes / 1024 / 1024).toFixed(2)}M, single-file server bundle)`, + `${targetName}/ ready (${(totalBytes / 1024 / 1024).toFixed(2)}M, image=${imageName}, features=${features.length})`, ); } +// ---- top-level pipeline -------------------------------------------------- + if (CLEAN_ONLY) { clean(); process.exit(0); } -clean(); +const pkg = readPkg(); +const currentVersion = parseSemver(pkg.version); +if (!currentVersion) { + failBuild( + `package.json#version "${pkg.version}" is not a valid semver — feature lifecycle validator needs a parseable version`, + ); +} + +const images = readImages(); +const features = readFeatures(); + +const validationErrors = validateConfig({ + images, + features, + currentVersion, +}); +if (validationErrors.length > 0) { + for (const err of validationErrors) { + process.stderr.write(`[build] config error: ${err}\n`); + } + process.exit(1); +} + +const allImageNames = Object.keys(images.images); +const imagesToBuild = ONLY_IMAGE + ? allImageNames.filter((n) => n === ONLY_IMAGE) + : allImageNames; +if (ONLY_IMAGE && imagesToBuild.length === 0) { + failBuild( + `--only=${ONLY_IMAGE} did not match any image in config/images.json. Available: ${allImageNames.join(", ")}`, + ); +} + +ensurePackageFilesCoverage({ pkg, imageNames: allImageNames }); + +if (!ONLY_IMAGE) clean(); installTemplateDeps(); buildSvelteKit(); -emitDistPackageJson(); -installRuntimeDeps(); -copyToDist(); -if (!SKIP_EXPERIMENTAL) { - await bundleExperimentalDist(); -} else { - log("--skip-experimental: dist-experimental/ not produced"); + +const BASE_DIR = join(ROOT, ".dist-base"); +await bundleBaseDist(BASE_DIR); + +for (const imageName of imagesToBuild) { + emitImageDist({ + imageName, + features: images.images[imageName].features, + baseDir: BASE_DIR, + pkgVersion: pkg.version, + }); } -log("done."); + +// .dist-base/ is an internal staging dir — not shipped, not gitted. +rmSync(BASE_DIR, { recursive: true, force: true }); + +log(`done. images built: ${imagesToBuild.join(", ")}`); diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs index 2c8234a..6947cb3 100644 --- a/scripts/smoke.mjs +++ b/scripts/smoke.mjs @@ -17,6 +17,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url)); const ROOT = resolve(__dirname, ".."); const BIN = join(ROOT, "bin", "forgeplan-web.mjs"); const DIST = join(ROOT, "dist"); +const DIST_NIGHTLY = join(ROOT, "dist-nightly"); const SHIM = join(ROOT, "scripts", "test", "forgeplan-shim.mjs"); const IS_WIN = process.platform === "win32"; @@ -30,11 +31,11 @@ function fail(line, code = 1) { } function ensureBuild() { - if (existsSync(join(DIST, "index.js"))) { - log("dist/ already built — reusing"); + if (existsSync(join(DIST, "index.js")) && existsSync(join(DIST_NIGHTLY, "index.js"))) { + log("dist/ + dist-nightly/ already built — reusing"); return; } - log("dist/ missing — running `node scripts/build.mjs`"); + log("dist*/ missing — running `node scripts/build.mjs`"); const r = spawnSync(process.execPath, [join(ROOT, "scripts", "build.mjs")], { cwd: ROOT, stdio: "inherit", @@ -79,10 +80,15 @@ async function check(url, expectStatus = 200) { return r; } -async function main() { - ensureBuild(); +function readJson(p) { + return JSON.parse(readFileSync(p, "utf8")); +} - const scratch = mkdtempSync(join(tmpdir(), "fpw-smoke-")); +async function exerciseImage({ imageName, initArgs, expectImageInConfig }) { + log(""); + log(`==== image: ${imageName} ====`); + + const scratch = mkdtempSync(join(tmpdir(), `fpw-smoke-${imageName}-`)); const shimDir = join(scratch, "shim"); log(`scratch: ${scratch}`); @@ -99,8 +105,8 @@ async function main() { const userGitignoreLine = "# pre-existing user line\nnode_modules/\n"; writeFileSync(join(scratch, ".gitignore"), userGitignoreLine); - log("init -y (run 1)"); - const initR = spawnSync(process.execPath, [BIN, "init", "-y"], { + log(`init ${initArgs.join(" ")} (run 1)`); + const initR = spawnSync(process.execPath, [BIN, "init", ...initArgs], { cwd: scratch, env, stdio: "inherit", @@ -110,9 +116,35 @@ async function main() { if (!existsSync(join(scratch, ".forgeplan-web", "index.js"))) { fail("dist not copied to .forgeplan-web/index.js"); } - if (!existsSync(join(scratch, ".forgeplan-web", "node_modules"))) { - fail(".forgeplan-web/node_modules missing"); + // Bundle shape has no node_modules/ — assert the negative. + if (existsSync(join(scratch, ".forgeplan-web", "node_modules"))) { + fail( + ".forgeplan-web/node_modules exists — image is shipping legacy SvelteKit shape, not the bundle (PRD-030 SC-1 / AC-1 violation)", + ); + } + + // Verify forgeplan-web.json#image and forgeplan-web-build.json#image both + // record the requested image. + const cfg = readJson(join(scratch, ".forgeplan-web", "forgeplan-web.json")); + if (cfg.image !== expectImageInConfig) { + fail( + `forgeplan-web.json#image = "${cfg.image}", expected "${expectImageInConfig}"`, + ); + } + const buildManifest = readJson( + join(scratch, ".forgeplan-web", "forgeplan-web-build.json"), + ); + if (buildManifest.image !== imageName) { + fail( + `forgeplan-web-build.json#image = "${buildManifest.image}", expected "${imageName}"`, + ); } + if (!Array.isArray(buildManifest.features)) { + fail("forgeplan-web-build.json#features missing or not an array"); + } + log( + `forgeplan-web.json#image = ${cfg.image}; build manifest image=${buildManifest.image}, features=[${buildManifest.features.join(",")}]`, + ); const ENTRY_RE = /^[ \t]*\.forgeplan-web\/?[ \t]*$/gm; const gi1 = readFileSync(join(scratch, ".gitignore"), "utf8"); @@ -127,12 +159,16 @@ async function main() { } log(`gitignore: ${matches1.length} match (preserved user content)`); - log("init -y --force (run 2 — must be idempotent)"); - const initR2 = spawnSync(process.execPath, [BIN, "init", "-y", "--force"], { - cwd: scratch, - env, - stdio: "inherit", - }); + log(`init ${initArgs.join(" ")} --force (run 2 — must be idempotent)`); + const initR2 = spawnSync( + process.execPath, + [BIN, "init", ...initArgs, "--force"], + { + cwd: scratch, + env, + stdio: "inherit", + }, + ); if (initR2.status !== 0) fail(`init (run 2) exit ${initR2.status}`); const gi2 = readFileSync(join(scratch, ".gitignore"), "utf8"); @@ -161,10 +197,6 @@ async function main() { maxRetries: IS_WIN ? 20 : 0, retryDelay: 100, }; - // Async cleanup is the happy path: kill the server, wait for it to - // actually exit (so Windows releases the cwd handle on `scratch`), then - // rmSync. Without the await, Windows trips EBUSY on the scratch root - // because the child still owns it as cwd. const cleanup = async () => { if (cleanedUp) return; cleanedUp = true; @@ -174,26 +206,6 @@ async function main() { } rmSync(scratch, rmOpts); }; - // process 'exit' listener cannot be async — best-effort sync fallback - // for unexpected termination (Ctrl-C in CI, uncaught throw before main() - // reaches its own `await cleanup()`). - const cleanupSync = () => { - if (cleanedUp) return; - cleanedUp = true; - if (!server.killed) server.kill(IS_WIN ? "SIGKILL" : "SIGTERM"); - try { - rmSync(scratch, rmOpts); - } catch { - // FIXME(windows-cleanup): if the child is still holding cwd here, - // rmSync trips EBUSY. The async path above prevents this on the - // happy path; the OS / runner will reap the temp dir on exit. - } - }; - process.on("exit", cleanupSync); - process.on("SIGINT", () => { - cleanupSync(); - process.exit(130); - }); const ready = await waitForListen(port); if (!ready) { @@ -222,7 +234,26 @@ async function main() { log("GET /: ok (HTML returned)"); await cleanup(); - log("PASS"); + log(`PASS (image=${imageName})`); +} + +async function main() { + ensureBuild(); + + // PRD-030 / RFC-026 SC-6: smoke must pass against both stable and nightly. + await exerciseImage({ + imageName: "stable", + initArgs: ["-y"], + expectImageInConfig: "stable", + }); + await exerciseImage({ + imageName: "nightly", + initArgs: ["-y", "--image", "nightly"], + expectImageInConfig: "nightly", + }); + + log(""); + log("ALL IMAGES PASS"); } main().catch((e) => fail(`unhandled: ${e?.stack ?? e}`));