@sabaiway/agent-workflow-kit 14.40.0 → 14.42.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,31 +1,36 @@
1
1
  #!/usr/bin/env node
2
- // git-hooks.mjs — the thin writer of the two git-hook items (`enforcement`, `commit-guard`): it copies
3
- // the bundled scripts create-only and spawns the project's own scripts/install-git-hooks.mjs, which
4
- // decides the hook at the write. The leaf decides nothing about the hook: the danger check binds the
5
- // copies and the installer bytes this dry run answers, never git's hooks dir. It is also the home of the
6
- // one pre-commit reader, which the commit-guard apply runs after the installer to verify the arm.
2
+ // git-hooks.mjs — the thin writer of the three git-hook items (`enforcement`, `commit-guard`,
3
+ // `hook-checks`): it copies the bundled scripts create-only, refreshes a known-prior installer, and
4
+ // spawns the project's own scripts/install-git-hooks.mjs, which decides the hook at the write. The leaf
5
+ // decides nothing about the hook: the danger check binds the copies and the installer bytes this dry run
6
+ // answers, never git's hooks dir. It is also the home of the one pre-commit reader, which the
7
+ // commit-guard and hook-checks applies run after the installer to verify the arm.
7
8
  import { lstatSync, readFileSync, readdirSync, rmdirSync, statSync, unlinkSync } from 'node:fs';
8
9
  import { createHash } from 'node:crypto';
9
10
  import { spawnSync } from 'node:child_process';
10
11
  import { dirname, join, resolve } from 'node:path';
11
12
  import { fileURLToPath } from 'node:url';
12
- import { writeProjectFileCreateOnly } from './atomic-write.mjs';
13
- import { NODE_EVIDENCE_SCRIPTS } from './node-evidence.mjs';
13
+ import { writeContainedFileAtomic, writeProjectFileCreateOnly } from './atomic-write.mjs';
14
+ import { BUNDLED_SCRIPT_NAMES, INSTALLER_REL, NODE_EVIDENCE_SCRIPTS, SCRIPTS_DIR } from './node-evidence.mjs';
14
15
  import { shellQuoteArg } from './repo-lex.mjs';
15
16
  import { GIT_MAX_BUFFER } from './git-env.mjs';
16
17
  import { isDirectRun } from './direct-run.mjs';
18
+ import { classifyDeployedScript } from './script-priors.mjs';
19
+ import { checkRules } from './project-rules/index.mjs';
20
+ import { readLayoutSetup } from './source-size-core.mjs';
17
21
 
18
22
  const TOOLS = dirname(fileURLToPath(import.meta.url));
19
- export const SCRIPTS_REL = 'scripts';
20
- export const INSTALLER_REL = 'scripts/install-git-hooks.mjs';
23
+ export const SCRIPTS_REL = SCRIPTS_DIR;
24
+ export { BUNDLED_SCRIPT_NAMES, INSTALLER_REL };
21
25
  const bundleDir = (toolsDir) => join(toolsDir, '..', 'references', 'scripts');
22
- export const BUNDLED_SCRIPT_NAMES = Object.freeze(readdirSync(bundleDir(TOOLS)).filter((name) => name.endsWith('.mjs')).sort());
26
+ const INSTALLER_NAME = 'install-git-hooks.mjs';
23
27
 
24
28
  const EXIT_OK = 0;
25
29
  const EXIT_INCOMPLETE = 1;
26
30
  const EXIT_USAGE = 2;
27
31
  const EXIT_REFUSED = 3;
28
- const USAGE = 'usage: git-hooks (--enforcement | --commit-guard) [--cwd <root>] [--apply]';
32
+ const VARIANTS = ['enforcement', 'commit-guard', 'hook-checks'];
33
+ const USAGE = 'usage: git-hooks (--enforcement | --commit-guard | --hook-checks) [--cwd <root>] [--apply]';
29
34
  const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
30
35
  const usageError = (message) => Object.assign(new Error(message), { exitCode: EXIT_USAGE });
31
36
  const refusal = (message) => Object.assign(new Error(message), { exitCode: EXIT_REFUSED });
@@ -53,24 +58,93 @@ const escapeRe = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
53
58
  // Armed means the exact line the installer writes on the kit's own guard path; a commented or lookalike line is not.
54
59
  export const canonicalGuardLineRe = (toolsDir = TOOLS) => new RegExp(`^node "${escapeRe(join(toolsDir, 'commit-guard.mjs'))}" --check$`, 'm');
55
60
 
