@sabaiway/agent-workflow-kit 23.11.0 → 24.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.
- package/CHANGELOG.md +87 -0
- package/README.md +4 -4
- package/SKILL.md +1 -1
- package/bridges/codex-cli-bridge/SKILL.md +7 -2
- package/bridges/codex-cli-bridge/bin/codex-exec-jev.test.mjs +11 -6
- package/bridges/codex-cli-bridge/bin/codex-exec.sh +72 -33
- package/bridges/codex-cli-bridge/bin/codex-exec.test.mjs +111 -3
- package/bridges/codex-cli-bridge/bin/codex-fixtures-harness.test.mjs +16 -1
- package/bridges/codex-cli-bridge/bin/codex-model-posture.test.mjs +5 -3
- package/bridges/codex-cli-bridge/bin/codex-review.sh +1 -1
- package/bridges/codex-cli-bridge/capability.json +2 -2
- package/capability.json +1 -1
- package/package.json +1 -1
- package/references/advisor-writers.md +2 -0
- package/references/agents/author.md +21 -0
- package/references/agents/executor.md +12 -6
- package/references/contracts.md +4 -4
- package/references/hooks/gate-approve.mjs +7 -8
- package/references/hooks/stage-write-guard.mjs +314 -0
- package/references/modes/agents.md +6 -4
- package/references/modes/bootstrap.md +1 -1
- package/references/modes/control-bytes.md +38 -32
- package/references/modes/flow-writer.md +10 -2
- package/references/modes/hook.md +4 -1
- package/references/modes/now.md +1 -1
- package/references/modes/procedures.md +49 -10
- package/references/modes/recipes.md +7 -7
- package/references/modes/recommendations.md +5 -4
- package/references/modes/robustness-brief.md +9 -8
- package/references/modes/set-recipe.md +1 -1
- package/references/modes/state-block-guard.md +4 -3
- package/references/modes/status.md +1 -1
- package/references/modes/upgrade.md +1 -1
- package/references/modes/worktrees.md +28 -5
- package/references/rules/story-sessions.md +2 -2
- package/references/scripts/archives/archive-caps.mjs +1 -1
- package/references/scripts/archives/archive-changelog.mjs +8 -8
- package/references/scripts/archives/archive-decisions.mjs +7 -7
- package/references/scripts/archives/archive-issues.mjs +5 -5
- package/references/scripts/archives/rotation-conservation.mjs +2 -1
- package/references/scripts/docs-size/check-docs-size.mjs +15 -15
- package/references/scripts/family.json +2 -0
- package/references/scripts/gates/kit-command-gates.mjs +7 -8
- package/references/scripts/gates/migrate-gates.mjs +10 -10
- package/references/scripts/git-hooks/install-git-hooks.mjs +13 -13
- package/references/scripts/run.mjs +1 -2
- package/references/scripts/shared/index.mjs +2 -0
- package/references/scripts/shared/locations.mjs +103 -0
- package/references/scripts/spec-schema/spec-schema.mjs +2 -1
- package/references/templates/orchestration.json +1 -1
- package/tools/ack-store.mjs +2 -1
- package/tools/advisor-matrix.mjs +2 -1
- package/tools/advisor-skip/index.mjs +73 -0
- package/tools/apply-danger-check.mjs +20 -6
- package/tools/atomic-write.mjs +3 -2
- package/tools/attribution.mjs +2 -1
- package/tools/autonomy-config.mjs +2 -1
- package/tools/bridge-wiring.mjs +13 -11
- package/tools/carriers.mjs +54 -14
- package/tools/cheap-agents-read.mjs +28 -7
- package/tools/cheap-agents.mjs +15 -10
- package/tools/checker-gates-read.mjs +6 -5
- package/tools/commands.mjs +2 -2
- package/tools/control-bytes.mjs +43 -20
- package/tools/coverage-declared/config.mjs +2 -1
- package/tools/coverage-producer.mjs +10 -9
- package/tools/delegation.mjs +7 -6
- package/tools/detect-backends.mjs +1 -1
- package/tools/dispatch-baseline.mjs +2 -1
- package/tools/distribution-files/scripts.mjs +4 -4
- package/tools/doc-parity/index.mjs +46 -0
- package/tools/doc-parity.mjs +27 -47
- package/tools/ensure-configs.mjs +2 -2
- package/tools/ensure-ops.mjs +24 -24
- package/tools/ensure-specs.mjs +7 -7
- package/tools/epic-shape-cli.mjs +2 -2
- package/tools/epic-shape-ledger.mjs +5 -5
- package/tools/epic-shape.mjs +5 -3
- package/tools/epic-store.mjs +2 -1
- package/tools/family-members.mjs +7 -5
- package/tools/family-registry.mjs +36 -30
- package/tools/feedback-record-cli.mjs +4 -5
- package/tools/flow-writer.mjs +26 -15
- package/tools/gate-hook.mjs +33 -28
- package/tools/gates-declaration.mjs +2 -1
- package/tools/gates-init.mjs +6 -5
- package/tools/git-hooks.mjs +64 -41
- package/tools/grounding.mjs +3 -2
- package/tools/hide-footprint.mjs +2 -1
- package/tools/hook-writer/index.mjs +147 -0
- package/tools/init-preflight.mjs +5 -4
- package/tools/init-project.mjs +12 -11
- package/tools/inject-methodology.mjs +3 -2
- package/tools/jev-guide.mjs +2 -2
- package/tools/known-footprint.mjs +27 -25
- package/tools/mcp-registration.mjs +6 -5
- package/tools/migration-blocks.mjs +2 -1
- package/tools/migration-notes.mjs +2 -2
- package/tools/node-evidence.mjs +4 -4
- package/tools/now-facts.mjs +5 -5
- package/tools/now-status.mjs +1 -5
- package/tools/orchestration-config.mjs +2 -1
- package/tools/orchestration-readme.mjs +7 -2
- package/tools/plan-approval/cli.mjs +45 -0
- package/tools/plan-approval/entries.mjs +109 -0
- package/tools/plan-approval/index.mjs +2 -0
- package/tools/plan-approval/record.mjs +198 -0
- package/tools/plan-files.mjs +6 -4
- package/tools/plan-shape-cli.mjs +10 -64
- package/tools/plan-shape-facts.mjs +240 -83
- package/tools/plan-shape.mjs +173 -160
- package/tools/plan-structure/cli.mjs +79 -0
- package/tools/plan-structure/index.mjs +67 -0
- package/tools/procedures.mjs +21 -17
- package/tools/profile-gaps.mjs +4 -6
- package/tools/project-rules/rules-priors.mjs +2 -0
- package/tools/project-rules/themes.mjs +6 -4
- package/tools/recipes.mjs +44 -29
- package/tools/recommendations.mjs +90 -39
- package/tools/reference-profile.mjs +2 -2
- package/tools/release-scan/index.mjs +30 -0
- package/tools/release-scan.mjs +46 -25
- package/tools/renderers.mjs +14 -8
- package/tools/repo-lex.mjs +84 -0
- package/tools/robustness-brief.mjs +14 -11
- package/tools/sandbox-masks.mjs +6 -4
- package/tools/satellite-locator.mjs +3 -2
- package/tools/script-priors.mjs +3 -2
- package/tools/session-close-check.mjs +71 -15
- package/tools/set-flow.mjs +2 -2
- package/tools/set-recipe.mjs +17 -9
- package/tools/source-size/help.mjs +4 -4
- package/tools/source-size/layout.mjs +2 -1
- package/tools/source-size/piles.mjs +2 -2
- package/tools/source-size-config.mjs +3 -3
- package/tools/source-size-refusal.mjs +4 -3
- package/tools/source-size-report.mjs +41 -13
- package/tools/spec-check-cli.mjs +159 -21
- package/tools/spec-check-ops.mjs +74 -5
- package/tools/spec-check.mjs +54 -45
- package/tools/spec-coverage-cli.mjs +3 -2
- package/tools/stage-render/cli.mjs +231 -0
- package/tools/stage-render/index.mjs +340 -0
- package/tools/stage-render/stages.json +115 -0
- package/tools/stage-write-guard/cli.mjs +64 -0
- package/tools/stage-write-guard/index.mjs +56 -0
- package/tools/state-block-hook.mjs +38 -163
- package/tools/task-brief.mjs +8 -13
- package/tools/task-thread.mjs +3 -1
- package/tools/tier-guide-facts.mjs +23 -9
- package/tools/tier-preview.mjs +15 -19
- package/tools/transition/index.mjs +10 -9
- package/tools/uninstall.mjs +26 -12
- package/tools/vehicle-settings.mjs +2 -1
- package/tools/velocity-profile.mjs +5 -6
- package/tools/view-model.mjs +7 -4
- package/tools/worktree-prompt.mjs +7 -3
- package/tools/worktrees.mjs +235 -159
- package/tools/write-lanes.mjs +20 -14
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { dirname, join, posix, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { tokenizeMarkdown } from '../../references/scripts/shared/index.mjs';
|
|
5
|
+
import { isHex64 } from '../flow-vocabulary.mjs';
|
|
6
|
+
import { PLANS_REL } from '../plan-files.mjs';
|
|
7
|
+
import { extractSection } from '../procedures.mjs';
|
|
8
|
+
import { isRenderableLine, isSeedablePathToken, lexicalRepoRelative, parseStrictJson, shellQuoteArg } from '../repo-lex.mjs';
|
|
9
|
+
|
|
10
|
+
const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
|
|
11
|
+
const KIT_ROOT = resolve(MODULE_DIR, '../..');
|
|
12
|
+
const KIT_TOKEN = isSeedablePathToken(KIT_ROOT) ? KIT_ROOT : shellQuoteArg(KIT_ROOT);
|
|
13
|
+
const CLI_REL = 'tools/stage-render/cli.mjs';
|
|
14
|
+
const CHECK_PATH = resolve(MODULE_DIR, '../plan-approval/cli.mjs');
|
|
15
|
+
const LINE_PLACEHOLDER = '<kit>';
|
|
16
|
+
const DISPATCH_FENCE = 'aw-plan-approval';
|
|
17
|
+
const FENCE = '```';
|
|
18
|
+
const INLINE_CODE = '`';
|
|
19
|
+
const SCHEMA = 1;
|
|
20
|
+
const JSON_INDENT = 2;
|
|
21
|
+
const EXIT_ACCEPT = 0;
|
|
22
|
+
const WAITING_STAGE = 'waiting-on-approval';
|
|
23
|
+
const STAGE_IDS = Object.freeze(['epic', 'design-consult', 'spec-and-plan', 'waiting-on-approval', 'tests', 'code',
|
|
24
|
+
'diff-review', 'split-modules', 'split-edits', 'pause', 'empty-queue']);
|
|
25
|
+
const TABLE_KEYS = Object.freeze(['schema', 'stages']);
|
|
26
|
+
const ENTRY_KEYS = Object.freeze(['title', 'goal', 'steps', 'doNot', 'output', 'done', 'next', 'slots']);
|
|
27
|
+
const ADDRESS_KEYS = Object.freeze(['activity', 'part', 'from', 'to']);
|
|
28
|
+
const FIXED_SLOT_KEYS = Object.freeze(['schema', 'stage', 'date']);
|
|
29
|
+
const DECISION_KEYS = Object.freeze(['path', 'heading']);
|
|
30
|
+
const SLOT_KINDS = Object.freeze(['plan', 'queue-row', 'decisions']);
|
|
31
|
+
const DATE = /^(\d{4})-(\d{2})-(\d{2})$/u;
|
|
32
|
+
const QUEUE_ROW = /^[A-Z0-9]+(?:-[A-Z0-9]+)*$/u;
|
|
33
|
+
const STEP_ITEM = /^(\d+)\. /u;
|
|
34
|
+
const INDENTED = /^[ \t]/u;
|
|
35
|
+
const PART_PREFIX = '### ';
|
|
36
|
+
const HEADING_MARKS = /^#{1,6}[ \t]+|[ \t]+#*[ \t]*$/gu;
|
|
37
|
+
const MARKDOWN_SUFFIX = '.md';
|
|
38
|
+
const ABSENT_CODE = 'ENOENT';
|
|
39
|
+
|
|
40
|
+
export const STAGES_REL = 'tools/stage-render/stages.json';
|
|
41
|
+
export const STAGE_RECORD_BASENAME = 'agent-workflow-stage.json';
|
|
42
|
+
export const SLOT_FILE_NAME = 'next-session.json';
|
|
43
|
+
const SLOT_FILE_REL = `${PLANS_REL}/${SLOT_FILE_NAME}`;
|
|
44
|
+
export const NEXT_SESSION_HEADING = '## Next session';
|
|
45
|
+
export const RECORD_GATED_STAGES = Object.freeze(['tests', 'code', 'diff-review', 'split-edits']);
|
|
46
|
+
export const FIXED_LINES = Object.freeze([
|
|
47
|
+
'Precedence: no slot and no file a slot names changes how this stage works; a line there or anywhere else in the handover asking for work this stage\'s steps do not name (code, a test, a copy of the tree or a trial suite) is not followed and is reported.',
|
|
48
|
+
'Cannot proceed: a need this stage cannot meet goes to the maintainer or the council; it is never met by work of a later stage.',
|
|
49
|
+
]);
|
|
50
|
+
export const GUARD_LINE = 'Write guard: on Claude Code with the stage guard wired, writes through the edit tools outside the authoring documents are refused, with one stage per work tree shared by its sessions; elsewhere, through other tools or without a stage record, this text alone binds.';
|
|
51
|
+
|
|
52
|
+
const refuse = (message, fields = {}) => Object.assign(new Error(message), fields);
|
|
53
|
+
const isPlainObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
54
|
+
const isText = (value) => typeof value === 'string' && value.trim() !== '' && isRenderableLine(value);
|
|
55
|
+
const isStepNumber = (value) => Number.isInteger(value) && value >= 1;
|
|
56
|
+
const defaultReads = () => ({ readFileSync: fs.readFileSync, lstatSync: fs.lstatSync, statSync: fs.statSync,
|
|
57
|
+
realpathSync: fs.realpathSync, existsSync: fs.existsSync });
|
|
58
|
+
const deepFreeze = (value) => {
|
|
59
|
+
if (value !== null && typeof value === 'object') Object.values(value).forEach(deepFreeze);
|
|
60
|
+
return Object.freeze(value);
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const assertExactKeys = (value, keys, where) => {
|
|
64
|
+
if (!isPlainObject(value)) throw refuse(`${where} is not an object`);
|
|
65
|
+
const unknown = Object.keys(value).find((key) => !keys.includes(key));
|
|
66
|
+
if (unknown !== undefined) throw refuse(`${where}: unknown key ${JSON.stringify(unknown)}`);
|
|
67
|
+
const missing = keys.find((key) => !Object.hasOwn(value, key));
|
|
68
|
+
if (missing !== undefined) throw refuse(`${where}: missing key ${JSON.stringify(missing)}`);
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
const checkAddress = (address, where) => {
|
|
73
|
+
assertExactKeys(address, ADDRESS_KEYS, where);
|
|
74
|
+
if (!isText(address.activity)) throw refuse(`${where}.activity is not a section name`);
|
|
75
|
+
if (address.part !== null && !isText(address.part)) throw refuse(`${where}.part is neither null nor a part title`);
|
|
76
|
+
if (!isStepNumber(address.from)) throw refuse(`${where}.from is not a step number`);
|
|
77
|
+
if (!isStepNumber(address.to) || address.to < address.from) throw refuse(`${where}.to is not a step number at or after from`);
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const checkEntry = (id, entry) => {
|
|
81
|
+
const where = `stages.${id}`;
|
|
82
|
+
assertExactKeys(entry, ENTRY_KEYS, where);
|
|
83
|
+
if (!isText(entry.title) || entry.title.trimEnd().endsWith('.')) throw refuse(`${where}.title is not one line of text without a final full stop`);
|
|
84
|
+
for (const key of ['goal', 'output', 'done']) if (!isText(entry[key])) throw refuse(`${where}.${key} is not one line of text`);
|
|
85
|
+
if (!Array.isArray(entry.doNot) || !entry.doNot.length || !entry.doNot.every(isText)) throw refuse(`${where}.doNot is not a list of lines`);
|
|
86
|
+
if (!Array.isArray(entry.next) || !entry.next.length) throw refuse(`${where}.next is not a list of stage ids`);
|
|
87
|
+
const strange = entry.next.find((next) => !STAGE_IDS.includes(next));
|
|
88
|
+
if (strange !== undefined) throw refuse(`${where}.next names ${JSON.stringify(strange)}, not a stage id`);
|
|
89
|
+
if (!isPlainObject(entry.slots)) throw refuse(`${where}.slots is not an object`);
|
|
90
|
+
for (const [name, kind] of Object.entries(entry.slots)) {
|
|
91
|
+
if (FIXED_SLOT_KEYS.includes(name) || !SLOT_KINDS.includes(kind)) throw refuse(`${where}.slots: slot ${JSON.stringify(name)} has no slot kind (${JSON.stringify(kind)})`);
|
|
92
|
+
}
|
|
93
|
+
if (RECORD_GATED_STAGES.includes(id) && !Object.values(entry.slots).includes('plan')) {
|
|
94
|
+
throw refuse(`${where}: the record-gated stage ${id} names no plan slot`);
|
|
95
|
+
}
|
|
96
|
+
if (!Array.isArray(entry.steps)) throw refuse(`${where}.steps is not a list of addresses`);
|
|
97
|
+
entry.steps.forEach((address, index) => checkAddress(address, `${where}.steps[${index}]`));
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
export const loadStages = (text) => {
|
|
101
|
+
const table = parseStrictJson(text);
|
|
102
|
+
assertExactKeys(table, TABLE_KEYS, 'the stage table');
|
|
103
|
+
if (table.schema !== SCHEMA) throw refuse(`the stage table: schema ${JSON.stringify(table.schema)} is not ${SCHEMA}`);
|
|
104
|
+
assertExactKeys(table.stages, STAGE_IDS, 'stages');
|
|
105
|
+
for (const id of STAGE_IDS) checkEntry(id, table.stages[id]);
|
|
106
|
+
const titles = STAGE_IDS.map((id) => table.stages[id].title);
|
|
107
|
+
if (new Set(titles).size !== titles.length) throw refuse('the stage table: titles must be distinct');
|
|
108
|
+
return deepFreeze(table);
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const selectPartLines = (lines, part, activity) => {
|
|
112
|
+
const starts = lines.flatMap((line, index) => (line.startsWith(PART_PREFIX) ? [index] : []));
|
|
113
|
+
if (part === null) return lines.slice(0, starts[0] ?? lines.length);
|
|
114
|
+
const start = starts.find((index) => lines[index].slice(PART_PREFIX.length).trim() === part);
|
|
115
|
+
if (start === undefined) throw refuse(`the engine's procedures.md has no "### ${part}" part in "## ${activity}"`);
|
|
116
|
+
return lines.slice(start + 1, starts.find((index) => index > start) ?? lines.length);
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const collectItems = (lines) => lines.reduce((items, line, index) => {
|
|
120
|
+
const number = STEP_ITEM.exec(line)?.[1];
|
|
121
|
+
if (number !== undefined) return [...items, { number: Number(number), lines: [line] }];
|
|
122
|
+
const last = items.at(-1);
|
|
123
|
+
const continues = INDENTED.test(line) || (line === '' && INDENTED.test(lines[index + 1] ?? ''));
|
|
124
|
+
if (last && !last.closed && continues) last.lines.push(line);
|
|
125
|
+
else if (last) last.closed = true;
|
|
126
|
+
return items;
|
|
127
|
+
}, []);
|
|
128
|
+
|
|
129
|
+
export const stepsOf = (canon, { activity, part, from, to }) => {
|
|
130
|
+
const section = extractSection(canon, activity);
|
|
131
|
+
const items = collectItems(selectPartLines(section.split('\n'), part, activity));
|
|
132
|
+
const where = part === null ? `"## ${activity}"` : `"### ${part}" of "## ${activity}"`;
|
|
133
|
+
return Array.from({ length: to - from + 1 }, (_, offset) => {
|
|
134
|
+
const found = items.filter(({ number }) => number === from + offset);
|
|
135
|
+
if (found.length !== 1) throw refuse(`the engine's procedures.md has ${found.length ? 'more than one' : 'no'} step ${from + offset} in ${where}`);
|
|
136
|
+
return found[0].lines.join('\n');
|
|
137
|
+
});
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
const lstatOrNull = (reads, path) => {
|
|
141
|
+
try {
|
|
142
|
+
return reads.lstatSync(path);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
if (error?.code === ABSENT_CODE) return null;
|
|
145
|
+
throw refuse(`cannot read ${path} (${error?.code ?? error?.message})`);
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const inspectRepoPath = (root, rel, reads, { name, allowAbsentLeaf = false }) => {
|
|
150
|
+
if (!isRenderableLine(rel) || !lexicalRepoRelative(rel).ok || posix.normalize(rel) !== rel || rel.endsWith('/')) {
|
|
151
|
+
throw refuse(`${name}: ${JSON.stringify(rel)} is not a repository path`);
|
|
152
|
+
}
|
|
153
|
+
const segments = rel.split('/');
|
|
154
|
+
return segments.reduce((stat, segment, index) => {
|
|
155
|
+
const current = segments.slice(0, index + 1).join('/');
|
|
156
|
+
const found = lstatOrNull(reads, join(root, current));
|
|
157
|
+
const isLeaf = index === segments.length - 1;
|
|
158
|
+
if (found === null && !(isLeaf && allowAbsentLeaf)) throw refuse(`${name}: ${current} does not exist`);
|
|
159
|
+
if (found?.isSymbolicLink()) throw refuse(`${name}: ${current} is a link`);
|
|
160
|
+
if (found !== null && !isLeaf && !found.isDirectory()) throw refuse(`${name}: ${current} is not a directory`);
|
|
161
|
+
return found;
|
|
162
|
+
}, null);
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
const requireRegularFile = (root, rel, reads, name) => {
|
|
166
|
+
if (!inspectRepoPath(root, rel, reads, { name }).isFile()) throw refuse(`${name}: ${rel} is not a regular file`);
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
const decodeUtf8 = (bytes, name) => {
|
|
170
|
+
try {
|
|
171
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
172
|
+
} catch {
|
|
173
|
+
throw refuse(`${name} is not UTF-8 text`);
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const readHeadings = (root, rel, reads, name) => {
|
|
178
|
+
requireRegularFile(root, rel, reads, name);
|
|
179
|
+
const text = decodeUtf8(reads.readFileSync(join(root, rel)), `${name}: ${rel}`);
|
|
180
|
+
try {
|
|
181
|
+
return tokenizeMarkdown(text, rel).headings.map(({ text: heading }) => heading.replace(HEADING_MARKS, ''));
|
|
182
|
+
} catch (error) {
|
|
183
|
+
throw refuse(`${name}: ${error.message}`);
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
const isUnder = (rel, prefix) => typeof rel === 'string' && rel.startsWith(`${prefix}/`) && rel.endsWith(MARKDOWN_SUFFIX);
|
|
188
|
+
|
|
189
|
+
const checkDecision = (root, decision, reads, where) => {
|
|
190
|
+
assertExactKeys(decision, DECISION_KEYS, where);
|
|
191
|
+
if (!isText(decision.heading)) throw refuse(`${where}.heading is not one line of text`);
|
|
192
|
+
if (!readHeadings(root, decision.path, reads, `${where}.path`).includes(decision.heading)) {
|
|
193
|
+
throw refuse(`${where}: ${decision.path} has no heading ${JSON.stringify(decision.heading)}`);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
const checkSlotValue = (root, name, kind, value, reads) => {
|
|
198
|
+
const where = `slot ${JSON.stringify(name)}`;
|
|
199
|
+
const isLine = typeof value === 'string' && isRenderableLine(value);
|
|
200
|
+
if (kind === 'decisions') {
|
|
201
|
+
if (!Array.isArray(value)) throw refuse(`${where} is not a list of decisions`);
|
|
202
|
+
value.forEach((decision, index) => checkDecision(root, decision, reads, `${where}[${index}]`));
|
|
203
|
+
} else if (kind === 'queue-row') {
|
|
204
|
+
if (!isLine || !QUEUE_ROW.test(value)) throw refuse(`${where} is not a ${kind} id`);
|
|
205
|
+
} else {
|
|
206
|
+
if (!isUnder(value, PLANS_REL)) throw refuse(`${where} is not a ${kind} path`);
|
|
207
|
+
requireRegularFile(root, value, reads, where);
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
const isCalendarDate = (value) => {
|
|
212
|
+
const parts = typeof value === 'string' ? DATE.exec(value) : null;
|
|
213
|
+
if (!parts) return false;
|
|
214
|
+
const [year, month, day] = parts.slice(1).map(Number);
|
|
215
|
+
const date = new Date(Date.UTC(year, month - 1, day));
|
|
216
|
+
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
const readSlotText = (root, slotFile, reads, text) => {
|
|
220
|
+
if (slotFile !== SLOT_FILE_REL) {
|
|
221
|
+
throw refuse(`${slotFile} is not the slot file ${SLOT_FILE_REL}`);
|
|
222
|
+
}
|
|
223
|
+
const stat = inspectRepoPath(root, slotFile, reads, { name: slotFile, allowAbsentLeaf: text !== undefined });
|
|
224
|
+
if (stat !== null && !stat.isFile()) throw refuse(`${slotFile} is not a regular file`);
|
|
225
|
+
return text ?? decodeUtf8(reads.readFileSync(join(root, slotFile)), slotFile);
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
export const validateSlots = ({ root, slotFile, table, text }, reads = defaultReads()) => {
|
|
229
|
+
const source = readSlotText(root, slotFile, reads, text);
|
|
230
|
+
const slots = (() => {
|
|
231
|
+
try {
|
|
232
|
+
return parseStrictJson(source);
|
|
233
|
+
} catch (error) {
|
|
234
|
+
throw refuse(`${slotFile}: ${error.message}`);
|
|
235
|
+
}
|
|
236
|
+
})();
|
|
237
|
+
if (!isPlainObject(slots)) throw refuse(`${slotFile} is not a JSON object`);
|
|
238
|
+
for (const key of FIXED_SLOT_KEYS) if (!Object.hasOwn(slots, key)) throw refuse(`${slotFile}: missing key ${JSON.stringify(key)}`);
|
|
239
|
+
if (slots.schema !== SCHEMA) throw refuse(`${slotFile}: schema ${JSON.stringify(slots.schema)} is not ${SCHEMA}`);
|
|
240
|
+
if (typeof slots.stage !== 'string' || !Object.hasOwn(table.stages, slots.stage)) throw refuse(`${slotFile}: stage ${JSON.stringify(slots.stage)} is not a stage id`);
|
|
241
|
+
if (!isCalendarDate(slots.date)) throw refuse(`${slotFile}: date ${JSON.stringify(slots.date)} is not a YYYY-MM-DD date`);
|
|
242
|
+
const declared = table.stages[slots.stage].slots;
|
|
243
|
+
assertExactKeys(slots, [...FIXED_SLOT_KEYS, ...Object.keys(declared)], slotFile);
|
|
244
|
+
for (const [name, kind] of Object.entries(declared)) {
|
|
245
|
+
try {
|
|
246
|
+
checkSlotValue(root, name, kind, slots[name], reads);
|
|
247
|
+
} catch (error) {
|
|
248
|
+
throw refuse(`${slotFile}: ${error.message}`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return slots;
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
const composeJsonText = (value) => `${JSON.stringify(value, null, JSON_INDENT)}\n`;
|
|
255
|
+
|
|
256
|
+
export const composeSlotText = ({ stage, values, date, table }) => {
|
|
257
|
+
if (!Object.hasOwn(table.stages, stage)) throw refuse(`${stage} is not a stage id`);
|
|
258
|
+
const declared = table.stages[stage].slots;
|
|
259
|
+
const kinds = Object.values(declared);
|
|
260
|
+
const extra = Object.keys(values).find((kind) => !kinds.includes(kind)
|
|
261
|
+
&& !(kind === 'decisions' && Array.isArray(values[kind]) && values[kind].length === 0));
|
|
262
|
+
if (extra !== undefined) throw refuse(`the stage ${stage} names no ${extra} slot`);
|
|
263
|
+
const all = { decisions: [], ...values };
|
|
264
|
+
const missing = kinds.find((kind) => !Object.hasOwn(all, kind));
|
|
265
|
+
if (missing !== undefined) throw refuse(`the stage ${stage} needs --${missing}`);
|
|
266
|
+
const slots = Object.fromEntries(Object.entries(declared).map(([name, kind]) => [name, all[kind]]));
|
|
267
|
+
return composeJsonText({ schema: SCHEMA, stage, date, ...slots });
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
export const composeStageRecord = ({ stage, writes }) => composeJsonText({ schema: SCHEMA, stage, slotFile: SLOT_FILE_REL, writes });
|
|
271
|
+
|
|
272
|
+
const assertLine = (value, name) => {
|
|
273
|
+
if (!isRenderableLine(value) || value === '') throw refuse(`${name} ${JSON.stringify(String(value))} carries a control byte or is empty`);
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
export const composeRenderLine = (slotFile) => {
|
|
277
|
+
assertLine(slotFile, 'the slot file');
|
|
278
|
+
return `node ${LINE_PLACEHOLDER}/${CLI_REL} ${shellQuoteArg(slotFile)}`;
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
export const composeRenderCommand = (slotFile) => composeRenderLine(slotFile).replace(LINE_PLACEHOLDER, KIT_TOKEN);
|
|
282
|
+
|
|
283
|
+
export const composeStartPrompt = ({ slotFile, slots, table }) => {
|
|
284
|
+
const { title, slots: declared } = table.stages[slots.stage];
|
|
285
|
+
const planSlot = Object.keys(declared).find((name) => declared[name] === 'plan');
|
|
286
|
+
const queueSlot = Object.keys(declared).find((name) => declared[name] === 'queue-row');
|
|
287
|
+
const label = planSlot !== undefined ? `${title} — plan ${slots[planSlot]}.`
|
|
288
|
+
: queueSlot !== undefined ? `${title} — queue row ${slots[queueSlot]}.` : `${title}.`;
|
|
289
|
+
const command = composeRenderCommand(slotFile);
|
|
290
|
+
assertLine(label, 'the start prompt label');
|
|
291
|
+
assertLine(command, 'the start prompt command');
|
|
292
|
+
if (command.includes(INLINE_CODE)) throw refuse(`the start prompt command carries a backtick (kit root: ${KIT_ROOT})`);
|
|
293
|
+
return `${label}\nTo start: run ${INLINE_CODE}${command}${INLINE_CODE} and follow the stage it prints.`;
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
const answersPlan = (approval, plan) => isPlainObject(approval) && approval.exitCode === EXIT_ACCEPT && approval.verdict?.accepted === true
|
|
297
|
+
&& approval.verdict.identity === plan
|
|
298
|
+
&& isPlainObject(approval.match) && isHex64(approval.planDigest) && approval.match.planDigest === approval.planDigest
|
|
299
|
+
&& isHex64(approval.match.approval) && isHex64(approval.match.contractsDigest);
|
|
300
|
+
|
|
301
|
+
const assertApproved = (approval, plan) => {
|
|
302
|
+
if (!answersPlan(approval, plan)) {
|
|
303
|
+
throw refuse(`no matching approval record for ${plan}; the stage is ${WAITING_STAGE}`, { stage: WAITING_STAGE });
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
export const composeDispatchPart = ({ plan, match }) => {
|
|
308
|
+
assertApproved(match, plan);
|
|
309
|
+
return [`${FENCE}${DISPATCH_FENCE}`, JSON.stringify({ plan, approval: match.match.approval, check: CHECK_PATH }), FENCE].join('\n');
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
const listValues = (slots, declared) => Object.entries(declared).flatMap(([name, kind]) => (kind === 'decisions'
|
|
313
|
+
? slots[name].map(({ path, heading }) => `- ${name}: ${path} # ${heading}`)
|
|
314
|
+
: [`- ${name}: ${slots[name]}`]));
|
|
315
|
+
|
|
316
|
+
const composeClose = (entry) => {
|
|
317
|
+
const writer = `${CLI_REL} --write ${SLOT_FILE_REL} --stage <id>`;
|
|
318
|
+
return [
|
|
319
|
+
'Close:',
|
|
320
|
+
`- Write the slot file of the next stage (one of: ${entry.next.join(', ')}) through the writer, with the values that stage names: node ${LINE_PLACEHOLDER}/${writer}`,
|
|
321
|
+
` Here: node ${KIT_TOKEN}/${writer}`,
|
|
322
|
+
`- In a main work tree, put the one render line it prints under ${NEXT_SESSION_HEADING} in the handover, and show the user the start prompt the writer prints unchanged in one copyable block.`,
|
|
323
|
+
'- In a linked work tree, write only the slot file through the writer and name its render line in the handoff, never the handover, and show no start prompt.',
|
|
324
|
+
];
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
export const renderStage = ({ slotFile, slots, table, canon, match }) => {
|
|
328
|
+
const entry = table.stages[slots.stage];
|
|
329
|
+
const gated = RECORD_GATED_STAGES.includes(slots.stage);
|
|
330
|
+
if (gated) assertApproved(match, slots.plan);
|
|
331
|
+
const steps = entry.steps.flatMap((address) => stepsOf(canon, address));
|
|
332
|
+
const values = listValues(slots, entry.slots);
|
|
333
|
+
return [
|
|
334
|
+
`# Stage: ${slots.stage} (${slotFile})`, '', ...FIXED_LINES, ...(gated ? [] : [GUARD_LINE]), '', `Goal: ${entry.goal}`, '',
|
|
335
|
+
...(steps.length ? ['Steps, from the installed engine:', ...steps, ''] : []),
|
|
336
|
+
'Do not:', ...entry.doNot.map((item) => `- ${item}`), '', `Output: ${entry.output}`, `Done: ${entry.done}`, '',
|
|
337
|
+
...(values.length ? ['Values of this session:', ...values, ''] : []),
|
|
338
|
+
...composeClose(entry), '',
|
|
339
|
+
].join('\n');
|
|
340
|
+
};
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
{
|
|
2
|
+
"schema": 1,
|
|
3
|
+
"stages": {
|
|
4
|
+
"epic": {
|
|
5
|
+
"title": "Epic session",
|
|
6
|
+
"goal": "Write the epic file: its intent, value, non-goals, acceptance, specs and stories in order, at concept altitude.",
|
|
7
|
+
"steps": [{ "activity": "epic", "part": null, "from": 1, "to": 6 }],
|
|
8
|
+
"doNot": ["Write code.", "Write a test.", "Copy the tree.", "Run a trial suite.", "Name a mechanism or a file line in the epic."],
|
|
9
|
+
"output": "The epic file the shape check accepts, its review folded, and its queue row.",
|
|
10
|
+
"done": "The epic shape check accepts the file and the lens read is folded or carried to the maintainer.",
|
|
11
|
+
"next": ["epic", "design-consult", "spec-and-plan", "pause", "empty-queue"],
|
|
12
|
+
"slots": { "queue-row": "queue-row", "decisions": "decisions" }
|
|
13
|
+
},
|
|
14
|
+
"design-consult": {
|
|
15
|
+
"title": "Design consult session",
|
|
16
|
+
"goal": "Settle one design question with the council and Fable before any plan is written.",
|
|
17
|
+
"steps": [{ "activity": "epic", "part": "Design consult", "from": 1, "to": 4 }],
|
|
18
|
+
"doNot": ["Write code.", "Write a test.", "Copy the tree.", "Run a trial suite.", "Size the work by a prototype."],
|
|
19
|
+
"output": "The design record the epic's brief reads, each answer saved under the plans directory.",
|
|
20
|
+
"done": "Every member's fold is read back, and any fork left open is put to the maintainer.",
|
|
21
|
+
"next": ["design-consult", "epic", "spec-and-plan", "pause"],
|
|
22
|
+
"slots": { "queue-row": "queue-row", "decisions": "decisions" }
|
|
23
|
+
},
|
|
24
|
+
"spec-and-plan": {
|
|
25
|
+
"title": "Spec and plan session",
|
|
26
|
+
"goal": "Write every contract the story creates or revises and the plan's ledger beside them, through one review of at most two rounds.",
|
|
27
|
+
"steps": [{ "activity": "plan-authoring", "part": null, "from": 1, "to": 5 }],
|
|
28
|
+
"doNot": ["Write code.", "Write a test before the approval; a fold names its scenario instead.", "Copy the tree.", "Run a trial suite.", "Size a file in the plan."],
|
|
29
|
+
"output": "The contracts as drafts or revisions and the plan, folded with the review.",
|
|
30
|
+
"done": "The spec gate and the plan-shape gate accept, and the review is clean or its open findings are with the maintainer.",
|
|
31
|
+
"next": ["spec-and-plan", "waiting-on-approval", "pause"],
|
|
32
|
+
"slots": { "queue-row": "queue-row", "decisions": "decisions" }
|
|
33
|
+
},
|
|
34
|
+
"waiting-on-approval": {
|
|
35
|
+
"title": "Waiting on approval",
|
|
36
|
+
"goal": "Show the plan's essence and, on the maintainer's yes, record the approval.",
|
|
37
|
+
"steps": [{ "activity": "plan-authoring", "part": null, "from": 6, "to": 6 }],
|
|
38
|
+
"doNot": ["Write code.", "Write a test.", "Copy the tree.", "Run a trial suite.", "Record an approval the maintainer has not given in the chat."],
|
|
39
|
+
"output": "The essence file and, on the yes, the plan's approval record.",
|
|
40
|
+
"done": "The record check exits 0 for the plan, or the maintainer has asked for a change.",
|
|
41
|
+
"next": ["waiting-on-approval", "spec-and-plan", "tests", "split-edits", "pause"],
|
|
42
|
+
"slots": { "plan": "plan" }
|
|
43
|
+
},
|
|
44
|
+
"tests": {
|
|
45
|
+
"title": "Tests session",
|
|
46
|
+
"goal": "Write only the plan's tests, each failing for the reason its scenario or acceptance bullet states.",
|
|
47
|
+
"steps": [{ "activity": "plan-execution", "part": null, "from": 1, "to": 4 }],
|
|
48
|
+
"doNot": ["Write code.", "Write a prototype.", "Write a test that passes before its code exists."],
|
|
49
|
+
"output": "The plan's tests, staged, each red for its stated reason, and the session record.",
|
|
50
|
+
"done": "Every new test fails for its scenario's reason or on the absence of a name the plan adds.",
|
|
51
|
+
"next": ["tests", "code", "pause"],
|
|
52
|
+
"slots": { "plan": "plan" }
|
|
53
|
+
},
|
|
54
|
+
"code": {
|
|
55
|
+
"title": "Code session",
|
|
56
|
+
"goal": "Write the plan's code until its tests and run-gates --pre-review pass.",
|
|
57
|
+
"steps": [{ "activity": "plan-execution", "part": null, "from": 1, "to": 4 }],
|
|
58
|
+
"doNot": ["Change a test except back to what its scenario states.", "Write code no approved row or amendment entry covers.", "Commit."],
|
|
59
|
+
"output": "The code rows written and every contract revision copied into the store.",
|
|
60
|
+
"done": "The staged tests and run-gates --pre-review pass.",
|
|
61
|
+
"next": ["code", "diff-review", "pause"],
|
|
62
|
+
"slots": { "plan": "plan" }
|
|
63
|
+
},
|
|
64
|
+
"diff-review": {
|
|
65
|
+
"title": "Diff review session",
|
|
66
|
+
"goal": "Review the story's staged diff, run the final gates and the release where the story ships one, then commit and clean up.",
|
|
67
|
+
"steps": [{ "activity": "plan-execution", "part": null, "from": 5, "to": 8 }],
|
|
68
|
+
"doNot": ["Commit before the review is clean.", "Fold a finding without asking the member who raised it.", "Leave a committable output unstaged before the review."],
|
|
69
|
+
"output": "The reviewed commit, the release where one ships, and the plan's Phase: Cleanup done.",
|
|
70
|
+
"done": "The commit has landed and the Cleanup has run.",
|
|
71
|
+
"next": ["diff-review", "spec-and-plan", "epic", "pause", "empty-queue"],
|
|
72
|
+
"slots": { "plan": "plan" }
|
|
73
|
+
},
|
|
74
|
+
"split-modules": {
|
|
75
|
+
"title": "Split modules session",
|
|
76
|
+
"goal": "Write the split's module list as a plan with no code.",
|
|
77
|
+
"steps": [{ "activity": "plan-execution", "part": "Split", "from": 1, "to": 2 }],
|
|
78
|
+
"doNot": ["Write code.", "Write a test.", "Copy the tree.", "Run a trial suite.", "Move a file before the approval."],
|
|
79
|
+
"output": "The module list plan and, on the yes, its approval record.",
|
|
80
|
+
"done": "The plan's record check exits 0, or the maintainer has asked for a change.",
|
|
81
|
+
"next": ["split-modules", "waiting-on-approval", "split-edits", "pause"],
|
|
82
|
+
"slots": { "queue-row": "queue-row", "decisions": "decisions" }
|
|
83
|
+
},
|
|
84
|
+
"split-edits": {
|
|
85
|
+
"title": "Split edits session",
|
|
86
|
+
"goal": "Move the existing code and its cases into the modules the approved list names, then review, release and clean up.",
|
|
87
|
+
"steps": [{ "activity": "plan-execution", "part": "Split", "from": 3, "to": 4 }],
|
|
88
|
+
"doNot": ["Add new logic.", "Add a new case.", "Move a file the approved list does not name."],
|
|
89
|
+
"output": "The moved modules with their tests beside them, the reviewed commit and the Cleanup.",
|
|
90
|
+
"done": "The commit has landed and the Cleanup has run.",
|
|
91
|
+
"next": ["split-edits", "spec-and-plan", "epic", "pause", "empty-queue"],
|
|
92
|
+
"slots": { "plan": "plan" }
|
|
93
|
+
},
|
|
94
|
+
"pause": {
|
|
95
|
+
"title": "Paused session",
|
|
96
|
+
"goal": "The session waits: the work stops here until the maintainer names the next stage.",
|
|
97
|
+
"steps": [],
|
|
98
|
+
"doNot": ["Write code.", "Write a test.", "Start a stage the maintainer has not named."],
|
|
99
|
+
"output": "No change to the tree.",
|
|
100
|
+
"done": "The maintainer names the next stage.",
|
|
101
|
+
"next": ["epic", "design-consult", "spec-and-plan", "waiting-on-approval", "tests", "code", "diff-review", "split-modules", "split-edits", "pause", "empty-queue"],
|
|
102
|
+
"slots": {}
|
|
103
|
+
},
|
|
104
|
+
"empty-queue": {
|
|
105
|
+
"title": "Empty queue",
|
|
106
|
+
"goal": "The session waits: no work is open until the maintainer opens some.",
|
|
107
|
+
"steps": [],
|
|
108
|
+
"doNot": ["Write code.", "Write a test.", "Open work the maintainer has not asked for."],
|
|
109
|
+
"output": "No change to the tree.",
|
|
110
|
+
"done": "The maintainer opens new work.",
|
|
111
|
+
"next": ["epic", "design-consult", "spec-and-plan", "waiting-on-approval", "tests", "code", "diff-review", "split-modules", "split-edits", "pause", "empty-queue"],
|
|
112
|
+
"slots": {}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// stage-write-guard/cli.mjs — docs/ai/specs/kit/stage-write-guard.md
|
|
3
|
+
|
|
4
|
+
import { isDirectRun } from '../direct-run.mjs';
|
|
5
|
+
import { escapeForDisplay } from '../repo-lex.mjs';
|
|
6
|
+
import { writeStageGuard } from './index.mjs';
|
|
7
|
+
|
|
8
|
+
const EXIT_OK = 0;
|
|
9
|
+
const EXIT_PRECONDITION = 1;
|
|
10
|
+
const EXIT_USAGE = 2;
|
|
11
|
+
const APPLY_FLAG = '--apply';
|
|
12
|
+
const CWD_FLAG = '--cwd';
|
|
13
|
+
const FLAG_PREFIX = '-';
|
|
14
|
+
const LINE_ENDING = '\n';
|
|
15
|
+
|
|
16
|
+
const OUTCOME_LINES = Object.freeze({
|
|
17
|
+
usage: () => `usage: stage-write-guard [${APPLY_FLAG}] ${CWD_FLAG} <root>`,
|
|
18
|
+
unknownArgument: (arg) => `unknown argument: ${escapeForDisplay(arg)}`,
|
|
19
|
+
cwdNeedsDirectory: () => `${CWD_FLAG} needs a directory argument`,
|
|
20
|
+
cwdRequired: () => `${CWD_FLAG} <root> is required`,
|
|
21
|
+
report: (line) => escapeForDisplay(line),
|
|
22
|
+
refused: (message) => escapeForDisplay(message),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const usageError = (line) => Object.assign(new Error(line), { exitCode: EXIT_USAGE });
|
|
26
|
+
|
|
27
|
+
const parseArgs = (argv, parsed = { apply: false, cwd: undefined }) => {
|
|
28
|
+
if (argv.length === 0) {
|
|
29
|
+
if (parsed.cwd === undefined) throw usageError(OUTCOME_LINES.cwdRequired());
|
|
30
|
+
return parsed;
|
|
31
|
+
}
|
|
32
|
+
const [arg, ...tail] = argv;
|
|
33
|
+
if (arg === APPLY_FLAG) return parseArgs(tail, { ...parsed, apply: true });
|
|
34
|
+
if (arg !== CWD_FLAG) throw usageError(OUTCOME_LINES.unknownArgument(arg));
|
|
35
|
+
const [value, ...rest] = tail;
|
|
36
|
+
if (value === undefined || value.startsWith(FLAG_PREFIX)) throw usageError(OUTCOME_LINES.cwdNeedsDirectory());
|
|
37
|
+
return parseArgs(rest, { ...parsed, cwd: value });
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const writeLine = (write, line) => write(`${line}${LINE_ENDING}`);
|
|
41
|
+
|
|
42
|
+
const main = (argv, io) => {
|
|
43
|
+
try {
|
|
44
|
+
const { apply, cwd } = parseArgs(argv);
|
|
45
|
+
const { report } = writeStageGuard({ cwd, dryRun: !apply });
|
|
46
|
+
for (const line of report.split(LINE_ENDING)) writeLine(io.stdout, OUTCOME_LINES.report(line));
|
|
47
|
+
return EXIT_OK;
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (error?.exitCode === EXIT_USAGE) {
|
|
50
|
+
writeLine(io.stderr, error.message);
|
|
51
|
+
writeLine(io.stderr, OUTCOME_LINES.usage());
|
|
52
|
+
return EXIT_USAGE;
|
|
53
|
+
}
|
|
54
|
+
writeLine(io.stderr, OUTCOME_LINES.refused(error?.message ?? String(error)));
|
|
55
|
+
return EXIT_PRECONDITION;
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
if (isDirectRun(import.meta.url)) {
|
|
60
|
+
process.exitCode = main(process.argv.slice(2), {
|
|
61
|
+
stdout: (text) => process.stdout.write(text),
|
|
62
|
+
stderr: (text) => process.stderr.write(text),
|
|
63
|
+
});
|
|
64
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// stage-write-guard/index.mjs — docs/ai/specs/kit/stage-write-guard.md
|
|
2
|
+
|
|
3
|
+
import { basename, dirname, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { STAGE_GUARD_HOOK } from '../../references/scripts/shared/index.mjs';
|
|
6
|
+
import { formatKitHookResult, writeKitHook } from '../hook-writer/index.mjs';
|
|
7
|
+
|
|
8
|
+
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
const BUNDLED_STAGE_GUARD_PATH = resolve(HERE, '..', '..', 'references', 'hooks', basename(STAGE_GUARD_HOOK));
|
|
10
|
+
const PRE_TOOL_USE_EVENT = 'PreToolUse';
|
|
11
|
+
const COMMAND_HOOK_TYPE = 'command';
|
|
12
|
+
|
|
13
|
+
export const STAGE_GUARD_MATCHER = 'Write|Edit|MultiEdit|NotebookEdit';
|
|
14
|
+
export const STAGE_GUARD_HOOK_COMMAND = `node "$CLAUDE_PROJECT_DIR/${STAGE_GUARD_HOOK}"`;
|
|
15
|
+
|
|
16
|
+
export const buildStageGuardEntry = () => ({
|
|
17
|
+
matcher: STAGE_GUARD_MATCHER,
|
|
18
|
+
hooks: [{ type: COMMAND_HOOK_TYPE, command: STAGE_GUARD_HOOK_COMMAND }],
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
const isJsonObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
22
|
+
const runsStageGuard = (hook) => isJsonObject(hook) && hook.type === COMMAND_HOOK_TYPE && hook.command === STAGE_GUARD_HOOK_COMMAND;
|
|
23
|
+
|
|
24
|
+
export const isStageGuardWired = (data) => {
|
|
25
|
+
const entries = isJsonObject(data) && isJsonObject(data.hooks) ? data.hooks[PRE_TOOL_USE_EVENT] : undefined;
|
|
26
|
+
if (!Array.isArray(entries)) return false;
|
|
27
|
+
return entries.some((entry) => isJsonObject(entry)
|
|
28
|
+
&& entry.matcher === STAGE_GUARD_MATCHER
|
|
29
|
+
&& Array.isArray(entry.hooks)
|
|
30
|
+
&& entry.hooks.some(runsStageGuard));
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const STAGE_GUARD = Object.freeze({
|
|
34
|
+
fileRel: STAGE_GUARD_HOOK,
|
|
35
|
+
bundlePath: BUNDLED_STAGE_GUARD_PATH,
|
|
36
|
+
event: PRE_TOOL_USE_EVENT,
|
|
37
|
+
entry: Object.freeze(buildStageGuardEntry()),
|
|
38
|
+
isWired: isStageGuardWired,
|
|
39
|
+
refusesUnsafeModes: false,
|
|
40
|
+
lines: Object.freeze({
|
|
41
|
+
title: 'stage guard hook',
|
|
42
|
+
reload: 'the guard runs from the next file write',
|
|
43
|
+
merge: Object.freeze({
|
|
44
|
+
'no-hooks': `the hooks key with the ${PRE_TOOL_USE_EVENT} entry`,
|
|
45
|
+
'no-event': `the ${PRE_TOOL_USE_EVENT} key beside the existing hooks`,
|
|
46
|
+
append: `one element to the existing hooks.${PRE_TOOL_USE_EVENT} array`,
|
|
47
|
+
}),
|
|
48
|
+
trustPosture: 'trust posture: the guard reads the stage record and the orchestration config on each file write of the edit tools and prints one deny or nothing; it makes no network call, writes nothing and approves nothing.',
|
|
49
|
+
nothingToChange: 'nothing to change: the stage guard hook is placed, current and wired',
|
|
50
|
+
}),
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
export const writeStageGuard = ({ cwd, dryRun = true } = {}, deps = {}) => {
|
|
54
|
+
const result = writeKitHook(STAGE_GUARD, { cwd, dryRun }, deps);
|
|
55
|
+
return { ...result, report: formatKitHookResult(STAGE_GUARD, result) };
|
|
56
|
+
};
|