@sabaiway/agent-workflow-kit 16.1.0 → 18.0.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.
@@ -32,7 +32,7 @@
32
32
 
33
33
  import { readFileSync, readdirSync, lstatSync, existsSync, statSync } from 'node:fs';
34
34
  import { homedir, hostname } from 'node:os';
35
- import { dirname, join, resolve } from 'node:path';
35
+ import { dirname, join, resolve, sep } from 'node:path';
36
36
  import { fileURLToPath } from 'node:url';
37
37
  import {
38
38
  preflightVelocityProfile,
@@ -47,7 +47,8 @@ import {
47
47
  import { loadAutonomy, isSparseSeedConfig, AUTONOMY_REL } from './autonomy-config.mjs';
48
48
  import { deriveDoctorPlan, TRUSTED_DIRS } from './autonomy-doctor.mjs';
49
49
  import { LANE_KIT, laneOf, applySlot, consoleArgv } from './write-lanes.mjs';
50
- import { STATE_BLOCK_HOOK_COMMAND, STATE_BLOCK_HOOK_RUNTIME, isStopHookWired } from './state-block-hook.mjs';
50
+ import { STATE_BLOCK_HOOK_COMMAND, STATE_BLOCK_HOOK_FILE_REL, STATE_BLOCK_HOOK_RUNTIME, isStopHookWired, writeStateBlockHook } from './state-block-hook.mjs';
51
+ import { HOOK_FILE_REL, HOOKS_DIR, writeGateHook } from './gate-hook.mjs';
51
52
  import { detectBackends } from './detect-backends.mjs';
52
53
  import { isDirectRun } from './direct-run.mjs';
53
54
  import { ACTIVITIES, resolveActivityRecipe, composeReadiness, safeLine } from './recipes.mjs';
@@ -55,8 +56,7 @@ import { surveyFamily, surveyGateHook } from './family-registry.mjs';
55
56
  import { probeSandboxMasks, needsMasksApply, patternToRel } from './sandbox-masks.mjs';
56
57
  import { shellQuoteArg } from './review-state.mjs';
57
58
  import { isFinalCapableDeclaration } from './run-gates.mjs';
58
- import { loadDeclaration, canonicalCheckerGates, coverageProducerPrecedes, isKitOwnedCheckerGate, LCOV_PRODUCER_KEY } from './gates-declaration.mjs';
59
- import { readRegularFileNoFollow } from './fs-read-nofollow.mjs';
59
+ import { loadDeclaration, canonicalCheckerGates, coverageProducerPrecedes, isKitOwnedCheckerGate } from './gates-declaration.mjs';
60
60
  // The typed channel's READ-ONLY leaf only — never tools/mcp.mjs, which reaches the write core.
61
61
  import {
62
62
  SERVER_NAME as MCP_SERVER_NAME,
@@ -82,13 +82,12 @@ import { homeRelative } from './bridge-state-dirs.mjs';
82
82
  import { sandboxEnabled, HOST_HONORS_QUALIFIER } from './bridge-wiring.mjs';
83
83
  import { assertContainedRealPath } from './fs-safe.mjs';
84
84
  import { nearestExistingDir, worktreesGrantDir, worktreesGrantHoldsHome } from './worktrees.mjs';
85
- import { preflightCheapAgents, writeCheapAgents, EXECUTOR_VEHICLE } from './cheap-agents.mjs';
85
+ import { readBundledAgents, writeCheapAgents, EXECUTOR_VEHICLE } from './cheap-agents.mjs';
86
86
  import { ATTRIBUTION_KEY, LEGACY_ATTRIBUTION_KEY, attributionHidesText, effectiveAttribution, readAttributionChoice, wrongTypedKey } from './attribution.mjs';
87
87
  import { planGlobalRemoval } from './hide-footprint.mjs';
88
88
  import { NODE_EVIDENCE, NODE_EVIDENCE_SCRIPTS, probeNodeEvidence } from './node-evidence.mjs';
89
89
  // The vehicle READINESS comes from the read-only half — the same survey `recipes` and `status` read.
90
- import { surveyExecutorVehicle, readExecutorPosture, executorBodyDiffers, executorTemplate, reviewLensTemplate, readStamp, readFsDeps, WORKFLOW_STAMP, EXPECTED_WORKFLOW_VERSION, REVIEW_LENS_VEHICLE } from './cheap-agents-read.mjs';
91
- import { readVehicles, resolveExecutor, resolveReviewLens } from './vehicle-settings.mjs';
90
+ import { surveyExecutorVehicle, readExecutorPosture, agentsAccepted, readStamp, readFsDeps, AGENTS_DIR, WORKFLOW_STAMP, EXPECTED_WORKFLOW_VERSION } from './cheap-agents-read.mjs';
92
91
  // The ack store's path, keys, lane registry, fingerprint and guarded reader live in their own leaf
93
92
  // (contract: kit/ack-store) — `status` reads the same store, and a second copy is what drifts.
94
93
  import {
@@ -194,27 +193,24 @@ export const SEVERITIES = Object.freeze({
194
193
  'source-size.schema-1': SEVERITY_ATTENTION,
195
194
  'source-size.layout': SEVERITY_OPTIONAL,
196
195
  'gate-hook': SEVERITY_OPTIONAL,
197
- // A placed hook that predates the marker key goes DARK on a marker-carrying declaration (unknown
198
- // key → auto-approval off), so a CONFIGURED capability silently stops working: attention, not an
199
- // offer to enable something.
200
- 'gate-hook.marker-stale': SEVERITY_ATTENTION,
196
+ // A wired hook's kit file absent or differing: its lane is kit, as `agents.not-current`'s.
197
+ 'gate-hook.not-current': SEVERITY_OPTIONAL,
201
198
  'commit-guard': SEVERITY_OPTIONAL,
202
199
  'hook-checks': SEVERITY_OPTIONAL,
203
200
  enforcement: SEVERITY_OPTIONAL,
204
201
  'read-lane': SEVERITY_OPTIONAL,
205
- 'read-lane.stale': SEVERITY_ATTENTION,
206
- 'read-lane.missing': SEVERITY_ATTENTION,
207
202
  'state-block': SEVERITY_OPTIONAL,
203
+ 'state-block.not-current': SEVERITY_OPTIONAL,
208
204
  'mcp-channel': SEVERITY_OPTIONAL,
209
205
  'mcp-channel.differing': SEVERITY_ATTENTION,
210
206
  agents: SEVERITY_OPTIONAL,
211
- // The `agents` row above is an OFFER to place vehicles. This one reports a config that ALREADY
207
+ // A placed component with a kit agent file not current: its lane is kit, so the agent writes it
208
+ // with no pick and the verdict counts it in neither class.
209
+ 'agents.not-current': SEVERITY_OPTIONAL,
210
+ // The `agents` rows above place and write vehicles. This one reports a config that ALREADY
212
211
  // names the subagent carrier over a vehicle that cannot carry it — a configured declaration that
213
212
  // is broken, which is what attention means.
214
213
  'executor-vehicle': SEVERITY_ATTENTION,
215
- // A hand edit of the placed executor is not a broken declaration — the vehicle still carries — so it is optional;
216
- // its lane is kit, so the agent writes it with no pick and the verdict counts it in neither class.
217
- 'executor-vehicle.differing': SEVERITY_OPTIONAL,
218
214
  // The AGENTS.md block is a configured choice the harness does not honour.
219
215
  attribution: SEVERITY_ATTENTION,
220
216
  'footprint-global': SEVERITY_OPTIONAL,
@@ -293,20 +289,18 @@ export const WHATS = Object.freeze({
293
289
  'source-size.adopted-elsewhere': "the source-size gate runs a DIFFERENT copy of this checker ({n} declared) — adopted here, just not through this kit's own tool",
294
290
  'source-size.id-squatter': 'a gate carries the source-size id but is not this checker — the practice reads as declared while nothing measures module size',
295
291
  'gate-hook': '{n} declared gate(s) prompt per run — the gate-approval hook is not wired',
296
- 'gate-hook.marker-stale': 'the declaration carries the lcovProducer key but the placed hook predates it — the hook goes dark and every gate prompts',
292
+ 'gate-hook.not-current': `${HOOK_FILE_REL} is absent or differs from the body the kit writes for it — written with that body, with no question`,
297
293
  'commit-guard': 'the gate matrix is final-run-capable but no commit-guard arms the pre-commit hook — a commit needs no green receipt yet',
298
294
  'hook-checks': 'the pre-commit hook lacks this kit\'s {checks} — the kit arms each line',
299
295
  enforcement: ENFORCEMENT_WHAT,
300
296
  'read-lane': 'the gate hook is wired but the read-only compound lane is off — pipes/chains of seeded reads still prompt one by one',
301
- 'read-lane.stale': 'the read-lane is ON but the placed gate hook is stale — an old hook never reads lanes.json, so the lane is silently dark; reseed it',
302
- 'read-lane.missing': 'the gate hook is wired but its placed file is missing — every Bash call errors and the read-lane is dark; re-place it',
303
297
  'state-block': 'nothing checks the closing state block — a turn that ends on «nothing needed from you», or on a promise it never started, passes unseen',
298
+ 'state-block.not-current': `${STATE_BLOCK_HOOK_FILE_REL} is absent or differs from the body the kit writes for it — written with that body, with no question`,
304
299
  'mcp-channel': "the kit's read-only MCP server is not registered here — path questions and literal searches stay shell strings",
305
300
  'mcp-channel.differing': 'an "{server}" MCP entry is already declared here and DIFFERS from the registration this kit copy would write',
306
301
  agents: '{n} bundled subagent vehicle(s) not placed (Claude Code) — {ro} read-only, {ex} the full-tool executor; the apply PREVIEWS first',
307
- 'agents.lens-rederive': 'the placed review-lens.md differs from its body derived from docs/ai/vehicles.json; {n} vehicle(s) to place ({ro} read-only, {ex} executor)',
302
+ 'agents.not-current': '{n} kit agent file(s) in .claude/agents/ not current — each is written with the body the kit writes for it, with no question',
308
303
  'executor-vehicle': '{n} slot(s) configured subagent but the executor vehicle is {state}{reason} — every such slot runs solo until it is usable',
309
- 'executor-vehicle.differing': 'the placed executor vehicle differs from the body derived from docs/ai/vehicles.json — the derived body is written with no question',
310
304
  attribution: 'AGENTS.md says attribution off but .claude/settings.json does not hide the harness trailer and PR text',
311
305
  'footprint-global': 'legacy kit ignore line(s) sit in {file} — they ignore kit paths in every repository here',
312
306
  'family-freshness': '{parts}',
@@ -384,9 +378,12 @@ export const BENEFITS = Object.freeze({
384
378
  'jev-connect': 'decisions — a typed choice with a confidence in under a second for your code and the agent\'s scripts, once for every project here',
385
379
  'jev-skill': 'the TypeSafe skill for Claude Code, Codex and Antigravity CLI, one pinned verified copy per agent root, from one command you run',
386
380
  });
387
- // The one arm whose gain differs from its base item's (BENEFITS stays keyed by item key).
381
+ // The arms whose gain differs from their base item's (BENEFITS stays keyed by item key).
382
+ const HOOK_CURRENCY_BENEFIT = 'currency — a hook you wired runs the body the kit writes for it today';
388
383
  export const VARIANT_BENEFITS = Object.freeze({
389
- 'executor-vehicle.differing': 'carrier fidelity — the placed executor runs the model and effort docs/ai/vehicles.json names',
384
+ 'agents.not-current': 'currency — each kit agent file carries the body the kit writes for it today, model and effort where docs/ai/vehicles.json names them',
385
+ 'gate-hook.not-current': HOOK_CURRENCY_BENEFIT,
386
+ 'state-block.not-current': HOOK_CURRENCY_BENEFIT,
390
387
  'source-size.layout': 'layout — piles past the layout limits become recorded, reasoned debt, so the commit hook can judge new ones once its layout line is armed',
391
388
  });
392
389
 
@@ -444,9 +441,9 @@ export const OPT_IN_CAPABILITIES = Object.freeze([
444
441
  // which is why the review-recipe benefit is worded for either slot rather than for review alone.
445
442
  { id: 'delegated-execution', mode: 'set-recipe', advisorKey: 'review-recipe' },
446
443
  { id: 'agents', mode: 'agents', advisorKey: 'agents' },
447
- // A DISTINCT capability from the offer above: the offer converges the moment nothing is left to
448
- // PLACE and the review lens matches its derived body, which a customized-but-unusable executor
449
- // also satisfies — so it can never observe the state that makes a configured subagent carrier run solo.
444
+ // A DISTINCT capability from the offer above: the `agents` key writes a regular executor whose bytes differ,
445
+ // but it never names a configured subagent slot that runs solo — over a component not placed it offers the
446
+ // placement, and over a refusal (a symlinked executor, an unreadable docs/ai/vehicles.json) only its skip.
450
447
  { id: 'executor-vehicle', mode: 'agents', advisorKey: 'executor-vehicle' },
451
448
  // Exempt, not un-audited. `acceptEdits` auto-applies Edit/Write and auto-runs mkdir/touch/mv/cp:
452
449
  // a TRUST-POSTURE change. Velocity presents its full posture at its own consent moment;
@@ -615,46 +612,33 @@ const probeReviewRecipe = ({ root, deps, add, skip }) => {
615
612
  }
616
613
  };
617
614
 
618
- const probeGates = ({ root, deps, add, skip, shared }) => {
615
+ // The kit arm of a WIRED hook (contract: init-project, part hook-writers): the writer's plain dry run,
616
+ // the call the danger check makes. A throw is the probe's stated skip; no planned place or replace
617
+ // renders nothing; a stale stamp beside one is the upgrade-first skip; otherwise the kit item.
618
+ const probeKitHook = ({ key, write, rel, root, deps, add }) => {
619
+ const plan = write({ cwd: root, dryRun: true }, deps);
620
+ if (!plan.placePlanned && !plan.replacePlanned) return;
621
+ if (!plan.stampOk) throw upgradeFirst(plan.stamp);
622
+ const variant = `${key}.not-current`;
623
+ add(key, WHATS[variant], formsApply(variant, root), variant, `writes: ${rel}`);
624
+ };
625
+
626
+ const probeGates = ({ root, deps, add, skip }) => {
619
627
  try {
620
628
  const sg = surveyGateHook(root, deps);
621
629
  if (sg.error) throw new Error(sg.error);
622
- if (sg.declarationPresent && sg.declaredGates === null) throw new Error(sg.declarationError ?? 'gates.json present but unreadable');
623
630
  // An ABSENT file and the seeded-EMPTY list are equally undeclared (Segment B); the
624
631
  // apply is the consent-gated gates-init PREVIEW (it proposes entries from the project's own
625
- // scripts and writes only on an explicit yes) — never the runner.
626
- if (!sg.declarationPresent || sg.declaredGates === 0) {
627
- // gates-init writes ONLY with --apply — the apply field stays a PURE executable command
628
- // (run-exactly-as-rendered feeds it to the shell); the two-step preview semantics live in
629
- // WHAT, never as prose appended to the command.
630
- add('gates-declaration', fillTemplate(WHATS['gates-declaration'], {}), `node ${q(toolPath('gates-init.mjs'))} --cwd ${q(root)}`);
631
- return;
632
- }
633
- if (!sg.wired) {
634
- add('gate-hook', fillTemplate(WHATS['gate-hook'], { n: sg.declaredGates }), `node ${q(toolPath('gate-hook.mjs'))} --apply --cwd ${q(root)}`);
635
- return;
636
- }
637
- // D8 — the marker REFRESH path. The placed hook validates the declaration through its OWN baked
638
- // copy and goes dark on any key it does not know (auto-approval off, every gate prompts again),
639
- // so a declaration carrying the marker key under a hook that predates it silently switches a
640
- // CONFIGURED capability off with no error anywhere. Deliberately marker-SCOPED: a stale hook is
641
- // otherwise harmless, and nagging every deployment about hook bytes is not this item's job.
642
- if (!declarationCarriesMarker(root, deps)) return;
643
- // Throws on a symlink / directory / unreadable target → the stated skip, never a wrong verdict.
644
- // ABSENT is not this arm either: a hook that is not placed belongs to the place offers above and
645
- // in the read-lane item, whose recovery actually places one.
646
- if (readPlacedHookCurrency(root, deps) !== HOOK_CURRENCY.STALE) return;
647
- // The writer's OWN stale recovery: `gate-hook --apply --reseed` replaces the placed hook with
648
- // the bundle in place — the one consented replacement; the slot renders it behind the check.
649
- // The RESULT is what the read-lane item defers to — not these conditions re-derived there. Both
650
- // probes read the placed hook independently, so a hook that changes between the two reads would
651
- // otherwise let each conclude the other owns it and leave a dark lane reported by nobody.
652
- shared.markerStaleRendered = add(
653
- 'gate-hook',
654
- fillTemplate(WHATS['gate-hook.marker-stale'], {}),
655
- `node ${q(toolPath('gate-hook.mjs'))} --apply --reseed --cwd ${q(root)}`,
656
- 'gate-hook.marker-stale',
657
- );
632
+ // scripts and writes only on an explicit yes) — never the runner. gates-init writes ONLY with
633
+ // --apply — the apply field stays a PURE executable command; the two-step preview semantics
634
+ // live in WHAT, never as prose appended to the command.
635
+ const undeclared = !sg.declarationPresent || sg.declaredGates === 0;
636
+ if (undeclared) add('gates-declaration', fillTemplate(WHATS['gates-declaration'], {}), `node ${q(toolPath('gates-init.mjs'))} --cwd ${q(root)}`);
637
+ // A wired hook is accepted: its kit file is written current whatever the declaration says (an
638
+ // unreadable one is the gates-inert probe's skip). An unwired one keeps the order of its offer.
639
+ if (sg.wired) return probeKitHook({ key: 'gate-hook', write: writeGateHook, rel: HOOK_FILE_REL, root, deps, add });
640
+ if (sg.declaredGates === null) throw new Error(sg.declarationError ?? 'gates.json present but unreadable');
641
+ if (!undeclared) add('gate-hook', fillTemplate(WHATS['gate-hook'], { n: sg.declaredGates }), `node ${q(toolPath('gate-hook.mjs'))} --apply --cwd ${q(root)}`);
658
642
  } catch (err) {
659
643
  skip('gate-hook', err);
660
644
  }
@@ -1069,55 +1053,18 @@ export const probeEnforcement = ({ root, deps, add, skip }) => {
1069
1053
  }
1070
1054
  };
1071
1055
 
1072
- // The read-lane offer (AD-055 Part II, Help-through-Recommendations): once the gate hook is PLACED
1073
- // and WIRED, offer to enable the opt-in read-only compound lane. Mutually exclusive with the
1074
- // gate-hook item BY CONSTRUCTION — that item keys on `!wired`, this one on `wired` — so an unplaced
1075
- // or un-wired hook is covered there, never double-offered here. The apply is the gate-hook
1076
- // --read-lane PREVIEW one-liner (its own currency check + posture note fire at the writer; it may
1077
- // prompt once — it IS a consent flow). Converges once lanes.json enables the lane.
1078
- const probeReadLane = ({ root, deps, add, skip, shared }) => {
1056
+ // The read-lane offer (AD-055 Part II, Help-through-Recommendations): once the gate hook is WIRED,
1057
+ // offer to enable the opt-in read-only compound lane, whatever the placed hook's bytes — a stale or
1058
+ // absent hook under it is a planned file of `gate-hook.not-current`, which the kit route applies
1059
+ // before the offers. Mutually exclusive with the gate-hook offer BY CONSTRUCTION — that offer keys
1060
+ // on `!wired`, this one on `wired`. The apply is the gate-hook --read-lane PREVIEW one-liner (its
1061
+ // own currency check + posture note fire at the writer; it IS a consent flow). Converges once
1062
+ // lanes.json enables the lane.
1063
+ const probeReadLane = ({ root, deps, add, skip }) => {
1079
1064
  try {
1080
1065
  const sg = surveyGateHook(root, deps);
1081
1066
  if (sg.error) throw new Error(sg.error);
1082
- if (!sg.wired) return; // not wired → the gate-hook item covers (no double-fire)
1083
- // Wired but the placed hook FILE is missing — the hook errors on every Bash call and the lane
1084
- // is silently dark; surface it as attention with a place-first recovery (council R2-M2).
1085
- const placeRecovery = () =>
1086
- add('read-lane', fillTemplate(WHATS['read-lane.missing'], {}), `node ${q(toolPath('gate-hook.mjs'))} --apply --cwd ${q(root)}`, 'read-lane.missing');
1087
- if (!sg.filePlaced || readsAbsent(deps, join(root, GATE_HOOK_REL))) {
1088
- placeRecovery();
1089
- return;
1090
- }
1091
- if (readReadLaneToggle(root, deps)) {
1092
- // The lane is ON: converged IFF the placed hook is byte-current — a stale (pre-1.48) hook never
1093
- // reads lanes.json, so the enabled lane is a silent no-op the user must reseed (council B7). The
1094
- // reseed route pins the ABSOLUTE root (council R2-M3), so running it from any cwd can only
1095
- // replace this repo's hook.
1096
- const currency = readPlacedHookCurrency(root, deps);
1097
- if (currency === HOOK_CURRENCY.CURRENT) return; // converged
1098
- if (currency === HOOK_CURRENCY.ABSENT) {
1099
- // The survey saw it placed and it is gone by the time we read it. The missing arm is the
1100
- // honest report of that; a reseed recovery, which refuses an absent hook, is not.
1101
- placeRecovery();
1102
- return;
1103
- }
1104
- // ONE render per condition — and the item that renders is the one whose CAUSE is true. A hook
1105
- // that postdates the read-lane but predates the marker key reads lanes.json perfectly well, so
1106
- // this arm's "an old hook never reads lanes.json" would be a false diagnosis over it, while the
1107
- // marker arm's is exact. Both carry the same reseed recovery, so deferring costs
1108
- // the reader nothing and buys a true sentence. The condition is that the marker arm REALLY
1109
- // rendered — never the conditions it would have used, re-derived here: each probe reads the
1110
- // placed hook itself, so a hook changing between the two reads could otherwise have both defer
1111
- // to the other and leave the dark lane reported by nobody.
1112
- if (shared.markerStaleRendered === true) return;
1113
- add(
1114
- 'read-lane',
1115
- fillTemplate(WHATS['read-lane.stale'], {}),
1116
- `node ${q(toolPath('gate-hook.mjs'))} --apply --reseed --cwd ${q(root)}`,
1117
- 'read-lane.stale',
1118
- );
1119
- return;
1120
- }
1067
+ if (!sg.wired || readReadLaneToggle(root, deps)) return;
1121
1068
  add('read-lane', fillTemplate(WHATS['read-lane'], {}), `node ${q(toolPath('gate-hook.mjs'))} --read-lane --cwd ${q(root)}`);
1122
1069
  } catch (err) {
1123
1070
  skip('read-lane', err);
@@ -1127,12 +1074,16 @@ const probeReadLane = ({ root, deps, add, skip, shared }) => {
1127
1074
  // The state-block-guard offer (AD-075 · OPT-IN-SHIPS-INVISIBLE). This item exists because its absence
1128
1075
  // fired: 3.14.0 shipped the detector with a mode doc, a catalog row and a README row — and no advisor
1129
1076
  // entry — so `upgrade` reported «nothing is broken» to a user who did not have it. Its writer is
1130
- // state-block-hook.mjs; convergence is that leaf's own isStopHookWired over both settings files.
1077
+ // state-block-hook.mjs; acceptance is that leaf's own isStopHookWired over both settings files, and
1078
+ // a wired hook takes the kit arm.
1131
1079
  const probeStateBlockHook = ({ root, deps, add, skip }) => {
1132
1080
  try {
1133
1081
  const project = readSettingsFile(join(root, SETTINGS_FILE), { ...deps, cwd: root });
1134
1082
  const local = readSettingsFile(join(root, SETTINGS_LOCAL_FILE), { ...deps, cwd: root });
1135
- if (isStopHookWired(project.data) || isStopHookWired(local.data)) return; // converged
1083
+ if (isStopHookWired(project.data) || isStopHookWired(local.data)) {
1084
+ probeKitHook({ key: 'state-block', write: writeStateBlockHook, rel: STATE_BLOCK_HOOK_FILE_REL, root, deps, add });
1085
+ return;
1086
+ }
1136
1087
  add(
1137
1088
  'state-block',
1138
1089
  fillTemplate(WHATS['state-block'], {}),
@@ -1147,37 +1098,35 @@ const probeStateBlockHook = ({ root, deps, add, skip }) => {
1147
1098
  // surfaced its absence: `agents` is the family's SECOND `.claude/` writer, the `help` Tune tail
1148
1099
  // advertises it, and the advisor had no entry for it — so a user who never runs `help` never learned
1149
1100
  // it existed while the advisor reported the deployment optimal. Found by the guard, not by an incident.
1150
- // A PLACE action and the bundled review lens's `re-derive` (its placed body differs from the one derived from docs/ai/vehicles.json) count as gaps: `already-current` is converged; a customized read-only vehicle or derived lens is
1151
- // the user's own edit the writer never clobbers and the advisor never nags about; the executor is not preserved but re-derived from docs/ai/vehicles.json (its `re-derive` answer is not a gap of this offer).
1152
- const probeCheapAgents = ({ root, deps, add, skip }) => {
1101
+ // The key renders by its state table (contract: kit/carriers, part agent-files) over the writer's
1102
+ // plain dry run, the call the danger check makes: a throw is one stated skip naming the refusal; no
1103
+ // planned file renders nothing; a stale stamp beside a planned file is the upgrade-first skip; over
1104
+ // a component not accepted the OFFER to place, over an accepted one `agents.not-current`, kit lane.
1105
+ const upgradeFirst = (stamp) => new Error(`run /agent-workflow-kit upgrade first (deployment stamp ${stamp ?? 'none'}, expected ${EXPECTED_WORKFLOW_VERSION})`);
1106
+
1107
+ const probeCheapAgents = ({ root, deps, add, skip, shared }) => {
1153
1108
  try {
1154
- const fs = readFsDeps(deps);
1155
- const answer = readVehicles(root, fs.readFile, fs.lstat);
1156
- const { posture, reason } = resolveExecutor(answer);
1157
- if (posture === null) {
1158
- skip('agents', new Error(`${reason} — fix that file first`));
1159
- return;
1160
- }
1161
- const derived = [executorTemplate(posture, deps), reviewLensTemplate(resolveReviewLens(answer).posture, deps)];
1162
- const preflight = preflightCheapAgents({ cwd: root, derived }, deps);
1163
- // The writer refuses below the expected lineage, so offering its command would hand the user a
1164
- // guaranteed failure — the honest surface is a stated skip naming the recovery.
1165
- if (!preflight.stampOk) {
1166
- skip('agents', new Error(`not a deployed agent-workflow project at the current lineage (found ${preflight.stamp ?? 'none'}) — run upgrade first`));
1109
+ const result = writeCheapAgents({ cwd: root, dryRun: true }, deps);
1110
+ const planned = result.plan.filter((item) => item.action === 'place' || item.action === 're-derive');
1111
+ if (planned.length === 0) return; // converged
1112
+ if (!result.stampOk) throw upgradeFirst(result.stamp);
1113
+ if (agentsAccepted(root, result.plan.map((item) => item.name), deps)) {
1114
+ // The detail names every file the apply writes, never truncated; the component is placed and the
1115
+ // known-footprint registry lists /.claude/agents/, so no hidden-mode follow-up rides it.
1116
+ shared.agentsNotCurrent = add('agents', fillTemplate(WHATS['agents.not-current'], { n: planned.length }),
1117
+ formsApply('agents.not-current', root), 'agents.not-current', `writes: ${planned.map((item) => item.rel).join(', ')}`);
1167
1118
  return;
1168
1119
  }
1169
- const toPlace = preflight.plan.filter((item) => item.action === 'place');
1170
- const lensRederive = preflight.plan.some((item) => item.name === REVIEW_LENS_VEHICLE && item.action === 're-derive');
1171
- if (toPlace.length === 0 && !lensRederive) return; // converged
1172
- // The writer's contract is «--dry-run first, ALWAYS» (references/modes/agents.md, and its stated
1173
- // invariant «preview by default»), so the rendered line is the PREVIEW — this item joins the
1174
- // dry-run-preview class the mode doc already documents for the gates-declaration seeder, where the
1175
- // same confirmation then runs the follow-up the preview prints. Rendering --apply here would have
1176
- // skipped the per-vehicle plan the user is supposed to see before consenting.
1177
- // The hidden-mode reconcile rides the detail, never the apply line: it is wrong to run on a
1178
- // VISIBLE deployment, and the apply slot must stay one pure executable command.
1120
+ // The offer counts the BUNDLED templates the plan would place. The writer's contract is «--dry-run
1121
+ // first, ALWAYS» (references/modes/agents.md), so the rendered line is the PREVIEW — the
1122
+ // dry-run-preview class the mode doc documents for the gates-declaration seeder, where the same
1123
+ // confirmation then runs the follow-up the preview prints. The hidden-mode reconcile rides the
1124
+ // detail, never the apply line: it is wrong to run on a VISIBLE deployment, and the apply slot
1125
+ // must stay one pure executable command.
1126
+ const bundled = new Set(readBundledAgents(deps).map((template) => template.name));
1127
+ const toPlace = planned.filter((item) => bundled.has(item.name));
1179
1128
  const executors = toPlace.filter((item) => item.name === EXECUTOR_VEHICLE).length;
1180
- add('agents', fillTemplate(WHATS[lensRederive ? 'agents.lens-rederive' : 'agents'], { n: toPlace.length, ex: executors, ro: toPlace.length - executors }),
1129
+ add('agents', fillTemplate(WHATS.agents, { n: toPlace.length, ex: executors, ro: toPlace.length - executors }),
1181
1130
  `node ${q(toolPath('cheap-agents.mjs'))} --cwd ${q(root)}`, 'agents',
1182
1131
  `hidden-mode deployments only: after the --apply the preview prints, run node ${q(toolPath('hide-footprint.mjs'))} --dir ${q(root)} --reconcile so the placed .claude/agents/ stays invisible to git status`,
1183
1132
  );
@@ -1187,14 +1136,15 @@ const probeCheapAgents = ({ root, deps, add, skip }) => {
1187
1136
  };
1188
1137
 
1189
1138
  // The subagent carrier's ONE instrument (contract: kit/carriers). Neither neighbour can report this
1190
- // state: `probeReviewRecipe` skips a slot configured `subagent` by construction, and the offer above
1191
- // judges only what is left to PLACE and the bundled lens's re-derive — a customized-but-broken executor
1192
- // gives it neither. So a project could declare the carrier and have every such slot run solo, unseen.
1139
+ // state: `probeReviewRecipe` skips a slot configured `subagent` by construction, and the `agents` key
1140
+ // above names files to place or write, never a configured slot that runs solo. It yields to
1141
+ // `agents.not-current`, whose apply writes the executor (the frozen order runs `agents` first).
1193
1142
  const VEHICLE_BROKEN_STATES = Object.freeze(['missing', 'unusable']);
1194
1143
 
1144
+ // The writer's plain dry run, the call the `agents` key makes: its refusal is the last precondition.
1195
1145
  const writerBlock = (root, deps) => {
1196
1146
  try {
1197
- preflightCheapAgents({ cwd: root }, deps);
1147
+ writeCheapAgents({ cwd: root, dryRun: true }, deps);
1198
1148
  return null;
1199
1149
  } catch (err) {
1200
1150
  return safeLine(err?.message ?? String(err));
@@ -1203,39 +1153,27 @@ const writerBlock = (root, deps) => {
1203
1153
 
1204
1154
  const HIDDEN_AGENTS_FOLLOW_UP = (root) => `hidden-mode deployments only: after the apply, run node ${q(toolPath('hide-footprint.mjs'))} --dir ${q(root)} --reconcile so the placed .claude/agents/ stays invisible to git status`;
1205
1155
 
1206
- const probeExecutorVehicle = ({ root, deps, add, skip }) => {
1207
- if (renderBrokenExecutor({ root, deps, add, skip })) return;
1208
- try {
1209
- if (!executorBodyDiffers(root, deps)) return;
1210
- // The executor-only dry run: the call the check makes, so the arm, the check and the apply judge one plan.
1211
- const plan = writeCheapAgents({ cwd: root, dryRun: true, executorOnly: true }, deps);
1212
- if (!plan.stampOk) throw new Error(`run /agent-workflow-kit upgrade first (deployment stamp ${plan.stamp ?? 'none'}, expected ${EXPECTED_WORKFLOW_VERSION})`);
1213
- add('executor-vehicle', WHATS['executor-vehicle.differing'], formsApply('executor-vehicle.differing', root), 'executor-vehicle.differing');
1214
- } catch (err) {
1215
- skip('executor-vehicle', err);
1216
- }
1217
- };
1218
-
1219
- const renderBrokenExecutor = ({ root, deps, add, skip }) => {
1156
+ const probeExecutorVehicle = ({ root, deps, add, skip, shared }) => {
1220
1157
  try {
1221
1158
  // The VALIDATED reader, as probeReviewRecipe uses it: a schema-invalid config is a stated skip,
1222
1159
  // never an item computed over a shape nothing accepted.
1223
1160
  const { config } = loadConfig(root, deps.readFile ?? readFileSync, deps.lstat ?? lstatSync);
1224
1161
  const configured = Object.entries(ACTIVITIES).flatMap(([activity, def]) =>
1225
1162
  Object.keys(def.slots).filter((slot) => config?.[activity]?.[slot] === 'subagent'));
1226
- if (configured.length === 0) return false;
1163
+ if (configured.length === 0) return;
1227
1164
  const survey = (deps.surveyVehicle ?? surveyExecutorVehicle)(root, deps);
1228
- if (!VEHICLE_BROKEN_STATES.includes(survey.state)) return false;
1165
+ if (!VEHICLE_BROKEN_STATES.includes(survey.state) || shared?.agentsNotCurrent) return;
1229
1166
  const reason = safeLine(survey.reason ?? '');
1230
1167
  const { posture, reason: settingsReason } = readExecutorPosture(root, deps);
1231
1168
  const stamp = readStamp(join(root, WORKFLOW_STAMP), readFsDeps(deps));
1232
1169
  const preconditions = [
1233
- ...(stamp === EXPECTED_WORKFLOW_VERSION ? [] : [`run /agent-workflow-kit upgrade first (deployment stamp ${stamp ?? 'none'}, expected ${EXPECTED_WORKFLOW_VERSION})`]),
1170
+ ...(stamp === EXPECTED_WORKFLOW_VERSION ? [] : [upgradeFirst(stamp).message]),
1234
1171
  ...(posture === null ? [`${safeLine(settingsReason)} — fix that`] : []),
1235
1172
  ];
1236
- // The writer refuses on ANY vehicle path it cannot touch (a symlinked read-only vehicle blocks a
1237
- // missing executor's placement too), so its own preflight is the last precondition.
1238
- const blocked = writerBlock(root, deps);
1173
+ // The writer refuses on ANY kit agent path it cannot touch (a linked configured lens blocks a
1174
+ // missing executor's placement too), so its plain dry run is the last precondition, skipped when
1175
+ // the posture is already unreadable so that reason is named once.
1176
+ const blocked = posture === null ? null : writerBlock(root, deps);
1239
1177
  if (blocked) preconditions.push(`${blocked} — fix that`);
1240
1178
  const room = templateBudget(WHATS['executor-vehicle']) - String(configured.length).length - survey.state.length - 2;
1241
1179
  add(
@@ -1245,16 +1183,14 @@ const renderBrokenExecutor = ({ root, deps, add, skip }) => {
1245
1183
  state: survey.state,
1246
1184
  reason: reason && room > 0 ? `: ${truncatedTo(reason, room)}` : '',
1247
1185
  }),
1248
- // The writer places a missing vehicle and re-derives a placed executor whose bytes differ from the derived body (an invalid
1186
+ // The writer places a missing vehicle and writes a placed executor whose bytes differ from the derived body (an invalid
1249
1187
  // frontmatter or read-only tools included), so those states need no precondition; every precondition above is a refusal the apply would meet.
1250
1188
  `node ${q(toolPath('cheap-agents.mjs'))} --apply --cwd ${q(root)}`,
1251
1189
  'executor-vehicle',
1252
1190
  `${preconditions.length ? `precondition: ${preconditions.join('; ')}; ` : ''}${HIDDEN_AGENTS_FOLLOW_UP(root)}`,
1253
1191
  );
1254
- return true;
1255
1192
  } catch (err) {
1256
1193
  skip('executor-vehicle', err);
1257
- return true;
1258
1194
  }
1259
1195
  };
1260
1196
 
@@ -1324,59 +1260,14 @@ export const recipeFingerprint = ({ hosts, dirs, home }) => {
1324
1260
  // so no lane names it. The store's path, keys, lane registry and reader are ack-store.mjs.
1325
1261
 
1326
1262
  // The opt-in read-lane toggle file (AD-055 Part II) — the SAME kit-owned docs/ai/lanes.json the
1327
- // placed hook reads live. The read-lane item offers to enable it once the hook is placed+wired.
1263
+ // placed hook reads live. The read-lane item offers to enable it once the hook is wired.
1328
1264
  export const LANES_FILE = 'docs/ai/lanes.json';
1329
1265
  export const READ_LANE_KEY = 'readLane';
1330
1266
 
1331
- // The placed gate hook + the bundled runtime the read-lane item byte-compares for currency (AD-055
1332
- // Part II, council B7): an enabled lane over a STALE hook is a silent no-op — the pre-1.48 hook never
1333
- // reads lanes.json — so it must surface as an ATTENTION reseed, not a silent convergence.
1334
- const GATE_HOOK_REL = '.claude/hooks/agent-workflow-gates.mjs';
1335
- const BUNDLED_HOOK_ABS = join(HERE, '..', 'references', 'hooks', 'gate-approve.mjs');
1336
-
1337
1267
  // The state-block-guard wiring the advisor looks for is the writer leaf's own rule (any Stop entry of
1338
1268
  // either settings file running the runtime); the two constants are re-exported for their readers.
1339
1269
  export { STATE_BLOCK_HOOK_COMMAND, STATE_BLOCK_HOOK_RUNTIME };
1340
1270
 
1341
- // The placed gate hook's currency, as the states a caller must tell APART (D8). Read through the
1342
- // writer-class fail-closed no-follow primitive, never a bare readFile: a byte-compare that FOLLOWS a
1343
- // symlink can call a placed hook current because something ELSE is — a wrong verdict, which is worse
1344
- // than a missing one. `current` and `stale` are answers; `absent` is one the caller disposes of
1345
- // itself (a hook that is not there belongs to the place offers, never to a refresh arm); a symlink,
1346
- // a directory and an unreadable target all THROW into the probe's stated-skip lane.
1347
- const HOOK_CURRENCY = Object.freeze({ CURRENT: 'current', STALE: 'stale', ABSENT: 'absent' });
1348
- const readsAbsent = (deps, path) => {
1349
- try {
1350
- (deps.lstat ?? lstatSync)(path);
1351
- return false;
1352
- } catch (err) {
1353
- return err?.code === ABSENT_CODE;
1354
- }
1355
- };
1356
-
1357
- const readPlacedHookCurrency = (root, deps) => {
1358
- if (readsAbsent(deps, join(root, GATE_HOOK_REL))) return HOOK_CURRENCY.ABSENT;
1359
- const read = deps.readRegularFileNoFollow ?? readRegularFileNoFollow;
1360
- const placed = read(join(root, GATE_HOOK_REL));
1361
- if (placed.outcome === 'absent') return HOOK_CURRENCY.ABSENT;
1362
- if (placed.outcome === 'foreign') {
1363
- throw new Error(`${GATE_HOOK_REL} is a ${placed.className}, not a regular file — refusing to judge its currency`);
1364
- }
1365
- if (placed.outcome !== 'ok') throw new Error(`${GATE_HOOK_REL} is unreadable (${placed.code})`);
1366
- const bundle = (deps.readFile ?? readFileSync)(deps.bundledHookPath ?? BUNDLED_HOOK_ABS, 'utf8');
1367
- return placed.content === bundle ? HOOK_CURRENCY.CURRENT : HOOK_CURRENCY.STALE;
1368
- };
1369
-
1370
- // Does the declaration carry the marker KEY at all? The question is PRESENCE, never the value: an
1371
- // older hook rejects a key it does not know whatever that key says, so `lcovProducer: false` — a
1372
- // perfectly valid declaration the runner accepts — darkens such a hook exactly as `true` does. Asking
1373
- // through the producer predicate would be wrong twice over: it answers yes for a cmd-recognized
1374
- // producer that needs nothing from the hook, and no for the false marker that does.
1375
- const declarationCarriesMarker = (root, deps) => {
1376
- const declaration = loadDeclaration(root, deps);
1377
- return declaration.outcome === 'loaded' && declaration.gates.some((gate) => Object.hasOwn(gate, LCOV_PRODUCER_KEY));
1378
- };
1379
-
1380
1271
  // Read the opt-in read-lane toggle for the read-lane item. An ABSENT file (or absent docs/ai) →
1381
1272
  // false (the lane is off — offer it). `readLane === true` → enabled (converged). A parse/IO error on
1382
1273
  // an EXISTING file, a symlinked ancestor/leaf, an escape, or a non-object root THROWS — the probe
@@ -1709,7 +1600,7 @@ export const buildRecommendations = ({ cwd, deps = {} } = {}) => {
1709
1600
  // TOO LONG for the capped WHAT and outside the pure-command apply (such as the bridge-tier
1710
1601
  // missing-entries line or the worktrees-dir ack fallback). Single-line like apply; absent otherwise.
1711
1602
  // Returns whether the item really RENDERED. One probe's disposition depends on another's having
1712
- // spoken (the marker-stale ⟷ read-lane.stale precedence), and "the conditions still look right"
1603
+ // spoken (executor-vehicle yields to agents.not-current), and "the conditions still look right"
1713
1604
  // is not the same fact as "an item exists" — the shape backstop can refuse, and a condition read
1714
1605
  // twice can answer twice.
1715
1606
  const add = (key, what, apply, variant = key, detail = null) => {
@@ -1734,16 +1625,21 @@ export const buildRecommendations = ({ cwd, deps = {} } = {}) => {
1734
1625
  return true;
1735
1626
  };
1736
1627
  // The per-run scratch a probe uses to tell a LATER probe what it actually did. Written by exactly
1737
- // one pair today (the marker-stale ⟷ read-lane.stale precedence) and read in the frozen PROBES
1628
+ // one pair today (executor-vehicle yields to agents.not-current) and read in the frozen PROBES
1738
1629
  // order, so the reader can never run first.
1739
1630
  const shared = {};
1631
+ // A device node reads as absent (a sandbox mask), except under .claude/agents/ and at or under
1632
+ // .claude/hooks/: there it is the kit writer's refusal, as the danger check reads it.
1633
+ const agentsDir = join(root, AGENTS_DIR) + sep;
1634
+ const hooksDir = join(root, HOOKS_DIR) + sep;
1635
+ const kitPath = (path) => String(path).startsWith(agentsDir) || `${path}${sep}`.startsWith(hooksDir);
1740
1636
  const contentDeps = Object.create(Object.getPrototypeOf(deps), {
1741
1637
  ...Object.getOwnPropertyDescriptors(deps),
1742
1638
  lstat: {
1743
1639
  enumerable: true,
1744
1640
  value: (path, ...args) => {
1745
1641
  const stat = (deps.lstat ?? deps.lstatSync ?? lstatSync)(path, ...args);
1746
- if (stat.isCharacterDevice?.() || stat.isBlockDevice?.()) {
1642
+ if (!kitPath(path) && (stat.isCharacterDevice?.() || stat.isBlockDevice?.())) {
1747
1643
  throw Object.assign(new Error(`${ABSENT_CODE}: ${path}`), { code: ABSENT_CODE });
1748
1644
  }
1749
1645
  return stat;
@@ -51,6 +51,7 @@ import {
51
51
  writeHookFile,
52
52
  } from './gate-hook.mjs';
53
53
  import { isDirectRun } from './direct-run.mjs';
54
+ import { fileLine } from './distribution-files/index.mjs';
54
55
 
55
56
  const HERE = dirname(fileURLToPath(import.meta.url));
56
57
 
@@ -206,11 +207,10 @@ const STATE_BLOCK_CURRENT_LINE = 'nothing to change: the state-block hook is pla
206
207
  const TRUST_POSTURE_LINE =
207
208
  'trust posture: the guard reads the closing assistant message of each turn and writes one warning line; it runs a Node process on every turn end, reads nothing else, makes no network call and approves nothing.';
208
209
 
209
- const PLACEMENT_LINES = Object.freeze({
210
- [PLACEMENT_CREATE]: ['would place', 'placed'],
211
- [PLACEMENT_KEEP]: ['already current', 'already current'],
212
- [PLACEMENT_REPLACE]: ['would replace with the bundle (it differs from the bundled runtime)', 'replaced with the bundle'],
213
- });
210
+ const PLACEMENT_LINES = Object.freeze({ [PLACEMENT_CREATE]: ['would place', 'placed'], [PLACEMENT_KEEP]: ['already current', 'already current'] });
211
+ const placementLine = ({ placement, dryRun }) => (placement === PLACEMENT_REPLACE
212
+ ? fileLine({ rel: STATE_BLOCK_HOOK_FILE_REL, state: 'hook' }, dryRun ? undefined : 'written', dryRun)
213
+ : `${STATE_BLOCK_HOOK_FILE_REL}: ${PLACEMENT_LINES[placement][dryRun ? 0 : 1]}`);
214
214
 
215
215
  const MERGE_LINES = Object.freeze({
216
216
  [MERGE_NO_HOOKS]: 'the hooks key with the Stop entry',
@@ -230,7 +230,7 @@ export const formatResult = (result) => {
230
230
  result.dryRun
231
231
  ? 'agent-workflow state-block hook — DRY RUN (no changes; re-run with --apply)'
232
232
  : 'agent-workflow state-block hook — APPLY',
233
- ` - ${STATE_BLOCK_HOOK_FILE_REL}: ${PLACEMENT_LINES[result.placement][result.dryRun ? 0 : 1]}`,
233
+ ` - ${placementLine(result)}`,
234
234
  formatSettingsLine(result),
235
235
  ` command: ${STATE_BLOCK_HOOK_COMMAND} (no --require-block; references/modes/state-block-guard.md says when to add it)`,
236
236
  TRUST_POSTURE_LINE,