From abaedc6e535de3a49b8cea503c693f1aac57af42 Mon Sep 17 00:00:00 2001 From: Focus Date: Sat, 7 Nov 2026 20:08:27 +0800 Subject: [PATCH 1/8] =?UTF-8?q?=F0=9F=93=A6=20new=20(tools):=20gate=20temp?= =?UTF-8?q?late=20syncs=20behind=20bocode-upgrade=20verify?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tier L (always-L list: verification semantics + shared contract — the upgrade ownership table became a machine contract between template and adopters). The upgrade path was prose an agent could skim and overclaim (an adopter declared ADR-011 incorporated while its new reference file was missing); the playbook was deleted on install; agent-side skills never re-installed; the stamp was compared against nothing. bocode-upgrade --check/--apply/--verify now diffs .bocode-version mechanically (applied/stale/merged/new-file/delete dispositions, --keep for conscious divergence, report into the adopter's book/changelogs/), bocode:doctor reports staleness, one MANIFEST owns template-vs-project paths for both the sync and the release gate, UPGRADE.md ships with every install and refreshes itself, and skills re-install via --skills-dir joins the verify gate. Verified: no-network selftest green (32 assertions), book:index zero warnings, book:release-check clean, commit subject validated. --- ADOPT.md | 21 +- AGENTS.md | 2 +- CHANGELOG.md | 11 +- README.ja.md | 12 +- README.md | 12 +- README.zh-CN.md | 12 +- UPGRADE.md | 55 ++- book/README.md | 3 +- ...DR-012-upgrade-sync-becomes-a-tool-gate.md | 39 ++ code/package.json | 7 +- code/tools/bocode-doctor.mjs | 106 ++++ code/tools/bocode-upgrade.mjs | 454 ++++++++++++++++++ code/tools/bocode-upgrade.test.mjs | 237 +++++++++ scripts/check-release-changelog.mjs | 21 +- scripts/init-project.sh | 8 +- skills/README.md | 2 + skills/bocode/SKILL.md | 2 +- 17 files changed, 938 insertions(+), 66 deletions(-) create mode 100644 book/docs/decisions/ADR-012-upgrade-sync-becomes-a-tool-gate.md create mode 100644 code/tools/bocode-doctor.mjs create mode 100644 code/tools/bocode-upgrade.mjs create mode 100644 code/tools/bocode-upgrade.test.mjs diff --git a/ADOPT.md b/ADOPT.md index 2409447..c65698d 100644 --- a/ADOPT.md +++ b/ADOPT.md @@ -46,14 +46,15 @@ Every migrated file gets a frontmatter `description` — one plain-language line ## Step 4 — Install the tooling -1. Copy `code/tools/gen-book-index.mjs` and wire the script (see the `scripts` block in BoCode's `code/package.json`). If the project has no JavaScript tooling at all, a shell wrapper calling `node` is fine — the script is zero-dependency. -2. Optional, recommended: copy `scripts/check-commit-message.mjs` and `.githooks/`, then run `git config core.hooksPath .githooks`. -3. Optional: copy `.github/workflows/git-policy.yml`. **Check the branch names** — if the project's integration branch isn't `dev`, either ask the user to adopt the branch model or adapt the workflow's branch filters. Don't silently rewrite their branch model. Also **delete the "Check template cleanliness" step** — it enforces the BoCode template repository's own cleanliness rule (its ADR-004) and would fail on a real project's notes and changelogs. -4. Run the index generator: every book file must carry a `description` and every internal link must resolve; zero warnings is the only passing state. +1. Copy all of `code/tools/` (the index generator plus the `bocode-upgrade` / `bocode-doctor` sync gate and its selftest) and wire the `scripts` block from BoCode's `code/package.json` into the project's `code/package.json` (keep the project's `name`). If the project has no JavaScript tooling at all, a shell wrapper calling `node` is fine — the scripts are zero-dependency. +2. Copy `UPGRADE.md` to the project root — it is the upgrade playbook, template-owned, and refreshes itself on every future sync. +3. Optional, recommended: copy `scripts/check-commit-message.mjs` and `.githooks/`, then run `git config core.hooksPath .githooks`. +4. Optional: copy `.github/workflows/git-policy.yml`. **Check the branch names** — if the project's integration branch isn't `dev`, either ask the user to adopt the branch model or adapt the workflow's branch filters. Don't silently rewrite their branch model. Also **delete the "Check template cleanliness" step** — it enforces the BoCode template repository's own cleanliness rule (its ADR-004) and would fail on a real project's notes and changelogs. +5. Run the index generator: every book file must carry a `description` and every internal link must resolve; zero warnings is the only passing state. ## Step 5 — Install the skills -Copy `skills/bocode`, `skills/boscope`, `skills/book-writeback`, and `skills/bowrite` into the agent's skills directory (see BoCode's `skills/README.md` for per-tool locations). If the user's agent can't install skills, the workflow still works — the guidelines carry the same rules in prose. +Copy `skills/bocode`, `skills/boscope`, `skills/book-writeback`, and `skills/bowrite` into the agent's skills directory (see BoCode's `skills/README.md` for per-tool locations). If the user's agent can't install skills, the workflow still works — the guidelines carry the same rules in prose. Skills do not auto-update: every later BoCode sync must re-install them (`cd code && npm run bocode:upgrade -- --apply --skills-dir `), or the agent keeps running the old behavior. ## Step 6 — Write the project's `AGENTS.md` @@ -63,9 +64,11 @@ Adapt BoCode's `AGENTS.md`: fill the project overview (what it is, in two senten 1. Index generator: zero warnings, exit 0. 2. `git config core.hooksPath .githooks` (if adopted) and the hook fires on commit. -3. Write `.bocode-version` at the project root — one line with the BoCode repository's current HEAD SHA (`git -C rev-parse HEAD`). Future upgrades diff against it. -4. Commit the adoption. Follow the project's existing commit convention unless the user chooses to adopt Clean Commit — their call, not yours. -5. Don't rewrite git history. Adoption is ordinary commits on top of what exists. +3. `cd code && npm run bocode:selftest` — the sync gate proves itself on a fixture; green is the only passing state. +4. Write `.bocode-version` at the project root — one line with the BoCode repository's current HEAD SHA (`git -C rev-parse HEAD`). Future upgrades diff against it. +5. `npm run bocode:doctor` — clean, or knowingly green on the warnings. +6. Commit the adoption. Follow the project's existing commit convention unless the user chooses to adopt Clean Commit — their call, not yours. +7. Don't rewrite git history. Adoption is ordinary commits on top of what exists. ## Step 8 — First writeback @@ -75,7 +78,7 @@ Adapt BoCode's `AGENTS.md`: fill the project overview (what it is, in two senten ## Later upgrades -When the BoCode template evolves, hand `UPGRADE.md` from the BoCode repository to an agent — it diffs the project's `.bocode-version` stamp against template HEAD, refreshes template-owned files, and leaves the project's own records untouched. `CHANGELOG.md` lists every change since the stamp. +The sync tooling installed in Step 4 carries the project forward: `cd code && npm run bocode:doctor` reports staleness, `npm run bocode:upgrade -- --check` lists every template-owned delta, and `--apply` refreshes pristine files, merges script entries, re-installs the skills (with `--skills-dir`), verifies, and writes a report into the project's `book/changelogs/`. `UPGRADE.md` at the project root is the playbook — a sync is done when `--verify` exits 0. ## What not to do diff --git a/AGENTS.md b/AGENTS.md index 1c39e67..3d4271d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ Git commits and branching strictly follow `book/guidelines/git-workflow.md`: eve ## Staying current -This workflow's template evolves. To sync an installed project, an agent reads `UPGRADE.md` and `CHANGELOG.md` from the BoCode repository (https://github.com/Focus695/BoCode) — the project's `.bocode-version` stamp records what it last synced to. +This workflow's template evolves, and the sync tooling ships with the project (template-owned, refreshes itself on every sync): `cd code && npm run bocode:doctor` reports staleness against the BoCode repository (https://github.com/Focus695/BoCode), and `npm run bocode:upgrade -- --check` lists every template-owned delta since the `.bocode-version` stamp. `UPGRADE.md` at the root is the playbook. **A sync is done when `--verify` exits 0 — never when an agent says so** — and the agent-side skills must be re-installed with it (`--skills-dir`). ## Document routing diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d1211e..edf3fbd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,9 +1,18 @@ # Changelog -Releases of the BoCode template itself. Adopting projects upgrade by handing [UPGRADE.md](UPGRADE.md) to an agent; each entry lists what changed and what an adopting project must do. History before 2026-11-05 lives in git log and [book/docs/decisions/](book/docs/decisions/) (ADR-001..ADR-004). +Releases of the BoCode template itself. Adopting projects upgrade with the sync tooling that ships with them — `cd code && npm run bocode:upgrade` per [UPGRADE.md](UPGRADE.md); each entry lists what changed and what an adopting project must do. History before 2026-11-05 lives in git log and [book/docs/decisions/](book/docs/decisions/) (ADR-001..ADR-004). When adding an entry, also refresh the collapsed What's-new block near the top of the three READMEs (`README.md`, `README.zh-CN.md`, `README.ja.md`): newest title in the summary line, latest three titles as bullets. +## 2026-11-07 — upgrades become a tool-gated sync (ADR-012) + +The upgrade path was prose an agent could skim and overclaim (an adopter's agent declared ADR-011 "incorporated" while its new reference file was missing); the playbook was deleted on install; the agent-side skills never re-installed; the stamp was compared against nothing. Syncing is now tool-gated: `bocode-upgrade` diffs the stamp mechanically, `--verify` exits 0 only when every template-owned delta is applied, merged, or consciously kept, `bocode:doctor` reports staleness, and a single `MANIFEST` owns template-vs-project paths for both the sync and the release gate. + +- Added: `code/tools/bocode-upgrade.mjs` (check/apply/verify, the MANIFEST single source, `--skills-dir` skill re-install, sync report into the adopter's `book/changelogs/`), `code/tools/bocode-doctor.mjs` (staleness checkup), `code/tools/bocode-upgrade.test.mjs` (no-network selftest), `book/docs/decisions/ADR-012-upgrade-sync-becomes-a-tool-gate.md` +- Changed: `code/package.json` (`bocode:upgrade` / `bocode:doctor` / `bocode:selftest` scripts), `UPGRADE.md` (rewritten around the tool; now template-owned and self-refreshing), `ADOPT.md` (installs all of `code/tools/` + `UPGRADE.md`, skills re-install obligation, doctor + selftest in verification), `scripts/init-project.sh` (keeps `UPGRADE.md`; next-steps point at the local tooling), `scripts/check-release-changelog.mjs` (imports `MANIFEST.releaseSignal`; the signal now also covers the three READMEs), `AGENTS.md` (Staying current → local tooling, "done means `--verify` exits 0"), `skills/bocode/SKILL.md` (upgrade contract rewritten), `skills/README.md` (re-install on every upgrade), `README.md` / `README.zh-CN.md` / `README.ja.md` (FAQ, tour, What's-new) + +**Adopter action:** bootstrap once — copy `code/tools/bocode-upgrade.mjs`, `bocode-doctor.mjs`, and `bocode-upgrade.test.mjs` from the BoCode repository into your `code/tools/`, add the three `bocode:*` entries to your `code/package.json` scripts, copy `UPGRADE.md` to your root (it is template-owned from now on). Then run `npm run bocode:selftest` (green), `npm run bocode:upgrade -- --check`, `--apply` (pass `--skills-dir ` so the four skills re-install — stale installed skills are the top reason an upgraded repo still behaves old), and rerun until `--verify` is green. If you kept `scripts/check-release-changelog.mjs`, re-copy it too — it now imports the manifest. Do not skip the skills re-install; do not declare the sync done from the CHANGELOG reading alone — the verify exit code is the only proof. + ## 2026-11-07 — trilingual readmes aligned with the current gates The readme bodies predated two shipped changes: they said every feature runs the six gates (task tiers landed with ADR-008 — S runs a light channel), and they said Phase 2 waits for user approval (the stop rule has fired only on real gaps since the phase-2 alignment). The zh-CN and ja bodies also missed the what-you-gain sentence under the adoption line. diff --git a/README.ja.md b/README.ja.md index 4af5a67..09899e6 100644 --- a/README.ja.md +++ b/README.ja.md @@ -17,11 +17,11 @@ BoCode はリポジトリを二つに分けます——ソースを置く `code/` と、ドキュメントの流れとナレッジベースを置く `book/` です。両者は双方向に接続されます。今のソフトウェアが実際に書かれている方法、つまり人間と AI コーディングエージェントの共同開発を前提に設計されています。エージェントは速く、メモリもありますが、その記憶はエージェントだけのもの:人間には読めず、管理もできません。プロジェクトの知識がどこに置かれ、誰が読めるかが、速さが制御とともにあるか、制御のない速さになるかを決めます。
-最新情報 · 2026-11-07 — 三言語の README を現行ゲートに合わせて更新 +最新情報 · 2026-11-07 — アップグレードがツールゲート式同期に(ADR-012) +- **2026-11-07** — アップグレードがツールゲート式同期に(ADR-012) - **2026-11-07** — 三言語の README を現行ゲートに合わせて更新 - **2026-11-06** — ub-mode の精選プラクティスを追加(ADR-011) -- **2026-11-06** — フェーズ 2 停止ルールを統一、L の ADR トリガーを判定可能に 履歴全文と移行手順は [CHANGELOG.md](CHANGELOG.md) @@ -184,7 +184,7 @@ cp -r skills/bocode skills/boscope skills/book-writeback skills/bowrite -What's new · 2026-11-07 — trilingual readmes aligned with the current gates +What's new · 2026-11-07 — upgrades become a tool-gated sync (ADR-012) +- **2026-11-07** — upgrades become a tool-gated sync (ADR-012) - **2026-11-07** — trilingual readmes aligned with the current gates - **2026-11-06** — selected ub-mode practices (ADR-011) -- **2026-11-06** — phase-2 stop rule aligned, L-tier ADR trigger decidable Full history and adopter actions: [CHANGELOG.md](CHANGELOG.md) @@ -184,7 +184,7 @@ cp -r skills/bocode skills/boscope skills/book-writeback skills/bowrite -最近更新 · 2026-11-07 — 三语 README 与现行关卡对齐 +最近更新 · 2026-11-07 — 升级链路变成工具把关的同步(ADR-012) +- **2026-11-07** — 升级链路变成工具把关的同步(ADR-012) - **2026-11-07** — 三语 README 与现行关卡对齐 - **2026-11-06** — 精选 ub-mode 实践(ADR-011) -- **2026-11-06** — Phase-2 停止规则对齐,L 级 ADR 触发判据化 完整历史与采用方操作见 [CHANGELOG.md](CHANGELOG.md) @@ -184,7 +184,7 @@ cp -r skills/bocode skills/boscope skills/book-writeback skills/bowrite **This file is for AI agents.** A project adopted the BoCode workflow at some point in the past; the template has moved on. Your job: bring the installed copy up to date without touching the project's own content. Follow it top to bottom. +> +> **A sync is done when `--verify` exits 0 — never when you say it is.** -The BoCode repository: https://github.com/Focus695/BoCode — its `CHANGELOG.md` tells you what changed; this file tells you how to apply it. +The sync tooling ships with the project (template-owned, refreshes itself on every sync): + +```bash +cd code +npm run bocode:doctor # am I behind? is anything stale? +npm run bocode:upgrade -- --check # every template-owned delta + its disposition +npm run bocode:upgrade -- --apply # copy pristine/new files, then verify +npm run bocode:upgrade -- --verify # the gate — exit 0 or the sync is not done +``` + +All three take `--repo ` (a local BoCode clone instead of cloning GitHub), `--skills-dir ` (check or re-install the four skills), `--stamp ` (set the baseline by hand), and `--keep ` (declare a template path consciously kept local). ## What is template-owned vs project-owned -The one table that decides everything. Template-owned files get refreshed; project-owned files are never touched. +The contract is the `MANIFEST` constant in `code/tools/bocode-upgrade.mjs` — the single source of truth; the table below is its human-readable restatement. Template-owned paths get refreshed; project-owned paths are never touched. When adding template files, update the manifest (UPGRADE.md's table follows it). | Template-owned (refresh) | Project-owned (never touch) | |--------------------------|------------------------------| -| `book/guidelines/{README,workflow,task-tiers,writing-style,git-workflow,review-checklist}.md` | `AGENTS.md`, root `README.md` | +| `UPGRADE.md`; `book/guidelines/{README,workflow,task-tiers,writing-style,git-workflow,review-checklist}.md` | `AGENTS.md`, root `README.md` | | the `README.md` of every `book/` directory (`docs/`, `docs/decisions/`, `docs/architecture/`, `docs/api/`, `notes/`, `plans/`, `changelogs/`) | `book/guidelines/architecture.md` and `coding-style.md` (project drafts since adoption) | | `skills/` — all four skills plus `skills/README.md` | everything under `book/docs/decisions/`, `book/docs/architecture/`, `book/docs/api/` (the project's own records) | -| `code/tools/*.mjs`; the `scripts` block of `code/package.json` (keep the project's `name`) | everything under `book/notes/`, `book/plans/`, `book/changelogs/` | +| `code/tools/*.mjs`; the `scripts` block of `code/package.json` (the project's `name` and local-only entries stay) | everything under `book/notes/`, `book/plans/`, `book/changelogs/` | | `scripts/check-*.mjs` (if adopted), `.githooks/` (if adopted), `.github/workflows/git-policy.yml` (if adopted — keep the template-clean step deleted, per ADOPT.md) | `book/README.md` (generated — regenerate, don't copy), `.bocode-version` | ## The procedure -1. Read `.bocode-version` at the project root: it holds the BoCode commit the project last synced to. No stamp (adopted before 2026-11-05)? Use the fallback below. -2. Clone the BoCode repository in full — not `--depth 1`, the stamp's commit must be reachable: `git clone https://github.com/Focus695/BoCode /tmp/bocode`. -3. List what changed: `git -C /tmp/bocode diff --name-status ..HEAD`, keep the rows that match the template-owned column, and read the `CHANGELOG.md` entries after the stamp for the intent and each entry's **Adopter action**. -4. Apply, per file: - - project copy unmodified since adoption (matches the stamp's template version) → copy the new version over it - - project copy modified → merge by hand: take the template's changes, keep the project's edits, ask the user where they collide - - project-owned path → never touch -5. Sync translated variants of the skills (e.g. a localized boscope) with the same insertions, if the project keeps any. -6. Regenerate and verify: `cd code && npm run book:index` must end with zero warnings and all links resolving. -7. Update `.bocode-version` to the new HEAD SHA (`git -C /tmp/bocode rev-parse HEAD`). +1. Run `npm run bocode:doctor`. Behind upstream? Continue. Stamp missing? See the fallback below. +2. `npm run bocode:upgrade -- --check` — read the disposition of every template-owned delta: + - `stale` / `new-file` / `stale-delete` / `pkg-stale` — safe, `--apply` handles them mechanically + - `merged` — the project's copy and the template both changed; nothing to do (a conscious merge already happened or the file carries local edits the sync must keep) + - `diverged-delete` / `missing` — a human decision: delete or restore the file, or record the deviation with `--keep ` +3. `npm run bocode:upgrade -- --apply`. It copies, deletes, and merges script entries, re-installs the skills when `--skills-dir` is given, re-verifies from disk, advances `.bocode-version` to the upstream HEAD, writes a report into `book/changelogs/YYYY-MM/`, and regenerates the index. If verify is not green it says exactly what is outstanding and leaves the stamp unchanged. +4. Merge the flagged files by hand: take the template's changes, keep the project's edits, ask the user where they collide. Resolve `diverged-delete` / `missing` (delete, restore, or `--keep`). +5. Re-run `--apply` (idempotent) until it prints verify green. +6. Re-install the skills if you did not pass `--skills-dir`: stale skills in the agent's directory are the number-one reason an upgraded repo still behaves old. `--skills-dir` given, `--verify` fails while any installed skill lags its `skills/` source. +7. Commit the sync in the project's own convention. The report under `book/changelogs/` is the review artifact — the user reads a generated list, not a promise. ADR numbers referenced in the guidelines (e.g. "ADR-006") are the template's own records — read them in the BoCode repository's `book/docs/decisions/`. +## Bootstrap: the project predates the tool + +Adopted before the tool existed? `bocode:doctor` will say the tool is missing. Fetch it from the BoCode repository first — copy `code/tools/bocode-upgrade.mjs`, `code/tools/bocode-doctor.mjs`, and `code/tools/bocode-upgrade.test.mjs` into the project's `code/tools/`, add the three `bocode:*` entries to the `scripts` block of `code/package.json`, then run the normal procedure. From then on the tool upgrades itself. + ## Fallback: no stamp -Projects adopted before the stamp existed have no baseline. Walk `CHANGELOG.md` top to bottom instead: every entry's **Adopter action** names the files it touched — compare each against the project's copy; identical or trivially old → apply per the rules above; project-modified → merge; conflicts → ask the user. Then stamp the current HEAD SHA and continue on the normal procedure. +Projects adopted before 2026-11-05 have no `.bocode-version`. Walk `CHANGELOG.md` (in the BoCode repository) top to bottom: every entry's **Adopter action** names the files it touched — compare each against the project's copy; identical or trivially old → apply; project-modified → merge; conflicts → ask the user. Then stamp the baseline for future runs: + +```bash +npm run bocode:upgrade -- --check --stamp +``` + +and continue on the normal procedure. ## What not to do +- Never claim a completed sync without a green `--verify` — the tool names what is outstanding; read it - Never overwrite a project-owned file — records, drafts, and ADRs belong to the project - Never re-add the "Check template cleanliness" step to a copied `git-policy.yml` (that gate is the template repo's own, per ADOPT.md) +- Never let the agent-side skills lag the repo's `skills/` — re-install them on every sync - Don't invent version numbers: the stamp is a commit SHA, and that is the whole versioning story (ADR-007) +- When adding template files, add them to `MANIFEST` in `code/tools/bocode-upgrade.mjs` — a file missing from the manifest is silently skipped by every future upgrade diff --git a/book/README.md b/book/README.md index e7182d2..c6478e1 100644 --- a/book/README.md +++ b/book/README.md @@ -60,6 +60,7 @@ description: Master index of the book — the map of every document. Regenerate - [ADR-009-bowrite-voice-on-every-write.md](docs/decisions/ADR-009-bowrite-voice-on-every-write.md) — bowrite's voice rules now run on every write, not just from-scratch drafts; conditions and exceptions join the fidelity contract's never-move list; the writeback path names bowrite explicitly - [ADR-010-archive-by-status-flip-not-by-moving-files.md](docs/decisions/ADR-010-archive-by-status-flip-not-by-moving-files.md) — task and issue entries archive by flipping a frontmatter status and regenerating the index — files never move, the index regroups with open entries first - [ADR-011-distill-selected-ub-mode-practices.md](docs/decisions/ADR-011-distill-selected-ub-mode-practices.md) — Selected ub-mode practices supplement project rules for modeling, calculations, testing, defects, terminology, and optional automation +- [ADR-012-upgrade-sync-becomes-a-tool-gate.md](docs/decisions/ADR-012-upgrade-sync-becomes-a-tool-gate.md) — The upgrade path ships as tooling — bocode-upgrade check/apply/verify diffs the stamp mechanically, a single manifest owns template-vs-project paths, doctor reports staleness, and UPGRADE.md self-refreshes; prose-only guidance is rejected - [README.md](docs/decisions/README.md) — How to write an ADR here — sections, naming, numbering, and when a decision needs a record ### guidelines/ @@ -81,4 +82,4 @@ description: Master index of the book — the map of every document. Regenerate - [README.md](plans/README.md) — Plans directory usage — implementation plans land here after Phase 2 approval, with naming and the plan template - + diff --git a/book/docs/decisions/ADR-012-upgrade-sync-becomes-a-tool-gate.md b/book/docs/decisions/ADR-012-upgrade-sync-becomes-a-tool-gate.md new file mode 100644 index 0000000..073d25f --- /dev/null +++ b/book/docs/decisions/ADR-012-upgrade-sync-becomes-a-tool-gate.md @@ -0,0 +1,39 @@ +--- +description: The upgrade path ships as tooling — bocode-upgrade check/apply/verify diffs the stamp mechanically, a single manifest owns template-vs-project paths, doctor reports staleness, and UPGRADE.md self-refreshes; prose-only guidance is rejected +--- + +# ADR-012: Upgrade sync becomes a tool gate + +## Status + +Accepted — 2026-11-07. Self-tested by `code/tools/bocode-upgrade.test.mjs` (`npm run bocode:selftest`). + +## Context + +ADR-007 made template updates *reachable* by adopters — a CHANGELOG, an agent-facing UPGRADE playbook, a `.bocode-version` stamp — but the upgrade path itself stayed prose. Downstream evidence (adopter session, 2026-11-07): an agent claimed "all major new specs incorporated" while missing ADR-011's added `boscope/references/automation-tools.md` — a miss the CHANGELOG entry had warned about in plain text. Four structural holes, in severity order: + +1. **No verification** — nothing checks that every template-owned delta since the stamp is applied or consciously kept; overclaiming costs zero (ADR-007's own words: a rule that can't be checked against a diff is a wish). +2. **The playbook vanishes on install** — init-project.sh deleted UPGRADE.md, and the only pointer (AGENTS.md's Staying-current section) is project-owned, frozen at adoption time. +3. **Skills never re-install** — the four skills live in the agent's directory outside the repo; the upgrade path refreshed the repo's `skills/` but never the copies the agent actually loads. An upgraded repo still behaved old. +4. **No staleness signal** — the stamp was written once and compared against nothing. + +The ownership knowledge itself lived in three copies (UPGRADE.md's table, check-release-changelog.mjs's prefix list, ADOPT.md's manifest) — exactly the drift ADR-007's consequences predicted. + +## Decision + +- **`code/tools/bocode-upgrade.mjs`** — `--check` lists every template-owned delta since the stamp with a disposition (`stale`/`new-file`/`stale-delete`/`pkg-stale` = mechanically safe; `merged` = conscious local state; `diverged-delete`/`missing` = human decision, recorded via `--keep`); `--apply` performs the safe actions, re-verifies from disk, advances the stamp only on green, writes a report into the adopter's `book/changelogs/YYYY-MM/`, and regenerates the index; `--verify` is the gate — exit 0 or the sync is not done. `--skills-dir` re-installs the four skills and joins the gate. Idempotent: a synced repo is a green no-op. +- **A single manifest** — `MANIFEST` in the tool is the one source of truth. It carries two facets with different semantics: `upgradeOwned` (what the tool may touch in an adopter; default-deny — everything unmatched is project-owned) and `releaseSignal` (what a template-repo change owes a CHANGELOG entry; wider on purpose). `check-release-changelog.mjs` imports the latter; UPGRADE.md's human table derives from the former. +- **`code/tools/bocode-doctor.mjs`** — read-only staleness checkup: tool presence, stamp validity, upstream HEAD via `git ls-remote` (offline degrades to unknown), skills freshness. Informational by default, `--strict` to gate. +- **UPGRADE.md becomes template-owned** — it ships with every install (init-project.sh no longer deletes it; ADOPT.md installs it) and refreshes itself through the tool it documents. AGENTS.md's Staying-current section and the `bocode` skill's upgrade contract now point at the local tooling, which survives adoption freezing because the tool, not the prose, carries the procedure. +- **Selftest ships too** — `bocode-upgrade.test.mjs` builds a fake upstream and adopters in a temp dir and drives every disposition state with no network; adopters can rerun it after any upgrade to prove their gate still gates. + +Rejected: semver/npm packaging (ADR-007's stance stands — install-by-copy means the tooling must be boring files); keeping the procedure prose-only with stricter wording (the failure was structural, not literary); forcing skills auto-detection (guessing a global skills directory is worse than an explicit `--skills-dir`). + +## Consequences + +- A sync claim is checkable: "done" means `--verify` exits 0, and the generated report is the human's review artifact +- Pre-ADR-012 adopters bootstrap once by hand: fetch `code/tools/bocode-*.mjs` + UPGRADE.md from upstream, then the tool upgrades itself (documented in UPGRADE.md's bootstrap section and this release's CHANGELOG entry) +- Adding a template file now means adding it to `MANIFEST` — a file missing there is silently skipped by every future upgrade; UPGRADE.md's what-not-to-do says so +- `code/package.json` is never byte-compared: only script entries merge, the project's `name` and local-only entries are untouchable +- The doctor's network check stays optional (offline is a warning, never a failure) — no session-start nagging +- The template repo itself never runs `--apply` (it *is* upstream); the selftest covers the tool with fixtures instead diff --git a/code/package.json b/code/package.json index 922f68d..a52e1d1 100644 --- a/code/package.json +++ b/code/package.json @@ -3,9 +3,12 @@ "version": "0.1.0", "private": true, "type": "module", - "description": "Project source tree. The only script here is the book index generator — this file has zero dependencies by design.", + "description": "Project source tree. Zero-dependency scripts by design: book index, template sync (bocode:*), and the release cleanliness check.", "scripts": { "book:index": "node tools/gen-book-index.mjs", - "book:release-check": "node tools/check-template-clean.mjs" + "book:release-check": "node tools/check-template-clean.mjs", + "bocode:upgrade": "node tools/bocode-upgrade.mjs", + "bocode:doctor": "node tools/bocode-doctor.mjs", + "bocode:selftest": "node tools/bocode-upgrade.test.mjs" } } diff --git a/code/tools/bocode-doctor.mjs b/code/tools/bocode-doctor.mjs new file mode 100644 index 0000000..ec25d0d --- /dev/null +++ b/code/tools/bocode-doctor.mjs @@ -0,0 +1,106 @@ +#!/usr/bin/env node +// bocode-doctor.mjs — staleness checkup for adopting projects (ADR-012). +// +// node code/tools/bocode-doctor.mjs [--skills-dir ] [--remote ] [--strict] +// +// Read-only. Checks: the upgrade tool itself, the .bocode-version stamp, +// upstream HEAD (git ls-remote; offline degrades to "unknown"), and — when +// --skills-dir is given — the four skills installed in the agent's directory. +// Default exit 0 with warnings; --strict exits 1 on any actionable finding. + +import { execSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { DEFAULT_REMOTE, skillsStates } from "./bocode-upgrade.mjs"; + +function parseArgs(argv) { + const flags = {}; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === "--strict") flags.strict = true; + else if (a === "--skills-dir") flags.skillsDir = argv[++i]; + else if (a === "--remote") flags.remote = argv[++i]; + else { console.error(`Unknown argument: ${a}`); process.exit(2); } + } + return flags; +} + +function adopterRoot() { + try { + return execSync("git rev-parse --show-toplevel", { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim(); + } catch { + return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); + } +} + +const flags = parseArgs(process.argv.slice(2)); +const root = adopterRoot(); +const remote = flags.remote || DEFAULT_REMOTE; +let hardFail = false; + +// 1. the upgrade tool itself (pre-ADR-012 adopters lack it) +const hasTool = existsSync(path.join(root, "code", "tools", "bocode-upgrade.mjs")); +console.log(`${hasTool ? "ok " : "FAIL"} upgrade tool present`); +if (!hasTool) { + hardFail = true; + console.log(" fetch code/tools/bocode-upgrade.mjs (and bocode-doctor.mjs) from the BoCode repository"); +} + +// 2. the stamp +const stampFile = path.join(root, ".bocode-version"); +let stamp = null; +if (!existsSync(stampFile)) { + console.log("WARN no .bocode-version stamp — adopted before 2026-11-05? see UPGRADE.md → \"Fallback: no stamp\""); + if (flags.strict) hardFail = true; +} else { + const raw = readFileSync(stampFile, "utf8").trim(); + if (/^[0-9a-f]{40}$/.test(raw)) { + stamp = raw; + console.log(`ok stamp ${raw.slice(0, 7)}`); + } else { + console.log(`FAIL stamp is not a 40-hex commit SHA: "${raw.slice(0, 20)}"`); + hardFail = true; + } +} + +// 3. upstream HEAD (offline degrades to unknown — never a failure) +if (stamp) { + try { + const upstream = execSync(`git ls-remote ${remote} HEAD`, { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }) + .trim().split(/\s+/)[0]; + if (upstream === stamp) { + console.log("ok up to date with upstream HEAD"); + } else { + console.log(`FAIL behind upstream: local ${stamp.slice(0, 7)}, upstream ${upstream.slice(0, 7)}`); + console.log(" run: cd code && npm run bocode:upgrade -- --check"); + hardFail = true; + } + } catch { + console.log("WARN upstream unknown (offline) — rerun with network, or diff against a local clone via bocode-upgrade --repo"); + } +} + +// 4. skills freshness in the agent's directory +if (flags.skillsDir) { + const states = skillsStates(root, flags.skillsDir); + for (const [name, state] of Object.entries(states)) { + if (state === "current") { + console.log(`ok skills/${name} current`); + } else if (state === "no-source") { + console.log(`WARN skills/${name} missing in this repo — nothing to install from`); + } else { + console.log(`FAIL skills/${name} ${state} in ${flags.skillsDir}`); + console.log(" run: cd code && npm run bocode:upgrade -- --apply --skills-dir "); + hardFail = true; + } + } +} else { + console.log("WARN skills not checked — pass --skills-dir to compare the four installed skills"); +} + +if (hardFail) { + console.error(flags.strict ? "\ndoctor: actionable findings (strict)" : "\ndoctor: actionable findings"); + process.exit(flags.strict ? 1 : 0); +} +console.log("\ndoctor: clean"); diff --git a/code/tools/bocode-upgrade.mjs b/code/tools/bocode-upgrade.mjs new file mode 100644 index 0000000..14e3130 --- /dev/null +++ b/code/tools/bocode-upgrade.mjs @@ -0,0 +1,454 @@ +#!/usr/bin/env node +// bocode-upgrade.mjs — the template-sync gate for adopting projects (ADR-012). +// +// node code/tools/bocode-upgrade.mjs --check list every template-owned delta and its disposition +// node code/tools/bocode-upgrade.mjs --apply copy pristine/new files, merge script entries, verify +// node code/tools/bocode-upgrade.mjs --verify the gate: exit 0 only when fully synced +// +// --repo use a local BoCode clone (default: full clone of --remote into a temp dir) +// --remote upstream URL (default https://github.com/Focus695/BoCode, or $BOCODE_REMOTE) +// --skills-dir agent skills directory; --apply re-installs the four skills, --verify checks them +// --stamp set the baseline by hand (stamp-less pre-2026-11-05 adoptions) +// --keep declare a template path consciously kept local (passes verify, lands in the report) +// +// MANIFEST below is the single source of truth for template-vs-project ownership. +// UPGRADE.md restates it for humans; scripts/check-release-changelog.mjs imports releaseSignal. + +import { execSync, spawnSync } from "node:child_process"; +import { + cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync, +} from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +export const DEFAULT_REMOTE = process.env.BOCODE_REMOTE || "https://github.com/Focus695/BoCode"; + +export const SKILL_DIRS = ["bocode", "boscope", "book-writeback", "bowrite"]; + +export const MANIFEST = { + // What an upgrade may refresh in an adopting project. Everything else is + // project-owned and never touched. UPGRADE.md's table restates this list. + upgradeOwned: { + files: [ + "UPGRADE.md", + "book/guidelines/README.md", + "book/guidelines/workflow.md", + "book/guidelines/task-tiers.md", + "book/guidelines/writing-style.md", + "book/guidelines/git-workflow.md", + "book/guidelines/review-checklist.md", + "book/docs/README.md", + "book/docs/architecture/README.md", + "book/docs/api/README.md", + "book/docs/decisions/README.md", + "book/notes/README.md", + "book/plans/README.md", + "book/changelogs/README.md", + "skills/README.md", + "code/package.json", // special: only the scripts block merges; name and the rest stay + ], + trees: [ + "skills/bocode", + "skills/boscope", + "skills/book-writeback", + "skills/bowrite", + "code/tools", + ], + // Template-owned only where the adopter kept them (ADOPT.md optional steps). + optional: [ + "scripts/check-commit-message.mjs", + "scripts/check-release-changelog.mjs", + ".githooks", + ".github/workflows/git-policy.yml", + ], + }, + // Template-repo paths whose change owes a CHANGELOG.md entry (ADR-007). + // Wider than upgradeOwned on purpose: the template's own front matter is + // release signal too, even though adopters own their copies of it. + releaseSignal: [ + "AGENTS.md", "ADOPT.md", "UPGRADE.md", + "README.md", "README.zh-CN.md", "README.ja.md", + "book/guidelines/", "book/docs/decisions/", + "skills/", "code/tools/", "code/package.json", + "scripts/", ".githooks/", ".github/workflows/", + ], +}; + +// ---------- small helpers ---------- + +const q = (s) => `"${String(s).replace(/"/g, '\\"')}"`; +const bufEq = (a, b) => Buffer.compare(a, b) === 0; + +function gitStr(repo, args) { + return execSync(`git -C ${q(repo)} ${args}`, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 }).trim(); +} + +function gitBuf(repo, args) { + return execSync(`git -C ${q(repo)} ${args}`, { encoding: "buffer", maxBuffer: 64 * 1024 * 1024 }); +} + +function parseArgs(argv) { + const flags = { keep: [] }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === "--check" || a === "--apply" || a === "--verify") flags.mode = a.slice(2); + else if (a === "--repo") flags.repo = argv[++i]; + else if (a === "--remote") flags.remote = argv[++i]; + else if (a === "--skills-dir") flags.skillsDir = argv[++i]; + else if (a === "--stamp") flags.stamp = argv[++i]; + else if (a === "--keep") flags.keep.push(argv[++i]); + else { console.error(`Unknown argument: ${a}`); usage(2); } + } + if (!flags.mode) usage(2); + return flags; +} + +function usage(code) { + console.error("Usage: bocode-upgrade.mjs --check|--apply|--verify [--repo ] [--remote ]"); + console.error(" [--skills-dir ] [--stamp ] [--keep ] [--keep ...]"); + process.exit(code); +} + +// The adopting project's root. Git first (adopters are repos); fall back to +// this script's location (code/tools/ -> root two levels up). +function adopterRoot() { + try { + return execSync("git rev-parse --show-toplevel", { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim(); + } catch { + return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); + } +} + +function readStamp(root) { + const file = path.join(root, ".bocode-version"); + if (!existsSync(file)) return null; + const sha = readFileSync(file, "utf8").trim(); + return /^[0-9a-f]{40}$/.test(sha) ? sha : null; +} + +// ---------- ownership + classification ---------- + +function ownership(p, root) { + const up = MANIFEST.upgradeOwned; + if (up.files.includes(p)) return p === "code/package.json" ? "package" : "template"; + for (const t of up.trees) if (p === t || p.startsWith(t + "/")) return "template"; + for (const o of up.optional) { + if (p === o || p.startsWith(o + "/")) return existsSync(path.join(root, p)) ? "template" : "none"; + } + return "none"; +} + +function changedEntries(repo, stamp, head) { + const out = gitStr(repo, `diff --name-status --no-renames ${stamp} ${head}`); + return out + .split("\n") + .filter(Boolean) + .map((line) => { + const tab = line.indexOf("\t"); + return { status: line.slice(0, tab), path: line.slice(tab + 1) }; + }); +} + +// Dispositions: +// applied local file already matches upstream HEAD +// stale local matches the old stamp version — safe to auto-copy +// merged local, stamp, and HEAD all differ — a conscious merge already happened +// new-file added upstream, absent locally — safe to auto-copy +// stale-delete deleted upstream, local still the old version — safe to delete +// diverged-delete deleted upstream, local modified — human decides (delete or move aside) +// missing modified upstream, adopter deleted it — restore, or --keep to record the removal +// pkg-stale code/package.json misses upstream script entries — merge keys only +// kept covered by an explicit --keep — recorded, never copied +function classify(entry, repo, stamp, head, root, keeps) { + const p = entry.path; + const localPath = path.join(root, p); + const hasLocal = existsSync(localPath); + + if (entry.status === "A") { + const headBuf = gitBuf(repo, `show ${head}:${p}`); + if (!hasLocal) return { path: p, state: "new-file", headBuf }; + return bufEq(readFileSync(localPath), headBuf) + ? { path: p, state: "applied" } + : { path: p, state: "merged" }; // created independently on both sides + } + if (entry.status === "D") { + if (!hasLocal) return { path: p, state: "applied" }; + if (keeps.includes(p)) return { path: p, state: "kept" }; + const stampBuf = gitBuf(repo, `show ${stamp}:${p}`); + return bufEq(readFileSync(localPath), stampBuf) + ? { path: p, state: "stale-delete" } + : { path: p, state: "diverged-delete" }; + } + // modified upstream + if (p === "code/package.json") return classifyPackage(repo, head, root); + if (!hasLocal) return keeps.includes(p) ? { path: p, state: "kept" } : { path: p, state: "missing" }; + const headBuf = gitBuf(repo, `show ${head}:${p}`); + if (bufEq(readFileSync(localPath), headBuf)) return { path: p, state: "applied" }; + const stampBuf = gitBuf(repo, `show ${stamp}:${p}`); + if (bufEq(readFileSync(localPath), stampBuf)) return { path: p, state: "stale", headBuf }; + return { path: p, state: "merged" }; +} + +function classifyPackage(repo, head, root) { + const upPkg = JSON.parse(gitBuf(repo, `show ${head}:code/package.json`).toString("utf8")); + const localPath = path.join(root, "code/package.json"); + const local = existsSync(localPath) + ? JSON.parse(readFileSync(localPath, "utf8")) + : { scripts: {} }; + const upScripts = upPkg.scripts || {}; + const missing = Object.entries(upScripts).filter(([k, v]) => (local.scripts || {})[k] !== v).map(([k]) => k); + return { + path: "code/package.json", + state: missing.length ? "pkg-stale" : "applied", + missing, + upScripts, + }; +} + +// ---------- apply / verify ---------- + +function applyItems(items, root) { + const actions = []; + for (const it of items) { + const localPath = path.join(root, it.path); + if (it.state === "stale" || it.state === "new-file") { + mkdirSync(path.dirname(localPath), { recursive: true }); + writeFileSync(localPath, it.headBuf); + actions.push(`copied ${it.path}`); + } else if (it.state === "stale-delete") { + rmSync(localPath); + actions.push(`deleted ${it.path}`); + } else if (it.state === "pkg-stale") { + const local = JSON.parse(readFileSync(localPath, "utf8")); + local.scripts = { ...(local.scripts || {}), ...it.upScripts }; + writeFileSync(localPath, JSON.stringify(local, null, 2) + "\n"); + actions.push(`merged scripts: ${it.missing.join(", ")}`); + } + } + return actions; +} + +const FAILING_STATES = ["stale", "new-file", "missing", "diverged-delete", "pkg-stale"]; + +function verify(items, skillsStates) { + const failures = items + .filter((it) => FAILING_STATES.includes(it.state)) + .map((it) => ` ${it.state.padEnd(15)} ${it.path}${it.state === "pkg-stale" ? ` (missing: ${it.missing.join(", ")})` : ""}`); + if (skillsStates) { + for (const [name, state] of Object.entries(skillsStates)) { + if (state === "stale" || state === "missing") { + failures.push(` ${("skill-" + state).padEnd(15)} skills/${name} → ${state} in the agent skills directory`); + } + } + } + return failures; +} + +// ---------- skills ---------- + +function walkFiles(dir, base = dir, out = []) { + for (const name of readdirSync(dir)) { + const full = path.join(dir, name); + if (statSync(full).isDirectory()) walkFiles(full, base, out); + else out.push(path.relative(base, full)); + } + return out.sort(); +} + +function treeEq(a, b) { + const filesA = walkFiles(a); + const filesB = walkFiles(b); + if (filesA.length !== filesB.length || filesA.some((f, i) => f !== filesB[i])) return false; + return filesA.every((f) => bufEq(readFileSync(path.join(a, f)), readFileSync(path.join(b, f)))); +} + +export function skillsStates(root, skillsDir) { + const states = {}; + for (const s of SKILL_DIRS) { + const src = path.join(root, "skills", s); + if (!existsSync(src)) { states[s] = "no-source"; continue; } + const dst = path.join(skillsDir, s); + if (!existsSync(dst)) { states[s] = "missing"; continue; } + states[s] = treeEq(src, dst) ? "current" : "stale"; + } + return states; +} + +function installSkills(root, skillsDir) { + mkdirSync(skillsDir, { recursive: true }); + for (const s of SKILL_DIRS) { + const src = path.join(root, "skills", s); + if (!existsSync(src)) continue; + const dst = path.join(skillsDir, s); + rmSync(dst, { recursive: true, force: true }); + cpSync(src, dst, { recursive: true }); + } +} + +// ---------- report + index ---------- + +function writeReport(root, fromSha, toSha, items, skillsNote) { + const now = new Date(); + const yyyy = now.getFullYear(); + const mm = String(now.getMonth() + 1).padStart(2, "0"); + const dd = String(now.getDate()).padStart(2, "0"); + const dir = path.join(root, "book", "changelogs", `${yyyy}-${mm}`); + mkdirSync(dir, { recursive: true }); + const file = path.join(dir, `bocode-sync-${yyyy}-${mm}-${dd}-${toSha.slice(0, 7)}.md`); + const rows = items.length + ? items.map((it) => `| ${it.state} | \`${it.path}\` |`).join("\n") + : "| (none — only the stamp moved) | |"; + const body = `--- +description: BoCode template sync ${fromSha.slice(0, 7)} → ${toSha.slice(0, 7)} on ${yyyy}-${mm}-${dd} — per-file dispositions, verify green, ${skillsNote} +--- + +# BoCode sync ${yyyy}-${mm}-${dd} + +- Baseline: \`${fromSha.slice(0, 7)}\` → \`${toSha.slice(0, 7)}\` (commit SHAs, ADR-007) +- Verify: green (every template-owned delta applied, merged, or consciously kept) +- Skills: ${skillsNote} + +| Disposition | Path | +|-------------|------| +${rows} + +Generated by \`code/tools/bocode-upgrade.mjs --apply\` — regenerate the index after editing. +`; + writeFileSync(file, body); + return file; +} + +function runIndex(root) { + const script = path.join(root, "code", "tools", "gen-book-index.mjs"); + if (!existsSync(script)) return { ok: true, note: "gen-book-index.mjs not installed — index step skipped" }; + const res = spawnSync("node", [script], { cwd: path.join(root, "code"), encoding: "utf8" }); + if (res.status !== 0) { + return { ok: false, note: (res.stdout || "") + (res.stderr || "") }; + } + return { ok: true, note: res.stdout || "" }; +} + +// ---------- main ---------- + +function main() { +const flags = parseArgs(process.argv.slice(2)); +const root = adopterRoot(); +const remote = flags.remote || DEFAULT_REMOTE; + +let tmpDir = null; +let repo = flags.repo; +if (!repo) { + tmpDir = mkdtempSync(path.join(os.tmpdir(), "bocode-upgrade-")); + console.error(`Cloning ${remote} (full clone — the stamp must be reachable, ADR-007)...`); + try { + execSync(`git clone --quiet ${q(remote)} ${q(tmpDir)}`, { stdio: "pipe" }); + } catch { + console.error(`Clone failed. Point --repo at a local BoCode clone, or check network access to ${remote}.`); + rmSync(tmpDir, { recursive: true, force: true }); + process.exit(1); + } + repo = tmpDir; +} + +try { + const head = gitStr(repo, "rev-parse HEAD"); + const stamp = flags.stamp || readStamp(root); + if (!stamp) { + console.error("No valid .bocode-version stamp and no --stamp given."); + console.error("Adopted before 2026-11-05? See UPGRADE.md → \"Fallback: no stamp\"."); + process.exit(1); + } + + const doSkills = () => (flags.skillsDir ? skillsStates(root, flags.skillsDir) : null); + const printSkills = (states) => { + if (!states) return; + for (const [name, state] of Object.entries(states)) console.log(` skills/${name}: ${state}`); + }; + + if (stamp === head) { + console.log(`Up to date: .bocode-version == upstream HEAD (${head.slice(0, 7)}). Nothing to do.`); + if (flags.skillsDir) { + const states = doSkills(); + printSkills(states); + if (Object.values(states).some((s) => s === "stale" || s === "missing")) { + if (flags.mode === "apply") { + installSkills(root, flags.skillsDir); + console.log("Skills re-installed into the agent skills directory."); + } else { + console.error("Skills are stale — rerun with --apply (or copy the four skills by hand)."); + process.exit(1); + } + } + } + process.exit(0); + } + + const entries = changedEntries(repo, stamp, head).filter((e) => ownership(e.path, root) !== "none"); + const items = entries.map((e) => classify(e, repo, stamp, head, root, flags.keep)); + + if (flags.mode === "check") { + console.log(`Baseline ${stamp.slice(0, 7)} → upstream HEAD ${head.slice(0, 7)}; ${items.length} template-owned change(s):`); + for (const it of items) { + console.log(` ${it.state.padEnd(15)} ${it.path}`); + } + printSkills(doSkills()); + const failures = verify(items, doSkills()); + if (failures.length) { + console.error(`\nNot fully synced (${failures.length} outstanding):`); + failures.forEach((f) => console.error(f)); + process.exit(1); + } + console.log("\nFully synced — every delta applied, merged, or consciously kept."); + process.exit(0); + } + + if (flags.mode === "apply") { + const actions = applyItems(items, root); + if (flags.skillsDir) installSkills(root, flags.skillsDir); + actions.forEach((a) => console.log(a)); + + // Recompute from disk: the gate trusts the tree, not the plan. + const items2 = entries.map((e) => classify(e, repo, stamp, head, root, flags.keep)); + const failures = verify(items2, doSkills()); + if (failures.length) { + console.error(`\nVerify NOT green (${failures.length} outstanding) — stamp left unchanged:`); + failures.forEach((f) => console.error(f)); + console.error("Merge the flagged files (keep your edits, take the template's changes), rerun --apply."); + process.exit(1); + } + + writeFileSync(path.join(root, ".bocode-version"), head + "\n"); + const report = writeReport(root, stamp, head, items2, flags.skillsDir ? "re-installed via --skills-dir" : "not checked (no --skills-dir given)"); + console.log(`Verify green. Stamp → ${head.slice(0, 7)}. Report: ${path.relative(root, report)}`); + + const index = runIndex(root); + if (!index.ok) { + console.error(`Index regeneration failed:\n${index.note}`); + process.exit(1); + } + if (index.note) console.log(index.note.trim()); + process.exit(0); + } + + // --verify + { + const failures = verify(items, doSkills()); + printSkills(doSkills()); + if (failures.length) { + console.error(`Verify failed (${failures.length} outstanding):`); + failures.forEach((f) => console.error(f)); + console.error("A sync is done when this exits 0 — never when an agent says so."); + process.exit(1); + } + console.log(`Verify green against upstream HEAD ${head.slice(0, 7)}.`); + process.exit(0); + } +} finally { + if (tmpDir) rmSync(tmpDir, { recursive: true, force: true }); +} +} + +// Run only when invoked directly — bocode-doctor.mjs imports this module for +// MANIFEST / SKILL_DIRS / skillsStates and must not trigger an upgrade. +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main(); diff --git a/code/tools/bocode-upgrade.test.mjs b/code/tools/bocode-upgrade.test.mjs new file mode 100644 index 0000000..c876557 --- /dev/null +++ b/code/tools/bocode-upgrade.test.mjs @@ -0,0 +1,237 @@ +#!/usr/bin/env node +// bocode-upgrade.test.mjs — selftest for the template-sync gate (ADR-012). +// +// node code/tools/bocode-upgrade.test.mjs (or: cd code && npm run bocode:selftest) +// +// Builds a fake upstream (two commits) and fake adopters in a temp dir, then +// drives bocode-upgrade / bocode-doctor through every disposition state. No +// network: everything runs against the local fixture via --repo / --remote. +// Adopters can rerun this after an upgrade to prove the tool still gates. + +import { execSync, spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const TOOL = path.join(HERE, "bocode-upgrade.mjs"); +const DOCTOR = path.join(HERE, "bocode-doctor.mjs"); + +const q = (s) => `"${String(s).replace(/"/g, '\\"')}"`; +const GIT_ID = `-c user.email=dev@test -c user.name=dev`; + +let failures = 0; +const ok = (cond, label) => { + console.log(`${cond ? "ok " : "FAIL"} ${label}`); + if (!cond) failures++; +}; + +const run = (script, args, cwd) => + spawnSync("node", [script, ...args], { cwd, encoding: "utf8" }); + +const sh = (cmd) => execSync(cmd, { stdio: "pipe" }).toString(); + +function write(root, rel, content) { + const full = path.join(root, rel); + mkdirSync(path.dirname(full), { recursive: true }); + writeFileSync(full, content); +} + +function gitInit(dir) { + sh(`git init -q ${q(dir)}`); +} + +function commitAll(repo, msg) { + sh(`git -C ${q(repo)} add -A && git -C ${q(repo)} ${GIT_ID} commit -q -m ${q(msg)}`); +} + +function checkoutTree(repo, sha, dest) { + const tar = execSync(`git -C ${q(repo)} archive ${sha}`, { maxBuffer: 64 * 1024 * 1024 }); + const res = spawnSync("tar", ["-x", "-C", dest], { input: tar }); + if (res.status !== 0) throw new Error("tar extract failed"); +} + +// ---------- fixture: the fake upstream ---------- + +const tmp = mkdtempSync(path.join(os.tmpdir(), "bocode-selftest-")); +const upstream = path.join(tmp, "upstream"); + +gitInit(upstream); +write(upstream, "UPGRADE.md", "upgrade v1\n"); +write(upstream, "AGENTS.md", "agents v1\n"); +write(upstream, "book/guidelines/workflow.md", "workflow v1\n"); +write(upstream, "book/guidelines/writing-style.md", "style v1\n"); +write(upstream, "book/guidelines/review-checklist.md", "review v1\n"); +write(upstream, "book/notes/README.md", "notes readme v1\n"); +write(upstream, "skills/README.md", "skills readme v1\n"); +write(upstream, "skills/bocode/SKILL.md", "bocode v1\n"); +write(upstream, "skills/bowrite/SKILL.md", "bowrite v1\n"); +write(upstream, "skills/book-writeback/SKILL.md", "writeback v1\n"); +write(upstream, "skills/boscope/SKILL.md", "boscope v1\n"); +write(upstream, "code/tools/gen-book-index.mjs", "console.log('index ok');\n"); +write(upstream, "code/tools/bocode-upgrade.mjs", "upgrade tool stub v1\n"); // so doctor's presence check passes +write(upstream, "code/tools/bocode-doctor.mjs", "doctor stub v1\n"); +write(upstream, "code/package.json", JSON.stringify({ + name: "bocode", + scripts: { "book:index": "node tools/gen-book-index.mjs" }, +}, null, 2) + "\n"); +write(upstream, "scripts/check-commit-message.mjs", "commit check v1\n"); +commitAll(upstream, "v1"); +const STAMP = sh(`git -C ${q(upstream)} rev-parse HEAD`).trim(); + +// v2: modify pristine + diverged + skills, add the reference (the ADR-011 +// regression shape), delete a guideline, extend package scripts, touch +// project-owned AGENTS.md (must be ignored). +write(upstream, "book/guidelines/workflow.md", "workflow v2\n"); +write(upstream, "book/guidelines/writing-style.md", "style v2\n"); +write(upstream, "book/notes/README.md", "notes readme v2\n"); +write(upstream, "skills/boscope/SKILL.md", "boscope v2\n"); +write(upstream, "skills/boscope/references/automation-tools.md", "automation v2\n"); +write(upstream, "code/package.json", JSON.stringify({ + name: "bocode", + scripts: { + "book:index": "node tools/gen-book-index.mjs", + "bocode:doctor": "node tools/bocode-doctor.mjs", + }, +}, null, 2) + "\n"); +write(upstream, "scripts/check-commit-message.mjs", "commit check v2\n"); +write(upstream, "AGENTS.md", "agents v2\n"); +rmSync(path.join(upstream, "book/guidelines/review-checklist.md")); +commitAll(upstream, "v2"); +const HEAD = sh(`git -C ${q(upstream)} rev-parse HEAD`).trim(); + +// ---------- fixture: the adopter (installed at v1, one file diverged) ---------- + +const adopter = path.join(tmp, "adopter"); +gitInit(adopter); +checkoutTree(upstream, STAMP, adopter); +// project-owned state: diverge one template file, keep the project's name +write(adopter, "book/guidelines/writing-style.md", "style v1 + local edit\n"); +{ + const pkgPath = path.join(adopter, "code/package.json"); + const pkg = JSON.parse(readFileSync(pkgPath, "utf8")); + pkg.name = "myproject"; + pkg.scripts["custom:thing"] = "echo hi"; + writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n"); +} +writeFileSync(path.join(adopter, ".bocode-version"), STAMP + "\n"); +// the agent's skills directory, installed at v1 (boscope will be stale after sync) +const skillsDir = path.join(tmp, "agent-skills"); +mkdirSync(skillsDir, { recursive: true }); +for (const s of ["bocode", "bowrite", "book-writeback", "boscope"]) { + execSync(`cp -r ${q(path.join(adopter, "skills", s))} ${q(skillsDir)}`); +} +// the index stub reports itself; the report lands in the adopter's changelogs +write(adopter, "book/changelogs/README.md", "changelogs readme v1\n"); + +try { + // 1. --check before any sync: every disposition, exit 1 + { + const r = run(TOOL, ["--check", "--repo", upstream], adopter); + const out = r.stdout + r.stderr; + ok(r.status === 1, "check before sync exits 1"); + ok(out.includes("stale") && out.includes("book/guidelines/workflow.md"), "check lists stale workflow.md"); + ok(out.includes("new-file") && out.includes("automation-tools.md"), "check lists the new reference file (ADR-011 shape)"); + ok(out.includes("stale-delete") && out.includes("review-checklist.md"), "check lists stale-delete review-checklist.md"); + ok(out.includes("pkg-stale") && out.includes("code/package.json"), "check lists pkg-stale package.json"); + ok(out.includes("merged") && out.includes("writing-style.md"), "check lists merged writing-style.md"); + ok(!out.includes("AGENTS.md"), "project-owned AGENTS.md never appears"); + } + + // 2. --verify before sync: exit 1 + ok(run(TOOL, ["--verify", "--repo", upstream], adopter).status === 1, "verify before sync exits 1"); + + // 3. --apply with --skills-dir: green, stamp moved, report written + { + const r = run(TOOL, ["--apply", "--repo", upstream, "--skills-dir", skillsDir], adopter); + const out = r.stdout + r.stderr; + ok(r.status === 0, `apply exits 0 (${out.split("\n").filter(Boolean).slice(0, 3).join(" | ")})`); + ok(readFileSync(path.join(adopter, "book/guidelines/workflow.md"), "utf8") === "workflow v2\n", "stale workflow.md auto-copied"); + ok(existsSync(path.join(adopter, "skills/boscope/references/automation-tools.md")), "new reference file installed"); + ok(!existsSync(path.join(adopter, "book/guidelines/review-checklist.md")), "stale-delete removed the guideline"); + ok(readFileSync(path.join(adopter, "book/guidelines/writing-style.md"), "utf8") === "style v1 + local edit\n", "merged file left untouched"); + ok(readFileSync(path.join(adopter, "AGENTS.md"), "utf8") === "agents v1\n", "project-owned AGENTS.md untouched"); + ok(readFileSync(path.join(adopter, "scripts/check-commit-message.mjs"), "utf8") === "commit check v2\n", "optional adopted file refreshed"); + const pkg = JSON.parse(readFileSync(path.join(adopter, "code/package.json"), "utf8")); + ok(pkg.name === "myproject", "package.json name preserved"); + ok(pkg.scripts["custom:thing"] === "echo hi", "local-only script entry preserved"); + ok(pkg.scripts["bocode:doctor"] === "node tools/bocode-doctor.mjs", "upstream script entry merged in"); + ok(readFileSync(path.join(adopter, ".bocode-version"), "utf8").trim() === HEAD, "stamp advanced to upstream HEAD"); + const now = new Date(); + const monthDir = path.join(adopter, "book/changelogs", `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`); + const reports = existsSync(monthDir) ? readdirSync(monthDir).filter((f) => f.startsWith("bocode-sync-")) : []; + ok(reports.length === 1, "exactly one sync report written under book/changelogs/YYYY-MM"); + ok(reports.length === 1 && readFileSync(path.join(monthDir, reports[0]), "utf8").startsWith("---\ndescription: BoCode template sync"), "report carries frontmatter description"); + ok(readFileSync(path.join(adopter, "skills/boscope/SKILL.md"), "utf8") === "boscope v2\n", "repo skill refreshed"); + ok(readFileSync(path.join(skillsDir, "boscope/SKILL.md"), "utf8") === "boscope v2\n", "agent skills directory re-installed"); + } + + // 4. idempotency: a second apply is a green no-op + { + const r = run(TOOL, ["--apply", "--repo", upstream, "--skills-dir", skillsDir], adopter); + ok(r.status === 0 && (r.stdout + r.stderr).includes("Up to date"), "second apply is a green no-op"); + } + + // 5. --verify after sync: green + ok(run(TOOL, ["--verify", "--repo", upstream, "--skills-dir", skillsDir], adopter).status === 0, "verify after sync exits 0"); + + // 6. missing template file: fails verify, passes with an explicit --keep + { + const adopter2 = path.join(tmp, "adopter2"); + gitInit(adopter2); + checkoutTree(upstream, HEAD, adopter2); + writeFileSync(path.join(adopter2, ".bocode-version"), STAMP + "\n"); + rmSync(path.join(adopter2, "book/notes/README.md")); + ok(run(TOOL, ["--verify", "--repo", upstream], adopter2).status === 1, "missing template file fails verify"); + const r = run(TOOL, ["--verify", "--repo", upstream, "--keep", "book/notes/README.md"], adopter2); + ok(r.status === 0, "explicit --keep records the removal and passes"); + } + + // 7. skills gate: stale skills directory fails verify even with a synced repo + { + writeFileSync(path.join(skillsDir, "boscope/SKILL.md"), "boscope v1\n"); + const r = run(TOOL, ["--verify", "--repo", upstream, "--skills-dir", skillsDir], adopter); + ok(r.status === 1 && (r.stdout + r.stderr).includes("skills/boscope"), "stale agent skills fail verify"); + run(TOOL, ["--apply", "--repo", upstream, "--skills-dir", skillsDir], adopter); // restore + } + + // 8. diverged-delete: a locally modified file on a path upstream deleted + { + const adopter3 = path.join(tmp, "adopter3"); + gitInit(adopter3); + checkoutTree(upstream, HEAD, adopter3); + writeFileSync(path.join(adopter3, ".bocode-version"), STAMP + "\n"); + write(adopter3, "book/guidelines/review-checklist.md", "review v1 + local edit\n"); + ok(run(TOOL, ["--verify", "--repo", upstream], adopter3).status === 1, "diverged-delete fails verify"); + ok(run(TOOL, ["--verify", "--repo", upstream, "--keep", "book/guidelines/review-checklist.md"], adopter3).status === 0, "--keep records the kept file and passes"); + } + + // 9. doctor: behind / current / stale skills, --remote against the local fixture + { + writeFileSync(path.join(adopter, ".bocode-version"), STAMP + "\n"); // temporarily behind + const behind = run(DOCTOR, ["--remote", upstream, "--strict"], adopter); + ok(behind.status === 1 && (behind.stdout + behind.stderr).includes("behind upstream"), "doctor strict exits 1 when behind"); + writeFileSync(path.join(adopter, ".bocode-version"), HEAD + "\n"); + writeFileSync(path.join(skillsDir, "bocode/SKILL.md"), "bocode v0\n"); // stale skill + const stale = run(DOCTOR, ["--remote", upstream, "--skills-dir", skillsDir, "--strict"], adopter); + ok(stale.status === 1 && (stale.stdout + stale.stderr).includes("skills/bocode"), "doctor flags stale skills"); + run(TOOL, ["--apply", "--repo", upstream, "--skills-dir", skillsDir], adopter); // restore skills + const clean = run(DOCTOR, ["--remote", upstream, "--skills-dir", skillsDir], adopter); + ok(clean.status === 0 && (clean.stdout + clean.stderr).includes("doctor: clean"), "doctor clean when current"); + } + + // 10. no stamp: refuses with the fallback pointer + { + const adopter4 = path.join(tmp, "adopter4"); + gitInit(adopter4); + write(adopter4, "README.md", "a project\n"); + const r = run(TOOL, ["--check", "--repo", upstream], adopter4); + ok(r.status === 1 && (r.stdout + r.stderr).includes("Fallback"), "stamp-less project is pointed at the fallback"); + } + + console.log(failures === 0 ? "\nselftest: all green" : `\nselftest: ${failures} failure(s)`); + process.exit(failures === 0 ? 0 : 1); +} finally { + rmSync(tmp, { recursive: true, force: true }); +} diff --git a/scripts/check-release-changelog.mjs b/scripts/check-release-changelog.mjs index dfb4bab..efef287 100644 --- a/scripts/check-release-changelog.mjs +++ b/scripts/check-release-changelog.mjs @@ -5,24 +5,15 @@ // // Fails when the base...head diff touches template-owned content but // CHANGELOG.md is not part of the diff. Template-owned = what adopting -// projects install (guidelines, skills, tooling, agent entry points). -// The list mirrors the ownership table in UPGRADE.md — keep them in sync. +// projects install (guidelines, skills, tooling, agent entry points) plus +// the template's own front matter. The path list lives in MANIFEST — the +// single source of truth exported by code/tools/bocode-upgrade.mjs +// (ADR-012); UPGRADE.md restates it for humans. import { execSync } from "node:child_process"; +import { MANIFEST } from "../code/tools/bocode-upgrade.mjs"; -const TEMPLATE_PREFIXES = [ - "AGENTS.md", - "ADOPT.md", - "UPGRADE.md", - "book/guidelines/", - "book/docs/decisions/", - "skills/", - "code/tools/", - "code/package.json", - "scripts/", - ".githooks/", - ".github/workflows/", -]; +const TEMPLATE_PREFIXES = MANIFEST.releaseSignal; const CHANGELOG = "CHANGELOG.md"; diff --git a/scripts/init-project.sh b/scripts/init-project.sh index c9dba73..d07f9be 100755 --- a/scripts/init-project.sh +++ b/scripts/init-project.sh @@ -78,7 +78,7 @@ ${DESC} This project runs on the BoCode workflow. EOF -rm -f README.zh-CN.md README.ja.md ADOPT.md CHANGELOG.md UPGRADE.md +rm -f README.zh-CN.md README.ja.md ADOPT.md CHANGELOG.md # 4. Clear BoCode's own living records for kind in learn summary issue; do @@ -126,5 +126,7 @@ echo " 2. Point your AI agent at AGENTS.md (most tools pick it up automatically echo " 3. Fill in book/guidelines/architecture.md and coding-style.md for your project." echo " 4. Set your remote:" echo " git remote add origin " -echo " 5. To upgrade later: an agent reads UPGRADE.md + CHANGELOG.md at" -echo " https://github.com/Focus695/BoCode (your .bocode-version pins the baseline)." +echo " 5. To upgrade later (the tooling ships with the project):" +echo " cd code && npm run bocode:doctor # am I behind upstream?" +echo " npm run bocode:upgrade -- --check # per-file disposition list" +echo " UPGRADE.md at the root is the playbook; .bocode-version pins the baseline." diff --git a/skills/README.md b/skills/README.md index dd8f452..fea4632 100644 --- a/skills/README.md +++ b/skills/README.md @@ -23,4 +23,6 @@ Copy the four skill directories, including any `references/` subdirectories, int cp -r skills/bocode skills/boscope skills/book-writeback skills/bowrite / ``` +Skills do not update themselves. Re-install them on every BoCode upgrade — `cd code && npm run bocode:upgrade -- --apply --skills-dir ` does it, and `--verify` fails while an installed skill lags its `skills/` source. Stale skills are the number-one reason an upgraded repo still behaves old. + `bowrite` distills two upstreams with attribution kept: [shuorenhua](https://github.com/MrGeDiao/shuorenhua) (MIT, by MrGeDiao) for cleanup, and [human-writing](https://github.com/KKKKhazix/human-writing) (MIT, by KKKKhazix) for the from-scratch gates(材料门槛、段段有新货、成稿禁令)— together with patterns accumulated in this project's own reviews. For deep Chinese cleanups or full long-form creation the upstreams go further and are worth installing alongside. diff --git a/skills/bocode/SKILL.md b/skills/bocode/SKILL.md index 9dca376..029d53e 100644 --- a/skills/bocode/SKILL.md +++ b/skills/bocode/SKILL.md @@ -38,7 +38,7 @@ book/ 1. **Index contract**: every new book document starts with frontmatter `description` — one plain-language line about the *content* (not the genre). After any book change, run `cd code && npm run book:index`; the build fails on a missing description, and that's the point. 2. **Record-only contract**: problems found during review or wrap-up are recorded to `notes/issue/`, never fixed in passing. A recorded problem becomes a task; fixing is separate work. -3. **Upgrade contract**: the template evolves — when the user asks to sync BoCode or the workflow feels stale, read `UPGRADE.md` and `CHANGELOG.md` from the BoCode repository (https://github.com/Focus695/BoCode); the project's `.bocode-version` stamp is the baseline to diff against. +3. **Upgrade contract**: the template evolves — run `cd code && npm run bocode:doctor` when staleness matters (it compares the `.bocode-version` stamp with the BoCode repository, https://github.com/Focus695/BoCode). A sync follows `UPGRADE.md` at the project root: `npm run bocode:upgrade -- --check` → merge what's flagged → `--apply` (pass `--skills-dir` so the agent skills re-install too). The sync is done only when `--verify` exits green — never when you feel done. ## What not to do From 800e02b6cd5fc196d08564a26a33f8654538feed Mon Sep 17 00:00:00 2001 From: Focus Date: Sat, 7 Nov 2026 20:12:33 +0800 Subject: [PATCH 2/8] =?UTF-8?q?=F0=9F=94=A7=20update=20(tools):=20guard=20?= =?UTF-8?q?skills-dir=20installs=20against=20stray=20targets?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tier M (F1 adds refusal behavior to --apply --skills-dir and needs new tests; F2/F3 ride along in the same functional area) — the follow-up round recorded in the abaedc6 review. F1: installSkills refuses to replace a --skills-dir entry that exists but holds no SKILL.md — a mistyped path can no longer delete unrelated same-named directories. F2: adopterRoot exported from bocode-upgrade and imported by bocode-doctor (dedup). F3: classifyPackage wraps both JSON.parse sites with readable, actionable errors. Verified: selftest green (37 assertions, three new), book:index zero warnings, book:release-check clean, commit subject validated. --- CHANGELOG.md | 2 +- code/tools/bocode-doctor.mjs | 11 +---------- code/tools/bocode-upgrade.mjs | 21 ++++++++++++++++++--- code/tools/bocode-upgrade.test.mjs | 23 +++++++++++++++++++++++ 4 files changed, 43 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index edf3fbd..9ae0b1a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ When adding an entry, also refresh the collapsed What's-new block near the top o The upgrade path was prose an agent could skim and overclaim (an adopter's agent declared ADR-011 "incorporated" while its new reference file was missing); the playbook was deleted on install; the agent-side skills never re-installed; the stamp was compared against nothing. Syncing is now tool-gated: `bocode-upgrade` diffs the stamp mechanically, `--verify` exits 0 only when every template-owned delta is applied, merged, or consciously kept, `bocode:doctor` reports staleness, and a single `MANIFEST` owns template-vs-project paths for both the sync and the release gate. -- Added: `code/tools/bocode-upgrade.mjs` (check/apply/verify, the MANIFEST single source, `--skills-dir` skill re-install, sync report into the adopter's `book/changelogs/`), `code/tools/bocode-doctor.mjs` (staleness checkup), `code/tools/bocode-upgrade.test.mjs` (no-network selftest), `book/docs/decisions/ADR-012-upgrade-sync-becomes-a-tool-gate.md` +- Added: `code/tools/bocode-upgrade.mjs` (check/apply/verify, the MANIFEST single source, `--skills-dir` skill re-install with a stray-target refusal guard, readable errors on a malformed local `package.json`, sync report into the adopter's `book/changelogs/`), `code/tools/bocode-doctor.mjs` (staleness checkup), `code/tools/bocode-upgrade.test.mjs` (no-network selftest), `book/docs/decisions/ADR-012-upgrade-sync-becomes-a-tool-gate.md` - Changed: `code/package.json` (`bocode:upgrade` / `bocode:doctor` / `bocode:selftest` scripts), `UPGRADE.md` (rewritten around the tool; now template-owned and self-refreshing), `ADOPT.md` (installs all of `code/tools/` + `UPGRADE.md`, skills re-install obligation, doctor + selftest in verification), `scripts/init-project.sh` (keeps `UPGRADE.md`; next-steps point at the local tooling), `scripts/check-release-changelog.mjs` (imports `MANIFEST.releaseSignal`; the signal now also covers the three READMEs), `AGENTS.md` (Staying current → local tooling, "done means `--verify` exits 0"), `skills/bocode/SKILL.md` (upgrade contract rewritten), `skills/README.md` (re-install on every upgrade), `README.md` / `README.zh-CN.md` / `README.ja.md` (FAQ, tour, What's-new) **Adopter action:** bootstrap once — copy `code/tools/bocode-upgrade.mjs`, `bocode-doctor.mjs`, and `bocode-upgrade.test.mjs` from the BoCode repository into your `code/tools/`, add the three `bocode:*` entries to your `code/package.json` scripts, copy `UPGRADE.md` to your root (it is template-owned from now on). Then run `npm run bocode:selftest` (green), `npm run bocode:upgrade -- --check`, `--apply` (pass `--skills-dir ` so the four skills re-install — stale installed skills are the top reason an upgraded repo still behaves old), and rerun until `--verify` is green. If you kept `scripts/check-release-changelog.mjs`, re-copy it too — it now imports the manifest. Do not skip the skills re-install; do not declare the sync done from the CHANGELOG reading alone — the verify exit code is the only proof. diff --git a/code/tools/bocode-doctor.mjs b/code/tools/bocode-doctor.mjs index ec25d0d..94bcd0e 100644 --- a/code/tools/bocode-doctor.mjs +++ b/code/tools/bocode-doctor.mjs @@ -11,8 +11,7 @@ import { execSync } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; -import { fileURLToPath } from "node:url"; -import { DEFAULT_REMOTE, skillsStates } from "./bocode-upgrade.mjs"; +import { DEFAULT_REMOTE, adopterRoot, skillsStates } from "./bocode-upgrade.mjs"; function parseArgs(argv) { const flags = {}; @@ -26,14 +25,6 @@ function parseArgs(argv) { return flags; } -function adopterRoot() { - try { - return execSync("git rev-parse --show-toplevel", { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim(); - } catch { - return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); - } -} - const flags = parseArgs(process.argv.slice(2)); const root = adopterRoot(); const remote = flags.remote || DEFAULT_REMOTE; diff --git a/code/tools/bocode-upgrade.mjs b/code/tools/bocode-upgrade.mjs index 14e3130..d695f9a 100644 --- a/code/tools/bocode-upgrade.mjs +++ b/code/tools/bocode-upgrade.mjs @@ -112,7 +112,7 @@ function usage(code) { // The adopting project's root. Git first (adopters are repos); fall back to // this script's location (code/tools/ -> root two levels up). -function adopterRoot() { +export function adopterRoot() { try { return execSync("git rev-parse --show-toplevel", { encoding: "utf8", stdio: ["pipe", "pipe", "pipe"] }).trim(); } catch { @@ -191,10 +191,18 @@ function classify(entry, repo, stamp, head, root, keeps) { } function classifyPackage(repo, head, root) { - const upPkg = JSON.parse(gitBuf(repo, `show ${head}:code/package.json`).toString("utf8")); + const parseOrQuit = (text, what) => { + try { + return JSON.parse(text); + } catch (e) { + console.error(`${what} is not valid JSON: ${e.message}`); + process.exit(1); + } + }; + const upPkg = parseOrQuit(gitBuf(repo, `show ${head}:code/package.json`).toString("utf8"), "upstream code/package.json"); const localPath = path.join(root, "code/package.json"); const local = existsSync(localPath) - ? JSON.parse(readFileSync(localPath, "utf8")) + ? parseOrQuit(readFileSync(localPath, "utf8"), `${localPath} (fix the JSON, or delete the file and rerun to regenerate the scripts block)`) : { scripts: {} }; const upScripts = upPkg.scripts || {}; const missing = Object.entries(upScripts).filter(([k, v]) => (local.scripts || {})[k] !== v).map(([k]) => k); @@ -281,6 +289,13 @@ function installSkills(root, skillsDir) { const src = path.join(root, "skills", s); if (!existsSync(src)) continue; const dst = path.join(skillsDir, s); + // A mistyped --skills-dir must not delete unrelated same-named directories: + // only ever replace a directory that already looks like the skill. + if (existsSync(dst) && !existsSync(path.join(dst, "SKILL.md"))) { + console.error(`Refusing to overwrite ${dst}: it exists but holds no SKILL.md — that is not the skill directory.`); + console.error("Check --skills-dir; if the stray directory is yours, delete or rename it by hand, then rerun."); + process.exit(1); + } rmSync(dst, { recursive: true, force: true }); cpSync(src, dst, { recursive: true }); } diff --git a/code/tools/bocode-upgrade.test.mjs b/code/tools/bocode-upgrade.test.mjs index c876557..dcb8241 100644 --- a/code/tools/bocode-upgrade.test.mjs +++ b/code/tools/bocode-upgrade.test.mjs @@ -207,6 +207,29 @@ try { ok(run(TOOL, ["--verify", "--repo", upstream, "--keep", "book/guidelines/review-checklist.md"], adopter3).status === 0, "--keep records the kept file and passes"); } + // 8b. the skills-dir guard: a stray same-named directory is never deleted + { + const stray = path.join(tmp, "stray-skills"); + write(stray, "bocode/important.txt", "not a skill\n"); + const r = run(TOOL, ["--apply", "--repo", upstream, "--skills-dir", stray], adopter); + const out = r.stdout + r.stderr; + ok(r.status === 1 && out.includes("SKILL.md"), "guard refuses a --skills-dir holding a stray bocode/"); + ok(existsSync(path.join(stray, "bocode", "important.txt")), "the stray directory is left intact"); + } + + // 8c. malformed local package.json: readable error, no raw stack + { + const broken = path.join(tmp, "adopter-broken-pkg"); + gitInit(broken); + checkoutTree(upstream, HEAD, broken); + writeFileSync(path.join(broken, ".bocode-version"), STAMP + "\n"); + writeFileSync(path.join(broken, "code/package.json"), "{ oops\n"); + const r = run(TOOL, ["--check", "--repo", upstream], broken); + const out = r.stdout + r.stderr; + ok(r.status === 1 && out.includes("not valid JSON"), "malformed package.json fails with a readable error"); + ok(!/\n\s+at /.test(out), "no raw stack trace in the output"); + } + // 9. doctor: behind / current / stale skills, --remote against the local fixture { writeFileSync(path.join(adopter, ".bocode-version"), STAMP + "\n"); // temporarily behind From 198c908c5e2c8fba82ab155c18c32bce1f72ee35 Mon Sep 17 00:00:00 2001 From: Focus Date: Sat, 7 Nov 2026 20:21:16 +0800 Subject: [PATCH 3/8] =?UTF-8?q?=F0=9F=93=A6=20new=20(tools):=20consent-gat?= =?UTF-8?q?ed=20session-start=20sync=20check?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tier M (adds --ff-only refusal behavior and .bocode.json config reading, needs new tests; the consent model lands as ADR-013 — ask vs auto is a decision a reasonable person could make differently). The bocode skill now opens sessions with bocode:doctor -- --strict; .bocode.json (project-owned, optional) declares skillsDir/skillsTool so skill re-install needs no flag, and autoSync sets who pulls the sync trigger: ask (default) or auto. --apply --ff-only refuses BEFORE touching anything when any file needs a human decision (merged / diverged-delete / missing) — automation can never land half a sync, never interrupts a task, and human-decision conflicts always surface to the user. Verified: selftest green (50 assertions, twelve new), book:index zero warnings, book:release-check clean, commit subject validated. --- AGENTS.md | 2 +- CHANGELOG.md | 9 +++ README.ja.md | 6 +- README.md | 6 +- README.zh-CN.md | 6 +- UPGRADE.md | 13 +++- book/README.md | 3 +- .../ADR-013-consent-gated-auto-sync.md | 34 +++++++++++ code/tools/bocode-doctor.mjs | 14 +++-- code/tools/bocode-upgrade.mjs | 61 +++++++++++++++++-- code/tools/bocode-upgrade.test.mjs | 51 ++++++++++++++++ skills/bocode/SKILL.md | 3 +- 12 files changed, 183 insertions(+), 25 deletions(-) create mode 100644 book/docs/decisions/ADR-013-consent-gated-auto-sync.md diff --git a/AGENTS.md b/AGENTS.md index 3d4271d..fc7e932 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,7 @@ Git commits and branching strictly follow `book/guidelines/git-workflow.md`: eve ## Staying current -This workflow's template evolves, and the sync tooling ships with the project (template-owned, refreshes itself on every sync): `cd code && npm run bocode:doctor` reports staleness against the BoCode repository (https://github.com/Focus695/BoCode), and `npm run bocode:upgrade -- --check` lists every template-owned delta since the `.bocode-version` stamp. `UPGRADE.md` at the root is the playbook. **A sync is done when `--verify` exits 0 — never when an agent says so** — and the agent-side skills must be re-installed with it (`--skills-dir`). +This workflow's template evolves, and the sync tooling ships with the project (template-owned, refreshes itself on every sync): `cd code && npm run bocode:doctor` reports staleness against the BoCode repository (https://github.com/Focus695/BoCode), and `npm run bocode:upgrade -- --check` lists every template-owned delta since the `.bocode-version` stamp. `UPGRADE.md` at the root is the playbook. **A sync is done when `--verify` exits 0 — never when an agent says so** — and the agent-side skills must be re-installed with it (`--skills-dir`). Sessions open with a doctor check; an optional `.bocode.json` at the root tunes automation — `autoSync: "ask"` (default) offers the sync, `"auto"` lets the agent run the conflict-free subset via `--apply --ff-only`, and `skillsDir` / `skillsTool` declare where skills install. ## Document routing diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ae0b1a..65801f9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ Releases of the BoCode template itself. Adopting projects upgrade with the sync When adding an entry, also refresh the collapsed What's-new block near the top of the three READMEs (`README.md`, `README.zh-CN.md`, `README.ja.md`): newest title in the summary line, latest three titles as bullets. +## 2026-11-07 — session-start sync check, consent-gated auto-sync (ADR-013) + +Staleness detection was still a manual step. The `bocode` skill now opens every session with `bocode:doctor -- --strict`; an optional project-owned `.bocode.json` tunes automation — `skillsDir` / `skillsTool` declare where skills install (no more per-run flags), and `autoSync` sets who pulls the trigger: `ask` (default) offers the sync, `auto` lets the agent run the conflict-free subset itself. The new `--apply --ff-only` gate refuses **before touching anything** when any file needs a human decision (`merged` / `diverged-delete` / `missing`), so automation can never land half a sync; syncs never interrupt a task in progress. + +- Added: `book/docs/decisions/ADR-013-consent-gated-auto-sync.md` +- Changed: `code/tools/bocode-upgrade.mjs` (`--ff-only`; `.bocode.json` reading — skillsDir/skillsTool/autoSync, flag beats config, unknown values warn and degrade), `code/tools/bocode-doctor.mjs` (config wiring; behind-message names the autoSync policy), `code/tools/bocode-upgrade.test.mjs` (ff-only refusal leaves the tree untouched; ff-only pristine sync; config-driven skills re-install; malformed config degrades — 50 assertions), `skills/bocode/SKILL.md` (session-start step 0 + consent policy in the upgrade contract), `AGENTS.md` (Staying current gains the automation sentence), `UPGRADE.md` (`--ff-only` flag + Automation section), `README.md` / `README.zh-CN.md` / `README.ja.md` (FAQ sentence, What's-new) + +**Adopter action:** run your next sync as usual (`bocode:upgrade` picks all of this up itself — the tool upgrades the tool). Optionally create `.bocode.json` at your root (`{"skillsTool": "zcode", "autoSync": "ask"}` — or `"auto"` to let session agents run conflict-free syncs unattended) and re-copy the four skills so the session-start check text lands. Human-decision conflicts keep going to you either way; nothing about ADR-012's verify gate changes. + ## 2026-11-07 — upgrades become a tool-gated sync (ADR-012) The upgrade path was prose an agent could skim and overclaim (an adopter's agent declared ADR-011 "incorporated" while its new reference file was missing); the playbook was deleted on install; the agent-side skills never re-installed; the stamp was compared against nothing. Syncing is now tool-gated: `bocode-upgrade` diffs the stamp mechanically, `--verify` exits 0 only when every template-owned delta is applied, merged, or consciously kept, `bocode:doctor` reports staleness, and a single `MANIFEST` owns template-vs-project paths for both the sync and the release gate. diff --git a/README.ja.md b/README.ja.md index 09899e6..24729da 100644 --- a/README.ja.md +++ b/README.ja.md @@ -17,11 +17,11 @@ BoCode はリポジトリを二つに分けます——ソースを置く `code/` と、ドキュメントの流れとナレッジベースを置く `book/` です。両者は双方向に接続されます。今のソフトウェアが実際に書かれている方法、つまり人間と AI コーディングエージェントの共同開発を前提に設計されています。エージェントは速く、メモリもありますが、その記憶はエージェントだけのもの:人間には読めず、管理もできません。プロジェクトの知識がどこに置かれ、誰が読めるかが、速さが制御とともにあるか、制御のない速さになるかを決めます。
-最新情報 · 2026-11-07 — アップグレードがツールゲート式同期に(ADR-012) +最新情報 · 2026-11-07 — セッション開始時に更新確認、自動同期は同意制(ADR-013) +- **2026-11-07** — セッション開始時に更新確認、自動同期は同意制(ADR-013) - **2026-11-07** — アップグレードがツールゲート式同期に(ADR-012) - **2026-11-07** — 三言語の README を現行ゲートに合わせて更新 -- **2026-11-06** — ub-mode の精選プラクティスを追加(ADR-011) 履歴全文と移行手順は [CHANGELOG.md](CHANGELOG.md) @@ -208,7 +208,7 @@ cp -r skills/bocode skills/boscope skills/book-writeback skills/bowrite -What's new · 2026-11-07 — upgrades become a tool-gated sync (ADR-012) +What's new · 2026-11-07 — session-start sync check, consent-gated auto-sync (ADR-013) +- **2026-11-07** — session-start sync check, consent-gated auto-sync (ADR-013) - **2026-11-07** — upgrades become a tool-gated sync (ADR-012) - **2026-11-07** — trilingual readmes aligned with the current gates -- **2026-11-06** — selected ub-mode practices (ADR-011) Full history and adopter actions: [CHANGELOG.md](CHANGELOG.md) @@ -208,7 +208,7 @@ Requirements: `bash` and `node` for the scripts. No packages, no install step, n Yes — hand [ADOPT.md](ADOPT.md) to your AI agent. It's a step-by-step retrofit playbook written for agents: inventory, book skeleton, layout decision, doc migration, tooling, skills, and the first writeback. The manual path also works: copy `book/`, `skills/`, `scripts/`, `.githooks/`, `AGENTS.md`, and `code/tools/` in, merge your existing docs into the book, and run the index generator. **My project adopted an older BoCode — how do we upgrade?** -The sync tooling ships with your project: `cd code && npm run bocode:doctor` reports staleness, `npm run bocode:upgrade -- --check` lists every template-owned change with its disposition, and `--apply` refreshes pristine files, verifies from disk, and writes a report into your `book/changelogs/`. The sync is done when `--verify` exits 0 — not when the agent says so. [UPGRADE.md](UPGRADE.md) is the playbook; [CHANGELOG.md](CHANGELOG.md) lists every change since your stamp. +The sync tooling ships with your project: `cd code && npm run bocode:doctor` reports staleness, `npm run bocode:upgrade -- --check` lists every template-owned change with its disposition, and `--apply` refreshes pristine files, verifies from disk, and writes a report into your `book/changelogs/`. The sync is done when `--verify` exits 0 — not when the agent says so. Sessions check staleness automatically; an optional `.bocode.json` (`autoSync`, `skillsTool`) tunes how much syncs themselves. [UPGRADE.md](UPGRADE.md) is the playbook; [CHANGELOG.md](CHANGELOG.md) lists every change since your stamp. **Does it lock me into a language or stack?** No. The book is Markdown; the scripts are plain Node with zero dependencies. Your `code/` can hold anything — the template's own `code/` contains only the tooling. diff --git a/README.zh-CN.md b/README.zh-CN.md index dd7a5c5..c59a891 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -17,11 +17,11 @@ BoCode 把仓库分成两半:`code/` 放源代码,`book/` 放文档和知识库,两边互相驱动。它是为现在最常见的开发方式设计的:人和 AI agent 一起写代码。agent 快,也有记忆,可记忆只归它自己:人读不懂、管不了。项目知识放在哪里、给谁读,决定了开发是又快又稳,还是快得让人心里没底。
-最近更新 · 2026-11-07 — 升级链路变成工具把关的同步(ADR-012) +最近更新 · 2026-11-07 — 会话开场检测更新,自动同步需授权(ADR-013) +- **2026-11-07** — 会话开场检测更新,自动同步需授权(ADR-013) - **2026-11-07** — 升级链路变成工具把关的同步(ADR-012) - **2026-11-07** — 三语 README 与现行关卡对齐 -- **2026-11-06** — 精选 ub-mode 实践(ADR-011) 完整历史与采用方操作见 [CHANGELOG.md](CHANGELOG.md) @@ -208,7 +208,7 @@ cp -r skills/bocode skills/boscope skills/book-writeback skills/bowrite ` (a local BoCode clone instead of cloning GitHub), `--skills-dir ` (check or re-install the four skills), `--stamp ` (set the baseline by hand), and `--keep ` (declare a template path consciously kept local). +All three take `--repo ` (a local BoCode clone instead of cloning GitHub), `--skills-dir ` (check or re-install the four skills), `--stamp ` (set the baseline by hand), `--keep ` (declare a template path consciously kept local), and `--apply --ff-only` (the automation-safe subset: refuse **before touching anything** when any file needs a human decision — `merged`, `diverged-delete`, `missing`). + +## Automation (session-start check) + +The `bocode` skill runs `bocode:doctor -- --strict` when a session opens. An optional `.bocode.json` at the project root (project-owned, never touched by syncs) tunes it: + +```json +{ "skillsTool": "zcode", "autoSync": "ask" } +``` + +- `skillsDir` (relative or `~/...`) or `skillsTool` (`zcode` | `claude`) — where the four skills install, so re-install needs no flag +- `autoSync` — `"ask"` (default): the agent offers the sync, the user decides; `"auto"`: the agent runs the conflict-free sync itself (`--apply --ff-only`) and reports. Human-decision conflicts always surface to the user, and a sync never interrupts a task in progress. ## What is template-owned vs project-owned diff --git a/book/README.md b/book/README.md index c6478e1..e117b38 100644 --- a/book/README.md +++ b/book/README.md @@ -61,6 +61,7 @@ description: Master index of the book — the map of every document. Regenerate - [ADR-010-archive-by-status-flip-not-by-moving-files.md](docs/decisions/ADR-010-archive-by-status-flip-not-by-moving-files.md) — task and issue entries archive by flipping a frontmatter status and regenerating the index — files never move, the index regroups with open entries first - [ADR-011-distill-selected-ub-mode-practices.md](docs/decisions/ADR-011-distill-selected-ub-mode-practices.md) — Selected ub-mode practices supplement project rules for modeling, calculations, testing, defects, terminology, and optional automation - [ADR-012-upgrade-sync-becomes-a-tool-gate.md](docs/decisions/ADR-012-upgrade-sync-becomes-a-tool-gate.md) — The upgrade path ships as tooling — bocode-upgrade check/apply/verify diffs the stamp mechanically, a single manifest owns template-vs-project paths, doctor reports staleness, and UPGRADE.md self-refreshes; prose-only guidance is rejected +- [ADR-013-consent-gated-auto-sync.md](docs/decisions/ADR-013-consent-gated-auto-sync.md) — Sessions open with a doctor staleness check; syncs stay consent-gated — ask by default, auto only for the conflict-free --ff-only subset and only via explicit project opt-in; skills paths are declared, never guessed - [README.md](docs/decisions/README.md) — How to write an ADR here — sections, naming, numbering, and when a decision needs a record ### guidelines/ @@ -82,4 +83,4 @@ description: Master index of the book — the map of every document. Regenerate - [README.md](plans/README.md) — Plans directory usage — implementation plans land here after Phase 2 approval, with naming and the plan template - + diff --git a/book/docs/decisions/ADR-013-consent-gated-auto-sync.md b/book/docs/decisions/ADR-013-consent-gated-auto-sync.md new file mode 100644 index 0000000..b638424 --- /dev/null +++ b/book/docs/decisions/ADR-013-consent-gated-auto-sync.md @@ -0,0 +1,34 @@ +--- +description: Sessions open with a doctor staleness check; syncs stay consent-gated — ask by default, auto only for the conflict-free --ff-only subset and only via explicit project opt-in; skills paths are declared, never guessed +--- + +# ADR-013: Consent-gated automatic sync + +## Status + +Accepted — 2026-11-07. Self-tested in `code/tools/bocode-upgrade.test.mjs` (ff-only refusal leaves the tree untouched; config-driven skills re-install; malformed config degrades with warnings). + +## Context + +ADR-012 made syncs verifiable but left them initiated by humans or by an agent that happened to be told. The wish: when the BoCode workflow triggers in an adopting project, detect staleness automatically and update without anyone asking. Three forces shape the answer: + +- **Safety by construction** — `--apply` already only replaces files that still match the stamp byte-for-byte, so local edits cannot be lost; but `merged` / `diverged-delete` / `missing` states need a human judgment no automation can supply. +- **Humans steer** — a sync that silently rewrites the workflow an agent is *currently* running is scope drift at best; the user's in-progress task outranks template freshness. +- **The chicken-and-egg** — automation lives in the tooling and skill text; an adopter gets it only after one manual bootstrap sync (ADR-012), and a skill re-installed mid-session takes effect next session. + +## Decision + +- **Detection is automatic, read-only, and cheap**: the `bocode` skill's session-start step runs `bocode:doctor -- --strict` (one `git ls-remote`); offline degrades silently to "unknown". +- **Syncs are consent-gated.** `.bocode.json` (optional, project-owned, never touched by syncs) sets `autoSync`: `"ask"` (default) — the agent offers, the user decides; `"auto"` — the agent applies only the conflict-free subset, via a new hard gate. +- **`--apply --ff-only`** refuses *before touching anything* when any changed template-owned file is `merged`, `diverged-delete`, or `missing` — automation can never land half a sync. Everything else (stale copies, new files, safe deletions, script merges) proceeds and verifies as usual. +- **Skills paths are declared, not guessed**: `skillsDir` (relative or `~/`) or `skillsTool` (`zcode`, `claude`) in `.bocode.json`; an explicit `--skills-dir` flag always wins. Unknown values warn and fall back — a broken config never breaks the workflow. +- **Timing**: syncs happen at session start, never mid-task; the skill contract says so explicitly. + +Rejected: fully automatic syncs including merges (impossible by principle — merges are a keep-whose choice); auto-detecting the agent's skills directory by probing the filesystem (wrong-machine guesses are worse than one declared line); caching the upstream check (one ls-remote per session is cheap; add a cache only if it ever measurably annoys). + +## Consequences + +- A conflict-free upgrade now lands with zero human effort on opted-in projects; every other case degrades to a one-question ask with the disposition list attached +- The consent model lives in three aligned places: the tool flag (hard gate), the skill contract (behavior), `.bocode.json` (policy) — the exit code stays the only completion proof (ADR-012 unchanged) +- Adopters who skip `.bocode.json` keep ADR-012 behavior exactly; the file is per-project and portable (`skillsTool` over absolute paths) +- A skill re-installed by an auto-sync affects the *next* session — the current one keeps its loaded text; tools and documents take effect immediately diff --git a/code/tools/bocode-doctor.mjs b/code/tools/bocode-doctor.mjs index 94bcd0e..7ec9155 100644 --- a/code/tools/bocode-doctor.mjs +++ b/code/tools/bocode-doctor.mjs @@ -11,7 +11,7 @@ import { execSync } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; -import { DEFAULT_REMOTE, adopterRoot, skillsStates } from "./bocode-upgrade.mjs"; +import { DEFAULT_REMOTE, adopterRoot, readConfig, skillsStates } from "./bocode-upgrade.mjs"; function parseArgs(argv) { const flags = {}; @@ -28,6 +28,8 @@ function parseArgs(argv) { const flags = parseArgs(process.argv.slice(2)); const root = adopterRoot(); const remote = flags.remote || DEFAULT_REMOTE; +const cfg = readConfig(root); +const skillsDir = flags.skillsDir || cfg.skillsDir; // explicit flag beats .bocode.json let hardFail = false; // 1. the upgrade tool itself (pre-ADR-012 adopters lack it) @@ -64,7 +66,7 @@ if (stamp) { console.log("ok up to date with upstream HEAD"); } else { console.log(`FAIL behind upstream: local ${stamp.slice(0, 7)}, upstream ${upstream.slice(0, 7)}`); - console.log(" run: cd code && npm run bocode:upgrade -- --check"); + console.log(` run: cd code && npm run bocode:upgrade -- --check (autoSync=${cfg.autoSync}${cfg.autoSync === "auto" ? " — the agent may apply the conflict-free sync via --apply --ff-only" : " — ask the user before syncing"})`); hardFail = true; } } catch { @@ -73,21 +75,21 @@ if (stamp) { } // 4. skills freshness in the agent's directory -if (flags.skillsDir) { - const states = skillsStates(root, flags.skillsDir); +if (skillsDir) { + const states = skillsStates(root, skillsDir); for (const [name, state] of Object.entries(states)) { if (state === "current") { console.log(`ok skills/${name} current`); } else if (state === "no-source") { console.log(`WARN skills/${name} missing in this repo — nothing to install from`); } else { - console.log(`FAIL skills/${name} ${state} in ${flags.skillsDir}`); + console.log(`FAIL skills/${name} ${state} in ${skillsDir}`); console.log(" run: cd code && npm run bocode:upgrade -- --apply --skills-dir "); hardFail = true; } } } else { - console.log("WARN skills not checked — pass --skills-dir to compare the four installed skills"); + console.log("WARN skills not checked — pass --skills-dir , or set skillsDir / skillsTool in .bocode.json"); } if (hardFail) { diff --git a/code/tools/bocode-upgrade.mjs b/code/tools/bocode-upgrade.mjs index d695f9a..1a4eb69 100644 --- a/code/tools/bocode-upgrade.mjs +++ b/code/tools/bocode-upgrade.mjs @@ -98,6 +98,7 @@ function parseArgs(argv) { else if (a === "--skills-dir") flags.skillsDir = argv[++i]; else if (a === "--stamp") flags.stamp = argv[++i]; else if (a === "--keep") flags.keep.push(argv[++i]); + else if (a === "--ff-only") flags.ffOnly = true; else { console.error(`Unknown argument: ${a}`); usage(2); } } if (!flags.mode) usage(2); @@ -106,7 +107,9 @@ function parseArgs(argv) { function usage(code) { console.error("Usage: bocode-upgrade.mjs --check|--apply|--verify [--repo ] [--remote ]"); - console.error(" [--skills-dir ] [--stamp ] [--keep ] [--keep ...]"); + console.error(" [--skills-dir ] [--stamp ] [--ff-only] [--keep ...]"); + console.error(" --ff-only: refuse the sync BEFORE touching anything when any file needs a human"); + console.error(" decision (merged / diverged-delete / missing) — the automation-safe subset."); process.exit(code); } @@ -271,6 +274,41 @@ function treeEq(a, b) { return filesA.every((f) => bufEq(readFileSync(path.join(a, f)), readFileSync(path.join(b, f)))); } +// ---------- project config (.bocode.json, optional, project-owned) ---------- + +// Known agent tools → default skills directory. A project declares one of +// these instead of a machine-specific absolute path. +const SKILL_TOOL_DIRS = { + zcode: () => path.join(os.homedir(), ".zcode", "skills"), + claude: () => path.join(os.homedir(), ".claude", "skills"), +}; + +export function readConfig(root) { + const file = path.join(root, ".bocode.json"); + const cfg = { skillsDir: null, autoSync: "ask" }; + if (!existsSync(file)) return cfg; + let parsed; + try { + parsed = JSON.parse(readFileSync(file, "utf8")); + } catch (e) { + console.warn(`.bocode.json is not valid JSON (${e.message}) — ignored, defaults apply`); + return cfg; + } + if (parsed.autoSync === "ask" || parsed.autoSync === "auto") cfg.autoSync = parsed.autoSync; + else if (parsed.autoSync !== undefined) console.warn(`.bocode.json: unknown autoSync "${parsed.autoSync}" — using "ask"`); + if (typeof parsed.skillsDir === "string" && parsed.skillsDir.length) { + const dir = parsed.skillsDir.startsWith("~/") + ? path.join(os.homedir(), parsed.skillsDir.slice(2)) + : path.resolve(root, parsed.skillsDir); + cfg.skillsDir = dir; + } else if (typeof parsed.skillsTool === "string" && SKILL_TOOL_DIRS[parsed.skillsTool]) { + cfg.skillsDir = SKILL_TOOL_DIRS[parsed.skillsTool](); + } else if (parsed.skillsTool !== undefined) { + console.warn(`.bocode.json: unknown skillsTool "${parsed.skillsTool}" — skills not configured`); + } + return cfg; +} + export function skillsStates(root, skillsDir) { const states = {}; for (const s of SKILL_DIRS) { @@ -350,6 +388,8 @@ function main() { const flags = parseArgs(process.argv.slice(2)); const root = adopterRoot(); const remote = flags.remote || DEFAULT_REMOTE; +const cfg = readConfig(root); +const skillsDir = flags.skillsDir || cfg.skillsDir; // explicit flag beats .bocode.json let tmpDir = null; let repo = flags.repo; @@ -375,7 +415,7 @@ try { process.exit(1); } - const doSkills = () => (flags.skillsDir ? skillsStates(root, flags.skillsDir) : null); + const doSkills = () => (skillsDir ? skillsStates(root, skillsDir) : null); const printSkills = (states) => { if (!states) return; for (const [name, state] of Object.entries(states)) console.log(` skills/${name}: ${state}`); @@ -383,12 +423,12 @@ try { if (stamp === head) { console.log(`Up to date: .bocode-version == upstream HEAD (${head.slice(0, 7)}). Nothing to do.`); - if (flags.skillsDir) { + if (skillsDir) { const states = doSkills(); printSkills(states); if (Object.values(states).some((s) => s === "stale" || s === "missing")) { if (flags.mode === "apply") { - installSkills(root, flags.skillsDir); + installSkills(root, skillsDir); console.log("Skills re-installed into the agent skills directory."); } else { console.error("Skills are stale — rerun with --apply (or copy the four skills by hand)."); @@ -419,8 +459,17 @@ try { } if (flags.mode === "apply") { + if (flags.ffOnly) { + const human = items.filter((it) => ["merged", "diverged-delete", "missing"].includes(it.state)); + if (human.length) { + console.error(`--ff-only: not fast-forwardable — ${human.length} item(s) need a human decision:`); + human.forEach((it) => console.error(` ${it.state.padEnd(15)} ${it.path}`)); + console.error("Nothing was touched. Merge or --keep per UPGRADE.md, then rerun."); + process.exit(1); + } + } const actions = applyItems(items, root); - if (flags.skillsDir) installSkills(root, flags.skillsDir); + if (skillsDir) installSkills(root, skillsDir); actions.forEach((a) => console.log(a)); // Recompute from disk: the gate trusts the tree, not the plan. @@ -434,7 +483,7 @@ try { } writeFileSync(path.join(root, ".bocode-version"), head + "\n"); - const report = writeReport(root, stamp, head, items2, flags.skillsDir ? "re-installed via --skills-dir" : "not checked (no --skills-dir given)"); + const report = writeReport(root, stamp, head, items2, skillsDir ? `re-installed into ${skillsDir}` : "not checked (no --skills-dir given, none configured)"); console.log(`Verify green. Stamp → ${head.slice(0, 7)}. Report: ${path.relative(root, report)}`); const index = runIndex(root); diff --git a/code/tools/bocode-upgrade.test.mjs b/code/tools/bocode-upgrade.test.mjs index dcb8241..cada7e9 100644 --- a/code/tools/bocode-upgrade.test.mjs +++ b/code/tools/bocode-upgrade.test.mjs @@ -230,6 +230,57 @@ try { ok(!/\n\s+at /.test(out), "no raw stack trace in the output"); } + // 8d. --ff-only refuses before touching anything when a human decision is pending + { + const ff = path.join(tmp, "adopter-ff"); + gitInit(ff); + checkoutTree(upstream, STAMP, ff); + writeFileSync(path.join(ff, ".bocode-version"), STAMP + "\n"); + write(ff, "book/guidelines/writing-style.md", "style v1 + local edit\n"); // forces a merged state + const r = run(TOOL, ["--apply", "--repo", upstream, "--ff-only"], ff); + const out = r.stdout + r.stderr; + ok(r.status === 1 && out.includes("not fast-forwardable"), "ff-only refuses when a merge is pending"); + ok(out.includes("writing-style.md"), "ff-only names the blocking file"); + ok(readFileSync(path.join(ff, "book/guidelines/workflow.md"), "utf8") === "workflow v1\n", "ff-only refusal left the tree untouched"); + ok(!existsSync(path.join(ff, "skills/boscope/references/automation-tools.md")), "ff-only refusal installed nothing"); + ok(readFileSync(path.join(ff, ".bocode-version"), "utf8").trim() === STAMP, "ff-only refusal left the stamp unchanged"); + } + + // 8e. --ff-only sails through a pristine adopter + { + const ff = path.join(tmp, "adopter-ff2"); + gitInit(ff); + checkoutTree(upstream, STAMP, ff); + writeFileSync(path.join(ff, ".bocode-version"), STAMP + "\n"); + const r = run(TOOL, ["--apply", "--repo", upstream, "--ff-only"], ff); + ok(r.status === 0, "ff-only apply exits 0 on a pristine adopter"); + ok(readFileSync(path.join(ff, "book/guidelines/workflow.md"), "utf8") === "workflow v2\n", "ff-only apply copied the delta"); + ok(readFileSync(path.join(ff, ".bocode-version"), "utf8").trim() === HEAD, "ff-only apply advanced the stamp"); + } + + // 8f. .bocode.json drives skills re-install without a --skills-dir flag + { + const c = path.join(tmp, "adopter-cfg"); + gitInit(c); + checkoutTree(upstream, HEAD, c); + writeFileSync(path.join(c, ".bocode-version"), HEAD + "\n"); + write(c, ".bocode.json", JSON.stringify({ skillsDir: "local-skills", autoSync: "auto" }, null, 2) + "\n"); + write(c, "local-skills/boscope/SKILL.md", "boscope v1\n"); // stale on purpose + const r = run(TOOL, ["--apply", "--repo", upstream], c); + ok(r.status === 0, "config-only apply exits 0"); + ok(readFileSync(path.join(c, "local-skills/boscope/SKILL.md"), "utf8") === "boscope v2\n", "skillsDir from .bocode.json was used for re-install"); + } + + // 8g. malformed config values degrade with a warning, never crash + { + const c = path.join(tmp, "adopter-cfg"); + write(c, ".bocode.json", '{"autoSync": "yolo", "skillsTool": "unknown-tool"}\n'); + const d = run(DOCTOR, ["--remote", upstream], c); + const out = d.stdout + d.stderr; + ok(d.status === 0 && out.includes('unknown autoSync "yolo"'), "unknown autoSync warns and falls back to ask"); + ok(out.includes('unknown skillsTool "unknown-tool"'), "unknown skillsTool warns and is ignored"); + } + // 9. doctor: behind / current / stale skills, --remote against the local fixture { writeFileSync(path.join(adopter, ".bocode-version"), STAMP + "\n"); // temporarily behind diff --git a/skills/bocode/SKILL.md b/skills/bocode/SKILL.md index 029d53e..9ca5d95 100644 --- a/skills/bocode/SKILL.md +++ b/skills/bocode/SKILL.md @@ -26,6 +26,7 @@ book/ ## Session discipline **Starting work:** +0. Sync check: `cd code && npm run bocode:doctor -- --strict` — clean or offline → continue; behind upstream → the upgrade contract below says what to do (ask the user, or run the conflict-free sync yourself when `.bocode.json` opts in). Never interrupt a task in progress for it. 1. Read `book/README.md` for the full map. 2. Read `AGENTS.md` for the repository's rules and hard constraints. 3. Before coding anything: check `book/guidelines/` for the baseline, and search `book/notes/learn/` for related experience. @@ -38,7 +39,7 @@ book/ 1. **Index contract**: every new book document starts with frontmatter `description` — one plain-language line about the *content* (not the genre). After any book change, run `cd code && npm run book:index`; the build fails on a missing description, and that's the point. 2. **Record-only contract**: problems found during review or wrap-up are recorded to `notes/issue/`, never fixed in passing. A recorded problem becomes a task; fixing is separate work. -3. **Upgrade contract**: the template evolves — run `cd code && npm run bocode:doctor` when staleness matters (it compares the `.bocode-version` stamp with the BoCode repository, https://github.com/Focus695/BoCode). A sync follows `UPGRADE.md` at the project root: `npm run bocode:upgrade -- --check` → merge what's flagged → `--apply` (pass `--skills-dir` so the agent skills re-install too). The sync is done only when `--verify` exits green — never when you feel done. +3. **Upgrade contract**: the template evolves — run `cd code && npm run bocode:doctor -- --strict` at session start (it compares the `.bocode-version` stamp with the BoCode repository, https://github.com/Focus695/BoCode). Behind → sync per `UPGRADE.md`: `--check` → merge what's flagged → `--apply` (pass `--skills-dir`, or declare it once in `.bocode.json` so skills re-install automatically) → done only when `--verify` exits green, never when you feel done. `.bocode.json`'s `autoSync` sets who pulls the trigger: `ask` (default) — offer, the user decides; `auto` — you run the conflict-free subset yourself (`--apply --ff-only`, which refuses before touching anything if any file needs a human decision) and report the result. Human-decision conflicts (`merged` / `diverged-delete` / `missing`) always go to the user. ## What not to do From ee4352f8fff66be041be963c35dfd8df1e08ea9b Mon Sep 17 00:00:00 2001 From: Focus Date: Sun, 15 Nov 2026 16:27:12 +0800 Subject: [PATCH 4/8] =?UTF-8?q?=F0=9F=93=96=20docs=20(workflow):=20weave?= =?UTF-8?q?=20openspec=20scenarios=20and=20deltas=20into=20the=20brief?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tier M (guideline change reaching adopters via the sync, but a single functional area — docs only, no code, no new tooling; the distillation decision lands as ADR-014). Learned from OpenSpec (Fission-AI, MIT): its progressive rigor, behavior-first boundary, and brownfield-first stance converge with what this baseline already does (ADR-008/005/006) — recorded as validation, not copied. Two practices distilled: Step-0 acceptance criteria become one-line GIVEN/WHEN/THEN scenarios with Phase 4's coverage running down that list first, and L-tier plans state acceptance as a behavior delta (ADDED/MODIFIED/REMOVED). The living- specs layer, mandatory proposal approval, and OpenSpec's tooling are deliberately not copied, reasons in the ADR. boscope's brief template and the session-side skill wording are aligned with workflow.md. Verified: book:index zero warnings (29 documents), book:release-check clean, commit subject validated. --- CHANGELOG.md | 9 +++++ README.ja.md | 4 +- README.md | 4 +- README.zh-CN.md | 4 +- book/README.md | 3 +- ...4-distill-openspec-scenarios-and-deltas.md | 38 +++++++++++++++++++ book/guidelines/workflow.md | 4 +- book/plans/README.md | 4 +- skills/boscope/SKILL.md | 7 ++-- 9 files changed, 64 insertions(+), 13 deletions(-) create mode 100644 book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 65801f9..ac6e8d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,15 @@ Releases of the BoCode template itself. Adopting projects upgrade with the sync When adding an entry, also refresh the collapsed What's-new block near the top of the three READMEs (`README.md`, `README.zh-CN.md`, `README.ja.md`): newest title in the summary line, latest three titles as bullets. +## 2026-11-15 — scenario acceptance criteria and plan behavior deltas (ADR-014) + +Distilled from [OpenSpec](https://github.com/Fission-AI/OpenSpec) (Fission-AI, MIT): acceptance criteria in the Step-0 brief are now written as one-line GIVEN/WHEN/THEN scenarios — observable outcomes, normal and error paths — and Phase 4's coverage starts by running down that list; L-tier plans state acceptance as a behavior delta (ADDED/MODIFIED/REMOVED relative to today), so review sees what changes in behavior, not only what gets built. The convergences (tiered rigor, behavior-first boundary, brownfield-first) are recorded in the ADR as validation of decisions the baseline had already made; the living-specs layer, mandatory proposal approval, and OpenSpec's tooling are deliberately not copied, with reasons in the ADR. + +- Added: `book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md` +- Changed: `book/guidelines/workflow.md` (Step-0 scenario sentence; Phase-4 coverage starts with the brief's scenarios), `book/plans/README.md` (acceptance scenarios in the brief slot; L-tier behavior-delta sentence), `skills/boscope/SKILL.md` (brief template and Phase-4 coverage wording), `README.md` / `README.zh-CN.md` / `README.ja.md` (What's-new) + +**Adopter action:** run your usual sync (`bocode:upgrade -- --apply`, then `--verify`). If you keep a session-side copy of the structured-feature-implementation skill, add the scenario line to its brief template yourself — session skills are yours, not template-owned. + ## 2026-11-07 — session-start sync check, consent-gated auto-sync (ADR-013) Staleness detection was still a manual step. The `bocode` skill now opens every session with `bocode:doctor -- --strict`; an optional project-owned `.bocode.json` tunes automation — `skillsDir` / `skillsTool` declare where skills install (no more per-run flags), and `autoSync` sets who pulls the trigger: `ask` (default) offers the sync, `auto` lets the agent run the conflict-free subset itself. The new `--apply --ff-only` gate refuses **before touching anything** when any file needs a human decision (`merged` / `diverged-delete` / `missing`), so automation can never land half a sync; syncs never interrupt a task in progress. diff --git a/README.ja.md b/README.ja.md index 24729da..11f9752 100644 --- a/README.ja.md +++ b/README.ja.md @@ -17,11 +17,11 @@ BoCode はリポジトリを二つに分けます——ソースを置く `code/` と、ドキュメントの流れとナレッジベースを置く `book/` です。両者は双方向に接続されます。今のソフトウェアが実際に書かれている方法、つまり人間と AI コーディングエージェントの共同開発を前提に設計されています。エージェントは速く、メモリもありますが、その記憶はエージェントだけのもの:人間には読めず、管理もできません。プロジェクトの知識がどこに置かれ、誰が読めるかが、速さが制御とともにあるか、制御のない速さになるかを決めます。
-最新情報 · 2026-11-07 — セッション開始時に更新確認、自動同期は同意制(ADR-013) +最新情報 · 2026-11-15 — シナリオ型受け入れ基準とプランの挙動デルタ(ADR-014) +- **2026-11-15** — シナリオ型受け入れ基準とプランの挙動デルタ(ADR-014) - **2026-11-07** — セッション開始時に更新確認、自動同期は同意制(ADR-013) - **2026-11-07** — アップグレードがツールゲート式同期に(ADR-012) -- **2026-11-07** — 三言語の README を現行ゲートに合わせて更新 履歴全文と移行手順は [CHANGELOG.md](CHANGELOG.md) diff --git a/README.md b/README.md index eab6504..ab35ed2 100644 --- a/README.md +++ b/README.md @@ -17,11 +17,11 @@ BoCode gives a repository two halves — `code/` for the source, `book/` for the documentation stream and knowledge base — wired together in both directions. It is built for the way software is written now: a human and AI coding agents together. Agents are fast and have memory now — but that memory serves the agent alone: unreadable to humans, unmanageable. Where a project's knowledge lives, and who can read it, decides whether speed comes with control or without it.
-What's new · 2026-11-07 — session-start sync check, consent-gated auto-sync (ADR-013) +What's new · 2026-11-15 — scenario acceptance criteria and plan behavior deltas (ADR-014) +- **2026-11-15** — scenario acceptance criteria and plan behavior deltas (ADR-014) - **2026-11-07** — session-start sync check, consent-gated auto-sync (ADR-013) - **2026-11-07** — upgrades become a tool-gated sync (ADR-012) -- **2026-11-07** — trilingual readmes aligned with the current gates Full history and adopter actions: [CHANGELOG.md](CHANGELOG.md) diff --git a/README.zh-CN.md b/README.zh-CN.md index c59a891..90f0c6f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -17,11 +17,11 @@ BoCode 把仓库分成两半:`code/` 放源代码,`book/` 放文档和知识库,两边互相驱动。它是为现在最常见的开发方式设计的:人和 AI agent 一起写代码。agent 快,也有记忆,可记忆只归它自己:人读不懂、管不了。项目知识放在哪里、给谁读,决定了开发是又快又稳,还是快得让人心里没底。
-最近更新 · 2026-11-07 — 会话开场检测更新,自动同步需授权(ADR-013) +最近更新 · 2026-11-15 — 场景式验收标准与计划行为增量(ADR-014) +- **2026-11-15** — 场景式验收标准与计划行为增量(ADR-014) - **2026-11-07** — 会话开场检测更新,自动同步需授权(ADR-013) - **2026-11-07** — 升级链路变成工具把关的同步(ADR-012) -- **2026-11-07** — 三语 README 与现行关卡对齐 完整历史与采用方操作见 [CHANGELOG.md](CHANGELOG.md) diff --git a/book/README.md b/book/README.md index e117b38..e26751f 100644 --- a/book/README.md +++ b/book/README.md @@ -62,6 +62,7 @@ description: Master index of the book — the map of every document. Regenerate - [ADR-011-distill-selected-ub-mode-practices.md](docs/decisions/ADR-011-distill-selected-ub-mode-practices.md) — Selected ub-mode practices supplement project rules for modeling, calculations, testing, defects, terminology, and optional automation - [ADR-012-upgrade-sync-becomes-a-tool-gate.md](docs/decisions/ADR-012-upgrade-sync-becomes-a-tool-gate.md) — The upgrade path ships as tooling — bocode-upgrade check/apply/verify diffs the stamp mechanically, a single manifest owns template-vs-project paths, doctor reports staleness, and UPGRADE.md self-refreshes; prose-only guidance is rejected - [ADR-013-consent-gated-auto-sync.md](docs/decisions/ADR-013-consent-gated-auto-sync.md) — Sessions open with a doctor staleness check; syncs stay consent-gated — ask by default, auto only for the conflict-free --ff-only subset and only via explicit project opt-in; skills paths are declared, never guessed +- [ADR-014-distill-openspec-scenarios-and-deltas.md](docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md) — Two OpenSpec practices distilled into the brief and L-tier plans — scenario acceptance criteria and behavior deltas — with the convergences validated and the parts deliberately not copied - [README.md](docs/decisions/README.md) — How to write an ADR here — sections, naming, numbering, and when a decision needs a record ### guidelines/ @@ -83,4 +84,4 @@ description: Master index of the book — the map of every document. Regenerate - [README.md](plans/README.md) — Plans directory usage — implementation plans land here after Phase 2 approval, with naming and the plan template - + diff --git a/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md b/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md new file mode 100644 index 0000000..442b7b9 --- /dev/null +++ b/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md @@ -0,0 +1,38 @@ +--- +description: Two OpenSpec practices distilled into the brief and L-tier plans — scenario acceptance criteria and behavior deltas — with the convergences validated and the parts deliberately not copied +--- + +# ADR-014: Distill OpenSpec's scenarios and deltas + +## Status + +Accepted — 2026-11-15. Ships with the template. + +## Context + +[OpenSpec](https://github.com/Fission-AI/OpenSpec) (Fission-AI, MIT) is a spec-driven development framework: requirements live in versioned Markdown instead of chat history. A change is a proposal folder — why/what, delta specs, design, tasks — that a human reviews before implementation; on archive, the deltas merge into per-capability living specs that serve as the system's current behavioral truth. + +Studying it against this workflow found more convergence than gap. Its progressive rigor (lightweight by default, rigor scaling with risk) is the S/M/L tiering (ADR-008). Its behavior-first boundary — specs capture observable behavior, implementation detail goes to design — is the Step-0 WHAT / Phase-2 HOW split (ADR-005, ADR-006). Its brownfield-first stance, specs written as you build rather than generated upfront, is how the book already compounds. Its explore phase is Phase 1's "no code changed" gate. The convergence validates the baseline; it is not something to copy. + +Two practices are worth distilling. First, OpenSpec writes acceptance as scenarios — a requirement with a SHALL line, scenario blocks in GIVEN/WHEN/THEN — so every criterion is checkable before code exists; our brief's requirement slot is free text, and Phase 4's gate has no explicit upstream list to run down. Second, OpenSpec's proposals store only deltas — ADDED/MODIFIED/REMOVED requirements against current behavior — which makes review sharp about what changes, not just what gets built; L-tier plans can state acceptance the same way without owning a permanent spec tree. + +## Decision + +Distill the two practices; take nothing else. + +- **Scenario acceptance criteria.** In the Step-0 brief (M/L), the requirement's acceptance criteria are written as one-line scenarios — GIVEN a starting state, WHEN the user or system acts, THEN the observable outcome — covering the normal path and the error paths. Phase 4's coverage starts by running down the brief's scenarios. A criterion that cannot be phrased as an observable outcome is a design question for Phase 2, not a requirement. +- **Behavior deltas in L-tier plans.** An L plan states acceptance as a delta — which observable behaviors the system ADDED, MODIFIED, or REMOVED relative to current behavior — so review sees what changes in behavior, not only what gets built. + +Not copied, with reasons: + +- **The living-specs layer** (`openspec/specs/` as permanent behavioral truth): its deltas merge mechanically at archive time via their tooling; maintained by hand it rots, and BoCode already has its executable behavior truth — code and tests. A second truth source would break the routing table's one job per document. +- **Mandatory human approval of the proposal before code**: a distrust gate under ADR-003's taxonomy. This workflow stops for the user on real gaps only; Step 0 plus the Phase-2 stop rule already carry the alignment OpenSpec gets from approval. +- **Replacing the hard gates with OpenSpec's fluid no-gates loop**: the gates are the product here (ADR-003); OpenSpec's looseness is a different bet, not a missing feature. +- **The CLI, directory layout, and skills tooling**: BoCode ships as book plus scripts and is agent-agnostic through the book; the value was the methodology, not the scaffolding. + +## Consequences + +- The brief's requirement slot and Phase 4's gate close a loop explicitly: scenarios written before code become the first test list. +- L plans gain a delta view of acceptance at no standing maintenance cost — the delta lives in the plan, which already records intent. +- No new directory, tool, phase, gate, or truth source. The weaves land in `guidelines/workflow.md`, `plans/README.md`, and the boscope skill's brief template; the session-side structured-feature-implementation skill is aligned with the same wording. +- Credit where due: the two practices and the format inspiration come from OpenSpec (MIT, Fission-AI). The convergences above are recorded as validation of decisions this repository had already made on its own. diff --git a/book/guidelines/workflow.md b/book/guidelines/workflow.md index 30a5353..9af31e2 100644 --- a/book/guidelines/workflow.md +++ b/book/guidelines/workflow.md @@ -20,7 +20,7 @@ The ub-mode-derived practices below are supplementary and apply only where usefu | Phase 5 | Code review | Review findings | Record only — no fixes | | Phase 6 | Wrap-up | Docs, learnings, issues | Record only — no fixes | -Step 0 comes before any code (M and L). Fill the brief: background, scope (what it affects, what it explicitly does **not** affect, and the boundaries), and the requirement itself. An empty "does not affect" list is the number-one cause of out-of-scope changes in Phase 3 — the exclusions slot is required. Requirements arrive as suggestions; physics is the only law — correctness, data integrity, and the user's explicit hard constraints don't negotiate, while convention, past practice, and "how it's done" do. Question the inherited HOW; the user's WHAT holds (reasoning and sources in ADR-005, in the BoCode repository's `book/docs/decisions/`). The stated request is a proxy — the experience behind it is the requirement: capture what the user will see, do, and get. Focus is saying no; the exclusions slot gives the feature its shape (ADR-006). +Step 0 comes before any code (M and L). Fill the brief: background, scope (what it affects, what it explicitly does **not** affect, and the boundaries), and the requirement itself. An empty "does not affect" list is the number-one cause of out-of-scope changes in Phase 3 — the exclusions slot is required. Requirements arrive as suggestions; physics is the only law — correctness, data integrity, and the user's explicit hard constraints don't negotiate, while convention, past practice, and "how it's done" do. Question the inherited HOW; the user's WHAT holds (reasoning and sources in ADR-005, in the BoCode repository's `book/docs/decisions/`). The stated request is a proxy — the experience behind it is the requirement: capture what the user will see, do, and get. Focus is saying no; the exclusions slot gives the feature its shape (ADR-006). Write the requirement's acceptance criteria as one-line scenarios — GIVEN a starting state, WHEN the user or system acts, THEN the observable outcome — covering the normal path and the error paths; a criterion that cannot be phrased as an observable outcome is a design question for Phase 2, not a requirement (ADR-014). For defect work, Phase 1 reproduces the failure or gathers checkable failure evidence and locates the cause before code changes. If reproduction is unavailable, distinguish facts from hypotheses and state how the fix will be verified. Suppressing an error alone does not establish a repair. If two fixes sharing a premise fail the same verification, state and recheck that premise before trying another fix (ADR-011). @@ -30,7 +30,7 @@ When domain concepts need clarification or terms are used inconsistently, mainta Where practical, Phase 2 uses types or data structures to exclude invalid state combinations. Phase 3 keeps business calculations as pure functions with explicit inputs and outputs, separate from database, file, and network operations (ADR-011). -Phase 4's hard part is the gate, not the sequence: all relevant tests green, no assertion weakened to get there, coverage of the normal path, boundary inputs (ranges, empty, extremes), error paths, and a regression check that existing behavior didn't break. Test-first (write a failing test → minimum implementation → refactor staying green) is the default loop — sequence the work however keeps the gate honest. Iterate fast inside the phase; polish at the gate — what crosses a gate is finished: defaults chosen, errors worded, edges handled (ADR-006). +Phase 4's hard part is the gate, not the sequence: all relevant tests green, no assertion weakened to get there, coverage starting with the brief's scenarios, then the normal path, boundary inputs (ranges, empty, extremes), error paths, and a regression check that existing behavior didn't break. Test-first (write a failing test → minimum implementation → refactor staying green) is the default loop — sequence the work however keeps the gate honest. Iterate fast inside the phase; polish at the gate — what crosses a gate is finished: defaults chosen, errors worded, edges handled (ADR-006). Phase 4 tests observable results and required side effects through the caller's interface, avoiding dependence on private call sequences. For defects, it verifies that the original failure is resolved and existing behavior holds; unverified outcomes remain explicit (ADR-011). diff --git a/book/plans/README.md b/book/plans/README.md index 2122092..5f6c503 100644 --- a/book/plans/README.md +++ b/book/plans/README.md @@ -21,7 +21,7 @@ status: draft | approved | in_progress | completed # — plan ## Requirements brief - + ## Impact range @@ -41,3 +41,5 @@ status: draft | approved | in_progress | completed ``` A plan is executable as written: each step small enough to verify on its own. The done-criteria slot is the finish line — agents stop where the text stops, so an explicit finish line prevents premature stops. When it reads true, flip `status` to `completed`; the plan then doubles as the record of what was intended, next to the summary of what happened. + +For L-tier plans, state acceptance as a behavior delta — which observable behaviors the system ADDED, MODIFIED, or REMOVED relative to today — so review sees what changes in behavior, not only what gets built (ADR-014, distilled from OpenSpec). diff --git a/skills/boscope/SKILL.md b/skills/boscope/SKILL.md index f67760d..7e4bba4 100644 --- a/skills/boscope/SKILL.md +++ b/skills/boscope/SKILL.md @@ -50,10 +50,11 @@ Render the brief below and fill every slot. For empty slots you have two duties: - Boundaries: ## Requirement - + ``` -> The **exclusions** slot is REQUIRED. An empty "does not affect" list is the number-one cause of out-of-scope changes in Phase 3. Focus is saying no — the exclusions slot is where the feature gets its shape. +> The **exclusions** slot is REQUIRED. An empty "does not affect" list is the number-one cause of out-of-scope changes in Phase 3. Focus is saying no — the exclusions slot is where the feature gets its shape. A criterion that cannot be phrased as an observable outcome is a Phase-2 design question, not a requirement. **Axes checklist (review every time, raise the relevant ones):** permissions/auth · notifications · idempotency · cache invalidation · transaction boundaries · concurrency/races · rate limits · data migration · regression impact · generated-artifact sync (codegen / schema / proto — refresh per the project's build scripts after changes). @@ -101,7 +102,7 @@ Where practical, keep business calculations as pure functions with explicit inpu Write a failing test → write the minimal implementation that passes → refactor with tests green. This loop is the iteration engine — run it fast and let it fail: a red test is data, not a setback. Iterate freely inside the phase, never past the gate. What crosses the gate crosses it polished — defaults chosen, errors worded, edges handled. -**Coverage (all required):** normal path · permission checks · boundaries (input ranges / empty / extremes) · error paths · regression (existing behavior intact). +**Coverage (all required):** the brief's scenarios · normal path · permission checks · boundaries (input ranges / empty / extremes) · error paths · regression (existing behavior intact). Test through the caller's interface and assert observable results and required side effects; avoid coupling tests to private call sequences. From 04f34def2acac899659992e7cbf85f2f14e59342 Mon Sep 17 00:00:00 2001 From: Focus Date: Sun, 15 Nov 2026 16:32:26 +0800 Subject: [PATCH 5/8] =?UTF-8?q?=F0=9F=94=A7=20update=20(workflow):=20remov?= =?UTF-8?q?ed=20behaviors=20owe=20an=20absence=20check?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tier M (follow-up round on the ADR-014 task, same functional area — the user ordered a deep-verification pass and this is its one finding; docs only, rides the parent CHANGELOG entry). Deep pass over OpenSpec's verify discipline (/opsx:verify): a REMOVED requirement is verified by absence — behavior still present in code is a CRITICAL finding there. Our regression dimension only said 'existing behavior didn't break'; deliberate removals now also check that the behavior is actually gone, in workflow.md, boscope's Phase-4 coverage, the L-plan delta sentence, and ADR-014. Everything else on OpenSpec's remaining surface re-verified as converged or deliberately not copied (onboard ↔ ADOPT.md Step-0 inventory, tasks.md ↔ plan build order, skipped-≠-passed ↔ ADR-011 unverified-explicit, design adherence ↔ Phase-3 gate + review scope item) — evidence in the session record. Verified: book:index zero warnings, book:release-check clean, commit subject validated. --- CHANGELOG.md | 4 ++-- .../ADR-014-distill-openspec-scenarios-and-deltas.md | 4 ++-- book/guidelines/workflow.md | 2 +- book/plans/README.md | 2 +- skills/boscope/SKILL.md | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ac6e8d3..470cc12 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,10 +6,10 @@ When adding an entry, also refresh the collapsed What's-new block near the top o ## 2026-11-15 — scenario acceptance criteria and plan behavior deltas (ADR-014) -Distilled from [OpenSpec](https://github.com/Fission-AI/OpenSpec) (Fission-AI, MIT): acceptance criteria in the Step-0 brief are now written as one-line GIVEN/WHEN/THEN scenarios — observable outcomes, normal and error paths — and Phase 4's coverage starts by running down that list; L-tier plans state acceptance as a behavior delta (ADDED/MODIFIED/REMOVED relative to today), so review sees what changes in behavior, not only what gets built. The convergences (tiered rigor, behavior-first boundary, brownfield-first) are recorded in the ADR as validation of decisions the baseline had already made; the living-specs layer, mandatory proposal approval, and OpenSpec's tooling are deliberately not copied, with reasons in the ADR. +Distilled from [OpenSpec](https://github.com/Fission-AI/OpenSpec) (Fission-AI, MIT): acceptance criteria in the Step-0 brief are now written as one-line GIVEN/WHEN/THEN scenarios — observable outcomes, normal and error paths — and Phase 4's coverage starts by running down that list; L-tier plans state acceptance as a behavior delta (ADDED/MODIFIED/REMOVED relative to today), so review sees what changes in behavior, not only what gets built. A deep-verification pass over OpenSpec's verify discipline added one more rule: deliberately removed behavior is checked for absence — gone, not merely unbroken. The convergences (tiered rigor, behavior-first boundary, brownfield-first) are recorded in the ADR as validation of decisions the baseline had already made; the living-specs layer, mandatory proposal approval, and OpenSpec's tooling are deliberately not copied, with reasons in the ADR. - Added: `book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md` -- Changed: `book/guidelines/workflow.md` (Step-0 scenario sentence; Phase-4 coverage starts with the brief's scenarios), `book/plans/README.md` (acceptance scenarios in the brief slot; L-tier behavior-delta sentence), `skills/boscope/SKILL.md` (brief template and Phase-4 coverage wording), `README.md` / `README.zh-CN.md` / `README.ja.md` (What's-new) +- Changed: `book/guidelines/workflow.md` (Step-0 scenario sentence; Phase-4 coverage starts with the brief's scenarios, regression includes removed-behavior absence), `book/plans/README.md` (acceptance scenarios in the brief slot; L-tier behavior-delta sentence with the REMOVED absence check), `skills/boscope/SKILL.md` (brief template and Phase-4 coverage wording), `README.md` / `README.zh-CN.md` / `README.ja.md` (What's-new) **Adopter action:** run your usual sync (`bocode:upgrade -- --apply`, then `--verify`). If you keep a session-side copy of the structured-feature-implementation skill, add the scenario line to its brief template yourself — session skills are yours, not template-owned. diff --git a/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md b/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md index 442b7b9..2ff8633 100644 --- a/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md +++ b/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md @@ -14,14 +14,14 @@ Accepted — 2026-11-15. Ships with the template. Studying it against this workflow found more convergence than gap. Its progressive rigor (lightweight by default, rigor scaling with risk) is the S/M/L tiering (ADR-008). Its behavior-first boundary — specs capture observable behavior, implementation detail goes to design — is the Step-0 WHAT / Phase-2 HOW split (ADR-005, ADR-006). Its brownfield-first stance, specs written as you build rather than generated upfront, is how the book already compounds. Its explore phase is Phase 1's "no code changed" gate. The convergence validates the baseline; it is not something to copy. -Two practices are worth distilling. First, OpenSpec writes acceptance as scenarios — a requirement with a SHALL line, scenario blocks in GIVEN/WHEN/THEN — so every criterion is checkable before code exists; our brief's requirement slot is free text, and Phase 4's gate has no explicit upstream list to run down. Second, OpenSpec's proposals store only deltas — ADDED/MODIFIED/REMOVED requirements against current behavior — which makes review sharp about what changes, not just what gets built; L-tier plans can state acceptance the same way without owning a permanent spec tree. +Two practices are worth distilling. First, OpenSpec writes acceptance as scenarios — a requirement with a SHALL line, scenario blocks in GIVEN/WHEN/THEN — so every criterion is checkable before code exists; our brief's requirement slot is free text, and Phase 4's gate has no explicit upstream list to run down. Second, OpenSpec's proposals store only deltas — ADDED/MODIFIED/REMOVED requirements against current behavior — which makes review sharp about what changes, not just what gets built; L-tier plans can state acceptance the same way without owning a permanent spec tree. A second pass over OpenSpec's verify discipline (its `/opsx:verify` skill) added a third, smaller rule: a REMOVED requirement is verified by absence — the behavior still present in code is a critical finding — which our regression dimension ("existing behavior didn't break") did not say. ## Decision Distill the two practices; take nothing else. - **Scenario acceptance criteria.** In the Step-0 brief (M/L), the requirement's acceptance criteria are written as one-line scenarios — GIVEN a starting state, WHEN the user or system acts, THEN the observable outcome — covering the normal path and the error paths. Phase 4's coverage starts by running down the brief's scenarios. A criterion that cannot be phrased as an observable outcome is a design question for Phase 2, not a requirement. -- **Behavior deltas in L-tier plans.** An L plan states acceptance as a delta — which observable behaviors the system ADDED, MODIFIED, or REMOVED relative to current behavior — so review sees what changes in behavior, not only what gets built. +- **Behavior deltas in L-tier plans.** An L plan states acceptance as a delta — which observable behaviors the system ADDED, MODIFIED, or REMOVED relative to current behavior — so review sees what changes in behavior, not only what gets built. REMOVED rows owe an absence check in Phase 4: the behavior is gone, not merely unbroken. Not copied, with reasons: diff --git a/book/guidelines/workflow.md b/book/guidelines/workflow.md index 9af31e2..e489397 100644 --- a/book/guidelines/workflow.md +++ b/book/guidelines/workflow.md @@ -30,7 +30,7 @@ When domain concepts need clarification or terms are used inconsistently, mainta Where practical, Phase 2 uses types or data structures to exclude invalid state combinations. Phase 3 keeps business calculations as pure functions with explicit inputs and outputs, separate from database, file, and network operations (ADR-011). -Phase 4's hard part is the gate, not the sequence: all relevant tests green, no assertion weakened to get there, coverage starting with the brief's scenarios, then the normal path, boundary inputs (ranges, empty, extremes), error paths, and a regression check that existing behavior didn't break. Test-first (write a failing test → minimum implementation → refactor staying green) is the default loop — sequence the work however keeps the gate honest. Iterate fast inside the phase; polish at the gate — what crosses a gate is finished: defaults chosen, errors worded, edges handled (ADR-006). +Phase 4's hard part is the gate, not the sequence: all relevant tests green, no assertion weakened to get there, coverage starting with the brief's scenarios, then the normal path, boundary inputs (ranges, empty, extremes), error paths, and a regression check that existing behavior didn't break and deliberately removed behavior is actually gone. Test-first (write a failing test → minimum implementation → refactor staying green) is the default loop — sequence the work however keeps the gate honest. Iterate fast inside the phase; polish at the gate — what crosses a gate is finished: defaults chosen, errors worded, edges handled (ADR-006). Phase 4 tests observable results and required side effects through the caller's interface, avoiding dependence on private call sequences. For defects, it verifies that the original failure is resolved and existing behavior holds; unverified outcomes remain explicit (ADR-011). diff --git a/book/plans/README.md b/book/plans/README.md index 5f6c503..ffd2de9 100644 --- a/book/plans/README.md +++ b/book/plans/README.md @@ -42,4 +42,4 @@ status: draft | approved | in_progress | completed A plan is executable as written: each step small enough to verify on its own. The done-criteria slot is the finish line — agents stop where the text stops, so an explicit finish line prevents premature stops. When it reads true, flip `status` to `completed`; the plan then doubles as the record of what was intended, next to the summary of what happened. -For L-tier plans, state acceptance as a behavior delta — which observable behaviors the system ADDED, MODIFIED, or REMOVED relative to today — so review sees what changes in behavior, not only what gets built (ADR-014, distilled from OpenSpec). +For L-tier plans, state acceptance as a behavior delta — which observable behaviors the system ADDED, MODIFIED, or REMOVED relative to today — so review sees what changes in behavior, not only what gets built. REMOVED rows owe an absence check: the behavior is gone, not merely unbroken (ADR-014, distilled from OpenSpec). diff --git a/skills/boscope/SKILL.md b/skills/boscope/SKILL.md index 7e4bba4..ef3bf7d 100644 --- a/skills/boscope/SKILL.md +++ b/skills/boscope/SKILL.md @@ -102,7 +102,7 @@ Where practical, keep business calculations as pure functions with explicit inpu Write a failing test → write the minimal implementation that passes → refactor with tests green. This loop is the iteration engine — run it fast and let it fail: a red test is data, not a setback. Iterate freely inside the phase, never past the gate. What crosses the gate crosses it polished — defaults chosen, errors worded, edges handled. -**Coverage (all required):** the brief's scenarios · normal path · permission checks · boundaries (input ranges / empty / extremes) · error paths · regression (existing behavior intact). +**Coverage (all required):** the brief's scenarios · normal path · permission checks · boundaries (input ranges / empty / extremes) · error paths · regression (existing behavior intact, deliberately removed behavior gone). Test through the caller's interface and assert observable results and required side effects; avoid coupling tests to private call sequences. From 94082f7503b776ef5132fe8416aa09306035b8f3 Mon Sep 17 00:00:00 2001 From: Focus Date: Sun, 15 Nov 2026 16:45:31 +0800 Subject: [PATCH 6/8] =?UTF-8?q?=F0=9F=93=96=20docs=20(decisions):=20record?= =?UTF-8?q?=20the=20audit's=20falsification=20conditions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tier S (single-file ADR addition, rides the parent ADR-014 task and its existing CHANGELOG entry — records the five-step audit outcome). The five-step audit of the distillation itself: requirement questioned (zero-adoption was considered and rejected on the absence-check hole), nothing left to delete (four-copy test passed on the Step-0/Phase-3 pairing precedent), nothing to automate (scenario linting would automate ceremony). Its surviving output: falsification conditions for the two belief-driven weaves — scenarios decaying into slot-filling ceremony, or L-plan deltas restating the impact range, each means that weave is deleted, not defended. Verified: book:index zero warnings, book:release-check clean, commit subject validated. --- .../decisions/ADR-014-distill-openspec-scenarios-and-deltas.md | 1 + 1 file changed, 1 insertion(+) diff --git a/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md b/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md index 2ff8633..dc2047d 100644 --- a/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md +++ b/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md @@ -34,5 +34,6 @@ Not copied, with reasons: - The brief's requirement slot and Phase 4's gate close a loop explicitly: scenarios written before code become the first test list. - L plans gain a delta view of acceptance at no standing maintenance cost — the delta lives in the plan, which already records intent. +- Both weaves carry falsification conditions, set by the five-step audit of this change (ADR-005's discipline applied to its own output): if brief scenarios decay into slot-filling ceremony, or L-plan deltas restate the impact range instead of behavior, the offending weave is deleted, not defended. - No new directory, tool, phase, gate, or truth source. The weaves land in `guidelines/workflow.md`, `plans/README.md`, and the boscope skill's brief template; the session-side structured-feature-implementation skill is aligned with the same wording. - Credit where due: the two practices and the format inspiration come from OpenSpec (MIT, Fission-AI). The convergences above are recorded as validation of decisions this repository had already made on its own. From 26026aa4c5e9c988ec35fef8821a2df298078aeb Mon Sep 17 00:00:00 2001 From: Focus Date: Sun, 15 Nov 2026 16:49:52 +0800 Subject: [PATCH 7/8] =?UTF-8?q?=F0=9F=93=96=20docs=20(plans):=20give=20l-t?= =?UTF-8?q?ier=20delta=20rows=20citable=20ids?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tier M (follow-up round 2 on the ADR-014 task, same functional area — guideline semantics reaching adopters via sync, riding the parent CHANGELOG entry). Empirical input: a real OpenSpec change drafted inside a BoCode-adopting project (its tasks cite requirement IDs as verification criteria; its done rule requires every requirement to link test or observation evidence; its brief numbers user-confirmed requirements apart from design choices). The same artifact left the living-specs tree empty with truth still in book architecture snapshots — confirming the living-specs exclusion from actual use. Adopted: stable short IDs on L-delta rows, done-time row-to-evidence links (the plan records intent, it is not evidence), and the user-confirmed vs design-derived distinction in the brief. Verified: book:index zero warnings, book:release-check clean, commit subject validated. --- CHANGELOG.md | 4 ++-- .../ADR-014-distill-openspec-scenarios-and-deltas.md | 6 +++--- book/plans/README.md | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 470cc12..78e2265 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,10 +6,10 @@ When adding an entry, also refresh the collapsed What's-new block near the top o ## 2026-11-15 — scenario acceptance criteria and plan behavior deltas (ADR-014) -Distilled from [OpenSpec](https://github.com/Fission-AI/OpenSpec) (Fission-AI, MIT): acceptance criteria in the Step-0 brief are now written as one-line GIVEN/WHEN/THEN scenarios — observable outcomes, normal and error paths — and Phase 4's coverage starts by running down that list; L-tier plans state acceptance as a behavior delta (ADDED/MODIFIED/REMOVED relative to today), so review sees what changes in behavior, not only what gets built. A deep-verification pass over OpenSpec's verify discipline added one more rule: deliberately removed behavior is checked for absence — gone, not merely unbroken. The convergences (tiered rigor, behavior-first boundary, brownfield-first) are recorded in the ADR as validation of decisions the baseline had already made; the living-specs layer, mandatory proposal approval, and OpenSpec's tooling are deliberately not copied, with reasons in the ADR. +Distilled from [OpenSpec](https://github.com/Fission-AI/OpenSpec) (Fission-AI, MIT): acceptance criteria in the Step-0 brief are now written as one-line GIVEN/WHEN/THEN scenarios — observable outcomes, normal and error paths — and Phase 4's coverage starts by running down that list; L-tier plans state acceptance as a behavior delta (ADDED/MODIFIED/REMOVED relative to today), so review sees what changes in behavior, not only what gets built. A deep-verification pass over OpenSpec's verify discipline added one more rule: deliberately removed behavior is checked for absence — gone, not merely unbroken. A real OpenSpec change drafted inside a BoCode-adopting project added the last piece: delta rows carry short stable IDs, at done every row cites its test or observation evidence (the plan records intent, it is not evidence), and user-confirmed requirements stay distinguishable from design-derived ones. The convergences (tiered rigor, behavior-first boundary, brownfield-first) are recorded in the ADR as validation of decisions the baseline had already made; the living-specs layer, mandatory proposal approval, and OpenSpec's tooling are deliberately not copied — the living-specs exclusion confirmed by that same artifact leaving its specs tree empty, truth still in the book's architecture snapshots. - Added: `book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md` -- Changed: `book/guidelines/workflow.md` (Step-0 scenario sentence; Phase-4 coverage starts with the brief's scenarios, regression includes removed-behavior absence), `book/plans/README.md` (acceptance scenarios in the brief slot; L-tier behavior-delta sentence with the REMOVED absence check), `skills/boscope/SKILL.md` (brief template and Phase-4 coverage wording), `README.md` / `README.zh-CN.md` / `README.ja.md` (What's-new) +- Changed: `book/guidelines/workflow.md` (Step-0 scenario sentence; Phase-4 coverage starts with the brief's scenarios, regression includes removed-behavior absence), `book/plans/README.md` (acceptance scenarios in the brief slot; L-tier behavior-delta sentence with the REMOVED absence check, stable row IDs, done-time evidence links, user-confirmed vs design-derived distinction), `skills/boscope/SKILL.md` (brief template and Phase-4 coverage wording), `README.md` / `README.zh-CN.md` / `README.ja.md` (What's-new) **Adopter action:** run your usual sync (`bocode:upgrade -- --apply`, then `--verify`). If you keep a session-side copy of the structured-feature-implementation skill, add the scenario line to its brief template yourself — session skills are yours, not template-owned. diff --git a/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md b/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md index dc2047d..37694e3 100644 --- a/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md +++ b/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md @@ -14,14 +14,14 @@ Accepted — 2026-11-15. Ships with the template. Studying it against this workflow found more convergence than gap. Its progressive rigor (lightweight by default, rigor scaling with risk) is the S/M/L tiering (ADR-008). Its behavior-first boundary — specs capture observable behavior, implementation detail goes to design — is the Step-0 WHAT / Phase-2 HOW split (ADR-005, ADR-006). Its brownfield-first stance, specs written as you build rather than generated upfront, is how the book already compounds. Its explore phase is Phase 1's "no code changed" gate. The convergence validates the baseline; it is not something to copy. -Two practices are worth distilling. First, OpenSpec writes acceptance as scenarios — a requirement with a SHALL line, scenario blocks in GIVEN/WHEN/THEN — so every criterion is checkable before code exists; our brief's requirement slot is free text, and Phase 4's gate has no explicit upstream list to run down. Second, OpenSpec's proposals store only deltas — ADDED/MODIFIED/REMOVED requirements against current behavior — which makes review sharp about what changes, not just what gets built; L-tier plans can state acceptance the same way without owning a permanent spec tree. A second pass over OpenSpec's verify discipline (its `/opsx:verify` skill) added a third, smaller rule: a REMOVED requirement is verified by absence — the behavior still present in code is a critical finding — which our regression dimension ("existing behavior didn't break") did not say. +Two practices are worth distilling. First, OpenSpec writes acceptance as scenarios — a requirement with a SHALL line, scenario blocks in GIVEN/WHEN/THEN — so every criterion is checkable before code exists; our brief's requirement slot is free text, and Phase 4's gate has no explicit upstream list to run down. Second, OpenSpec's proposals store only deltas — ADDED/MODIFIED/REMOVED requirements against current behavior — which makes review sharp about what changes, not just what gets built; L-tier plans can state acceptance the same way without owning a permanent spec tree. A second pass over OpenSpec's verify discipline (its `/opsx:verify` skill) added a third, smaller rule: a REMOVED requirement is verified by absence — the behavior still present in code is a critical finding — which our regression dimension ("existing behavior didn't break") did not say. A third input was empirical: a real OpenSpec change drafted inside a BoCode-adopting project. Its task list cited stable requirement IDs (`ARC-01`…) as verification criteria, its done rule required every requirement to link real test or observation evidence ("a planning document is not evidence"), and its brief numbered user-confirmed requirements apart from design choices. The same artifact left the living-specs tree empty with implementation truth still in the book's architecture snapshots and ADRs — confirming the living-specs exclusion below from actual use. ## Decision Distill the two practices; take nothing else. - **Scenario acceptance criteria.** In the Step-0 brief (M/L), the requirement's acceptance criteria are written as one-line scenarios — GIVEN a starting state, WHEN the user or system acts, THEN the observable outcome — covering the normal path and the error paths. Phase 4's coverage starts by running down the brief's scenarios. A criterion that cannot be phrased as an observable outcome is a design question for Phase 2, not a requirement. -- **Behavior deltas in L-tier plans.** An L plan states acceptance as a delta — which observable behaviors the system ADDED, MODIFIED, or REMOVED relative to current behavior — so review sees what changes in behavior, not only what gets built. REMOVED rows owe an absence check in Phase 4: the behavior is gone, not merely unbroken. +- **Behavior deltas in L-tier plans.** An L plan states acceptance as a delta — which observable behaviors the system ADDED, MODIFIED, or REMOVED relative to current behavior — so review sees what changes in behavior, not only what gets built. REMOVED rows owe an absence check in Phase 4: the behavior is gone, not merely unbroken. Rows carry short stable IDs so tests, tasks, and evidence can cite them, and at done every row cites its test or observation evidence — the plan records intent, it is not evidence. User-confirmed requirements stay distinguishable from design-derived ones in the brief. Not copied, with reasons: @@ -34,6 +34,6 @@ Not copied, with reasons: - The brief's requirement slot and Phase 4's gate close a loop explicitly: scenarios written before code become the first test list. - L plans gain a delta view of acceptance at no standing maintenance cost — the delta lives in the plan, which already records intent. -- Both weaves carry falsification conditions, set by the five-step audit of this change (ADR-005's discipline applied to its own output): if brief scenarios decay into slot-filling ceremony, or L-plan deltas restate the impact range instead of behavior, the offending weave is deleted, not defended. +- The weaves carry falsification conditions, set by the five-step audit of this change (ADR-005's discipline applied to its own output): if brief scenarios decay into slot-filling ceremony, or L-plan deltas restate the impact range instead of behavior, the offending weave is deleted, not defended. - No new directory, tool, phase, gate, or truth source. The weaves land in `guidelines/workflow.md`, `plans/README.md`, and the boscope skill's brief template; the session-side structured-feature-implementation skill is aligned with the same wording. - Credit where due: the two practices and the format inspiration come from OpenSpec (MIT, Fission-AI). The convergences above are recorded as validation of decisions this repository had already made on its own. diff --git a/book/plans/README.md b/book/plans/README.md index ffd2de9..3ba0439 100644 --- a/book/plans/README.md +++ b/book/plans/README.md @@ -42,4 +42,4 @@ status: draft | approved | in_progress | completed A plan is executable as written: each step small enough to verify on its own. The done-criteria slot is the finish line — agents stop where the text stops, so an explicit finish line prevents premature stops. When it reads true, flip `status` to `completed`; the plan then doubles as the record of what was intended, next to the summary of what happened. -For L-tier plans, state acceptance as a behavior delta — which observable behaviors the system ADDED, MODIFIED, or REMOVED relative to today — so review sees what changes in behavior, not only what gets built. REMOVED rows owe an absence check: the behavior is gone, not merely unbroken (ADR-014, distilled from OpenSpec). +For L-tier plans, state acceptance as a behavior delta — which observable behaviors the system ADDED, MODIFIED, or REMOVED relative to today — so review sees what changes in behavior, not only what gets built. REMOVED rows owe an absence check: the behavior is gone, not merely unbroken. Rows carry short stable IDs (e.g. `ARC-01`) so tests, tasks, and evidence can cite them; at done, every row cites its test or observation evidence — the plan records intent, it is not evidence. Keep user-confirmed requirements distinguishable from design-derived ones in the brief (ADR-014, distilled from OpenSpec). From 4852d44a779e93636bc7e3614deb3e0c23c93b37 Mon Sep 17 00:00:00 2001 From: Focus Date: Sun, 15 Nov 2026 18:03:20 +0800 Subject: [PATCH 8/8] =?UTF-8?q?=F0=9F=93=96=20docs=20(decisions):=20retrac?= =?UTF-8?q?t=20the=20overstated=20living-specs=20proof?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tier S (wording correction on two files, rides the parent ADR-014 CHANGELOG entry). The ADR claimed the adopter project's empty living-specs tree 'confirms the exclusion from actual use' — but nothing has been archived there yet (the project's own rule: no archive before acceptance), so the empty tree is a stage, not a verdict. Citing an unreached stage as evidence violates our own ADR-011 discipline: unverified conclusions stay explicit. Corrected in ADR-014 and the CHANGELOG: the living-specs exclusion rests on structural reasons; its real test arrives when that change is implemented and archived — the merged tree either stays maintained or rots. The change-local delta specs (seven capability domains) remain the empirical source for the ID/evidence-link rules; they map to L-plan behavior deltas. Verified: book:index zero warnings, book:release-check clean, commit subject validated. --- CHANGELOG.md | 2 +- .../decisions/ADR-014-distill-openspec-scenarios-and-deltas.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78e2265..1168c6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ When adding an entry, also refresh the collapsed What's-new block near the top o ## 2026-11-15 — scenario acceptance criteria and plan behavior deltas (ADR-014) -Distilled from [OpenSpec](https://github.com/Fission-AI/OpenSpec) (Fission-AI, MIT): acceptance criteria in the Step-0 brief are now written as one-line GIVEN/WHEN/THEN scenarios — observable outcomes, normal and error paths — and Phase 4's coverage starts by running down that list; L-tier plans state acceptance as a behavior delta (ADDED/MODIFIED/REMOVED relative to today), so review sees what changes in behavior, not only what gets built. A deep-verification pass over OpenSpec's verify discipline added one more rule: deliberately removed behavior is checked for absence — gone, not merely unbroken. A real OpenSpec change drafted inside a BoCode-adopting project added the last piece: delta rows carry short stable IDs, at done every row cites its test or observation evidence (the plan records intent, it is not evidence), and user-confirmed requirements stay distinguishable from design-derived ones. The convergences (tiered rigor, behavior-first boundary, brownfield-first) are recorded in the ADR as validation of decisions the baseline had already made; the living-specs layer, mandatory proposal approval, and OpenSpec's tooling are deliberately not copied — the living-specs exclusion confirmed by that same artifact leaving its specs tree empty, truth still in the book's architecture snapshots. +Distilled from [OpenSpec](https://github.com/Fission-AI/OpenSpec) (Fission-AI, MIT): acceptance criteria in the Step-0 brief are now written as one-line GIVEN/WHEN/THEN scenarios — observable outcomes, normal and error paths — and Phase 4's coverage starts by running down that list; L-tier plans state acceptance as a behavior delta (ADDED/MODIFIED/REMOVED relative to today), so review sees what changes in behavior, not only what gets built. A deep-verification pass over OpenSpec's verify discipline added one more rule: deliberately removed behavior is checked for absence — gone, not merely unbroken. A real OpenSpec change drafted inside a BoCode-adopting project added the last piece: delta rows carry short stable IDs, at done every row cites its test or observation evidence (the plan records intent, it is not evidence), and user-confirmed requirements stay distinguishable from design-derived ones. The convergences (tiered rigor, behavior-first boundary, brownfield-first) are recorded in the ADR as validation of decisions the baseline had already made; the living-specs layer, mandatory proposal approval, and OpenSpec's tooling are deliberately not copied, with reasons in the ADR (the living-specs call is structural, not yet tested — its source change is unimplemented, and the question becomes observable only after it is archived). - Added: `book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md` - Changed: `book/guidelines/workflow.md` (Step-0 scenario sentence; Phase-4 coverage starts with the brief's scenarios, regression includes removed-behavior absence), `book/plans/README.md` (acceptance scenarios in the brief slot; L-tier behavior-delta sentence with the REMOVED absence check, stable row IDs, done-time evidence links, user-confirmed vs design-derived distinction), `skills/boscope/SKILL.md` (brief template and Phase-4 coverage wording), `README.md` / `README.zh-CN.md` / `README.ja.md` (What's-new) diff --git a/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md b/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md index 37694e3..c97b22e 100644 --- a/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md +++ b/book/docs/decisions/ADR-014-distill-openspec-scenarios-and-deltas.md @@ -14,7 +14,7 @@ Accepted — 2026-11-15. Ships with the template. Studying it against this workflow found more convergence than gap. Its progressive rigor (lightweight by default, rigor scaling with risk) is the S/M/L tiering (ADR-008). Its behavior-first boundary — specs capture observable behavior, implementation detail goes to design — is the Step-0 WHAT / Phase-2 HOW split (ADR-005, ADR-006). Its brownfield-first stance, specs written as you build rather than generated upfront, is how the book already compounds. Its explore phase is Phase 1's "no code changed" gate. The convergence validates the baseline; it is not something to copy. -Two practices are worth distilling. First, OpenSpec writes acceptance as scenarios — a requirement with a SHALL line, scenario blocks in GIVEN/WHEN/THEN — so every criterion is checkable before code exists; our brief's requirement slot is free text, and Phase 4's gate has no explicit upstream list to run down. Second, OpenSpec's proposals store only deltas — ADDED/MODIFIED/REMOVED requirements against current behavior — which makes review sharp about what changes, not just what gets built; L-tier plans can state acceptance the same way without owning a permanent spec tree. A second pass over OpenSpec's verify discipline (its `/opsx:verify` skill) added a third, smaller rule: a REMOVED requirement is verified by absence — the behavior still present in code is a critical finding — which our regression dimension ("existing behavior didn't break") did not say. A third input was empirical: a real OpenSpec change drafted inside a BoCode-adopting project. Its task list cited stable requirement IDs (`ARC-01`…) as verification criteria, its done rule required every requirement to link real test or observation evidence ("a planning document is not evidence"), and its brief numbered user-confirmed requirements apart from design choices. The same artifact left the living-specs tree empty with implementation truth still in the book's architecture snapshots and ADRs — confirming the living-specs exclusion below from actual use. +Two practices are worth distilling. First, OpenSpec writes acceptance as scenarios — a requirement with a SHALL line, scenario blocks in GIVEN/WHEN/THEN — so every criterion is checkable before code exists; our brief's requirement slot is free text, and Phase 4's gate has no explicit upstream list to run down. Second, OpenSpec's proposals store only deltas — ADDED/MODIFIED/REMOVED requirements against current behavior — which makes review sharp about what changes, not just what gets built; L-tier plans can state acceptance the same way without owning a permanent spec tree. A second pass over OpenSpec's verify discipline (its `/opsx:verify` skill) added a third, smaller rule: a REMOVED requirement is verified by absence — the behavior still present in code is a critical finding — which our regression dimension ("existing behavior didn't break") did not say. A third input was empirical: a real OpenSpec change drafted inside a BoCode-adopting project. Its task list cited stable requirement IDs (`ARC-01`…) as verification criteria, its done rule required every requirement to link real test or observation evidence ("a planning document is not evidence"), and its brief numbered user-confirmed requirements apart from design choices. The same artifact's change-local delta specs are rich while its living-specs tree stays empty — but nothing has been archived yet (the project's own rule: no archive before acceptance), so that is not evidence for or against the living-specs layer. The exclusion below rests on structural reasons; its real test arrives when that change is implemented and archived, and the merged tree either stays maintained or rots. ## Decision