@sabaiway/agent-workflow-kit 14.40.0 → 14.41.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,12 +1,11 @@
1
- // install-git-hooks.test.mjs — spec for the pre-commit installer (strip-the-kit round-1 folds):
2
- // the hooks path comes from git plumbing (a linked worktree resolves ITS OWN hooks path, never a
3
- // hardcoded `.git/hooks`), and an armed commit-guard line SURVIVES a flagless re-run (exactly one
4
- // strictly-parsed canonical guard line carries forward; --no-commit-guard is the only consented
5
- // disable; both flags together are a usage error; a duplicated guard line fails closed).
1
+ // install-git-hooks.test.mjs — the pre-commit installer on a deployed copy: the hooks path comes from git
2
+ // plumbing (a linked worktree resolves ITS OWN hooks path); the guard, rules-check and layout-check lines
3
+ // are carried by role, fail closed on a duplicate and refuse a bad flag value, writing nothing. Every child
4
+ // runs with each inherited GIT_* variable stripped, so a hook's environment never leaks in.
6
5
 
7
6
  import { describe, it } from 'node:test';
8
7
  import assert from 'node:assert/strict';
9
- import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, cpSync, existsSync } from 'node:fs';
8
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync, cpSync, existsSync, realpathSync } from 'node:fs';
10
9
  import { tmpdir } from 'node:os';
11
10
  import { basename, join, dirname, resolve } from 'node:path';
12
11
  import { fileURLToPath } from 'node:url';
@@ -15,118 +14,217 @@ import { spawnSync } from 'node:child_process';
15
14
  const HERE = dirname(fileURLToPath(import.meta.url));
16
15
  const INSTALLER_SRC = join(HERE, 'install-git-hooks.mjs');
17
16
  const MALFORMED_PACKAGE_JSON = '{ not json';
18
- const NAMED_PACKAGE_JSON = '{"name":"named-fixture"}';
19
- const NAMED_FIXTURE = 'named-fixture';
17
+ const [NAMED_PACKAGE_JSON, NAMED_FIXTURE] = ['{"name":"named-fixture"}', 'named-fixture'];
18
+ const WIN32 = ['--import', 'data:text/javascript,Object.defineProperty(process,"platform",{value:"win32"})'];
19
+ const BACKSLASH = String.fromCharCode(92);
20
+ const SHELL_ACTIVE = [34, 36, 96, 92, 13, 10].map((code) => String.fromCharCode(code)).filter((ch) => process.platform !== 'win32' || ch !== BACKSLASH);
21
+ const shown = (path) => (process.platform === 'win32' ? path.replaceAll(BACKSLASH, '/') : path);
22
+
23
+ const BASE_ENV = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^[Gg][Ii][Tt]_/.test(key)));
24
+ const envAt = (home) => ({
25
+ ...BASE_ENV, HOME: home, XDG_CONFIG_HOME: join(home, '.config'), LC_ALL: 'C', GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_SYSTEM: '/dev/null',
26
+ GIT_CONFIG_NOSYSTEM: '1', GIT_ATTR_NOSYSTEM: '1', GIT_AUTHOR_NAME: 'p', GIT_AUTHOR_EMAIL: 'p@e', GIT_COMMITTER_NAME: 'p', GIT_COMMITTER_EMAIL: 'p@e',
27
+ });
28
+
29
+ // A child that never started or was killed has no exit status to judge — it fails the cell outright.
30
+ const spawnChecked = (command, args, cwd) => {
31
+ const r = spawnSync(command, args, { cwd, env: envAt(cwd), encoding: 'utf8' });
32
+ if (r.error) throw r.error;
33
+ if (r.signal !== null) throw new Error(`${command} was killed by ${r.signal}`);
34
+ return r;
35
+ };
36
+ const succeeds = (r) => { assert.equal(r.status, 0, r.stderr); return r; };
37
+ const git = (cwd, ...args) => succeeds(spawnChecked('git', args, cwd));
20
38
 
