@sabaiway/agent-workflow-kit 20.1.0 → 21.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/README.md +7 -5
  3. package/SKILL.md +1 -1
  4. package/bin/install.mjs +10 -11
  5. package/capability.json +1 -1
  6. package/launchers/windsurf-workflow.md +3 -1
  7. package/package.json +5 -2
  8. package/references/contracts.md +9 -9
  9. package/references/modes/bootstrap.md +3 -3
  10. package/references/modes/commit-guard.md +1 -1
  11. package/references/modes/gates.md +1 -1
  12. package/references/modes/recommendations.md +2 -2
  13. package/references/modes/upgrade.md +4 -4
  14. package/references/scripts/{archive-caps.mjs → archives/archive-caps.mjs} +1 -1
  15. package/references/scripts/{archive-changelog.mjs → archives/archive-changelog.mjs} +7 -9
  16. package/references/scripts/{archive-decisions.mjs → archives/archive-decisions.mjs} +13 -10
  17. package/references/scripts/{archive-issues.mjs → archives/archive-issues.mjs} +7 -8
  18. package/references/scripts/{check-docs-size.mjs → docs-size/check-docs-size.mjs} +3 -4
  19. package/references/scripts/docs-size/index.mjs +2 -0
  20. package/references/scripts/family.json +43 -0
  21. package/references/scripts/family.mjs +90 -0
  22. package/references/scripts/gates/kit-command-gates.mjs +117 -0
  23. package/references/scripts/{migrate-gates.mjs → gates/migrate-gates.mjs} +30 -13
  24. package/references/scripts/{install-git-hooks.mjs → git-hooks/install-git-hooks.mjs} +50 -38
  25. package/references/scripts/run.mjs +74 -0
  26. package/references/scripts/shared/index.mjs +3 -0
  27. package/references/scripts/shared/project-root.mjs +11 -0
  28. package/references/scripts/spec-schema/index.mjs +2 -0
  29. package/references/shared/composition-handoff.md +1 -1
  30. package/references/shared/deploy-tail.md +2 -2
  31. package/references/templates/SPEC_TEMPLATE.md +1 -1
  32. package/references/templates/adr-record.md +3 -3
  33. package/tools/apply-danger-check.mjs +9 -5
  34. package/tools/atomic-write.mjs +3 -1
  35. package/tools/checker-gates-read.mjs +4 -1
  36. package/tools/direct-run.mjs +2 -0
  37. package/tools/distribution-files/retired.mjs +99 -0
  38. package/tools/distribution-files/scripts.mjs +67 -52
  39. package/tools/ensure-configs.mjs +21 -21
  40. package/tools/ensure-ops.mjs +60 -18
  41. package/tools/ensure-specs.mjs +82 -47
  42. package/tools/ensure-vocabulary.mjs +4 -4
  43. package/tools/epic-shape-cli.mjs +1 -1
  44. package/tools/epic-shape-ledger.mjs +1 -1
  45. package/tools/epic-shape.mjs +1 -1
  46. package/tools/family-registry.mjs +3 -1
  47. package/tools/feedback-record-cli.mjs +1 -1
  48. package/tools/fold-scope.mjs +2 -2
  49. package/tools/gates-declaration.mjs +8 -4
  50. package/tools/git-hooks.mjs +90 -65
  51. package/tools/jev-connect.mjs +1 -1
  52. package/tools/jev-guide.mjs +1 -1
  53. package/tools/jev-skill.mjs +1 -1
  54. package/tools/known-footprint.mjs +7 -29
  55. package/tools/node-evidence.mjs +29 -15
  56. package/tools/now-cli.mjs +1 -1
  57. package/tools/payload-prune.mjs +53 -58
  58. package/tools/plan-shape-cli.mjs +1 -1
  59. package/tools/plan-shape.mjs +1 -1
  60. package/tools/project-rules/rules-record.mjs +1 -1
  61. package/tools/queue-audit-cli.mjs +1 -1
  62. package/tools/queue-audit.mjs +2 -2
  63. package/tools/queue-purge-archive.mjs +1 -1
  64. package/tools/queue-purge-cli.mjs +1 -1
  65. package/tools/queue-purge.mjs +1 -1
  66. package/tools/recommendations.mjs +22 -19
  67. package/tools/script-priors.mjs +31 -3
  68. package/tools/source-size/piles.mjs +1 -1
  69. package/tools/spec-adoption.mjs +1 -1
  70. package/tools/spec-check-ops.mjs +2 -2
  71. package/tools/spec-check.mjs +2 -2
  72. package/tools/spec-coverage.mjs +1 -1
  73. package/tools/tier-guide.mjs +1 -1
  74. package/tools/transition/index.mjs +1 -1
  75. package/tools/upgrade-runlist.mjs +1 -1
  76. package/tools/write-lanes.mjs +2 -2
  77. package/references/scripts/_expect-shim.mjs +0 -41
  78. package/references/scripts/archive-caps.test.mjs +0 -321
  79. package/references/scripts/archive-changelog.test.mjs +0 -560
  80. package/references/scripts/archive-conservation.test.mjs +0 -466
  81. package/references/scripts/archive-decisions.test.mjs +0 -1503
  82. package/references/scripts/archive-issues.test.mjs +0 -825
  83. package/references/scripts/archiver-structure.test.mjs +0 -84
  84. package/references/scripts/check-docs-size-cli.test.mjs +0 -325
  85. package/references/scripts/check-docs-size-ensure.test.mjs +0 -360
  86. package/references/scripts/check-docs-size.test.mjs +0 -395
  87. package/references/scripts/install-git-hooks-repo-exec.test.mjs +0 -185
  88. package/references/scripts/install-git-hooks.test.mjs +0 -241
  89. package/references/scripts/markdown-blocks.test.mjs +0 -310
  90. package/references/scripts/migrate-gates-branches.test.mjs +0 -302
  91. package/references/scripts/migrate-gates.test.mjs +0 -517
  92. package/references/scripts/spec-schema.test.mjs +0 -352
  93. /package/references/scripts/{markdown-blocks.mjs → shared/markdown-blocks.mjs} +0 -0
  94. /package/references/scripts/{spec-schema.mjs → spec-schema/spec-schema.mjs} +0 -0
