@sabaiway/agent-workflow-kit 1.10.0 → 1.11.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,42 @@ 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
+ ## 1.11.0 — One source of truth: the kit reads the methodology live from the installed engine
8
+
9
+ The bounded methodology fragment the kit writes into a project's `AGENTS.md` is now read **live from
10
+ the installed `@sabaiway/agent-workflow-engine`** — the family's single source of truth. The kit's old
11
+ bundled mirror of that text (and its drift-guard) is **retired**: there is exactly one copy now, in the
12
+ engine. `npx @sabaiway/agent-workflow-kit@latest init` installs the engine as a **core** part of the
13
+ kit (it is core methodology, not an optional backend — deliberately diverging from AD-011 §5), so the
14
+ slot can always be filled. The read is **lazy + fail-loud**: the engine is consulted only when a slot
15
+ actually needs filling — a deployment whose slot is already filled upgrades to a **zero-diff no-op even
16
+ without the engine** — and when a fill *is* needed but the engine is absent/invalid the reconcile
17
+ **STOPs** with the exact install command, never a silent fallback. The deployment-lineage head stays
18
+ **`1.3.0`** (no `docs/ai` structural change; no migration file). See **AD-016**.
19
+
20
+ ### Added
21
+ - `tools/engine-source.mjs` — resolves the installed engine via the family `detect.installed` pattern
22
+ (env `AGENT_WORKFLOW_ENGINE_DIR` → `~/.claude/skills/agent-workflow-engine`, **not** an npm
23
+ dependency), validates it with the kit's own manifest validator, and reads the live fragment —
24
+ throwing a loud, actionable error (with the install command) when the engine is needed but absent.
25
+ - `npx … init` now installs the engine after placing the kit. `--no-engine` opts out (the live read
26
+ then STOPs until the engine is installed by hand). An install failure **retries once**, then fails
27
+ loudly with concrete recovery steps and a non-zero exit (the kit itself is already on disk).
28
+
29
+ ### Changed
30
+ - `tools/inject-methodology.mjs` sources the fragment live from the engine (a lazy `slotNeedsFill`
31
+ guard), not a bundled file. `SKILL.md` / `README.md` rewired to the live-read reality; the
32
+ `init-command-uses-latest` drift-guard now also covers the engine's `init` command.
33
+
34
+ ### Removed
35
+ - The bundled mirror (`references/planning.md` + `tools/methodology-slot.md`) and its drift-guard
36
+ `test/methodology-mirror.test.mjs` — retired in favor of the live read.
37
+
38
+ ### Honesty
39
+ - `init` now contacts a server (it fetches the engine over npm) and the kit gains a **runtime
40
+ dependency on the installed engine**; the "nothing contacts a server" / "no new dependency" notes
41
+ were scoped accordingly. The stale-version gate stays no-network, and there is still no telemetry.
42
+
7
43
  ## 1.10.0 — Hidden mode covers the full AI/agent footprint, project-local
8
44
 
9
45
  Hidden visibility now hides the **full AI/agent footprint** — the kit's own artifacts **and** every
