slicekit 0.0.1 → 0.1.2

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 (170) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +252 -3
  3. package/bin/slicekit.js +4 -0
  4. package/package.json +21 -4
  5. package/src/adapters/githost/errors.js +17 -0
  6. package/src/adapters/githost/fixture.js +136 -0
  7. package/src/adapters/githost/gh-json.js +99 -0
  8. package/src/adapters/githost/github.js +127 -0
  9. package/src/adapters/githost/index.js +12 -0
  10. package/src/adapters/tracker/errors.js +53 -0
  11. package/src/adapters/tracker/fixture.js +71 -0
  12. package/src/adapters/tracker/github-issues.js +65 -0
  13. package/src/adapters/tracker/index.js +14 -0
  14. package/src/baseline.js +109 -0
  15. package/src/build/commit.js +201 -0
  16. package/src/build/decline.js +81 -0
  17. package/src/build/finish.js +155 -0
  18. package/src/build/order.js +158 -0
  19. package/src/build/overlap.js +173 -0
  20. package/src/build/parallel.js +50 -0
  21. package/src/build/pr.js +263 -0
  22. package/src/build/record.js +28 -0
  23. package/src/build/red.js +207 -0
  24. package/src/build/review.js +123 -0
  25. package/src/build/sync.js +47 -0
  26. package/src/build/verdict.js +410 -0
  27. package/src/build/worktree.js +169 -0
  28. package/src/check/ci-event.js +52 -0
  29. package/src/check/context.js +129 -0
  30. package/src/check/index.js +140 -0
  31. package/src/check/rules/.gitkeep +0 -0
  32. package/src/check/rules/ci-body.js +22 -0
  33. package/src/check/rules/ci-title.js +43 -0
  34. package/src/check/rules/citations.js +224 -0
  35. package/src/check/rules/commands.js +146 -0
  36. package/src/check/rules/coverage.js +248 -0
  37. package/src/check/rules/hooks.js +58 -0
  38. package/src/check/rules/journal.js +17 -0
  39. package/src/check/rules/layout.js +56 -0
  40. package/src/check/rules/managed.js +31 -0
  41. package/src/check/rules/queue.js +106 -0
  42. package/src/check/rules/references.js +249 -0
  43. package/src/check/rules/style.js +177 -0
  44. package/src/check/rules/trailer.js +67 -0
  45. package/src/cli/baseline.js +66 -0
  46. package/src/cli/branch.js +86 -0
  47. package/src/cli/build.js +239 -0
  48. package/src/cli/check.js +40 -0
  49. package/src/cli/decide.js +59 -0
  50. package/src/cli/gaps.js +73 -0
  51. package/src/cli/hook.js +28 -0
  52. package/src/cli/index.js +83 -0
  53. package/src/cli/init.js +96 -0
  54. package/src/cli/instructions.js +63 -0
  55. package/src/cli/intake.js +107 -0
  56. package/src/cli/journal.js +82 -0
  57. package/src/cli/plan.js +29 -0
  58. package/src/cli/pr.js +83 -0
  59. package/src/cli/process.js +59 -0
  60. package/src/cli/ready-label.js +119 -0
  61. package/src/cli/review.js +64 -0
  62. package/src/cli/spec.js +31 -0
  63. package/src/cli/stage.js +37 -0
  64. package/src/cli/state.js +106 -0
  65. package/src/cli/status.js +108 -0
  66. package/src/cli/update.js +62 -0
  67. package/src/cli/workflow.js +48 -0
  68. package/src/config.js +203 -0
  69. package/src/decisions.js +289 -0
  70. package/src/evidence.js +27 -0
  71. package/src/fs.js +38 -0
  72. package/src/gaps.js +271 -0
  73. package/src/git.js +209 -0
  74. package/src/githooks.js +37 -0
  75. package/src/hook-cli.js +63 -0
  76. package/src/hooks/io.js +205 -0
  77. package/src/hooks/paths.js +82 -0
  78. package/src/hooks/pre-bash.js +715 -0
  79. package/src/hooks/pre-compact.js +139 -0
  80. package/src/hooks/pre-edit.js +170 -0
  81. package/src/hooks/session-end.js +118 -0
  82. package/src/hooks/session-start.js +209 -0
  83. package/src/hooks/shapes.js +103 -0
  84. package/src/hooks/stop.js +37 -0
  85. package/src/hooks/subagent-marker.js +88 -0
  86. package/src/hooks/subagent-start.js +100 -0
  87. package/src/hooks/subagent-stop.js +106 -0
  88. package/src/ids.js +43 -0
  89. package/src/init.js +281 -0
  90. package/src/instructions.js +235 -0
  91. package/src/intake.js +409 -0
  92. package/src/journal.js +326 -0
  93. package/src/lock.js +35 -0
  94. package/src/markdown.js +155 -0
  95. package/src/paths.js +33 -0
  96. package/src/plan.js +25 -0
  97. package/src/pr.js +73 -0
  98. package/src/prbody.js +266 -0
  99. package/src/ready-label.js +107 -0
  100. package/src/redact.js +33 -0
  101. package/src/render/compare.js +23 -0
  102. package/src/render/entry.js +101 -0
  103. package/src/render/index.js +27 -0
  104. package/src/render/managed.js +128 -0
  105. package/src/render/manifest.js +24 -0
  106. package/src/render/settings.js +76 -0
  107. package/src/render/update.js +151 -0
  108. package/src/slicefile.js +173 -0
  109. package/src/spec-verify.js +58 -0
  110. package/src/stage.js +325 -0
  111. package/src/state/build.js +156 -0
  112. package/src/state/covers.js +58 -0
  113. package/src/state/index.js +191 -0
  114. package/src/state/sync.js +64 -0
  115. package/src/state/transitions.js +282 -0
  116. package/src/verdict.js +203 -0
  117. package/src/which.js +37 -0
  118. package/src/workflow.js +177 -0
  119. package/src/worktrees.js +68 -0
  120. package/templates/claude-code/agents/auditor.md +7 -0
  121. package/templates/claude-code/agents/designer.md +7 -0
  122. package/templates/claude-code/agents/developer.md +7 -0
  123. package/templates/claude-code/agents/fixer.md +7 -0
  124. package/templates/claude-code/agents/ops.md +7 -0
  125. package/templates/claude-code/agents/reviewer.md +7 -0
  126. package/templates/claude-code/commands/slicekit-audit.md +7 -0
  127. package/templates/claude-code/commands/slicekit-build.md +7 -0
  128. package/templates/claude-code/commands/slicekit-gaps.md +6 -0
  129. package/templates/claude-code/commands/slicekit-intake.md +7 -0
  130. package/templates/claude-code/commands/slicekit-ops.md +7 -0
  131. package/templates/claude-code/commands/slicekit-plan.md +6 -0
  132. package/templates/claude-code/commands/slicekit-release.md +7 -0
  133. package/templates/claude-code/commands/slicekit-review.md +7 -0
  134. package/templates/claude-code/commands/slicekit-specify.md +6 -0
  135. package/templates/claude-code/commands/slicekit.md +7 -0
  136. package/templates/claude-code/hooks.json +90 -0
  137. package/templates/claude-code/manifest.json +171 -0
  138. package/templates/claude-code/skills/slicekit-ids/SKILL.md +16 -0
  139. package/templates/claude-code/skills/slicekit-loop/SKILL.md +23 -0
  140. package/templates/claude-code/skills/slicekit-writing/SKILL.md +24 -0
  141. package/templates/docs/BUILD.md +5 -0
  142. package/templates/docs/decisions.md +15 -0
  143. package/templates/docs/intake/.keep +0 -0
  144. package/templates/docs/observability.md +25 -0
  145. package/templates/docs/phases/.keep +0 -0
  146. package/templates/docs/platform.md +25 -0
  147. package/templates/docs/releases/.keep +0 -0
  148. package/templates/docs/runbook.md +21 -0
  149. package/templates/docs/spec/00-overview.md +8 -0
  150. package/templates/docs/spec/contracts/.keep +0 -0
  151. package/templates/docs/spec/gaps.md +6 -0
  152. package/templates/docs/spec/stack.md +3 -0
  153. package/templates/githooks/pre-commit +79 -0
  154. package/templates/githooks/pre-merge-commit +79 -0
  155. package/templates/githooks/prepare-commit-msg +110 -0
  156. package/templates/instructions/agents/auditor.md +33 -0
  157. package/templates/instructions/agents/designer.md +21 -0
  158. package/templates/instructions/agents/developer.md +49 -0
  159. package/templates/instructions/agents/fixer.md +41 -0
  160. package/templates/instructions/agents/ops.md +21 -0
  161. package/templates/instructions/agents/reviewer.md +63 -0
  162. package/templates/instructions/commands/build.md +234 -0
  163. package/templates/instructions/commands/gaps.md +65 -0
  164. package/templates/instructions/commands/intake.md +90 -0
  165. package/templates/instructions/commands/plan.md +60 -0
  166. package/templates/instructions/commands/review.md +117 -0
  167. package/templates/instructions/commands/specify.md +49 -0
  168. package/templates/style.json +11 -0
  169. package/templates/workflow/pins.json +6 -0
  170. package/templates/workflow/slicekit.yml +110 -0