21
39
  // The installer anchors ROOT at <its dir>/.. — deploy it into a fixture's scripts/ like a consumer.
22
40
  const mkProject = () => {
23
- const root = mkdtempSync(join(tmpdir(), 'install-hooks-'));
24
- const g = (...a) => spawnSync('git', a, { cwd: root, encoding: 'utf8' });
41
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'install-hooks-')));
42
+ const g = (...a) => git(root, ...a);
25
43
  g('init', '-q');
26
- g('config', 'user.email', 'p@e');
27
- g('config', 'user.name', 'p');
28
44
  mkdirSync(join(root, 'scripts'), { recursive: true });
29
45
  cpSync(INSTALLER_SRC, join(root, 'scripts', 'install-git-hooks.mjs'));
30
46
  writeFileSync(join(root, 'guard.mjs'), '// a stand-in commit-guard tool\n');
31
47
  writeFileSync(join(root, 'base.txt'), 'base\n');
32
- g('add', '-A');
33
- g('commit', '-qm', 'base');
48
+ for (const args of [['add', '-A'], ['commit', '-qm', 'base']]) g(...args);
34
49
  return { root, g };
35
50
  };
51
+ const inProject = (cell) => () => { const fx = mkProject(); try { cell(fx); } finally { rmSync(fx.root, { recursive: true, force: true }); } };
36
52
 
37
- const runInstaller = (root, args = []) =>
38
- spawnSync('node', [join(root, 'scripts', 'install-git-hooks.mjs'), ...args], { cwd: root, encoding: 'utf8' });
39
-
40
- const hooksPathOf = (root) => {
41
- const r = spawnSync('git', ['rev-parse', '--git-path', 'hooks'], { cwd: root, encoding: 'utf8' });
42
- return resolve(root, r.stdout.trim());
43
- };
53
+ const runInstaller = (root, args = [], pre = []) =>
54
+ spawnChecked(process.execPath, [...pre, join(root, 'scripts', 'install-git-hooks.mjs'), ...args], root);
55
+ const installs = (...a) => succeeds(runInstaller(...a));
44
56
 
57
+ const hooksPathOf = (root) => resolve(root, git(root, 'rev-parse', '--git-path', 'hooks').stdout.trim());
45
58
  const markerFor = (name) => `# ${name}:install-git-hooks.mjs`;
46
59
  const readHook = (root) => readFileSync(join(hooksPathOf(root), 'pre-commit'), 'utf8');
60
+ const stub = (root, rel) => (mkdirSync(dirname(join(root, rel)), { recursive: true }), writeFileSync(join(root, rel), '// a stand-in tool\n'), join(root, rel));
47
61
 