package/README.md CHANGED
@@ -159,8 +159,10 @@ different sub-commands:
159
159
  > [`@sabaiway/agent-workflow-memory`](https://www.npmjs.com/package/@sabaiway/agent-workflow-memory).
160
160
  > If a **healthy** copy is installed (the kit validates it with its own shipped validator), the kit
161
161
  > **delegates** substrate deployment to it and injects the workflow methodology; otherwise it uses
162
- > its **own bundled copy** — the one command above keeps working with no new dependency. Same
163
- > `docs/ai/` either way.
162
+ > its **own bundled copy** — the one command above keeps working with **no new dependency on the
163
+ > memory substrate**. Same `docs/ai/` either way. (The **methodology slot** is a separate axis: its
164
+ > fragment is read **live from the installed `agent-workflow-engine`**, which `npx … init` installs
165
+ > for you — a runtime dependency placed by `init`, read live.)
164
166
 
165
167
  ### Refresh the kit itself — same command with `@latest`
166
168
 
@@ -248,7 +250,7 @@ the kit globally; the composition happens when you **deploy it in a repo** (`/ag
248
250
  agent-workflow-kit — the composition root (installed via npx … init)
249
251
  on /agent-workflow-kit in a repo, the kit:
250
252
  ├─ delegates ─▶ memory substrate (healthy copy, else bundled fallback)
251
- ├─ injects ─▶ workflow methodology (engine = future supplier; stub)
253
+ ├─ injects ─▶ workflow methodology (live from the installed engine)
252
254
  ├─ deploys ─▶ AGENTS.md + docs/ai/ + Node scripts + pre-commit hook
253
255
  ├─ detects ─▶ optional backends (codex / agy, read-only)
254
256
  └─ sets up ─▶ a bridge (opt-in) (place skill + link wrappers)
@@ -296,12 +298,12 @@ agent-workflow-kit/
296
298
  ├── references/
297
299
  │ ├── templates/ ← AGENTS.md + every docs/ai file
298
300
  │ ├── scripts/ ← caps / archive / index + tests
299
- ├── contracts.md ← visibility / language / attribution rules
300
- │ └── planning.md ← plan lifecycle + continuity
301
+ └── contracts.md ← visibility / language / attribution rules
301
302
  ├── tools/ ← family tooling:
302
303
  │ ├── manifest/ ← capability-manifest schema + validator
303
304
  │ ├── delegation.mjs ← detect substrate · delegate-or-fall-back
304
305
  │ ├── inject-methodology.mjs ← write the methodology slot
306
+ │ ├── engine-source.mjs ← live engine fragment read (fail-loud)
305
307
  │ ├── detect-backends.mjs ← read-only backend detector
306
308
  │ ├── setup-backends.mjs ← link-only backend setup
307
309
  │ ├── fs-safe.mjs ← symlink-safe copy/link
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".
4
4
  disable-model-invocation: true
5
5
  metadata:
6
- version: '1.10.0'
6
+ version: '1.11.0'
7
7
  ---
8
8
 
9
9
  # agent-workflow-kit
@@ -24,7 +24,10 @@ This kit is the **composition root** of the `agent-workflow` family. The memory
24
24
  (`docs/ai/`, the entry-point doc, caps / archive / index, the setup contracts) is owned by
25
25
  **`agent-workflow-memory`**. The kit **prefers to delegate** substrate deployment to that skill
26
26
  when it is present and healthy, and otherwise uses its **own bundled copy** (`references/`,
27
- `migrations/`) — so the existing one-command install keeps working with **no new dependency**.
27
+ `migrations/`) — so the existing one-command install keeps working with **no new dependency on the
28
+ memory substrate**. (The methodology slot is a separate axis: its fragment is read **live from the
29
+ installed `agent-workflow-engine`**, which `npx @sabaiway/agent-workflow-kit@latest init` installs — a
30
+ runtime dependency placed by `init` and read live; see *Methodology slot reconciliation* below.)
28
31
 
29
32
  **Detection (kit-owned, decided BEFORE any project write).** Run the kit's **own shipped**
30
33
  validator — `node ${CLAUDE_SKILL_DIR}/tools/manifest/validate.mjs <memory-skill-dir>` — never a
@@ -67,11 +70,16 @@ made: a partial/broken memory install discovered mid-flow must not disable the w
67
70
  **one atomic operation**: **ensure the slot exists** (insert an empty marker pair right after the
68
71
  Session-Protocols anchor when a legacy entry point lacks one) → **inject the bounded fragment ONLY
69
72
  IF the slot is empty** (a filled / user-customized slot is preserved verbatim) → **cap-check**
70
- (keeps `AGENTS.md` ≤100 lines). The fragment is a short summary + pointer (source: the kit's bundled
71
- `tools/methodology-slot.md`, a **byte-identical mirror of the `agent-workflow-engine` canon**) —
72
- **not** the full `references/planning.md`. Contract: exactly one ordered `start → end` pair; a
73
- malformed slot (single, reversed, nested, duplicate) or a missing / duplicate anchor **STOP with
74
- an error**, never edit (the file is left byte-for-byte unchanged).
73
+ (keeps `AGENTS.md` ≤100 lines). The fragment is a short summary + pointer read **live from the
74
+ installed `agent-workflow-engine`** (`references/methodology-slot.md`, the family's one source of
75
+ truth) — **not** a bundled mirror, and **not** the full `references/planning.md`. The live read is
76
+ **lazy + fail-loud**: the engine is consulted **only when the slot actually needs filling**, so a
77
+ deployment whose slot is already filled reconciles to a zero-diff no-op even on a host without the
78
+ engine; but when a fill **is** needed and the engine is **absent/invalid**, reconcile **STOPs** —
79
+ report it in plain language with the one-line install command `npx @sabaiway/agent-workflow-engine@latest init`
80
+ (`npx @sabaiway/agent-workflow-kit@latest init` installs the engine for you; translate, never leak tool internals). Contract:
81
+ exactly one ordered `start → end` pair; a malformed slot (single, reversed, nested, duplicate) or a
82
+ missing / duplicate anchor → **STOP with an error**, never edit (the file is left byte-for-byte unchanged).
75
83
 
76
84
  **One composition-level commit gate.** The delegated memory mode performs **no** commit and
77
85
  raises **no** "ask to commit". There is exactly **one** gate, owned by the kit, **after**
@@ -175,11 +183,17 @@ Fill strategy:
175
183
 
176
184
  1. Read `docs/ai/.workflow-version` (the project's stamped lineage). If missing, treat as a pre-versioned deployment and offer to re-bootstrap conservatively.
177
185
  2. **Never-downgrade gate — FIRST, before any write.** Compare the stamp to the **deployment-lineage head** (`1.3.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).
178
- 3. **Reconcile the methodology slot — stamp-independent, BEFORE the equal-head short-circuit.** Reached only when the stamp **≤ head**. Run `node ${CLAUDE_SKILL_DIR}/tools/inject-methodology.mjs reconcile <project>/AGENTS.md`. This ensures the `workflow:methodology` slot exists and is filled on **every** upgrade, idempotently (zero-diff when already present + filled) — so even a legacy / current **`1.3.0`** deployment gains the slot **without a lineage-head bump** (the head stays `1.3.0`; **no `agent-workflow-memory` change**). It inserts an empty slot at the Session-Protocols anchor if absent, preserves a customized slot verbatim, and STOPs (never edits) on a malformed slot or a missing / duplicate anchor.
186
+ 3. **Reconcile the methodology slot — stamp-independent, BEFORE the equal-head short-circuit.** Reached only when the stamp **≤ head**. Run `node ${CLAUDE_SKILL_DIR}/tools/inject-methodology.mjs reconcile <project>/AGENTS.md`. This ensures the `workflow:methodology` slot exists and is filled on **every** upgrade, idempotently (zero-diff when already present + filled) — so even a legacy / current **`1.3.0`** deployment gains the slot **without a lineage-head bump** (the head stays `1.3.0`; **no `agent-workflow-memory` change**). It inserts an empty slot at the Session-Protocols anchor if absent, preserves a customized slot verbatim, and STOPs (never edits) on a malformed slot, a missing / duplicate anchor, or **when a fill is needed but the installed `agent-workflow-engine` is absent/invalid** (the fragment is read live from it — see the three distinct non-zero outcomes below).
179
187
 
180
- **Cap-refusal is a soft, reported skip — not a STOP.** If — and ONLY if — `reconcile` exits non-zero because filling the slot would exceed the deployed `AGENTS.md` 100-line cap (the entry point is already at / over budget), leave the file byte-for-byte unchanged (the tool already did) and **continue** the upgrade without the slot. A malformed slot or a missing / duplicate anchor is a *different* non-zero exit and still **STOPs** (above) never soft-skip those. This is **not** a silent skip (Hard Constraint — no silent failures): report it explicitly in the successful-exit report (**step 4** on an equal-head deployment, else **step 8**), in plain language, e.g. *"The workflow-methodology pointer wasn't added — `AGENTS.md` is N lines, over its 100-line limit. The methodology is already documented in `docs/ai/agent_rules.md`; to add the pointer, trim the entry point (move detail into `docs/ai/`) and re-run upgrade."* N is the file's **current** line count — never the tool's number (that is the would-be post-injection size). Because the entry point is already over cap, ensure the rest of the upgrade does not push it further: any mandatory `AGENTS.md` edit must keep it ≤100 lines or pause for an explicit trim — never bust the cap to land a migration.
188
+ **`reconcile` has THREE distinct non-zero exitsclassify by the stderr text, handle each differently:**
181
189
 
182
- **No-Node project:** open `AGENTS.md`; if there is no `<!-- workflow:methodology:start/end -->` pair, **count the lines first** if pasting the pair + the fragment from `tools/methodology-slot.md` would take the file over 100 lines, **skip it and report the skip** (as abovethe methodology is already in `docs/ai/agent_rules.md`; trim to add the pointer). Otherwise paste the pair right after the *Read it before any code change.* line and fill it from `tools/methodology-slot.md`.
190
+ (a) **Cap-refusal a soft, reported skip (CONTINUE the upgrade).** If — and ONLY if — `reconcile` exits non-zero because filling the slot would exceed the deployed `AGENTS.md` 100-line cap (the entry point is already at / over budget), leave the file byte-for-byte unchanged (the tool already did) and **continue** the upgrade without the slot. This is **not** a silent skip (Hard Constraint no silent failures): report it explicitly in the successful-exit report (**step 4** on an equal-head deployment, else **step 8**), in plain language, e.g. *"The workflow-methodology pointer wasn't added `AGENTS.md` is N lines, over its 100-line limit. The methodology is already documented in `docs/ai/agent_rules.md`; to add the pointer, trim the entry point (move detail into `docs/ai/`) and re-run upgrade."* N is the file's **current** line count — never the tool's number (that is the would-be post-injection size). Because the entry point is already over cap, ensure the rest of the upgrade does not push it further: any mandatory `AGENTS.md` edit must keep it ≤100 lines or pause for an explicit trim — never bust the cap to land a migration.
191
+
192
+ (b) **Malformed slot / missing-or-duplicate anchor — a hard STOP (do NOT continue).** A different non-zero exit (above); never soft-skip it.
193
+
194
+ (c) **`methodology engine not found/invalid …` — a hard STOP (do NOT continue).** A fill was needed but the installed `agent-workflow-engine` (the live source of the fragment) is **absent/invalid**. 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 the cap soft-skip (a) — its message is distinct, and mis-handling it as a soft-skip would silently drop the slot (a no-silent-failures violation). (b) and (c) STOP the upgrade; only (a) continues.
195
+
196
+ **No-Node project:** the fragment lives only in the **installed `agent-workflow-engine`** (`references/methodology-slot.md`, under `~/.claude/skills/agent-workflow-engine` or `$AGENT_WORKFLOW_ENGINE_DIR`) — there is no bundled copy. A No-Node host also cannot run the `npx` engine install. Open `AGENTS.md` and classify the slot by hand: a **filled / customized** slot → leave it verbatim (no-op, no engine needed); a **malformed** slot (not exactly one ordered `start → end` pair) → STOP, do not edit. A slot that needs filling — **absent markers OR a present-but-empty pair** — needs the engine's fragment, so: if the engine is **not installed**, the pointer **cannot be added** — report that plainly (mirroring the Node STOP: the methodology is already in `docs/ai/agent_rules.md`; install the engine to add the pointer). If the engine **is** present, **count the lines first** — if adding/filling the pair with that fragment would take the file over 100 lines, **skip it and report the skip** (as above — trim to add the pointer). Otherwise: when markers are absent, paste the pair right after the *Read it before any code change.* line; then fill the empty pair from the engine's `references/methodology-slot.md` (never inline a copy — that would re-create the retired mirror).
183
197
 
184
198
  **Hidden-mode footprint reconcile — stamp-independent, same gate, BEFORE the equal-head short-circuit (D9 / AD-014).** A deployment does not record whether it chose `hidden`, so first **infer visibility**: `node ${CLAUDE_SKILL_DIR}/tools/hide-footprint.mjs --dir <project> --reconcile --dry-run` (writes **zero bytes**). It 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 (already-committed → show `git rm --cached`, ask before `--include`; generic-name present file → ask; **leftover machine-wide ignore block → ASK before `--remove-global`**, default keep + report). No Node on the agent host / Windows → as step 9. This runs on **every** hidden upgrade, like the methodology slot — no lineage-head bump, no migration file.
185
199
  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 methodology-slot **and** hidden-mode footprint reconciles) ran first and may have changed things, so this is a proper exit report, not a no-op:
