@sabaiway/agent-workflow-kit 19.0.0 → 19.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,63 @@ Semantically versioned ([semver](https://semver.org)), newest first. The `versio
4
4
  is the current release. `upgrade` mode reads a project's `docs/ai/.workflow-version` and applies
5
5
  every `migrations/<version>-<slug>.md` newer than it, in semver order.
6
6
 
7
+ ## 19.2.0 — the entry file's kit pointers and Memory Map rows are written current with no question; a differing one is named with its route (AD-212)
8
+
9
+ **Your upgrade now writes the kit's three pointers in `AGENTS.md` current, with no question and no copy kept.**
10
+ Before, the reconcile filled an empty pointer and refreshed one that matched text the kit had shipped; any other text
11
+ between a pointer's two `<!-- workflow: -->` comment lines was kept as found, with an advisory note, so an edited
12
+ pointer stayed on old wording for good. Now a current pointer is left, a known earlier one refreshed, and any other
13
+ text is written with the installed engine's fragment, every byte outside the two comment lines unchanged and a CRLF
14
+ file staying CRLF. Its clause in the reconcile line reads `wrote the current <name> pointer over a different one`, and
15
+ one note line names where your own text goes:
16
+
17
+ `[inject-methodology] note: text of your own goes outside the two <!-- workflow: --> comment lines around each pointer.`
18
+
19
+ - **The Memory Map rows of the rules themes follow the same rule.** A theme's row with other text is written with the
20
+ current row (`the <theme> Memory Map row written with the current text`), and its note reads `a row of your own goes
21
+ on a line of its own, its first cell a path of your own`. A theme with more than one row, or a row that does not
22
+ close its cells on one line, is left as it stands with its reason.
23
+ - **The engine is read for every pointer the run judges.** A filled pointer cannot be judged without its fragment, so
24
+ a file whose three pointers are all filled now stops with the install command when the engine is absent, where it
25
+ was a zero-diff exit 0. The kit's own route always installs the engine; the No-Node walk reports that no pointer was
26
+ brought current and continues the upgrade.
27
+ - **The line cap still guards every write**: a differing pointer whose write would pass the 100-line cap takes the
28
+ same lane as a fill, and the chained soft skips are unchanged.
29
+ - **The advisory notes retire**: the procedures hint and the per-pointer upgrade advice no longer print.
30
+ - **The texts say the same.** `upgrade.md` (the pointers row and block, the No-Node walk, the step-4 and step-8
31
+ relays), the run-list's pointers outcomes (`written over a different one`), `composition-handoff.md`, the procedures
32
+ guide's cap-soft-skip paragraph and the guide's *Reserved names and channels*, which names the pointers and the
33
+ rules-theme rows as the kit's and gains the ninth channel.
34
+
35
+ ## 19.1.0 — the kit sections of the agent rules file are written current with no question; a differing body is named with its route (AD-211)
36
+
37
+ **Your upgrade now writes the kit's three sections of `docs/ai/agent_rules.md` current, with no question and no copy
38
+ kept.** Before, the `lens` step refreshed Communication (user-facing messages), Story sessions and the planning/review
39
+ lens only when a section matched a body the kit had shipped; any other body was preserved verbatim with a note, so an
40
+ edited section stayed on old wording for good. Now a current section is left, a known earlier one refreshed, and any
41
+ other body is written with the canon at the file's own heading number, in the file's own newline form, its trailing
42
+ blank lines kept and every byte outside the section unchanged. Its line names where your own text goes:
43
+
44
+ `[lens-region] the planning/review lens section differed from the current canon — written with it; text of your own goes under a ### heading of its own, titled unlike the kit's sections.`
45
+
46
+ From engine 5.12.2 on, the lens section's own intro says it is written current; with an earlier engine that ships the
47
+ lens canon, the step writes that engine's canon, whose intro still says a custom edit is preserved.
48
+
49
+ - **A `### 2.<N>.` heading that opens with a section's title words is that section.** Alone, `### 2.6. Planning,
50
+ review & process-fidelity invariants: my additions` is written over too; beside the kit's own heading the two are
51
+ doubled and neither is changed. A section of your own needs a title of its own.
52
+ - **A section with doubled headings is left.** With more than one heading for a section, the step prints `none of them
53
+ was changed` for it, still reconciles the other sections, and asks you to retitle every heading but one, then re-run.
54
+ - **A target the step cannot rewrite safely is left alone.** A link or any other node that is not a regular file at
55
+ the target, or a file that is not valid UTF-8, prints one line and nothing is written.
56
+ - **The line cap still guards every write where the file declares `maxLines`**: a section whose write would pass it
57
+ is refused and left as it stands, exit 0; a file with no `maxLines` skips the guard with a note.
58
+ - **The texts say the same.** `upgrade.md` (the `lens` row, its relay and the report), `composition-handoff.md`, the
59
+ run-list's `lens` outcome `differing body written` in place of `custom edit preserved`, the Recommendations remedy
60
+ (a prior or any other body → the upgrade's `lens` reconcile), the rules template, and the guide's *Reserved names and
61
+ channels*, which names the three sections as the kit's and gains the eighth channel: text of your own under a `###`
62
+ heading of its own, titled unlike the kit's sections.
63
+
7
64
  ## 19.0.0 — the Jev copy is written current with no question beside a copy at a kit pin; `jev-skill.earlier` retires (AD-210)
8
65
 
9
66
  **MAJOR: the advisor's `jev-skill.earlier` item is gone, and `apply-danger-check --variant jev-skill.earlier` is a
package/SKILL.md CHANGED
@@ -3,7 +3,7 @@ name: agent-workflow-kit
3
3
  description: Deploy or upgrade a portable AI-agent memory-and-workflow system in any project. Use when the user wants to bootstrap `docs/ai/` + an entry-point `AGENTS.md` (+ `CLAUDE.md` alias) + cap/archive/index enforcement in a new or existing repo, set up the Memory Map and session protocols, install the docs-rotation pre-commit hook, or run `/agent-workflow-kit` / `/agent-workflow-kit upgrade`. Triggers on phrases like "set up the memory system", "deploy the AI workflow here", "bootstrap docs/ai", "upgrade the workflow". New to the epic, story and task tier? Run `/agent-workflow-kit tier`. A typed decision with a confidence from Jev? Run `/agent-workflow-kit jev`.
4
4
  disable-model-invocation: true
5
5
  metadata:
6
- version: '19.0.0'
6
+ version: '19.2.0'
7
7
  ---
8
8
 
9
9
  # agent-workflow-kit
package/capability.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "schema": 1,
4
4
  "name": "agent-workflow-kit",
5
5
  "kind": "composition-root",
6
- "version": "19.0.0",
6
+ "version": "19.2.0",
7
7
  "provides": [],
8
8
  "roles": {},
9
9
  "detect": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sabaiway/agent-workflow-kit",
3
- "version": "19.0.0",
3
+ "version": "19.2.0",
4
4
  "description": "Portable, cross-agent memory & workflow for AI coding agents — Claude Code, Codex, Cursor, Devin Desktop. One command deploys an AGENTS.md entry point + docs/ai context with cap/archive/index enforcement into any repo.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -104,9 +104,13 @@ files (the five the kit bundles for `.claude/agents/` — `changelog-skeleton.md
104
104
  by the next upgrade with no question and no copy kept.
105
105
  Also the kit's: the vendor skill copy the kit installs into the three agent skill roots
106
106
  when it matches a pin the kit shipped, written with no question beside a copy at a kit pin;
107
- a copy matching none is the user's, left and named. A declaration seeded once from a template and never
107
+ a copy matching none is the user's, left and named. Also the kit's: the three kit sections of
108
+ `docs/ai/agent_rules.md` (Communication, Story sessions and the planning/review lens), each
109
+ written current on every upgrade with no question and no copy kept. Also the kit's: the three pointers of `AGENTS.md`
110
+ and its Memory Map rows of the rules themes, each written current on every upgrade with no question and no copy kept.
111
+ A declaration seeded once from a template and never
108
112
  replaced by the upgrade's ensures (a migration rewrites one only on the user's explicit yes) is the
109
- user's own file. A customization goes into one of seven channels instead:
113
+ user's own file. A customization goes into one of nine channels instead:
110
114
 
111
115
  - **Your own commit checks** go in the local hook file `scripts/pre-commit.local`: the managed
112
116
  pre-commit hook runs it first, once the installer has run.
@@ -117,6 +121,11 @@ user's own file. A customization goes into one of seven channels instead:
117
121
  - **A vehicle of your own** goes in `.claude/agents/<name>.local.md` with a `name:` of its own, which
118
122
  no review roster names; a lens of your own in a review slot keeps a stem of its own.
119
123
  - **A hook of your own** goes in `.claude/hooks/<name>.local.mjs`, which you wire.
124
+ - **Your own text in the agent rules file**: text of your own goes under a ### heading of its own,
125
+ titled unlike the kit's sections.
126
+ - **Your own text in the entry file `AGENTS.md`**: text of your own goes outside the two
127
+ `<!-- workflow: -->` comment lines around each pointer; a row of your own goes on a line of its
128
+ own, its first cell a path of your own.
120
129
 
121
130
  No path segment of a file the kit bundles and places as its own has a dot-separated part exactly
122
131
  `local`; a path of that form is the user's, and no kit tool writes one on its own. Outside that rule:
@@ -43,6 +43,6 @@ Run **`node ${CLAUDE_SKILL_DIR}/tools/procedures.mjs <activity> [--override <slo
43
43
 
44
44
  **Record-bound review block (`feedback-triage` only).** In place of the driving contracts and the grounding pre-step the advisor renders the check-with-excerpts line, then one line per review member — a ready bridge's plan-mode command, a ready lens's brief (the record plus the excerpts), a skipped line for a not-ready member — and the round-table line while the slot carries a bridge obligation (a roster naming no bridge: the no-receipt fact in its place; a fully degraded reviewed or council slot keeps the line). The round-table line is followed by the standing fact that the table judges the obligation `review-rounds-cli` resolves from `docs/ai/orchestration.json`, never this run's `--override`. `--json` carries the identical lines under **`feedbackTriage`** (an empty array for the other activities).
45
45
 
46
- **Cap-soft-skip degradation (the feature's only AUTO route).** The activity procedures are auto-discoverable only through the one-line **`workflow:methodology`** pointer (this kit + the engine carry `disable-model-invocation:true`, so NL like "write a plan" does **not** auto-load this skill). On a deployment whose methodology pointer was cap-soft-skipped — or whose pre-existing customized pointer lacks the procedures clause — the procedures are still reachable by **explicitly** invoking `/agent-workflow-kit procedures`; surface that plainly rather than treating it as a gap.
46
+ **Cap-soft-skip degradation (the feature's only AUTO route).** The activity procedures are auto-discoverable only through the one-line **`workflow:methodology`** pointer (this kit + the engine carry `disable-model-invocation:true`, so NL like "write a plan" does **not** auto-load this skill). On a deployment whose methodology pointer could not fit the line cap, the procedures are still reachable by **explicitly** invoking `/agent-workflow-kit procedures`; surface that plainly rather than treating it as a gap.
47
47
 
48
48
  **Invariants:** read-only · never writes · never commits · never runs a subscription CLI · the deterministic resolution is the kit's, the recipe execution is the orchestrator's.
@@ -46,7 +46,7 @@ A variant's posture note, where its key has one, is printed by `init` from this
46
46
  - `mcp-channel` — the offer is to REGISTER the kit's read-only stdio MCP server in this project on the harness lane: a registration is a command your MCP client will RUN. The agent applies it on the chat yes after the check; `init` previews the exact entry and applies it on the terminal y as the route the user may take instead. What the registration buys: path questions and literal searches become typed tool calls whose arguments are named JSON fields instead of a string handed to a shell, so a pipe, a redirect or a quote inside a pattern or a path stays DATA and is never interpreted. Posture: the server is a **read-only child of your client** (path/type/size/line facts and literal search over this project root; no write and no exec API), and like the client itself it runs **outside the Bash sandbox** — the sandbox is not what bounds it, the server's own root containment is. The two allow rules it adds make those two tools promptless and nothing else. The **`.differing`** arm is also a harness item: an `agent-workflow` entry already stands in `.mcp.json` and **structurally differs** from what this kit copy would write (another kit copy, a hand-edited path, an added `env`; the comparison ignores key order, so re-serialized identical bytes are the same registration). The check shows the entry standing in `.mcp.json` and the entry it would write; the chat yes confirms the replacement. `init` previews `mcp --replace` and replaces only on the terminal y. Stated limit: this item does **not** detect a `disabledMcpjsonServers` veto, so a converged `mcp-channel` means *what the mode writes is in place*, not *the client will load it* — see `${CLAUDE_SKILL_DIR}/references/modes/mcp.md`. Risk profile: a new read-only channel your client will launch; no write or exec exposure; a differing registration is replaced only on the checked chat yes or the terminal y and every other declaration is kept.
47
47
  - ADDITIONAL `gates-inert` arms (the third outcomes) — two further arms, and they differ in whether anything is BROKEN. **`producer-unrecognized`** — a checker with no producer anywhere in the declaration, on a tracked tree the changed-line coverage domain cannot reach (`.ts`/`.tsx`/`.jsx`/`.mts`/`.cts` strictly outnumber `.mjs`/`.cjs`/`.js`): the dead pair is real, so this arm is a user item, the user's own step, and the two remedies are marking the real producer with `"lcovProducer": true` or dropping the checker. Never a `node --test` prescription, the fill preview or an acknowledgement — a dead pair is broken, not narrow. **`coverage-domain-narrow`** — the producer/checker pair IS live and the tree is still dominated by what the domain excludes: nothing is broken, and the honest sentence is that certification covers the assessable minority. Its apply is the consent-gated **ack writer** preview (a NEUTRAL fingerprint into `docs/ai/acks.json` as `coverageDomainAck`, never a security key); after the SAME confirmation you run the `--apply` it prints. The fingerprint binds the FACT — the verdict plus the unsupported extensions present, never the file counts — so an acknowledged project stays quiet as it grows and re-fires when a new unsupported language arrives or the verdict flips. The census reads the TRACKED tree with a read-only `git ls-files`; a tree it cannot read (a non-git deployment) becomes a stated skip. Risk profile: no enforcement change of any kind — one acknowledgement recorded in a family-owned file, and one edit that is the user's own step.
48
48
  - `spec-adoption` — the feature-spec layer's ADOPTION STATE, judged from `docs/ai/specs/` alone through the same census `spec-check --all` runs, so a store the checker would refuse to observe is never counted here either. Both arms are OFFERS (`optional`) — the layer is opt-in, and `attention` stays reserved for a configured declaration that is broken. **`not-adopted`** (no store): every plan then cites zero governing specs by default and nothing says adoption never started; its apply is the spec-layer ensure one-liner (`ensure-configs --reconcile --only specs`, the same seed `upgrade` runs — it seeds the reader/checker pairs and the store root, and skips with a stated reason where no Node evidence exists), and its `recipe:` line carries the decline alternative — the DECLINE preview (`ack-write --lane spec-adoption`, a dry-run that prints the exact `--apply`), which records `specAdoptionAck` in the family-owned `docs/ai/acks.json`. **The two are exclusive, and the order is part of the contract:** ask which the user wants, apart, BEFORE the confirmation; on "seed" run the apply; on "decline" the agent records it — the preview line, then on that same answer its printed `--apply`; never run the seed after a decline, nor the decline after the seed. **`adopting`** (a store with no live contract): an optional item naming the draft count; its apply is that same decline preview (a dry-run; after the SAME confirmation you run the `--apply` it prints), and the honest remedy is authoring a contract from the skill's `SPEC_TEMPLATE.md`. A recorded decline silences BOTH arms and shows on `status` as ` — declined`; one live contract makes the decline moot. An unreadable store is a stated skip, never `flow optimal`. Risk profile: the seed writes create-only files under `scripts/` and `docs/ai/specs/` and refreshes a script body a release shipped; it writes an edited spec-layer file with the bundled body with no question, its line naming where an edit meant to last goes; the decline writes one key into the ack store; nothing here authors a spec or blocks a plan.
49
- - `profile-gap` — each item's apply is a PREVIEW that writes nothing, and consent takes two steps: the confirmed pick runs the preview and you relay every line it prints (the environment-resolved slot values, each checker `entry:` line with its trust-chain disclosure, a Communication region the insert plans in the same run); the same line with ` --apply` appended runs only on a SECOND yes over those lines, never carried by the first. Items whose apply lines are byte-equal are one writer and take one answer: the tier preview's `--apply` writes the absent slots, the store seed and the queue seed together; the checker verb writes only its own entries; the insert writes every region it plans, all or nothing, so a `communication-absent` skip beside a declined `story-sessions-section` gets its own ask after the insert's full preview. A no records nothing and the item stays on the screen. A DECLINE is asked apart from later, before anything runs, and runs `node ${CLAUDE_SKILL_DIR}/tools/tier-preview.mjs --decline --cwd <project-root>` only when the user refuses EVERY item the tier preview then reports offered: it records each of them at the shipped lineage, and a declined item leaves the screen until a lineage step changes the profile. An undecidable entry is a stated skip naming its reason, the remedy by reason: a prior → the upgrade's `lens` reconcile; an absent region → the insert; a customized region → a hand edit only (the lens preserves it), so that skip stands and withholds `flow optimal`. Risk profile: the tier preview's `--apply` rewrites `docs/ai/orchestration.json` in canonical form with the `_README` note and creates `docs/ai/epics/.gitkeep` and `docs/plans/queue.md` create-only; the insert adds regions to `docs/ai/agent_rules.md`; the checker verb adds entries to the PRIVILEGED `docs/ai/gates.json`; the decline writes `docs/ai/profile-declines.json`; nothing here commits.
49
+ - `profile-gap` — each item's apply is a PREVIEW that writes nothing, and consent takes two steps: the confirmed pick runs the preview and you relay every line it prints (the environment-resolved slot values, each checker `entry:` line with its trust-chain disclosure, a Communication region the insert plans in the same run); the same line with ` --apply` appended runs only on a SECOND yes over those lines, never carried by the first. Items whose apply lines are byte-equal are one writer and take one answer: the tier preview's `--apply` writes the absent slots, the store seed and the queue seed together; the checker verb writes only its own entries; the insert writes every region it plans, all or nothing, so a `communication-absent` skip beside a declined `story-sessions-section` gets its own ask after the insert's full preview. A no records nothing and the item stays on the screen. A DECLINE is asked apart from later, before anything runs, and runs `node ${CLAUDE_SKILL_DIR}/tools/tier-preview.mjs --decline --cwd <project-root>` only when the user refuses EVERY item the tier preview then reports offered: it records each of them at the shipped lineage, and a declined item leaves the screen until a lineage step changes the profile. An undecidable entry is a stated skip naming its reason, the remedy by reason: a prior or any other body → the upgrade's `lens` reconcile, which writes the region current or names the line cap that refused the write; an absent region → the insert. Risk profile: the tier preview's `--apply` rewrites `docs/ai/orchestration.json` in canonical form with the `_README` note and creates `docs/ai/epics/.gitkeep` and `docs/plans/queue.md` create-only; the insert adds regions to `docs/ai/agent_rules.md`; the checker verb adds entries to the PRIVILEGED `docs/ai/gates.json`; the decline writes `docs/ai/profile-declines.json`; nothing here commits.
50
50
  - `jev-connect` — the lane is user and env-dependent: the connect command is the user's own step in a terminal of their own, where it asks for the key; the key never reaches the agent or the chat (the command refuses without a terminal, and a terminal is not consent). When the recipe line opens with `run the apply in <place>`, that place is the terminal to run it in; `init`, run there, offers the command on its own consent line. The command reads the key with no echo, makes one network call to api.typesafe.ai with the vendor's sample text only on the user's own run, and writes the key in plain text — as managed export lines in the shell's startup files (bash: ~/.bashrc and the login file, created as ~/.bash_profile when none exists; zsh: ~/.zshrc), as the kit's own file ~/.config/fish/conf.d/typesafe-api-key.fish for fish, or on Windows as the user environment variable TYPESAFE_API_KEY, stored in the Windows user environment; a process already running at the save can keep its old environment and hand it to what it starts — the guide's key mark confirms the agent sees it (a file is readable by any process running as that user, and by other local accounts when one is world-readable in a traversable home); the vendor keeps data under its processing agreement and offers zero retention only to enterprise accounts. The item reads the environment the agent's commands run in: a host setting that filters it shows the item while the key is set in the user's shell. The decline alternative rides the recipe line, asked apart BEFORE the confirmation (the `spec-adoption` order): on "connect" hand over the apply line; on "decline" the agent records it — the recipe line's preview, then its printed `--apply` — per project as `jevConnectAck` in `docs/ai/acks.json`. Risk profile: a plain-text key in the user's startup files or the Windows user environment, written by a command the user runs; one network call from that run.
51
51
  - `jev-skill` — two arms, both env-dependent. The offer `jev-skill`, lane harness, shows once `TYPESAFE_API_KEY` is set and no decline is recorded, while no skill root holds a copy at a kit pin and a root the kit fills is absent: the agent applies it on the chat yes after the check, showing the files it would write; it changes no harness setting. `init` applies it on the batch terminal yes as the route the user may take instead. When the recipe line opens with `run the apply in <place>`, that place is where a user who prefers their own terminal runs it. The kit item `jev-skill.not-current`, lane kit, shows beside a copy at a kit pin in any root: the kit route applies it with no question, writing every root absent or behind the kit's pin. The skill is third-party text — the vendor's, MIT — that the kit ships pinned and installs as a verified copy into three agent skill roots: `~/.agents/skills`, the Claude Code skills dir (`CLAUDE_CONFIG_DIR` or `~/.claude`) and `~/.gemini/config/skills`. The copy is written current with no question beside a copy at a kit pin; a foreign copy is left untouched and named on the recipe line. A copy the vendor's `skills` CLI wrote with the same bytes reads current, accepts the component and is written at a later pin like a kit copy; a vendor plugin install is invisible to the file check, so the Claude Code root may read absent while the plugin serves it. Only when the user asks to see the plan does the agent run the command without `--apply` (a read-only dry run). The decline alternative rides the offer's recipe line, asked apart BEFORE the confirmation: on "install" run the check line and, on the yes given on its result, the apply line by the consent route; on "decline" the agent records it — the recipe line's preview, then its printed `--apply` — per project as `jevSkillAck` in `docs/ai/acks.json`. Risk profile: third-party text written into the user's agent skill roots by the kit's skill command; no network.
52
52
 
@@ -10,26 +10,26 @@ Requires: ${CLAUDE_SKILL_DIR}/references/shared/report-footer.md · ${CLAUDE_SKI
10
10
  2. **Never-downgrade gate — FIRST, before any write.** Compare the stamp to the **deployment-lineage head** (`4.0.0` — NOT this kit's package version). If the stamp is **greater than the head** or unparseable → **STOP and report**; do not touch a newer / unknown deployment at all (not even the methodology slot). This STOP is one of the few places the number is actionable (*Version disclosure* in `${CLAUDE_SKILL_DIR}/references/shared/report-footer.md`): show the user **the `docs/ai` structure version** their deployment carries versus the one this kit expects, plus the plain one-line two-axes note — naming it the structure version, **never** "lineage head".
11
11
  3. **The step-3 run-list — stamp-independent reconciles, BEFORE the equal-head short-circuit.** Reached only when the stamp **≤ head**. Run the **eight operations below in order, on every upgrade** (equal-head too) — no lineage-head bump, no migration file. Each backticked id anchors its rationale block below the checklist; a consent marker is a CONDITIONAL gate — an explicit yes is required exactly where the row's clause states one:
12
12
 
13
- 1. `pointers` — `node ${CLAUDE_SKILL_DIR}/tools/inject-methodology.mjs reconcile <project>/AGENTS.md` → per pointer: added · already present · skipped (reported) · a hard STOP; per Memory Map row of a rules theme: added · already present · refreshed · skipped (reported).
13
+ 1. `pointers` — `node ${CLAUDE_SKILL_DIR}/tools/inject-methodology.mjs reconcile <project>/AGENTS.md` → per pointer: added · already present · written over a different one · skipped (reported) · a hard STOP; per Memory Map row of a rules theme: added · already present · refreshed · skipped (reported) · written.
14
14
  2. `footprint` — `node ${CLAUDE_SKILL_DIR}/tools/hide-footprint.mjs --dir <project> --reconcile --dry-run` → visibility: visible · ambiguous · hidden — consent (conditional): ambiguous → ask which it is BEFORE anything; hidden → the conditional re-run without `--dry-run` (its surfaced paths ask per bootstrap step 9).
15
15
  3. `configs` — `node ${CLAUDE_SKILL_DIR}/tools/ensure-configs.mjs --reconcile --cwd <project>` → one line per ensure: `seeded` / `note-refreshed` / `refreshed` / `regenerated` / `pending` / `already-current` / `customized-preserved` / `malformed-preserved` / `already-present` / `not-placed` / `skipped-no-node-evidence` / `failed`.
16
16
  4. `gates-migration` — `node ${CLAUDE_SKILL_DIR}/references/scripts/migrate-gates.mjs --kit-tools ${CLAUDE_SKILL_DIR}/tools --cwd <project>` → the preview plan · INERT checker · CUSTOMIZED entries, each named — consent: apply only on an explicit yes, re-run with `--apply`.
17
17
  5. `bridges` — `node ${CLAUDE_SKILL_DIR}/tools/setup-backends.mjs --refresh-placed` → per-bridge lines: refreshed · already current · skipped — with its stated reason (not placed / newer than the bundle / unsupported host) · `skipped-readonly` · could not refresh.
18
- 6. `lens` — `node ${CLAUDE_SKILL_DIR}/tools/lens-region.mjs reconcile <project>/docs/ai/agent_rules.md` → per section: refreshed · already current · custom edit preserved · file absent / engine too old — skipped · over the line cap — refused · section absent — noted · a fully absent/invalid engine → hard STOP.
18
+ 6. `lens` — `node ${CLAUDE_SKILL_DIR}/tools/lens-region.mjs reconcile <project>/docs/ai/agent_rules.md` → per section: refreshed · already current · differing body written · file absent / engine too old — skipped · over the line cap — refused · section absent — noted · a fully absent/invalid engine → hard STOP.
19
19
  7. `tier` — `node ${CLAUDE_SKILL_DIR}/tools/tier-preview.mjs --cwd <project>` → per gap: present · offered · declined · undecidable · applied · recorded · refused — consent: one ask, only when offered.
20
20
  8. `bridge-settings` — `node ${CLAUDE_SKILL_DIR}/tools/bridge-settings.mjs --reconcile` → outcome line(s), pasted verbatim: ok · absent · flagged · duplicates · unusable.
21
21
 
22
- **`pointers` — the bounded pointers.** ONE call reconciles **three** pointers — the **workflow-methodology** pointer, the **orchestration-recipes** pointer (Solo / Reviewed / Council / Delegated / Subagent, routing to `/agent-workflow-kit recipes`) right below it, and the **autonomy-policy** pointer (the `docs/ai/autonomy.json` read contract, routing to `/agent-workflow-kit set-autonomy`) below that — and is filled on **every** upgrade, idempotently (zero-diff when all are already present + filled and the Memory Map rows present), so even a legacy or current equal-head deployment gains them **without a lineage-head bump or a migration** (the `agent-workflow-memory` **package** template did get docs-only headroom trims for the chained pointers, but no deployed-`docs/ai` structure changed). Per slot it inserts an empty pair at its anchor if absent, preserves a customized pair verbatim, and STOPs (never edits) on a malformed pair, a missing / duplicate anchor, or **when a fill is needed but the installed `agent-workflow-engine` is absent/invalid** (the fragments are read live from it — see the distinct outcomes below). The same call keeps one Memory Map row per project-rules theme, after the `docs/ai/agent_rules.md` row; one it cannot place is skipped and reported, never a STOP.
22
+ **`pointers` — the bounded pointers.** ONE call reconciles **three** pointers — the **workflow-methodology** pointer, the **orchestration-recipes** pointer (Solo / Reviewed / Council / Delegated / Subagent, routing to `/agent-workflow-kit recipes`) right below it, and the **autonomy-policy** pointer (the `docs/ai/autonomy.json` read contract, routing to `/agent-workflow-kit set-autonomy`) below that — and is filled on **every** upgrade, idempotently (zero-diff when all are already present + filled and the Memory Map rows present, each with the current text), so even a legacy or current equal-head deployment gains them **without a lineage-head bump or a migration** (the `agent-workflow-memory` **package** template did get docs-only headroom trims for the chained pointers, but no deployed-`docs/ai` structure changed). Per slot it inserts an empty pair at its anchor if absent, writes a pair holding other text with the current pointer, no question and no copy kept, its line naming the route — text of your own goes outside the two `<!-- workflow: -->` comment lines around each pointer — and STOPs (never edits) on a malformed pair or a missing / duplicate anchor. The installed `agent-workflow-engine` is read for every pointer the run judges (the fragments live there — see the distinct outcomes below), and an absent/invalid one STOPs also when every pointer is filled. The same call keeps one Memory Map row per project-rules theme, after the `docs/ai/agent_rules.md` row: a row with other text is written current, its line naming the route — a row of your own goes on a line of its own, its first cell a path of your own; one it cannot place is skipped and reported, never a STOP.
23
23
 
24
24
  **Classify the exit — there are THREE non-zero exits + soft in-band skips; handle each differently:**
25
25
 
26
- (a) **Soft, reported skip of a CHAINED pointer — orchestration and/or autonomy (CONTINUE the upgrade).** The chained pointers are the less-critical ones; when one can't be added right now `reconcile` exits **zero**, keeps every prior fill, and **reports each skip on stdout** (the `… skipped …` line) — never silent (Hard Constraint). Three reasons: **(i)** the prior pointers fit but adding this one would push the file past the `AGENTS.md` 100-line cap; **(ii)** the installed `agent-workflow-engine` is **present but too old** to ship that fragment (`<1.2.0` lacks the recipes one; every engine before the autonomy release lacks the autonomy one) — it can still supply the earlier pointers, so only that pointer is withheld; or **(iii)** — autonomy only — its **anchor is absent** because the orchestration pair is itself absent or was skipped, so the autonomy pointer has nowhere to chain (add the orchestration pointer first, then re-run). Report it in the successful-exit report (**step 4** equal-head, else **step 8**) in plain language, e.g. *"The orchestration-recipes / autonomy pointer wasn't added — the entry point is at its 100-line limit / your methodology engine is older than that feature. The recipes stay available via `/agent-workflow-kit recipes` and the autonomy policy via `/agent-workflow-kit set-autonomy`; to add the pointer, trim the entry point and/or refresh the engine with `npx @sabaiway/agent-workflow-engine@latest init`, then re-run upgrade."* (The separate case where the **methodology** pointer ITSELF can't fit the cap is a non-zero exit that changes nothing — continue without the pointers, same plain-language framing.) A skipped Memory Map row is its own clause, never a pointer skip: report it as step 4 words the rows.
26
+ (a) **Soft, reported skip of a CHAINED pointer — orchestration and/or autonomy (CONTINUE the upgrade).** The chained pointers are the less-critical ones; when one can't be brought current right now `reconcile` exits **zero**, writes the earlier pointers' results, and **reports each skip on stdout** (the `… skipped …` line) — never silent (Hard Constraint). Three reasons: **(i)** the prior pointers fit but adding or writing this one would push the file past the `AGENTS.md` 100-line cap; **(ii)** the installed `agent-workflow-engine` is **present but too old** to ship that fragment (`<1.2.0` lacks the recipes one; every engine before the autonomy release lacks the autonomy one) — it can still supply the earlier pointers, so only that pointer is not current; or **(iii)** — autonomy only — its **anchor is absent** because the orchestration pair is itself absent or was skipped, so the autonomy pointer has nowhere to chain (add the orchestration pointer first, then re-run). Report it in the successful-exit report (**step 4** equal-head, else **step 8**) in plain language, e.g. *"The orchestration-recipes / autonomy pointer wasn't added — the entry point is at its 100-line limit / your methodology engine is older than that feature. The recipes stay available via `/agent-workflow-kit recipes` and the autonomy policy via `/agent-workflow-kit set-autonomy`; to add the pointer, trim the entry point and/or refresh the engine with `npx @sabaiway/agent-workflow-engine@latest init`, then re-run upgrade."* (The separate case where the **methodology** pointer ITSELF can't fit the cap is a non-zero exit that changes nothing — continue without the pointers, same plain-language framing.) A skipped Memory Map row is its own clause, never a pointer skip: report it as step 4 words the rows.
27
27
 
28
28
  (b) **Malformed pair / missing-or-duplicate anchor (any pointer) — a hard STOP (do NOT continue).** A non-zero exit whose message names a marker/anchor problem; never soft-skip it. (The one deliberate exception is (a)(iii): the autonomy pointer's ABSENT anchor is the chained soft skip, exit zero — a reported skip, not this STOP.)
29
29
 
30
- (c) **`methodology engine not found/invalid …` — a hard STOP (do NOT continue).** A fill was needed but the installed `agent-workflow-engine` is **fully absent/invalid** — it can supply **no** fragment (distinct from (a)(ii), where the engine is valid but merely too old for a chained one). Report it in plain language with the one-line install command `npx @sabaiway/agent-workflow-engine@latest init` (or note that `npx @sabaiway/agent-workflow-kit@latest init` installs the engine for you), then re-run upgrade once it is present. **Never** treat (c) as a soft-skip (a) — mis-handling it would silently drop a pointer (a no-silent-failures violation). (b) and (c) STOP the upgrade; only (a) continues.
30
+ (c) **`methodology engine not found/invalid …` — a hard STOP (do NOT continue).** The engine is read for every pointer the run judges, so a **fully absent/invalid** installed `agent-workflow-engine` STOPs also when every pointer is filled — it can supply **no** fragment (distinct from (a)(ii), where the engine is valid but merely too old for a chained one). Report it in plain language with the one-line install command `npx @sabaiway/agent-workflow-engine@latest init` (or note that `npx @sabaiway/agent-workflow-kit@latest init` installs the engine for you), then re-run upgrade once it is present. **Never** treat (c) as a soft-skip (a) — mis-handling it would silently drop a pointer (a no-silent-failures violation). (b) and (c) STOP the upgrade; only (a) continues.
31
31
 
32
- **No-Node project:** the fragments live only in the **installed `agent-workflow-engine`** (`references/methodology-slot.md` + `references/orchestration-slot.md` + `references/autonomy-slot.md`, under `~/.claude/skills/agent-workflow-engine` or `$AGENT_WORKFLOW_ENGINE_DIR`) — there is no bundled copy, and a No-Node host cannot run the `npx` engine install. Open `AGENTS.md` and classify **each** pointer by hand: a **filled / customized** pair → leave it verbatim (no engine needed); a **malformed** pair (not exactly one ordered `start → end`) → STOP, do not edit. A pair that needs filling — **absent markers OR a present-but-empty pair** — needs the engine's fragment, so: if the engine is **not installed**, that pointer **cannot be added** — report it plainly (the methodology is already in `docs/ai/agent_rules.md`; the recipes are available via `/agent-workflow-kit recipes`; the autonomy policy via `/agent-workflow-kit set-autonomy`; install the engine to add the pointers). If the engine **is** present, **count the lines first** — if adding/filling would take the file over 100 lines, **skip that pointer and report the skip** (methodology first, then orchestration, then autonomy; each chained pair sits right under the previous pair's end marker). Fill each empty pair from its engine fragment (`methodology-slot.md` / `orchestration-slot.md` / `autonomy-slot.md`) — never inline a copy (that would re-create the retired mirror).
32
+ **No-Node project:** the fragments live only in the **installed `agent-workflow-engine`** (`references/methodology-slot.md` + `references/orchestration-slot.md` + `references/autonomy-slot.md`, under `~/.claude/skills/agent-workflow-engine` or `$AGENT_WORKFLOW_ENGINE_DIR`) — there is no bundled copy, and a No-Node host cannot run the `npx` engine install. Open `AGENTS.md` and classify **each** pointer by hand: a **malformed** pair (not exactly one ordered `start → end`) → STOP, do not edit. If the engine is **not installed**, no pointer is brought current this run — report it plainly (the methodology is already in `docs/ai/agent_rules.md`; the recipes are available via `/agent-workflow-kit recipes`; the autonomy policy via `/agent-workflow-kit set-autonomy`; install the engine to bring the pointers current), and the upgrade continues. If the engine **is** present, judge each pair against its engine fragment (`methodology-slot.md` / `orchestration-slot.md` / `autonomy-slot.md`): the same text → nothing to do; absent markers, an empty pair or other text → the fragment goes between the markers. **Count the lines first** — if a write would take the file over 100 lines, **skip that pointer and report the skip** (methodology first, then orchestration, then autonomy; each chained pair sits right under the previous pair's end marker). Never inline a copy (that would re-create the retired mirror).
33
33
 
34
34
  **`footprint` — hidden-mode footprint reconcile (D9 / AD-014).** A deployment does not record whether it chose `hidden`, so first **infer visibility** — the dry-run writes **zero bytes** and reports one of — **visible** (the entry point is tracked) → nothing to do; **ambiguous** (untracked but not ignored — could be a fresh uncommitted repo, or a hide that broke) → **ASK** the user which it is, never guess; **hidden** → re-run without `--dry-run` to migrate any older **machine-global** hide to the **project-local** `.git/info/exclude` (one managed block; folds in the legacy `.claude/skills/` line), idempotently (a clean re-run is zero-diff). Handle its surfaced paths exactly as bootstrap step 9 (`${CLAUDE_SKILL_DIR}/references/modes/bootstrap.md`) (already-committed → show `git rm --cached`, ask before `--include`; generic-name present file → ask; **a leftover machine-wide ignore block is kept + reported — the advisor's `footprint-global` item removes it**). This runs on **every** hidden upgrade, like the methodology slot — no lineage-head bump, no migration file.
35
35
 
@@ -77,18 +77,19 @@ Requires: ${CLAUDE_SKILL_DIR}/references/shared/report-footer.md · ${CLAUDE_SKI
77
77
 
78
78
  **`lens` — agent-rules lens refresh.** Relay the outcome in plain
79
79
  language: the planning/review lens section was **refreshed** to
80
- the current canon · was **already current** · carries a **custom edit — preserved verbatim** (+
81
- its one-line note) · the **file is absent — skipped** · the **engine is too old — skipped**
80
+ the current canon · had a **differing body — written** with the canon, its line naming the
81
+ route: text of your own goes under a ### heading of its own, titled unlike the kit's sections ·
82
+ the **file is absent — skipped** · the **engine is too old — skipped**
82
83
  (refresh it with `npx @sabaiway/agent-workflow-engine@latest init`, then re-run) · **over the
83
84
  file's line cap — refused** (trim the file, re-run). The section is found by its heading — no
84
- markers; a renamed heading is preserved + noted. A fully absent/invalid engine is the same hard
85
+ markers; a renamed heading, no longer opening with the title words, is noted. A fully absent/invalid engine is the same hard
85
86
  STOP as (c). Exit 0 covers every soft outcome; only the STOP is non-zero. The same invocation
86
87
  also reconciles the **Communication (user-facing messages)** and **story-sessions** sections
87
88
  from the kit's own bundled template canon (no engine involved) — relay each section's line:
88
- *refreshed* / *already current* / *custom edit preserved + note* / *section absent — noted* /
89
+ *refreshed* / *already current* / *differing body written* / *section absent — noted* /
89
90
  *over the file's line cap — refused*; an unreadable bundled template canon is its own loud STOP
90
91
  naming the kit reinstall command.
91
- A doubled heading in any of the three sections is preserved with a note and no write.
92
+ A doubled heading in any of the three sections has nothing written.
92
93
  The **Communication and story-sessions** absent-section notes already carry the preview
93
94
  command: relay the printed note verbatim as the offer.
94
95
  Run the insert with `--apply` only on the user's explicit yes (the `tier` ask while `tier`
@@ -113,7 +114,7 @@ Requires: ${CLAUDE_SKILL_DIR}/references/shared/report-footer.md · ${CLAUDE_SKI
113
114
  **The LATE navigator finalizer — the AUTHORITATIVE run, after the last `docs/ai` mutation.** `lens` above rewrites `docs/ai/agent_rules.md`, so the step-3 index ensure is already behind by the time the run-list ends. Re-run that ONE op here, before the step-4 report: `node ${CLAUDE_SKILL_DIR}/tools/ensure-configs.mjs --reconcile --only index --cwd <project>`. Relay **this** line in the report (it supersedes the early one; an untouched tree changes nothing, a failure STOPs the upgrade like any other ensure). On the migrated path the same rung runs again at the END of step 7 — after the migrations, before the step-8 re-stamp.
114
115
  4. **Equal-head exit — a real successful-exit report, not a bare stop.** If the stamp **equals** the head, the lineage is up to date — but step 3 (the stamp-independent reconciles) ran first and may have changed things, so this is a proper exit report, not a no-op:
115
116
  - **A skip line that contradicts the observed tree is a FINDING, never pasted as neutral.** Every ensure skip names the fact it proved (the probes that answered absent); if the tree you can see disproves that reason — a "no Node" skip beside deployed Node scripts, a "not deployed" skip beside a stamped `docs/ai` — do not relay the line as an outcome: raise it in the report as a defect of the tool, with the contradicting fact named, and stop short of any step that would build on the skip.
116
- - **Report step 3's outcome in plain language** — for **each** `pointers` slot (workflow-methodology, orchestration-recipes and autonomy-policy) whether it was *added*, was *already present* (nothing changed), or was *skipped* (the soft-skip from step 3, with its reason — over the line limit / engine too old / the autonomy pointer's anchor absent), and each Memory Map row the same way (or *refreshed*); the **nine project-configuration ensure** (`configs`) lines exactly as the one ensure run composed them (the ensures and their outcome tokens are enumerated in step 3), each rendered in plain language: what was created, what was left exactly as the user wrote it, and — for a `failed` line — what stopped it; for the navigator, relay the **late** `--only index` line, not the early one; the **`gates-migration`** result — *nothing to migrate*, the shown plan *applied* on your explicit yes, or the plan *left unapplied* (consent not given), with any INERT checker or CUSTOMIZED entries named; the **placed-bridge refresh** (`bridges`) outcome — paste the tool's per-bridge lines verbatim (they are already plain: *refreshed* / *already current* / *skipped — not placed* / `skipped-readonly` with its re-scan verdict / *could not refresh* + recovery); the **agent-rules lens** (`lens`) outcome (*refreshed* / *already current* / *custom edit preserved + note* / *file absent* / *engine too old* / *over the line cap*) and the **Communication-section** outcome (its own set: refreshed / already current / custom preserved + note / section absent — noted / over the cap — refused) and the **story-sessions section** outcome (its own set: refreshed / already current / custom edit preserved + note / section absent — noted / over the file's line cap — refused); the **full-flow offer** (`tier`) lines; the **bridge-settings reconcile** (`bridge-settings`) outcome (paste the tool's line(s) verbatim); and, for a hidden deployment, whether the hidden-mode footprint (`footprint`) was *moved to project-local*, was *already project-local* (nothing changed), or needed a question (ambiguous visibility). Plain wording only — never the reconcile/slot/anchor/marker terms (the never-leak-kit-internals Gotcha — `${CLAUDE_SKILL_DIR}/references/shared/deploy-tail.md`).
117
+ - **Report step 3's outcome in plain language** — for **each** `pointers` slot (workflow-methodology, orchestration-recipes and autonomy-policy) whether it was *added*, was *already present* (nothing changed), was *written over a different one* (its route: text of your own goes outside the two `<!-- workflow: -->` comment lines around each pointer), or was *skipped* (the soft-skip from step 3, with its reason — over the line limit / engine too old / the autonomy pointer's anchor absent), and each Memory Map row the same way (or *refreshed*), a *written* row with its route: a row of your own goes on a line of its own, its first cell a path of your own; the **nine project-configuration ensure** (`configs`) lines exactly as the one ensure run composed them (the ensures and their outcome tokens are enumerated in step 3), each rendered in plain language: what was created, what was left exactly as the user wrote it, and — for a `failed` line — what stopped it; for the navigator, relay the **late** `--only index` line, not the early one; the **`gates-migration`** result — *nothing to migrate*, the shown plan *applied* on your explicit yes, or the plan *left unapplied* (consent not given), with any INERT checker or CUSTOMIZED entries named; the **placed-bridge refresh** (`bridges`) outcome — paste the tool's per-bridge lines verbatim (they are already plain: *refreshed* / *already current* / *skipped — not placed* / `skipped-readonly` with its re-scan verdict / *could not refresh* + recovery); the **agent-rules lens** (`lens`) outcome (*refreshed* / *already current* / *differing body written*, its line naming the route: text of your own goes under a ### heading of its own, titled unlike the kit's sections / *file absent* / *engine too old* / *over the line cap*; a doubled heading has nothing written) and the **Communication-section** and **story-sessions section** outcomes (each its own set: refreshed / already current / differing body written / section absent — noted / over the file's line cap — refused); the **full-flow offer** (`tier`) lines; the **bridge-settings reconcile** (`bridge-settings`) outcome (paste the tool's line(s) verbatim); and, for a hidden deployment, whether the hidden-mode footprint (`footprint`) was *moved to project-local*, was *already project-local* (nothing changed), or needed a question (ambiguous visibility). Plain wording only — never the reconcile/slot/anchor/marker terms (the never-leak-kit-internals Gotcha — `${CLAUDE_SKILL_DIR}/references/shared/deploy-tail.md`).
117
118
  - **Never surface the structure number on this exit.** Whatever step 3 did, do **not** recite the `docs/ai` structure version, the internal versioning vocabulary, or the two-axes note here — the number is inert on an equal-head exit; it belongs to *Version disclosure* in `${CLAUDE_SKILL_DIR}/references/shared/report-footer.md` (shown at the never-downgrade STOP, the explicit status view, or on an explicit ask). Frame the success itself per the final bullet: if step 3 changed anything, say **what changed** in plain human terms; only a pure zero-diff no-op is *settings already current — no update needed*.
118
119
  - **Render the mandatory Recommendations section — on this exit too, BEFORE the footer.** Run `node ${CLAUDE_SKILL_DIR}/tools/recommendations.mjs --cwd <project-root>` and PRESENT its output — from the `## Recommendations (agent-workflow)` header — in the user's conversational language: every fact, count and item from the tool, nothing added or dropped; commands, paths, hosts and rule strings byte-exact; show the raw tool block on request. The section is present-even-when-empty (with everything optimal the body is exactly `no recommendations — flow optimal.`) and VERDICT-FIRST — the composed verdict line renders from the frozen templates `{K} item(s) need attention` / `nothing is broken` / `{N} optional recommendation(s), apply any you want` / `optimality NOT attested — {M} probe check(s) skipped`. Then apply each kit item by the kit route, with no question: its check line in the sandbox, then at once its apply line once outside it. Then OFFER the consent route: the user picks items in plain language; surface each picked item's posture note and get the explicit confirm; run its lane's rendered lines — chat: the one-liner; harness: the check line, then on the yes to its result the apply line; user: the user's own step — per the full consent route in `${CLAUDE_SKILL_DIR}/references/modes/recommendations.md`. Pinned order on this exit: Recommendations block → optional applies → report footer → the commit ask (the advisor/apply lane never lands after the commit ask).
119
120
  - **Recommendations lanes — both exits.** The four lanes (`chat`, `harness`, `kit`, `user`), the consent route and the kit route live in `${CLAUDE_SKILL_DIR}/references/modes/recommendations.md`; `init` stays a route the user may take.
@@ -23,25 +23,27 @@ exists, run ONE command — `node ${CLAUDE_SKILL_DIR}/tools/inject-methodology.m
23
23
  `/agent-workflow-kit recipes`) right below it, and the **autonomy-policy** pointer (the
24
24
  `docs/ai/autonomy.json` read contract) below that. Each is **one atomic operation per slot**:
25
25
  **ensure the slot exists**
26
- (insert an empty marker pair at its anchor when a legacy entry point lacks one) → **inject the bounded
27
- fragment ONLY IF the slot is empty** (a filled / user-customized slot is preserved verbatim) →
26
+ (insert an empty marker pair at its anchor when a legacy entry point lacks one) → **judge it against
27
+ the bounded fragment**: the same text needs no write; an empty slot is filled; any other text is
28
+ written with the fragment, no question and no copy kept, its line naming the route — text of your
29
+ own goes outside the two `<!-- workflow: -->` comment lines around each pointer →
28
30
  **cap-check** (each chained pointer's check runs on the file *after* the previous one, so it guards the
29
- **combined** ≤100-line budget). The fragments are short summary + pointer, read **live from the
31
+ **combined** ≤100-line budget). The same call writes a Memory Map row with other text current, its
32
+ line naming the route — a row of your own goes on a line of its own, its first cell a path of your
33
+ own. The fragments are short summary + pointer, read **live from the
30
34
  installed `agent-workflow-engine`** (`references/methodology-slot.md` + `references/orchestration-slot.md`
31
35
  + `references/autonomy-slot.md`,
32
36
  the family's one source of truth) — **not** a bundled mirror, and **not** the full references. The
33
- live read is **lazy + fail-loud**: the engine is consulted **only when a slot actually needs filling**,
34
- so a deployment with **all three** pointers filled and its Memory Map rows present reconciles to a
35
- zero-diff no-op even on a host without the engine (one still missing the autonomy pair needs the engine to gain it); when a fill
36
- **is** needed and the engine is **absent/invalid**, reconcile
37
- **STOPs** — report it in plain language with the one-line install command
37
+ live read is **fail-loud**: the engine is read for every pointer the run judges, so an
38
+ **absent/invalid** engine **STOPs** the reconcile also when every pointer is filled — report it in
39
+ plain language with the one-line install command
38
40
  `npx @sabaiway/agent-workflow-engine@latest init` (`npx @sabaiway/agent-workflow-kit@latest init`
39
41
  installs the engine for you; translate, never leak tool internals). Contract per slot: exactly one
40
42
  ordered `start → end` pair; a malformed slot (single, reversed, nested, duplicate) or a missing /
41
- duplicate anchor → **STOP with an error**, never edit (the file is left byte-for-byte unchanged). A
42
- **chained pointer is soft-skipped** (reported, never silent) when — and only when — adding it would
43
- exceed the 100-line cap, the engine is too old to ship its fragment, or (autonomy only) its anchor
44
- (the orchestration pair) is absent: every prior pointer still lands and the upgrade continues.
43
+ duplicate anchor → **STOP with an error**, never edit (nothing is written). A
44
+ **chained pointer is soft-skipped** (reported, never silent) when — and only when — adding or writing it
45
+ would exceed the 100-line cap, the engine is too old to ship its fragment, or (autonomy only) the
46
+ orchestration pointer was itself skipped this run: every prior pointer still lands and the upgrade continues.
45
47
 
46
48
  **Agent-rules lens + Communication refresh (runs in BOTH paths).** Its precondition is its own target file — run it
47
49
  only after `<project>/docs/ai/agent_rules.md` exists: after the substrate deploy in the
@@ -51,13 +53,15 @@ only after `<project>/docs/ai/agent_rules.md` exists: after the substrate deploy
51
53
  This is what converges a substrate seeded by an older memory — a lens section matching a known
52
54
  prior canonical body is refreshed from the installed engine; a current seed reports *already
53
55
  current* (zero-diff). Relay its outcome in plain language (*refreshed* / *already current* /
54
- *custom edit preserved + note* / *file absent — skipped* / *engine too old — skipped* / *over the
56
+ *differing body written* / *file absent — skipped* / *engine too old — skipped* / *over the
55
57
  line cap — refused*); a fully absent/invalid engine is the same loud STOP + one-line install
56
58
  command as the pointer reconcile. The same invocation also reconciles the **Communication
57
59
  (user-facing messages)** and **story-sessions** sections from the kit's own bundled template canon (no engine involved):
58
60
  a body matching the current canon is reported *already current*; a body matching a known prior
59
- is refreshed; a custom body is preserved + noted; an absent section is a stated note;
60
- an over-cap refresh is refused; and an unreadable bundled template canon is its own
61
+ is refreshed; any other differing body is written with the canon, its line naming the route: text
62
+ of your own goes under a ### heading of its own, titled unlike the kit's sections; a doubled
63
+ heading has nothing written; an absent section is a stated note;
64
+ an over-cap write is refused; and an unreadable bundled template canon is its own
61
65
  loud STOP naming the kit reinstall command. Relay both sections' outcome lines.
62
66
  The printed absent-section note already carries the preview command: relaying it is the offer.
63
67
  Run the insert with `--apply` only on the user's explicit yes.
@@ -76,7 +76,7 @@ Apply this as part of §2 before any user-facing summary:
76
76
  - **Two blocks for the user.** At a plan's approval, at a release and at every session close, the message BODY — above the closing state block — carries two short blocks in the dialogue language. *What was done, and for what*: per item the user-facing problem, then what now exists; a command name is allowed, an internal id is not. *What is next, and why*: each proposal names its benefit, plus the one hand step if any. No internal ids, no review-round tallies. The same two blocks are the handover's `## For the user` section, which the kit's `session-close-check` checker judges at the close, where the kit is installed.
77
77
 
78
78
  ### 2.6. Planning, review & process-fidelity invariants
79
- Apply these when authoring a plan, reviewing, folding a finding, or editing code — the layer read **before any code change**. (Full canon: the project's planning / workflow-methodology + orchestration canon. This section is rendered from that canon and refreshed on upgrade; a custom edit is preserved verbatim, but flagged.)
79
+ Apply these when authoring a plan, reviewing, folding a finding, or editing code — the layer read **before any code change**. (Full canon: the project's planning / workflow-methodology + orchestration canon. This section is rendered from that canon and written current on every upgrade; text of your own goes under a ### heading of its own, titled unlike the kit's sections.)
80
80
  - **Fold by code, not prose.** Before folding a code-touching finding into a plan or change, read the cited `file:line` and cite it — a prose fold drifts from the code and seeds the next bug.
81
81
  - **Finding scope (plan-execution) — name the invariant BEFORE the edit.** During EXECUTION only — a spec and its plan under authoring have no shipped behaviour to call a live defect in, so the spec review carries none of this. Every finding names the invariant its fix would enforce, and where that invariant already lives decides the disposition: already an acceptance criterion of the phase → **fold here**; it would have to be ADDED → ship the **narrow fix** for the found site (red first, then green) and queue ONLY the generalization — a deferral row carries the invariant, the origin `file:line`, the narrow fix, its proof and a residual exposure declared NOT live; no correct narrow fix → **blocking**: the phase does not close, and it is **never queued**. Two bars declared before each round: a finding counts only if it changes a **WRITE/REMOVE decision** or is a false statement in shipped text; a repeat finding in one subarea **routes to SUBTRACTION**, not a fourth patch.
82
82
  - **Right altitude.** Pin intent + invariants + acceptance criteria (named tests); leave fine code-mechanics to Execute, where prose cannot diverge from reality.
@@ -14,17 +14,17 @@
14
14
  // exactly one ordered start→end pair → replace only the bytes between them;
15
15
  // markers absent → ensure-insert an empty pair at the slot's anchor (or NO-OP in legacy inject);
16
16
  // any malformed state (single, reversed, nested, duplicate) → NO-OP WITH AN ERROR, never edit.
17
- // The live read is lazy + fail-loud: resolve+read the engine ONLY when a fill is actually needed, and
18
- // STOP loudly (never a silent fallback) when the engine is needed but absent/invalid.
17
+ // The live read is fail-loud: the engine is read for every slot the ensure can place (a filled slot
18
+ // cannot be judged without its fragment), and a needed-but-absent/invalid engine is a loud STOP.
19
19
  // Pure string functions (testable with byte-preservation fixtures); dependency-free, Node >= 22.
20
20
  //
21
- // Canonical-refresh (AD-025): reconcileMarkerSlot REFRESHES a filled slot ONLY when its content
22
- // normalize-matches a KNOWN PRIOR canonical fragment (drift-guarded, append-only per descriptor); a
23
- // customized slot never matches → preserved verbatim + a read-only upgrade advisory.
21
+ // The policy per slot (entry-pointers revision 1): content equal to the fragment is left, a KNOWN PRIOR
22
+ // canonical fragment (drift-guarded, append-only per descriptor) is refreshed, and any other content is
23
+ // written current with no question and no copy kept. Contract: docs/ai/specs/kit/install/entry-pointers.md.
24
24
 
25
25
  import { isDirectRun } from './direct-run.mjs';
26
26
  import { normalizeCanonical } from './orchestration-config.mjs';
27
- import { reconcileMemoryMapRows } from './project-rules/index.mjs';
27
+ import { reconcileMemoryMapRows, ROW_ROUTE } from './project-rules/index.mjs';
28
28
 
29
29
  export const START_MARKER = '<!-- workflow:methodology:start -->';
30
30
  export const END_MARKER = '<!-- workflow:methodology:end -->';
@@ -73,9 +73,8 @@ export const AUTONOMY_EMPTY_SLOT = `${AUTONOMY_START_MARKER}\n${AUTONOMY_END_MAR
73
73
 
74
74
  // ── known-prior canonical fragments (drift-guarded, APPEND-ONLY per slot) ───────
75
75
  // The EXACT content a PREVIOUS release's engine fragment shipped (what a filled slot would carry today).
76
- // reconcileMarkerSlot refreshes a filled slot to the current engine fragment IFF its content
77
- // normalize-matches one of these — so the install base gains a new clause without clobbering a
78
- // customization (which never matches). Any release that CHANGES an engine fragment must FIRST append the
76
+ // reconcileMarkerSlot words a filled slot's write as a refresh IFF its content normalize-matches one of
77
+ // these. Any release that CHANGES an engine fragment must FIRST append the
79
78
  // OUTGOING content here, so the immediately-previous deployments still match (a drift-guard test pins
80
79
  // current-minus-one → new). NEVER edit an existing entry — only append.
81
80
  export const KNOWN_PRIOR_METHODOLOGY_SLOT = [
@@ -100,9 +99,8 @@ export const KNOWN_PRIOR_ORCH_SLOT = [
100
99
  // A slot descriptor bundles everything the generic engine needs to operate on ONE marker pair.
101
100
  // `leadingBlank` controls whether the inserted empty pair gets a blank separator line above it — the
102
101
  // methodology insert keeps it (readability), the orchestration insert omits it to save a cap line
103
- // (the pair already sits right under the methodology block). `knownPriorCanonicals` drives the refresh;
104
- // `upgradeSignature` + `upgradeAdvice` drive the read-only advisory for a CUSTOMIZED (non-matching) slot
105
- // that predates the current clause.
102
+ // (the pair already sits right under the methodology block). `knownPriorCanonicals` words the refresh;
103
+ // `label` names the pointer in the reconcile line and the over-cap error.
106
104
  export const METHODOLOGY_DESCRIPTOR = {
107
105
  startMarker: START_MARKER,
108
106
  endMarker: END_MARKER,
@@ -110,11 +108,9 @@ export const METHODOLOGY_DESCRIPTOR = {
110
108
  emptySlot: EMPTY_SLOT,
111
109
  leadingBlank: true,
112
110
  markerName: 'methodology',
111
+ label: 'workflow-methodology',
113
112
  anchorLabel: 'methodology anchor (the "Read it before any code change." Session-Protocols line)',
114
113
  knownPriorCanonicals: KNOWN_PRIOR_METHODOLOGY_SLOT,
115
- upgradeSignature: 'feedback-triage, epic, task',
116
- upgradeAdvice:
117
- 'the workflow-methodology pointer predates the current canon — six named activities (plan-authoring, plan-execution, routine, feedback-triage, epic, task) with the communication-contract clause (deliver the artifact inline, lead with the result) — refresh it to the current canon, or add what it lacks by hand; the contract still applies.',
118
114
  };
119
115
  export const ORCHESTRATION_DESCRIPTOR = {
120
116
  startMarker: ORCH_START_MARKER,
@@ -123,11 +119,9 @@ export const ORCHESTRATION_DESCRIPTOR = {
123
119
  emptySlot: ORCH_EMPTY_SLOT,
124
120
  leadingBlank: false,
125
121
  markerName: 'orchestration',
122
+ label: 'orchestration-recipes',
126
123
  anchorLabel: 'orchestration anchor (the methodology end-marker line)',
127
124
  knownPriorCanonicals: KNOWN_PRIOR_ORCH_SLOT,
128
- upgradeSignature: '/agent-workflow-kit set-recipe',
129
- upgradeAdvice:
130
- 'the orchestration-recipes pointer predates the read-at-start clause — add "read `docs/ai/orchestration.json` at session start; set it with /agent-workflow-kit set-recipe", or set your preference now with /agent-workflow-kit set-recipe.',
131
125
  };
132
126
  // The autonomy-policy slot (AD-044 Plan 3) — first canon, so no known priors yet: any future
133
127
  // fragment change must append the outgoing content to a KNOWN_PRIOR_AUTONOMY_SLOT store first.
@@ -138,11 +132,9 @@ export const AUTONOMY_DESCRIPTOR = {
138
132
  emptySlot: AUTONOMY_EMPTY_SLOT,
139
133
  leadingBlank: false,
140
134
  markerName: 'autonomy',
135
+ label: 'autonomy',
141
136
  anchorLabel: 'autonomy anchor (the orchestration end-marker line)',
142
137
  knownPriorCanonicals: [],
143
- upgradeSignature: 'docs/ai/autonomy.json',
144
- upgradeAdvice:
145
- 'the autonomy pointer does not name the per-project policy file — add "read `docs/ai/autonomy.json` at session start; set it with /agent-workflow-kit set-autonomy", or refresh the slot to the current canon.',
146
138
  };
147
139
 
148
140
  // ── generic marker-slot engine (descriptor-parameterized) ──────────────────────
@@ -222,55 +214,40 @@ export const ensureMarkerSlot = (text, descriptor) => {
222
214
  return { status: 'inserted', text: out };
223
215
  };
224
216
 
225
- // Bootstrap/upgrade reconciliation policy (pure): ensure the slot exists, then fill it ONLY IF it
226
- // is empty (a filled/customized slot is preserved verbatim), enforcing the line cap — all as one step
227
- // the CLI commits with a single atomic write. On ANY error the INPUT bytes are returned unchanged.
217
+ // Bootstrap/upgrade reconciliation policy (pure): ensure the slot exists, then judge the bytes between
218
+ // its markers against `fragment`, enforcing the line cap — all as one step the CLI commits with a single
219
+ // atomic write. On ANY error the INPUT bytes are returned unchanged.
228
220
  // reconciled-inserted — slot was absent, inserted at the anchor, then filled.
229
221
  // reconciled-filled — slot existed but was empty, now filled.
230
222
  // reconciled-refreshed — slot was filled with a KNOWN PRIOR canonical → replaced with `fragment`.
231
- // present-filled — slot already carried CUSTOM content → preserved verbatim.
232
- // error — malformed slot, 0/>1 anchors, or cap exceeded → input unchanged.
223
+ // reconciled-written — slot held any other content → replaced with `fragment`.
224
+ // present-filled — slot already carries `fragment` → left, bytes unchanged.
225
+ // error — malformed slot, 0/>1 anchors, a blank fragment, or cap exceeded → input unchanged.
233
226
  export const reconcileMarkerSlot = (text, descriptor, fragment, { maxLines } = {}) => {
234
227
  const ensured = ensureMarkerSlot(text, descriptor);
235
228
  if (ensured.status === 'error') return { status: 'error', text, error: ensured.error };
229
+ if (fragment.trim() === '') return { status: 'error', text, error: `the ${descriptor.label} fragment is blank — refusing to write an empty pointer` };
236
230
  const current = extractMarkerSlot(ensured.text, descriptor);
237
- const isEmpty = current == null || current.trim() === '';
238
- if (!isEmpty) {
239
- // Canonical-refresh: a slot whose content normalize-matches a known prior canonical is STALE — replace
240
- // it with the current `fragment`. A customized slot never matches → preserved verbatim. (`fragment`
241
- // is empty for a customized slot — main() only sources it when markerSlotNeedsFill is true.)
242
- const priors = descriptor.knownPriorCanonicals ?? [];
243
- const matchesPrior = fragment && fragment.trim() !== '' && priors.some((p) => normalizeCanonical(p) === normalizeCanonical(current));
244
- if (matchesPrior) {
245
- const injected = injectIntoSlot(ensured.text, descriptor, fragment, { maxLines });
246
- if (injected.status !== 'injected') return { status: 'error', text, error: injected.error };
247
- return { status: 'reconciled-refreshed', text: injected.text };
248
- }
249
- if (maxLines != null && lineCount(ensured.text) > maxLines) {
250
- return { status: 'error', text, error: `AGENTS.md is ${lineCount(ensured.text)} lines (cap ${maxLines}) — trim the file (a customized ${descriptor.markerName} slot must still fit the cap)` };
231
+ let status = ensured.status === 'inserted' ? 'reconciled-inserted' : 'reconciled-filled';
232
+ if (current.trim() !== '') {
233
+ if (normalizeCanonical(current) === normalizeCanonical(fragment)) {
234
+ if (maxLines != null && lineCount(ensured.text) > maxLines) {
235
+ return { status: 'error', text, error: `AGENTS.md is ${lineCount(ensured.text)} lines (cap ${maxLines}) — trim the file (the current ${descriptor.label} pointer must still fit the cap)` };
236
+ }
237
+ return { status: 'present-filled', text: ensured.text };
251
238
  }
252
- return { status: 'present-filled', text: ensured.text };
239
+ const priors = descriptor.knownPriorCanonicals ?? [];
240
+ status = priors.some((p) => normalizeCanonical(p) === normalizeCanonical(current)) ? 'reconciled-refreshed' : 'reconciled-written';
253
241
  }
254
242
  const injected = injectIntoSlot(ensured.text, descriptor, fragment, { maxLines });
255
243
  if (injected.status !== 'injected') return { status: 'error', text, error: injected.error };
256
- const status = ensured.status === 'inserted' ? 'reconciled-inserted' : 'reconciled-filled';
257
244
  return { status, text: injected.text };
258
245
  };
259
246
 
260
- // Pure predicate (no fs): does this slot actually need its fragment? True only when the slot can be
261
- // ensured (present or insertable) AND is empty — i.e. when reconcileMarkerSlot would inject. Reuses
262
- // the SAME primitives as reconcileMarkerSlot, so the lazy "read the engine only when needed" guard in
263
- // main() cannot diverge from the actual fill decision.
264
- export const markerSlotNeedsFill = (text, descriptor) => {
265
- const ensured = ensureMarkerSlot(text, descriptor);
266
- if (ensured.status === 'error') return false;
267
- const current = extractMarkerSlot(ensured.text, descriptor);
268
- if (current == null || current.trim() === '') return true; // empty → fill
269
- // filled-but-STALE (content matches a known prior canonical) → needs a refresh, so main() must
270
- // re-source the fragment. A customized slot doesn't match → no source needed (preserved verbatim).
271
- const priors = descriptor.knownPriorCanonicals ?? [];
272
- return priors.some((p) => normalizeCanonical(p) === normalizeCanonical(current));
273
- };
247
+ // Pure predicate (no fs): can the ensure place this slot (present or insertable)? Every such slot is
248
+ // judged against its fragment, so main() reads the engine exactly when this is true. Reuses the SAME
249
+ // ensure as reconcileMarkerSlot, so the engine-read guard cannot diverge from the policy.
250
+ export const markerSlotEnsurable = (text, descriptor) => ensureMarkerSlot(text, descriptor).status !== 'error';
274
251
 
275
252
  // ── methodology-slot exports (delegate to the generic engine, byte-for-byte) ────
276
253
 
@@ -279,36 +256,9 @@ export const injectMethodology = (text, fragment, opts) => injectIntoSlot(text,
279
256
  export const extractSlot = (text) => extractMarkerSlot(text, METHODOLOGY_DESCRIPTOR);
280
257
  export const ensureSlot = (text) => ensureMarkerSlot(text, METHODOLOGY_DESCRIPTOR);
281
258
  export const reconcileSlot = (text, fragment, opts) => reconcileMarkerSlot(text, METHODOLOGY_DESCRIPTOR, fragment, opts);
282
- export const slotNeedsFill = (text) => markerSlotNeedsFill(text, METHODOLOGY_DESCRIPTOR);
283
-
284
- // The routing token the methodology pointer should carry so NL like "write a plan" auto-discovers the
285
- // activity procedures. A deployment whose methodology slot was filled (legacy / customized) BEFORE this
286
- // clause existed will NOT auto-receive it — reconcile preserves a filled slot verbatim (AD-019 §3.1a).
287
- export const PROCEDURES_POINTER = '/agent-workflow-kit procedures';
288
-
289
- // Read-only upgrade advisory (NO mutation): when the methodology slot is present + FILLED but lacks the
290
- // procedures route, return a one-line note the upgrade flow surfaces — add it for auto-discovery; the
291
- // feature is reachable now via the explicit command. Returns null for an absent / empty / malformed slot
292
- // or one that already routes to procedures. Pure; never edits the file.
293
- export const methodologyProceduresHint = (text) => {
294
- const content = extractSlot(text);
295
- if (content == null || content.trim() === '') return null; // only a FILLED methodology slot
296
- if (content.includes(PROCEDURES_POINTER)) return null; // already routes to the procedures advisor
297
- return `the methodology pointer has no procedures route — add "${PROCEDURES_POINTER} <activity>" for auto-discovery; the activity procedures are reachable now via ${PROCEDURES_POINTER}.`;
298
- };
299
259
 
300
- // Generic read-only upgrade advisory (AD-025; the §1.6a/§1.9 reach to CUSTOMIZED filled slots): a slot
301
- // that is present + FILLED but lacks the descriptor's current-canon `upgradeSignature` (and so could not
302
- // be canonical-refreshed — its content is customized) gets a one-line note the upgrade flow surfaces.
303
- // Returns null for an absent / empty / malformed slot, or one that already carries the signature. Pure;
304
- // never edits the file (a customization is never rewritten — only the user decides).
305
- export const markerSlotUpgradeHint = (text, descriptor) => {
306
- if (!descriptor.upgradeSignature) return null;
307
- const content = extractMarkerSlot(text, descriptor);
308
- if (content == null || content.trim() === '') return null; // only a FILLED slot
309
- if (content.includes(descriptor.upgradeSignature)) return null; // already carries the current clause
310
- return descriptor.upgradeAdvice;
311
- };
260
+ // The route the reconcile's pointer note names when it wrote a pointer over a different one.
261
+ export const POINTER_ROUTE = 'text of your own goes outside the two <!-- workflow: --> comment lines around each pointer';
312
262
 
313
263
  // A cap-refusal is a SOFT, reported skip (distinct from a malformed/anchor STOP) — keyed off the
314
264
  // stable "(cap N)" substring both cap messages carry, so the dual-slot reconcile can skip the
@@ -316,14 +266,26 @@ export const markerSlotUpgradeHint = (text, descriptor) => {
316
266
  const isCapRefusal = (errorMessage) => typeof errorMessage === 'string' && errorMessage.includes('(cap ');
317
267
  // The autonomy lane distinguishes the TWO cap messages "(cap " conflates (D4 cap-lane honesty):
318
268
  // only a FILL-overflow from an in-cap input (injectIntoSlot's "injection would push …") is the soft
319
- // skip — the pointer was genuinely withheld. An ALREADY-over-cap custom file (reconcileMarkerSlot's
269
+ // skip — the pointer was genuinely withheld. An ALREADY-over-cap file (reconcileMarkerSlot's
320
270
  // "AGENTS.md is N lines … trim the file") keeps its distinct over-cap report as a hard refusal,
321
271
  // never a mislabeled "skipped". Exported so the split is pinned against the real messages.
322
272
  export const isFillCapRefusal = (errorMessage) =>
323
273
  isCapRefusal(errorMessage) && errorMessage.includes('injection would push');
324
274
 
325
275
  const EXIT = Symbol('inject-methodology.exit');
326
- const ROW_WORDS = { inserted: 'added', kept: 'already present', refreshed: 'refreshed to the current text' };
276
+ const ROW_WORDS = { inserted: 'added', kept: 'already present', refreshed: 'refreshed to the current text', written: 'written with the current text' };
277
+ // The reconcile line's clause for a judged slot, by its status.
278
+ const describeSlot = (descriptor, status) => {
279
+ const pointer = `${descriptor.label} pointer`;
280
+ const where = descriptor === METHODOLOGY_DESCRIPTOR ? 'at the Session-Protocols anchor' : 'below it';
281
+ return {
282
+ 'reconciled-inserted': `inserted the ${pointer} ${where} and filled it`,
283
+ 'reconciled-filled': `filled the empty ${pointer}`,
284
+ 'reconciled-refreshed': `refreshed the ${pointer} to the current canon`,
285
+ 'reconciled-written': `wrote the current ${pointer} over a different one`,
286
+ 'present-filled': `${pointer} already present`,
287
+ }[status];
288
+ };
327
289
 
328
290
  // The return-code entry point (5.1): argv[] + injected env/home → { code, stdout, stderr }, no
329
291
  // process.argv / process.exit / console inside — an in-process caller is as hermetic as a spawned
@@ -362,11 +324,11 @@ export const runCli = async (argv, deps = {}) => {
362
324
  try {
363
325
  const text = await readFile(resolve(agentsPath), 'utf8');
364
326
 
365
- // Source a bounded fragment LAZILY, per slot. An explicit [fragment.md] arg (tests + manual) wins and
366
- // skips engine resolution entirely; it binds the METHODOLOGY slot only. Otherwise read it LIVE from
367
- // the installed engine (no bundled mirror) — readEngineFragment THROWS (never falls back) when the
368
- // engine is needed but absent/invalid; sourceFragmentOrStop turns that into a hard, loud STOP carrying
369
- // the install command. The caller only invokes this when a fill is actually needed (the laziness).
327
+ // Source a bounded fragment per slot. An explicit [fragment.md] arg (tests + manual) wins and skips
328
+ // engine resolution entirely; it binds the METHODOLOGY slot only. Otherwise read it LIVE from the
329
+ // installed engine (no bundled mirror) — readEngineFragment THROWS (never falls back) when the engine
330
+ // is needed but absent/invalid; sourceFragmentOrStop turns that into a hard, loud STOP carrying the
331
+ // install command. The caller invokes this for every slot the ensure can place.
370
332
  const sourceFragment = async (rel) => {
371
333
  if (explicitFragmentArg) return readFile(resolve(explicitFragmentArg), 'utf8');
372
334
  const { dir, source } = resolveEngineDir({ env, home });
@@ -383,10 +345,10 @@ export const runCli = async (argv, deps = {}) => {
383
345
  }
384
346
  };
385
347
 
386
- // The orchestration + autonomy fragments are the CHAINED (less-critical) pointers. Source each
387
- // lazily, but DISTINGUISH two failures keyed off the engine's own detection (not message text): an
388
- // engine that is VALID but simply TOO OLD to ship the requested fragment is a SOFT skip — the prior
389
- // fills are kept and the pointer is reported as withheld (parallel to the cap-skip); only a FULLY
348
+ // The orchestration + autonomy fragments are the CHAINED (less-critical) pointers. Source each, but
349
+ // DISTINGUISH two failures keyed off the engine's own detection (not message text): an engine that
350
+ // is VALID but simply TOO OLD to ship the requested fragment is a SOFT skip — the earlier slots'
351
+ // results are written and the pointer is reported as withheld (parallel to the cap-skip); only a FULLY
390
352
  // absent/invalid engine (it cannot supply ANY pointer) is a hard STOP. A read error on a PRESENT
391
353
  // fragment is a real corruption STOP, NEVER a "too old" skip (don't mislabel a current engine with
392
354
  // an unreadable fragment). Returns { fragment } on success, { skip } for the soft case, or
@@ -426,8 +388,8 @@ export const runCli = async (argv, deps = {}) => {
426
388
  };
427
389
 
428
390
  if (mode === 'reconcile') {
429
- // ── Slot 1: methodology (lazy engine read, then reconcile) ──
430
- const methFragment = slotNeedsFill(text) ? await sourceFragmentOrStop('reconcile STOP', ENGINE_FRAGMENT_REL) : '';
391
+ // ── Slot 1: methodology (the engine read for a slot the ensure can place, then reconcile) ──
392
+ const methFragment = markerSlotEnsurable(text, METHODOLOGY_DESCRIPTOR) ? await sourceFragmentOrStop('reconcile STOP', ENGINE_FRAGMENT_REL) : '';
431
393
  const methResult = reconcileSlot(text, methFragment, { maxLines: AGENTS_MD_CAP });
432
394
  if (methResult.status === 'error') {
433
395
  // cap-refusal OR malformed/anchor STOP — preserve the single-slot classification (SKILL.md
@@ -435,23 +397,13 @@ export const runCli = async (argv, deps = {}) => {
435
397
  logError(`[inject-methodology] reconcile refused — ${methResult.error}`);
436
398
  return result(1);
437
399
  }
438
- const afterMeth = methResult.text; // === text when the methodology slot was already filled (custom)
439
- const describeMeth = {
440
- 'reconciled-inserted': 'inserted the workflow-methodology pointer at the Session-Protocols anchor and filled it',
441
- 'reconciled-filled': 'filled the empty workflow-methodology pointer',
442
- 'reconciled-refreshed': 'refreshed the workflow-methodology pointer to the current canon',
443
- 'present-filled': 'workflow-methodology pointer already present',
444
- }[methResult.status];
445
- // Read-only upgrade advisories for a CUSTOMIZED methodology pointer that reconcile preserved verbatim
446
- // (a refreshed/filled/inserted slot already carries the current canon, so it gets none): the AD-019 procedures route
447
- // AND the current-canon hint, keyed on the six-activity token (it names the §1.9 clause too). No mutation — notes only.
448
- const notes = [];
449
- if (methResult.status === 'present-filled') {
450
- const p = methodologyProceduresHint(afterMeth); if (p) notes.push(p);
451
- const u = markerSlotUpgradeHint(afterMeth, METHODOLOGY_DESCRIPTOR); if (u) notes.push(u);
452
- }
453
- const reportNotes = () => {
454
- for (const n of notes) log(`[inject-methodology] note: ${n}`);
400
+ const afterMeth = methResult.text; // === text when the methodology slot was already current
401
+ const describeMeth = describeSlot(METHODOLOGY_DESCRIPTOR, methResult.status);
402
+ // One pointer note when a pointer was written over a different one; the row note follows it.
403
+ let pointerWritten = methResult.status === 'reconciled-written';
404
+ const reportNotes = (rowWritten = false) => {
405
+ if (pointerWritten) log(`[inject-methodology] note: ${POINTER_ROUTE}.`);
406
+ if (rowWritten) log(`[inject-methodology] note: ${ROW_ROUTE}.`);
455
407
  };
456
408
 
457
409
  // ── Explicit [fragment.md] binds methodology ONLY → skip the orchestration + autonomy reconciles ──
@@ -462,21 +414,22 @@ export const runCli = async (argv, deps = {}) => {
462
414
  }
463
415
  await writeAtomic(afterMeth);
464
416
  log(`[inject-methodology] reconcile: ${describeMeth}.`);
417
+ reportNotes();
465
418
  return result(0);
466
419
  }
467
420
 
468
421
  // ── Slot 2: orchestration, reconciled on the methodology-reconciled text (the cap-check then guards
469
- // the COMBINED ≤100). Lazy: the engine is read only when the orchestration slot needs filling. ──
422
+ // the COMBINED ≤100). The engine is read whenever the ensure can place the slot. ──
470
423
  let finalText = afterMeth;
471
424
  let describeOrch;
472
425
  let orchSkipped = false;
473
426
 
474
- const orchSource = markerSlotNeedsFill(afterMeth, ORCHESTRATION_DESCRIPTOR)
427
+ const orchSource = markerSlotEnsurable(afterMeth, ORCHESTRATION_DESCRIPTOR)
475
428
  ? await sourceChainedFragment(ORCHESTRATION_FRAGMENT_REL)
476
429
  : { fragment: '' };
477
430
  if (orchSource.skip) {
478
431
  // Engine too old to supply the recipes pointer → SOFT skip, parallel to the cap-skip: the
479
- // methodology fill is preserved and written; the recipes pointer is reported as withheld.
432
+ // methodology result is written; the recipes pointer is reported as withheld.
480
433
  orchSkipped = true;
481
434
  describeOrch = `orchestration-recipes pointer skipped — ${orchSource.skip}`;
482
435
  } else {
@@ -484,7 +437,7 @@ export const runCli = async (argv, deps = {}) => {
484
437
  if (orchResult.status === 'error') {
485
438
  if (isCapRefusal(orchResult.error)) {
486
439
  // SOFT skip — keep the methodology result, report the orchestration cap-skip loudly (not
487
- // silent). The methodology fill (if any) is preserved; the orchestration pointer is not added.
440
+ // silent); the orchestration slot is unchanged.
488
441
  orchSkipped = true;
489
442
  describeOrch = `orchestration-recipes pointer skipped — ${orchResult.error}`;
490
443
  } else {
@@ -494,27 +447,17 @@ export const runCli = async (argv, deps = {}) => {
494
447
  }
495
448
  } else {
496
449
  finalText = orchResult.text;
497
- describeOrch = {
498
- 'reconciled-inserted': 'inserted the orchestration-recipes pointer below it and filled it',
499
- 'reconciled-filled': 'filled the empty orchestration-recipes pointer',
500
- 'reconciled-refreshed': 'refreshed the orchestration-recipes pointer to the current canon',
501
- 'present-filled': 'orchestration-recipes pointer already present',
502
- }[orchResult.status];
503
- // §1.6a advisory: a CUSTOMIZED orchestration pointer preserved verbatim, lacking the read-at-start
504
- // clause, gets a read-only nudge (a refreshed/filled slot already carries it).
505
- if (orchResult.status === 'present-filled') {
506
- const u = markerSlotUpgradeHint(finalText, ORCHESTRATION_DESCRIPTOR);
507
- if (u) notes.push(u);
508
- }
450
+ describeOrch = describeSlot(ORCHESTRATION_DESCRIPTOR, orchResult.status);
451
+ pointerWritten ||= orchResult.status === 'reconciled-written';
509
452
  }
510
453
  }
511
454
 
512
455
  // ── Slot 3: autonomy, chained on the orchestration-reconciled text (same combined ≤100 guard).
513
- // D4 invariant: every failure lane SPECIFIC to this slot is a LOUD soft skip that preserves
514
- // the prior fills and exits 0 — (i) a too-old engine (no autonomy fragment), (ii) a
456
+ // D4 invariant: every failure lane SPECIFIC to this slot is a LOUD soft skip that writes the
457
+ // earlier slots' results and exits 0 — (i) a too-old engine (no autonomy fragment), (ii) a
515
458
  // fill-overflow cap refusal, (iii) an ABSENT anchor (the orchestration pair is absent or was
516
- // itself skipped above — a 0-anchors ensure error must not discard the methodology fill).
517
- // Malformed autonomy markers, an already-over-cap custom file, a present-but-unreadable
459
+ // itself skipped above — a 0-anchors ensure error must not discard the methodology result).
460
+ // Malformed autonomy markers, an already-over-cap file, a present-but-unreadable
518
461
  // fragment, and a fully absent/invalid engine stay hard STOPs. ──
519
462
  let describeAut;
520
463
  let autSkipped = false;
@@ -538,7 +481,7 @@ export const runCli = async (argv, deps = {}) => {
538
481
  describeAut =
539
482
  'autonomy pointer skipped — chained below the orchestration pointer, which was itself skipped this run; re-run once it lands';
540
483
  } else {
541
- const autSource = markerSlotNeedsFill(finalText, AUTONOMY_DESCRIPTOR)
484
+ const autSource = markerSlotEnsurable(finalText, AUTONOMY_DESCRIPTOR)
542
485
  ? await sourceChainedFragment(AUTONOMY_FRAGMENT_REL)
543
486
  : { fragment: '' };
544
487
  if (autSource.skip) {
@@ -549,7 +492,7 @@ export const runCli = async (argv, deps = {}) => {
549
492
  if (autResult.status === 'error') {
550
493
  if (isFillCapRefusal(autResult.error)) {
551
494
  // SOFT skip — only the genuine fill-overflow withholds the pointer; an already-over-cap
552
- // custom file keeps its distinct over-cap report via the hard-STOP branch below.
495
+ // file keeps its distinct over-cap report via the hard-STOP branch below.
553
496
  autSkipped = true;
554
497
  describeAut = `autonomy pointer skipped — ${autResult.error}`;
555
498
  } else {
@@ -558,16 +501,8 @@ export const runCli = async (argv, deps = {}) => {
558
501
  }
559
502
  } else {
560
503
  finalText = autResult.text;
561
- describeAut = {
562
- 'reconciled-inserted': 'inserted the autonomy pointer below it and filled it',
563
- 'reconciled-filled': 'filled the empty autonomy pointer',
564
- 'reconciled-refreshed': 'refreshed the autonomy pointer to the current canon',
565
- 'present-filled': 'autonomy pointer already present',
566
- }[autResult.status];
567
- if (autResult.status === 'present-filled') {
568
- const u = markerSlotUpgradeHint(finalText, AUTONOMY_DESCRIPTOR);
569
- if (u) notes.push(u);
570
- }
504
+ describeAut = describeSlot(AUTONOMY_DESCRIPTOR, autResult.status);
505
+ pointerWritten ||= autResult.status === 'reconciled-written';
571
506
  }
572
507
  }
573
508
  }
@@ -575,16 +510,16 @@ export const runCli = async (argv, deps = {}) => {
575
510
  // ── The Memory Map rows on the three-slot text, then one atomic write ──
576
511
  const rows = reconcileMemoryMapRows(finalText, { maxLines: AGENTS_MD_CAP });
577
512
  const describeRows = rows.outcomes.map((o) => `the ${o.theme} Memory Map row ${ROW_WORDS[o.status] ?? `skipped — ${o.note}`}`).join('; ');
513
+ const rowWritten = rows.outcomes.some((o) => o.status === 'written');
578
514
  if (rows.text === text) {
579
515
  // Byte-unchanged. Still report a skip (it is not "nothing to do" — a pointer was withheld).
580
516
  if (orchSkipped || autSkipped) log(`[inject-methodology] reconcile: ${describeMeth}; ${describeOrch}; ${describeAut}; ${describeRows}.`);
581
517
  else log(`[inject-methodology] reconcile: all three pointers already present and filled; ${describeRows} — nothing to do (zero-diff).`);
582
- reportNotes();
583
518
  return result(0);
584
519
  }
585
520
  await writeAtomic(rows.text);
586
521
  log(`[inject-methodology] reconcile: ${describeMeth}; ${describeOrch}; ${describeAut}; ${describeRows}.`);
587
- reportNotes();
522
+ reportNotes(rowWritten);
588
523
  return result(0);
589
524
  }
590
525
 
@@ -2,9 +2,10 @@
2
2
  // The only mutation of a deployed rules file the composition root runs WITHOUT a consent ask.
3
3
  import { isDirectRun } from './direct-run.mjs';
4
4
  import { normalizeCanonical } from './orchestration-config.mjs';
5
- import { RULES_REGIONS, extractRegionBy, readTemplateSpan, frontmatterMaxLines, exceedsCap, buildInsertPreview } from './rules-regions.mjs';
5
+ import { RULES_REGIONS, extractRegionBy, readTemplateSpan, frontmatterMaxLines, exceedsCap, buildInsertPreview, decodeUtf8Strict } from './rules-regions.mjs';
6
6
 
7
7
  export { frontmatterMaxLines } from './rules-regions.mjs';
8
+ export const REGION_ROUTE = "text of your own goes under a ### heading of its own, titled unlike the kit's sections";
8
9
  const [COMMUNICATION, STORY, LENS] = RULES_REGIONS;
9
10
  export const LENS_HEADING_RE = LENS.headingRe;
10
11
  export const COMMS_HEADING_RE = COMMUNICATION.headingRe;
@@ -88,13 +89,13 @@ export const replaceLensRegion = (text, region, renderedBody) => {
88
89
  const reconcileRegionText = (text, fragment, priors, { extract, normalize, render }) => {
89
90
  const region = extract(text);
90
91
  if (!region.found) return { status: 'no-region', text };
91
- if (region.count > SINGLE_HEADING) return { status: 'custom', text };
92
+ if (region.count > SINGLE_HEADING) return { status: 'doubled', text };
92
93
  const current = normalize(region.body);
93
94
  const canon = normalize(fragment);
94
95
  if (current === canon) return { status: 'current', text };
95
96
  const known = priors.map((prior) => normalize(prior));
96
- if (!known.includes(current)) return { status: 'custom', text };
97
- return { status: 'refreshed', text: replaceLensRegion(text, region, render(fragment, region.number)) };
97
+ const status = known.includes(current) ? 'refreshed' : 'custom';
98
+ return { status, text: replaceLensRegion(text, region, render(fragment, region.number)) };
98
99
  };
99
100
  export const reconcileLensText = (text, fragment, priors) =>
100
101
  reconcileRegionText(text, fragment, priors, { extract: extractLensRegion, normalize: normalizeLensBody, render: renderLens });
@@ -104,20 +105,22 @@ export const reconcileStoryText = (text, fragment, priors) =>
104
105
  reconcileRegionText(text, fragment, priors, { extract: extractStoryRegion, normalize: normalizeStoryBody, render: renderStory });
105
106
  const RECONCILERS = Object.freeze({ communication: reconcileCommsText, 'story-sessions': reconcileStoryText, lens: reconcileLensText });
106
107
 
108
+ const writtenLine = (section) => `[lens-region] the ${section} differed from the current canon ${EM_DASH} written with it; ${REGION_ROUTE}.`;
109
+ const capRefusedLine = (section, target, count, cap, capWord = 'cap') => `[lens-region] refused ${EM_DASH} writing the current ${section} would push ${oneLine(target)} to ${count} lines (${capWord} ${cap}); trim the file and re-run. The ${section} was not changed.`;
110
+
107
111
  export const OUTCOME_LINES = Object.freeze({
108
112
  errorDetail,
109
113
  targetAbsent: (target) => `[lens-region] ${oneLine(target)} is absent ${EM_DASH} skipped (nothing to update; the file is seeded at bootstrap).`,
114
+ targetNotRegular: (target) => `[lens-region] ${oneLine(target)} is a link or not a regular file ${EM_DASH} left as it stands; nothing written.`,
115
+ targetUndecodable: (target) => `[lens-region] ${oneLine(target)} is not valid UTF-8 ${EM_DASH} nothing written; fix its encoding and re-run.`,
110
116
  commsNoRegion: (target, command) => [
111
117
  `[lens-region] no "${COMMUNICATION.label}" section in ${spanFree(target)} ${EM_DASH} left untouched.`,
112
118
  ...insertNote(command),
113
119
  ],
114
120
  commsCurrent: () => `[lens-region] Communication section already current ${EM_DASH} nothing to do (zero-diff).`,
115
- commsCustom: () => [
116
- `[lens-region] Communication section carries a custom edit ${EM_DASH} preserved verbatim.`,
117
- `[lens-region] note: the canonical Communication section has changed since this section was edited ${EM_DASH} compare it with the current template when convenient; your wording is never overwritten.`,
118
- ],
121
+ commsWritten: () => writtenLine('Communication section'),
119
122
  capSkipNote: () => '[lens-region] note: no `maxLines` frontmatter on the target ' + EM_DASH + ' the line-cap guard is skipped.',
120
- commsCapRefused: (target, count, cap) => `[lens-region] refused ${EM_DASH} refreshing the Communication section would push ${oneLine(target)} to ${count} lines (cap ${cap}); trim the file and re-run. The Communication section was not changed.`,
123
+ commsCapRefused: (target, count, cap) => capRefusedLine('Communication section', target, count, cap),
121
124
  commsRefreshed: () => '[lens-region] refreshed the Communication section to the current canon.',
122
125
  templateCanonStop: () => `[lens-region] STOP ${EM_DASH} the kit's bundled agent_rules.md template canon is unreadable; reinstall the kit: npx @sabaiway/agent-workflow-kit@latest init`,
123
126
  storyNoRegion: (target, command) => [
@@ -125,15 +128,12 @@ export const OUTCOME_LINES = Object.freeze({
125
128
  ...insertNote(command),
126
129
  ],
127
130
  storyCurrent: () => `[lens-region] Story sessions section already current ${EM_DASH} nothing to do (zero-diff).`,
128
- storyCustom: () => [
129
- `[lens-region] Story sessions section carries a custom edit ${EM_DASH} preserved verbatim.`,
130
- `[lens-region] note: this body differs from the bundled template's Story sessions section ${EM_DASH} compare the two when convenient; your wording is never overwritten.`,
131
- ],
132
- storyCapRefused: (target, count, cap) => `[lens-region] refused ${EM_DASH} refreshing the Story sessions section would push ${oneLine(target)} to ${count} lines (maxLines ${cap}); trim the file and re-run. The Story sessions section was not changed.`,
131
+ storyWritten: () => writtenLine('Story sessions section'),
132
+ storyCapRefused: (target, count, cap) => capRefusedLine('Story sessions section', target, count, cap, 'maxLines'),
133
133
  storyRefreshed: () => '[lens-region] refreshed the Story sessions section to the current canon.',
134
134
  regionHeadingTwice: (label, target) => [
135
- `[lens-region] more than one "${oneLine(label)}" section in ${oneLine(target)} ${EM_DASH} preserved verbatim.`,
136
- '[lens-region] note: give the sections distinct headings before retrying; their wording was not changed.',
135
+ `[lens-region] more than one "${oneLine(label)}" section in ${oneLine(target)} ${EM_DASH} none of them was changed.`,
136
+ "[lens-region] note: retitle every one of these headings but one so it no longer opens with the section's title words, then re-run.",
137
137
  ],
138
138
  lensNoRegion: (target) => [
139
139
  `[lens-region] no "${LENS.label}" section in ${oneLine(target)} ${EM_DASH} left untouched.`,
@@ -145,11 +145,8 @@ export const OUTCOME_LINES = Object.freeze({
145
145
  return err?.reason ? [human, errorDetail(err.reason)] : [human];
146
146
  },
147
147
  lensCurrent: () => `[lens-region] lens section already current ${EM_DASH} nothing to do (zero-diff).`,
148
- lensCustom: () => [
149
- `[lens-region] lens section carries a custom edit ${EM_DASH} preserved verbatim.`,
150
- `[lens-region] note: the canonical planning/review lens has changed since this section was edited ${EM_DASH} compare it with the project methodology canon when convenient; your wording is never overwritten.`,
151
- ],
152
- lensCapRefused: (target, count, cap) => `[lens-region] refused ${EM_DASH} refreshing would push ${oneLine(target)} to ${count} lines (cap ${cap}); trim the file and re-run. The planning/review lens section was not changed.`,
148
+ lensWritten: () => writtenLine('planning/review lens section'),
149
+ lensCapRefused: (target, count, cap) => capRefusedLine('planning/review lens section', target, count, cap),
153
150
  lensRefreshed: () => '[lens-region] refreshed the planning/review lens section to the current canon.',
154
151
  });
155
152
 
@@ -195,16 +192,28 @@ export const runCli = async (argv, deps = {}) => {
195
192
  const targetPath = resolve(argv[1]);
196
193
  const served = targetPath.endsWith(sep + SERVED_TARGET.join(sep));
197
194
  const command = served ? buildInsertPreview(resolve(targetPath, '..', '..', '..')) : '';
198
- const text = await (async () => {
195
+ const stat = await fs.lstat(targetPath).catch((err) => {
196
+ if (err.code === 'ENOENT') return null;
197
+ throw err;
198
+ });
199
+ if (stat === null) {
200
+ log(OUTCOME_LINES.targetAbsent(argv[1]));
201
+ return EXIT_OK;
202
+ }
203
+ if (stat.isSymbolicLink() || !stat.isFile()) {
204
+ log(OUTCOME_LINES.targetNotRegular(argv[1]));
205
+ return EXIT_OK;
206
+ }
207
+ const bytes = await fs.readFile(targetPath);
208
+ const text = (() => {
199
209
  try {
200
- return await fs.readFile(targetPath, UTF8);
201
- } catch (err) {
202
- if (err.code === 'ENOENT') return null;
203
- throw err;
210
+ return decodeUtf8Strict(bytes);
211
+ } catch {
212
+ return null;
204
213
  }
205
214
  })();
206
215
  if (text === null) {
207
- log(OUTCOME_LINES.targetAbsent(argv[1]));
216
+ log(OUTCOME_LINES.targetUndecodable(argv[1]));
208
217
  return EXIT_OK;
209
218
  }
210
219
  const templatePath = join(dirname(fileURLToPath(import.meta.url)), '..', 'references', 'templates', 'agent_rules.md');
@@ -255,10 +264,6 @@ export const runCli = async (argv, deps = {}) => {
255
264
  log(OUTCOME_LINES[`${prefix}Current`]());
256
265
  return state;
257
266
  }
258
- if (result.status === 'custom') {
259
- for (const line of OUTCOME_LINES[`${prefix}Custom`]()) log(line);
260
- return state;
261
- }
262
267
  const cap = frontmatterMaxLines(state.text);
263
268
  const decision = exceedsCap(result.text, cap);
264
269
  if (decision.skipped) log(OUTCOME_LINES.capSkipNote());
@@ -267,7 +272,7 @@ export const runCli = async (argv, deps = {}) => {
267
272
  return state;
268
273
  }
269
274
  await atomicWrite(result.text);
270
- log(OUTCOME_LINES[`${prefix}Refreshed`]());
275
+ log(OUTCOME_LINES[`${prefix}${result.status === 'custom' ? 'Written' : 'Refreshed'}`]());
271
276
  return { text: result.text, code: EXIT_OK };
272
277
  }, Promise.resolve({ text, code: EXIT_OK }));
273
278
  return outcome.code;
@@ -2,4 +2,4 @@
2
2
  export { THEMES } from './themes.mjs';
3
3
  export { checkRules } from './rules-check.mjs';
4
4
  export { ensureRules } from './rules-ensure.mjs';
5
- export { reconcileMemoryMapRows } from './memory-map-row.mjs';
5
+ export { reconcileMemoryMapRows, ROW_ROUTE } from './memory-map-row.mjs';
@@ -8,6 +8,9 @@ import { THEMES, themePaths } from './themes.mjs';
8
8
  // the outgoing one here.
9
9
  export const MEMORY_MAP_PRIOR_ROWS = Object.freeze([]);
10
10
 
11
+ // The route the reconcile's row note names when it wrote a row with other text.
12
+ export const ROW_ROUTE = 'a row of your own goes on a line of its own, its first cell a path of your own';
13
+
11
14
  const ANCHOR_PATH = 'docs/ai/agent_rules.md';
12
15
  const opening = (path) => `| [\`${path}\`](./${path}) |`;
13
16
  const rowOf = (theme) => {
@@ -21,6 +24,11 @@ const bodyOf = (line) => line.replace(/\r?\n$/, '');
21
24
  const endingOf = (line) => line.slice(bodyOf(line).length);
22
25
  // A table line that does not close its last cell goes on over the next line.
23
26
  const isWhole = (line) => bodyOf(line).trimEnd().endsWith('|');
27
+ // One whole row: at least four | that no backslash escapes, the last of them closing the line.
28
+ const isOneRow = (line) => {
29
+ const body = bodyOf(line).trimEnd();
30
+ return (body.match(/(?<!\\)\|/g) ?? []).length >= 4 && /(?<!\\)\|$/.test(body);
31
+ };
24
32
 
25
33
  // placeAfter(lines, i, row) → the lines with row on the line after i, taking line i's ending.
26
34
  const placeAfter = (lines, i, row) => {
@@ -30,21 +38,30 @@ const placeAfter = (lines, i, row) => {
30
38
  };
31
39
 
32
40
  // reconcileMemoryMapRows(text, { maxLines, priors }) → { text, outcomes }: one outcome
33
- // { theme, status, note } per registry theme in registry order, status inserted, kept, refreshed or
34
- // skipped; a skipped theme changes no byte and its note names the reason.
41
+ // { theme, status, note } per registry theme in registry order, status inserted, kept, refreshed,
42
+ // written or skipped; a skipped theme changes no byte and its note names the reason.
35
43
  export const reconcileMemoryMapRows = (text, { maxLines, priors = MEMORY_MAP_PRIOR_ROWS } = {}) => {
36
44
  let lines = splitLines(text);
37
45
  let last = -1;
38
46
  const outcomes = [];
39
47
  for (const theme of THEMES) {
40
48
  const row = rowOf(theme);
49
+ const path = themePaths(theme.name).effective;
41
50
  const answer = (status, note = '') => outcomes.push({ theme: theme.name, status, note });
42
- const at = lines.findIndex((line) => line.startsWith(opening(themePaths(theme.name).effective)));
43
- if (at !== -1) {
44
- if (priors.includes(bodyOf(lines[at]))) {
51
+ const found = lines.flatMap((line, i) => (line.startsWith(opening(path)) ? [i] : []));
52
+ if (found.length > 1) {
53
+ answer('skipped', `the Memory Map has more than one ${path} row — none of them was changed`);
54
+ continue;
55
+ }
56
+ if (found.length === 1) {
57
+ const at = found[0];
58
+ const body = bodyOf(lines[at]);
59
+ if (!isOneRow(lines[at])) answer('skipped', `the ${path} row does not close its cells on one line — left as it stands`);
60
+ else if (body === row) answer('kept');
61
+ else {
45
62
  lines = lines.with(at, `${row}${endingOf(lines[at])}`);
46
- answer('refreshed');
47
- } else answer('kept');
63
+ answer(priors.includes(body) ? 'refreshed' : 'written');
64
+ }
48
65
  continue;
49
66
  }
50
67
  const anchor = last !== -1 ? last : lines.findIndex((line) => line.startsWith(opening(ANCHOR_PATH)));
@@ -23,7 +23,7 @@ export const UPGRADE_RUNLIST = Object.freeze([
23
23
  'pointers',
24
24
  'node ${CLAUDE_SKILL_DIR}/tools/inject-methodology.mjs reconcile <project>/AGENTS.md',
25
25
  null,
26
- ['added', 'already present', 'skipped', 'STOP'],
26
+ ['added', 'already present', 'written over a different one', 'skipped', 'STOP'],
27
27
  ),
28
28
  entry(
29
29
  'footprint',
@@ -78,7 +78,7 @@ export const UPGRADE_RUNLIST = Object.freeze([
78
78
  [
79
79
  'refreshed',
80
80
  'already current',
81
- 'custom edit preserved',
81
+ 'differing body written',
82
82
  'file absent',
83
83
  'engine too old',
84
84
  'over the line cap — refused',