@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.
Files changed (150) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/README.md +4 -4
  3. package/SKILL.md +1 -1
  4. package/bridges/codex-cli-bridge/SKILL.md +7 -2
  5. package/bridges/codex-cli-bridge/bin/codex-exec-jev.test.mjs +11 -6
  6. package/bridges/codex-cli-bridge/bin/codex-exec.sh +72 -33
  7. package/bridges/codex-cli-bridge/bin/codex-exec.test.mjs +111 -3
  8. package/bridges/codex-cli-bridge/bin/codex-fixtures-harness.test.mjs +16 -1
  9. package/bridges/codex-cli-bridge/bin/codex-model-posture.test.mjs +5 -3
  10. package/bridges/codex-cli-bridge/bin/codex-review.sh +1 -1
  11. package/bridges/codex-cli-bridge/capability.json +2 -2
  12. package/capability.json +1 -1
  13. package/package.json +1 -1
  14. package/references/advisor-writers.md +2 -0
  15. package/references/agents/author.md +21 -0
  16. package/references/agents/executor.md +12 -6
  17. package/references/contracts.md +4 -4
  18. package/references/hooks/gate-approve.mjs +7 -8
  19. package/references/hooks/stage-write-guard.mjs +314 -0
  20. package/references/modes/agents.md +6 -4
  21. package/references/modes/bootstrap.md +1 -1
  22. package/references/modes/flow-writer.md +10 -2
  23. package/references/modes/hook.md +4 -1
  24. package/references/modes/now.md +1 -1
  25. package/references/modes/procedures.md +49 -10
  26. package/references/modes/recipes.md +7 -7
  27. package/references/modes/recommendations.md +4 -3
  28. package/references/modes/robustness-brief.md +9 -8
  29. package/references/modes/set-recipe.md +1 -1
  30. package/references/modes/state-block-guard.md +4 -3
  31. package/references/modes/status.md +1 -1
  32. package/references/modes/upgrade.md +1 -1
  33. package/references/modes/worktrees.md +28 -5
  34. package/references/rules/story-sessions.md +2 -2
  35. package/references/scripts/archives/archive-caps.mjs +1 -1
  36. package/references/scripts/archives/archive-changelog.mjs +8 -8
  37. package/references/scripts/archives/archive-decisions.mjs +7 -7
  38. package/references/scripts/archives/archive-issues.mjs +5 -5
  39. package/references/scripts/archives/rotation-conservation.mjs +2 -1
  40. package/references/scripts/docs-size/check-docs-size.mjs +15 -15
  41. package/references/scripts/family.json +2 -0
  42. package/references/scripts/gates/kit-command-gates.mjs +7 -8
  43. package/references/scripts/gates/migrate-gates.mjs +10 -10
  44. package/references/scripts/git-hooks/install-git-hooks.mjs +13 -13
  45. package/references/scripts/run.mjs +1 -2
  46. package/references/scripts/shared/index.mjs +2 -0
  47. package/references/scripts/shared/locations.mjs +103 -0
  48. package/references/scripts/spec-schema/spec-schema.mjs +2 -1
  49. package/references/templates/orchestration.json +1 -1
  50. package/tools/ack-store.mjs +2 -1
  51. package/tools/apply-danger-check.mjs +20 -6
  52. package/tools/atomic-write.mjs +3 -2
  53. package/tools/attribution.mjs +2 -1
  54. package/tools/autonomy-config.mjs +2 -1
  55. package/tools/bridge-wiring.mjs +13 -11
  56. package/tools/carriers.mjs +54 -14
  57. package/tools/cheap-agents-read.mjs +28 -7
  58. package/tools/cheap-agents.mjs +15 -10
  59. package/tools/checker-gates-read.mjs +6 -5
  60. package/tools/commands.mjs +2 -2
  61. package/tools/coverage-declared/config.mjs +2 -1
  62. package/tools/coverage-producer.mjs +10 -9
  63. package/tools/delegation.mjs +7 -6
  64. package/tools/detect-backends.mjs +1 -1
  65. package/tools/dispatch-baseline.mjs +2 -1
  66. package/tools/distribution-files/scripts.mjs +4 -4
  67. package/tools/ensure-configs.mjs +2 -2
  68. package/tools/ensure-ops.mjs +24 -24
  69. package/tools/ensure-specs.mjs +7 -7
  70. package/tools/epic-shape-cli.mjs +2 -2
  71. package/tools/epic-shape-ledger.mjs +5 -5
  72. package/tools/epic-shape.mjs +5 -3
  73. package/tools/epic-store.mjs +2 -1
  74. package/tools/family-members.mjs +7 -5
  75. package/tools/family-registry.mjs +36 -30
  76. package/tools/feedback-record-cli.mjs +4 -5
  77. package/tools/flow-writer.mjs +26 -15
  78. package/tools/gate-hook.mjs +33 -28
  79. package/tools/gates-declaration.mjs +2 -1
  80. package/tools/gates-init.mjs +6 -5
  81. package/tools/git-hooks.mjs +64 -41
  82. package/tools/grounding.mjs +3 -2
  83. package/tools/hide-footprint.mjs +2 -1
  84. package/tools/hook-writer/index.mjs +147 -0
  85. package/tools/init-preflight.mjs +5 -4
  86. package/tools/init-project.mjs +12 -11
  87. package/tools/inject-methodology.mjs +3 -2
  88. package/tools/jev-guide.mjs +2 -2
  89. package/tools/known-footprint.mjs +27 -25
  90. package/tools/mcp-registration.mjs +6 -5
  91. package/tools/migration-blocks.mjs +2 -1
  92. package/tools/migration-notes.mjs +2 -2
  93. package/tools/node-evidence.mjs +4 -4
  94. package/tools/now-facts.mjs +5 -5
  95. package/tools/now-status.mjs +1 -5
  96. package/tools/orchestration-config.mjs +2 -1
  97. package/tools/orchestration-readme.mjs +7 -2
  98. package/tools/plan-approval/cli.mjs +45 -0
  99. package/tools/plan-approval/entries.mjs +109 -0
  100. package/tools/plan-approval/index.mjs +2 -0
  101. package/tools/plan-approval/record.mjs +198 -0
  102. package/tools/plan-files.mjs +6 -4
  103. package/tools/plan-shape-cli.mjs +10 -64
  104. package/tools/plan-shape-facts.mjs +240 -83
  105. package/tools/plan-shape.mjs +173 -160
  106. package/tools/plan-structure/cli.mjs +79 -0
  107. package/tools/plan-structure/index.mjs +67 -0
  108. package/tools/procedures.mjs +21 -17
  109. package/tools/profile-gaps.mjs +4 -6
  110. package/tools/project-rules/rules-priors.mjs +2 -0
  111. package/tools/project-rules/themes.mjs +6 -4
  112. package/tools/recipes.mjs +44 -29
  113. package/tools/recommendations.mjs +84 -33
  114. package/tools/reference-profile.mjs +2 -2
  115. package/tools/renderers.mjs +14 -8
  116. package/tools/repo-lex.mjs +84 -0
  117. package/tools/robustness-brief.mjs +14 -11
  118. package/tools/satellite-locator.mjs +3 -2
  119. package/tools/script-priors.mjs +3 -2
  120. package/tools/session-close-check.mjs +71 -15
  121. package/tools/set-flow.mjs +2 -2
  122. package/tools/set-recipe.mjs +17 -9
  123. package/tools/source-size/help.mjs +4 -4
  124. package/tools/source-size/layout.mjs +2 -1
  125. package/tools/source-size/piles.mjs +2 -2
  126. package/tools/source-size-config.mjs +3 -3
  127. package/tools/source-size-refusal.mjs +4 -3
  128. package/tools/source-size-report.mjs +41 -13
  129. package/tools/spec-check-cli.mjs +159 -21
  130. package/tools/spec-check-ops.mjs +74 -5
  131. package/tools/spec-check.mjs +54 -45
  132. package/tools/spec-coverage-cli.mjs +3 -2
  133. package/tools/stage-render/cli.mjs +231 -0
  134. package/tools/stage-render/index.mjs +340 -0
  135. package/tools/stage-render/stages.json +115 -0
  136. package/tools/stage-write-guard/cli.mjs +64 -0
  137. package/tools/stage-write-guard/index.mjs +56 -0
  138. package/tools/state-block-hook.mjs +38 -163
  139. package/tools/task-brief.mjs +8 -13
  140. package/tools/task-thread.mjs +3 -1
  141. package/tools/tier-guide-facts.mjs +23 -9
  142. package/tools/tier-preview.mjs +15 -19
  143. package/tools/transition/index.mjs +10 -9
  144. package/tools/uninstall.mjs +26 -12
  145. package/tools/vehicle-settings.mjs +2 -1
  146. package/tools/velocity-profile.mjs +5 -6
  147. package/tools/view-model.mjs +7 -4
  148. package/tools/worktree-prompt.mjs +7 -3
  149. package/tools/worktrees.mjs +235 -159
  150. package/tools/write-lanes.mjs +20 -14