@@ -287,11 +301,11 @@ Deploy these into `AGENTS.md`; remove rows that don't apply to the stack.
287
301
  ## References
288
302
 
289
303
  - [`references/contracts.md`](references/contracts.md) — the three setup contracts (visibility, conversational language, agent attribution) in full; the *Setup contracts* section above points here.
290
- - [`references/planning.md`](references/planning.md) — plan vocabulary (Plan→Phase→Step→Substep), lifecycle, `queue.md` series-index, mandatory Cleanup, session-continuity heuristic.
304
+ - **Plan vocabulary** (Plan→Phase→Step→Substep), lifecycle, `queue.md` series-index, mandatory Cleanup, session-continuity heuristic — the single home is the **installed `agent-workflow-engine`** canon (`~/.claude/skills/agent-workflow-engine/references/planning.md`, or `$AGENT_WORKFLOW_ENGINE_DIR`); there is no bundled mirror. `npx @sabaiway/agent-workflow-kit@latest init` installs the engine.
291
305
  - [`references/templates/`](references/templates/) — stack-agnostic `AGENTS.md`, `agent_rules.md`, and all `docs/ai/` files to deploy.
292
306
  - [`references/scripts/`](references/scripts/) — the Node enforcement scripts (caps + staleness + index-freshness gate, 3-tier archive, hook installer) and their unit tests.