package/src/stage.js ADDED
@@ -0,0 +1,325 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { exists, listFiles, readText } from './fs.js';
5
+ import { GitError, assertRef, git, hasCommits, isRepo } from './git.js';
6
+ import { readDecisions } from './decisions.js';
7
+ import { blankCodeSpans, headings, lines, prose, refs, tables } from './markdown.js';
8
+ import { re } from './ids.js';
9
+ import { kitPaths } from './paths.js';
10
+ import { findSliceFiles, parseSliceFile } from './slicefile.js';
11
+ import { listSlices } from './state/index.js';
12
+
13
+ export const STAGES = ['intake', 'clarify', 'specify', 'spec-review', 'gap-scan', 'stack', 'plan', 'build', 'release'];
14
+
15
+ // The slash command that does each stage, named in the refusal.
16
+ const COMMANDS = {
17
+ intake: 'intake',
18
+ clarify: 'intake (clarify)',
19
+ specify: 'specify',
20
+ 'spec-review': 'specify (spec-review: merge the spec pull request)',
21
+ 'gap-scan': 'gaps',
22
+ stack: 'plan (stack)',
23
+ plan: 'plan',
24
+ build: 'build',
25
+ release: 'release',
26
+ };
27
+
28
+ // The display name of each stage, used in messages; the ids stay in code.
29
+ const LABELS = {
30
+ intake: 'intake',
31
+ clarify: 'clarify',
32
+ specify: 'specify',
33
+ 'spec-review': 'spec review',
34
+ 'gap-scan': 'gap scan',
35
+ stack: 'stack',
36
+ plan: 'plan',
37
+ build: 'build',
38
+ release: 'release',
39
+ };
40
+
41
+ export class StageError extends Error {
42
+ constructor(stage, blocker) {
43
+ super(`${LABELS[stage]} not done: ${blocker}; run /slicekit ${COMMANDS[stage]}`);
44
+ this.name = 'StageError';
45
+ this.stage = stage;
46
+ }
47
+ }
48
+
49
+ const posix = (p) => p.split(path.sep).join('/');
50
+ const rel = (root, p) => posix(path.relative(root, p));
51
+ const filesUnder = (dir, ext) => (exists(dir) ? listFiles(dir, { ext }).map((f) => path.join(dir, f)) : []);
52
+
53
+ // How an intake file is pinned (REQ-1.2): `frozen` when `<file>.meta.json` or `<stem>.meta.json`
54
+ // exists and its sha256 matches the file's bytes; otherwise `no-sidecar`, `bad-json` or
55
+ // `mismatch`, with the sidecar path when there is one.
56
+ export function intakePin(file) {
57
+ const sidecar = [`${file}.meta.json`, path.join(path.dirname(file), `${path.basename(file, path.extname(file))}.meta.json`)].find(exists);
58
+ if (!sidecar) return { status: 'no-sidecar', sidecar: null };
59
+ let want;
60
+ try {
61
+ want = JSON.parse(fs.readFileSync(sidecar, 'utf8')).sha256;
62
+ } catch {
63
+ return { status: 'bad-json', sidecar };
64
+ }
65
+ const got = crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
66
+ return { status: typeof want === 'string' && want.toLowerCase() === got ? 'frozen' : 'mismatch', sidecar };
67
+ }
68
+
69
+ // Every intake file must be pinned: one valid snapshot does not excuse another.
70
+ function intake(root, cfg) {
71
+ const dir = kitPaths(root, cfg).intake;
72
+ const files = filesUnder(dir).filter((f) => {
73
+ const name = path.basename(f);
74
+ return name !== '.keep' && !name.endsWith('.meta.json');
75
+ });
76
+ if (files.length === 0) return [`no snapshot under ${rel(root, dir)}/`];
77
+ const blockers = [];
78
+ for (const f of files) {
79
+ const { status, sidecar } = intakePin(f);
80
+ const name = rel(root, f);
81
+ if (status === 'no-sidecar') blockers.push(`${name} has no sidecar .meta.json`);
82
+ else if (status === 'bad-json') blockers.push(`${rel(root, sidecar)} is not valid JSON`);
83
+ else if (status === 'mismatch') blockers.push(`${name} does not match the sha256 in its sidecar`);
84
+ }
85
+ return blockers;
86
+ }
87
+
88
+ // The Types of an open row that do not stop clarify: work only a person can do, or a fact still
89
+ // being gathered.
90
+ const PENDING_TYPES = ['Action', 'Information'];
91
+
92
+ // A row is open when it sits in the Open table, whatever its Type (REQ-1.4). An open Action or
93
+ // Information row is listed as pending. Any other open row blocks: Decision, Open, Counsel (an
94
+ // expert view not yet given), and an unknown or empty Type, so a typo never passes silently.
95
+ function clarify(root, cfg) {
96
+ const p = kitPaths(root, cfg);
97
+ if (!exists(p.decisions)) return [`${rel(root, p.decisions)} is missing`];
98
+ const rows = readDecisions(readText(p.decisions)).rows.filter((r) => r.table === 'open');
99
+ const open = new Map(rows.map((r) => [r.id, r.type]));
100
+ const cited = new Set();
101
+ // The gaps file names Open rows in order to close them; that is not the spec resting on them.
102
+ for (const f of filesUnder(p.spec, '.md').filter((x) => x !== p.gaps)) {
103
+ for (const r of refs(readText(f))) if (r.kind === 'id' && open.has(r.value)) cited.add(r.value);
104
+ }
105
+ const ids = [...cited].sort();
106
+ const blocks = (id) => !PENDING_TYPES.includes(open.get(id));
107
+ return {
108
+ blockers: ids.filter(blocks).map((id) => `${id} is Open and cited by the spec`),
109
+ pending: ids.filter((id) => !blocks(id)).map((id) => `${id} is Open (${open.get(id)}) and cited by the spec; it does not block`),
110
+ };
111
+ }
112
+
113
+ // Every REQ heading in the spec's own files (not contracts or another subfolder, as check's citation
114
+ // rule reads them): its ID, its file (relative to root, forward slashes), the 1-based line of the
115
+ // heading, and the text after the heading up to the next heading of the same or a higher level, or
116
+ // the next REQ heading of any level. S-11 and S-12 report findings at `file:line`.
117
+ export function reqBlocks(root, cfg) {
118
+ const dir = kitPaths(root, cfg).spec;
119
+ const own = exists(dir) ? listFiles(dir, { ext: '.md' }).filter((f) => !f.includes('/')).map((f) => path.join(dir, f)) : [];
120
+ return own.flatMap((f) => reqBlocksIn(readText(f)).map(({ id, line, block }) => ({ id, file: rel(root, f), line, block })));
121
+ }
122
+
123
+ // The REQ blocks of one file's text, read as `reqBlocks` reads them: `{id, line, block}`.
124
+ // `gaps close --req` reads the same REQ at the merge base with this.
125
+ export function reqBlocksIn(text) {
126
+ const reqHead = new RegExp(`^(${re('req').source})\\b`);
127
+ const all = lines(text);
128
+ const hs = headings(text);
129
+ const out = [];
130
+ hs.forEach((h, i) => {
131
+ const m = h.level >= 2 && h.level <= 3 ? reqHead.exec(h.text) : null;
132
+ if (!m) return;
133
+ const next = hs.slice(i + 1).find((n) => n.level <= h.level || reqHead.test(n.text));
134
+ out.push({ id: m[1], line: h.line, block: all.slice(h.line, next ? next.line - 1 : all.length).join('\n') });
135
+ });
136
+ return out;
137
+ }
138
+
139
+ const MARKER_START = '[NEEDS CLARIFICATION:';
140
+
141
+ // Every `[NEEDS CLARIFICATION: …]` marker in `text`, outside fences and code spans: its 1-based
142
+ // starting line and its text up to the closing `]`, a marker wrapped over lines joined with
143
+ // spaces. `spec verify` lists these; the stack stage refuses them.
144
+ export function clarificationMarkers(text) {
145
+ const ls = [...prose(text)].map(([l, n]) => [blankCodeSpans(l), n]);
146
+ const out = [];
147
+ for (let i = 0; i < ls.length; i++) {
148
+ let from = 0;
149
+ for (;;) {
150
+ const at = ls[i][0].indexOf(MARKER_START, from);
151
+ if (at === -1) break;
152
+ let rest = ls[i][0].slice(at);
153
+ let j = i;
154
+ while (!rest.includes(']') && j + 1 < ls.length && ls[j + 1][0].trim() !== '') rest += ` ${ls[++j][0].trim()}`;
155
+ const end = rest.indexOf(']');
156
+ out.push({ line: ls[i][1], text: end === -1 ? rest.trimEnd() : rest.slice(0, end + 1) });
157
+ if (j > i) break;
158
+ from = at + MARKER_START.length;
159
+ }
160
+ }
161
+ return out;
162
+ }
163
+
164
+ function specify(root, cfg) {
165
+ const reqs = reqBlocks(root, cfg);
166
+ if (reqs.length === 0) return [`${rel(root, kitPaths(root, cfg).spec)}/ has no REQ`];
167
+ const blockers = [];
168
+ for (const { id, block } of reqs) {
169
+ const missing = [];
170
+ if (!/\bSHALL\b/.test(block)) missing.push('SHALL');
171
+ if (!/^\s*Scenario:/m.test(block)) missing.push('Scenario:');
172
+ if (!/^\s*Cites:/m.test(block)) missing.push('Cites:');
173
+ if (!/^\s*Enforced by:/m.test(block)) missing.push('Enforced by:');
174
+ if (missing.length > 0) blockers.push(`${id} lacks ${missing.join(', ')}`);
175
+ }
176
+ return blockers;
177
+ }
178
+
179
+ // A directory counts as merged when nothing in it is untracked or changed and its content equals the default branch's.
180
+ // `exclude` lists files under `dir` left out of the comparison.
181
+ function unmerged(root, cfg, dir, what, exclude = []) {
182
+ if (!isRepo(root)) return [`${what} needs a git repository`];
183
+ if (!hasCommits(root)) return [`${what} needs a commit on ${cfg.defaultBranch}`];
184
+ const base = cfg.defaultBranch;
185
+ try {
186
+ assertRef(base);
187
+ git(root, ['rev-parse', '--verify', '--quiet', `${base}^{commit}`]);
188
+ } catch (e) {
189
+ if (e instanceof GitError) return [`${what} needs the default branch ${base}, which was not found`];
190
+ throw e;
191
+ }
192
+ const where = rel(root, dir);
193
+ const paths = [where, ...exclude.map((f) => `:(exclude)${rel(root, f)}`)];
194
+ if (git(root, ['status', '--porcelain', '--', ...paths]) !== '') return [`${where} has uncommitted changes`];
195
+ try {
196
+ git(root, ['diff', '--quiet', '--end-of-options', base, '--', ...paths]);
197
+ } catch (e) {
198
+ if (e instanceof GitError) return [`${where} differs from ${base}; merge the pull request`];
199
+ throw e;
200
+ }
201
+ return [];
202
+ }
203
+
204
+ // The gaps file is written on the gaps branch and stack.md on the plan branch, both after the spec
205
+ // merges, so this stage leaves them out.
206
+ function specReview(root, cfg) {
207
+ const p = kitPaths(root, cfg);
208
+ return unmerged(root, cfg, p.spec, 'spec review', [p.gaps, p.stack]);
209
+ }
210
+
211
+ // The line `gaps scan` writes into the gaps file. Without it the gap scan has not run, whatever the
212
+ // table holds: init's empty table is not a finished scan.
213
+ export const SCANNED_LINE = /^Scanned: \d{4}-\d{2}-\d{2} at \S+$/;
214
+
215
+ function gapScan(root, cfg) {
216
+ const file = kitPaths(root, cfg).gaps;
217
+ if (!exists(file)) return [`${rel(root, file)} is missing`];
218
+ const text = readText(file);
219
+ const { hasColumn, open } = openGapRows(text);
220
+ if (!hasColumn && re('gap', 'g').test(text)) return [`${rel(root, file)} has no Closed by column`];
221
+ if (![...prose(text)].some(([l]) => SCANNED_LINE.test(l.trim()))) return [`${rel(root, file)} has no Scanned: line; gaps scan has not run`];
222
+ return open.map((r) => `${r.id} is not closed`);
223
+ }
224
+
225
+ // The rows of every table in the gaps file with a Closed by column whose first cell is set and whose
226
+ // Closed by cell is empty: `{hasColumn, open: [{id, line}]}`, 1-based lines. The gap-scan stage and
227
+ // `gaps verify` both read open rows through this.
228
+ export function openGapRows(text) {
229
+ let hasColumn = false;
230
+ const open = [];
231
+ for (const t of tables(text)) {
232
+ const closed = t.header.findIndex((h) => h.toLowerCase() === 'closed by');
233
+ if (closed === -1) continue;
234
+ hasColumn = true;
235
+ t.rows.forEach((row, i) => {
236
+ if (row[0] && (row[closed] ?? '') === '') open.push({ id: row[0], line: t.line + 2 + i });
237
+ });
238
+ }
239
+ return { hasColumn, open };
240
+ }
241
+
242
+ function stack(root, cfg) {
243
+ const file = kitPaths(root, cfg).stack;
244
+ if (!exists(file)) return [`${rel(root, file)} is missing`];
245
+ const text = readText(file);
246
+ if (clarificationMarkers(text).length > 0) return [`${rel(root, file)} still has a [NEEDS CLARIFICATION marker`];
247
+ const body = text.replace(/^#.*$/gm, '').trim();
248
+ if (body === '' || /^not yet known\.?$/i.test(body)) return [`${rel(root, file)} says nothing is known yet`];
249
+ return [];
250
+ }
251
+
252
+ function readSlices(root, cfg) {
253
+ const slices = [];
254
+ const errors = [];
255
+ for (const f of findSliceFiles(root, cfg)) {
256
+ try {
257
+ slices.push(parseSliceFile(readText(f.path), f.path));
258
+ } catch (e) {
259
+ errors.push(e.message);
260
+ }
261
+ }
262
+ return { slices, errors };
263
+ }
264
+
265
+ function plan(root, cfg) {
266
+ const { slices, errors } = readSlices(root, cfg);
267
+ const named = new Set(slices.flatMap((s) => s.requirements));
268
+ const ids = [...new Set(reqBlocks(root, cfg).map((r) => r.id))];
269
+ const blockers = [
270
+ ...errors,
271
+ ...ids.filter((id) => !named.has(id)).map((id) => `${id} is named by no slice file`),
272
+ ];
273
+ return [...blockers, ...unmerged(root, cfg, kitPaths(root, cfg).phases, 'plan review')];
274
+ }
275
+
276
+ function build(root, cfg) {
277
+ const { errors } = readSlices(root, cfg);
278
+ if (errors.length > 0) return errors;
279
+ const all = listSlices(root, cfg);
280
+ if (all.length === 0) return ['no slice is planned'];
281
+ return all
282
+ .filter(({ state }) => state.state !== 'merged' && state.state !== 'released')
283
+ .map(({ state }) => `${state.slice} is ${state.state}, not merged`);
284
+ }
285
+
286
+ function release(root, cfg) {
287
+ const p = kitPaths(root, cfg);
288
+ const phases = exists(p.phases)
289
+ ? fs
290
+ .readdirSync(p.phases, { withFileTypes: true })
291
+ .map((d) => (d.isDirectory() ? /^P(\d+)(?:\b|[-_])/.exec(d.name) : null))
292
+ .filter(Boolean)
293
+ .map((m) => `P${m[1]}`)
294
+ : [];
295
+ if (phases.length === 0) return ['no phase is planned'];
296
+ return [...new Set(phases)]
297
+ .filter((id) => !exists(path.join(p.releases, `${id}.md`)))
298
+ .map((id) => `${id} has no releases/${id}.md`);
299
+ }
300
+
301
+ const CHECKS = { intake, clarify, specify, 'spec-review': specReview, 'gap-scan': gapScan, stack, plan, build, release };
302
+
303
+ // Evaluates the stages in order and stops after `upTo` (default: all), so later stages cost nothing.
304
+ export function programStage(root, cfg, { upTo = 'release' } = {}) {
305
+ const last = STAGES.indexOf(upTo);
306
+ if (last === -1) throw new Error(`unknown stage ${upTo}`);
307
+ // A check returns its blockers, or `{blockers, pending}` when it also lists rows that do not
308
+ // block. The result carries `pending` only when something is pending.
309
+ const pending = [];
310
+ const result = (r) => (pending.length > 0 ? { ...r, pending } : r);
311
+ for (const stage of STAGES.slice(0, last + 1)) {
312
+ const out = CHECKS[stage](root, cfg);
313
+ const blockers = Array.isArray(out) ? out : out.blockers;
314
+ if (!Array.isArray(out)) pending.push(...out.pending);
315
+ if (blockers.length > 0) return result({ stage, complete: false, blockers });
316
+ }
317
+ return result({ stage: upTo, complete: true, blockers: [] });
318
+ }
319
+
320
+ // requireStage(X) means X and every stage before it are complete; it throws for the first that is not.
321
+ export function requireStage(root, cfg, stage) {
322
+ const now = programStage(root, cfg, { upTo: stage });
323
+ if (!now.complete) throw new StageError(now.stage, now.blockers[0]);
324
+ return now;
325
+ }
@@ -0,0 +1,156 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { readText } from '../fs.js';
5
+ import { headings, lines } from '../markdown.js';
6
+ import { kitPaths } from '../paths.js';
7
+ import { findSliceFiles, parsePhaseFile, parseSliceFile, phaseOfDir } from '../slicefile.js';
8
+ import { readSlice } from './index.js';
9
+
10
+ export const MARKER = '<!-- slicekit:generated:end -->';
11
+ const LINE_MARK = /\s*<!--\s*slicekit:(?:example|pending\s+P\d+\/S-\d{2})\s*-->\s*$/;
12
+
13
+ const TEMPLATE = fileURLToPath(new URL('../../templates/docs/BUILD.md', import.meta.url));
14
+ const TITLE = '# BUILD — the queue';
15
+ const PHASE_HEADING = /^Phase\s+(\d+)\b/;
16
+ const IN_PROGRESS = new Set(['tests-red', 'building']);
17
+ const OPEN_PR = new Set(['draft-pr', 'in-review', 'changes-requested', 'ci-green', 'ready']);
18
+ const DONE = new Set(['merged', 'released']);
19
+
20
+ export function statusCell(state) {
21
+ if (DONE.has(state.state)) return 'Done';
22
+ if (OPEN_PR.has(state.state)) return `PR ${state.pr?.number != null ? `#${state.pr.number}` : '-'}`;
23
+ if (IN_PROGRESS.has(state.state)) return 'Todo (in progress)';
24
+ return 'Todo';
25
+ }
26
+
27
+ const cell = (s) => String(s).replace(/\s*\n\s*/g, ' ').replace(/(?<!\\)\|/g, '\\|');
28
+
29
+ // The text under a level-2 heading, up to the next level-2 heading, trimmed; null when absent.
30
+ function section(text, title) {
31
+ const hs = headings(text).filter((h) => h.level === 2);
32
+ const i = hs.findIndex((h) => h.text.toLowerCase() === title.toLowerCase());
33
+ if (i === -1) return null;
34
+ const all = lines(text);
35
+ const end = i + 1 < hs.length ? hs[i + 1].line - 1 : all.length;
36
+ const body = all.slice(hs[i].line, end).join('\n').trim();
37
+ return body === '' ? null : body;
38
+ }
39
+
40
+ // Phase directories that carry a phase file, in phase order: [{ n, id, name, dir, order }].
41
+ function phases(root, cfg) {
42
+ const dir = kitPaths(root, cfg).phases;
43
+ if (!fs.existsSync(dir)) return [];
44
+ const out = [];
45
+ for (const d of fs.readdirSync(dir, { withFileTypes: true })) {
46
+ const phase = phaseOfDir(d.name);
47
+ if (!d.isDirectory() || !phase) continue;
48
+ const phaseDir = path.join(dir, d.name);
49
+ const own = `${phase.id}.md`;
50
+ const candidates = fs
51
+ .readdirSync(phaseDir)
52
+ .filter((f) => f.endsWith('.md') && !/^S-\d+/.test(f))
53
+ .sort((a, b) => (a === own ? -1 : b === own ? 1 : a.localeCompare(b)));
54
+ for (const f of candidates) {
55
+ const text = readText(path.join(phaseDir, f));
56
+ const parsed = parsePhaseFile(text);
57
+ if (parsed && parsed.id === phase.id) {
58
+ out.push({ n: phase.n, id: parsed.id, name: parsed.name, dir: phaseDir, order: section(text, 'Order') });
59
+ break;
60
+ }
61
+ }
62
+ }
63
+ return out.sort((a, b) => a.n - b.n);
64
+ }
65
+
66
+ // Every phase that has a phase file or a slice file. A phase with slices and no phase file takes
67
+ // its heading from the directory name, so its slices still reach BUILD.md, and is warned.
68
+ function allPhases(root, cfg, sliceFiles, onWarning) {
69
+ const byId = new Map(phases(root, cfg).map((p) => [p.id, p]));
70
+ for (const f of sliceFiles) {
71
+ if (byId.has(f.phaseId)) continue;
72
+ const dirPhase = phaseOfDir(path.basename(f.phaseDir));
73
+ byId.set(f.phaseId, { n: dirPhase.n, id: dirPhase.id, name: dirPhase.name, dir: f.phaseDir, order: null });
74
+ onWarning(`phase ${f.phaseId} has no phase file; heading taken from the directory`);
75
+ }
76
+ return [...byId.values()].sort((a, b) => a.n - b.n);
77
+ }
78
+
79
+ function preamble(cfg) {
80
+ const text = readText(TEMPLATE).replace(/\{\{docsRoot\}\}/g, cfg.docsRoot);
81
+ const all = lines(text);
82
+ const start = all.findIndex((l) => l.trim() === TITLE);
83
+ return all.slice(start + 1).join('\n').trim();
84
+ }
85
+
86
+ // Splits BUILD.md at the marker. Without a marker the whole text is generated and tail is null.
87
+ export function generatedRegion(text) {
88
+ const all = lines(text);
89
+ const i = all.findIndex((l) => l.trim() === MARKER);
90
+ if (i === -1) return { generated: all.join('\n'), tail: null };
91
+ return { generated: all.slice(0, i).join('\n') + (i > 0 ? '\n' : ''), tail: all.slice(i + 1).join('\n') };
92
+ }
93
+
94
+ // A BUILD.md written before the marker existed: keep every level-2 section except the generated
95
+ // phases; drop the title and preamble above the first section.
96
+ function migratedTail(text, generatedPhases) {
97
+ const all = lines(text);
98
+ const hs = headings(text).filter((h) => h.level === 2);
99
+ const kept = [];
100
+ hs.forEach((h, i) => {
101
+ const m = PHASE_HEADING.exec(h.text);
102
+ if (m && generatedPhases.has(Number(m[1]))) return;
103
+ const end = i + 1 < hs.length ? hs[i + 1].line - 1 : all.length;
104
+ kept.push(all.slice(h.line - 1, end).join('\n').trim());
105
+ });
106
+ return kept.length === 0 ? '' : `\n${kept.join('\n\n')}\n`;
107
+ }
108
+
109
+ // The text below the marker, verbatim, less any `## Phase <n>` section whose phase is now generated.
110
+ function prunedTail(text, generatedPhases) {
111
+ const all = lines(text);
112
+ const hs = headings(text).filter((h) => h.level === 2);
113
+ const drop = new Set();
114
+ hs.forEach((h, i) => {
115
+ const m = PHASE_HEADING.exec(h.text);
116
+ if (!m || !generatedPhases.has(Number(m[1]))) return;
117
+ const end = i + 1 < hs.length ? hs[i + 1].line - 1 : all.length;
118
+ for (let j = h.line - 1; j < end; j++) drop.add(j);
119
+ });
120
+ if (drop.size === 0) return text;
121
+ const kept = all.filter((_, j) => !drop.has(j));
122
+ if (all[all.length - 1] === '' && kept[kept.length - 1] !== '') kept.push('');
123
+ return kept.join('\n');
124
+ }
125
+
126
+ // `onWarning` receives each problem that does not stop the render, such as a phase without a phase file.
127
+ export function renderBuild(root, cfg, existingText = '', { onWarning = () => {} } = {}) {
128
+ const sliceFiles = findSliceFiles(root, cfg);
129
+ const found = allPhases(root, cfg, sliceFiles, onWarning);
130
+ const slicesByPhase = new Map();
131
+ for (const f of sliceFiles) {
132
+ const slice = parseSliceFile(readText(f.path), f.path);
133
+ const list = slicesByPhase.get(f.phaseId) ?? [];
134
+ list.push({ slice, state: readSlice(root, cfg, slice.id) });
135
+ slicesByPhase.set(f.phaseId, list);
136
+ }
137
+
138
+ const out = [TITLE, '', preamble(cfg)];
139
+ for (const phase of found) {
140
+ out.push('', `## Phase ${phase.n} — ${phase.name}`, '');
141
+ out.push('| Slice | Name | Done when | Group | Status |', '|---|---|---|---|---|');
142
+ for (const { slice, state } of slicesByPhase.get(phase.id) ?? []) {
143
+ const short = slice.id.split('/')[1];
144
+ // A slice file's example or pending marker stays in the slice file, which is checked bullet by bullet.
145
+ const done = slice.doneWhen.map((d) => d.replace(LINE_MARK, '').replace(/(?<!\.)\.$/, '')).join('; ');
146
+ out.push(`| ${short} | ${cell(slice.name)} | ${cell(done)} | ${cell(slice.group)} | ${statusCell(state)} |`);
147
+ }
148
+ if (phase.order) out.push('', phase.order);
149
+ }
150
+ const generated = `${out.join('\n')}\n`;
151
+
152
+ const { tail } = generatedRegion(existingText ?? '');
153
+ const generatedPhases = new Set(found.map((p) => p.n));
154
+ const rest = tail === null ? migratedTail(existingText ?? '', generatedPhases) : prunedTail(tail, generatedPhases);
155
+ return `${generated}\n${MARKER}\n${rest}`;
156
+ }
@@ -0,0 +1,58 @@
1
+ // D-35: a verdict given on head `from` still holds on a later head `to` when `to` descends from
2
+ // `from` and every change between them is the kit's own bookkeeping: the state directory, the
3
+ // review verdicts, the journal directory (every file under it) and BUILD.md. Without this, committing the verdict and the state
4
+ // file would itself make every verdict stale. Any doubt (unknown commit, no repository) is "no".
5
+ import path from 'node:path';
6
+ import { isSha, sameSha } from '../evidence.js';
7
+ import { GitError, git, resolveCommit } from '../git.js';
8
+ import { kitPaths } from '../paths.js';
9
+
10
+ // The bookkeeping paths as repository-relative prefixes (a directory ends in `/`). None of them
11
+ // depends on docsRoot, so the default only keeps kitPaths happy.
12
+ function bookkeeping(root) {
13
+ const p = kitPaths(root, { docsRoot: 'docs' });
14
+ const prefix = git(root, ['rev-parse', '--show-prefix']);
15
+ const rel = (f) => prefix + path.relative(root, f).split(path.sep).join('/');
16
+ return {
17
+ dirs: [p.state, path.join(p.kit, 'reviews'), p.journalDir].map((d) => `${rel(d)}/`),
18
+ files: [rel(p.build)],
19
+ };
20
+ }
21
+
22
+ const inBookkeeping = ({ dirs, files }, f) => files.includes(f) || dirs.some((d) => f.startsWith(d));
23
+
24
+ // A test of whether a repository-relative POSIX path of the repository at `root` is bookkeeping,
25
+ // with the bookkeeping paths worked out once (one git process) for every path it is asked about.
26
+ export function bookkeepingTest(root) {
27
+ const kept = bookkeeping(root);
28
+ return (rel) => inBookkeeping(kept, rel);
29
+ }
30
+
31
+ // Whether `rel`, a repository-relative POSIX path of the repository at `root`, is bookkeeping.
32
+ export function isBookkeepingPath(root, rel) {
33
+ return bookkeepingTest(root)(rel);
34
+ }
35
+
36
+ export function headCovers(root, from, to) {
37
+ if (!isSha(from) || !isSha(to)) return false;
38
+ if (sameSha(from, to)) return true;
39
+ try {
40
+ const a = resolveCommit(root, from);
41
+ const b = resolveCommit(root, to);
42
+ if (!a || !b) return false;
43
+ if (a === b) return true;
44
+ try {
45
+ git(root, ['merge-base', '--is-ancestor', a, b]);
46
+ } catch (e) {
47
+ if (e instanceof GitError) return false;
48
+ throw e;
49
+ }
50
+ const out = git(root, ['diff', '--name-only', '--no-renames', a, b, '--']);
51
+ const changed = out === '' ? [] : out.split('\n');
52
+ const kept = bookkeeping(root);
53
+ return changed.every((f) => inBookkeeping(kept, f));
54
+ } catch (e) {
55
+ if (e instanceof GitError) return false;
56
+ throw e;
57
+ }
58
+ }