@sabaiway/agent-workflow-kit 15.1.0 → 16.1.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.
@@ -1,35 +1,26 @@
1
- // ensure-specs.mjs — the SIXTH upgrade ensure: the spec layer (memory 4.6.0, AD-112) delivered to an
2
- // EXISTING deployment on an equal-head upgrade. Four deployed scripts (the pairs script-priors.mjs
3
- // names; every other kit script is the scripts ensure's) and one store root, written in a FIXED order
4
- // the measured coupling dictates:
5
- // 1. the reader pair scripts/spec-schema.mjs + .test.mjs — created when absent; since 2a
6
- // also REFRESHED when the deployed bytes are a body a release shipped (script-priors.mjs), a
7
- // custom body preserved verbatim and reported as a replace entry (distribution-files/): the
8
- // ONE replace block keeps it aside and replaces it only on the user's yes;
9
- // 2. the checker pair scripts/check-docs-size.mjs + .test.mjs — the same prior-refresh lane, and
10
- // only behind a reader pair this run leaves byte-current;
11
- // 3. the store root docs/ai/specs/index.md — seeded (placeholders rendered)
12
- // only once both pairs are current.
1
+ // ensure-specs.mjs — the SIXTH upgrade ensure: the spec layer (memory 4.6.0, AD-112) kept current on an
2
+ // EXISTING deployment. Four deployed scripts (the pairs script-priors.mjs names; every other kit script
3
+ // is the scripts ensure's) and one store root, by the scripts op's rule (distribution-files/): every
4
+ // file is surveyed by proof first, then on every plain run a prior body is refreshed and an edited one
5
+ // replaced in place, an absent one placed create-only and an absent store root seeded create-only, with
6
+ // no question and no copy kept; a current file is left. The writes run in a FIXED order:
7
+ // 1. the reader pair scripts/spec-schema.mjs + .test.mjs
8
+ // 2. the checker pair scripts/check-docs-size.mjs + .test.mjs
9
+ // 3. the store root docs/ai/specs/index.md (placeholders rendered)
13
10
  // Why the order: the kit's bundled navigator generator collapses `specs/` into one row, while the
14
11
  // project's pre-commit hook runs ITS deployed checker — an older one renders the store row by row and
15
- // reds `--check-index`. A store root seeded behind a stale checker breaks the hook, so the store is
16
- // the LAST write and admits only behind a checker this run has proven current.
17
- //
18
- // The state table (enumerate by PROOF, never by exclusion): every file is classified into exactly one
19
- // of current | prior | custom | absent | wrong-kind before anything is written, each write admits
20
- // through ONE conjunction of those facts (decideWrites), and every other cell is a stated refusal —
21
- // a custom file of either pair preserves itself AND withholds every write that depends on it. Under
22
- // the replace the driver hands back (`replace: { digest, entries }`), the bound custom files are
23
- // rewritten. Writes run in order and each is idempotent, so a stopped run converges on the next.
12
+ // reds `--check-index`. So the checker is written before the spec store, and a write that fails stops
13
+ // every later one. The pair lines and the hook-run line are the scripts op's own, from the module's
14
+ // index. Each write is idempotent, so a stopped run converges on the next.
24
15
  //
25
16
  // Dependency-free, Node >= 22. Every fs primitive is injectable (deps.*). No side effects on import.
26
17
 
27
18
  import { readFileSync, lstatSync } from 'node:fs';
28
19
  import { join } from 'node:path';
29
20
  import { writeContainedFileAtomic, writeProjectFileCreateOnly } from './atomic-write.mjs';
30
- import { CHECKER_PAIR, READER_PAIR, classifyDeployedScript, digestOf } from './script-priors.mjs';
21
+ import { CHECKER_PAIR, READER_PAIR, classifyDeployedScript } from './script-priors.mjs';
31
22
  import { composeFailure, composeOutcome, nodeEvidenceRefusal, probeSeedTarget, tmpNote } from './ensure-ops.mjs';
32
- import { SCRIPT_CHANNEL, keptAsidePath } from './distribution-files/index.mjs';
23
+ import { fileLine, hookLine } from './distribution-files/index.mjs';
33
24
 
34
25
  const OP = 'specs';
35
26
  const SCRIPTS_DIR = 'scripts';
@@ -56,8 +47,7 @@ const surveyScript = ({ cwd, kitRoot, name, read, lstat }) => {
56
47
  const probe = probeSeedTarget(join(cwd, SCRIPTS_DIR, name), lstat);
57
48
  if (probe.wrongKind) return { rel, name, state: 'wrong-kind', wrongKind: probe.wrongKind, bundle };
58
49
  if (!probe.present) return { rel, name, state: 'absent', bundle };
59
- const bytes = read(join(cwd, SCRIPTS_DIR, name));
60
- return { rel, name, state: classifyDeployedScript(bytes, name, bundle), bundle, bytes };
50
+ return { rel, name, state: classifyDeployedScript(read(join(cwd, SCRIPTS_DIR, name)), name, bundle), bundle };
61
51
  };
62
52
 
