@mmerterden/multi-agent-pipeline 24.5.0 → 24.6.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
@@ -14,6 +14,56 @@ Internal file-layout changes that don't affect the slash-command surface are sti
14
14
 
15
15
  ---
16
16
 
17
+ ## [24.6.0] - 2026-11-20
18
+
19
+ ### Changed
20
+
21
+ - The dev phase's skill routing is carried by the run's own mechanics instead of
22
+ by a step that has to be remembered. `write-state.mjs` resolves it on the
23
+ write that opens Phase 2, stores `telemetry.skillRouting`, and prints the
24
+ `index` skills to load; the write that closes Phase 2 is refused while any
25
+ kept toolkit's `index` is unrecorded (exit 6, nothing written). Both run on
26
+ every host, because every host moves its phases through that writer.
27
+ - `run-scope-guard.mjs` holds a code write inside a run's own tree while a kept
28
+ toolkit's `index` has not been loaded, and names the calls to make: a skill
29
+ read after the file is written cannot shape it. A run that reaches a code
30
+ write with no routing at all has one resolved for it there too. Bounded at two
31
+ holds per run, after which the same text arrives as a note - the phase's exit
32
+ refusal is what makes the requirement binding.
33
+ - `note-skill-use.mjs` appends every Skill tool call it observes to
34
+ `telemetry.skillLoads[]` of the run bound to that session, so what a phase
35
+ opened is read off the host rather than reported by the phase. Separate from
36
+ `skillCalls[]`, which carries the files a skill was applied to and stays the
37
+ phase's own attribution. Not gated by `skillUsage.enabled` or
38
+ `usageLog.optOut`: run telemetry is not passive collection, and nothing leaves
39
+ the machine either way.
40
+ - `skill-conformance.mjs` reads the post-condition back before it resolves
41
+ anything, and exits 4 without writing a manifest when the dev phase recorded
42
+ no routing or kept a toolkit it never consulted. The rules it resolves are the
43
+ ones the diff is held to, so a diff written without opening the skills its own
44
+ stack routes to has no chosen rule set behind it.
45
+
46
+ ### Added
47
+
48
+ - `pipeline/lib/dev-routing.mjs`: one definition of "the write that opens the
49
+ dev phase", "the write that closes it", and how the routing is resolved,
50
+ shared by the state writer and the run-scoped guard.
51
+ - `pipeline/scripts/check-skill-routing.mjs`: the post-condition as a command.
52
+ Exit 0 holds or there is nothing to check, 1 the state could not be read, 2
53
+ the routing is missing or a kept toolkit's `index` was never consulted.
54
+ `--require-done` additionally refuses to start review over a Phase 2 that
55
+ never closed; a review-only run, whose Phase 2 is skipped, is not held to it.
56
+ Criteria resolution calls it with that flag.
57
+ - `telemetry.skillLoads[]` in `agent-state.schema.json`.
58
+
59
+ ### Fixed
60
+
61
+ - `smoke-stack-skill-routing.sh` asserted the recording by grepping the phase
62
+ document for the words `skillCalls` and `routedBy`, which is a check on this
63
+ repo's own prose. It now drives the checker over synthetic states, drives the
64
+ state writer through a dev-phase open and close, and fails when either stops
65
+ refusing.
66
+
17
67
  ## [24.5.0] - 2026-11-19
18
68
 
19
69
  ### Changed
package/docs/facts.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$comment": "Generated by pipeline/scripts/gen-facts.mjs. Do not hand-edit: the site reads this, and a number edited here instead of at its source is the drift this file removes.",
3
- "generatedAt": "2026-11-19",
4
- "version": "24.5.0",
3
+ "generatedAt": "2026-11-20",
4
+ "version": "24.6.0",
5
5
  "phaseSchema": 2,