56
- // The one reader of git's pre-commit: whose hook it is, and whether the canonical guard line arms it.
61
+ // The one safe shell representation of an armed path, the installer's rule: on win32 its separators
62
+ // made `/`; null when a byte would not name the file inside the hook's double quotes.
63
+ export const safeHookPath = (path, platform = process.platform) => {
64
+ const shown = platform === 'win32' ? path.replaceAll('\\', '/') : path;
65
+ return /["$`\\\r\n]/.test(shown) ? null : shown;
66
+ };
67
+
68
+ // The two role-tagged lines, in hook order: the flag that arms each and the kit tool it runs.
69
+ const ROLES = Object.freeze([
70
+ { key: 'rules', role: 'rules-check', flag: '--rules-check', tool: (toolsDir) => join(toolsDir, 'project-rules', 'rules-cli.mjs') },
71
+ { key: 'layout', role: 'layout-check', flag: '--layout-check', tool: (toolsDir) => join(toolsDir, 'source-size-check.mjs') },
72
+ ]);
73
+ const roleLineRe = ({ role, tool }, toolsDir, platform) => {
74
+ const path = safeHookPath(tool(toolsDir), platform);
75
+ return path === null ? /(?!)/ : new RegExp(`^node "${escapeRe(path)}" --check # ${role}$`, 'm');
76
+ };
77
+ export const canonicalRulesLineRe = (toolsDir = TOOLS, platform = process.platform) => roleLineRe(ROLES[0], toolsDir, platform);
78
+ export const canonicalLayoutLineRe = (toolsDir = TOOLS, platform = process.platform) => roleLineRe(ROLES[1], toolsDir, platform);
79
+ const CANONICAL = { rules: canonicalRulesLineRe, layout: canonicalLayoutLineRe };
80
+
81
+ // Each role's arm, and whether an uncommented line ending in its role comment runs another path.
82
+ const roleStates = (hook, toolsDir, platform) => Object.fromEntries(ROLES.flatMap(({ key, role }) => {
83
+ const canonical = CANONICAL[key](toolsDir, platform);
84
+ const lines = hook === null ? [] : hook.split('\n').filter((line) => !line.trimStart().startsWith('#') && line.endsWith(`# ${role}`));
85
+ return [[`${key}Armed`, hook !== null && canonical.test(hook)], [`${key}Foreign`, lines.some((line) => !canonical.test(line))]];
86
+ }));
87
+
88
+ // The one reader of git's pre-commit: whose hook it is, and which canonical lines arm it.
57
89
  export const readPreCommitState = (root, deps = {}) => {
90
+ const unarmed = (fields) => ({ ...fields, armed: false, ...roleStates(null) });
58
91
  const hooksPath = (deps.gitHooksPath ?? resolveGitHooksPath)(root, deps.env);
59
- if (hooksPath === null) return { state: 'no-hooks-dir', armed: false };
92
+ if (hooksPath === null) return unarmed({ state: 'no-hooks-dir' });
60
93
  const path = join(hooksPath, 'pre-commit');
61
94
  let hook;
62
95
  try {
63
96
  (deps.lstat ?? lstatSync)(path);
64
97
  hook = String((deps.readFile ?? readFileSync)(path, 'utf8'));
65
98
  } catch (error) {
66
- if (error?.code === 'ENOENT') return { state: 'absent', armed: false };
67
- return { state: 'unreadable', code: error?.code ?? String(error?.message ?? error), path, armed: false };
99
+ if (error?.code === 'ENOENT') return unarmed({ state: 'absent' });
100
+ return unarmed({ state: 'unreadable', code: error?.code ?? String(error?.message ?? error), path });
68
101
  }
69
- return { state: INSTALLER_MARKER_RE.test(hook) ? 'managed' : 'unmanaged', armed: canonicalGuardLineRe(deps.toolsDir).test(hook) };
102
+ return { state: INSTALLER_MARKER_RE.test(hook) ? 'managed' : 'unmanaged', armed: canonicalGuardLineRe(deps.toolsDir).test(hook),
103
+ ...roleStates(hook, deps.toolsDir ?? TOOLS, deps.platform) };
104
+ };
105
+
106
+ // The two read-only answers the hook-checks dry run and the advisor's probe ask, on the tree on disk.
107
+ export const hookCheckAnswers = (root, deps = {}) => {
108
+ const verdicts = (deps.checkRules ?? checkRules)(root, deps);
109
+ const setup = (deps.readLayoutSetup ?? readLayoutSetup)(root, deps);
110
+ return {
111
+ rules: { armable: verdicts.every(({ verdict }) => verdict === 'current'),
112
+ why: verdicts.filter(({ verdict }) => verdict !== 'current').map(({ theme, verdict }) => `${theme}: ${verdict}`).join(', ') },
113
+ layout: { armable: setup.answer === 'armable', why: `the layout setup answers ${setup.answer}${setup.reason ? ` (${setup.reason})` : ''}`, setup },
114
+ };
115
+ };
116
+
117
+ // The roles a hook-checks apply passes: each armable and unarmed, or standing on another path.
118
+ export const plannedRoles = (answers, hook) => ROLES.filter(({ key }) =>
119
+ (answers[key].armable && !hook[`${key}Armed`]) || hook[`${key}Foreign`]);
120
+
121
+ // The kit's tools path in the one safe representation, or the refusal naming it.
122
+ export const unsafeToolsPath = (toolsDir, platform) => (ROLES.some(({ tool }) => safeHookPath(tool(toolsDir), platform) === null)
123
+ ? `the kit's tools path ${toolsDir} carries ", $, a backtick, a backslash, CR or LF — a hook line would not run the file it names` : null);
124
+
125
+ // hook-checks: the lines it arms, from the two answers and the hook, and a refresh of a known-prior installer.
126
+ const planHookChecks = ({ root, toolsDir, installer, scriptsNode, kinds, readFile, deps }) => {
127
+ if (!isPlainDir(scriptsNode) || kinds.get(INSTALLER_NAME) !== 'file') throw refusal(`${installer} is absent — nothing here places the hook installer`);
128
+ const unsafe = unsafeToolsPath(toolsDir, deps.platform);
129
+ if (unsafe !== null) throw refusal(unsafe);
130
+ const hook = readPreCommitState(root, { toolsDir, platform: deps.platform, gitHooksPath: deps.gitHooksPath });
131
+ if (hook.state === 'unreadable') throw refusal(`${hook.path} is unreadable (${hook.code}) — the pre-commit hook cannot be judged`);
132
+ if (hook.state === 'no-hooks-dir') throw refusal('nothing to plan — git reports no hooks dir here (not a git checkout), so there is no hook to arm');
133
+ const answers = hookCheckAnswers(root, deps);
134
+ const roles = plannedRoles(answers, hook);
135
+ if (roles.length === 0) {
136
+ throw refusal(`nothing to plan — ${ROLES.map(({ key, role }) => `the ${role} line: ${hook[`${key}Armed`] ? 'armed' : `not armable (${answers[key].why})`}`).join('; ')}`);
137
+ }
138
+ const deployed = readFile(installer);
139
+ const bundled = readFile(join(bundleDir(toolsDir), INSTALLER_NAME));
140
+ const refresh = classifyDeployedScript(deployed, INSTALLER_NAME, bundled) === 'prior' ? { path: installer, bytes: bundled, replaces: deployed } : null;
141
+ const flags = roles.flatMap(({ flag, tool }) => [flag, tool(toolsDir)]);
142
+ return { root, variant: 'hook-checks', scriptsCreated: false, copies: [], refresh, roles: roles.map(({ key }) => key),
143
+ runs: { argv: ['node', installer, ...flags], shown: ['node', INSTALLER_REL, ...flags], bytes: refresh ? bundled : deployed } };
70
144
  };
71
145
 
72
146
  // The dry run: what the apply copies and the installer it runs, with the bytes of each.
73
- export const planGitHooks = ({ root, variant, toolsDir = TOOLS, lstat = lstatSync, readFile = readFileSync }) => {
147
+ export const planGitHooks = ({ root, variant, toolsDir = TOOLS, lstat = lstatSync, readFile = readFileSync, ...deps }) => {
74
148
  const scripts = join(root, SCRIPTS_REL);
75
149
  const scriptsNode = nodeAt(scripts, lstat);
76
150
  if (scriptsNode !== null && !isPlainDir(scriptsNode)) throw refusal(`${scripts} is not a plain directory`);
@@ -83,6 +157,7 @@ export const planGitHooks = ({ root, variant, toolsDir = TOOLS, lstat = lstatSyn
83
157
  kinds.set(name, node === null ? 'absent' : 'file');
84
158
  }
85
159
  const installer = join(root, INSTALLER_REL);
160
+ if (variant === 'hook-checks') return planHookChecks({ root, toolsDir, installer, scriptsNode, kinds, readFile, deps });
86
161
  const deployed = NODE_EVIDENCE_SCRIPTS.some((name) => kinds.get(name) === 'file');
87
162
  const copies = variant === 'enforcement' && !deployed ? BUNDLED_SCRIPT_NAMES.map((name) => {
88
163
  if (kinds.get(name) === 'file') return { name, path: join(scripts, name), action: 'kept' };
@@ -102,6 +177,7 @@ export const planGitHooks = ({ root, variant, toolsDir = TOOLS, lstat = lstatSyn
102
177
 
103
178
  export const formatPlan = (plan) => [
104
179
  ...plan.copies.map(({ name, action, bytes }) => `copy: ${SCRIPTS_REL}/${name} ${action}${action === 'created' ? ` sha256:${sha(bytes)}` : ''}`),
180
+ ...(plan.refresh ? [`refresh: ${INSTALLER_REL} sha256:${sha(plan.refresh.bytes)} — replaces sha256:${sha(plan.refresh.replaces)}`] : []),
105
181
  `runs: ${plan.runs.shown.map(shellQuoteArg).join(' ')} sha256:${sha(plan.runs.bytes)}`,
106
182
  ];
107
183
 
@@ -143,10 +219,60 @@ const rollBack = (plan, created, io) => {
143
219
  return left;
144
220
  };
145
221
 
222
+ // The hook's bytes, null when absent; undefined when it cannot be read, which never compares equal.
223
+ const hookBytes = (path, readFile) => {
224
+ try {
225
+ return readFile(path);
226
+ } catch (error) {
227
+ return error?.code === 'ENOENT' ? null : undefined;
228
+ }
229
+ };
230
+ const sameHook = (left, right) => left !== undefined && right !== undefined && (left === null ? right === null : right !== null && left.equals(right));
231
+
232
+ // hook-checks at the write: the refresh, the spawn, the re-read of every passed line; on a failed outcome
233
+ // the prior installer comes back exactly when the hook still holds the bytes it held before the spawn.
234
+ const applyHookChecks = (plan, resolved) => {
235
+ const hooksDir = resolveGitHooksPath(plan.root, resolved.env);
236
+ const preCommit = hooksDir === null ? null : join(hooksDir, 'pre-commit');
237
+ const before = preCommit === null ? null : hookBytes(preCommit, resolved.readFile);
238
+ const replace = (bytes) => resolved.replaceFile(plan.root, plan.runs.argv[1], bytes, {}, { label: INSTALLER_REL });
239
+ if (plan.refresh) {
240
+ try {
241
+ replace(plan.refresh.bytes);
242
+ } catch (error) {
243
+ resolved.error(error?.message ?? String(error));
244
+ return EXIT_INCOMPLETE;
245
+ }
246
+ }
247
+ const child = resolved.spawn(plan.runs.argv, { cwd: plan.root, env: resolved.env, stdio: 'inherit' });
248
+ const hook = readPreCommitState(plan.root, { env: resolved.env, toolsDir: resolved.toolsDir, platform: resolved.platform, gitHooksPath: () => hooksDir });
249
+ const failure = child.status !== 0 ? `installer exited ${child.status ?? child.signal ?? child.error?.code}`
250
+ : hook.state === 'no-hooks-dir' ? null
251
+ : hook.state === 'unreadable' ? `${preCommit} is unreadable (${hook.code}) after the installer exited 0`
252
+ : ROLES.filter(({ key }) => plan.roles.includes(key)).map(({ key, role, flag }) => (!hook[`${key}Armed`]
253
+ ? `${preCommit} carries no ${role} line after the installer exited 0 — an installer older than the arm ignores ${flag}; refreshing ${INSTALLER_REL} from the kit's references/scripts/ copy is your own step`
254
+ : hook[`${key}Foreign`] ? `${preCommit} still carries a ${role} line on a path other than this kit's after the installer exited 0` : null)).find(Boolean) ?? null;
255
+ if (failure === null) return EXIT_OK;
256
+ resolved.error(failure);
257
+ if (!plan.refresh) return EXIT_INCOMPLETE;
258
+ if (!sameHook(before, preCommit === null ? null : hookBytes(preCommit, resolved.readFile))) {
259
+ resolved.error(`${INSTALLER_REL} keeps the refreshed bytes: ${preCommit} no longer holds what it held before the installer ran, or cannot be read, and the prior body would drop the new lines at its next run`);
260
+ return EXIT_INCOMPLETE;
261
+ }
262
+ try {
263
+ replace(plan.refresh.replaces);
264
+ } catch (error) {
265
+ resolved.error(`not restored: ${INSTALLER_REL} (${error?.message ?? error})`);
266
+ }
267
+ return EXIT_INCOMPLETE;
268
+ };
269
+
146
270
  export const applyGitHooks = (plan, io = {}) => {
147
271
  const resolved = { lstat: lstatSync, unlink: unlinkSync, rmdir: rmdirSync, readdir: readdirSync, env: process.env,
148
- log: console.log, error: console.error, writeFile: writeProjectFileCreateOnly, toolsDir: TOOLS,
272
+ log: console.log, error: console.error, writeFile: writeProjectFileCreateOnly, toolsDir: TOOLS, readFile: readFileSync,
273
+ replaceFile: writeContainedFileAtomic, platform: process.platform,
149
274
  spawn: (argv, options) => spawnSync(argv[0], argv.slice(1), options), ...io };
275
+ if (plan.variant === 'hook-checks') return applyHookChecks(plan, resolved);
150
276
  const created = [];
151
277
  const leftovers = [];
152
278
  const fail = (lines) => {
@@ -192,7 +318,7 @@ export const parseArgs = (argv) => {
192
318
  for (let index = 0; index < argv.length; index += 1) {
193
319
  const flag = argv[index];
194
320
  if (flag === '--apply') args.apply = true;
195
- else if (flag === '--enforcement' || flag === '--commit-guard') args.variants.push(flag.slice(2));
321
+ else if (flag.startsWith('--') && VARIANTS.includes(flag.slice(2))) args.variants.push(flag.slice(2));
196
322
  else if (flag === '--cwd') {
197
323
  const value = argv[index + 1];
198
324
  if (value === undefined || value.startsWith('-')) throw usageError('--cwd takes a value');
@@ -200,7 +326,7 @@ export const parseArgs = (argv) => {
200
326
  index += 1;
201
327
  } else throw usageError(`unknown argument: ${flag}`);
202
328
  }
203
- if (args.variants.length !== 1) throw usageError('pass exactly one of --enforcement and --commit-guard');
329
+ if (args.variants.length !== 1) throw usageError('pass exactly one of --enforcement, --commit-guard and --hook-checks');
204
330
  return { help: false, apply: args.apply, cwd: args.cwd, variant: args.variants[0] };
205
331
  };
206
332
 
@@ -1,8 +1,9 @@
1
1
  // node-evidence.mjs — does Node PROVABLY run in this project tree? Contract: docs/ai/specs/kit/node-evidence.md.
2
2
  // Pure over an injectable lstat; no writes, no side effects on import. Dependency-free, Node >= 22.
3
3
 
4
- import { lstatSync } from 'node:fs';
5
- import { join } from 'node:path';
4
+ import { lstatSync, readdirSync } from 'node:fs';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
6
7
 
7
8
  export const NODE_EVIDENCE = Object.freeze({
8
9
  PACKAGE_JSON: 'package-json',
@@ -13,6 +14,13 @@ export const NODE_EVIDENCE = Object.freeze({
13
14
 
14
15
  export const PACKAGE_JSON_REL = 'package.json';
15
16
  export const SCRIPTS_DIR = 'scripts';
17
+ export const INSTALLER_REL = `${SCRIPTS_DIR}/install-git-hooks.mjs`;
18
+
19
+ // Every *.mjs of the kit's references/scripts/, sorted, the tests and the shim included: what the
20
+ // enforcement copy places. Read from this kit copy at import, so a module the git-hooks leaf's own
21
+ // imports reach names the bundle without importing that leaf back.
22
+ export const BUNDLED_SCRIPT_NAMES = Object.freeze(readdirSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'references', 'scripts'))
23
+ .filter((name) => name.endsWith('.mjs')).sort());
16
24
 
17
25
  // The runnable scripts the bootstrap copies from references/scripts/ — pinned against the bundle by the suite.
18
26
  export const NODE_EVIDENCE_SCRIPTS = Object.freeze([
@@ -71,11 +71,11 @@ import { takeCensus, censusFact, CENSUS_VERDICT } from './tracked-tree-census.mj
71
71
  // fill's own WRITER is never called from here — the advisor renders its consent-gated command, it
72
72
  // does not run it.
73
73
  import { buildOffer } from './gates-init.mjs';
74
- import { CHECKER_CLAIM, INITIAL_ADOPTION_REASON, SOURCE_SIZE_GATE_ID, classifySourceSizeGate, loadSourceSizeConfig } from './source-size-core.mjs';
74
+ import { CHECKER_CLAIM, INITIAL_ADOPTION_REASON, SOURCE_SIZE_GATE_ID, classifySourceSizeGate, loadSourceSizeConfig, readLayoutSetup } from './source-size-core.mjs';
75
75
  // The declared-path resolution + segment containment this item's convergence lane shares with the
76
76
  // autonomy render's allowWrite degrade — ONE leaf, so the two answers cannot drift.
77
77
  import { resolveDeclaredDir, dirCovers, isResolvableDeclaredEntry } from './declared-paths.mjs';
78
- import { readPreCommitState } from './git-hooks.mjs';
78
+ import { hookCheckAnswers, plannedRoles, readPreCommitState, unsafeToolsPath } from './git-hooks.mjs';
79
79
  export { resolveGitHooksPath, readPreCommitState, canonicalGuardLineRe, INSTALLER_MARKER_RE } from './git-hooks.mjs';
80
80
  import { loadConfig } from './orchestration-config.mjs';
81
81
  import { homeRelative } from './bridge-state-dirs.mjs';
@@ -130,6 +130,13 @@ const ENFORCEMENT_UNMANAGED_HOOK = 'an UNMANAGED pre-commit hook exists \u2014 t
130
130
  const COMMIT_GUARD_INSTALLER_VIA_ITEM = 'the hook installer (scripts/install-git-hooks.mjs) is not deployed \u2014 apply the enforcement item first, then re-run';
131
131
  const COMMIT_GUARD_INSTALLER_OWN_STEP = 'the hook installer (scripts/install-git-hooks.mjs) is not deployed here \u2014 deploying the enforcement scripts into this project is your own step, then re-run';
132
132
  const COMMIT_GUARD_UNMANAGED_HOOK = 'an UNMANAGED pre-commit hook exists \u2014 the installer never overwrites it; adding the guard line to it is your own step';
133
+ const HOOK_CHECKS_UNMANAGED_HOOK = 'an UNMANAGED pre-commit hook exists \u2014 the installer never overwrites it; adding the lines this item would arm to it is your own step';
134
+ const HOOK_CHECKS_WAIT = 'the layout line follows the source-size.layout record \u2014 apply that item first; this item\'s check line then arms the layout line too';
135
+ const LAYOUT_RECORD_RECIPE = 'the hook is per clone and the config per branch: a branch or linked worktree with no size config is judged under the kit\'s values and stops on its piles until it takes the record (a hidden deployment\'s linked worktree carries none); one with an older config without layout is not judged on layout; one whose config is schema 1 or unminted stops every commit on that config\'s own stop until it takes the current config';
136
+ const LAYOUT_HELD = {
137
+ stops: () => 'the source-size check stops on this tree, so a layout record or layout line not yet in place waits \u2014 record that growth first with the reasoned --write-baseline its stop names, then re-run',
138
+ 'store-root': ({ root }) => `the source-size config declares the root "${root}" at or inside the spec store docs/ai/specs \u2014 the layout record starts once that root is declared outside it`,
139
+ };
133
140
  // ── the section contract tokens (doc-parity-bound in upgrade.md + the mode doc) ────────────────
134
141
  export const RECOMMENDATIONS_SECTION_HEADER = '## Recommendations (agent-workflow)';
135
142
  export const RECOMMENDATIONS_EMPTY_LINE = 'no recommendations — flow optimal.';
@@ -185,12 +192,14 @@ export const SEVERITIES = Object.freeze({
185
192
  'source-size.id-squatter': SEVERITY_ATTENTION,
186
193
  // A minted schema-1 config is a record the check stops on until the writer moves it.
187
194
  'source-size.schema-1': SEVERITY_ATTENTION,
195
+ 'source-size.layout': SEVERITY_OPTIONAL,
188
196
  'gate-hook': SEVERITY_OPTIONAL,
189
197
  // A placed hook that predates the marker key goes DARK on a marker-carrying declaration (unknown
190
198
  // key → auto-approval off), so a CONFIGURED capability silently stops working: attention, not an
191
199
  // offer to enable something.
192
200
  'gate-hook.marker-stale': SEVERITY_ATTENTION,
193
201
  'commit-guard': SEVERITY_OPTIONAL,
202
+ 'hook-checks': SEVERITY_OPTIONAL,
194
203
  enforcement: SEVERITY_OPTIONAL,
195
204
  'read-lane': SEVERITY_OPTIONAL,
196
205
  'read-lane.stale': SEVERITY_ATTENTION,
@@ -282,11 +291,13 @@ export const WHATS = Object.freeze({
282
291
  'source-size': 'no source-size gate — module size drifts unmeasured, and an over-cap file is invisible instead of recorded debt',
283
292
  'source-size.unminted': 'the source-size gate is declared over an unminted record ({state}) — the check refuses it, or if absent judges layout alone, no line',
284
293
  'source-size.schema-1': 'the source-size config is schema 1, which the check stops on — the writer moves it to schema 2 in one write',
294
+ 'source-size.layout': 'the layout record is not started — starting it records any directory already beyond the layout limits, so the commit hook can judge layout',
285
295
  '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",
286
296
  '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',
287
297
  'gate-hook': '{n} declared gate(s) prompt per run — the gate-approval hook is not wired',
288
298
  'gate-hook.marker-stale': 'the declaration carries the lcovProducer key but the placed hook predates it — the hook goes dark and every gate prompts',
289
299
  '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',
300
+ 'hook-checks': 'the pre-commit hook lacks this kit\'s {checks} — the kit arms each line, refreshing a known-prior installer first',
290
301
  enforcement: ENFORCEMENT_WHAT,
291
302
  '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',
292
303
  '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',
@@ -359,6 +370,7 @@ export const BENEFITS = Object.freeze({
359
370
  'source-size': 'maintainability — a module you can hold whole stays reviewable, and size drift becomes recorded, reasoned debt',
360
371
  'gate-hook': 'velocity — your own declared gate commands auto-approve byte-exactly (opt-in PreToolUse hook)',
361
372
  'commit-guard': 'integrity — commits require the ONE green --final receipt at the exact staged fingerprint (consented pre-commit arm)',
373
+ 'hook-checks': 'enforcement — every commit runs the checks armed here, so their findings stop the commit',
362
374
  enforcement: 'enforcement — bundled checks and the pre-commit hook keep caps, archives, and the generated index current',
363
375
  'read-lane': 'velocity — pipes/chains of your seeded read-only commands auto-approve instead of prompting (opt-in, conservatively classified)',
364
376
  'state-block': 'no silent stalls — a turn ending on «you are not needed», or on work it never started, warns at once instead of waiting to be spotted',
@@ -379,6 +391,7 @@ export const BENEFITS = Object.freeze({
379
391
  // The one arm whose gain differs from its base item's (BENEFITS stays keyed by item key).
380
392
  export const VARIANT_BENEFITS = Object.freeze({
381
393
  'executor-vehicle.differing': 'carrier fidelity — the placed executor runs the model and effort docs/ai/vehicles.json names, not a hand edit',
394
+ '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',
382
395
  });
383
396
 
384
397
  // ── the CLOSED opt-in capability registry (OPT-IN-SHIPS-INVISIBLE) ──────────────────────────────
@@ -416,6 +429,7 @@ export const OPT_IN_CAPABILITIES = Object.freeze([
416
429
  { id: 'read-lane', mode: 'hook', advisorKey: 'read-lane' },
417
430
  { id: 'commit-guard', mode: 'commit-guard', advisorKey: 'commit-guard' },
418
431
  { id: 'enforcement', mode: 'bootstrap', advisorKey: 'enforcement' },
432
+ { id: 'hook-checks', mode: 'bootstrap', advisorKey: 'hook-checks' },
419
433
  { id: 'attribution', mode: 'bootstrap', advisorKey: 'attribution' },
420
434
  { id: 'footprint-global', mode: 'bootstrap', advisorKey: 'footprint-global' },
421
435
  { id: 'state-block', mode: 'state-block-guard', advisorKey: 'state-block' },
@@ -855,13 +869,30 @@ const schema1Minted = (root, deps) => {
855
869
  try { const { state, config } = loadSourceSizeConfig(root, deps); return state === 'minted' && config.schema === 1; } catch { return false; }
856
870
  };
857
871
 
858
- const probeSourceSize = ({ root, deps, add, skip }) => {
872
+ // The layout setup's answer for the layout arm; its throw is a stated skip, and the other arms still speak.
873
+ const layoutSetupOrSkip = (root, deps, skip) => {
874
+ try {
875
+ return readLayoutSetup(root, deps);
876
+ } catch (err) {
877
+ skip('source-size.layout', err);
878
+ return null;
879
+ }
880
+ };
881
+
882
+ const probeSourceSize = ({ root, deps, add, skip, shared }) => {
859
883
  try {
860
884
  const tool = toolPath('source-size-check.mjs');
861
885
  if (schema1Minted(root, deps)) {
862
886
  add('source-size', fillTemplate(WHATS['source-size.schema-1'], {}), `node ${q(tool)} --write-baseline --cwd ${q(root)}`, 'source-size.schema-1');
863
887
  return;
864
888
  }
889
+ // The layout arm, additive: the record renders as its own item ahead of the other arms; a held answer
890
+ // no other arm speaks for is a stated skip, so the item's absence is explained in the run it goes.
891
+ const setup = layoutSetupOrSkip(root, deps, skip);
892
+ if (setup?.answer === 'record') {
893
+ shared.layoutRecord = add('source-size', fillTemplate(WHATS['source-size.layout'], {}),
894
+ `node ${q(tool)} ${setup.args.map(q).join(' ')} --cwd ${q(root)}`, 'source-size.layout', LAYOUT_RECORD_RECIPE);
895
+ } else if (setup?.answer === 'held' && Object.hasOwn(LAYOUT_HELD, setup.reason)) skip('source-size.layout', new Error(LAYOUT_HELD[setup.reason](setup)));
865
896
  const declaration = loadDeclaration(root, deps);
866
897
  const gates = declaration.outcome === 'loaded' ? declaration.gates : [];
867
898
  // The reason string is PINNED, not composed: it is copied unchanged into every entry the first
@@ -965,6 +996,30 @@ const probeCommitGuard = ({ root, deps, add, skip }) => {
965
996
  }
966
997
  };
967
998
 
999
+ // The hook-checks offer: the commit-guard probe's shape over the two answers the leaf asks, on disk.
1000
+ const HOOK_CHECK_NAMES = { rules: 'project-rules check', layout: 'layout check', both: 'project-rules and layout checks' };
1001
+ const probeHookChecks = ({ root, deps, add, skip, shared }) => {
1002
+ try {
1003
+ if (!(deps.exists ?? existsSync)(join(root, 'docs', 'ai'))) return;
1004
+ const unsafe = unsafeToolsPath(HERE);
1005
+ if (unsafe !== null) throw new Error(unsafe);
1006
+ const hook = readHookState(root, deps);
1007
+ if (hook.state === 'no-hooks-dir') return;
1008
+ const roles = plannedRoles(hookCheckAnswers(root, deps), hook).map(({ key }) => key);
1009
+ const waits = shared.layoutRecord === true && !hook.layoutArmed && !roles.includes('layout');
1010
+ if (roles.length === 0 && !waits) return;
1011
+ if (hook.state === 'unmanaged') throw new Error(HOOK_CHECKS_UNMANAGED_HOOK);
1012
+ if (!(deps.exists ?? existsSync)(join(root, 'scripts', 'install-git-hooks.mjs'))) {
1013
+ throw new Error(enforcementAdmits(root, deps) ? COMMIT_GUARD_INSTALLER_VIA_ITEM : COMMIT_GUARD_INSTALLER_OWN_STEP);
1014
+ }
1015
+ const keys = [...roles, ...(waits ? ['layout'] : [])];
1016
+ const checks = HOOK_CHECK_NAMES[keys.length === 2 ? 'both' : keys[0]];
1017
+ add('hook-checks', fillTemplate(WHATS['hook-checks'], { checks }), formsApply('hook-checks', root), 'hook-checks', waits ? HOOK_CHECKS_WAIT : null);
1018
+ } catch (err) {
1019
+ skip('hook-checks', err);
1020
+ }
1021
+ };
1022
+
968
1023
  const readEnforcementNode = (path, lstat) => {
969
1024
  try {
970
1025
  return lstat(path);
@@ -1357,7 +1412,7 @@ const readReadLaneToggle = (root, deps) => {
1357
1412
  // D3: the risk-marked keys — every key here has a per-item posture note in the mode doc, surfaced
1358
1413
  // at the consent moment; the static contract test asserts EXACT bidirectional coverage
1359
1414
  // (risk-marked keys == mode-doc note keys — a dropped note goes red, not silent).
1360
- export const RISK_NOTED_KEYS = Object.freeze(['bridge-tier', 'read-lane', 'worktrees-dir', 'adr-store-migration', 'gates-inert', 'source-size', 'gate-hook', 'mcp-channel', 'spec-adoption', 'enforcement', 'profile-gap', 'jev-connect', 'jev-skill', 'attribution', 'footprint-global']);
1415
+ export const RISK_NOTED_KEYS = Object.freeze(['bridge-tier', 'read-lane', 'worktrees-dir', 'adr-store-migration', 'gates-inert', 'source-size', 'gate-hook', 'mcp-channel', 'spec-adoption', 'enforcement', 'hook-checks', 'profile-gap', 'jev-connect', 'jev-skill', 'attribution', 'footprint-global']);
1361
1416
 
1362
1417
  // The feature-spec layer's adoption state (contract: kit/spec-adoption). The canon lets a plan cite
1363
1418
  // zero governing specs while a project adopts the layer, and nothing ever said whether adoption had
@@ -1657,6 +1712,7 @@ const PROBES = Object.freeze([
1657
1712
  probeGatesInert,
1658
1713
  probeSourceSize,
1659
1714
  probeCommitGuard,
1715
+ probeHookChecks,
1660
1716
  probeEnforcement,
1661
1717
  probeReadLane,
1662
1718
  probeStateBlockHook,
@@ -1,8 +1,9 @@
1
1
  // script-priors.mjs — the APPEND-ONLY catalog of every enforcement-script body this family has shipped
2
- // into a project's `scripts/`, as sha256 digests, and the ONE classifier the spec-layer ensure asks
3
- // before it refreshes a deployed script: `current` (byte-equal to the bundled copy) · `prior` (a body
4
- // a release shipped, never edited since) · `custom` (anything else — preserved verbatim, replaced only by
5
- // the replace run the user's yes starts). The lens-region idiom (AD-041) over whole script bodies.
2
+ // into a project's `scripts/`, as sha256 digests, and the ONE classifier a refresh asks before it
3
+ // replaces a deployed script — the spec-layer ensure for its pairs, the `hook-checks` writer for the
4
+ // hook installer alone and the upgrade's `scripts` ensure for the installer set: `current` (byte-equal to the bundled copy) · `prior` (a body a release shipped, never
5
+ // edited since) · `custom` (anything else — preserved verbatim, replaced only by the replace run the
6
+ // user's yes starts). The lens-region idiom (AD-041) over whole script bodies.
6
7
  //
7
8
  // Append discipline: when a release changes one of PRIOR_FILES, append the OUTGOING body's row here
8
9
  // in the same release and copy its bytes to test/fixtures/script-priors/<firstShipped>/<file>.txt —
@@ -13,13 +14,19 @@
13
14
 
14
15
  import { createHash } from 'node:crypto';
15
16
 
16
- // The deployed scripts the spec-layer ensure may REFRESH — the FULL refreshable catalog: the checker
17
- // pair that imports the reader, and (since 2a) the reader pair itself. Every other deployed script is
18
- // outside the refresh lane by design.
17
+ // The deployed scripts a refresh may REPLACE — the FULL refreshable catalog: the checker pair that
18
+ // imports the reader and (since 2a) the reader pair itself, which the spec-layer ensure refreshes, and
19
+ // the installer set: the `hook-checks` writer refreshes the installer alone, the upgrade's `scripts`
20
+ // ensure the installer with its two suites. Every other deployed script is outside the refresh lane by design.
19
21
  export const PRIOR_FILES = Object.freeze([
20
- 'check-docs-size.mjs', 'check-docs-size.test.mjs', 'spec-schema.mjs', 'spec-schema.test.mjs',
22
+ 'check-docs-size.mjs', 'check-docs-size.test.mjs', 'spec-schema.mjs', 'spec-schema.test.mjs', 'install-git-hooks.mjs',
23
+ 'install-git-hooks.test.mjs', 'install-git-hooks-repo-exec.test.mjs',
21
24
  ]);
22
25
 
26
+ // The hook installer and the two suites that test it beside it — refreshed as ONE set, installer first,
27
+ // so a stop partway never leaves a bundled suite beside a prior installer.
28
+ export const INSTALLER_SET = Object.freeze(['install-git-hooks.mjs', 'install-git-hooks.test.mjs', 'install-git-hooks-repo-exec.test.mjs']);
29
+
23
30
  const prior = (file, firstShipped, lastShipped, digest) => Object.freeze({ file, firstShipped, lastShipped, digest });
24
31
 
25
32
  // One row per DISTINCT shipped body (memory package versions; the body is the memory canon the kit
@@ -37,6 +44,10 @@ export const SCRIPT_PRIORS = Object.freeze([
37
44
  prior('spec-schema.mjs', '5.0.0', '7.2.1', '6a7d1e836c158baab5a412a1ad76d34891934dc28c88486c264a4b5d46f5892a'),
38
45
  prior('spec-schema.test.mjs', '5.0.0', '7.2.1', '698564d7283281be1826019d214df475bb876687915de086818d8f5ece0e0336'),
39
46
  prior('check-docs-size.mjs', '7.0.0', '8.1.5', '0cf90ae2cbfc809847574a8c71a6b1322c783359740b08e0ff179f0d9d04dffc'),
47
+ prior('install-git-hooks.mjs', '4.0.0', '8.2.1', '4c4010153cd3a9ca556f34d567d9985cff5c6e1b5ec3087ed7805e5c98f6f918'),
48
+ prior('install-git-hooks.test.mjs', '4.0.0', '7.1.2', '9603c4dec823d4de8b7b603563d98acb836c0f430565ef8b56c31db4aea4829b'),
49
+ prior('install-git-hooks.test.mjs', '7.2.0', '8.2.1', 'b57d6b2004ef1967034d9ad8d1f1db0a3b4972c6284bb8c79dea6900dcec0b69'),
50
+ prior('install-git-hooks-repo-exec.test.mjs', '4.0.0', '8.2.1', 'f12584b062cfa337f09f21b8d4d096549eaecc08242ee264e6f0b98226605464'),
40
51
  ]);
41
52
 
42
53
  export const digestOf = (bytes) => createHash('sha256').update(bytes).digest('hex');
@@ -28,3 +28,9 @@ export {
28
28
  projectLayout,
29
29
  serialize,
30
30
  } from './record.mjs';
31
+
32
+ export {
33
+ SETUP_ANSWERS,
34
+ checkTargetOf,
35
+ layoutSetupOf,
36
+ } from './setup.mjs';
@@ -0,0 +1,40 @@
1
+ // setup.mjs — the layout setup: its closed answers, the one statement of what a --check run judges,
2
+ // and the setup's answer for a project. It writes no file, spawns no process of its own and imports no
3
+ // file of the practice: every read reaches it through the values its caller hands it, so the advisor,
4
+ // the git-hooks leaf and the check ask one rule.
5
+ //
6
+ // Dependency-free, Node >= 22. No side effects on import.
7
+
8
+ import { SPEC_STORE_ROOT } from './layout.mjs';
9
+
10
+ export const SETUP_ANSWERS = Object.freeze(['armable', 'record', 'held']);
11
+
12
+ // checkTargetOf({ loaded, absentConfig }) → exactly one of: the schema-1 stop, the unminted stop (a
13
+ // present config authored or incomplete), or the config to judge with the dimensions judged.
14
+ export const checkTargetOf = ({ loaded, absentConfig }) => {
15
+ const absent = loaded.state === 'absent';
16
+ const config = absent ? absentConfig : loaded.config;
17
+ if (config.schema === 1) return { stop: 'schema-1', config };
18
+ if (!absent && loaded.state !== 'minted') return { stop: 'unminted', config, state: loaded.state, missing: loaded.missingMachineKeys };
19
+ return { stop: null, config, judged: { absent, layout: absent || config.layout !== null } };
20
+ };
21
+
22
+ // The store-root rule of a config that starts layout: the store is a root of its own there.
23
+ const insideStore = (root) => root === SPEC_STORE_ROOT || root.startsWith(`${SPEC_STORE_ROOT}/`);
24
+
25
+ // layoutSetupOf(root, practice, deps) → { answer: 'armable' } | { answer: 'record', args } |
26
+ // { answer: 'held', reason } with reason schema-1, unminted, store-root (with the root) or stops.
27
+ // `practice` carries the loader, judgeTree, stopsOf, the absent config the check judges and the reason
28
+ // the record's first entries take.
29
+ export const layoutSetupOf = (root, practice, deps = {}) => {
30
+ const target = checkTargetOf({ loaded: practice.loadSourceSizeConfig(root, deps), absentConfig: practice.absentConfig });
31
+ if (target.stop !== null) return { answer: 'held', reason: target.stop };
32
+ const { config, judged } = target;
33
+ const starts = !judged.layout;
34
+ const storeRoot = starts ? config.roots.find(insideStore) : undefined;
35
+ if (storeRoot !== undefined) return { answer: 'held', reason: 'store-root', root: storeRoot };
36
+ const stops = practice.stopsOf(practice.judgeTree(root, config, deps, judged).findings).length > 0;
37
+ if (judged.absent) return stops ? { answer: 'record', args: ['--write-baseline', '--reason', practice.reason] } : { answer: 'armable' };
38
+ if (stops) return { answer: 'held', reason: 'stops' };
39
+ return starts ? { answer: 'record', args: ['--write-baseline', '--layout', '--reason', practice.reason] } : { answer: 'armable' };
40
+ };
@@ -42,6 +42,8 @@ import {
42
42
  SOURCE_SIZE_SCHEMA,
43
43
  applyOverride,
44
44
  assertNoStoreRoot,
45
+ checkTargetOf,
46
+ isRaise,
45
47
  loadSourceSizeConfig,
46
48
  matchesSourceSizeGate,
47
49
  materialize,
@@ -82,6 +84,7 @@ import {
82
84
 
83
85
  const usageFail = (message) => Object.assign(new Error(`[agent-workflow-kit] ${message}`), { exitCode: 2 });
84
86
  const RECORD_NOUN = 'the source-size record';
87
+ const LAYOUT_GROWTH_LEAD = 'source-size: --layout REFUSED — it starts the layout record and raises nothing else, but the record no longer holds for this tree, so that growth takes --write-baseline --reason first; nothing was written.';
85
88
 
86
89
  // What an absent config is judged as: schema 2 under the kit's values, layout over "." and the store.
87
90
  const ABSENT = Object.freeze({ _README: TEMPLATE_README, schema: SOURCE_SIZE_SCHEMA });
@@ -89,14 +92,12 @@ const ABSENT = Object.freeze({ _README: TEMPLATE_README, schema: SOURCE_SIZE_SCH
89
92
  // Every run returns the config it resolved, so the CLI states the limits that run judged, and the
90
93
  // scope it judged, so the CLI says once what it did not.
91
94
  export const runCheck = ({ cwd, deps = {} }) => {
92
- const { state, config: present, missingMachineKeys } = loadSourceSizeConfig(cwd, deps);
93
- const absent = state === 'absent';
94
- const config = absent ? validateSourceSizeConfig(ABSENT) : present;
95
- if (config.schema === 1) return { code: 1, lines: schema1StopLines(cwd), config };
96
- if (!absent && state !== 'minted') return { code: 1, lines: unmintedRefusalLines(cwd, { state, missing: missingMachineKeys }), config };
97
- const judged = { absent, layout: absent || config.layout !== null };
95
+ const target = checkTargetOf({ loaded: loadSourceSizeConfig(cwd, deps), absentConfig: validateSourceSizeConfig(ABSENT) });
96
+ const { config, judged } = target;
97
+ if (target.stop === 'schema-1') return { code: 1, lines: schema1StopLines(cwd), config };
98
+ if (target.stop === 'unminted') return { code: 1, lines: unmintedRefusalLines(cwd, { state: target.state, missing: target.missing }), config };
98
99
  const verdict = judgeTree(cwd, config, deps, judged);
99
- return { code: stopsOf(verdict.findings).length === 0 ? 0 : 1, lines: checkReportLines({ cwd, config, verdict, absent }), config, judged };
100
+ return { code: stopsOf(verdict.findings).length === 0 ? 0 : 1, lines: checkReportLines({ cwd, config, verdict, absent: judged.absent }), config, judged };
100
101
  };
101
102
 
102
103
  // ── the writer ────────────────────────────────────────────────────────────────────────────────────
@@ -133,6 +134,9 @@ export const runWriteBaseline = ({ cwd, reason, layout = false, deps = {} }) =>
133
134
  const judged = { absent, layout: absent || layout || config.layout !== null };
134
135
  const { plan, bandWarnings, warnings } = judgeForWrite(cwd, config, deps, judged);
135
136
  const starts = layout && !absent && config.layout === null;
137
+ // Starting layout on a minted record raises the layout record alone: growth takes the plain write first.
138
+ const plain = starts && loaded.state === 'minted' ? plan.deltas.filter((delta) => !plan.layout.deltas.includes(delta)) : [];
139
+ if (plain.some(isRaise)) return { code: 1, lines: [...bandWarnings, LAYOUT_GROWTH_LEAD, ...reasonRequiredLines(cwd, plain)], config, judged };
136
140
  if (plan.raises.length > 0 && reason === undefined) return { code: 1, lines: [...bandWarnings, ...reasonRequiredLines(cwd, plan.deltas, { layout: starts })], config, judged };
137
141
  const body = serialize(schema2Of(parsed), materialize(plan, reason));
138
142
  // Whether anything was written is decided by the BYTES, not by the delta count: completing a