@sabaiway/agent-workflow-kit 23.12.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 +58 -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/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 +4 -3
- 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/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/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/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 +84 -33
- package/tools/reference-profile.mjs +2 -2
- package/tools/renderers.mjs +14 -8
- package/tools/repo-lex.mjs +84 -0
- package/tools/robustness-brief.mjs +14 -11
- 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,231 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { writeContainedFileAtomic } from '../atomic-write.mjs';
|
|
7
|
+
import { isDirectRun } from '../direct-run.mjs';
|
|
8
|
+
import { PROCEDURES_FRAGMENT_REL, readEngineFragment, resolveEngineDir } from '../engine-source.mjs';
|
|
9
|
+
import { readRegularFileNoFollow } from '../fs-read-nofollow.mjs';
|
|
10
|
+
import { resolveGitLocation, stripGitLocationEnv } from '../git-env.mjs';
|
|
11
|
+
import { OUTCOME_LINES as APPROVAL_LINES, getLocalDate, readApproval } from '../plan-approval/index.mjs';
|
|
12
|
+
import { escapeForDisplay, isRenderableLine, isSeedablePathToken, shellQuoteArg } from '../repo-lex.mjs';
|
|
13
|
+
import {
|
|
14
|
+
RECORD_GATED_STAGES, STAGES_REL, STAGE_RECORD_BASENAME, composeDispatchPart, composeRenderCommand, composeRenderLine,
|
|
15
|
+
composeSlotText, composeStageRecord, composeStartPrompt, loadStages, renderStage, validateSlots,
|
|
16
|
+
} from './index.mjs';
|
|
17
|
+
|
|
18
|
+
const CLI_PATH = fileURLToPath(import.meta.url);
|
|
19
|
+
const CLI_TOKEN = isSeedablePathToken(CLI_PATH) ? CLI_PATH : shellQuoteArg(CLI_PATH);
|
|
20
|
+
const STAGES_PATH = resolve(dirname(CLI_PATH), '../..', STAGES_REL);
|
|
21
|
+
const WRITE = '--write';
|
|
22
|
+
const DISPATCH = '--dispatch';
|
|
23
|
+
const STAGE_FLAG = '--stage';
|
|
24
|
+
const DECISIONS_FLAG = '--decisions';
|
|
25
|
+
const DECISION_SEPARATOR = '#';
|
|
26
|
+
const VALUE_FLAGS = Object.freeze(['plan', 'queue-row']);
|
|
27
|
+
const WAITING_STAGE = 'waiting-on-approval';
|
|
28
|
+
const UPGRADE = 'upgrade the kit and its engine (/agent-workflow-kit upgrade)';
|
|
29
|
+
const START_HEADER = 'the start prompt, shown to the user unchanged:';
|
|
30
|
+
const WRITES_AUTHORING = 'authoring';
|
|
31
|
+
const WRITES_ANY = 'any';
|
|
32
|
+
const LOCATED = 'work-tree';
|
|
33
|
+
const NO_REPOSITORY = 'not-a-repository';
|
|
34
|
+
const EXIT_OK = 0;
|
|
35
|
+
const EXIT_REFUSE = 1;
|
|
36
|
+
const EXIT_USAGE = 2;
|
|
37
|
+
const LINE_ENDING = '\n';
|
|
38
|
+
const display = escapeForDisplay;
|
|
39
|
+
|
|
40
|
+
export const OUTCOME_LINES = Object.freeze({
|
|
41
|
+
usage: (reason) => `Usage: node ${display(CLI_TOKEN)} <slot file> | ${WRITE} <slot file> ${STAGE_FLAG} <id> [--plan <path>] [--queue-row <id>] [${DECISIONS_FLAG} <path>#<heading>]... | ${DISPATCH} <plan> — ${display(reason)}`,
|
|
42
|
+
cannotRender: (subject, reason) => `stage-render: CANNOT RENDER — ${display(subject)}: ${display(reason)}; ${UPGRADE}`,
|
|
43
|
+
refused: (subject, reason) => `stage-render: REFUSE — ${display(subject)}: ${display(reason)}`,
|
|
44
|
+
unapproved: (stage, plan, reason) => `stage-render: REFUSE — ${display(stage)} for ${display(plan)} waits for its approval record, so the stage is ${WAITING_STAGE}; ${APPROVAL_LINES.refused(plan, reason)}`,
|
|
45
|
+
finding: (plan, finding) => APPROVAL_LINES.finding(plan, finding),
|
|
46
|
+
malformed: (recordPath, line) => APPROVAL_LINES.malformed(recordPath, line),
|
|
47
|
+
unlocated: (reason) => `stage-render: ERROR — cannot locate the git directory of ${STAGE_RECORD_BASENAME}: ${display(reason)}`,
|
|
48
|
+
recordFailed: (recordPath, reason) => `stage-render: ERROR — cannot record the stage at ${display(recordPath)}: ${display(reason)}`,
|
|
49
|
+
writeFailed: (slotFile, reason) => `stage-render: ERROR — cannot write ${display(slotFile)}: ${display(reason)}`,
|
|
50
|
+
written: (slotFile) => `stage-render: WRITTEN — ${display(slotFile)}; its render line and the command that runs it here:`,
|
|
51
|
+
startHeader: () => START_HEADER,
|
|
52
|
+
text: (line) => display(line),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const halt = (exitCode, lines) => Object.assign(new Error(lines[0]), { exitCode, lines });
|
|
56
|
+
const isOperand = (value) => typeof value === 'string' && value !== '' && !value.startsWith('-');
|
|
57
|
+
|
|
58
|
+
const parseWriteFlags = (pairs) => pairs.reduce((flags, value, index) => {
|
|
59
|
+
if (flags === null || index % 2 === 1) return flags;
|
|
60
|
+
const flag = value;
|
|
61
|
+
const operand = pairs[index + 1];
|
|
62
|
+
const kind = flag.startsWith('--') ? flag.slice(2) : null;
|
|
63
|
+
if (flag === DECISIONS_FLAG && operand.includes(DECISION_SEPARATOR)) {
|
|
64
|
+
const cut = operand.indexOf(DECISION_SEPARATOR);
|
|
65
|
+
return { ...flags, decisions: [...flags.decisions, { path: operand.slice(0, cut), heading: operand.slice(cut + 1) }] };
|
|
66
|
+
}
|
|
67
|
+
if (flag === STAGE_FLAG && flags.stage === undefined && isOperand(operand)) return { ...flags, stage: operand };
|
|
68
|
+
if (VALUE_FLAGS.includes(kind) && !Object.hasOwn(flags.values, kind) && operand !== '') {
|
|
69
|
+
return { ...flags, values: { ...flags.values, [kind]: operand } };
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
}, { values: {}, decisions: [] });
|
|
73
|
+
|
|
74
|
+
const parseArgs = (argv) => {
|
|
75
|
+
const broken = argv.find((value) => !isRenderableLine(value));
|
|
76
|
+
if (broken !== undefined) return { usage: `${broken} carries a control byte` };
|
|
77
|
+
const [first, second, ...rest] = argv;
|
|
78
|
+
if (first === DISPATCH) return argv.length === 2 && isOperand(second) ? { command: DISPATCH, plan: second } : { usage: `${DISPATCH} takes one plan` };
|
|
79
|
+
if (first === WRITE) {
|
|
80
|
+
const flags = isOperand(second) && rest.length % 2 === 0 ? parseWriteFlags(rest) : null;
|
|
81
|
+
return flags?.stage === undefined ? { usage: `${WRITE} takes one slot file, ${STAGE_FLAG} once and known flags` } : { command: WRITE, slotFile: second, ...flags };
|
|
82
|
+
}
|
|
83
|
+
return argv.length === 1 && isOperand(first) ? { command: 'render', slotFile: first } : { usage: 'one slot file, --write or --dispatch' };
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const locateGitDir = ({ cwd, env }) => {
|
|
87
|
+
const location = resolveGitLocation(cwd, { env: stripGitLocationEnv(env) });
|
|
88
|
+
if (location.state === NO_REPOSITORY) return null;
|
|
89
|
+
if (location.state !== LOCATED) throw halt(EXIT_USAGE, [OUTCOME_LINES.unlocated(location.cause)]);
|
|
90
|
+
return location;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const isMainTree = (location) => location === null || location.gitDir === location.commonDir;
|
|
94
|
+
|
|
95
|
+
const recordStage = (location, slotFile, stage, writes) => {
|
|
96
|
+
if (location === null) return;
|
|
97
|
+
const recordPath = join(location.gitDir, STAGE_RECORD_BASENAME);
|
|
98
|
+
try {
|
|
99
|
+
writeContainedFileAtomic(location.gitDir, recordPath, composeStageRecord({ stage, slotFile, writes }), {}, { label: recordPath });
|
|
100
|
+
} catch (error) {
|
|
101
|
+
throw halt(EXIT_USAGE, [OUTCOME_LINES.recordFailed(recordPath, error.message)]);
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const loadTable = ({ stagesPath }) => {
|
|
106
|
+
const read = readRegularFileNoFollow(stagesPath);
|
|
107
|
+
if (read.outcome !== 'ok' || read.closeFailure) {
|
|
108
|
+
throw halt(EXIT_USAGE, [OUTCOME_LINES.cannotRender(STAGES_REL, `cannot read ${stagesPath} (${read.closeFailure ?? read.code ?? read.outcome})`)]);
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
return loadStages(read.content);
|
|
112
|
+
} catch (error) {
|
|
113
|
+
throw halt(EXIT_USAGE, [OUTCOME_LINES.cannotRender(STAGES_REL, error.message)]);
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
const requireApproval = ({ cwd, env, stderr }, plan, stage) => {
|
|
118
|
+
const approval = readApproval({ cwd, env, plan });
|
|
119
|
+
const malformed = (approval.malformedLines ?? []).map((line) => OUTCOME_LINES.malformed(approval.recordPath, line));
|
|
120
|
+
if (approval.exitCode === EXIT_OK) {
|
|
121
|
+
malformed.forEach(stderr);
|
|
122
|
+
return approval;
|
|
123
|
+
}
|
|
124
|
+
const findings = (approval.verdict?.result.findings ?? []).map((finding) => OUTCOME_LINES.finding(plan, finding));
|
|
125
|
+
throw halt(EXIT_REFUSE, [OUTCOME_LINES.unapproved(stage, plan, approval.reason), ...malformed, ...findings]);
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const readCanon = (env) => {
|
|
129
|
+
try {
|
|
130
|
+
const { dir, source } = resolveEngineDir({ env, home: homedir() });
|
|
131
|
+
return readEngineFragment(dir, { source, rel: PROCEDURES_FRAGMENT_REL });
|
|
132
|
+
} catch (error) {
|
|
133
|
+
throw halt(EXIT_USAGE, [OUTCOME_LINES.cannotRender(PROCEDURES_FRAGMENT_REL, error.message)]);
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const validate = (io, slotFile, table, text) => {
|
|
138
|
+
try {
|
|
139
|
+
return validateSlots({ root: io.cwd, slotFile, table, text });
|
|
140
|
+
} catch (error) {
|
|
141
|
+
throw halt(EXIT_REFUSE, [OUTCOME_LINES.refused(slotFile, error.message)]);
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
const runRender = (io, { slotFile }) => {
|
|
146
|
+
const location = locateGitDir(io);
|
|
147
|
+
recordStage(location, slotFile, null, WRITES_AUTHORING);
|
|
148
|
+
const table = loadTable(io);
|
|
149
|
+
const slots = validate(io, slotFile, table);
|
|
150
|
+
const gated = RECORD_GATED_STAGES.includes(slots.stage);
|
|
151
|
+
const match = gated ? requireApproval(io, slots.plan, slots.stage) : null;
|
|
152
|
+
const canon = readCanon(io.env);
|
|
153
|
+
const rendering = (() => {
|
|
154
|
+
try {
|
|
155
|
+
return renderStage({ root: io.cwd, slotFile, slots, table, canon, match });
|
|
156
|
+
} catch (error) {
|
|
157
|
+
throw error.stage === WAITING_STAGE
|
|
158
|
+
? halt(EXIT_REFUSE, [OUTCOME_LINES.unapproved(slots.stage, slots.plan, error.message)])
|
|
159
|
+
: halt(EXIT_USAGE, [OUTCOME_LINES.cannotRender(PROCEDURES_FRAGMENT_REL, error.message)]);
|
|
160
|
+
}
|
|
161
|
+
})();
|
|
162
|
+
recordStage(location, slotFile, slots.stage, gated ? WRITES_ANY : WRITES_AUTHORING);
|
|
163
|
+
io.stdout(rendering);
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
const runDispatch = (io, { plan }) => {
|
|
167
|
+
const approval = requireApproval(io, plan, DISPATCH);
|
|
168
|
+
composeDispatchPart({ plan: approval.verdict.identity, match: approval }).split(LINE_ENDING).forEach((line) => io.out(OUTCOME_LINES.text(line)));
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
const refusing = (subject, compose) => {
|
|
172
|
+
try {
|
|
173
|
+
return compose();
|
|
174
|
+
} catch (error) {
|
|
175
|
+
throw halt(EXIT_REFUSE, [OUTCOME_LINES.refused(subject, error.message)]);
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
const composeText = (table, { stage, values, decisions }) => refusing(STAGE_FLAG,
|
|
180
|
+
() => composeSlotText({ stage, values: { ...values, decisions }, date: getLocalDate(), table }));
|
|
181
|
+
|
|
182
|
+
const composeWrittenLines = (slotFile, slots, table, location) => refusing(slotFile, () => {
|
|
183
|
+
const prompt = isMainTree(location)
|
|
184
|
+
? [OUTCOME_LINES.startHeader(), ...composeStartPrompt({ slotFile, slots, table }).split(LINE_ENDING).map(OUTCOME_LINES.text)]
|
|
185
|
+
: [];
|
|
186
|
+
return [OUTCOME_LINES.written(slotFile), OUTCOME_LINES.text(composeRenderLine(slotFile)), OUTCOME_LINES.text(composeRenderCommand(slotFile)), ...prompt];
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
const runWrite = (io, flags) => {
|
|
190
|
+
const { slotFile, stage } = flags;
|
|
191
|
+
const table = loadTable(io);
|
|
192
|
+
const text = composeText(table, flags);
|
|
193
|
+
const slots = validate(io, slotFile, table, text);
|
|
194
|
+
const gated = RECORD_GATED_STAGES.includes(stage);
|
|
195
|
+
if (gated) requireApproval(io, slots.plan, stage);
|
|
196
|
+
const location = locateGitDir(io);
|
|
197
|
+
const lines = composeWrittenLines(slotFile, slots, table, location);
|
|
198
|
+
if (!gated) recordStage(location, slotFile, stage, WRITES_AUTHORING);
|
|
199
|
+
try {
|
|
200
|
+
writeContainedFileAtomic(io.cwd, join(io.cwd, slotFile), text, {}, { label: slotFile });
|
|
201
|
+
} catch (error) {
|
|
202
|
+
throw halt(EXIT_USAGE, [OUTCOME_LINES.writeFailed(slotFile, error.message)]);
|
|
203
|
+
}
|
|
204
|
+
lines.forEach(io.out);
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const COMMANDS = Object.freeze({ render: runRender, [WRITE]: runWrite, [DISPATCH]: runDispatch });
|
|
208
|
+
|
|
209
|
+
export const main = (argv = process.argv.slice(2), io = {}) => {
|
|
210
|
+
const stdout = io.stdout ?? ((text) => process.stdout.write(text));
|
|
211
|
+
const stderr = io.stderr ?? ((text) => process.stderr.write(text));
|
|
212
|
+
const context = {
|
|
213
|
+
cwd: io.cwd ?? process.cwd(), env: io.env ?? process.env, stagesPath: io.stagesPath ?? STAGES_PATH, stdout,
|
|
214
|
+
out: (line) => stdout(`${line}${LINE_ENDING}`), stderr: (line) => stderr(`${line}${LINE_ENDING}`),
|
|
215
|
+
};
|
|
216
|
+
const args = parseArgs(argv);
|
|
217
|
+
if (args.usage !== undefined) {
|
|
218
|
+
context.stderr(OUTCOME_LINES.usage(args.usage));
|
|
219
|
+
return EXIT_USAGE;
|
|
220
|
+
}
|
|
221
|
+
try {
|
|
222
|
+
COMMANDS[args.command](context, args);
|
|
223
|
+
return EXIT_OK;
|
|
224
|
+
} catch (error) {
|
|
225
|
+
if (error.exitCode === undefined) throw error;
|
|
226
|
+
error.lines.forEach(context.stderr);
|
|
227
|
+
return error.exitCode;
|
|
228
|
+
}
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
if (isDirectRun(import.meta.url)) process.exitCode = main();
|
|
@@ -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
|
+
};
|