6
6
  "phases": [
7
7
  {
package/manifest.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@mmerterden/multi-agent-pipeline",
3
- "version": "24.5.0",
4
- "commit": "cc5822ea5c80ab14b9c2f6880c93aeae48775b93",
5
- "generatedAt": "2026-11-19T23:22:39.000Z",
3
+ "version": "24.6.0",
4
+ "commit": "2383b619775a721ae865c1ffcdeb53847d424353",
5
+ "generatedAt": "2026-11-20T15:43:08.000Z",
6
6
  "algorithm": "sha256",
7
- "fileCount": 1292,
7
+ "fileCount": 1294,
8
8
  "files": {
9
- "CHANGELOG.md": "739c71ffccf0636fab673681b4b8086ecb1c9816208bea1b8ced4f95368f0c98",
9
+ "CHANGELOG.md": "4e3844745f2d9baf7d3b766971ec47f08a871250d5b6e0de2ac1b1e2acfd972a",
10
10
  "LICENSE": "8d8c51aaf1e1538b180c69965fa038db71be86798cc3e26a143bebfefe16a43e",
11
11
  "README.md": "a817e88b17e96615484ad3ef451079254a64700b9a3de819a933cc3c0718d95f",
12
12
  "README.tr.md": "c9c91ba4586adf56d98b0ce9e92cc5461e8acdae5ea97407c7377b312415be80",
@@ -35,7 +35,7 @@
35
35
  "docs/best-practices.md": "d5d9b116a82ca9616c69bb9b3bebf06ee9d0f67be09b59962cee8b30f84e0041",
36
36
  "docs/ecosystem.md": "e0321b917812793d2b66f0e519af693e0f9317ee9e2f82ad5d8cb4dc1f67832c",
37
37
  "docs/engineering.md": "5c37fabddbe23675c743fe58a5e5db4dcca140fc316447c913c0ad606a8b26d9",
38
- "docs/facts.json": "4e6837342a66afec68d17b7943104d3b0b78cb6bd2b7b470bdb9c3c641bec901",
38
+ "docs/facts.json": "6eadfc35567297a2f6b8df08b270b9fab194dd223fec69855ada856a479a16b7",
39
39
  "docs/features.md": "1a545bcc05f1eed9099c2ca0dd9662a47d4a93bf49c1a69c40c65094d2833f07",
40
40
  "docs/performance.md": "7eca7991d3adf03b1df74335d8245b2f9142936fdbdb1eafd127e85b01d8b518",
41
41
  "docs/recovery-guide.md": "be0ec8f5b7d7658b90811a9aaedede94390da5a8eb57aa7c22f7ca533c8ef3ce",
@@ -69,7 +69,7 @@
69
69
  "install/templates/multi-agent-autopilot-awake.plist.template": "ddd25c76c56fcbb38a89de8e35637372d70ace993d6bc487a88ca9cfb702fe1f",
70
70
  "install/templates/multi-agent-autopilot.plist.template": "122c8a61cd927edd99375d6e3da40f1d42bcceed5b6641785c8b28bb930bc77e",
71
71
  "install/unattended-profile-legacy.json": "f52e86b998956f09ad306b1735a6c10b58580d7082d8a55665a4c6bb15c3aa1f",
72
- "package.json": "806491381fde771f7072bf081f8be0def8915e507ec31a3c58b71c23ddf1d165",
72
+ "package.json": "d97f53001b0a665ec8dbaa496bddf27058bf448535e0442fbad0ef6bf9dd31bd",
73
73
  "pipeline/agents/android-architect.md": "11fb74543cb0ebcf9525ca6654fe95d53da7229e0bf4a1149b31fd9005abc453",
74
74
  "pipeline/agents/backend-architect.md": "b02a606c301e4714131aed70ae6d16eeb77fbc819a001e2752cff2488d4246de",
75
75
  "pipeline/agents/bulk-reader.md": "5619d5fb3dee26da7b4c5b1f55d22584c9404e350c221d13bc25a70d88f75f8c",
@@ -216,6 +216,7 @@
216
216
  "pipeline/lib/cross-repo.mjs": "3296e9502a9913e4099923649686b8ec3312cb10e10c57ff8939a8ade0cd0639",
217
217
  "pipeline/lib/decisions.mjs": "ef662c9eabc6bdebc72b72881d643c1c8593495a29829766190b09a160f526e4",
218
218
  "pipeline/lib/detach-self.mjs": "251025f17248cd9bbf13a74fe0068e8ab36ef79e9aebea17a3eb20eaee250495",
219
+ "pipeline/lib/dev-routing.mjs": "5c490092bbe515a012fd59ebb3565a332d93e9806e3666042a644774e17a1ecf",
219
220
  "pipeline/lib/extract-conventions.sh": "f9a65376b21df2f8dd43502f1618f29af0cbe875ddbf90c51ca3590873a6105e",
220
221
  "pipeline/lib/fatal.mjs": "6b1e34d9f143df1ff9802df62ba77b27f83dccb72654e4351b882b9eb1ab2977",
221
222
  "pipeline/lib/fetch-confluence.sh": "69b48c77cda5eccd68e21a7f16526fbc05a2b11afafd896629b25102c629880f",
@@ -428,9 +429,9 @@
428
429
  "pipeline/multi-agent-refs/features/service-accounts.md": "24de169f69d51ed3fdc671693fd0bb95ddb098ddf051eb39f61e927d13a12aff",
429
430
  "pipeline/multi-agent-refs/features/session-brief.md": "02d5c7f67907af9ea072a19d23323b1f9fb95b145ab562f3eac795d38d27a9a9",
430
431
  "pipeline/multi-agent-refs/features/shadow-git.md": "d020c7b99a993eb11398d08e0518207b990b3ec3807fbcf0926c6cb304777ce9",
431
- "pipeline/multi-agent-refs/features/skill-conformance.md": "058c6bf53fd71701920210cde5b310ec1b897ea9068b802e6fbf771b9a6cfbdc",
432
+ "pipeline/multi-agent-refs/features/skill-conformance.md": "f3b3a55c2d5e3262df7d03a8fa900eb910b484bd9741a2389f84a43609425fd3",
432
433
  "pipeline/multi-agent-refs/features/stack-adapters.md": "71e23385da872ceed35263f4838f154800aa2da55bb6688ccca74726b70a3ef5",
433
- "pipeline/multi-agent-refs/features/stack-skill-routing.md": "1989f7f64be6c5ee0a42d8e9962aead7cd7472d795915ab953d89d9382f317e6",
434
+ "pipeline/multi-agent-refs/features/stack-skill-routing.md": "fe82efcb1e0ab515e000d5d1955f2a725c187f3f9486e30b39f8eb0b19e5b4a5",
434
435
  "pipeline/multi-agent-refs/features/test-classification.md": "6ddb2d24d18ba70242bb58e3c5f68c44b7de78e38238210abc60c771e5af8b4b",
435
436
  "pipeline/multi-agent-refs/features/test-gap.md": "a5c2da90840c74b56e859809919cf9f8282d6a2605a5989ff2bc46167090eb8c",
436
437
  "pipeline/multi-agent-refs/features/unattended-gates.md": "da9e9d7cc4bec0dfb16bf0ead44760ef40f83eb72881629ecf7685e85400d5b0",
@@ -468,7 +469,7 @@
468
469
  "pipeline/multi-agent-refs/phases/operations.md": "0ddf16da2464b73851a8094e57bf7ef5ccb9220214b8895284377569d16f9fcc",
469
470
  "pipeline/multi-agent-refs/phases/phase-0-init.md": "8c8d95d5402c454a03f3fd60b98b6ae733f447f1b0b762a30633487fa2c1220b",
470
471
  "pipeline/multi-agent-refs/phases/phase-1-plan.md": "fca72a1a7026c4321c4c819e30a3da933cafd479139e27b819148bd9fa3acb1d",
471
- "pipeline/multi-agent-refs/phases/phase-2-dev.md": "b206ef27f4e57a80f0e3aaaf18639b57b53115edb3f530288ef490ea3c7ac12f",
472
+ "pipeline/multi-agent-refs/phases/phase-2-dev.md": "cc183001bb3cb6279474cadf12b39c747f4bc6caa19067c9429285423d9ed7f7",
472
473
  "pipeline/multi-agent-refs/phases/phase-3-review.md": "a672a284d267dc5e7f85a543446fedfc7c86d361e025f36fe77e3f4787cef3c4",
473
474
  "pipeline/multi-agent-refs/phases/phase-4-commit.md": "6fe29d816d2b4d61fef3a4da8d89794e54411583bd8ebe108b2f73c855099208",
474
475
  "pipeline/multi-agent-refs/phases/phase-5-report.md": "15d64f90784f8df39134212bcd646eefed08b687bbc74c082f881c7577fecce9",
@@ -637,7 +638,7 @@
637
638
  "pipeline/schemas/activity-roles.json": "bb7062d2405e0db9e68d3c66f4c5b5cd8ffdb811ec872e79534530d2927b8636",
638
639
  "pipeline/schemas/activity-roles.schema.json": "c333707783e29aed6377431dda00dad5ad0554b68c2ac772418d872b9c4947a2",
639
640
  "pipeline/schemas/activity.schema.json": "ee941ef62b1b44224cea0856225c8a705c4e9638c1afb24aebf06165ddadafba",
640
- "pipeline/schemas/agent-state.schema.json": "8a3d8db5aea40a419bcd81de8f2d22d419c1485cec0df218c846a153c7cce66c",
641
+ "pipeline/schemas/agent-state.schema.json": "9d6902479db1a1f86c1018a6fe273d63009f826f72a88e47a06eddd21cdeb227",
641
642
  "pipeline/schemas/analysis-output.schema.json": "3df1f03022d7e15b0f51f8748f4c36db170c74b67865f2292e0164b7c54f598c",
642
643
  "pipeline/schemas/analysis-spec.schema.json": "6192ba6a813ead3e6ab53095548556b406169a870211d9854f4491f9899a189e",
643
644
  "pipeline/schemas/answer-request.schema.json": "ba61b09052b70c64fc3e026cdbda6b4a90c2b2230245b43b5865a39cfe74ef55",
@@ -908,6 +909,7 @@
908
909
  "pipeline/scripts/check-derived-drift.mjs": "9d0cb0a7254b4e24932d6c557b53fc2e352cdb263ed37990620752187b4415be",
909
910
  "pipeline/scripts/check-read-size.py": "c87763d0d5745e2d5a149fea64b00e4a6f4f2835073a9cdd66c1632ee1f5391d",
910
911
  "pipeline/scripts/check-read-size.sh": "e596810d72eb1c7e9970501d31e406fc568055e20a88a8a0d81a2a3669c2b04d",
912
+ "pipeline/scripts/check-skill-routing.mjs": "452e0afee22f7d8f05629ba479977a5e15143c2a2b8a01b33e78f051028b4f13",
911
913
  "pipeline/scripts/checkpoint-fold.sh": "a60512eedf1980ff7508c9a29eeb4ee54d82b8aeb728468bae7f7e5d2211f04f",
912
914
  "pipeline/scripts/classify-plan-safety.mjs": "2d60614cff54e2fbf95d44a37cb8516852f6dcf4dc2c72c2ba7714a6a2b0d5c1",
913
915
  "pipeline/scripts/code-graph-rules/android.json": "62945571d2c18532824f21842e8ab7fa8a4c3507cbe8486502e89f7ff4d7cc37",
@@ -1014,7 +1016,7 @@
1014
1016
  "pipeline/scripts/note-mcp-failure.mjs": "0a2a2f738ef6e9ea5b94e4b72509b2d74adccffe2a49b8c751936ff052d9aa29",
1015
1017
  "pipeline/scripts/note-mcp-failure.sh": "8dbf3a3f7676b61c2d7a1c408e39f384d2196133c3422dc154848b5bb0717fa2",
1016
1018
  "pipeline/scripts/note-session.sh": "3fa4670025ac1daebba848942a454072ae7352c8cc043378ba420ec1736dc800",
1017
- "pipeline/scripts/note-skill-use.mjs": "bc01a1d0820d4c3f14a3295c4964dd7aaebb67453dee187200d01a06cb27866c",
1019
+ "pipeline/scripts/note-skill-use.mjs": "83768730c688574f4c669ac4374f91b1e69ef41c1d485738c71488221728d9e9",
1018
1020
  "pipeline/scripts/note-skill-use.sh": "32ae95acac7b71d01a433c8af188a824e4cbbac05385891956c7cedf7cd82736",
1019
1021
  "pipeline/scripts/observations.mjs": "a578535dab1025f1eed84013c2afd47d3d9db0b6b49ceae2c49961c64fec1101",
1020
1022
  "pipeline/scripts/office-archive.mjs": "0eacc7ac3287866cd539a7034c0382de5986112c1496750619ab03a9d004256e",
@@ -1108,7 +1110,7 @@
1108
1110
  "pipeline/scripts/run-log.mjs": "782ccd7f0e723bd5485fac47179e410b640e3a5c150064b0eb52df6f2cfffc7e",
1109
1111
  "pipeline/scripts/run-metrics.mjs": "72a6d269dd53de63f451b70b9202c657e61d89c9ef1e1b47b64a39a40ae0a3c1",
1110
1112
  "pipeline/scripts/run-results.mjs": "f29a8a8a7102d7065a5b883ecc6d90f669df24438dbc77cfa3a45d91d8a2ed9a",
1111
- "pipeline/scripts/run-scope-guard.mjs": "d2ae8b50dae3c00085caa361bf6a29c0e1c1275a21429a4f0bd32a7dbc88d08a",
1113
+ "pipeline/scripts/run-scope-guard.mjs": "4e105667bf1b94595a0aec80c1a22b2d03b7e32298fdf98a732d827207446d6b",
1112
1114
  "pipeline/scripts/run-scope-guard.sh": "b7ff914c6de774636f5ea4ca47797be8ae788c214c1baf4d57b0d8f20fa64a17",
1113
1115
  "pipeline/scripts/run-stop-guard.mjs": "12b07239c4e6688fdb76291a4fcdae050dc64d88c523ec9ed6f1abd06426a0fc",
1114
1116
  "pipeline/scripts/run-stop-guard.sh": "5c8281e283203e9314c78a26aa0026f81a6ad5afcf06dfdfd7bd9b3f55810d64",
@@ -1128,7 +1130,7 @@
1128
1130
  "pipeline/scripts/sign-skills.sh": "779355dcf8ce383959e9a3c6093f46660a0875e83a805b7a67983acc8551cb59",
1129
1131
  "pipeline/scripts/skill-candidates.mjs": "6bbf69ff774d0e93263e995f70cb67cf61484566badbd6388c4066012fd5ea47",
1130
1132
  "pipeline/scripts/skill-catalog.mjs": "df973c061e8d85bbffe825ecb0e81d0ca8dab8838f493a95b85706ec4415e9fe",
1131
- "pipeline/scripts/skill-conformance.mjs": "0986c0fee9bf79494ab35add60d8d34363928100ca12a0819ea4cde624622025",
1133
+ "pipeline/scripts/skill-conformance.mjs": "82f377c57397a9d4de6c15f41be4f356e02ce03d621c467a6f2838d462f45c92",
1132
1134
  "pipeline/scripts/skill-siblings.mjs": "39aa1705cf919d277c73f5f9bbe690c8fca5a11ac46097d628deebf873663ea2",
1133
1135
  "pipeline/scripts/skill-usage.mjs": "efe7a3213093e9139b8d320a03f0e22fa579c8c74c493b3abff865a83d8f00f9",
1134
1136
  "pipeline/scripts/smoke-cross-cli-behavior.sh": "d65b7e0d2899c222e1210650d5ae72f7faffb96583c29f6f21d22d05cc724578",
@@ -1199,7 +1201,7 @@
1199
1201
  "pipeline/scripts/worktree-prepare-all.mjs": "ead3999de481b83f123a8327cc4e9f9e65801ec573f609aed3219457626babfa",
1200
1202
  "pipeline/scripts/worktree-prepare.sh": "7341a756358a10dbd24d1ec9708b78a273f660435cf1051dc322b1983991b0fe",
1201
1203
  "pipeline/scripts/worktrees.mjs": "62a36279c0dfbe9360262b4995b639a7de7297ed26b62afe66e8d34111e1aa06",
1202
- "pipeline/scripts/write-state.mjs": "8b869e172be27db2a609d7bc6dbb20f68b0a21452640899783ccd796e2dcfdbb",
1204
+ "pipeline/scripts/write-state.mjs": "f0386192513de3cbeb750d9c9e5c248107f265d67006dee547415f871d385f01",
1203
1205
  "pipeline/scripts/write-store-config.mjs": "c9bd3131190b3b0d5eb7d363c832cb5ecf0c4f818492610430ba5e1349604ff9",
1204
1206
  "pipeline/skills/.skill-manifest.json": "8d92c519dfaae8f62212f5f2b220f064e273c61ae7ad874524e7fe9744eba2cb",
1205
1207
  "pipeline/skills/.skills-index.json": "a8bc3146640ebd48748406b5a210264b8eeace30a5fdac84e439fcbf408c96b7",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmerterden/multi-agent-pipeline",
3
- "version": "24.5.0",
3
+ "version": "24.6.0",
4
4
  "description": "6-phase AI development pipeline with full orchestration on Claude Code, Copilot CLI and Codex CLI. Analysis, planning, TDD, CLI-aware parallel review with consensus surfacing + Fable triage, default-FAIL evidence gates, secret + intent guards, per-phase cost ledger, persistent learnings memory, wiki generation, commit automation. Token-preserving uninstall.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -0,0 +1,124 @@
1
+ /**
2
+ * @file dev-routing.mjs - the dev phase's skill routing, in one place.
3
+ *
4
+ * Which skills govern a change is decided by the stack toolkits the repo
5
+ * enables, and the decision has to be made before the first line is written
6
+ * and kept where the rest of the run can read it. Three callers need the same
7
+ * answer: the state writer resolves it on the write that opens the dev phase,
8
+ * the run-scoped PreToolUse guard resolves it for a run that arrives at a code
9
+ * edit without one, and the post-condition checker reads it back.
10
+ *
11
+ * The transition predicates live here for the same reason: "the write that
12
+ * opens Phase 2" and "the write that closes it" are the same two questions for
13
+ * the writer and the guard, and two spellings of them would drift.
14
+ *
15
+ * @module pipeline/lib/dev-routing
16
+ */
17
+
18
+ import { existsSync } from "node:fs";
19
+
20
+ import { modeOf } from "./run-completion.mjs";
21
+
22
+ /**
23
+ * Whether the run's mode writes code, and so has skills to route.
24
+ *
25
+ * Stated as the one exclusion rather than a list of included modes: an
26
+ * analysis run's artefact is a document and has no diff to govern, while every
27
+ * other mode - full, autopilot, dev, and whatever is added next - writes code
28
+ * and is held to the requirement without the list being widened. The
29
+ * transition predicates below do the rest of the gating, so a mode that never
30
+ * opens or closes Phase 2 is never asked for a routing either way.
31
+ */
32
+ export function hasDevPhase(state) {
33
+ return !modeOf(state).startsWith("analysis");
34
+ }
35
+
36
+ /**
37
+ * The phase the routing belongs to. Deliberately not exported: the resolver
38
+ * already publishes this number for its own callers, and a second public name
39
+ * for it would be a second thing to keep in step.
40
+ */
41
+ const PHASE = 2;
42
+
43
+ const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : null);
44
+ const statusOf = (state) => state?.phases?.[String(PHASE)]?.status ?? null;
45
+
46
+ /**
47
+ * Whether this write is the one that opens the dev phase: either the run moves
48
+ * into it, or the phase's own status turns to in_progress.
49
+ */
50
+ export function opensDevPhase(next, was = {}) {
51
+ const from = num(was.currentPhase) ?? 0;
52
+ const entering = from < PHASE && num(next?.currentPhase) === PHASE;
53
+ const starting = statusOf(next) === "in_progress" && statusOf(was) !== "in_progress";
54
+ return Boolean(entering || starting);
55
+ }
56
+
57
+ /**
58
+ * Whether this write is the one that closes the dev phase: either the run
59
+ * leaves it, or the phase's own status turns to done.
60
+ */
61
+ export function closesDevPhase(next, was = {}) {
62
+ const leaving = num(was.currentPhase) === PHASE && (num(next?.currentPhase) ?? 0) > PHASE;
63
+ const closing = statusOf(next) === "done" && statusOf(was) !== "done";
64
+ return Boolean(leaving || closing);
65
+ }
66
+
67
+ /** Whether a live run is inside its dev phase right now. */
68
+ export function inDevPhase(state) {
69
+ if (!hasDevPhase(state)) return false;
70
+ if (statusOf(state) === "done") return false;
71
+ return num(state?.currentPhase) === PHASE || statusOf(state) === "in_progress";
72
+ }
73
+
74
+ /** The first readable directory the run calls its own, or null. */
75
+ export function repoOf(state) {
76
+ return (
77
+ [state?.worktreePath, state?.projectRoot].find(
78
+ (d) => typeof d === "string" && d && existsSync(d),
79
+ ) ?? null
80
+ );
81
+ }
82
+
83
+ /**
84
+ * Resolve the routing for one run, as the resolver answers it.
85
+ *
86
+ * Returns null when it cannot be resolved, and never a half-answer: an empty
87
+ * `toolkits` means the resolver kept none, and that has to stay different from
88
+ * "nothing was resolved", which is the distinction the stored field exists to
89
+ * keep.
90
+ *
91
+ * @param {object} state
92
+ * @param {{recordedBy: string, now?: () => string}} opts
93
+ * @returns {Promise<object|null>}
94
+ */
95
+ export async function resolveRouting(state, { recordedBy, now = () => new Date().toISOString() }) {
96
+ const repo = repoOf(state);
97
+ if (!repo) return null;
98
+ const { resolveSkillCandidates, matchRepoSkills } =
99
+ await import("../scripts/skill-candidates.mjs");
100
+ const out = resolveSkillCandidates(repo, { state });
101
+ const routing = {
102
+ mode: out.mode,
103
+ toolkits: out.toolkits,
104
+ excluded: out.excluded,
105
+ unscoped: out.unscoped,
106
+ hints: out.hints,
107
+ fallbacks: out.fallbacks,
108
+ recordedBy,
109
+ resolvedAt: now(),
110
+ };
111
+ const task = [state?.title, state?.taskSummary]
112
+ .filter((t) => typeof t === "string" && t)
113
+ .join(" ");
114
+ if (task) routing.repoMatches = matchRepoSkills(out.repoSkills, task);
115
+ return routing;
116
+ }
117
+
118
+ /** The line that tells a phase which index skills to open, given a routing. */
119
+ export function loadLine(routing) {
120
+ const kept = (routing?.toolkits ?? []).map((t) => t?.name).filter(Boolean);
121
+ return kept.length
122
+ ? `load ${kept.map((n) => `${n}:index`).join(", ")} before writing code`
123
+ : "no toolkit applies to this repo";
124
+ }
@@ -114,8 +114,9 @@ Exit codes:
114
114
  | `0` | manifest written; may still carry findings or declared coverage gaps |
115
115
  | `1` | setup error: no diff, unreadable state, or an explicit `--skills-root` that does not exist |
116
116
  | `2` | **fail closed**: no skills root resolved at all, a declared registry could not be parsed, or a declared registry path escaped its skill directory |
117
+ | `4` | **fail closed**: the dev phase recorded no skill routing, or kept a toolkit it never consulted. Read with `--state` only, and only once Phase 2 has closed; no manifest is written. Contract: [`features/stack-skill-routing.md`]($HOME/.claude/multi-agent-refs/features/stack-skill-routing.md) |
117
118
 
118
- Any non-zero code halts before the reviewers. Continuing on `2` would drop a whole rule set from the denominator; and because `validate-reviewer.mjs` skips the checklist when zero rules were selected, an empty resolution would otherwise render as a clean review over criteria that were never loaded. An empty registry set inside a root that DOES exist is the different, legitimate case: declared coverage gap, exit 0.
119
+ Any non-zero code halts before the reviewers. `4` is the same failure as `2` one step earlier: the rules resolved here are the ones the diff is held to, so a diff written without opening the skills its own stack routes to has no chosen rule set behind it, and a manifest over it would read as criteria when it is a default. Continuing on `2` would drop a whole rule set from the denominator; and because `validate-reviewer.mjs` skips the checklist when zero rules were selected, an empty resolution would otherwise render as a clean review over criteria that were never loaded. An empty registry set inside a root that DOES exist is the different, legitimate case: declared coverage gap, exit 0.
119
120
 
120
121
  `skillsRootsSearched` lists every candidate root that was probed with an `existed` flag, not only the ones found - otherwise the field is empty in exactly the case it exists to explain.
121
122
 
@@ -10,7 +10,7 @@
10
10
  - [What this deliberately does NOT do](#what-this-deliberately-does-not-do)
11
11
  <!-- /toc -->
12
12
 
13
- > **TLDR** - Phase 2 (Dev) asks each kept toolkit plugin's own `index` skill which of its skills apply to this task, loads them before writing code, and records each into `state.telemetry.skillCalls[]`. The routing table lives in the plugin; the pipeline copies none of it, and does not keep a stack-to-plugin table either - it reads the enabled set, drops inherited toolkits that contradict the repo's detected stack, and puts the repo's own `.claude/skills` ahead of both. The step runs for every task; with no toolkit it is a recorded no-op.
13
+ > **TLDR** - Phase 2 (Dev) asks each kept toolkit plugin's own `index` skill which of its skills apply to this task, loads them before writing code, and records each into `state.telemetry.skillCalls[]`. Three mechanisms carry it rather than one instruction: the write that opens the phase resolves the routing itself, a code write before the routed index was loaded is held, and the write that closes the phase is refused while any kept toolkit's index is unrecorded. The routing table lives in the plugin; the pipeline copies none of it, and does not keep a stack-to-plugin table either - it reads the enabled set, drops inherited toolkits that contradict the repo's detected stack, and puts the repo's own `.claude/skills` ahead of both. The step runs for every task; with no toolkit it is a recorded no-op.
14
14
  >
15
15
  > The same routing applies outside a run: `rules/outside-the-pipeline.md` carries it for ordinary sessions. One discipline, two callers; only the recording is run-specific.
16
16
 
@@ -31,18 +31,25 @@ Phase 2 (Dev) pre-flight, before any code is written, for **every** `taskType` a
31
31
  ## Resolution
32
32
 
33
33
  **Read the enabled set, filter it by the repo's stack; do not keep a stack table.**
34
- Candidates come from one resolver, run before the index call. The task text goes
35
- through a file, never through a shell string: write the task title and one-line
36
- intent to `$TASK_FILE` with the Write tool, then
34
+ Candidates come from one resolver, and it is run for the phase rather than by it:
35
+ `write-state.mjs` resolves on the write that opens Phase 2 (`lib/dev-routing.mjs`,
36
+ in-process, with the run's own state so the mode is right) and stores the answer
37
+ before any code exists. The kept toolkits are printed on that write's stderr, so
38
+ the phase reads which `index` skills to open as the output of a command every
39
+ host has to run.
40
+
41
+ Outside a run, and for any state that needs the answer recomputed, the same
42
+ resolver is a CLI:
37
43
 
38
44
  ```bash
39
45
  node $HOME/.claude/scripts/skill-candidates.mjs resolve --dir "$PROJECT_ROOT" \
40
46
  --state "$STATE_FILE" --task-file "$TASK_FILE"
41
47
  ```
42
48
 
43
- `--task -` reads the same text from stdin. `--task "<text>"` still takes a literal,
44
- but ticket titles are untrusted input and a literal puts them inside a shell
45
- command, so no pipeline document uses it.
49
+ The task text goes through a file, never a shell string. `--task -` reads it from
50
+ stdin. `--task "<text>"` still takes a literal, but ticket titles are untrusted
51
+ input and a literal puts them inside a shell command, so no pipeline document
52
+ uses it.
46
53
 
47
54
  Pass `--state "$STATE_FILE"` inside a run so autopilot is recognised. It prints JSON
48
55
  with `mode`, `toolkits[]` (kept, each with `role`, `reason`, `source`, `version`),
@@ -206,6 +213,10 @@ A repo-local skill carries `source: "repo"` and `routedBy: "repo:.claude/skills"
206
213
 
207
214
  `routedBy` names the index and version that chose it. That is the difference between "the model happened to read a skill" and "the toolkit said this skill governs this task".
208
215
 
216
+ On a host that installs hooks, `telemetry.skillLoads[]` carries the same calls as the host saw them: one row per Skill tool call, written by `note-skill-use.mjs` into the run bound to that session. It is deliberately a second field rather than an entry in this one, because a hook sees the call and not the files a phase applied the skill to, and an entry with an empty `targetFiles` would read as "applied to nothing". The two answer different questions: `skillLoads[]` whether a skill was opened, `skillCalls[]` what it was applied to.
217
+
218
+ Both are a post-condition of a finished Phase 2, not a courtesy. `scripts/check-skill-routing.mjs` requires `skillRouting` to carry the resolver's own `mode` and `toolkits`, and requires every kept toolkit's `index` to be evidenced by either field - observed by the hook, or declared by the phase, which is what a host with no hooks has. The check reports which it got rather than leaving the reader to assume. It is read back in three places: the write that closes the phase (`write-state.mjs`, exit 6), Phase 3's criteria resolution (`skill-conformance.mjs --state`, exit 4, before it writes a manifest), and the guard's hold on a code write. Exit codes of the checker itself: 0 holds or nothing to check, 1 the state could not be read, 2 the post-condition is violated. A kept-nothing run passes with an empty `toolkits`; a run that resolved nothing does not.
219
+
209
220
  Usage reporting (`scripts/usage-report.mjs`) never sends a repo-local skill's name, which the repo's owner chose: it sends the constant `repo-local`. A `marketplace-fallback` entry keeps its name only when the toolkit is one the public marketplace carries, and is sent as `marketplace-fallback` otherwise.
210
221
 
211
222
  What Phase 3 (Review) does with it, precisely: Step 1.78 lists these entries in the manifest under `ledger.routedByToolkit`, so a reviewer and the Phase 5 report can see which skills the project's own toolkit selected. It does **not** give them extra weight in the coverage maths. The deterministic resolver stays primary because an unrecorded load and no load are indistinguishable in state, and no `routedBy` tag changes that - the tag says who chose the skill, not that the code honoured it.
@@ -224,7 +235,18 @@ What Phase 3 (Review) does with it, precisely: Step 1.78 lists these entries in
224
235
  | `index` resolves but routes to a skill that does not exist in this version | record the miss with the version, load the rest, continue. A stale row in a plugin's table must not stop a run |
225
236
  | `index` itself does not resolve | record and fall back to the host's own description matching - no worse than having no routing step |
226
237
 
227
- Nothing here blocks Phase 2. What is downstream is visibility, not enforcement: routed skills appear in the manifest's `ledger.routedByToolkit`, and a task that recorded nothing shows up as `ledgerSource: derived` with its coverage gap stated. Enforcement over rule IDs is the registry's job (`features/skill-conformance.md`), not this step's.
238
+ Nothing in the table blocks Phase 2: each row is the step running and finding nothing to route to, which is an answer. What blocks is the step not running, and it blocks three times over, in the order a run meets them:
239
+
240
+ | Where | What it does |
241
+ |---|---|
242
+ | the write that opens Phase 2 | resolves the routing and stores it, so the choice is made before the first edit exists |
243
+ | a code write in Phase 2 (hosts with hooks) | held while a kept toolkit's `index` is unloaded, bounded at `MAX_ROUTING_STOPS` holds per run, then the same text as a note |
244
+ | the write that closes Phase 2 | refused while any kept toolkit's `index` is unrecorded, on every host |
245
+ | Phase 3 criteria resolution | exits 4 and writes no manifest, for a state that reached review another way |
246
+
247
+ The distinction the fields keep is the whole point: "no toolkit applied" is a recorded verdict, "nothing was resolved" is an unanswered question, and a review over the second reports clean against rules nobody chose. The hold is bounded and the refusal is not, because a hold that could not be passed would strand a run while the refusal cannot be passed without doing the thing.
248
+
249
+ Enforcement over rule IDs stays the registry's job (`features/skill-conformance.md`). What this step owes is its own answer, recorded.
228
250
 
229
251
  ## What this deliberately does NOT do
230
252
 
@@ -39,7 +39,7 @@ Pre-flight steps (run in order, abort on failure).
39
39
 
40
40
  `targetFiles` is required - without it a skill applied to the wrong files still reads as "applied". Append at the moment of consultation, not at the end of the phase. Phase 3 Step 1.78 treats this as self-report only and resolves criteria independently; it is the one signal separating "applied to the wrong files" from "never opened".
41
41
 
42
- 9. **Stack skill routing (every `taskType`, always)**: write the task title + intent to `$TASK_FILE` with the Write tool (never a shell string), run `node $HOME/.claude/scripts/skill-candidates.mjs resolve --dir "$PROJECT_ROOT" --state "$STATE_FILE" --task-file "$TASK_FILE"`, and store its `mode`, `toolkits`, `excluded`, `unscoped`, `hints` and `fallbacks` in `state.telemetry.skillRouting`. Ask each kept toolkit's own `index` which skills govern this task, load them BEFORE writing code, and record each into `state.telemetry.skillCalls[]` with `phase: 2` and `routedBy: "<toolkit>:index@<version>"`. Precedence: repo-local skill (`source: "repo"`) > detected-stack toolkit skill > common toolkit; `overlaps[]` names the owner of a skill two toolkits share. Unattended or autopilot runs load `fallbacks[]` read-only (`source: "marketplace-fallback"`) and never route to `unscoped[]`; a missing stack toolkit is a hint, never another stack's toolkit. The routing table stays in the plugin. A screen-creation task loads the routed toolkit's `workflow/create-screen` when one exists. No toolkit is a recorded no-op, not a halt. Contract: [`features/stack-skill-routing.md`]($HOME/.claude/multi-agent-refs/features/stack-skill-routing.md).
42
+ 9. **Stack skill routing (every `taskType`, always)**: the write that opens this phase resolves the routing itself - `write-state.mjs` runs the resolver in-process, stores `mode`, `toolkits`, `excluded`, `unscoped`, `hints` and `fallbacks` in `state.telemetry.skillRouting`, and prints the line `skill routing resolved - load <toolkit>:index, ... before writing code`. That line is the step's input: **load each named `index` through the Skill tool before the first edit**, ask it which of its skills govern this task, load those too, and record each into `state.telemetry.skillCalls[]` with `phase: 2`, `targetFiles` and `routedBy: "<toolkit>:index@<version>"`. A host with hooks also writes `telemetry.skillLoads[]` for every Skill call it sees, so what was opened is not this phase's to remember; the ledger entry stays what attributes a skill to files. Nothing is resolved by hand: a code write before a kept index was loaded is stopped by `run-scope-guard`, and the write that closes this phase is refused while any kept index is unrecorded (`write-state.mjs` exit 6). Precedence: repo-local skill (`source: "repo"`) > detected-stack toolkit skill > common toolkit; `overlaps[]` names the owner of a skill two toolkits share. Unattended or autopilot runs load `fallbacks[]` read-only (`source: "marketplace-fallback"`) and never route to `unscoped[]`; a missing stack toolkit is a hint, never another stack's toolkit. The routing table stays in the plugin. A screen-creation task loads the routed toolkit's `workflow/create-screen` when one exists. No toolkit is a recorded no-op, not a halt. Contract: [`features/stack-skill-routing.md`]($HOME/.claude/multi-agent-refs/features/stack-skill-routing.md).
43
43
 
44
44
  10. **Autopilot** (or `MULTI_AGENT_UNATTENDED=1`): a run that Phase 1's `open-questions-gate.mjs` parked (`waitingFor: "question"`), or that `spec-consistency-gate.mjs` or `plan-critique-gate.mjs` failed (`verificationFailed.gate: spec-consistency` / `plan-critique`), does not enter this phase. When `state.research.md` exists, read it before writing code: what research closed, each answer with its source ([`features/research.md`]($HOME/.claude/multi-agent-refs/features/research.md)).
45
45
 
@@ -898,6 +898,36 @@
898
898
  }
899
899
  }
900
900
  }
901
+ },
902
+ "skillLoads": {
903
+ "type": "array",
904
+ "description": "One entry per Skill tool call observed by the note-skill-use hook, on a host that installs hooks, appended to the run bound to that session. Unlike skillCalls[] this is not a self-report: it answers whether a skill was opened at all, and carries no targetFiles, because the hook sees the call and not the files the phase applied it to. check-skill-routing.mjs accepts either field as evidence that a kept toolkit's index was consulted, so a host with no hooks is held to the same requirement through the self-report.",
905
+ "items": {
906
+ "type": "object",
907
+ "required": ["skill", "outcome", "timestamp"],
908
+ "additionalProperties": true,
909
+ "properties": {
910
+ "skill": {
911
+ "type": "string",
912
+ "minLength": 1,
913
+ "description": "Skill name as invoked, e.g. ai-ios-toolkit:index."
914
+ },
915
+ "outcome": {
916
+ "type": "string",
917
+ "enum": ["ok", "error"],
918
+ "description": "ok from PostToolUse, error from PostToolUseFailure. An errored load is recorded: it says the skill was reached for and did not arrive."
919
+ },
920
+ "timestamp": { "type": "string", "description": "ISO-8601 time the hook ran." },
921
+ "phase": {
922
+ "type": "integer",
923
+ "minimum": 0,
924
+ "maximum": 5,
925
+ "description": "The run's currentPhase when the call was observed."
926
+ },
927
+ "host": { "type": "string", "description": "Host that observed the call." },
928
+ "recordedBy": { "type": "string", "description": "The hook that wrote the entry." }
929
+ }
930
+ }
901
931
  }
902
932
  }
903
933
  },
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file check-skill-routing.mjs - Phase 2's skill routing, checked from the
4
+ * state file instead of from the prose that asks for it.
5
+ *
6
+ * Phase 2 pre-flight resolves which toolkit skills govern the task, asks each
7
+ * kept toolkit's own `index` which of its skills apply, and records both: the
8
+ * resolver's answer in `telemetry.skillRouting`, every loaded skill in
9
+ * `telemetry.skillCalls[]` with `routedBy`. Those two fields are the only
10
+ * evidence that the step ran at all, so Phase 3 reads them as a post-condition
11
+ * of a finished Phase 2 before it reviews the code that step was supposed to
12
+ * govern.
13
+ *
14
+ * Two requirements, both read off the state:
15
+ * 1. routing recorded `telemetry.skillRouting` carries a `mode` the
16
+ * resolver can produce and a `toolkits` array
17
+ * 2. index asked every kept toolkit has a `telemetry.skillCalls[]`
18
+ * entry naming its `index`, directly or through
19
+ * `routedBy`
20
+ *
21
+ * Nothing here is skipped for being inconvenient: a run resumed from before
22
+ * the step existed fails the same way, and satisfying it costs one resolver
23
+ * call. A check that exempted those runs would pass on exactly the states it
24
+ * was written to catch.
25
+ *
26
+ * Usage:
27
+ * node check-skill-routing.mjs --state <agent-state.json> [--json] [--out <file>]
28
+ * [--require-done]
29
+ *
30
+ * `--require-done` is for the caller that is about to start review: a phase 2
31
+ * left in any state but `done` or `skipped` is then a violation of its own,
32
+ * because review would otherwise begin over code whose dev phase never closed.
33
+ * `skipped` stays legitimate - a review-only mode has no dev phase to route -
34
+ * and so does a document with no phase table, which is not a run under review.
35
+ *
36
+ * Exit codes:
37
+ * 0 the post-condition holds, or there is nothing to check yet
38
+ * 1 setup error: no --state, unreadable file, or invalid JSON
39
+ * 2 Phase 2 finished without recording the routing it was required to run
40
+ */
41
+
42
+ import { readFileSync, writeFileSync, existsSync } from "node:fs";
43
+
44
+ import { ArgsError, parseArgs as parseArgv } from "../lib/args.mjs";
45
+ import { exitOnHelp } from "../lib/cli-help.mjs";
46
+
47
+ exitOnHelp(import.meta.url);
48
+
49
+ const MODES = ["attended", "unattended", "autopilot"];
50
+
51
+ function options(argv) {
52
+ const { flags } = parseArgv(argv, {
53
+ strings: ["state", "out"],
54
+ booleans: ["json", "require-done"],
55
+ unknown: "error",
56
+ positionals: false,
57
+ });
58
+ return {
59
+ state: flags.state ?? null,
60
+ out: flags.out ?? null,
61
+ json: Boolean(flags.json),
62
+ requireDone: Boolean(flags["require-done"]),
63
+ };
64
+ }
65
+
66
+ /**
67
+ * The post-condition itself, with no opinion about whether this state is due to
68
+ * satisfy it yet: routing recorded, and every kept toolkit's index asked.
69
+ * `write-state.mjs` calls this on the write that closes Phase 2, which is the
70
+ * moment the requirement falls due.
71
+ *
72
+ * @param {object} state
73
+ * @returns {Array<{requirement: string, detail: string, fix: string, toolkit?: string}>}
74
+ */
75
+ export function routingViolations(state) {
76
+ const violations = [];
77
+ const telemetry = state?.telemetry;
78
+ const routing =
79
+ telemetry &&
80
+ typeof telemetry.skillRouting === "object" &&
81
+ !Array.isArray(telemetry.skillRouting)
82
+ ? telemetry.skillRouting
83
+ : null;
84
+
85
+ if (!routing) {
86
+ violations.push({
87
+ requirement: "routing recorded",
88
+ detail:
89
+ "telemetry.skillRouting is absent: the pre-flight resolver either never ran or its answer was not stored",
90
+ fix: "run skill-candidates.mjs resolve for this repo and store mode, toolkits, excluded, unscoped, hints and fallbacks in telemetry.skillRouting",
91
+ });
92
+ return violations;
93
+ }
94
+
95
+ if (!MODES.includes(routing.mode)) {
96
+ violations.push({
97
+ requirement: "routing recorded",
98
+ detail: `telemetry.skillRouting.mode is ${JSON.stringify(routing.mode)}, not one of ${MODES.join(", ")}`,
99
+ fix: "store the resolver's own mode field, unedited",
100
+ });
101
+ }
102
+ if (!Array.isArray(routing.toolkits)) {
103
+ violations.push({
104
+ requirement: "routing recorded",
105
+ detail:
106
+ "telemetry.skillRouting.toolkits is not an array, so 'no toolkit applied' cannot be told from 'nothing was resolved'",
107
+ fix: "store the resolver's toolkits array, empty when it kept none",
108
+ });
109
+ return violations;
110
+ }
111
+
112
+ for (const toolkit of keptToolkits(routing)) {
113
+ if (indexEvidence(telemetry, toolkit)) continue;
114
+ violations.push({
115
+ requirement: "index asked",
116
+ toolkit,
117
+ detail: `${toolkit} was kept for this task but nothing records a call to ${toolkit}:index: the routing was resolved and then not consulted`,
118
+ fix: `load ${toolkit}:index through the Skill tool before writing code`,
119
+ });
120
+ }
121
+ return violations;
122
+ }
123
+
124
+ /** The names of the toolkits the resolver kept for this task. */
125
+ export function keptToolkits(routing) {
126
+ return Array.isArray(routing?.toolkits)
127
+ ? routing.toolkits.map((t) => (typeof t?.name === "string" ? t.name : null)).filter(Boolean)
128
+ : [];
129
+ }
130
+
131
+ /**
132
+ * How a toolkit's `index` call is evidenced, or null when nothing records one.
133
+ *
134
+ * `observed` is the hook's record of the Skill call, which no phase has to
135
+ * remember to write. `self-reported` is the phase's own ledger entry, and it is
136
+ * what a host that installs no hooks has: the requirement is the same on every
137
+ * host, only the strength of the evidence differs, and the caller is told which
138
+ * it got rather than being left to assume.
139
+ *
140
+ * @returns {"observed"|"self-reported"|null}
141
+ */
142
+ export function indexEvidence(telemetry, toolkit) {
143
+ const index = `${toolkit}:index`;
144
+ const loads = Array.isArray(telemetry?.skillLoads) ? telemetry.skillLoads : [];
145
+ if (loads.some((l) => l?.skill === index && l?.outcome === "ok")) return "observed";
146
+ const calls = Array.isArray(telemetry?.skillCalls) ? telemetry.skillCalls : [];
147
+ const named = calls.some(
148
+ (c) =>
149
+ c?.skill === index ||
150
+ (typeof c?.skill === "string" && c.skill.startsWith(`${index}@`)) ||
151
+ (typeof c?.routedBy === "string" && c.routedBy.startsWith(index)),
152
+ );
153
+ return named ? "self-reported" : null;
154
+ }
155
+
156
+ export function checkRouting(state, { requireDone = false } = {}) {
157
+ const violations = [];
158
+ const phase2 = state?.phases?.["2"];
159
+ const status = typeof phase2?.status === "string" ? phase2.status : null;
160
+
161
+ if (state?.mode === "analysis") {
162
+ return { ok: true, checked: false, skipped: "analysis mode has no dev phase", violations };
163
+ }
164
+ if (status !== "done") {
165
+ // `requireDone` judges a run's phase record, so it needs one to judge. A
166
+ // document with no `phases` at all is not a run mid-review; it is a state
167
+ // that carries something else, and refusing it would be a verdict on a
168
+ // phase table that was never written.
169
+ const hasPhases =
170
+ state?.phases && typeof state.phases === "object" && !Array.isArray(state.phases);
171
+ if (requireDone && hasPhases && status !== "skipped") {
172
+ violations.push({
173
+ requirement: "phase 2 closed",
174
+ detail: `review is starting while phase 2 is ${status ?? "absent"}: a dev phase that never closed recorded no routing either`,
175
+ fix: "close phase 2 with its routing recorded, or skip it as a review-only run",
176
+ });
177
+ return { ok: false, checked: true, violations };
178
+ }
179
+ return {
180
+ ok: true,
181
+ checked: false,
182
+ skipped: `phase 2 is ${status ?? "absent"}, not done`,
183
+ violations,
184
+ };
185
+ }
186
+
187
+ violations.push(...routingViolations(state));
188
+ const telemetry = state?.telemetry;
189
+ const kept = keptToolkits(telemetry?.skillRouting);
190
+ const evidence = kept.map((t) => indexEvidence(telemetry, t));
191
+ const calls = Array.isArray(telemetry?.skillCalls) ? telemetry.skillCalls : [];
192
+ const loads = Array.isArray(telemetry?.skillLoads) ? telemetry.skillLoads : [];
193
+
194
+ return {
195
+ ok: violations.length === 0,
196
+ checked: true,
197
+ keptToolkits: kept,
198
+ evidence: evidence.includes("self-reported")
199
+ ? "self-reported"
200
+ : evidence.length
201
+ ? "observed"
202
+ : "none-kept",
203
+ recordedCalls: calls.length,
204
+ observedLoads: loads.length,
205
+ violations,
206
+ };
207
+ }
208
+
209
+ function main() {
210
+ let opts;
211
+ try {
212
+ opts = options(process.argv.slice(2));
213
+ } catch (err) {
214
+ console.error(`ERR: ${err instanceof ArgsError ? err.message : err.message}`);
215
+ process.exit(1);
216
+ }
217
+ if (!opts.state) {
218
+ console.error("ERR: --state <agent-state.json> is required");
219
+ process.exit(1);
220
+ }
221
+ if (!existsSync(opts.state)) {
222
+ console.error(`ERR: state not found: ${opts.state}`);
223
+ process.exit(1);
224
+ }
225
+
226
+ let state;
227
+ try {
228
+ state = JSON.parse(readFileSync(opts.state, "utf8"));
229
+ } catch (e) {
230
+ console.error(`ERR: state is not valid JSON: ${e.message}`);
231
+ process.exit(1);
232
+ }
233
+
234
+ const result = checkRouting(state, { requireDone: opts.requireDone });
235
+ const payload = JSON.stringify(result, null, 2);
236
+ if (opts.out) {
237
+ try {
238
+ writeFileSync(opts.out, `${payload}\n`);
239
+ } catch (e) {
240
+ console.error(`ERR: could not write ${opts.out}: ${e.message}`);
241
+ process.exit(1);
242
+ }
243
+ }
244
+
245
+ if (opts.json) console.log(payload);
246
+ else if (!result.checked) console.log(`skill routing: not checked - ${result.skipped}`);
247
+ else if (result.ok)
248
+ console.log(
249
+ `skill routing: recorded - ${result.keptToolkits.length} toolkit(s) kept, evidence ${result.evidence} (${result.observedLoads} observed load(s), ${result.recordedCalls} declared call(s))`,
250
+ );
251
+ else {
252
+ console.error("skill routing: NOT recorded by a finished phase 2");
253
+ for (const v of result.violations) console.error(` - [${v.requirement}] ${v.detail}`);
254
+ for (const v of result.violations) console.error(` fix: ${v.fix}`);
255
+ }
256
+
257
+ process.exit(result.checked && !result.ok ? 2 : 0);
258
+ }
259
+
260
+ if (import.meta.url === `file://${process.argv[1]}`) main();
@@ -78,6 +78,8 @@ export const MAX_LOG_BYTES = 1024 * 1024;
78
78
  export const ROW_VERSION = "1.0.0";
79
79
  export const DEADLINE_MS = 1500;
80
80
  export const SKILL_NAME_MAX = 96;
81
+ /** Observed loads kept per run. A run that opens more than this is pathological. */
82
+ export const MAX_RUN_LOADS = 500;
81
83
  /** One to three `:`-joined segments of [A-Za-z0-9._-], each opening alphanumeric. */
82
84
  export const SKILL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*(?::[A-Za-z0-9][A-Za-z0-9._-]*){0,2}$/;
83
85
  const MAX_INPUT = 512 * 1024;
@@ -357,6 +359,55 @@ export async function record(payload, env = process.env) {
357
359
  return appendRow(row, env) ? row : null;
358
360
  }
359
361
 
362
+ /**
363
+ * Append the observed call to `telemetry.skillLoads[]` of the run bound to this
364
+ * session, so which skills a phase opened is read off the host rather than
365
+ * reported by the model.
366
+ *
367
+ * It is deliberately not `skillCalls[]`: that field carries the files a skill
368
+ * was applied to, which this hook cannot see, and a hook writing an empty
369
+ * `targetFiles` would turn "unattributed" into "applied to nothing". The two
370
+ * fields answer different questions and Phase 3 reads both.
371
+ *
372
+ * Run telemetry is not the passive local log, so `skillUsage.enabled` and
373
+ * `usageLog.optOut` do not gate it: a run records what it did, in its own run
374
+ * directory, and nothing leaves the machine either way. Every failure returns
375
+ * null; a skill load is never worth holding or failing a tool call over.
376
+ */
377
+ export async function noteRunLoad(payload, env = process.env) {
378
+ const row = rowFor(payload);
379
+ if (!row) return null;
380
+ try {
381
+ const { findActiveRun } = await import("./_active-run.mjs");
382
+ const run = findActiveRun({
383
+ sessionId: payload.session_id ?? null,
384
+ cwd: payload.cwd ?? null,
385
+ env,
386
+ });
387
+ if (!run?.statePath) return null;
388
+ const entry = {
389
+ skill: row.skill,
390
+ outcome: row.outcome,
391
+ timestamp: row.ts,
392
+ host: row.host,
393
+ recordedBy: "note-skill-use",
394
+ };
395
+ const phase = Number(run.state?.currentPhase);
396
+ if (Number.isInteger(phase)) entry.phase = phase;
397
+ const { updateState } = await import("./gate-ledger.mjs");
398
+ await updateState(run.statePath, (state) => {
399
+ const telemetry =
400
+ state.telemetry && typeof state.telemetry === "object" ? state.telemetry : {};
401
+ const loads = Array.isArray(telemetry.skillLoads) ? telemetry.skillLoads : [];
402
+ if (loads.length >= MAX_RUN_LOADS) return state;
403
+ return { ...state, telemetry: { ...telemetry, skillLoads: [...loads, entry] } };
404
+ });
405
+ return entry;
406
+ } catch {
407
+ return null;
408
+ }
409
+ }
410
+
360
411
  /** stdin as text, or null once DEADLINE_MS passes or it grows past MAX_INPUT. */
361
412
  function readStdin() {
362
413
  return new Promise((resolve) => {
@@ -391,6 +442,7 @@ async function main() {
391
442
  return;
392
443
  }
393
444
  if (!claimHookEvent("note-skill-use", payload)) return;
445
+ await noteRunLoad(payload);
394
446
  await record(payload);
395
447
  }
396
448
 
@@ -28,6 +28,17 @@
28
28
  * worktree, a real-path prefix match; unattended, that policy and its
29
29
  * protected paths decide instead, so this rule stays silent there.
30
30
  *
31
+ * Dev-phase skill routing (matcher `Edit|Write|NotebookEdit|MultiEdit`): a code
32
+ * write inside the bound run's own tree, while that run is in its dev phase and
33
+ * a kept toolkit's `index` skill has not been loaded, is denied with the calls
34
+ * to make - the routed skills decide how the change is written, so they come
35
+ * before the edit. A run that reaches a code write with no routing at all has
36
+ * one resolved for it here and stored, the same way an allowed Figma call is
37
+ * recorded rather than left to the model. Bounded at MAX_ROUTING_STOPS denies
38
+ * per run, after which the same text arrives as a note: the phase's exit
39
+ * refusal is what makes the requirement binding, and a rule that could not be
40
+ * passed would only strand the run.
41
+ *
31
42
  * Subagent spawn (matcher `Agent|Task`): when prefs.global.costBudget.enabled
32
43
  * is true and the bound live run's tracker prices above the budget
33
44
  * (_cost-budget.mjs), a new subagent asks the user first, and is refused with
@@ -52,7 +63,9 @@ import { invokedDirectly } from "../lib/invoked-directly.mjs";
52
63
  import { globalPref } from "../lib/prefs-value.mjs";
53
64
  import { readRegularJson } from "../lib/regular-file.mjs";
54
65
  import { isUnattended } from "../lib/unattended.mjs";
66
+ import { inDevPhase, resolveRouting } from "../lib/dev-routing.mjs";
55
67
  import { findActiveRun, logHookFailure, modeOf, phaseContract } from "./_active-run.mjs";
68
+ import { indexEvidence, keptToolkits } from "./check-skill-routing.mjs";
56
69
  import { budgetConfig, budgetLevel, rateFor, trackerSpend } from "./_cost-budget.mjs";
57
70
  import { logsRoot } from "./_run-paths.mjs";
58
71
  import { exitOnHelp } from "../lib/cli-help.mjs";
@@ -73,6 +86,14 @@ const HTTP_CLIENT = /(?:^|[\s;&|(])(?:curl|wget|http|https|xh)\s/;
73
86
 
74
87
  const SPAWN_TOOLS = new Set(["Agent", "Task"]);
75
88
 
89
+ /**
90
+ * Times one run is stopped for an unloaded index before the rule drops to a
91
+ * note. Bounded on purpose: the dev phase cannot close without the routing
92
+ * either way, so a rule that could not be passed would only turn a missing
93
+ * skill into a stuck run.
94
+ */
95
+ const MAX_ROUTING_STOPS = 2;
96
+
76
97
  const deny = (reason) => ({
77
98
  hookSpecificOutput: {
78
99
  hookEventName: "PreToolUse",
@@ -213,6 +234,76 @@ export function allowedRoots(run, env = process.env) {
213
234
  return roots.filter((r) => typeof r === "string" && r).map((r) => realish(resolve(r)));
214
235
  }
215
236
 
237
+ /** The file this call writes, resolved against the call's own directory, or null. */
238
+ function targetPath(payload) {
239
+ const ti = payload.tool_input || {};
240
+ const raw = ti.file_path || ti.notebook_path;
241
+ if (typeof raw !== "string" || !raw) return null;
242
+ const base = typeof payload.cwd === "string" && payload.cwd ? payload.cwd : process.cwd();
243
+ return realish(isAbsolute(raw) ? raw : resolve(base, raw));
244
+ }
245
+
246
+ async function updateRouting(statePath, mutate) {
247
+ const { updateState } = await import("./gate-ledger.mjs");
248
+ await updateState(statePath, (state) => {
249
+ const telemetry = state.telemetry && typeof state.telemetry === "object" ? state.telemetry : {};
250
+ const routing =
251
+ telemetry.skillRouting && typeof telemetry.skillRouting === "object"
252
+ ? telemetry.skillRouting
253
+ : {};
254
+ return { ...state, telemetry: { ...telemetry, skillRouting: mutate(routing) } };
255
+ });
256
+ }
257
+
258
+ /**
259
+ * A code write in the dev phase before the skills that govern it were opened.
260
+ *
261
+ * The routing says which toolkit indexes decide how this change is written, so
262
+ * the order matters: a skill read after the file is written cannot shape it.
263
+ * This is the moment the requirement bites, which is why the rule lives on the
264
+ * write rather than only on the phase's exit, and why a run that arrives here
265
+ * with no routing gets one resolved for it instead of a complaint.
266
+ *
267
+ * Returns a deny for the first MAX_ROUTING_STOPS writes, then a note.
268
+ */
269
+ async function routingDecision(payload, run) {
270
+ const s = run.state;
271
+ if (!LIVE.has(s.status) || !inDevPhase(s)) return null;
272
+ const target = targetPath(payload);
273
+ if (!target) return null;
274
+ const root = [s.worktreePath, s.projectRoot]
275
+ .filter((d) => typeof d === "string" && d)
276
+ .map((d) => realish(resolve(d)))
277
+ .find((d) => under(target, d));
278
+ if (!root) return null;
279
+ if (under(target, realish(dirname(run.statePath)))) return null;
280
+
281
+ let routing = s.telemetry?.skillRouting;
282
+ if (!routing || typeof routing !== "object") {
283
+ routing = await resolveRouting(s, { recordedBy: HOOK });
284
+ if (!routing) return null;
285
+ await updateRouting(run.statePath, () => routing);
286
+ }
287
+ const missing = keptToolkits(routing).filter((t) => !indexEvidence(s.telemetry, t));
288
+ if (!missing.length) return null;
289
+
290
+ const names = missing.map((t) => `${t}:index`).join(", ");
291
+ const msg =
292
+ `run ${s.taskId || run.statePath} is in its dev phase and ${names} ` +
293
+ `${missing.length > 1 ? "have" : "has"} not been loaded. The routed skills decide how this ` +
294
+ "change is written, so they come before the edit, not after it. Load them, apply what they " +
295
+ "say, and continue; Phase 2 cannot close until a call to each kept toolkit's index is recorded.";
296
+ const stops = Number(routing.stops ?? 0);
297
+ if (stops >= MAX_ROUTING_STOPS) {
298
+ return {
299
+ systemMessage: `${HOOK}: ${msg}`,
300
+ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: `${HOOK}: ${msg}` },
301
+ };
302
+ }
303
+ await updateRouting(run.statePath, (r) => ({ ...r, stops: stops + 1 }));
304
+ return deny(msg);
305
+ }
306
+
216
307
  function boundaryDecision(payload, run, env) {
217
308
  const s = run.state;
218
309
  if (isUnattended(env)) return null;
@@ -274,7 +365,8 @@ export async function decide(payload, env = process.env) {
274
365
  : null;
275
366
  }
276
367
  if (figmaHttp) return figmaDecision(payload, run, { record: false });
277
- return figma ? figmaDecision(payload, run) : boundaryDecision(payload, run, env);
368
+ if (figma) return figmaDecision(payload, run);
369
+ return (await routingDecision(payload, run)) || boundaryDecision(payload, run, env);
278
370
  }
279
371
 
280
372
  async function main() {
@@ -40,9 +40,17 @@
40
40
  // 2 fail-closed: no skills root resolved at all, a declared registry could not
41
41
  // be parsed, or a declared path escaped its skill directory. All named in the
42
42
  // manifest (`resolutionFailure`, `unparseableRegistries`).
43
+ // 4 the dev phase recorded no skill routing, or a toolkit it kept was never
44
+ // consulted (`lib/dev-routing.mjs` chose it, `check-skill-routing.mjs` reads
45
+ // it back). Criteria resolution is the consumer of that choice: resolving a
46
+ // rule set over a diff written without opening the skills that govern it is
47
+ // the clean-review-over-unchosen-rules outcome rule 3 above describes, one
48
+ // step earlier. Only with `--state`, and only once Phase 2 has closed.
43
49
 
44
50
  import { existsSync, readFileSync, writeFileSync, readdirSync, statSync } from "node:fs";
45
51
  import { dirname, join, resolve, relative, basename, extname, sep } from "node:path";
52
+
53
+ import { checkRouting } from "./check-skill-routing.mjs";
46
54
  import { fileURLToPath } from "node:url";
47
55
  import { matchesAnyGlob } from "./glob-match.mjs";
48
56
  import { pluginSkillRootCandidates } from "../lib/plugin-skill-roots.mjs";
@@ -698,6 +706,7 @@ if (opts.diff) {
698
706
  // consulted nothing, so treating a missing array as "nothing applied" would let
699
707
  // every completeness number report green over an empty set.
700
708
  let ledger = { status: "absent", entries: [] };
709
+ let routingState = null;
701
710
  if (opts.state) {
702
711
  if (!existsSync(opts.state)) {
703
712
  console.error(`ERR: state not found: ${opts.state}`);
@@ -705,6 +714,7 @@ if (opts.state) {
705
714
  }
706
715
  try {
707
716
  const state = JSON.parse(readFileSync(opts.state, "utf8"));
717
+ routingState = state;
708
718
  const calls = state?.telemetry?.skillCalls;
709
719
  if (Array.isArray(calls)) {
710
720
  ledger = { status: calls.length ? "declared" : "empty", entries: calls };
@@ -715,6 +725,21 @@ if (opts.state) {
715
725
  }
716
726
  }
717
727
 
728
+ // Fail closed on a dev phase that chose no skills. The rules this run resolves
729
+ // are the ones the diff is held to; a diff written without opening the skills
730
+ // its own stack routes to has no chosen rule set behind it, and a manifest built
731
+ // over it reads as criteria when it is a default. Written states only: with no
732
+ // --state there is nothing to read, and the check abstains until Phase 2 closes.
733
+ if (routingState) {
734
+ const routing = checkRouting(routingState, { requireDone: true });
735
+ if (routing.checked && !routing.ok) {
736
+ console.error("ERR: the dev phase recorded no skill routing:");
737
+ for (const v of routing.violations) console.error(` [${v.requirement}] ${v.detail}`);
738
+ console.error(` fix: ${routing.violations[0].fix}`);
739
+ process.exit(4);
740
+ }
741
+ }
742
+
718
743
  // --- language census of the diff ------------------------------------------
719
744
  const languages = {};
720
745
  for (const file of changedFiles) {
@@ -66,6 +66,15 @@ import { readRegularFile } from "../lib/regular-file.mjs";
66
66
  import { createExclusive, unlinkSafe, writeFileSafe } from "../lib/safe-write.mjs";
67
67
  import { invokedDirectly } from "../lib/invoked-directly.mjs";
68
68
  import { completionGaps, modeOf } from "../lib/run-completion.mjs";
69
+ import {
70
+ closesDevPhase,
71
+ hasDevPhase,
72
+ loadLine,
73
+ opensDevPhase,
74
+ repoOf,
75
+ resolveRouting,
76
+ } from "../lib/dev-routing.mjs";
77
+ import { routingViolations } from "./check-skill-routing.mjs";
69
78
  import { exitOnHelp } from "../lib/cli-help.mjs";
70
79
 
71
80
  exitOnHelp(import.meta.url);
@@ -490,6 +499,72 @@ export function transitionRefusal(next, payload, current, { replace = false } =
490
499
  return null;
491
500
  }
492
501
 
502
+ /**
503
+ * The refusal message for a write that closes Phase 2 without the skill
504
+ * routing the phase is required to have recorded, or null.
505
+ *
506
+ * The code a dev phase writes is written under a set of skills, and which set
507
+ * it was is a fact about the change, not a preference: Phase 3 resolves the
508
+ * criteria the reviewers hold the diff to, and a run that recorded no routing
509
+ * reads as reviewed against rules nothing chose. The requirement falls due the
510
+ * moment the phase closes, so that is where it is read back. There is no
511
+ * unattended exemption: resolving the routing needs nobody's approval.
512
+ *
513
+ * @param {object} next
514
+ * @param {object|undefined} current
515
+ * @returns {string|null}
516
+ */
517
+ export function routingRefusal(next, current) {
518
+ const was = current && typeof current === "object" ? current : {};
519
+ if (!hasDevPhase(next)) return null;
520
+ if (!closesDevPhase(next, was)) return null;
521
+ const violations = routingViolations(next);
522
+ if (!violations.length) return null;
523
+ const lines = violations.map((v) => ` - [${v.requirement}] ${v.detail}`).join("\n");
524
+ return (
525
+ "write-state: refusing to close Phase 2: the skills the code was written under are not " +
526
+ `recorded. Nothing was written.\n${lines}\n fix: ${violations[0].fix}`
527
+ );
528
+ }
529
+
530
+ /**
531
+ * Resolve the stack skill routing on the write that OPENS Phase 2, and store
532
+ * it, so the step that chooses which skills govern the task is carried by a
533
+ * command every host has to run rather than by a document asking for it.
534
+ *
535
+ * Resolution is the resolver's own, in-process, with the run's own state so it
536
+ * sees the right mode. The kept toolkits are printed on stderr: that output is
537
+ * what tells the dev phase which `index` skills to load. A resolver that
538
+ * cannot answer leaves the field absent and says why - writing an empty
539
+ * routing here would turn "nothing was resolved" into "no toolkit applied",
540
+ * which is the one distinction the field exists to keep.
541
+ *
542
+ * @param {object} next
543
+ * @param {object|undefined} current
544
+ * @returns {Promise<void>}
545
+ */
546
+ export async function resolveDevRouting(next, current) {
547
+ const was = current && typeof current === "object" ? current : {};
548
+ if (!hasDevPhase(next)) return;
549
+ if (!opensDevPhase(next, was)) return;
550
+ if (next.telemetry && typeof next.telemetry.skillRouting === "object") return;
551
+ // No readable tree of its own: nothing to detect a stack from. Silent here,
552
+ // because the phase's exit refusal is what states the requirement, and a
553
+ // warning on every write of such a run would say it many times over.
554
+ if (!repoOf(next)) return;
555
+ try {
556
+ const routing = await resolveRouting(next, { recordedBy: "write-state" });
557
+ if (!routing) return;
558
+ next.telemetry = next.telemetry && typeof next.telemetry === "object" ? next.telemetry : {};
559
+ next.telemetry.skillRouting = routing;
560
+ console.error(`write-state: skill routing resolved - ${loadLine(routing)}`);
561
+ for (const h of routing.hints ?? [])
562
+ if (h?.hint) console.error(`write-state: hint - ${h.hint}`);
563
+ } catch (err) {
564
+ console.error(`write-state: skill routing not resolved: ${err.message}`);
565
+ }
566
+ }
567
+
493
568
  /**
494
569
  * Bind the run to the host session that drives it.
495
570
  *
@@ -663,6 +738,18 @@ async function main() {
663
738
  process.exit(6);
664
739
  }
665
740
 
741
+ // Resolution runs after the other refusals so a write that was never going
742
+ // to land does not pay for it, and before its own refusal because the two
743
+ // never meet: one acts on the write that opens Phase 2, the other on the
744
+ // write that closes it.
745
+ await resolveDevRouting(next, current);
746
+ const routingBlock = routingRefusal(next, current);
747
+ if (routingBlock) {
748
+ console.error(routingBlock);
749
+ releaseLock(path);
750
+ process.exit(6);
751
+ }
752
+
666
753
  next.rev = priorRev + 1;
667
754
  stampWaitingSince(next, current);
668
755
  stampHostSession(next, payload, fileExistedBefore);