@@ -0,0 +1,109 @@
1
+ import { SPEC_SCHEMA } from '../../references/scripts/spec-schema/index.mjs';
2
+ import { tokenizeMarkdown } from '../../references/scripts/shared/index.mjs';
3
+ import { canonicalFlowDigest } from '../flow-record-identity.mjs';
4
+ import { isHex64, isPlainObject } from '../flow-vocabulary.mjs';
5
+ import { PLAN_HEADINGS, isSweep, makeFinding, parseLedger } from '../plan-shape.mjs';
6
+ import { relateAmendments } from '../plan-structure/index.mjs';
7
+ import { lexicalRepoRelative, parseStrictJson } from '../repo-lex.mjs';
8
+ import { parseRobustTag } from '../robustness-literals.mjs';
9
+
10
+ export const APPROVAL_RECORD_BASENAME = 'agent-workflow-plan-approvals.jsonl';
11
+
12
+ const SCHEMA = 1;
13
+ const ENTRY_KEYS = Object.freeze(['schema', 'plan', 'date', 'planDigest', 'contractsDigest', 'contracts', 'essence', 'from', 'approval']);
14
+ const ORIGINS = new Set(['approval', 'provision']);
15
+ const DATE = /^\d{4}-\d{2}-\d{2}$/u;
16
+ const SCENARIOS_HEADING = '## Scenarios';
17
+ const SCENARIO_SEPARATOR = ' :: ';
18
+ const SCENARIO_LINE = /^- S\d+ /u;
19
+ const REWRITTEN_KEYS = new Set([...SPEC_SCHEMA.rootOwnedKeys, 'lastUpdated']);
20
+ const LINE_ENDING = '\n';
21
+ const [GOAL_HEADING, , VERIFICATION_HEADING] = PLAN_HEADINGS;
22
+
23
+ const normalizeLineEndings = (text) => text.replaceAll('\r\n', LINE_ENDING);
24
+
25
+ const getSectionBounds = (document, headingText) => {
26
+ const heading = document.headings.find(({ text }) => text === headingText);
27
+ if (!heading) return null;
28
+ const next = document.headings.find(({ index, level }) => index > heading.index && level <= heading.level);
29
+ return [heading.index + 1, next?.index ?? document.lines.length];
30
+ };
31
+
32
+ const readSection = (document, headingText) => document.lines.slice(...getSectionBounds(document, headingText)).join(LINE_ENDING);
33
+
34
+ const removeRobustTag = (responsibility) => {
35
+ const { classes } = parseRobustTag(responsibility);
36
+ if (!classes?.length) return responsibility;
37
+ return responsibility.replace(`robust:${classes.join(',')}`, '').trim();
38
+ };
39
+
40
+ export const approvedParts = (text, verdict) => {
41
+ if (!verdict?.accepted) return null;
42
+ const parsed = parseLedger(normalizeLineEndings(text));
43
+ const { approved } = relateAmendments({ parsed, makeFinding, isSweep });
44
+ return {
45
+ goal: readSection(parsed.document, GOAL_HEADING),
46
+ rows: approved.map(({ verb, path, responsibility }) => ({ verb, path, responsibility: removeRobustTag(responsibility) })),
47
+ verification: readSection(parsed.document, VERIFICATION_HEADING),
48
+ };
49
+ };
50
+
51
+ export const digestPlan = (text, verdict) => {
52
+ const parts = approvedParts(text, verdict);
53
+ return parts === null ? null : canonicalFlowDigest(parts);
54
+ };
55
+
56
+ export const digestContract = (text) => {
57
+ const document = tokenizeMarkdown(normalizeLineEndings(text));
58
+ const frontmatter = document.frontmatter.split(LINE_ENDING)
59
+ .filter((line) => !REWRITTEN_KEYS.has(line.split(':', 1)[0])).join(LINE_ENDING);
60
+ const bounds = getSectionBounds(document, SCENARIOS_HEADING);
61
+ const lines = document.lines.map((line, index) => {
62
+ if (!bounds || index < bounds[0] || index >= bounds[1] || !SCENARIO_LINE.test(line) || document.fencedLines.has(index)) return line;
63
+ const separator = line.indexOf(SCENARIO_SEPARATOR);
64
+ return separator === -1 ? line : line.slice(0, separator);
65
+ });
66
+ return canonicalFlowDigest(frontmatter + lines.join(LINE_ENDING));
67
+ };
68
+
69
+ const digestApproval = ({ planDigest, contractsDigest, essence }) => canonicalFlowDigest({ planDigest, contractsDigest, essence });
70
+
71
+ export const composeEntry = ({ plan, date, planDigest, contractsDigest, contracts, essence, from = 'approval' }) => ({
72
+ schema: SCHEMA, plan, date, planDigest, contractsDigest, contracts: [...contracts].sort(), essence, from,
73
+ approval: digestApproval({ planDigest, contractsDigest, essence }),
74
+ });
75
+
76
+ const isContractPath = (path) => lexicalRepoRelative(path).ok && path.startsWith(SPEC_SCHEMA.storePrefix);
77
+ const isEntry = (entry) => isPlainObject(entry)
78
+ && Object.keys(entry).length === ENTRY_KEYS.length && ENTRY_KEYS.every((key) => Object.hasOwn(entry, key))
79
+ && entry.schema === SCHEMA && lexicalRepoRelative(entry.plan).ok
80
+ && typeof entry.date === 'string' && DATE.test(entry.date)
81
+ && isHex64(entry.planDigest) && isHex64(entry.contractsDigest)
82
+ && Array.isArray(entry.contracts) && entry.contracts.every((path, index) => isContractPath(path) && (index === 0 || entry.contracts[index - 1] < path))
83
+ && typeof entry.essence === 'string' && entry.essence.trim() !== '' && ORIGINS.has(entry.from)
84
+ && isHex64(entry.approval) && entry.approval === digestApproval(entry);
85
+
86
+ const parseLine = (line, index) => {
87
+ try {
88
+ const entry = parseStrictJson(line);
89
+ if (isEntry(entry)) return { entry };
90
+ } catch {
91
+ return { malformedLine: index + 1, reason: `line ${index + 1}: invalid JSON` };
92
+ }
93
+ return { malformedLine: index + 1, reason: `line ${index + 1}: invalid approval entry` };
94
+ };
95
+
96
+ export const parseEntries = (text) => {
97
+ const lines = text.split(LINE_ENDING);
98
+ const parsed = (lines.at(-1) === '' ? lines.slice(0, -1) : lines).map(parseLine);
99
+ const invalid = parsed.filter(({ malformedLine }) => malformedLine !== undefined);
100
+ return {
101
+ entries: parsed.filter(({ entry }) => entry !== undefined).map(({ entry }) => entry),
102
+ malformedLines: invalid.map(({ malformedLine }) => malformedLine),
103
+ malformedReasons: invalid.map(({ reason }) => reason),
104
+ };
105
+ };
106
+
107
+ export const findMatch = (entries, { planDigest, contractsDigest, approval } = {}) => entries.find((entry) =>
108
+ entry.planDigest === planDigest && (approval === undefined || entry.approval === approval)
109
+ && (entry.from === 'provision' || entry.contractsDigest === contractsDigest)) ?? null;
@@ -0,0 +1,2 @@
1
+ export { APPROVAL_RECORD_BASENAME, approvedParts, composeEntry, digestContract, digestPlan, findMatch, parseEntries } from './entries.mjs';
2
+ export { readApproval, appendApproval, getLocalDate, OUTCOME_LINES } from './record.mjs';
@@ -0,0 +1,198 @@
1
+ import { dirname, join, resolve } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { SPEC_SCHEMA, readSpecDocument } from '../../references/scripts/spec-schema/index.mjs';
4
+ import { resolveReceiptsPath } from '../core-evidence-receipts.mjs';
5
+ import { canonicalFlowDigest } from '../flow-record-identity.mjs';
6
+ import { isHex64 } from '../flow-vocabulary.mjs';
7
+ import { readRegularFileNoFollow } from '../fs-read-nofollow.mjs';
8
+ import { judgePlan, readPlanDocument } from '../plan-shape-facts.mjs';
9
+ import { escapeForDisplay, isSeedablePathToken, lexicalRepoRelative, shellQuoteArg } from '../repo-lex.mjs';
10
+ import { getRevisionHomePath } from '../spec-check-ops.mjs';
11
+ import { createStoreAppendLane } from '../store-append.mjs';
12
+ import { APPROVAL_RECORD_BASENAME, approvedParts, composeEntry, digestContract, digestPlan, findMatch, parseEntries } from './entries.mjs';
13
+
14
+ const CLI_PATH = fileURLToPath(new URL('./cli.mjs', import.meta.url));
15
+ const CLI_TOKEN = isSeedablePathToken(CLI_PATH) ? CLI_PATH : shellQuoteArg(CLI_PATH);
16
+ const RECORD = 'record';
17
+ const CHECK = 'check';
18
+ const ESSENCE_FLAG = '--essence-file';
19
+ const DIGEST_FLAG = '--digest';
20
+ const CONTRACT_VERBS = new Set(['create', 'modify']);
21
+ const EXIT_ACCEPT = 0;
22
+ const EXIT_REFUSE = 1;
23
+ const EXIT_USAGE = 2;
24
+ const LINE_ENDING = '\n';
25
+ const LOCK_SUFFIX = '.lock';
26
+ const YEAR_WIDTH = 4;
27
+ const DAY_MONTH_WIDTH = 2;
28
+
29
+ const renderRecordCommand = (plan) => `node ${CLI_TOKEN} ${RECORD} ${shellQuoteArg(plan)} ${ESSENCE_FLAG} <file>`;
30
+ const display = escapeForDisplay;
31
+
32
+ export const OUTCOME_LINES = Object.freeze({
33
+ usage: () => `Usage: node ${display(CLI_TOKEN)} ${RECORD} <plan> ${ESSENCE_FLAG} <file> | ${CHECK} <plan> [${DIGEST_FLAG} <approval>]`,
34
+ accepted: (plan, approval) => `plan-approval: ACCEPT — ${display(plan)} (${display(approval)})`,
35
+ recorded: (plan, approval, recordPath) => `plan-approval: RECORDED — ${display(plan)} (${display(approval)}) at ${display(recordPath)}`,
36
+ refused: (plan, reason) => `plan-approval: REFUSE — ${display(plan)}: ${display(reason)}; ${display(renderRecordCommand(plan))}`,
37
+ error: (plan, reason) => `plan-approval: ERROR — ${display(plan)}: ${display(reason)}`,
38
+ finding: (plan, finding) => `${display(plan)}:${display(finding.line)}: ${display(finding.code)}: ${display(finding.message)}`,
39
+ malformed: (recordPath, line) => `plan-approval: malformed entry at ${display(recordPath)}: line ${display(line)}`,
40
+ });
41
+
42
+ const refuse = (exitCode, reason, fields = {}) => ({ ...fields, exitCode, reason });
43
+ const describeReadFailure = (read) => read.closeFailure ?? read.code ?? read.className ?? read.outcome;
44
+
45
+ const readJudgedPlan = (cwd, plan) => {
46
+ try {
47
+ const document = readPlanDocument(cwd, plan);
48
+ const verdict = judgePlan(cwd, document);
49
+ const planDigest = digestPlan(verdict.text, verdict);
50
+ const fields = { verdict, planDigest };
51
+ return verdict.accepted && planDigest !== null
52
+ ? { ...fields, exitCode: EXIT_ACCEPT }
53
+ : refuse(EXIT_REFUSE, 'the plan structure does not accept', fields);
54
+ } catch (error) {
55
+ return refuse(EXIT_USAGE, error.message);
56
+ }
57
+ };
58
+
59
+ const resolveRecordPath = (cwd, env) => {
60
+ const receipts = resolveReceiptsPath(cwd, env);
61
+ return receipts === null ? null : join(dirname(receipts), APPROVAL_RECORD_BASENAME);
62
+ };
63
+
64
+ const readRecord = (cwd, env) => {
65
+ const recordPath = resolveRecordPath(cwd, env);
66
+ if (recordPath === null) return refuse(EXIT_USAGE, 'no git directory for the approval record');
67
+ const read = readRegularFileNoFollow(recordPath);
68
+ if (read.closeFailure || !['ok', 'absent'].includes(read.outcome)) {
69
+ return refuse(EXIT_USAGE, `cannot read ${recordPath} (${describeReadFailure(read)})`, { recordPath });
70
+ }
71
+ return { recordPath, ...parseEntries(read.outcome === 'absent' ? '' : read.content), exitCode: EXIT_ACCEPT };
72
+ };
73
+
74
+ const readContract = (cwd, plan, path) => {
75
+ const home = getRevisionHomePath(plan, path);
76
+ if (home === null) return refuse(EXIT_REFUSE, `cannot resolve the revision home for ${path}`);
77
+ const revision = readRegularFileNoFollow(resolve(cwd, home));
78
+ const source = revision.outcome === 'absent' && !revision.closeFailure ? path : home;
79
+ const read = source === path ? readRegularFileNoFollow(resolve(cwd, path)) : revision;
80
+ if (read.outcome !== 'ok' || read.closeFailure) return refuse(EXIT_REFUSE, `cannot read contract ${path} at ${source} (${describeReadFailure(read)})`);
81
+ const { kind, errors } = readSpecDocument(read.content, path.slice(SPEC_SCHEMA.storePrefix.length));
82
+ if (errors.length) return refuse(EXIT_REFUSE, `contract ${path} at ${source}: ${errors.map(({ message }) => message).join('; ')}`);
83
+ return { exitCode: EXIT_ACCEPT, pair: kind === 'index' ? null : [path, digestContract(read.content)] };
84
+ };
85
+
86
+ const readContracts = (cwd, plan, verdict) => {
87
+ const paths = [...new Set(approvedParts(verdict.text, verdict).rows
88
+ .filter(({ verb, path }) => CONTRACT_VERBS.has(verb) && path.startsWith(SPEC_SCHEMA.storePrefix))
89
+ .map(({ path }) => path))].sort();
90
+ const pairs = [];
91
+ for (const path of paths) {
92
+ try {
93
+ const result = readContract(cwd, plan, path);
94
+ if (result.exitCode !== EXIT_ACCEPT) return result;
95
+ if (result.pair !== null) pairs.push(result.pair);
96
+ } catch (error) {
97
+ return refuse(EXIT_REFUSE, `cannot digest contract ${path}: ${error.message}`);
98
+ }
99
+ }
100
+ return { exitCode: EXIT_ACCEPT, contracts: pairs.map(([path]) => path), contractsDigest: canonicalFlowDigest(pairs) };
101
+ };
102
+
103
+ export const readApproval = ({ cwd = process.cwd(), env = process.env, plan, approval, contractsCwd = cwd } = {}) => {
104
+ if (!isOperand(plan) || (approval !== undefined && !isHex64(approval))) {
105
+ return refuse(EXIT_USAGE, 'invalid plan operand or approval digest');
106
+ }
107
+ const judged = readJudgedPlan(cwd, plan);
108
+ if (judged.exitCode !== EXIT_ACCEPT) return judged;
109
+ const { verdict, planDigest } = judged;
110
+ const record = readRecord(cwd, env);
111
+ if (record.exitCode !== EXIT_ACCEPT) return { verdict, planDigest, ...record };
112
+ const { entries, malformedLines, recordPath } = record;
113
+ const fields = { verdict, planDigest, malformedLines, recordPath, match: null };
114
+ const candidates = entries.filter((entry) => entry.planDigest === planDigest && (approval === undefined || entry.approval === approval));
115
+ const contractRefusals = [];
116
+ for (const entry of candidates) {
117
+ const contracts = entry.from === 'provision' ? {} : readContracts(contractsCwd, entry.plan, verdict);
118
+ if (contracts.exitCode === EXIT_REFUSE) {
119
+ contractRefusals.push(contracts.reason);
120
+ continue;
121
+ }
122
+ const match = findMatch([entry], { planDigest, contractsDigest: contracts.contractsDigest, approval });
123
+ if (match !== null) return { ...fields, match, exitCode: EXIT_ACCEPT };
124
+ }
125
+ return refuse(EXIT_REFUSE, contractRefusals.length ? contractRefusals.join('; ') : 'no matching approval record', fields);
126
+ };
127
+
128
+ const findTwin = (entries, entry) => entries.find(({ approval, plan }) => approval === entry.approval && plan === entry.plan);
129
+ const stop = (message) => new Error(message);
130
+ const appendLane = createStoreAppendLane({
131
+ nouns: { store: 'plan approval store', adj: 'plan-approval', record: 'plan approval entry' },
132
+ envNames: { store: 'AW_REVIEW_RECEIPTS', waitKnob: 'AW_PLAN_APPROVAL_LOCK_WAIT_MS', pollKnob: 'AW_PLAN_APPROVAL_LOCK_POLL_MS' },
133
+ stop,
134
+ resolveStorePath: resolveRecordPath,
135
+ resolveLockPath: (path) => `${path}${LOCK_SUFFIX}`,
136
+ validateRecord: (entry) => {
137
+ const { malformedReasons } = parseEntries(JSON.stringify(entry));
138
+ return malformedReasons.length ? { ok: false, reason: malformedReasons[0] } : { ok: true };
139
+ },
140
+ parseStoreText: (text) => {
141
+ const { entries, malformedLines, malformedReasons } = parseEntries(text);
142
+ return { records: entries, malformed: malformedLines.length, malformedReasons };
143
+ },
144
+ });
145
+
146
+ export const appendApproval = ({ cwd = process.cwd(), env = process.env, entry } = {}) => {
147
+ const record = readRecord(cwd, env);
148
+ if (record.exitCode !== EXIT_ACCEPT) return record;
149
+ const { recordPath, malformedLines } = record;
150
+ const fields = { recordPath, malformedLines };
151
+ const captured = (() => {
152
+ try {
153
+ return appendLane.captureRecordSnapshot(entry);
154
+ } catch (error) {
155
+ return { error };
156
+ }
157
+ })();
158
+ if (captured.error) return refuse(EXIT_USAGE, captured.error.message, fields);
159
+ const { line, snapshot } = captured;
160
+ const twin = findTwin(record.entries, snapshot);
161
+ if (twin) return { ...fields, exitCode: EXIT_ACCEPT, entry: twin, written: false };
162
+ try {
163
+ const result = appendLane.appendResolvedRecord({
164
+ cwd, env, deps: {}, makeRecord: () => ({ line, snapshot }),
165
+ preflight: ({ records }) => {
166
+ if (findTwin(records, snapshot)) throw stop('approval already recorded for this plan');
167
+ },
168
+ });
169
+ return { ...fields, recordPath: result.writtenPath, exitCode: EXIT_ACCEPT, entry: result.record, written: true };
170
+ } catch (error) {
171
+ const reread = readRecord(cwd, env);
172
+ const twin = reread.exitCode === EXIT_ACCEPT ? findTwin(reread.entries, snapshot) : null;
173
+ if (twin) return { recordPath: reread.recordPath, malformedLines: reread.malformedLines, exitCode: EXIT_ACCEPT, entry: twin, written: false };
174
+ const reason = reread.exitCode === EXIT_ACCEPT ? error.message : `${error.message}; ${reread.reason}`;
175
+ return refuse(EXIT_USAGE, reason, { ...fields, malformedLines: reread.malformedLines ?? malformedLines });
176
+ }
177
+ };
178
+
179
+ export const getLocalDate = (date = new Date()) => [String(date.getFullYear()).padStart(YEAR_WIDTH, '0'),
180
+ ...[date.getMonth() + 1, date.getDate()].map((part) => String(part).padStart(DAY_MONTH_WIDTH, '0'))].join('-');
181
+
182
+ const recordApproval = (cwd, env, plan, essenceFile) => {
183
+ const judged = readJudgedPlan(cwd, plan);
184
+ if (judged.exitCode !== EXIT_ACCEPT) return judged;
185
+ const { verdict, planDigest } = judged;
186
+ if (!lexicalRepoRelative(verdict.identity).ok) return refuse(EXIT_USAGE, `plan ${plan} is not repository-relative`);
187
+ const read = readRegularFileNoFollow(resolve(cwd, essenceFile));
188
+ if (read.outcome !== 'ok' || read.closeFailure) return refuse(EXIT_USAGE, `cannot read essence file ${essenceFile} (${describeReadFailure(read)})`);
189
+ if (!read.content.trim()) return refuse(EXIT_USAGE, `essence file ${essenceFile} has no non-blank line`);
190
+ const contracts = readContracts(cwd, verdict.identity, verdict);
191
+ if (contracts.exitCode !== EXIT_ACCEPT) return contracts;
192
+ const entry = composeEntry({ plan: verdict.identity, date: getLocalDate(), planDigest, ...contracts, essence: read.content });
193
+ return appendApproval({ cwd, env, entry });
194
+ };
195
+
196
+ const isOperand = (value) => typeof value === 'string' && value.length > 0 && !value.startsWith('-');
197
+
198
+ export { RECORD, CHECK, ESSENCE_FLAG, DIGEST_FLAG, EXIT_ACCEPT, EXIT_REFUSE, EXIT_USAGE, LINE_ENDING, recordApproval, isOperand };
@@ -1,13 +1,15 @@
1
1
  // plan-files.mjs — the in-flight-plan file convention (FLOW-READ-GRAPH-PURITY, flow Plan 4