63
53
  const surveyStoreRoot = (cwd, lstat) => {
@@ -66,94 +56,23 @@ const surveyStoreRoot = (cwd, lstat) => {
66
56
  return { rel: STORE_ROOT_REL, state: probe.present ? 'present' : 'absent' };
67
57
  };
68
58
 
69
- // ── the decision: which writes the survey admits (pure over the survey) ───────────────────────────
70
-
71
- // Reader seeds are create-only and always admitted. A REFRESH overwrites bytes, so it runs only
72
- // inside a pair whose every file is proven refreshable (current | prior | absent) — one custom file
73
- // withholds its whole pair; the checker lane (its seeds included) and the store additionally wait
74
- // for a reader pair this run leaves byte-current (seeded + refreshed = current). Under the user's
75
- // replace yes a custom file is refreshable too: it is rewritten to the bundled body.
76
- const PAIR_ELIGIBLE = new Set(['current', 'prior', 'absent']);
77
- const REPLACE_ELIGIBLE = new Set([...PAIR_ELIGIBLE, 'custom']);
59
+ // ── the lines (composed from what HAPPENED: each file's state and the fate of its write) ─────────
78
60
 
79
- export const decideWrites = ({ reader, checker, store }, replace = false) => {
80
- const eligible = replace ? REPLACE_ELIGIBLE : PAIR_ELIGIBLE;
81
- const refreshable = replace ? ['prior', 'custom'] : ['prior'];
82
- const readerEligible = reader.every((f) => eligible.has(f.state));
83
- const checkerEligible = readerEligible && checker.every((f) => eligible.has(f.state));
84
- const writes = [];
85
- for (const f of reader) {
86
- if (f.state === 'absent') writes.push({ kind: 'seed', file: f });
87
- if (readerEligible && refreshable.includes(f.state)) writes.push({ kind: 'refresh', file: f });
88
- }
89
- if (checkerEligible) {
90
- for (const f of checker) {
91
- if (f.state === 'absent') writes.push({ kind: 'seed', file: f });
92
- if (refreshable.includes(f.state)) writes.push({ kind: 'refresh', file: f });
93
- }
94
- }
95
- if (checkerEligible && store.state === 'absent') writes.push({ kind: 'store' });
96
- return { writes, withheld: !checkerEligible };
97
- };
98
-
99
- // ── the lines (composed from what HAPPENED, never from what was planned) ──────────────────────────
100
-
101
- // Every file's line is a function of its surveyed state and the FATE of its write this run:
102
- // `written` · `stood` (lost the create-only race to the bundled body) · `would` (dry run) ·
103
- // `withheld` (a custom file in the pair) · `stopped` (the run failed before reaching it) · `none`
104
- // (no write was admitted or needed). A line never claims a write that did not happen. Under the
105
- // replace a custom line names its kept-aside copy and never points at a block below.
106
- const LEFT_FOR = { withheld: 'it waits on the pair named above', stopped: 'the run stopped before it' };
107
- const SCRIPT_LINES = {
108
- current: () => 'already the bundled body — nothing written',
109
- custom: (fate, kept) => (fate === 'written' ? `carried an edit — kept aside at ${kept}, then replaced by the bundled body on the user's yes`
110
- : kept !== undefined ? `carries an edit — not replaced${kept ? `; its copy kept aside at ${kept} stays` : ''}`
111
- : "carries an edit — left as it stands until the user's yes keeps it aside and replaces it (the block below); the writes that depend on it wait"),
112
- absent: (fate) => ({
113
- written: 'copied from the bundled scripts',
114
- stood: 'appeared while this run was seeding it — the bundled body stands',
115
- would: 'absent — would be copied from the bundled scripts',
116
- })[fate] ?? `absent — not copied${fate === 'withheld' ? ' this run' : ''}; ${LEFT_FOR[fate]}`,
117
- prior: (fate) => `matches a body an earlier release shipped — ${({
118
- written: 'refreshed to the bundled one',
119
- would: 'would be refreshed to the bundled one',
120
- })[fate] ?? `left as is; ${LEFT_FOR[fate]}`}`,
121
- };
122
- const scriptLine = (f, fate, keptOf) => `${f.rel}: ${SCRIPT_LINES[f.state](fate, keptOf?.(f.rel))}`;
61
+ // A fate is `written`, `stood` (a create-only write that found the path taken: a pair file with the
62
+ // bundled body, or a store root as found), `refused` (its write failed), or none: the run stopped
63
+ // before it, or, dry, would write it. A pair file that is not current takes the scripts op's line.
64
+ const CURRENT = 'already the bundled body — nothing written';
123
65
  const STORE_LINES = {
124
66
  present: 'already present — preserved byte-for-byte, nothing written',
125
67
  written: "created from the bundled template (today's date rendered)",
126
68
  stood: 'appeared while this run was seeding it — the existing file stands',
127
69
  would: 'absent — would be created from the bundled template',
128
- withheld: (custom) => `not seeded — it waits on the edited ${custom.join(', ')} (a body this kit did not ship): an older or edited checker renders the spec store row by row and reds the hook's index check, so the store root waits for a current checker pair`,
129
- stopped: 'absent — not created; the run stopped before it',
130
- };
131
- const storeLine = (store, fate, custom) => {
132
- const line = STORE_LINES[store.state === 'present' ? 'present' : fate];
133
- return `${STORE_ROOT_REL}: ${typeof line === 'function' ? line(custom) : line}`;
134
- };
135
- const relOf = (write) => (write.kind === 'store' ? STORE_ROOT_REL : write.file.rel);
136
-
137
- // The fate of every path for the lines: a write that ran carries its result, an admitted write the
138
- // run never reached is `stopped`, and a path with no admitted write is `withheld` behind a custom
139
- // file or `none` when nothing was needed.
140
- const fateOf = (rel, { writes, fates, withheld, stopped }) => {
141
- if (fates.has(rel)) return fates.get(rel);
142
- if (writes.some((w) => relOf(w) === rel)) return stopped ? 'stopped' : 'would';
143
- return withheld ? 'withheld' : 'none';
144
- };
145
- const composeLines = ({ reader, checker, store, writes, fates, withheld, stopped, keptOf }) => {
146
- const fate = (rel) => fateOf(rel, { writes, fates, withheld, stopped });
147
- const lines = [...reader, ...checker].map((f) => scriptLine(f, fate(f.rel), keptOf));
148
- const storeFate = fate(STORE_ROOT_REL);
149
- const custom = [...reader, ...checker].filter((f) => f.state === 'custom').map((f) => f.rel);
150
- if (store.state === 'present' || storeFate !== 'none') lines.push(storeLine(store, storeFate, custom));
151
- return lines;
70
+ stopped: 'absent — not created',
152
71
  };
153
-
154
- // Under the replace the op's own survey must yield exactly the entries the yes bound.
155
- const sameEntries = (own, bound) =>
156
- own.length === bound.length && own.every((e) => bound.some((b) => b.rel === e.rel && !b.absent && b.sha256 === e.sha256));
72
+ const composeLines = ({ files, store, fates, dryRun }) => [
73
+ ...files.map((f) => (f.state === 'current' ? `${f.rel}: ${CURRENT}` : fileLine(f, fates.get(f.rel), dryRun))),
74
+ `${STORE_ROOT_REL}: ${STORE_LINES[store.state === 'present' ? 'present' : fates.get(STORE_ROOT_REL) ?? (dryRun ? 'would' : 'stopped')]}`,
75
+ ];
157
76
 
158
77
  // A per-file loop can stop partway; the run says which files already landed — never "nothing happened".
159
78
  const partialNote = (count) =>
@@ -169,82 +88,67 @@ const renderStoreRoot = (kitRoot, read, today) => {
169
88
  return body;
170
89
  };
171
90
 
172
- export const ensureSpecs = ({ cwd, kitRoot, dryRun = false, deps = {}, replace }) => {
91
+ // One write per due path in write order: a prior refreshed and an edit replaced by the atomic write,
92
+ // an absent pair file and the store root written create-only. → { fates, notes, failure? }
93
+ const writeAll = ({ cwd, due, storeBody, deps, read }) => {
94
+ const fates = new Map();
95
+ const notes = [];
96
+ for (const f of due) {
97
+ const isStore = f.rel === STORE_ROOT_REL;
98
+ let result;
99
+ try {
100
+ result = isStore ? writeProjectFileCreateOnly(cwd, f.rel, storeBody, deps, { noun: 'the spec store root' })
101
+ : f.state === 'absent' ? writeProjectFileCreateOnly(cwd, f.rel, String(f.bundle), deps, { noun: 'a seeded spec-layer script' })
102
+ : writeContainedFileAtomic(cwd, join(cwd, f.rel), String(f.bundle), deps, { label: f.rel });
103
+ } catch (err) {
104
+ if (!isStore) fates.set(f.rel, 'refused');
105
+ return { fates, notes, failure: ['write-refused', `${f.rel}: ${causeOf(err)}`] };
106
+ }
107
+ notes.push(...tmpNote(f.rel, result.tmpLeftBehind));
108
+ const stood = f.state === 'absent' && !result.created;
109
+ if (stood && !isStore && classifyDeployedScript(read(join(cwd, f.rel)), f.name, f.bundle) !== 'current') {
110
+ fates.set(f.rel, 'refused');
111
+ return { fates, notes, failure: ['race-unresolved', `${f.rel}: appeared while this run was placing it and does not carry the bundled body — nothing further written, re-run when the tree is settled`] };
112
+ }
113
+ fates.set(f.rel, stood ? 'stood' : 'written');
114
+ }
115
+ return { fates, notes };
116
+ };
117
+
118
+ export const ensureSpecs = ({ cwd, kitRoot, dryRun = false, deps = {} }) => {
173
119
  const lstat = deps.lstat ?? lstatSync;
174
120
  const read = deps.readFile ?? readFileSync;
175
121
  const refusal = nodeEvidenceRefusal(OP, cwd, lstat);
176
122
  if (refusal) return refusal;
177
123
  const survey = (name) => surveyScript({ cwd, kitRoot, name, read, lstat });
178
- const reader = READER_PAIR.map(survey);
179
- const checker = CHECKER_PAIR.map(survey);
124
+ const files = [...READER_PAIR.map(survey), ...CHECKER_PAIR.map(survey)];
180
125
  const store = surveyStoreRoot(cwd, lstat);
181
- for (const f of [...reader, ...checker]) {
126
+ for (const f of files) {
182
127
  if (f.state === 'bundle-unreadable') return composeFailure(OP, 'bundle-unreadable', `${f.rel}: the bundled script could not be read, so nothing was written — reinstall the kit. ${f.error}`);
183
128
  }
184
- for (const f of [...reader, ...checker, store]) {
129
+ for (const f of [...files, store]) {
185
130
  if (f.state === 'wrong-kind') return composeFailure(OP, 'wrong-node-kind', `${f.rel}: exists but is ${f.wrongKind} — nothing was read or written; resolve it by hand, then re-run`);
186
131
  }
187
132
 
188
- // The survey completed: its entries ride every outcome from here on, a failed one included.
189
- const custom = [...reader, ...checker].filter((f) => f.state === 'custom');
190
- const entries = custom.map((f) => ({ rel: f.rel, sha256: digestOf(f.bytes), bytes: f.bytes, channel: SCRIPT_CHANNEL }));
191
- const ok = (token, lines) => ({ ...composeOutcome(OP, token, lines, false), entries });
192
- const loud = (cause, ...lines) => ({ ...composeFailure(OP, cause, ...lines), entries });
193
- const bound = replace ? new Map(replace.entries.map((e) => [e.rel, e.sha256])) : null;
194
- const keptOf = bound && ((rel) => (bound.has(rel) ? keptAsidePath(replace.digest, rel) : ''));
195
- if (bound && !sameEntries(entries, replace.entries)) {
196
- const asFound = decideWrites({ reader, checker, store });
197
- return loud('race-unresolved', 'the edited spec-layer files are not the set the yes was given for (another set or other bytes), so nothing was written', ...composeLines({ reader, checker, store, ...asFound, fates: new Map(), stopped: true, keptOf }));
133
+ const due = [...files.filter((f) => f.state !== 'current'), ...(store.state === 'absent' ? [store] : [])];
134
+ const seeds = (fs) => fs.some((f) => f.state === 'absent');
135
+ const refreshes = (fs) => fs.some((f) => f.state === 'prior' || f.state === 'custom');
136
+ if (dryRun) {
137
+ const token = seeds(due) ? 'would-seed' : refreshes(due) ? 'would-refresh' : 'already-present';
138
+ return composeOutcome(OP, token, [...composeLines({ files, store, fates: new Map(), dryRun }), ...(due.length > 0 ? [hookLine(false, true)] : [])], false);
198
139
  }
199
- const { writes, withheld } = decideWrites({ reader, checker, store }, Boolean(bound));
200
- const kinds = new Set(writes.map((w) => w.kind));
201
- // ONE token by precedence — a write that happened (or, dry, would happen) always outranks the
202
- // preserved-custom report, which names a run that wrote nothing behind an edited pair.
203
- const tokenFor = (seeded, refreshed) => {
204
- if (seeded) return dryRun ? 'would-seed' : 'seeded';
205
- if (refreshed) return dryRun ? 'would-refresh' : 'refreshed';
206
- return withheld ? 'customized-preserved' : 'already-present';
207
- };
208
- const fates = new Map();
209
- const linesNow = (stopped) => composeLines({ reader, checker, store, writes, fates, withheld, stopped, keptOf });
210
- const writtenCount = () => [...fates.values()].filter((fate) => fate === 'written').length;
211
- if (dryRun) return ok(tokenFor(kinds.has('seed') || kinds.has('store'), kinds.has('refresh')), linesNow(false));
212
140
 
213
141
  let storeBody = null;
214
- if (kinds.has('store')) {
142
+ if (store.state === 'absent') {
215
143
  try {
216
144
  storeBody = renderStoreRoot(kitRoot, read, deps.today ?? todayIso());
217
145
  } catch (err) {
218
- return loud('template-unreadable', `${STORE_ROOT_REL}: ${causeOf(err)}`, ...linesNow(true));
219
- }
220
- }
221
- const writeOne = ({ kind, file }) => {
222
- if (kind === 'store') return writeProjectFileCreateOnly(cwd, STORE_ROOT_REL, storeBody, deps, { noun: 'the spec store root' });
223
- if (kind === 'seed') return writeProjectFileCreateOnly(cwd, file.rel, String(file.bundle), deps, { noun: 'a seeded spec-layer script' });
224
- return writeContainedFileAtomic(cwd, join(cwd, file.rel), String(file.bundle), deps, { label: file.rel });
225
- };
226
- // A seed that lost the create-only race is re-PROVEN before anything that depends on it runs: the
227
- // file that appeared must carry the bundled body, or the tree is changing underneath this run.
228
- const stoodCurrent = ({ kind, file }) => kind === 'store' || classifyDeployedScript(read(join(cwd, file.rel)), file.name, file.bundle) === 'current';
229
- const movedSinceBind = ({ kind, file }) => { if (kind !== 'refresh' || !bound?.has(file.rel)) return false; try { return digestOf(read(join(cwd, file.rel))) !== bound.get(file.rel); } catch { return true; } };
230
- const notes = [];
231
- for (const write of writes) {
232
- const rel = relOf(write);
233
- if (movedSinceBind(write)) {
234
- return loud('race-unresolved', `${rel}: changed after this run read it — left as it stands and nothing further written`, ...linesNow(true), ...notes, ...partialNote(writtenCount()));
235
- }
236
- let result;
237
- try {
238
- result = writeOne(write);
239
- } catch (err) {
240
- return loud('write-refused', `${rel}: ${causeOf(err)}`, ...linesNow(true), ...notes, ...partialNote(writtenCount()));
241
- }
242
- if (write.kind !== 'refresh' && !result.created && !stoodCurrent(write)) {
243
- return loud('race-unresolved', `${rel}: appeared while this run was seeding it and does not carry the bundled body — something is writing there underneath this run; nothing further written, re-run when the tree is settled`, ...linesNow(true), ...notes, ...partialNote(writtenCount()));
146
+ return composeFailure(OP, 'template-unreadable', `${STORE_ROOT_REL}: ${causeOf(err)}`, ...composeLines({ files, store, fates: new Map(), dryRun }));
244
147
  }
245
- fates.set(rel, write.kind !== 'refresh' && !result.created ? 'stood' : 'written');
246
- notes.push(...tmpNote(rel, result.tmpLeftBehind));
247
148
  }
248
- const landed = (kind) => writes.some((w) => w.kind === kind && fates.get(relOf(w)) === 'written');
249
- return ok(tokenFor(landed('seed') || landed('store'), landed('refresh')), [...linesNow(false), ...notes]);
149
+ const { fates, notes, failure } = writeAll({ cwd, due, storeBody, deps, read });
150
+ const written = due.filter((f) => fates.get(f.rel) === 'written');
151
+ const lines = [...composeLines({ files, store, fates, dryRun }), ...(written.length > 0 ? [hookLine(false, false)] : []), ...notes];
152
+ if (failure) return composeFailure(OP, failure[0], failure[1], ...lines, ...partialNote(written.length));
153
+ return composeOutcome(OP, seeds(written) ? 'seeded' : refreshes(written) ? 'refreshed' : 'already-present', lines, false);
250
154
  };
@@ -9,9 +9,9 @@
9
9
 
10
10
  // The FIXED order the CLI runs them in — the order references/modes/upgrade.md already prescribed.
11
11
  // `specs` sits after `scripts` (its reader pair is a scripts/ seed too) and BEFORE `index`: the store
12
- // root it seeds is a docs/ai file the navigator must count. `specs` alone owns the replace run: its
13
- // edited files are written only on the user's yes, while `scripts` writes every kit script with no
14
- // question and then runs the project's rotator (`--ensure-current`), which brings the ADR store current.
12
+ // root it seeds is a docs/ai file the navigator must count. `specs` writes its pairs and `scripts`
13
+ // every kit script with no question and no copy kept, and `scripts` then
14
+ // runs the project's rotator (`--ensure-current`), which brings the ADR store current.
15
15
  // `executor` follows `vehicles`: its body is derived from the settings file that op seeds.
16
16
  // `rules` follows `specs` and precedes `index`: the rules files it lays are docs/ai files the navigator counts.
17
17
  export const ENSURE_OPS = Object.freeze(['orchestration', 'gates', 'autonomy', 'vehicles', 'executor', 'scripts', 'specs', 'rules', 'index']);
@@ -20,8 +20,8 @@ export const ENSURE_OPS = Object.freeze(['orchestration', 'gates', 'autonomy', '
20
20
  // walks this set), and each has exactly one `would-` counterpart below. `refreshed` is the spec-layer
21
21
  // ensure's pair refresh (reader or checker) or the scripts ensure's write of a kit script — a deployed
22
22
  // script on a body a release shipped, or an edited one, rewritten to the bundled one on a plain run, an
23
- // absent kit script placed (`seeded`), or the ADR store the rotator brought current; an edited spec-layer file is replaced only by the replace run the
24
- // user's yes starts (--replace-custom, over the spec layer).
23
+ // absent kit script placed (`seeded`), or the ADR store the rotator brought current; an edited
24
+ // spec-layer file is replaced on the same plain run.
25
25
  export const WRITE_TOKENS = Object.freeze(['seeded', 'note-refreshed', 'refreshed', 'regenerated']);
26
26
  export const DRY_RUN_TOKENS = Object.freeze(['would-seed', 'would-refresh-note', 'would-refresh', 'would-regenerate']);
27
27
 
@@ -13,7 +13,7 @@ import { preflightInit } from './init-preflight.mjs';
13
13
  import { buildRecommendations, hostFacts } from './recommendations.mjs';
14
14
  import { compareSemver } from './semver-lite.mjs';
15
15
  import { EXPECTED_WORKFLOW_VERSION } from './velocity-profile.mjs';
16
- import { LANE_HARNESS, VARIANT_LANES, consoleArgv, isEnvDependent, isProtectedPath, isRejudged, laneOf, writesOf } from './write-lanes.mjs';
16
+ import { LANE_HARNESS, LANE_KIT, VARIANT_LANES, consoleArgv, isEnvDependent, isProtectedPath, isRejudged, laneOf, writesOf } from './write-lanes.mjs';
17
17
 
18
18
  const INSIDE_LINE = 'you are inside an agent; run this in your own terminal';
19
19
  const APPLY_PROMPT = 'apply? y/N: ';
@@ -218,7 +218,7 @@ const previewQueue = async (context, queue) => {
218
218
  const tuple = result.stdout.match(/--apply\s+(\S+)/)?.[1];
219
219
  const facts = { ...context.facts, env: context.spawnEnv, tuple };
220
220
  let checkDigest = null;
221
- if (laneOf(item.variant) === LANE_HARNESS) {
221
+ if ([LANE_HARNESS, LANE_KIT].includes(laneOf(item.variant))) {
222
222
  try {
223
223
  const { lines, refused, digest } = context.checkApply(item.variant, facts, {});
224
224
  for (const line of lines) context.print(line);
@@ -46,7 +46,7 @@ import {
46
46
  } from './velocity-profile.mjs';
47
47
  import { loadAutonomy, isSparseSeedConfig, AUTONOMY_REL } from './autonomy-config.mjs';
48
48
  import { deriveDoctorPlan, TRUSTED_DIRS } from './autonomy-doctor.mjs';
49
- import { laneOf, applySlot, consoleArgv } from './write-lanes.mjs';
49
+ import { LANE_KIT, laneOf, applySlot, consoleArgv } from './write-lanes.mjs';
50
50
  import { STATE_BLOCK_HOOK_COMMAND, STATE_BLOCK_HOOK_RUNTIME, isStopHookWired } from './state-block-hook.mjs';
51
51
  import { detectBackends } from './detect-backends.mjs';
52
52
  import { isDirectRun } from './direct-run.mjs';
@@ -212,8 +212,8 @@ export const SEVERITIES = Object.freeze({
212
212
  // names the subagent carrier over a vehicle that cannot carry it — a configured declaration that
213
213
  // is broken, which is what attention means.
214
214
  'executor-vehicle': SEVERITY_ATTENTION,
215
- // A hand edit of the placed executor is not a broken declaration — the vehicle still carries — so
216
- // re-deriving it is an offer.
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
217
  'executor-vehicle.differing': SEVERITY_OPTIONAL,
218
218
  // The AGENTS.md block is a configured choice the harness does not honour.
219
219
  attribution: SEVERITY_ATTENTION,
@@ -249,16 +249,15 @@ const fillTemplate = (template, values) => template.replace(/\{([A-Za-z]+)\}/g,
249
249
  // composeVerdict(counts) → the ONE verdict line, or null for the optimal state (D1 state matrix).
250
250
  // attention>0 leads; the "nothing is broken" wording renders ONLY when attention==0 AND skipped==0
251
251
  // (a skipped probe could hide an attention-class problem, so the claim would overreach; it renders
252
- // only as the lead-in to the optional offer, never in a skips-only state); the skips part is
253
- // appended last.
254
- export const composeVerdict = ({ attention, optional, skipped }) => {
255
- if (attention === 0 && optional === 0 && skipped === 0) return null;
252
+ // as the lead-in to the optional offer, or alone beside kit items only, which count in neither class:
253
+ // the agent applies them with no pick); the skips part is appended last.
254
+ export const composeVerdict = ({ attention, optional, skipped, kit = 0 }) => {
255
+ if (attention === 0 && optional === 0 && skipped === 0 && kit === 0) return null;
256
256
  const parts = [];
257
257
  if (attention > 0) parts.push(fillTemplate(VERDICT_ATTENTION_TEMPLATE, { K: attention }));
258
- if (optional > 0) {
259
- const offer = fillTemplate(VERDICT_OPTIONAL_TEMPLATE, { N: optional });
260
- parts.push(attention === 0 && skipped === 0 ? `${VERDICT_NOTHING_BROKEN} — ${offer}` : offer);
261
- }
258
+ const offer = optional > 0 ? fillTemplate(VERDICT_OPTIONAL_TEMPLATE, { N: optional }) : null;
259
+ if (attention === 0 && skipped === 0) parts.push(offer ? `${VERDICT_NOTHING_BROKEN} — ${offer}` : VERDICT_NOTHING_BROKEN);
260
+ else if (offer) parts.push(offer);
262
261
  if (skipped > 0) parts.push(fillTemplate(VERDICT_SKIPS_TEMPLATE, { M: skipped }));
263
262
  return parts.join('; ');
264
263
  };
@@ -307,7 +306,7 @@ export const WHATS = Object.freeze({
307
306
  agents: '{n} bundled subagent vehicle(s) not placed (Claude Code) — {ro} read-only, {ex} the full-tool executor; the apply PREVIEWS first',
308
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)',
309
308
  'executor-vehicle': '{n} slot(s) configured subagent but the executor vehicle is {state}{reason} — every such slot runs solo until it is usable',
310
- 'executor-vehicle.differing': 'the placed executor vehicle differs from the body derived from docs/ai/vehicles.json — a hand edit stands until it is re-derived',
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',
311
310
  attribution: 'AGENTS.md says attribution off but .claude/settings.json does not hide the harness trailer and PR text',
312
311
  'footprint-global': 'legacy kit ignore line(s) sit in {file} — they ignore kit paths in every repository here',
313
312
  'family-freshness': '{parts}',
@@ -387,7 +386,7 @@ export const BENEFITS = Object.freeze({
387
386
  });
388
387
  // The one arm whose gain differs from its base item's (BENEFITS stays keyed by item key).
389
388
  export const VARIANT_BENEFITS = Object.freeze({
390
- 'executor-vehicle.differing': 'carrier fidelity — the placed executor runs the model and effort docs/ai/vehicles.json names, not a hand edit',
389
+ 'executor-vehicle.differing': 'carrier fidelity — the placed executor runs the model and effort docs/ai/vehicles.json names',
391
390
  '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',
392
391
  });
393
392
 
@@ -1208,10 +1207,10 @@ const probeExecutorVehicle = ({ root, deps, add, skip }) => {
1208
1207
  if (renderBrokenExecutor({ root, deps, add, skip })) return;
1209
1208
  try {
1210
1209
  if (!executorBodyDiffers(root, deps)) return;
1211
- const plan = writeCheapAgents({ cwd: root, dryRun: true }, deps);
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
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),
1214
- 'executor-vehicle.differing', HIDDEN_AGENTS_FOLLOW_UP(root));
1213
+ add('executor-vehicle', WHATS['executor-vehicle.differing'], formsApply('executor-vehicle.differing', root), 'executor-vehicle.differing');
1215
1214
  } catch (err) {
1216
1215
  skip('executor-vehicle', err);
1217
1216
  }
@@ -1761,8 +1760,8 @@ export const buildRecommendations = ({ cwd, deps = {} } = {}) => {
1761
1760
  // facts/counts complete, commands byte-exact; the raw block on request) ─────────────────────────
1762
1761
  export const formatRecommendations = ({ items, skips }) => {
1763
1762
  const lines = [RECOMMENDATIONS_SECTION_HEADER, ''];
1764
- const attention = items.filter((i) => i.severity === SEVERITY_ATTENTION).length;
1765
- const verdict = composeVerdict({ attention, optional: items.length - attention, skipped: skips.length });
1763
+ const [kit, attention] = [items.filter((i) => i.lane === LANE_KIT).length, items.filter((i) => i.lane !== LANE_KIT && i.severity === SEVERITY_ATTENTION).length];
1764
+ const verdict = composeVerdict({ attention, optional: items.length - attention - kit, skipped: skips.length, kit });
1766
1765
  if (verdict == null) {
1767
1766
  // The flow-optimal claim renders ONLY when every probe ran and none fired — an empty item
1768
1767
  // list beside skipped checks would falsely attest optimality (Segment B).
@@ -1800,7 +1799,7 @@ Computes the deterministic Recommendations section every kit upgrade ends with
1800
1799
  one composed verdict line opens every non-optimal render, then per item {severity · what is
1801
1800
  sub-optimal · the benefit in one plain line · the lane · an optional \`recipe:\` line (an item's own
1802
1801
  facts or its alternative, such as the bridge-tier missing-entries line or
1803
- the worktrees-dir ack fallback) · the harness check line · the exact consent-gated apply one-liner}. --cwd is
1802
+ the worktrees-dir ack fallback) · the harness or kit check line · the exact consent-gated apply one-liner}. --cwd is
1804
1803
  REQUIRED (the target project is explicit, never inferred from the shell's current directory). The
1805
1804
  section renders present-even-when-empty ("${RECOMMENDATIONS_EMPTY_LINE}"); a probe failure is a
1806
1805
  stated skipped-item line. Apply lines are cwd-independent (absolute tool paths, a pinned --cwd;
@@ -1811,7 +1810,7 @@ allow rules, <wrapper> * exclusions (codex-exec * where an execute slot delegate
1811
1810
  sandbox.network.allowedDomains and state dirs in sandbox.filesystem.allowWrite. Where the host
1812
1811
  honors the settings sandbox keys, an excluded wrapper runs outside the sandbox, every sandboxed
1813
1812
  command of the project can reach each host, and every sandboxed command can write each state dir;
1814
- plan/diff review modes and delegated execution keep their prompt.
1813
+ plan/diff review modes and delegated execution keep their prompt. A kit item the agent applies with no question, after its check.
1815
1814
  A user item stays the user's own step.
1816
1815
 
1817
1816
  Read-only: never writes, never commits, never runs a subscription CLI. Exit codes: 0 report
@@ -2,8 +2,8 @@
2
2
  // into a project's `scripts/`, as sha256 digests, and the ONE classifier a refresh asks before it
3
3
  // replaces a deployed script — the spec-layer ensure for its pairs and the upgrade's `scripts` ensure
4
4
  // for every other kit script: `current` (byte-equal to the bundled copy) · `prior` (a body a release
5
- // shipped, never edited since) · `custom` (anything else — replaced on the plain run by the scripts op,
6
- // and by the user's yes for the spec-layer pairs alone). The lens-region idiom (AD-041) over whole
5
+ // shipped, never edited since) · `custom` (anything else — replaced on the plain run, the spec-layer
6
+ // pairs included, with no question). The lens-region idiom (AD-041) over whole
7
7
  // script bodies.
8
8
  //
9
9
  // Append discipline: when a release changes one of PRIOR_FILES, append the OUTGOING body's row here
@@ -34,7 +34,7 @@ export const UPGRADE_RUNLIST = Object.freeze([
34
34
  entry(
35
35
  'configs',
36
36
  'node ${CLAUDE_SKILL_DIR}/tools/ensure-configs.mjs --reconcile --cwd <project>',
37
- "a replace line → ONE yes naming every spec-layer file its block names, each edit's kept-aside copy and that the bundled body replaces it, asked even on a non-zero exit; on the yes run the printed line, then STOP if that run fails or an op it does not re-run failed; on a no STOP on any failed op. The printed line: node ${CLAUDE_SKILL_DIR}/tools/ensure-configs.mjs --reconcile --replace-custom <digest> --cwd <project>",
37
+ null,
38
38
  [
39
39
  'seeded',
40
40
  'note-refreshed',
@@ -11,6 +11,7 @@ import { GATES_REL } from './gates-declaration.mjs';
11
11
  export const LANE_CHAT = 'chat';
12
12
  export const LANE_HARNESS = 'harness';
13
13
  export const LANE_USER = 'user';
14
+ export const LANE_KIT = 'kit';
14
15
 
15
16
  export const VARIANT_LANES = Object.freeze({
16
17
  'velocity-core': LANE_HARNESS,
@@ -46,7 +47,7 @@ export const VARIANT_LANES = Object.freeze({
46
47
  'mcp-channel.differing': LANE_HARNESS,
47
48
  agents: LANE_HARNESS,
48
49
  'executor-vehicle': LANE_HARNESS,
49
- 'executor-vehicle.differing': LANE_HARNESS,
50
+ 'executor-vehicle.differing': LANE_KIT,
50
51
  attribution: LANE_HARNESS,
51
52
  'footprint-global': LANE_HARNESS,
52
53
  'family-freshness': LANE_USER,
@@ -161,7 +162,8 @@ const FORMS = Object.freeze({
161
162
  ['--replace', '--cwd', '<root>'], ['--replace', '--apply', '--cwd', '<root>'], MCP_WRITES),
162
163
  agents: AGENT_FORM,
163
164
  'executor-vehicle': AGENT_FORM,
164
- 'executor-vehicle.differing': AGENT_FORM,
165
+ 'executor-vehicle.differing': createForm('cheap-agents.mjs',
166
+ ['--executor', '--cwd', '<root>'], ['--apply', '--executor', '--cwd', '<root>'], [join('.claude', 'agents', 'executor.md')]),
165
167
  attribution: createForm('attribution.mjs', ['--cwd', '<root>'], ['--apply', '--cwd', '<root>'], SETTINGS_WRITES),
166
168
  'footprint-global': createForm('hide-footprint.mjs',
167
169
  ['--remove-global', '--dry-run', '--dir', '<root>'], ['--remove-global', '--dir', '<root>'], [], false, null, true),
@@ -246,7 +248,7 @@ export const isRejudged = (variant) => {
246
248
  export const applySlot = (variant, facts) => {
247
249
  const lane = laneOf(variant);
248
250
  const form = FORMS[variant];
249
- if (lane === LANE_HARNESS) {
251
+ if (lane === LANE_HARNESS || lane === LANE_KIT) {
250
252
  const args = ['node', join(facts.toolsDir, 'apply-danger-check.mjs'), '--variant', variant, '--cwd', facts.root];
251
253
  const skillArgs = form === SKILL_FORM ? form.preview.map((arg) => resolveArgument(arg, facts)) : [];
252
254
  const check = formatCommand([...args, ...skillArgs]);
@@ -1,83 +0,0 @@
1
- // kept-aside.mjs — where an upgrade keeps a user's edit before the bundled body replaces it:
2
- // `.agent-workflow/kept-aside/<the first 16 hex of the replace set's digest>/<rel>` at the project
3
- // root. Every copy is written create-only from the bytes the survey read (never a re-read of the
4
- // source), read back and proven against the sha256 the digest bound, before anything is replaced.
5
- // `.agent-workflow/.gitignore` holding exactly `*` and a line feed is proven before the first copy,
6
- // so no stop leaves a copy git can see, with no edit of the user's own ignore files. The kit never
7
- // overwrites or deletes a kept-aside copy: a copy with other bytes is the user's to move.
8
- //
9
- // Dependency-free, Node >= 22. Every fs primitive is injectable (deps.*). No side effects on import.
10
-
11
- import { lstatSync, readFileSync } from 'node:fs';
12
- import { createHash } from 'node:crypto';
13
- import { join } from 'node:path';
14
- import { lstatNoFollow, writeProjectFileCreateOnly } from '../atomic-write.mjs';
15
- import { RESERVED_DIR } from '../repo-lex.mjs';
16
-
17
- export const KEPT_ASIDE_DIR = `${RESERVED_DIR}/kept-aside`;
18
- const IGNORE_REL = `${RESERVED_DIR}/.gitignore`;
19
- const IGNORE_BODY = '*\n';
20
-
21
- export const keptAsidePath = (digest, rel) => `${KEPT_ASIDE_DIR}/${digest.slice(0, 16)}/${rel}`;
22
-
23
- const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
24
- const causeOf = (err) => String((err && err.message) || err);
25
- const kindOf = (st) => (st.isSymbolicLink() ? 'a symlink' : st.isDirectory() ? 'a directory' : st.isFile() ? 'a regular file' : 'not a regular file');
26
- const NOTHING_DONE = 'nothing was kept aside or replaced';
27
-
28
- // The node-kind preflight, before anything is created: every directory from the project root down
29
- // to each copy's parent must be a real directory, and each copy path and the ignore file a regular
30
- // file when present. Returns the refusal line, or null.
31
- const chainRefusal = (cwd, rels, lstat) => {
32
- for (const rel of rels) {
33
- const parts = rel.split('/');
34
- for (let i = 1; i <= parts.length; i += 1) {
35
- const sub = parts.slice(0, i).join('/');
36
- const st = lstatNoFollow(join(cwd, sub), lstat);
37
- const leaf = i === parts.length;
38
- if (st && (leaf ? !st.isFile() : !st.isDirectory())) return `${sub}: exists but is ${kindOf(st)} — ${NOTHING_DONE}; resolve it by hand, then re-run`;
39
- }
40
- }
41
- return null;
42
- };
43
-
44
- const fail = (cause, line, kept) => {
45
- const written = kept.filter((copy) => copy.created).map((copy) => copy.path);
46
- const note = written.length > 0 ? [`the edits already kept aside stay where they are: ${written.join(', ')}`] : [];
47
- return { failed: true, cause, lines: [line, ...note], kept };
48
- };
49
-
50
- // keepAside({ cwd, digest, entries, deps }) → { failed: false, kept } with every edited entry's copy
51
- // proven, or { failed: true, cause, lines, kept } naming why and which copies were already written.
52
- // An absent entry gets no copy. `kept` lists { rel, path, created } per proven copy.
53
- export const keepAside = ({ cwd, digest, entries, deps = {} }) => {
54
- const lstat = deps.lstat ?? lstatSync;
55
- const read = deps.readFile ?? readFileSync;
56
- const edited = entries.filter((entry) => !entry.absent).sort((a, b) => (a.rel < b.rel ? -1 : 1));
57
- const kept = [];
58
- if (edited.length === 0) return { failed: false, kept };
59
- const refusal = chainRefusal(cwd, [IGNORE_REL, ...edited.map((entry) => keptAsidePath(digest, entry.rel))], lstat);
60
- if (refusal) return fail('wrong-node-kind', refusal, kept);
61
- let at = IGNORE_REL;
62
- try {
63
- if (lstatNoFollow(join(cwd, IGNORE_REL), lstat) === null) {
64
- writeProjectFileCreateOnly(cwd, IGNORE_REL, IGNORE_BODY, deps, { noun: 'the kept-aside ignore file' });
65
- }
66
- if (String(read(join(cwd, IGNORE_REL))) !== IGNORE_BODY) {
67
- return fail('write-refused', `${IGNORE_REL}: holds other bytes — it must hold exactly "*" and a line feed, so git sees no kept-aside copy; ${NOTHING_DONE}`, kept);
68
- }
69
- for (const entry of edited) {
70
- const path = keptAsidePath(digest, entry.rel);
71
- const abs = join(cwd, path);
72
- at = path;
73
- const created = lstatNoFollow(abs, lstat) === null && writeProjectFileCreateOnly(cwd, path, entry.bytes, deps, { noun: 'a kept-aside copy' }).created;
74
- if (sha256(read(abs)) !== entry.sha256) {
75
- return fail('race-unresolved', `${path}: a copy with other bytes is there — it is the user's to move or delete before the yes is asked again; nothing was replaced`, kept);
76
- }
77
- kept.push({ rel: entry.rel, path, created });
78
- }
79
- } catch (err) {
80
- return fail('write-refused', `${at}: ${causeOf(err)} — nothing was replaced`, kept);
81
- }
82
- return { failed: false, kept };
83
- };