293
307
  - [`migrations/`](migrations/) — per-version upgrade steps; see `migrations/README.md`.
294
308
  - [`launchers/`](launchers/) — run the bootstrapper from non-Claude agents (`SKILL.md` is a native Codex skill; a Devin Desktop workflow launcher + install script). See `launchers/README.md`.
295
- - [`tools/`](tools/) — the family-wide tooling the kit **owns and ships**: `manifest/{schema.md,validate.mjs}` (the `capability.json` schema + the validator the kit runs as the memory detector, and root CI invokes), `delegation.mjs` (the executable delegate/fallback decision + hand-off plan), `inject-methodology.mjs` + `methodology-slot.md` (the bounded slot reconciliation — ensure-slot / inject-if-empty / cap; the fragment is a byte-identical mirror of the `agent-workflow-engine` canon, pinned by `methodology-mirror.test.mjs`), `detect-backends.mjs` (the read-only **backend detector** behind `/agent-workflow-kit backends`, plus the axis-aware `guideFor`), `setup-backends.mjs` (the **link-only** backend setup behind `/agent-workflow-kit setup` — place the bundled bridge + link wrappers), `fs-safe.mjs` (the shared symlink-traversal-safe copy/link primitives both `setup-backends` and the npx installer use), `known-footprint.mjs` + `hide-footprint.mjs` (the **hidden-mode** registry + the single hide-writer behind step 9 / the upgrade reconcile — one managed block in the **project-local** `.git/info/exclude` covering the full AI/agent footprint; pinned by `known-footprint.test.mjs` drift-guard + `hide-footprint.test.mjs` / `.integration.test.mjs`), and `release-scan.mjs` (the attribution-off release gate). The bundled bridge skill mirrors live under [`bridges/`](bridges/) (byte-identical to the repo-root bridges, pinned by `test/bridges-mirror.test.mjs`). See [`tools/manifest/schema.md`](tools/manifest/schema.md).
309
+ - [`tools/`](tools/) — the family-wide tooling the kit **owns and ships**: `manifest/{schema.md,validate.mjs}` (the `capability.json` schema + the validator the kit runs as the memory detector, and root CI invokes), `delegation.mjs` (the executable delegate/fallback decision + hand-off plan), `inject-methodology.mjs` + `engine-source.mjs` (the bounded slot reconciliation — ensure-slot / inject-if-empty / cap; the fragment is read **live** from the installed `agent-workflow-engine` via `engine-source.mjs` — the family's one source of truth, no bundled mirror; fail-loud when the engine is needed but absent), `detect-backends.mjs` (the read-only **backend detector** behind `/agent-workflow-kit backends`, plus the axis-aware `guideFor`), `setup-backends.mjs` (the **link-only** backend setup behind `/agent-workflow-kit setup` — place the bundled bridge + link wrappers), `fs-safe.mjs` (the shared symlink-traversal-safe copy/link primitives both `setup-backends` and the npx installer use), `known-footprint.mjs` + `hide-footprint.mjs` (the **hidden-mode** registry + the single hide-writer behind step 9 / the upgrade reconcile — one managed block in the **project-local** `.git/info/exclude` covering the full AI/agent footprint; pinned by `known-footprint.test.mjs` drift-guard + `hide-footprint.test.mjs` / `.integration.test.mjs`), and `release-scan.mjs` (the attribution-off release gate). The bundled bridge skill mirrors live under [`bridges/`](bridges/) (byte-identical to the repo-root bridges, pinned by `test/bridges-mirror.test.mjs`). See [`tools/manifest/schema.md`](tools/manifest/schema.md).
296
310
  - [`capability.json`](capability.json) — the kit's own `agent-workflow` family manifest (`kind: composition-root`).
297
311
  - [`CHANGELOG.md`](CHANGELOG.md) — version history of this kernel.
package/bin/install.mjs CHANGED
@@ -14,17 +14,19 @@
14
14
  // docs/ai deployment — see README "Use".
15
15
  //
16
16
  // No telemetry, no phone-home: adoption is the npm registry's public, passive per-version
17
- // download numbers (api.npmjs.org/downloads). Nothing here contacts a serverincluding the
18
- // stale-version defenses below, which compare the version already on disk (the installed SKILL.md)
19
- // against this runner's own version, never the registry. That is why `@latest` (above) is the
20
- // documented form: a bare `npx … init` can reuse an OLDER cached build of this installer, so a
21
- // returning user must bypass the cache to actually upgrade. See decisions.md AD-012.
17
+ // download numbers (api.npmjs.org/downloads). The stale-version GATE below is no-network it
18
+ // compares the version already on disk (the installed SKILL.md) against this runner's own version,
19
+ // never the registry which is why `@latest` (above) is the documented form: a bare `npx … init`
20
+ // can reuse an OLDER cached build of this installer, so a returning user must bypass the cache to
21
+ // actually upgrade (see decisions.md AD-012). One step DOES contact a server: `init` fetches and
22
+ // installs the methodology engine the kit reads live (`npx @sabaiway/agent-workflow-engine@latest
23
+ // init`), skippable with `--no-engine` (Plan 3D / AD-016). No tracking either way.
22
24
  //
23
25
  // Dependency-free, Node >= 18.
24
26
 
25
- import { readFile, mkdir } from 'node:fs/promises';
27
+ import { readFile, mkdir, rm } from 'node:fs/promises';
26
28
  import { existsSync, lstatSync, realpathSync } from 'node:fs';
27
- import { dirname, resolve } from 'node:path';
29
+ import { dirname, resolve, sep } from 'node:path';
28
30
  import { fileURLToPath } from 'node:url';
29
31
  import { homedir } from 'node:os';
30
32
  import { spawnSync } from 'node:child_process';
@@ -50,7 +52,16 @@ const PAYLOAD = [
50
52
  'bridges',
51
53
  ];
52
54
 
53
- const tildify = (path) => path.replace(homedir(), '~');
55
+ // Kit-owned files the package NO LONGER ships (Plan 3D retired the bundled methodology mirror). The
56
+ // refresh copy is additive, so a 1.10.0→1.11.0 upgrade would leave these dead copies behind; remove
57
+ // exactly these known kit paths from the target on install (never user content, never a dir/symlink),
58
+ // so an upgraded install has the same single-source-of-truth shape as a fresh one.
59
+ const RETIRED_PATHS = ['references/planning.md', 'tools/methodology-slot.md'];
60
+
61
+ // Collapse only a LEADING homedir() to "~" — anchored at the string start (boundary-checked with
62
+ // `sep`), never a mid-path occurrence (Issue-004 parity with the engine/memory installers).
63
+ const tildify = (path) =>
64
+ path === homedir() ? '~' : path.startsWith(homedir() + sep) ? `~${path.slice(homedir().length)}` : path;
54
65
 
55
66
  const readVersion = async () => {
56
67
  try {
@@ -135,12 +146,63 @@ const parseArgs = (argv) => {
135
146
  help: argv.includes('--help') || argv.includes('-h'),
136
147
  version: argv.includes('--version') || argv.includes('-v'),
137
148
  noLaunchers: argv.includes('--no-launchers'),
149
+ noEngine: argv.includes('--no-engine'),
138
150
  force: argv.includes('--force'),
139
151
  allowDowngrade: argv.includes('--allow-downgrade'),
140
152
  dir: dirFlag >= 0 ? argv[dirFlag + 1] : undefined,
141
153
  };
142
154
  };
143
155
 
156
+ // Mandatory engine install (Plan 3D / AD-016). The kit reads the methodology fragment LIVE from the
157
+ // installed agent-workflow-engine, so init places it as a CORE part of the kit (not an optional
158
+ // execution-backend — this deliberately diverges from AD-011 §5). It is fetched over npm, consistent
159
+ // with the kit's own npx install context; NO engine canon is bundled into the kit (that would
160
+ // re-create the mirror Plan 3D deletes). --no-engine skips it for air-gapped/scripted installs.
161
+ export const ENGINE_PACKAGE = '@sabaiway/agent-workflow-engine';
162
+
163
+ // The exact command + argv to install the engine. Windows resolution: spawn `npx.cmd` on win32,
164
+ // `npx` elsewhere, WITHOUT shell:true (no shell-parse overhead/inconsistency; the repo has no
165
+ // npx-spawn precedent to inherit a shell from). Pure → unit-tested in-process, no network.
166
+ export const engineInstallArgv = (platform) => ({
167
+ command: platform === 'win32' ? 'npx.cmd' : 'npx',
168
+ args: [`${ENGINE_PACKAGE}@latest`, 'init'],
169
+ options: { stdio: 'inherit' }, // note: no `shell: true`
170
+ });
171
+
172
+ // The default runner — the only place that actually spawns. Injected in tests so the suite never
173
+ // hits the network.
174
+ const spawnEngine = ({ command, args, options }) => spawnSync(command, args, options);
175
+
176
+ // Synchronous backoff before the single retry. The common first-attempt failure is a TRANSIENT
177
+ // npm/network blip (rate-limit, registry hiccup, momentary DNS) — an immediate retry tends to hit the
178
+ // same blip, so wait briefly first. Atomics.wait is a dependency-free sync sleep (the install flow is
179
+ // already synchronous here). Injected in tests as a 0ms no-op so the suite never actually sleeps.
180
+ const ENGINE_RETRY_DELAY_MS = 1500;
181
+ const sleepSync = (ms) => {
182
+ if (ms > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
183
+ };
184
+
185
+ // D1 failure policy: attempt → wait → retry-once → fail. Retry exactly once before giving up. Pure
186
+ // aside from the injected runner/sleep; returns { ok } so the caller prints the loud manual-recovery
187
+ // message + nonzero exit on a hard failure (the kit is already on disk — recovery is one step; never
188
+ // a silent skip).
189
+ export const installEngine = (platform, runner, { sleep = sleepSync, retryDelayMs = ENGINE_RETRY_DELAY_MS } = {}) => {
190
+ const descriptor = engineInstallArgv(platform);
191
+ const ranOk = (label) => {
192
+ const res = runner(descriptor);
193
+ const ok = (res?.status ?? 1) === 0 && !res?.error;
194
+ if (!ok) {
195
+ const why = res?.error ? `: ${res.error.message}` : ` (exit ${res?.status ?? 'unknown'})`;
196
+ console.warn(`[agent-workflow-kit] methodology engine install ${label} failed${why}.`);
197
+ }
198
+ return ok;
199
+ };
200
+ if (ranOk('attempt 1')) return { ok: true };
201
+ sleep(retryDelayMs); // brief backoff so the retry does not immediately re-hit a transient blip
202
+ if (ranOk('retry')) return { ok: true };
203
+ return { ok: false };
204
+ };
205
+
144
206
  const resolveTarget = (dirArg) => {
145
207
  if (dirArg) return resolve(dirArg);
146
208
  if (process.env.AGENT_WORKFLOW_KIT_DIR) return resolve(process.env.AGENT_WORKFLOW_KIT_DIR);
@@ -151,7 +213,7 @@ const printHelp = (version) => {
151
213
  console.log(`agent-workflow-kit ${version}
152
214
 
153
215
  Usage:
154
- npx @sabaiway/agent-workflow-kit@latest init [--dir <path>] [--no-launchers] [--force] [--allow-downgrade]
216
+ npx @sabaiway/agent-workflow-kit@latest init [--dir <path>] [--no-launchers] [--no-engine] [--force] [--allow-downgrade]
155
217
  npx @sabaiway/agent-workflow-kit@latest --version
156
218
  npx @sabaiway/agent-workflow-kit@latest --help
157
219
 
@@ -160,11 +222,14 @@ Use the @latest form: a bare \`npx … init\` (no @latest) can reuse an OLDER ca
160
222
 
161
223
  Installs/refreshes the kit at ~/.claude/skills/agent-workflow-kit
162
224
  (override with --dir <path> or AGENT_WORKFLOW_KIT_DIR), then wires any
163
- Codex / Devin Desktop you have. --no-launchers skips that wiring; --force replaces a
164
- pre-existing non-kit launcher file (backed up first). init is additive — it never
165
- deletes your settings. If the installed kit is newer than the version you ran, init
166
- refuses (no network it compares the version on disk) and points you at @latest;
167
- --allow-downgrade overrides that refusal (distinct from --force, which is launcher-only).
225
+ Codex / Devin Desktop you have, then installs the methodology engine the kit reads
226
+ live (npx ${ENGINE_PACKAGE}@latest init). --no-launchers skips the
227
+ launcher wiring; --no-engine skips the engine install (the live methodology read then
228
+ STOPs until you install it by hand); --force replaces a pre-existing non-kit launcher
229
+ file (backed up first). init is additive it never deletes your settings. If the
230
+ installed kit is newer than the version you ran, init refuses (no network — it compares
231
+ the version on disk) and points you at @latest; --allow-downgrade overrides that
232
+ refusal (distinct from --force, which is launcher-only).
168
233
 
169
234
  After install, invoke the skill in your agent, inside a project:
170
235
  first time in the project -> /agent-workflow-kit
@@ -232,6 +297,16 @@ const main = async () => {
232
297
  for (const entry of PAYLOAD.filter((e) => existsSync(resolve(PKG_ROOT, e)))) {
233
298
  copyTreeRefresh(resolve(PKG_ROOT, entry), resolve(target, entry), target);
234
299
  }
300
+ // Remove the retired mirror files an older install may have left (additive refresh never deletes).
301
+ // Only a regular file at the exact known path is removed — lstat (no-follow) so a dir/symlink is
302
+ // left untouched, and the path is a hardcoded kit-owned constant (no traversal, never user content).
303
+ for (const rel of RETIRED_PATHS) {
304
+ const retired = resolve(target, rel);
305
+ if (lstatNoFollow(retired)?.isFile()) {
306
+ await rm(retired, { force: true });
307
+ console.log(`[agent-workflow-kit] removed retired file ${tildify(retired)} (now read live from the engine).`);
308
+ }
309
+ }
235
310
  console.log(`[agent-workflow-kit] ${wasPresent ? 'updated the kit to' : 'installed'} v${version} -> ${tildify(target)}`);
236
311
 
237
312
  // No-op re-run: the install just refreshed the skill with the SAME version it already had. For a
@@ -260,6 +335,34 @@ const main = async () => {
260
335
  }
261
336
  }
262
337
 
338
+ // Mandatory engine install — AFTER the kit + launchers but BEFORE the success block, so a failure
339
+ // never first claims everything succeeded. The kit reads the methodology fragment live from the
340
+ // installed engine; this places it (over npm, no canon bundled into the kit). --no-engine opts out.
341
+ const engineCmd = `npx ${ENGINE_PACKAGE}@latest init`;
342
+ if (args.noEngine) {
343
+ console.log(
344
+ `[agent-workflow-kit] --no-engine: skipped installing the methodology engine. The methodology ` +
345
+ `slot is read LIVE from the installed engine, so a reconcile/upgrade will STOP until you run:\n` +
346
+ ` ${engineCmd}`,
347
+ );
348
+ } else {
349
+ console.log(`[agent-workflow-kit] installing the methodology engine the kit reads live: ${engineCmd}`);
350
+ const engine = installEngine(process.platform, spawnEngine);
351
+ if (!engine.ok) {
352
+ // D1: two attempts failed → loud error + concrete recommendations + nonzero exit. The kit IS on
353
+ // disk, so recovery is one step. Never a silent skip (Hard Constraint: no silent failures).
354
+ console.error(
355
+ `[agent-workflow-kit] FAILED to install the methodology engine after two attempts. The kit ` +
356
+ `itself IS installed at ${tildify(target)}, but the methodology-slot read will STOP until the ` +
357
+ `engine is present. Finish with EITHER:\n` +
358
+ ` ${engineCmd} (install the engine — recommended)\n` +
359
+ ` npx @sabaiway/agent-workflow-kit@latest init --no-engine (skip it deliberately)`,
360
+ );
361
+ process.exit(1);
362
+ }
363
+ console.log('[agent-workflow-kit] methodology engine installed.');
364
+ }
365
+
263
366
  // This command (de)installed the *kit* globally. Deploying it into a project is a
264
367
  // separate, in-agent step — and which sub-command depends on whether that project
265
368
  // already has the kit. Spell both out so it's unambiguous (see README "Use").
@@ -7,11 +7,16 @@ import { tmpdir } from 'node:os';
7
7
  import { dirname, join } from 'node:path';
8
8
  import { fileURLToPath, pathToFileURL } from 'node:url';
9
9
 
10
+ import { engineInstallArgv, installEngine, ENGINE_PACKAGE } from './install.mjs';
11
+
10
12
  const INSTALLER = join(dirname(fileURLToPath(import.meta.url)), 'install.mjs');
11
13
  const KIT_ROOT = dirname(dirname(INSTALLER));
12
- // --no-launchers so the test never wires Codex/Devin on the host. `extra` appends flags (e.g. --force).
14
+ // --no-launchers so the test never wires Codex/Devin on the host; --no-engine so a full install never
15
+ // spawns a real `npx … agent-workflow-engine init` (network + a write to the real engine dir). The
16
+ // dedicated engine-step tests cover that path in-process / via a deliberately-broken PATH. `extra`
17
+ // appends flags (e.g. --force, --allow-downgrade).
13
18
  const runInstaller = (target, extra = []) =>
14
- spawnSync(process.execPath, [INSTALLER, '--dir', target, '--no-launchers', ...extra], { encoding: 'utf8' });
19
+ spawnSync(process.execPath, [INSTALLER, '--dir', target, '--no-launchers', '--no-engine', ...extra], { encoding: 'utf8' });
15
20
 
16
21
  // Rewrite / read the installed skill's frontmatter version — used to simulate "a newer kit is already
17
22
  // installed" (the stale-cache downgrade scenario). The installer reads exactly this field.
@@ -44,6 +49,21 @@ describe('kit installer — payload + symlink-traversal hardening', () => {
44
49
  assert.equal(existsSync(join(target, 'bin/install.mjs')), false);
45
50
  });
46
51
 
52
+ it('removes retired mirror files an older install left behind (single source of truth on upgrade)', async () => {
53
+ const target = join(dir, 'agent-workflow-kit');
54
+ // Seed a pre-3D install carrying the now-retired bundled mirror files.
55
+ await mkdir(join(target, 'references'), { recursive: true });
56
+ await mkdir(join(target, 'tools'), { recursive: true });
57
+ await writeFile(join(target, 'references', 'planning.md'), 'stale mirror\n');
58
+ await writeFile(join(target, 'tools', 'methodology-slot.md'), 'stale mirror\n');
59
+ const res = runInstaller(target);
60
+ assert.equal(res.status, 0, res.stderr);
61
+ assert.equal(existsSync(join(target, 'references', 'planning.md')), false, 'retired references/planning.md removed');
62
+ assert.equal(existsSync(join(target, 'tools', 'methodology-slot.md')), false, 'retired tools/methodology-slot.md removed');
63
+ assert.ok(existsSync(join(target, 'SKILL.md')), 'the real payload is still installed');
64
+ assert.ok(existsSync(join(target, 'references', 'contracts.md')), 'non-retired references/ content survives');
65
+ });
66
+
47
67
  it('refuses to write through a symlinked INTERMEDIATE dest component (no leak)', async () => {
48
68
  const target = join(dir, 'target');
49
69
  const evil = join(dir, 'evil');
@@ -96,7 +116,7 @@ describe('kit installer — runs through the npx bin symlink', () => {
96
116
  const shim = join(dir, 'agent-workflow-kit'); // stands in for node_modules/.bin/<name>
97
117
  await symlink(INSTALLER, shim);
98
118
  const target = join(dir, 'home', 'agent-workflow-kit');
99
- const res = spawnSync(process.execPath, [shim, '--dir', target, '--no-launchers'], { encoding: 'utf8' });
119
+ const res = spawnSync(process.execPath, [shim, '--dir', target, '--no-launchers', '--no-engine'], { encoding: 'utf8' });
100
120
  assert.equal(res.status, 0, res.stderr);
101
121
  assert.match(res.stdout, /installed v|updated the kit/);
102
122
  assert.ok(existsSync(join(target, 'SKILL.md')), 'install through the symlink must write the payload');
@@ -211,8 +231,107 @@ describe('kit installer — stale-cache defenses (no network)', () => {
211
231
  });
212
232
  });
213
233
 
214
- describe('kit installer — published tarball bundles the bridges', () => {
215
- it('npm pack ships bridges/<name>/ (the execution-backend skill mirrors)', () => {
234
+ describe('kit installer — mandatory engine install dispatch (Plan 3D, in-process, no network)', () => {
235
+ it('engineInstallArgv: `npx @…/engine@latest init` on POSIX, `npx.cmd` on win32, no shell:true', () => {
236
+ const posix = engineInstallArgv('linux');
237
+ assert.equal(posix.command, 'npx');
238
+ assert.deepEqual(posix.args, [`${ENGINE_PACKAGE}@latest`, 'init']);
239
+ assert.equal(posix.options.shell, undefined, 'must not spawn through a shell');
240
+ assert.equal(engineInstallArgv('darwin').command, 'npx');
241
+ assert.equal(engineInstallArgv('win32').command, 'npx.cmd');
242
+ });
243
+
244
+ it('installEngine: first attempt succeeds → ok, runner called once (no retry)', () => {
245
+ let calls = 0;
246
+ const res = installEngine('linux', () => {
247
+ calls += 1;
248
+ return { status: 0 };
249
+ });
250
+ assert.deepEqual(res, { ok: true });
251
+ assert.equal(calls, 1);
252
+ });
253
+
254
+ const NO_SLEEP = { sleep: () => {} }; // skip the real backoff so the suite never actually waits
255
+
256
+ it('installEngine: fail once then succeed → backoff + retried exactly once, ends ok (D1)', () => {
257
+ let calls = 0;
258
+ let slept = 0;
259
+ const res = installEngine('linux', () => {
260
+ calls += 1;
261
+ return { status: calls === 1 ? 1 : 0 };
262
+ }, { sleep: () => { slept += 1; } });
263
+ assert.deepEqual(res, { ok: true });
264
+ assert.equal(calls, 2);
265
+ assert.equal(slept, 1, 'backoff runs exactly once, before the single retry');
266
+ });
267
+
268
+ it('installEngine: fails twice → not ok (D1 hard-failure outcome), no third attempt', () => {
269
+ let calls = 0;
270
+ const res = installEngine('linux', () => {
271
+ calls += 1;
272
+ return { status: 1 };
273
+ }, NO_SLEEP);
274
+ assert.deepEqual(res, { ok: false });
275
+ assert.equal(calls, 2);
276
+ });
277
+
278
+ it('installEngine: a spawn error (npx not found) counts as a failure', () => {
279
+ const res = installEngine('linux', () => ({ status: null, error: new Error('spawn npx ENOENT') }), NO_SLEEP);
280
+ assert.deepEqual(res, { ok: false });
281
+ });
282
+
283
+ it('installEngine: hands the runner the exact descriptor (command/args/options, no shell)', () => {
284
+ let received;
285
+ installEngine('win32', (d) => {
286
+ received = d;
287
+ return { status: 0 };
288
+ });
289
+ assert.equal(received.command, 'npx.cmd');
290
+ assert.deepEqual(received.args, [`${ENGINE_PACKAGE}@latest`, 'init']);
291
+ assert.equal(received.options.shell, undefined);
292
+ });
293
+ });
294
+
295
+ describe('kit installer — mandatory engine install (subprocess)', () => {
296
+ let dir;
297
+ beforeEach(async () => {
298
+ dir = await mkdtemp(join(tmpdir(), 'aw-kit-engine-'));
299
+ });
300
+ afterEach(async () => {
301
+ await rm(dir, { recursive: true, force: true });
302
+ });
303
+
304
+ it('--no-engine skips the engine install and prints the live-read STOP note (exit 0)', () => {
305
+ const target = join(dir, 'agent-workflow-kit'); // runInstaller appends --no-engine by default
306
+ const res = runInstaller(target);
307
+ assert.equal(res.status, 0, res.stderr);
308
+ assert.match(res.stdout, /--no-engine: skipped installing the methodology engine/);
309
+ assert.match(res.stdout, /@latest init/);
310
+ assert.match(res.stdout, /installed v|updated the kit/, 'the kit itself still installs');
311
+ });
312
+
313
+ it('D1: when `npx` cannot run (both attempts fail) → nonzero exit, recommendations, success block NOT printed first', async () => {
314
+ // Force both engine-install attempts to fail deterministically WITHOUT network: run a real install
315
+ // (no --no-engine) with an empty PATH so `npx` resolves to ENOENT. The kit copy + the version gate
316
+ // do not need PATH; only the engine spawn does. This exercises the D1 loud-error + nonzero exit.
317
+ const target = join(dir, 'agent-workflow-kit');
318
+ const emptyBin = join(dir, 'emptybin');
319
+ await mkdir(emptyBin, { recursive: true });
320
+ const res = spawnSync(process.execPath, [INSTALLER, '--dir', target, '--no-launchers'], {
321
+ encoding: 'utf8',
322
+ env: { ...process.env, PATH: emptyBin },
323
+ });
324
+ assert.notEqual(res.status, 0, 'an engine-install failure must exit nonzero');
325
+ assert.match(res.stderr, /FAILED to install the methodology engine/);
326
+ assert.match(res.stderr, /@latest init/, 'recommends the manual engine install');
327
+ assert.match(res.stderr, /--no-engine/, 'recommends the opt-out');
328
+ assert.doesNotMatch(res.stdout, /Next — open your agent/, 'must NOT claim success before the engine failed');
329
+ assert.ok(existsSync(join(target, 'SKILL.md')), 'the kit itself is still on disk (recovery is one step)');
330
+ });
331
+ });
332
+
333
+ describe('kit installer — published tarball bundles the bridges + the live-read tool', () => {
334
+ it('npm pack ships bridges/<name>/ and tools/engine-source.mjs', () => {
216
335
  // The real `files` whitelist decides what publishes — assert against `npm pack`, not the source
217
336
  // tree, so a dropped `bridges/` entry in package.json fails here (not silently at install time).
218
337
  const res = spawnSync('npm', ['pack', '--dry-run', '--json'], { cwd: KIT_ROOT, encoding: 'utf8' });
@@ -220,5 +339,9 @@ describe('kit installer — published tarball bundles the bridges', () => {
220
339
  const paths = JSON.parse(res.stdout)[0].files.map((f) => f.path);
221
340
  assert.ok(paths.includes('bridges/codex-cli-bridge/SKILL.md'), 'codex bridge SKILL.md not packed');
222
341
  assert.ok(paths.includes('bridges/antigravity-cli-bridge/bin/agy.sh'), 'antigravity agy.sh not packed');
342
+ assert.ok(paths.includes('tools/engine-source.mjs'), 'the live-read resolver must ship in the tarball');
343
+ // The retired mirror must NOT ship — the whole point of Plan 3D is one source of truth.
344
+ assert.ok(!paths.includes('tools/methodology-slot.md'), 'retired mirror tools/methodology-slot.md must not be packed');
345
+ assert.ok(!paths.includes('references/planning.md'), 'retired mirror references/planning.md must not be packed');
223
346
  });
224
347
  });
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": "1.10.0",
6
+ "version": "1.11.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": "1.10.0",
3
+ "version": "1.11.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",