2
- // Phase 2). A LEAF: Node built-ins only, read-only fs (one injectable readdir), no CLI, no side
2
+ // Phase 2). A LEAF: Node built-ins and shared locations, read-only fs (one injectable readdir), no CLI, no side
3
3
  // effects on import — extracted so the procedures read surface lists plans without importing
4
4
  // review-state (whose graph reaches the flow-store write API). review-state re-exports everything
5
5
  // here except readPlanEntries, so every existing consumer keeps its import site. Dependency-free, Node >= 22.
6
6
 
7
7
  import { readdirSync } from 'node:fs';
8
- import { join } from 'node:path';
8
+ import { join, posix } from 'node:path';
9
+ import { PLANS, QUEUE } from '../references/scripts/shared/index.mjs';
9
10
 
10
- export const PLANS_REL = 'docs/plans';
11
+ export const PLANS_REL = PLANS;
12
+ const QUEUE_NAME = posix.basename(QUEUE);
11
13
 
12
14
  // The plans directory's entries as plan-shape-cli and the tier guide read them: absent is an empty
13
15
  // list, any other read error is thrown with its code.
@@ -23,7 +25,7 @@ export const readPlanEntries = (cwd) => {
23
25
  // Scratch by the naming convention: EXECUTE-/FEEDBACK-/TASK- prefixes, or a name carrying PROMPT/prompt/
24
26
  // handoff. queue.md is the series index, never a plan.
25
27
  export const isScratchPlanName = (name) =>
26
- name === 'queue.md' ||
28
+ name === QUEUE_NAME ||
27
29
  name.startsWith('EXECUTE-') ||
28
30
  name.startsWith('FEEDBACK-') ||
29
31
  name.startsWith('TASK-') ||
@@ -1,12 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { resolve } from 'node:path';
4
- import { tokenizeMarkdown } from '../references/scripts/shared/index.mjs';
5
3
  import { isDirectRun } from './direct-run.mjs';
6
- import { readRegularFileNoFollow } from './fs-read-nofollow.mjs';
7
- import { plansInFlight, PLANS_REL, readPlanEntries } from './plan-files.mjs';
8
- import { buildFacts, openRepo } from './plan-shape-facts.mjs';
9
- import { checkPlan, checkPlanStructure, formatFindings, parseLedger, PLAN_TITLE_PREFIX, verifyPlan } from './plan-shape.mjs';
4
+ import { judgePlan, readPlanDocument, readPlansInFlight } from './plan-shape-facts.mjs';
5
+ import { checkPlan, formatFindings, verifyPlan } from './plan-shape.mjs';
10
6
 
11
7
  const USAGE = `Usage:
12
8
  node plan-shape-cli.mjs --check <plan>
@@ -14,72 +10,22 @@ const USAGE = `Usage:
14
10
  node plan-shape-cli.mjs --check --in-flight
15
11
  node plan-shape-cli.mjs --verify --in-flight`;
16
12
 
17
- const readPlan = (path) => {
18
- const result = readRegularFileNoFollow(path);
19
- if (result.outcome !== 'ok') throw new Error(`${path} must be a readable regular plan file (${result.className ?? result.code ?? result.outcome})`);
20
- return result.content;
21
- };
22
-
23
- const getPaths = (text) => {
24
- try {
25
- const rows = parseLedger(text).rows.filter((row) => row.valid);
26
- return [...rows.map((row) => row.path), ...rows.map((row) => row.anchorPath).filter(Boolean)];
27
- } catch {
28
- return [];
29
- }
30
- };
31
-
32
- const isPlanShape = (text) => {
33
- try {
34
- const first = tokenizeMarkdown(text, 'the in-flight document').headings[0];
35
- return Boolean(first && first.level === 1 && first.text.startsWith(PLAN_TITLE_PREFIX));
36
- } catch {
37
- return true;
38
- }
39
- };
40
-
41
13
  const writeLine = (write, line) => write(`${line}\n`);
42
14
 
43
- // A facts failure scoped to the plan's own paths is that plan's listed finding, so the other plans
44
- // are still judged; a repository-level refusal (the practice, a package, its pins) keeps its usage class.
45
- const buildPlanFacts = (cwd, repo, text) => {
46
- try {
47
- return { facts: buildFacts(cwd, { paths: getPaths(text), repo }) };
48
- } catch (error) {
49
- if (error?.scope !== 'plan') throw error;
50
- return { findings: [{ line: 1, code: 'facts', message: error.message, rowId: null }], skips: [] };
51
- }
52
- };
53
-
54
- const judgeWith = (cwd, repo, text, rules) => {
55
- const built = buildPlanFacts(cwd, repo, text);
56
- return built.facts ? rules(text, built.facts) : built;
57
- };
58
-
59
15
  const runExplicit = (cwd, arm, operand, write) => {
60
- const text = readPlan(resolve(cwd, operand));
61
- const result = judgeWith(cwd, openRepo(cwd), text, arm === '--check' ? checkPlan : verifyPlan);
16
+ const document = readPlanDocument(cwd, operand);
17
+ const options = arm === '--check' ? { rules: checkPlan, plan: document.identity } : { rules: verifyPlan };
18
+ const { result } = judgePlan(cwd, document, options);
62
19
  writeLine(write, formatFindings(result, operand));
63
20
  return result.findings.length === 0 ? 0 : 1;
64
21
  };
65
22
 
66
23
  const runInFlight = (cwd, write) => {
67
- const entries = readPlanEntries(cwd);
68
- const names = plansInFlight(cwd, () => entries);
69
- const documents = names.map((name) => {
70
- const label = `${PLANS_REL}/${name}`;
71
- return { label, text: readPlan(resolve(cwd, label)) };
72
- });
73
- const judged = documents.filter((document) => isPlanShape(document.text));
74
- const repo = openRepo(cwd);
75
- const results = judged.map((document) => {
76
- const result = judgeWith(cwd, repo, document.text, checkPlanStructure);
77
- writeLine(write, formatFindings(result, document.label));
78
- return result;
79
- });
80
- writeLine(write, `plan-shape: judged plans: ${judged.length}`);
81
- writeLine(write, `plan-shape: skipped by shape: ${documents.length - judged.length}`);
82
- return results.some((result) => result.findings.length > 0) ? 1 : 0;
24
+ const { plans, skipped = 0 } = readPlansInFlight(cwd);
25
+ for (const { identity, result } of plans) writeLine(write, formatFindings(result, identity));
26
+ writeLine(write, `plan-shape: judged plans: ${plans.length}`);
27
+ writeLine(write, `plan-shape: skipped by shape: ${skipped}`);
28
+ return plans.some(({ accepted }) => !accepted) ? 1 : 0;
83
29
  };
84
30
 
85
31
  export const main = (argv = process.argv.slice(2), io = {}) => {