48
- describe('install-git-hooks \u2014 beside no package.json, or a malformed one, the marker names the directory basename', () => {
49
- it('no package.json, then a MALFORMED one \u2014 the marker names the directory basename', () => {
50
- const { root } = mkProject();
62
+ // The hook the 4.0.0-8.2.1 installer body writes with no guard: the six docs and scripts lines.
63
+ const plainHook = (root) => `#!/usr/bin/env bash
64
+ ${markerFor(basename(root))}
65
+ # Auto-installed by scripts/install-git-hooks.mjs (run it from "prepare" or by hand).
66
+ # Runs the docs cap-validator + index-freshness gate + rotation-freshness checks
67
+ # + the scripts/ test suite before every commit, so files cannot drift over their
68
+ # declared maxLines, the auto-generated index.md cannot silently go stale, stale
69
+ # archive entries never reach a commit, and regressions to the scripts are caught.
70
+ set -e
71
+ node scripts/check-docs-size.mjs
72
+ node scripts/check-docs-size.mjs --check-index
73
+ node scripts/archive-changelog.mjs --check
74
+ node scripts/archive-issues.mjs --check
75
+ node scripts/archive-decisions.mjs --check
76
+ node --test scripts/*.test.mjs
77
+ `;
78
+ const line = (path, role) => `node "${role ? shown(path) : path}" --check${role ? ` # ${role}` : ''}\n`;
79
+
80
+ describe('install-git-hooks — beside no package.json, or a malformed one, the marker names the directory basename', () => {
81
+ it('no package.json, then a MALFORMED one — the marker names the directory basename', inProject(({ root }) => {
51
82
  const expected = markerFor(basename(root));
52
- const absent = runInstaller(root);
53
- assert.equal(absent.status, 0, absent.stderr);
83
+ installs(root);
54
84
  assert.ok(readHook(root).split('\n').includes(expected));
55
85
  writeFileSync(join(root, 'package.json'), MALFORMED_PACKAGE_JSON);
56
- const malformed = runInstaller(root);
57
- assert.equal(malformed.status, 0, malformed.stderr);
86
+ installs(root);
58
87
  assert.ok(readHook(root).split('\n').includes(expected));
59
- rmSync(root, { recursive: true, force: true });
60
- });
88
+ }));
61
89
 
62
- it('a named package.json wins \u2014 the marker carries its name', () => {
63
- const { root } = mkProject();
90
+ it('a named package.json wins — the marker carries its name', inProject(({ root }) => {
64
91
  writeFileSync(join(root, 'package.json'), NAMED_PACKAGE_JSON);
65
- const result = runInstaller(root);
66
- assert.equal(result.status, 0, result.stderr);
92
+ installs(root);
67
93
  assert.ok(readHook(root).split('\n').includes(markerFor(NAMED_FIXTURE)));
68
- rmSync(root, { recursive: true, force: true });
69
- });
94
+ }));
70
95
  });
71
96
 
72
97
  describe('install-git-hooks — the hooks path comes from git plumbing (C7)', () => {
73
- it('a normal repo installs at the git-path hooks location', () => {
74
- const { root } = mkProject();
75
- const r = runInstaller(root);
76
- assert.equal(r.status, 0, r.stderr);
98
+ it('a normal repo installs at the git-path hooks location', inProject(({ root }) => {
99
+ installs(root);
77
100
  assert.ok(existsSync(join(hooksPathOf(root), 'pre-commit')), 'the hook lands where git says hooks live');
78
- rmSync(root, { recursive: true, force: true });
79
- });
101
+ }));
80
102
 
81
- it('a LINKED WORKTREE installs at ITS OWN git-path hooks (never a hardcoded <worktree>/.git/hooks)', () => {
82
- const { root, g } = mkProject();
103
+ it('a LINKED WORKTREE installs at ITS OWN git-path hooks (never a hardcoded <worktree>/.git/hooks)', inProject(({ root, g }) => {
83
104
  const wt = join(root, '..', `wt-${Date.now() % 1e6}`);
84
105
  g('worktree', 'add', '-q', wt);
85
- mkdirSync(join(wt, 'scripts'), { recursive: true });
86
- cpSync(INSTALLER_SRC, join(wt, 'scripts', 'install-git-hooks.mjs'));
87
- const r = runInstaller(wt);
88
- assert.equal(r.status, 0, r.stderr);
89
- const expected = join(hooksPathOf(wt), 'pre-commit');
90
- assert.ok(existsSync(expected), `the worktree hook lands at git's own answer (${expected})`);
91
- assert.ok(!existsSync(join(wt, '.git', 'hooks', 'pre-commit')), 'never a literal <worktree>/.git/hooks (a worktree .git is a FILE)');
92
- rmSync(wt, { recursive: true, force: true });
93
- rmSync(root, { recursive: true, force: true });
94
- });
106
+ try {
107
+ mkdirSync(join(wt, 'scripts'), { recursive: true });
108
+ cpSync(INSTALLER_SRC, join(wt, 'scripts', 'install-git-hooks.mjs'));
109
+ installs(wt);
110
+ const expected = join(hooksPathOf(wt), 'pre-commit');
111
+ assert.ok(existsSync(expected), `the worktree hook lands at git's own answer (${expected})`);
112
+ assert.ok(!existsSync(join(wt, '.git', 'hooks', 'pre-commit')), 'never a literal <worktree>/.git/hooks (a worktree .git is a FILE)');
113
+ } finally {
114
+ rmSync(wt, { recursive: true, force: true });
115
+ }
116
+ }));
95
117
  });
96
118
 
97
119
  describe('install-git-hooks — the commit-guard arm persists (C8)', () => {
98
- it('an armed guard SURVIVES a later flagless re-run (carried forward from the managed hook)', () => {
99
- const { root } = mkProject();
120
+ it('an armed guard SURVIVES a later flagless re-run (carried forward from the managed hook)', inProject(({ root }) => {
100
121
  assert.equal(runInstaller(root, ['--commit-guard', 'guard.mjs']).status, 0);
101
- const armed = readFileSync(join(hooksPathOf(root), 'pre-commit'), 'utf8');
102
- assert.match(armed, /guard\.mjs" --check/, 'the guard line is written armed');
122
+ assert.match(readHook(root), /guard\.mjs" --check/, 'the guard line is written armed');
103
123
  assert.equal(runInstaller(root).status, 0, 'the flagless canonical re-run succeeds');
104
- const after = readFileSync(join(hooksPathOf(root), 'pre-commit'), 'utf8');
105
- assert.match(after, /guard\.mjs" --check/, 'the armed guard line survives a flagless re-run');
106
- rmSync(root, { recursive: true, force: true });
107
- });
124
+ assert.match(readHook(root), /guard\.mjs" --check/, 'the armed guard line survives a flagless re-run');
125
+ }));
108
126
 
109
- it('--no-commit-guard is the ONLY consented disable; combining both flags is a usage error', () => {
110
- const { root } = mkProject();
127
+ it('--no-commit-guard is the ONLY consented disable; combining both flags is a usage error', inProject(({ root }) => {
111
128
  assert.equal(runInstaller(root, ['--commit-guard', 'guard.mjs']).status, 0);
112
129
  assert.equal(runInstaller(root, ['--no-commit-guard']).status, 0);
113
- const after = readFileSync(join(hooksPathOf(root), 'pre-commit'), 'utf8');
114
- assert.doesNotMatch(after, /" --check$/m, 'the guard line is removed on the explicit disable');
130
+ assert.doesNotMatch(readHook(root), /" --check$/m, 'the guard line is removed on the explicit disable');
115
131
  const both = runInstaller(root, ['--commit-guard', 'guard.mjs', '--no-commit-guard']);
116
132
  assert.equal(both.status, 2, 'both flags together are a usage error, never an order-dependent pick');
117
- rmSync(root, { recursive: true, force: true });
118
- });
133
+ }));
119
134
 
120
- it('a DUPLICATED/malformed guard line in the managed hook fails CLOSED on a flagless re-run', () => {
121
- const { root } = mkProject();
135
+ it('a DUPLICATED/malformed guard line in the managed hook fails CLOSED on a flagless re-run', inProject(({ root }) => {
122
136
  assert.equal(runInstaller(root, ['--commit-guard', 'guard.mjs']).status, 0);
123
- const hookPath = join(hooksPathOf(root), 'pre-commit');
124
- const armed = readFileSync(hookPath, 'utf8');
137
+ const armed = readHook(root);
125
138
  const guardLine = armed.split('\n').find((l) => /" --check$/.test(l));
126
- writeFileSync(hookPath, `${armed}${guardLine}\n`); // duplicate the guard line
139
+ writeFileSync(join(hooksPathOf(root), 'pre-commit'), `${armed}${guardLine}\n`); // duplicate the guard line
127
140
  const r = runInstaller(root);
128
141
  assert.equal(r.status, 1, 'two guard lines are ambiguous — fail closed, never guess');
129
142
  assert.match(r.stderr, /guard/i);
130
- rmSync(root, { recursive: true, force: true });
131
- });
143
+ }));
144
+ });
145
+
146
+ describe('spec:init-project/S58 install-git-hooks — the rules-check and layout-check lines on a deployed copy', () => {
147
+ it('each flag writes its resolved path and role comment, ordered docs, rules, layout, guard; a flagless re-run keeps all three; --commit-guard replaces and --no-commit-guard drops the guard alone', inProject(({ root }) => {
148
+ const [rules, layout, guard, guard2] = ['tools/rules-cli.mjs', 'tools/source-size-check.mjs', 'guard.mjs', 'g2/guard.mjs'].map((rel) => stub(root, rel));
149
+ installs(root, ['--commit-guard', 'guard.mjs']);
150
+ installs(root, ['--layout-check', 'tools/source-size-check.mjs']);
151
+ installs(root, ['--rules-check', rules]);
152
+ const armed = plainHook(root) + line(rules, 'rules-check') + line(layout, 'layout-check');
153
+ assert.equal(readHook(root), armed + line(guard), 'each arming run carried the other armed lines');
154
+ assert.match(installs(root).stdout, /already up to date/, 'a flagless re-run keeps all three');
155
+ assert.equal(readHook(root), armed + line(guard));
156
+ installs(root, ['--commit-guard', guard2]);
157
+ assert.equal(readHook(root), armed + line(guard2), '--commit-guard replaces the guard line alone');
158
+ installs(root, ['--no-commit-guard']);
159
+ assert.equal(readHook(root), armed, '--no-commit-guard drops the guard line alone');
160
+ }));
161
+
162
+ it('a legacy guard line whose file name is rules-cli.mjs keeps the guard role beside a rules line', inProject(({ root }) => {
163
+ const [legacy, rules] = ['legacy/rules-cli.mjs', 'tools/rules-cli.mjs'].map((rel) => stub(root, rel));
164
+ installs(root, ['--commit-guard', legacy]);
165
+ installs(root, ['--rules-check', rules]);
166
+ const expected = plainHook(root) + line(rules, 'rules-check') + line(legacy);
167
+ assert.equal(readHook(root), expected);
168
+ installs(root);
169
+ assert.equal(readHook(root), expected, 'the flagless re-run keeps the legacy line as the guard');
170
+ }));
171
+
172
+ it('two lines of one role exit 1 naming that role, the hook unchanged', inProject(({ root }) => {
173
+ installs(root, ['--rules-check', stub(root, 'tools/rules-cli.mjs'), '--layout-check', stub(root, 'tools/source-size-check.mjs')]);
174
+ const armed = readHook(root);
175
+ for (const role of ['rules-check', 'layout-check']) {
176
+ const roleLine = armed.split('\n').find((l) => l.endsWith(` --check # ${role}`));
177
+ assert.ok(roleLine, `the ${role} line is armed`);
178
+ writeFileSync(join(hooksPathOf(root), 'pre-commit'), `${armed}${roleLine}\n`);
179
+ const r = runInstaller(root);
180
+ assert.equal(r.status, 1, r.stderr);
181
+ assert.match(r.stderr, new RegExp(`carries 2 ${role} lines`));
182
+ assert.equal(readHook(root), `${armed}${roleLine}\n`);
183
+ }
184
+ }));
185
+
186
+ it('over a hook with no rules or layout line, a flagless and a --commit-guard run write the 4.0.0-8.2.1 bytes', inProject(({ root }) => {
187
+ installs(root);
188
+ assert.equal(readHook(root), plainHook(root));
189
+ installs(root, ['--commit-guard', 'guard.mjs']);
190
+ assert.equal(readHook(root), plainHook(root) + line(join(root, 'guard.mjs')));
191
+ }));
192
+
193
+ it('a wrong file name, a shell-active path or a missing value exits 2, a missing file exits 1, each writing nothing', inProject(({ root }) => {
194
+ const [rules, layout] = ['tools/rules-cli.mjs', 'tools/source-size-check.mjs'].map((rel) => stub(root, rel));
195
+ installs(root, ['--commit-guard', 'guard.mjs']);
196
+ const before = readHook(root);
197
+ const cases = [
198
+ [['--rules-check', layout], 2, /--rules-check takes a path to rules-cli\.mjs/],
199
+ [['--layout-check', rules], 2, /--layout-check takes a path to source-size-check\.mjs/],
200
+ ...SHELL_ACTIVE.flatMap((ch, at) => [
201
+ [['--rules-check', join(root, `r${at}${ch}x`, 'rules-cli.mjs')], 2, /a backslash, CR or LF/],
202
+ [['--layout-check', join(root, `l${at}${ch}x`, 'source-size-check.mjs')], 2, /a backslash, CR or LF/],
203
+ ]),
204
+ [['--rules-check', join(root, 'nowhere', 'rules-cli.mjs')], 1, /does not exist/],
205
+ [['--layout-check', join(root, 'nowhere', 'source-size-check.mjs')], 1, /does not exist/],
206
+ [['--rules-check'], 2, /--rules-check needs a path/],
207
+ [['--layout-check'], 2, /--layout-check needs a path/],
208
+ ];
209
+ for (const [args, status, message] of cases) {
210
+ const r = runInstaller(root, args);
211
+ assert.equal(r.status, status, `${JSON.stringify(args)}: ${r.stderr}`);
212
+ assert.match(r.stderr, message);
213
+ assert.equal(readHook(root), before, `${JSON.stringify(args)} wrote nothing`);
214
+ }
215
+ }));
216
+
217
+ it('an ordinary win32 path, its separators made /, arms and a flagless re-run carries it; on posix it is the backslash refusal', inProject(({ root }) => {
218
+ installs(root);
219
+ const given = `${root}/a${BACKSLASH}b/rules-cli.mjs`;
220
+ const armedAt = stub(root, 'a/b/rules-cli.mjs');
221
+ if (process.platform !== 'win32') { // there the backslash is refused, writing nothing
222
+ const posix = runInstaller(root, ['--rules-check', given]);
223
+ assert.deepEqual([posix.status, /a backslash, CR or LF/.test(posix.stderr), readHook(root)], [2, true, plainHook(root)], posix.stderr);
224
+ }
225
+ installs(root, ['--rules-check', given], WIN32);
226
+ assert.equal(readHook(root), plainHook(root) + line(armedAt, 'rules-check'));
227
+ assert.match(installs(root).stdout, /already up to date/, 'the flagless re-run recognises the win32-armed line');
228
+ assert.equal(readHook(root), plainHook(root) + line(armedAt, 'rules-check'));
229
+ }));
132
230
  });
@@ -26,6 +26,7 @@ import { findOnPath } from './detect-backends.mjs';
26
26
  import { consoleArgv } from './write-lanes.mjs';
27
27
  import { BUNDLED_SCRIPT_NAMES, INSTALLER_REL, SCRIPTS_REL, formatPlan, planGitHooks } from './git-hooks.mjs';
28
28
  import { ATTRIBUTION_HIDDEN, ATTRIBUTION_KEY, writeAttribution } from './attribution.mjs';
29
+ import { classifyDeployedScript } from './script-priors.mjs';
29
30
  import { globalRemovalOf, planGlobalRemoval } from './hide-footprint.mjs';
30
31
  import { isDirectRun } from './direct-run.mjs';
31
32
  import { dirCovers as covers } from './declared-paths.mjs';
@@ -38,7 +39,7 @@ const HOOK_VARIANTS = ['gate-hook', 'read-lane.missing', ...RESEED_VARIANTS];
38
39
  const STOP = 'state-block';
39
40
  const MCP_VARIANTS = ['mcp-channel', 'mcp-channel.differing'];
40
41
  const AGENT_VARIANTS = ['agents', 'executor-vehicle', 'executor-vehicle.differing'];
41
- const GIT_VARIANTS = ['enforcement', 'commit-guard'];
42
+ const GIT_VARIANTS = ['enforcement', 'commit-guard', 'hook-checks'];
42
43
  const WORKTREES = 'worktrees-dir';
43
44
  const ATTRIBUTION = 'attribution';
44
45
  const FOOTPRINT = 'footprint-global';
@@ -219,13 +220,16 @@ export const scopeOf = (variant, facts, deps = {}) => {
219
220
  }
220
221
  const scripts = join(facts.root, SCRIPTS_REL);
221
222
  if (GIT_VARIANTS.includes(variant)) {
222
- directories.splice(0, directories.length, scripts);
223
- filePaths.push(...BUNDLED_SCRIPT_NAMES.map((name) => join(scripts, name)));
223
+ directories.splice(0, directories.length, ...(variant === 'hook-checks' ? [] : [scripts]));
224
+ filePaths.push(...(variant === 'hook-checks' ? [join(facts.root, INSTALLER_REL)] : BUNDLED_SCRIPT_NAMES.map((name) => join(scripts, name))));
224
225
  }
225
- const runs = GIT_VARIANTS.includes(variant) ? ['node', INSTALLER_REL,
226
- ...(variant === 'commit-guard' ? ['--commit-guard', join(facts.toolsDir, 'commit-guard.mjs')] : [])] : null;
226
+ const rules = ['--rules-check', join(facts.toolsDir, 'project-rules', 'rules-cli.mjs')];
227
+ const layout = ['--layout-check', join(facts.toolsDir, 'source-size-check.mjs')];
228
+ const flagSets = variant === 'hook-checks' ? [rules, layout, [...rules, ...layout]]
229
+ : variant === 'commit-guard' ? [['--commit-guard', join(facts.toolsDir, 'commit-guard.mjs')]] : [[]];
230
+ const runs = GIT_VARIANTS.includes(variant) ? flagSets.map((flags) => ['node', INSTALLER_REL, ...flags]) : [];
227
231
  return {
228
- admitsRun: (argv) => runs !== null && equal(argv, runs),
232
+ admitsRun: (argv) => runs.some((run) => equal(argv, run)),
229
233
  admits: ({ path, key, change, value }) => {
230
234
  const correctFile = key.startsWith(`${SERVERS_KEY}.`) ? path === MCP_JSON_REL
231
235
  : path === (variant === WORKTREES ? SETTINGS_LOCAL_FILE : SETTINGS_FILE);
@@ -314,6 +318,12 @@ export const plannedChange = (variant, facts, deps = {}) => {
314
318
  } else if (GIT_VARIANTS.includes(variant)) {
315
319
  const plan = (deps.planGitHooks ?? planGitHooks)({ root: facts.root, variant, toolsDir: facts.toolsDir });
316
320
  for (const copy of plan.copies.filter(({ action }) => action === 'created')) writes.push({ path: copy.path, bytes: copy.bytes });
321
+ if (plan.refresh) {
322
+ // The one replace hook-checks makes: the bundled installer's bytes over a catalogued prior body.
323
+ const bundled = readFileSync(join(facts.toolsDir, '..', 'references', INSTALLER_REL));
324
+ const { path, bytes, replaces } = plan.refresh;
325
+ writes.push({ path, bytes, replaces, matches: bundled.equals(bytes) && classifyDeployedScript(replaces, basename(INSTALLER_REL), bundled) === 'prior' });
326
+ }
317
327
  runs = { argv: plan.runs.shown, line: formatPlan(plan).at(-1) };
318
328
  } else if (variant === WORKTREES) {
319
329
  const plan = writeVelocityProfile({ cwd: facts.root, dryRun: true, worktrees: true }, writerDeps);
@@ -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([