@@ -32,23 +32,22 @@
32
32
  // --today=YYYY-MM-DD (default UTC today)
33
33
 
34
34
  import { readFileSync, writeFileSync, mkdirSync, existsSync, realpathSync } from 'node:fs';
35
- import { dirname, resolve, basename } from 'node:path';
35
+ import { resolve, basename } from 'node:path';
36
36
  import { fileURLToPath } from 'node:url';
37
- import { tokenizeMarkdown, fail } from './markdown-blocks.mjs';
37
+ import { tokenizeMarkdown, fail, findProjectRoot } from '../shared/index.mjs';
38
38
 
39
- const __dirname = dirname(fileURLToPath(import.meta.url));
40
- const ROOT = resolve(__dirname, '..');
39
+ const ROOT = findProjectRoot(import.meta.url);
41
40
 
42
- const readProjectName = () => {
41
+ export const readProjectName = (root) => {
43
42
  try {
44
- const pkg = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf8'));
43
+ const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
45
44
  if (pkg.name) return pkg.name;
46
45
  } catch {
47
46
  /* no package.json — fall back to repo dir basename */
48
47
  }
49
- return basename(ROOT);
48
+ return basename(root);
50
49
  };
51
- const PROJECT_NAME = readProjectName();
50
+ const PROJECT_NAME = readProjectName(ROOT);
52
51
 
53
52
  const KNOWN_REL = 'docs/ai/known_issues.md';
54
53
  const HISTORY_REL = 'docs/ai/history';
@@ -29,11 +29,10 @@ import { existsSync, lstatSync, realpathSync } from 'node:fs';
29
29
  import { dirname, resolve, relative, join, basename, sep } from 'node:path';
30
30
  import { fileURLToPath } from 'node:url';
31
31
  import { randomBytes } from 'node:crypto';
32
- import { readSpecDocument, SPECS_COLLAPSE } from './spec-schema.mjs';
32
+ import { readSpecDocument, SPECS_COLLAPSE } from '../spec-schema/index.mjs';
33
+ import { findProjectRoot } from '../shared/index.mjs';
33
34
 
34
- const __filename = fileURLToPath(import.meta.url);
35
- const __dirname = dirname(__filename);
36
- const ROOT = resolve(__dirname, '..');
35
+ const ROOT = findProjectRoot(import.meta.url);
37
36
  const DOCS_DIR = resolve(ROOT, 'docs/ai');
38
37
  const INDEX_PATH = resolve(DOCS_DIR, 'index.md');
39
38
 
@@ -0,0 +1,2 @@
1
+ // The docs-size module's one door (spec script-family): the frontmatter reader the kit's tools import.
2
+ export { parseFrontmatter } from './check-docs-size.mjs';
@@ -0,0 +1,43 @@
1
+ {
2
+ "schema": 1,
3
+ "entries": [
4
+ { "path": "family.mjs", "role": "skill-home" },
5
+ { "path": "family.test.mjs", "role": "suite" },
6
+ { "path": "run.mjs", "role": "deployed", "seed": false },
7
+ { "path": "run.test.mjs", "role": "suite" },
8
+ { "path": "docs-size/check-docs-size.mjs", "role": "deployed", "seed": false },
9
+ { "path": "docs-size/index.mjs", "role": "skill-home" },
10
+ { "path": "docs-size/check-docs-size.test.mjs", "role": "suite" },
11
+ { "path": "docs-size/check-docs-size-cli.test.mjs", "role": "suite" },
12
+ { "path": "docs-size/check-docs-size-ensure.test.mjs", "role": "suite" },
13
+ { "path": "spec-schema/spec-schema.mjs", "role": "deployed", "seed": false },
14
+ { "path": "spec-schema/index.mjs", "role": "deployed", "seed": false },
15
+ { "path": "spec-schema/spec-schema.test.mjs", "role": "suite" },
16
+ { "path": "archives/archive-changelog.mjs", "role": "deployed", "seed": false },
17
+ { "path": "archives/archive-issues.mjs", "role": "deployed", "seed": false },
18
+ { "path": "archives/archive-decisions.mjs", "role": "deployed", "seed": true },
19
+ { "path": "archives/archive-caps.mjs", "role": "deployed", "seed": false },
20
+ { "path": "archives/index.mjs", "role": "support" },
21
+ { "path": "archives/archive-changelog.test.mjs", "role": "suite" },
22
+ { "path": "archives/archive-issues.test.mjs", "role": "suite" },
23
+ { "path": "archives/archive-decisions.test.mjs", "role": "suite" },
24
+ { "path": "archives/archive-caps.test.mjs", "role": "suite" },
25
+ { "path": "archives/archive-conservation.test.mjs", "role": "suite" },
26
+ { "path": "archives/archiver-structure.test.mjs", "role": "suite" },
27
+ { "path": "git-hooks/install-git-hooks.mjs", "role": "deployed", "seed": false },
28
+ { "path": "git-hooks/install-git-hooks.test.mjs", "role": "suite" },
29
+ { "path": "git-hooks/install-git-hooks-repo-exec.test.mjs", "role": "suite" },
30
+ { "path": "gates/migrate-gates.mjs", "role": "skill-home" },
31
+ { "path": "gates/kit-command-gates.mjs", "role": "skill-home" },
32
+ { "path": "gates/migrate-gates.test.mjs", "role": "suite" },
33
+ { "path": "gates/migrate-gates-branches.test.mjs", "role": "suite" },
34
+ { "path": "gates/kit-command-gates.test.mjs", "role": "suite" },
35
+ { "path": "shared/markdown-blocks.mjs", "role": "deployed", "seed": true },
36
+ { "path": "shared/project-root.mjs", "role": "deployed", "seed": true },
37
+ { "path": "shared/index.mjs", "role": "deployed", "seed": true },
38
+ { "path": "shared/markdown-blocks.test.mjs", "role": "suite" },
39
+ { "path": "shared/project-root.test.mjs", "role": "suite" },
40
+ { "path": "test-support/_expect-shim.mjs", "role": "support" },
41
+ { "path": "test-support/index.mjs", "role": "support" }
42
+ ]
43
+ }
@@ -0,0 +1,90 @@
1
+ // family.mjs — the one reader of the script family's manifest (spec script-family).
2
+ //
3
+ // family.json lists every file of this tree but itself: its path relative to the tree, its role and, on a
4
+ // deployed entry alone, whether the rotator needs it to load (seed). readFamily returns the entries frozen, in
5
+ // the manifest's order, or throws an error naming the manifest's path, the offending field and the one cause —
6
+ // a strict config: an unknown key, a missing field or a value outside its grammar is refused, never guessed.
7
+ // Dependency-free, Node >= 22. No side effects on import.
8
+
9
+ import { readFileSync } from 'node:fs';
10
+ import { dirname, join } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+
13
+ const HERE = dirname(fileURLToPath(import.meta.url));
14
+
15
+ export const FAMILY_FILE = 'family.json';
16
+ export const FAMILY_ROLES = Object.freeze(['deployed', 'skill-home', 'suite', 'support']);
17
+
18
+ const SCHEMA = 1;
19
+ const TOP_KEYS = ['schema', 'entries'];
20
+ const ENTRY_KEYS = ['path', 'role', 'seed'];
21
+ const TOP_FILES = new Set(['family.mjs', 'family.test.mjs', 'run.mjs', 'run.test.mjs']);
22
+ const MODULES = new Set(['docs-size', 'spec-schema', 'archives', 'git-hooks', 'gates', 'shared', 'test-support']);
23
+ const FILE_NAME = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
24
+
25
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
26
+
27
+ // A path is one of the top-level files, or <module>/<file> with the module one of the seven.
28
+ const inGrammar = (path) => {
29
+ const parts = path.split('/');
30
+ if (parts.length === 1) return TOP_FILES.has(path);
31
+ return parts.length === 2 && MODULES.has(parts[0]) && FILE_NAME.test(parts[1]);
32
+ };
33
+
34
+ const checkKeys = (object, keys, where, refuse) => {
35
+ const unknown = Object.keys(object).find((key) => !keys.includes(key));
36
+ if (unknown !== undefined) refuse(`${where}${unknown}`, `unknown key (allowed: ${keys.join(', ')})`);
37
+ };
38
+
39
+ const readEntry = (raw, at, seen, refuse) => {
40
+ const where = `entries[${at}]`;
41
+ if (!isObject(raw)) refuse(where, 'an entry must be an object');
42
+ checkKeys(raw, ENTRY_KEYS, `${where}.`, refuse);
43
+ for (const field of ['path', 'role']) {
44
+ if (!(field in raw)) refuse(`${where}.${field}`, 'missing');
45
+ if (typeof raw[field] !== 'string') refuse(`${where}.${field}`, 'must be a string');
46
+ }
47
+ const { path, role } = raw;
48
+ if (!inGrammar(path)) {
49
+ refuse(`${where}.path`, `${JSON.stringify(path)} is outside the grammar (${[...TOP_FILES].join(', ')} or <module>/<file> of ${[...MODULES].join(', ')})`);
50
+ }
51
+ if (seen.has(path)) refuse(`${where}.path`, `duplicate ${JSON.stringify(path)}`);
52
+ seen.add(path);
53
+ if (!FAMILY_ROLES.includes(role)) refuse(`${where}.role`, `${JSON.stringify(role)} is not one of ${FAMILY_ROLES.join(', ')}`);
54
+ if (role === 'deployed') {
55
+ if (!('seed' in raw)) refuse(`${where}.seed`, 'missing on a deployed entry');
56
+ if (typeof raw.seed !== 'boolean') refuse(`${where}.seed`, 'must be a boolean');
57
+ } else if ('seed' in raw) {
58
+ refuse(`${where}.seed`, 'only a deployed entry carries a seed');
59
+ }
60
+ return Object.freeze({ path, module: path.includes('/') ? path.split('/')[0] : null, role, seed: raw.seed === true });
61
+ };
62
+
63
+ // The family of the manifest in `dir` (this reader's own directory when none is given).
64
+ export const readFamily = (dir = HERE) => {
65
+ const manifest = join(dir, FAMILY_FILE);
66
+ const refuse = (field, cause) => {
67
+ throw new Error(`${manifest}: ${field === null ? '' : `${field}: `}${cause}`);
68
+ };
69
+ let text;
70
+ try {
71
+ text = readFileSync(manifest, 'utf8');
72
+ } catch (error) {
73
+ refuse(null, `cannot read the manifest (${error.code ?? error.message})`);
74
+ }
75
+ let parsed;
76
+ try {
77
+ parsed = JSON.parse(text);
78
+ } catch (error) {
79
+ refuse(null, `not JSON (${error.message})`);
80
+ }
81
+ if (!isObject(parsed)) refuse(null, 'the top level must be an object');
82
+ checkKeys(parsed, TOP_KEYS, '', refuse);
83
+ for (const key of TOP_KEYS) if (!(key in parsed)) refuse(key, 'missing');
84
+ if (parsed.schema !== SCHEMA) refuse('schema', `must be ${SCHEMA}, got ${JSON.stringify(parsed.schema)}`);
85
+ if (!Array.isArray(parsed.entries)) refuse('entries', 'must be an array');
86
+ const seen = new Set();
87
+ const entries = parsed.entries.map((raw, at) => readEntry(raw, at, seen, refuse));
88
+ if (!entries.some((entry) => entry.role === 'deployed')) refuse(null, 'no deployed entry — a family that deploys nothing is no family');
89
+ return Object.freeze(entries);
90
+ };
@@ -0,0 +1,117 @@
1
+ // kit-command-gates.mjs — the gate migration's reading of a kit-check gate (spec kit-command): a matched gate over a
2
+ // current kit folder is switched to the stable kit command, any other form naming a check is named with its repoint.
3
+ // Dependency-free, Node >= 22. No side effects on import.
4
+
5
+ import { lstatSync, readFileSync } from 'node:fs';
6
+ import { dirname, join, posix } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { KIT_COMMANDS, KIT_COMMAND_PATH } from '../run.mjs';
9
+ import { readFamily } from '../family.mjs';
10
+
11
+ const TREE = dirname(dirname(fileURLToPath(import.meta.url)));
12
+ const KIT_FOLDER = dirname(KIT_COMMAND_PATH);
13
+ const SCRIPTS_FOLDER = dirname(KIT_FOLDER);
14
+ const COMMAND = `node ${KIT_COMMAND_PATH}`;
15
+
16
+ const fileNameOf = (path) => path.slice(path.lastIndexOf('/') + 1);
17
+ const NAME_BY_FILE = new Map(Object.entries(KIT_COMMANDS).map(([name, target]) => [fileNameOf(target), name]));
18
+ const flatOf = (target) => `${SCRIPTS_FOLDER}/${fileNameOf(target)}`;
19
+
20
+ // path token → { name, flat } for the deployed or the flat path of a known name, relative to the project root.
21
+ const KNOWN_PATHS = new Map(Object.entries(KIT_COMMANDS).flatMap(([name, target]) => [
22
+ [`${KIT_FOLDER}/${target}`, { name, flat: false }],
23
+ [flatOf(target), { name, flat: true }],
24
+ ]));
25
+
26
+ const SAFE_FLAG = /^--[A-Za-z0-9][A-Za-z0-9-]*$/;
27
+ const MATCHED = /^node +("[^"]*"|[^\s"]+)((?: +[^\s"]+)*)$/;
28
+ const CHECK_FILE = new RegExp(`(?<![A-Za-z0-9._-])(${[...NAME_BY_FILE.keys()].map((file) => file.replaceAll('.', '\\.')).join('|')})(?=$|[\\s"';&|<>()])`, 'g');
29
+
30
+ const unquoted = (token) => (token.length > 1 && token.startsWith('"') && token.endsWith('"') ? token.slice(1, -1) : token);
31
+
32
+ // The gate's one kit-check invocation, or null: `node`, one path token of a known name, then only safe `--` flags.
33
+ const matchOf = (cmd) => {
34
+ const found = MATCHED.exec(cmd.trim());
35
+ if (!found) return null;
36
+ const token = unquoted(found[1]).replace(/^\.\//, '');
37
+ const known = KNOWN_PATHS.get(token);
38
+ const flags = found[2].split(' ').filter(Boolean);
39
+ if (!known || !flags.every((flag) => SAFE_FLAG.test(flag))) return null;
40
+ return { ...known, token, args: flags };
41
+ };
42
+
43
+ // Every known name whose target's file name stands whole in the cmd and not as the end of its deployed path, one per occurrence.
44
+ const namedChecks = (cmd) => [...cmd.matchAll(CHECK_FILE)].flatMap((found) => {
45
+ const name = NAME_BY_FILE.get(found[1]);
46
+ return cmd.slice(0, found.index).endsWith(`agent-workflow/${posix.dirname(KIT_COMMANDS[name])}/`) ? [] : [name];
47
+ });
48
+
49
+ export const repointsOf = (gate) => namedChecks(gate.cmd).map((name) => ({ id: gate.id, repoint: `${COMMAND} ${name}` }));
50
+
51
+ // The first path, relative to the project, that keeps the name from being current — the command, its target and
52
+ // what the target loads — or null when it is.
53
+ const firstStaleKitPath = (projectDir, name) => {
54
+ const at = (path) => join(projectDir, ...path.split('/'));
55
+ const isPlain = (path, kind) => {
56
+ try {
57
+ const stat = lstatSync(at(path));
58
+ return kind === 'directory' ? stat.isDirectory() : stat.isFile();
59
+ } catch {
60
+ return false;
61
+ }
62
+ };
63
+ const folders = new Set();
64
+ for (const folder of [SCRIPTS_FOLDER, KIT_FOLDER]) {
65
+ if (!isPlain(folder, 'directory')) return folder;
66
+ folders.add(folder);
67
+ }
68
+ const deployedPaths = new Set(readFamily(TREE).filter((entry) => entry.role === 'deployed').map(({ path }) => path));
69
+ const needed = new Set([fileNameOf(KIT_COMMAND_PATH), KIT_COMMANDS[name]]);
70
+ for (const path of needed) {
71
+ const deployed = `${KIT_FOLDER}/${path}`;
72
+ const folder = dirname(deployed);
73
+ if (!folders.has(folder)) {
74
+ if (!isPlain(folder, 'directory')) return folder;
75
+ folders.add(folder);
76
+ }
77
+ if (!isPlain(deployed, 'file')) return deployed;
78
+ try {
79
+ const source = readFileSync(join(TREE, path));
80
+ if (!deployedPaths.has(path) || !readFileSync(at(deployed)).equals(source)) return deployed;
81
+ for (const found of source.toString('utf8').matchAll(/(?:\bfrom\s*|\bimport\s*(?:\(\s*)?)['"](\.[^'"\n]+)['"]/g)) needed.add(posix.join(posix.dirname(path), found[1]));
82
+ } catch {
83
+ return deployed;
84
+ }
85
+ }
86
+ return null;
87
+ };
88
+
89
+ const isAbsent = (path) => {
90
+ try { lstatSync(path); } catch (error) { return error.code === 'ENOENT'; }
91
+ return false;
92
+ };
93
+
94
+ export const planKitCommandGates = (gates, projectDir) => {
95
+ const read = gates.map((gate) => {
96
+ const cmd = gate !== null && typeof gate === 'object' && typeof gate.cmd === 'string' ? gate.cmd : '';
97
+ return { gate, match: matchOf(cmd), names: namedChecks(cmd) };
98
+ });
99
+ const namesToCheck = new Set(read.flatMap(({ match, names }) => match ? [match.name, ...names] : names));
100
+ const staleByName = new Map([...namesToCheck].map((name) => [name, firstStaleKitPath(projectDir, name)]));
101
+ const result = { gates: [], switched: [], withheld: [], repoints: [] };
102
+ for (const { gate, match, names } of read) {
103
+ const stale = match ? staleByName.get(match.name) : null;
104
+ if (stale !== null) {
105
+ if (match) result.withheld.push({ id: gate.id, path: stale });
106
+ result.gates.push(gate);
107
+ } else if (match && (!match.flat || isAbsent(join(projectDir, match.token)))) {
108
+ const cmd = [COMMAND, match.name, ...match.args].join(' ');
109
+ result.switched.push({ id: gate.id, cmd, was: gate.cmd });
110
+ result.gates.push({ ...gate, cmd });
111
+ } else {
112
+ for (const name of names) if (staleByName.get(name) === null) result.repoints.push({ id: gate.id, repoint: `${COMMAND} ${name}` });
113
+ result.gates.push(gate);
114
+ }
115
+ }
116
+ return result;
117
+ };
@@ -13,9 +13,12 @@
13
13
  // provenance): a legacy entry is `node <path>/review-ledger.mjs --check` or
14
14
  // `node <path>/fold-completeness.mjs --check` (quoted or bare path, ONE plain invocation); the
15
15
  // canonical unit-tests entry is id `unit-tests` with a cmd starting `node --test `. ANYTHING
16
- // else is a CUSTOMIZED entry — never auto-touched: the preview reports it loudly and prints the
17
- // paste-ready recovery so the maintainer applies the intent by hand; the commit guard is NOT to
18
- // be installed until the declaration is final-run-capable.
16
+ // else, but a kit-check gate the switch below rewrites, is a CUSTOMIZED entry — never auto-touched: the
17
+ // preview reports it loudly and prints the paste-ready recovery so the maintainer applies the intent by
18
+ // hand; the commit guard is NOT to be installed until the declaration is final-run-capable.
19
+ //
20
+ // A kit-check gate over a current kit folder that the rules above do not hold customized is SWITCHED to the stable kit command (spec kit-command, read by
21
+ // ./kit-command-gates.mjs); any other form is named.
19
22
  //
20
23
  // Write discipline (the family's consented-writer contract): preview (dry-run) is the DEFAULT
21
24
  // and writes NOTHING; `--apply` rewrites docs/ai/gates.json via exclusive tmp+rename in the same
@@ -31,6 +34,7 @@ import { join, resolve, isAbsolute } from 'node:path';
31
34
  import { fileURLToPath } from 'node:url';
32
35
  import { randomBytes } from 'node:crypto';
33
36
  import { spawnSync } from 'node:child_process';
37
+ import { planKitCommandGates, repointsOf } from './kit-command-gates.mjs';
34
38
 
35
39
  export const MIGRATE_GATES_STOP = 'MIGRATE_GATES_STOP';
36
40
  const stop = (message) =>
@@ -274,8 +278,8 @@ const CORE_CHECK_NAMES = Object.freeze(['coverage-check', 'review-state']);
274
278
  const coreCheckTools = (kitToolsDir) =>
275
279
  Object.fromEntries(CORE_CHECK_NAMES.map((name) => [name, checkerClaimTool(`${name}.mjs`, join(kitToolsDir, `${name}.mjs`))]));
276
280
 
277
- // buildMigrationPlan(gates, kitToolsDir, projectDir) → the PURE migration plan.
278
- // plan rows: { action: 'keep' | 'remove' | 'extend' | 'move' | 'add', entry, reason }.
281
+ // buildMigrationPlan(gates, kitToolsDir, projectDir) → the migration plan.
282
+ // plan rows: { action: 'keep' | 'remove' | 'extend' | 'switch' | 'move' | 'add', entry, reason }.
279
283
  // finalCapable mirrors the run-gates --final acceptance shape: the canonical review-state check
280
284
  // must be PRESENT (the checker itself is guaranteed last by the plan) — missing means the result
281
285
  // is NOT final-run-capable and the preview says so loudly with the paste-ready candidate. An
@@ -284,6 +288,7 @@ export const buildMigrationPlan = (gates, kitToolsDir, projectDir) => {
284
288
  if (typeof projectDir !== 'string') {
285
289
  throw stop('buildMigrationPlan needs the project root — a declared cmd may name a core check by a RELATIVE path, and only the project root resolves it the way the runner does');
286
290
  }
291
+ const kit = planKitCommandGates(gates, projectDir);
287
292
  const tools = coreCheckTools(kitToolsDir);
288
293
  const claimOf = (name, cmd) => classifyCheckerClaim(tools[name], cmd, projectDir);
289
294
  const plan = [];
@@ -296,7 +301,7 @@ export const buildMigrationPlan = (gates, kitToolsDir, projectDir) => {
296
301
  let unitTestsExtended = false;
297
302
  let hasReviewState = false;
298
303
  const coverageCmd = `node "${join(kitToolsDir, 'coverage-check.mjs')}" --check`;
299
- for (const gate of gates) {
304
+ for (const [at, gate] of gates.entries()) {
300
305
  const legacy = LEGACY_FORMS.find((f) => f.re.test(gate.cmd.trim()));
301
306
  if (legacy) {
302
307
  plan.push({ action: 'remove', entry: gate, reason: `the ${legacy.name} check died with its tool (strip-the-kit)` });
@@ -317,7 +322,7 @@ export const buildMigrationPlan = (gates, kitToolsDir, projectDir) => {
317
322
  }
318
323
  // The third outcome: this IS the tool, from a copy the caller did not name. A vendored
319
324
  // deployment declared it deliberately, so it is PRESERVED as written — a plain keep row, never
320
- // a new action kind (resultingGates carries only keep|extend|move|add and would silently drop
325
+ // a new action kind (resultingGates carries only keep|extend|switch|move|add and would silently drop
321
326
  // one) — and it counts as DECLARED, which is what stops the checker being added on top of it
322
327
  // and stops its id reading as a squatter. What it does not buy is the final-capability claim:
323
328
  // run-gates --final anchors on the installed copy by realpath and would refuse this cmd.
@@ -355,12 +360,18 @@ export const buildMigrationPlan = (gates, kitToolsDir, projectDir) => {
355
360
  continue;
356
361
  }
357
362
  // A dead-tool reference or a core-check LOOKALIKE in a non-canonical form — reported, never touched.
358
- if (/review-ledger|fold-completeness|verification-profile|seed-gates|sarif|coverage-check\.mjs|review-state\.mjs/.test(gate.cmd)) {
359
- customized.push(gate);
363
+ const deadTool = /review-ledger|fold-completeness|verification-profile|seed-gates|sarif|coverage-check\.mjs|review-state\.mjs/.test(gate.cmd);
364
+ if (deadTool) customized.push(gate);
365
+ if (kit.gates[at] !== gate && !deadTool) {
366
+ plan.push({ action: 'switch', entry: kit.gates[at], reason: `was: ${gate.cmd} — the kit check runs through the stable kit command` });
367
+ continue;
360
368
  }
361
369
  plan.push({ action: 'keep', entry: gate, reason: null });
362
370
  }
363
- const kept = plan.filter((r) => r.action === 'keep' || r.action === 'extend');
371
+ // A gate the kit reading would switch but the rules above keep untouched is named with its repoint instead.
372
+ const switchedEntries = new Set(plan.filter((r) => r.action === 'switch').map((r) => r.entry));
373
+ const repoints = [...kit.repoints, ...gates.flatMap((gate, at) => (kit.gates[at] !== gate && !switchedEntries.has(kit.gates[at]) ? repointsOf(gate) : []))];
374
+ const kept = plan.filter((r) => r.action === 'keep' || r.action === 'extend' || r.action === 'switch');
364
375
  const checkerRow = checkerRows[checkerRows.length - 1] ?? null;
365
376
  const externalCoverageChecks = externalCoreChecks.filter((c) => c.name === 'coverage-check');
366
377
  // The checker READS an lcov; something has to WRITE it FIRST. Adding the checker over a
@@ -451,11 +462,13 @@ export const buildMigrationPlan = (gates, kitToolsDir, projectDir) => {
451
462
  canonicalCheckerInert,
452
463
  reviewStateCandidate,
453
464
  collision,
465
+ repoints,
466
+ withheld: kit.withheld,
454
467
  };
455
468
  };
456
469
 
457
470
  export const resultingGates = (plan) => {
458
- const kept = plan.filter((r) => r.action === 'keep' || r.action === 'extend').map((r) => r.entry);
471
+ const kept = plan.filter((r) => r.action === 'keep' || r.action === 'extend' || r.action === 'switch').map((r) => r.entry);
459
472
  const moved = plan.filter((r) => r.action === 'move').map((r) => r.entry);
460
473
  const added = plan.filter((r) => r.action === 'add').map((r) => r.entry);
461
474
  return [...kept, ...moved, ...added]; // move/add go LAST — the checker ends up the last declared gate
@@ -471,8 +484,10 @@ const customizedRecovery = (gate) =>
471
484
  ? `declare the canonical suite gate by hand so the coverage contract is verifiable: node --test ${UNIT_TESTS_COVERAGE_FLAGS} <your test paths> — ${MARKER_LANE}`
472
485
  : 'remove the entry, or repoint it at a living check — the review-ledger / fold-completeness tools no longer exist.';
473
486
 
474
- const warningLines = ({ customized, finalCapable, hasReviewState = finalCapable, hasProducer = false, checkerWithheld = false, canonicalCheckerInert = false, duplicateCheckers = 0, externalCoreChecks = [], reviewStateCandidate }) => {
487
+ const warningLines = ({ customized, finalCapable, hasReviewState = finalCapable, hasProducer = false, checkerWithheld = false, canonicalCheckerInert = false, duplicateCheckers = 0, externalCoreChecks = [], reviewStateCandidate, repoints = [], withheld = [] }) => {
475
488
  const lines = [];
489
+ for (const { id, path } of withheld) lines.push(` WARNING: ${id} runs a kit check, but the kit folder is not current (${path}) — kept as declared; refresh the kit's scripts, then re-run this migration.`);
490
+ for (const { id, repoint } of repoints) lines.push(` REPOINT (untouched): ${id}: run ${repoint} in place of its invocation of that check, its arguments kept.`);
476
491
  for (const gate of customized) {
477
492
  lines.push(` CUSTOMIZED (untouched): ${gate.id}: ${gate.cmd}`);
478
493
  lines.push(` recovery (apply by hand if the intent still stands): ${customizedRecovery(gate)}`);
@@ -650,7 +665,9 @@ Default is a dry-run PREVIEW (writes nothing). --apply rewrites ${GATES_REL} ato
650
665
  canonical legacy entries (review-ledger / fold-completeness --check, matched by their documented
651
666
  single-invocation forms) are REMOVED; the canonical unit-tests cmd gains the built-in lcov
652
667
  reporters; the coverage-check gate is ADDED last (resolved, QUOTED path) — and WITHHELD, loudly,
653
- when no declared gate produces the lcov it reads. Customized entries are
668
+ when no declared gate produces the lcov it reads. A kit-check gate over a current kit folder is
669
+ SWITCHED in place to node scripts/agent-workflow/run.mjs <name>, unless it is a customized entry below,
670
+ a flat scripts/<file> only when nothing stands at that path; any other form naming a kit check is kept, named with its repoint. Customized entries are
654
671
  NEVER auto-touched — the preview names each with a paste-ready recovery, and the commit guard
655
672
  must not be installed until they are resolved.`;
656
673
 
@@ -1,13 +1,16 @@
1
1
  #!/usr/bin/env node
2
- // Idempotent installer for the project's git hooks.
2
+ // Idempotent installer for the project's git hooks: `node scripts/agent-workflow/run.mjs install-git-hooks`.
3
3
  //
4
4
  // Installs the `pre-commit` hook running the docs cap-validator + index-freshness
5
- // gate + changelog/issues rotation-freshness checks + the `scripts/` test
6
- // suite, so docs files cannot drift over their declared `maxLines`, the auto-generated
7
- // `index.md` navigator cannot silently fall out of sync, stale archive entries never
8
- // reach a commit, and regressions to the scripts themselves are caught at commit time.
5
+ // gate + changelog/issues/decisions rotation-freshness checks, each through the stable kit
6
+ // command `node scripts/agent-workflow/run.mjs <name>`, so docs files cannot drift over their declared
7
+ // `maxLines`, the auto-generated `index.md` navigator cannot silently fall out of sync, and
8
+ // stale archive entries never reach a commit. The hook runs no suite.
9
9
  // First after `set -e` it runs the project's own `scripts/pre-commit.local` with bash when present.
10
10
  //
11
+ // The project root is three levels above this file's own folder (scripts/agent-workflow/git-hooks/):
12
+ // the installer imports nothing, so the bytes a danger check binds are the bytes the run executes.
13
+ //
11
14
  // The hooks location comes from git's OWN answer (`git rev-parse --git-path hooks`) — a linked
12
15
  // worktree resolves ITS OWN hooks path (its `.git` is a FILE; a hardcoded `.git/hooks` would
13
16
  // miss or mis-write).
@@ -29,32 +32,26 @@
29
32
  // and is carried forward by flagless re-runs exactly as the guard is; no flag disarms either.
30
33
  //
31
34
  // Package-manager-agnostic: the hook calls the scripts via `node` directly (no pnpm/npm
32
- // assumption). Re-running is safe — the script detects a previously installed hook via
33
- // the MAGIC_MARKER comment and rewrites only that file.
35
+ // assumption). Re-running is safe — the script reads a hook as its own when a line of it, one
36
+ // trailing carriage return dropped, ends with `:install-git-hooks.mjs` (the MAGIC_MARKER names no
37
+ // project, and an older project-named marker still reads as managed) and rewrites only that file.
34
38
  //
35
39
  // To bypass once (only when truly justified): `git commit --no-verify`.
36
40
 
37
41
  import { writeFile, readFile, mkdir, chmod } from 'node:fs/promises';
38
- import { existsSync, readFileSync } from 'node:fs';
42
+ import { existsSync, realpathSync } from 'node:fs';
39
43
  import { dirname, resolve, basename } from 'node:path';
40
44
  import { fileURLToPath } from 'node:url';
41
45
  import { spawnSync } from 'node:child_process';
42
46
 
43
47
  const __filename = fileURLToPath(import.meta.url);
44
48
  const __dirname = dirname(__filename);
45
- const ROOT = resolve(__dirname, '..');
46
-
47
- const readProjectName = () => {
48
- try {
49
- const pkg = JSON.parse(readFileSync(resolve(ROOT, 'package.json'), 'utf8'));
50
- if (pkg.name) return pkg.name;
51
- } catch {
52
- /* no package.json — fall back to repo dir basename */
53
- }
54
- return basename(ROOT);
55
- };
49
+ const ROOT = resolve(__dirname, '..', '..', '..');
56
50
 
57
- const MAGIC_MARKER = `# ${readProjectName()}:install-git-hooks.mjs`;
51
+ export const MAGIC_MARKER = '# agent-workflow:install-git-hooks.mjs';
52
+ const MARKER_TAIL = ':install-git-hooks.mjs';
53
+ // A hook is this installer's when a line of it, one trailing carriage return dropped, ends with the marker tail.
54
+ export const isManaged = (hook) => hook.split('\n').some((l) => l.replace(/\r$/, '').endsWith(MARKER_TAIL));
58
55
 
59
56
  // git's own hooks location (worktree-correct), or null outside a git checkout.
60
57
  const gitHooksDir = () => {
@@ -133,7 +130,7 @@ const resolveRoleFlag = (argv, { flag, file }) => {
133
130
  // leaves it out, more than one fails CLOSED naming the role.
134
131
  const carriedRolePath = (existingHook, { role, re }) => {
135
132
  if (existingHook === null) return null;
136
- const matches = existingHook.split('\n').map((l) => re.exec(l)).filter(Boolean);
133
+ const matches = existingHook.split('\n').map((l) => re.exec(l.replace(/\r$/, ''))).filter(Boolean);
137
134
  if (matches.length > 1) {
138
135
  console.error(`[install-git-hooks] the managed pre-commit hook carries ${matches.length} ${role} lines — ambiguous; remove the duplicates by hand and re-run (refusing to guess)`);
139
136
  process.exit(1);
@@ -146,7 +143,7 @@ const carriedRolePath = (existingHook, { role, re }) => {
146
143
  // ambiguous and fails CLOSED (an installer must never guess which line was the real guard).
147
144
  const carriedGuardPath = (existingHook) => {
148
145
  if (existingHook === null) return null;
149
- const matches = existingHook.split('\n').map((l) => GUARD_LINE_RE.exec(l)).filter(Boolean);
146
+ const matches = existingHook.split('\n').map((l) => GUARD_LINE_RE.exec(l.replace(/\r$/, ''))).filter(Boolean);
150
147
  if (matches.length > 1) {
151
148
  console.error(`[install-git-hooks] the managed pre-commit hook carries ${matches.length} commit-guard --check lines — ambiguous; remove the duplicates by hand and re-run (refusing to guess)`);
152
149
  process.exit(1);
@@ -156,20 +153,23 @@ const carriedGuardPath = (existingHook) => {
156
153
 
157
154
  const preCommitContent = (guardPath, rolePaths = []) => `#!/usr/bin/env bash
158
155
  ${MAGIC_MARKER}
159
- # Auto-installed by scripts/install-git-hooks.mjs (run it from "prepare" or by hand).
156
+ # Auto-installed by node scripts/agent-workflow/run.mjs install-git-hooks (run it by hand or from the kit).
160
157
  # Runs the docs cap-validator + index-freshness gate + rotation-freshness checks
161
- # + the scripts/ test suite before every commit, so files cannot drift over their
162
- # declared maxLines, the auto-generated index.md cannot silently go stale, stale
163
- # archive entries never reach a commit, and regressions to the scripts are caught.
158
+ # before every commit, so files cannot drift over their declared maxLines, the
159
+ # auto-generated index.md cannot silently go stale, and stale archive entries
160
+ # never reach a commit.
164
161
  set -e
165
162
  # Your own commit checks go in scripts/pre-commit.local; it runs first, with bash, when present.
166
163
  if [ -f scripts/pre-commit.local ]; then bash scripts/pre-commit.local; fi
167
- node scripts/check-docs-size.mjs
168
- node scripts/check-docs-size.mjs --check-index
169
- node scripts/archive-changelog.mjs --check
170
- node scripts/archive-issues.mjs --check
171
- node scripts/archive-decisions.mjs --check
172
- node --test scripts/*.test.mjs
164
+ if [ -f scripts/agent-workflow/run.mjs ]; then
165
+ node scripts/agent-workflow/run.mjs docs-size
166
+ node scripts/agent-workflow/run.mjs docs-size --check-index
167
+ node scripts/agent-workflow/run.mjs archive-changelog --check
168
+ node scripts/agent-workflow/run.mjs archive-issues --check
169
+ node scripts/agent-workflow/run.mjs archive-decisions --check
170
+ else
171
+ echo "scripts/agent-workflow/run.mjs is not in this checkout — the kit's docs and archive checks are skipped for this commit; merge the commit that adds scripts/agent-workflow/, or run the kit's upgrade in this checkout"
172
+ fi
173
173
  ${rolePaths.map((path, at) => (path ? `node "${path}" --check # ${ROLES[at].role}\n` : '')).join('')}${guardPath ? `node "${guardPath}" --check\n` : ''}`;
174
174
 
175
175
  const main = async () => {
@@ -185,7 +185,7 @@ const main = async () => {
185
185
  let existing = null;
186
186
  if (existsSync(preCommitPath)) {
187
187
  existing = await readFile(preCommitPath, 'utf8');
188
- if (!existing.includes(MAGIC_MARKER)) {
188
+ if (!isManaged(existing)) {
189
189
  console.warn(
190
190
  `[install-git-hooks] WARNING: ${preCommitPath} exists and was not installed by this script. Refusing to overwrite — remove or merge it manually.`,
191
191
  );
@@ -205,11 +205,23 @@ const main = async () => {
205
205
  await writeFile(preCommitPath, content, 'utf8');
206
206
  await chmod(preCommitPath, 0o755);
207
207
  console.log(
208
- `[install-git-hooks] installed ${preCommitPath} (docs caps + index freshness + archive checks + scripts/ tests${rolePaths.map((path, at) => (path ? ` + ${ROLES[at].role}` : '')).join('')}${guardPath ? ' + commit guard' : ''}).`,
208
+ `[install-git-hooks] installed ${preCommitPath} (docs caps + index freshness + archive checks${rolePaths.map((path, at) => (path ? ` + ${ROLES[at].role}` : '')).join('')}${guardPath ? ' + commit guard' : ''}).`,
209
209
  );
210
210
  };
211
211
 
212
- main().catch((err) => {
213
- console.error(err);
214
- process.exit(1);
215
- });
212
+ // Run main() only when executed directly, never on import; compare by REAL path so a symlinked entry still runs.
213
+ const isDirectRun = (() => {
214
+ const invoked = process.argv[1];
215
+ if (!invoked) return false;
216
+ try {
217
+ return realpathSync(invoked) === realpathSync(__filename);
218
+ } catch {
219
+ return false;
220
+ }
221
+ })();
222
+ if (isDirectRun) {
223
+ main().catch((err) => {
224
+ console.error(err);
225
+ process.exit(1);
226
+ });
227
+ }