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
@@ -0,0 +1,289 @@
1
+ // Decision rows (REQ-1.4): one row per decision in `<docsRoot>/decisions.md`, with an ID, a type,
2
+ // who answered and when. A row of the Open table is open, whatever its Type; settling moves it to
3
+ // the Settled table under the same ID. A settled row is never rewritten: a reversal is a new row
4
+ // that names the one it replaces.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { exists, listFiles, readText } from './fs.js';
8
+ import { git } from './git.js';
9
+ import { headings, prose, tableCells as cells } from './markdown.js';
10
+ import { kitPaths } from './paths.js';
11
+
12
+ export const TYPES = ['Decision', 'Action', 'Information', 'Counsel', 'Open'];
13
+
14
+ // `code` 1: a file problem (missing file or table, wrong columns, a settled row). `code` 2: bad input.
15
+ export class DecisionError extends Error {
16
+ constructor(code, message) {
17
+ super(message);
18
+ this.name = 'DecisionError';
19
+ this.code = code;
20
+ }
21
+ }
22
+
23
+ const SECTIONS = { settled: 'Settled', open: 'Open' };
24
+ // The columns of each table, as `templates/docs/decisions.md` writes them.
25
+ const COLUMNS = {
26
+ settled: ['#', 'Type', 'Question', 'Answer', 'Who, when'],
27
+ open: ['#', 'Type', 'Question', 'Why it matters', 'Recommendation'],
28
+ };
29
+ const ID = /^D-(\d+)$/;
30
+
31
+ const isRow = (l) => /^\s*\|.*\|\s*$/.test(l);
32
+ const isDivider = (l) => /^\s*\|(\s*:?-+:?\s*\|)+\s*$/.test(l);
33
+
34
+ // Each section's table: `{header: [cells], rows: [{line, cells}], last}` with 1-based lines, `last`
35
+ // the line after which a new row goes. Null for a section or table that is absent.
36
+ function sections(text) {
37
+ const all = text.replace(/^/, '').split(/\r?\n/);
38
+ const hs = headings(text);
39
+ const inProse = new Set([...prose(text)].map(([, n]) => n));
40
+ const out = { settled: null, open: null };
41
+ for (const [key, name] of Object.entries(SECTIONS)) {
42
+ const i = hs.findIndex((h) => h.level === 2 && h.text.toLowerCase() === name.toLowerCase());
43
+ if (i === -1) continue;
44
+ const start = hs[i].line + 1;
45
+ const end = i + 1 < hs.length ? hs[i + 1].line - 1 : all.length;
46
+ for (let n = start; n < end; n++) {
47
+ if (!inProse.has(n) || !isRow(all[n - 1]) || !isDivider(all[n] ?? '')) continue;
48
+ const rows = [];
49
+ let m = n + 2;
50
+ while (m <= end && inProse.has(m) && isRow(all[m - 1])) {
51
+ rows.push({ line: m, cells: cells(all[m - 1]) });
52
+ m++;
53
+ }
54
+ out[key] = { header: cells(all[n - 1]), rows, last: m - 1 };
55
+ break;
56
+ }
57
+ }
58
+ return out;
59
+ }
60
+
61
+ // `{rows, next}`. `next` is the highest number plus one, zero-padded to the widest ID already used.
62
+ export function readDecisions(text) {
63
+ const rows = [];
64
+ const found = sections(text);
65
+ for (const table of ['settled', 'open']) {
66
+ for (const { line, cells: c } of found[table]?.rows ?? []) {
67
+ const m = ID.exec(c[0] ?? '');
68
+ if (!m) continue;
69
+ const base = { id: c[0], n: Number(m[1]), table, type: c[1] ?? '', question: c[2] ?? '', line };
70
+ rows.push(
71
+ table === 'settled'
72
+ ? { ...base, answer: c[3] ?? '', who: c[4] ?? '', why: null, recommendation: null }
73
+ : { ...base, answer: null, who: null, why: c[3] ?? '', recommendation: c[4] ?? '' },
74
+ );
75
+ }
76
+ }
77
+ return { rows, next: nextId('D', rows) };
78
+ }
79
+
80
+ // The next ID after `rows` (each `{id, n}`): the highest number plus one, zero-padded to the widest
81
+ // ID already used. `gaps.md` numbers its rows the same way.
82
+ export function nextId(prefix, rows) {
83
+ const width = Math.max(1, ...rows.map((r) => r.id.length - prefix.length - 1));
84
+ const high = Math.max(0, ...rows.map((r) => r.n));
85
+ return `${prefix}-${String(high + 1).padStart(width, '0')}`;
86
+ }
87
+
88
+ export const posix = (p) => p.split(path.sep).join('/');
89
+
90
+ function load(root, cfg) {
91
+ const file = kitPaths(root, cfg).decisions;
92
+ if (!exists(file)) throw new DecisionError(1, `${posix(path.relative(root, file))} is missing; run slicekit init`);
93
+ return { file, text: fs.readFileSync(file, 'utf8') };
94
+ }
95
+
96
+ // Writes a temporary file in the same directory, then renames it over the file, so a reader never
97
+ // sees half a file.
98
+ export function save(file, text) {
99
+ const tmp = path.join(path.dirname(file), `.${path.basename(file)}.${process.pid}.${Date.now()}.tmp`);
100
+ try {
101
+ fs.writeFileSync(tmp, text);
102
+ fs.renameSync(tmp, file);
103
+ } catch (e) {
104
+ fs.rmSync(tmp, { force: true });
105
+ throw e;
106
+ }
107
+ }
108
+
109
+ function oneLine(field, value) {
110
+ if (value === undefined || value === null) return;
111
+ if (typeof value !== 'string') throw new DecisionError(2, `${field} must be text`);
112
+ if (/[\r\n]/.test(value)) throw new DecisionError(2, `${field} must be one line`);
113
+ }
114
+
115
+ export const escape = (s) => s.trim().replace(/\|/g, '\\|');
116
+ export const row = (cs) => `| ${cs.map(escape).join(' | ')} |`;
117
+
118
+ function whoDefault(root) {
119
+ try {
120
+ return git(root, ['config', 'user.name']) || 'unknown';
121
+ } catch {
122
+ return 'unknown';
123
+ }
124
+ }
125
+
126
+ const todayUtc = () => new Date().toISOString().slice(0, 10);
127
+ const whoWhen = (root, who, today) => `${(who ?? whoDefault(root)).trim() || 'unknown'}, ${today ?? todayUtc()}`;
128
+
129
+ // The file's lines, each with its own ending. A new line takes the first line's ending; no other
130
+ // line's ending changes, except that a last line with no ending gets one when a line follows it.
131
+ export const split = (text) => text.split(/(?<=\n)/);
132
+
133
+ export function insertAfter(text, after, line) {
134
+ const parts = split(text);
135
+ const eol = parts[0]?.endsWith('\r\n') ? '\r\n' : '\n';
136
+ const prev = parts[after - 1];
137
+ if (prev !== undefined && !prev.endsWith('\n')) parts[after - 1] = prev + eol;
138
+ parts.splice(after, 0, line + eol);
139
+ return parts.join('');
140
+ }
141
+
142
+ function removeLine(text, n) {
143
+ const parts = split(text);
144
+ parts.splice(n - 1, 1);
145
+ return parts.join('');
146
+ }
147
+
148
+ // The table under `## <name>`, refused when absent or when its columns are not the template's.
149
+ function table(found, key) {
150
+ const t = found[key];
151
+ if (!t) throw new DecisionError(1, `decisions.md has no ${SECTIONS[key]} table`);
152
+ const want = COLUMNS[key];
153
+ if (t.header.length !== want.length || t.header.some((h, i) => h !== want[i])) {
154
+ throw new DecisionError(1, `decisions table ${SECTIONS[key]} has columns ${t.header.join(' | ')}; expected ${want.join(' | ')}`);
155
+ }
156
+ return t;
157
+ }
158
+
159
+ function byNumber(rows, id) {
160
+ const m = ID.exec(id ?? '');
161
+ return m ? rows.find((r) => r.n === Number(m[1])) : undefined;
162
+ }
163
+
164
+ const SOURCE = /^\S+:\d+$/;
165
+
166
+ // `open: true`, or type Open, puts the row in the Open table, where it keeps its real Type.
167
+ export function addDecision(root, cfg, opts) {
168
+ const { question, answer, why, recommendation, replaces, iface, today } = opts;
169
+ const open = Boolean(opts.open) || opts.type === 'Open';
170
+ const type = opts.type ?? (open ? 'Open' : undefined);
171
+ if (!TYPES.includes(type)) throw new DecisionError(2, `unknown type '${type}'; one of ${TYPES.join(', ')}`);
172
+ for (const field of ['question', 'answer', 'why', 'recommendation', 'who', 'replaces', 'today']) oneLine(field, opts[field]);
173
+ if (iface) {
174
+ oneLine('interface', iface.name);
175
+ oneLine('source', iface.source);
176
+ }
177
+ if (!question?.trim()) throw new DecisionError(2, 'question is required');
178
+ if (open) {
179
+ if (!why?.trim() || !recommendation?.trim()) throw new DecisionError(2, 'an open row needs why and recommendation');
180
+ if (answer !== undefined) throw new DecisionError(2, 'an open row takes why and recommendation, not answer');
181
+ } else {
182
+ if (!answer?.trim()) throw new DecisionError(2, `a ${type} row needs answer`);
183
+ if (why !== undefined || recommendation !== undefined) throw new DecisionError(2, `a ${type} row takes answer, not why or recommendation`);
184
+ }
185
+ if (iface) {
186
+ if (!iface.name?.trim()) throw new DecisionError(2, 'interface needs a name');
187
+ if (/\.( |$)/.test(iface.name.trim())) throw new DecisionError(2, 'interface name must not hold ". " or end in "."');
188
+ if (iface.source !== undefined && !SOURCE.test(iface.source)) throw new DecisionError(2, 'source must be <file>:<line>');
189
+ }
190
+
191
+ const { file, text } = load(root, cfg);
192
+ const { rows, next: id } = readDecisions(text);
193
+ let replaced;
194
+ if (replaces !== undefined) {
195
+ replaced = byNumber(rows, replaces);
196
+ if (!replaced) throw new DecisionError(2, `unknown decision ${replaces}`);
197
+ if (replaced.table === 'open') throw new DecisionError(2, `${replaced.id} is still open; settle it instead`);
198
+ }
199
+ const target = table(sections(text), open ? 'open' : 'settled');
200
+
201
+ let q = question.trim();
202
+ if (replaced) q = `Replaces ${replaced.id}. ${q}`;
203
+ if (iface) q = `Interface: ${iface.name.trim()}. ${q}`;
204
+ const named = iface?.source !== undefined ? ` Named at ${iface.source}.` : '';
205
+ const cellsOut = open
206
+ ? [id, type, q, `${why.trim()}${named}`, recommendation]
207
+ : [id, type, q, `${answer.trim()}${named}`, whoWhen(root, opts.who, today)];
208
+ save(file, insertAfter(text, target.last, row(cellsOut)));
209
+ return { id };
210
+ }
211
+
212
+ const NAMED_AT = /\s*\bNamed at (\S+:\d+)\.$/;
213
+ const sentence = (s) => (s ?? '').trim().replace(/\.+$/, '');
214
+
215
+ // The Settled answer of a settled open row: the answer, then the open row's reasons in brackets
216
+ // (an empty part left out), then the `Named at` source, so an interface row keeps it.
217
+ function settledAnswer(answer, why, recommendation) {
218
+ const source = NAMED_AT.exec(why);
219
+ const parts = [];
220
+ const reason = sentence(why.replace(NAMED_AT, ''));
221
+ if (reason) parts.push(`Asked because: ${reason}.`);
222
+ if (sentence(recommendation)) parts.push(`Recommended: ${sentence(recommendation)}.`);
223
+ const own = NAMED_AT.exec(answer.trim());
224
+ let out = answer.trim().replace(NAMED_AT, '');
225
+ if (parts.length > 0) out += ` (${parts.join(' ')})`;
226
+ const where = own ?? source;
227
+ return where ? `${out} Named at ${where[1]}.` : out;
228
+ }
229
+
230
+ // Moves an Open-table row to Settled under the same ID. A row whose Type is Open (or not a known
231
+ // Type) needs `type`, one of the other Types; any other row keeps its Type, and a different
232
+ // `type` is refused.
233
+ export function settleDecision(root, cfg, id, { answer, who, today, type } = {}) {
234
+ for (const [field, value] of Object.entries({ answer, who, today, type })) oneLine(field, value);
235
+ if (!answer?.trim()) throw new DecisionError(2, 'settle needs answer');
236
+ const settledTypes = TYPES.filter((t) => t !== 'Open');
237
+ if (type !== undefined && !settledTypes.includes(type)) {
238
+ throw new DecisionError(2, `settle --type must be one of ${settledTypes.join(', ')}`);
239
+ }
240
+ const { file, text } = load(root, cfg);
241
+ const found = byNumber(readDecisions(text).rows, id);
242
+ if (!found) throw new DecisionError(2, `unknown decision ${id}`);
243
+ if (found.table === 'settled') {
244
+ throw new DecisionError(1, `${found.id} is settled; a reversal is a new row (decide add --replaces ${found.id})`);
245
+ }
246
+ const known = settledTypes.includes(found.type);
247
+ if (!known && type === undefined) throw new DecisionError(2, `${found.id} has Type ${found.type || '(empty)'}; settle with --type`);
248
+ if (known && type !== undefined && type !== found.type) {
249
+ throw new DecisionError(2, `${found.id} has Type ${found.type}; settle keeps it`);
250
+ }
251
+ const found2 = sections(text);
252
+ table(found2, 'open');
253
+ table(found2, 'settled');
254
+ const line = row([found.id, known ? found.type : type, found.question, settledAnswer(answer, found.why, found.recommendation), whoWhen(root, who, today)]);
255
+ const without = removeLine(text, found.line);
256
+ save(file, insertAfter(without, table(sections(without), 'settled').last, line));
257
+ return { id: found.id };
258
+ }
259
+
260
+ const INTERFACE = /^Interface: (.+?)\.(?: |$)/;
261
+
262
+ function interfaceRows(text) {
263
+ return readDecisions(text)
264
+ .rows.map((r) => {
265
+ const m = INTERFACE.exec(r.question);
266
+ if (!m) return null;
267
+ const s = NAMED_AT.exec(r.answer ?? r.why ?? '');
268
+ return { id: r.id, name: m[1], source: s ? s[1] : null, line: r.line };
269
+ })
270
+ .filter(Boolean);
271
+ }
272
+
273
+ // The rows whose question begins `Interface: `, with the `Named at` source or null.
274
+ export const interfacesNamed = (text) => interfaceRows(text).map(({ id, name, source }) => ({ id, name, source }));
275
+
276
+ // Each interface row that no contract under `<docsRoot>/spec/contracts/` names on its `Cites:` line.
277
+ export function interfacesWithoutContract(root, cfg) {
278
+ const { text } = load(root, cfg);
279
+ const dir = kitPaths(root, cfg).contracts;
280
+ const cited = new Set();
281
+ const files = exists(dir) ? listFiles(dir, { ext: '.md' }).map((f) => path.join(dir, f)) : [];
282
+ for (const f of files) {
283
+ for (const [l] of prose(readText(f))) {
284
+ if (!/^\s*Cites:/.test(l)) continue;
285
+ for (const m of l.matchAll(/\bD-(\d+)\b/g)) cited.add(Number(m[1]));
286
+ }
287
+ }
288
+ return interfaceRows(text).filter((i) => !cited.has(Number(ID.exec(i.id)[1])));
289
+ }
@@ -0,0 +1,27 @@
1
+ // The shapes of evidence the kit accepts from a person or a host, in one place: the git host
2
+ // adapter and the state machine read SHAs and dates through these.
3
+
4
+ const SHA = /^[0-9a-f]{7,40}$/;
5
+
6
+ export const isSha = (s) => typeof s === 'string' && SHA.test(s);
7
+
8
+ export const isDate = (s) => typeof s === 'string' && !Number.isNaN(Date.parse(s));
9
+
10
+ export function assertSha(sha) {
11
+ if (!isSha(sha)) throw new Error(`commit sha must be 7 to 40 lowercase hex characters, got '${sha}'`);
12
+ return sha;
13
+ }
14
+
15
+ export function assertDate(isoDate) {
16
+ if (!isDate(isoDate)) throw new Error(`expected an ISO date, got '${isoDate}'`);
17
+ return Date.parse(isoDate);
18
+ }
19
+
20
+ // Two SHAs name the same commit when equal, or, when either is abbreviated, when one is a prefix
21
+ // of the other. Two full SHAs are compared whole.
22
+ export function sameSha(a, b) {
23
+ if (!isSha(a) || !isSha(b)) return false;
24
+ if (a === b) return true;
25
+ if (a.length === 40 && b.length === 40) return false;
26
+ return a.startsWith(b) || b.startsWith(a);
27
+ }
package/src/fs.js ADDED
@@ -0,0 +1,38 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ export function readText(p) {
5
+ return fs.readFileSync(p, 'utf8').replace(/^/, '').replace(/\r\n/g, '\n');
6
+ }
7
+
8
+ export function writeText(p, s) {
9
+ fs.mkdirSync(path.dirname(p), { recursive: true });
10
+ const tmp = `${p}.tmp-${process.pid}`;
11
+ fs.writeFileSync(tmp, s.replace(/\r\n/g, '\n'));
12
+ try {
13
+ fs.renameSync(tmp, p);
14
+ } catch (e) {
15
+ fs.rmSync(tmp, { force: true });
16
+ throw e;
17
+ }
18
+ }
19
+
20
+ export function exists(p) {
21
+ return fs.existsSync(p);
22
+ }
23
+
24
+ export function listFiles(dir, { ext, ignore = ['node_modules', '.git', '.worktrees'] } = {}) {
25
+ const out = [];
26
+ const walk = (abs, rel) => {
27
+ for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
28
+ const relPath = rel ? `${rel}/${entry.name}` : entry.name;
29
+ if (entry.isDirectory()) {
30
+ if (!ignore.includes(entry.name)) walk(path.join(abs, entry.name), relPath);
31
+ } else if (!ext || path.extname(entry.name).toLowerCase() === ext.toLowerCase()) {
32
+ out.push(relPath);
33
+ }
34
+ }
35
+ };
36
+ walk(dir, '');
37
+ return out.sort();
38
+ }
package/src/gaps.js ADDED
@@ -0,0 +1,271 @@
1
+ // Gap rows (REQ-2.4): one `G-<n>` row per gap in `<docsRoot>/spec/gaps.md`, of one of five classes,
2
+ // open until its `Closed by` cell names a settled decision row or a REQ changed on this branch. The
3
+ // gap-scan stage (`src/stage.js`) refuses while any row has that cell empty.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { citedRefs } from './check/rules/citations.js';
7
+ import { insertAfter, interfacesWithoutContract, nextId, posix, readDecisions, row, save, split } from './decisions.js';
8
+ import { exists, readText } from './fs.js';
9
+ import { GitError, git } from './git.js';
10
+ import { headings, lines, prose, tables } from './markdown.js';
11
+ import { kitPaths } from './paths.js';
12
+ import { SCANNED_LINE, openGapRows, reqBlocks, reqBlocksIn } from './stage.js';
13
+
14
+ export const CLASSES = ['missing', 'unsupported', 'contradiction', 'unknown', 'unrequested'];
15
+
16
+ // `code` 1: a file problem (missing file or table, a row with no G id, a closed row). `code` 2: bad
17
+ // input or an unknown ID.
18
+ export class GapError extends Error {
19
+ constructor(code, message) {
20
+ super(message);
21
+ this.name = 'GapError';
22
+ this.code = code;
23
+ }
24
+ }
25
+
26
+ // The columns of the table, as `templates/docs/spec/gaps.md` writes them.
27
+ const COLUMNS = ['#', 'Class', 'Where', 'What', 'Closed by'];
28
+ const CLOSED = COLUMNS.indexOf('Closed by');
29
+ const ID = /^G-(\d+)$/;
30
+ const sameColumns = (header) => header.length === COLUMNS.length && header.every((h, i) => h === COLUMNS[i]);
31
+
32
+ // The gaps table: `{rows: [{line, cells}], last}`, 1-based lines, `last` the line after which a new
33
+ // row goes. Null when no table has the template's columns.
34
+ function gapTable(text) {
35
+ const t = tables(text).find((x) => sameColumns(x.header));
36
+ if (!t) return null;
37
+ const rows = t.rows.map((cells, i) => ({ line: t.line + 2 + i, cells }));
38
+ return { header: t.line, rows, last: t.line + 1 + t.rows.length };
39
+ }
40
+
41
+ // `{rows, next}`, with `next` numbered as `readDecisions` numbers decision rows. A row whose first
42
+ // cell is not a G id is left out here; `addGap` and `closeGap` refuse the file instead.
43
+ export function readGaps(text) {
44
+ const rows = [];
45
+ for (const { line, cells: c } of gapTable(text)?.rows ?? []) {
46
+ const m = ID.exec(c[0] ?? '');
47
+ if (!m) continue;
48
+ rows.push({ id: c[0], n: Number(m[1]), cls: c[1] ?? '', where: c[2] ?? '', what: c[3] ?? '', closedBy: c[CLOSED] ?? '', line });
49
+ }
50
+ return { rows, next: nextId('G', rows) };
51
+ }
52
+
53
+ // The gap-scan stage counts every row with a first cell, so a row the command cannot read is
54
+ // refused here rather than skipped.
55
+ function load(root, cfg) {
56
+ const file = kitPaths(root, cfg).gaps;
57
+ const rel = posix(path.relative(root, file));
58
+ if (!exists(file)) throw new GapError(1, `${rel} is missing; run slicekit init`);
59
+ const text = fs.readFileSync(file, 'utf8');
60
+ const table = gapTable(text);
61
+ if (!table) throw new GapError(1, `${rel} has no table with columns ${COLUMNS.join(' | ')}`);
62
+ const bad = table.rows.find((r) => !ID.test(r.cells[0] ?? ''));
63
+ if (bad) throw new GapError(1, `gaps table row ${bad.line} has no G id`);
64
+ return { file, text, table };
65
+ }
66
+
67
+ function field(name, value) {
68
+ if (typeof value !== 'string') throw new GapError(2, `${name} is required`);
69
+ if (/[\r\n]/.test(value)) throw new GapError(2, `${name} must be one line`);
70
+ if (value.trim() === '') throw new GapError(2, `${name} is required`);
71
+ return value.trim();
72
+ }
73
+
74
+ function replaceLine(text, n, line) {
75
+ const parts = split(text);
76
+ const eol = /\r?\n$/.exec(parts[n - 1])?.[0] ?? '';
77
+ parts[n - 1] = line + eol;
78
+ return parts.join('');
79
+ }
80
+
81
+ const byNumber = (rows, id, re) => {
82
+ const m = re.exec(id ?? '');
83
+ return m ? rows.find((r) => r.n === Number(m[1])) : undefined;
84
+ };
85
+
86
+ // Appends a gap row and returns its ID. A row with the same class, where and what is not written
87
+ // again: its ID comes back with `added: false`, so a repeated scan adds nothing.
88
+ export function addGap(root, cfg, { cls, where, what } = {}) {
89
+ if (!CLASSES.includes(cls)) throw new GapError(2, `unknown class '${cls}'; one of ${CLASSES.join(', ')}`);
90
+ const w = field('where', where);
91
+ const t = field('what', what);
92
+ const { file, text, table } = load(root, cfg);
93
+ const { rows, next } = readGaps(text);
94
+ const same = rows.find((r) => r.cls === cls && r.where === w && r.what === t);
95
+ if (same) return { id: same.id, added: false };
96
+ save(file, insertAfter(text, table.last, row([next, cls, w, t, ''])));
97
+ return { id: next, added: true };
98
+ }
99
+
100
+ // The commit this branch forked from the default branch, or null when there is none to compare with.
101
+ function mergeBase(root, cfg) {
102
+ for (const ref of [cfg.defaultBranch, `origin/${cfg.defaultBranch}`]) {
103
+ try {
104
+ return git(root, ['merge-base', 'HEAD', ref]);
105
+ } catch (e) {
106
+ if (!(e instanceof GitError)) throw e;
107
+ }
108
+ }
109
+ return null;
110
+ }
111
+
112
+ // A REQ closes a gap only when its block differs from the same REQ at the merge base: the REQ
113
+ // change REQ-2.4 asks for. A REQ new since the base, or in a file new since it, counts as changed.
114
+ function assertReqChanged(root, cfg, now) {
115
+ const base = mergeBase(root, cfg);
116
+ if (!base) throw new GapError(2, `${now.id} has no merge base with ${cfg.defaultBranch} to compare with; change it on a branch first`);
117
+ let then;
118
+ try {
119
+ then = reqBlocksIn(git(root, ['show', `${base}:${now.file}`])).find((r) => r.id === now.id);
120
+ } catch (e) {
121
+ if (!(e instanceof GitError)) throw e;
122
+ }
123
+ if (then && then.block.trim() === now.block.trim()) {
124
+ throw new GapError(2, `${now.id} is unchanged from ${base.slice(0, 7)}; change it first`);
125
+ }
126
+ }
127
+
128
+ // Writes a decision ID or a REQ ID into the row's `Closed by` cell, keeping every other cell. The
129
+ // decision must be a settled row of decisions.md; the REQ a heading of the spec changed since the
130
+ // merge base. A closed row is not closed again.
131
+ export function closeGap(root, cfg, id, { decision, req } = {}) {
132
+ if ((decision === undefined) === (req === undefined)) throw new GapError(2, 'close needs exactly one of decision and req');
133
+ const by = field(decision !== undefined ? 'decision' : 'req', decision ?? req);
134
+ const { file, text, table } = load(root, cfg);
135
+ const gap = byNumber(readGaps(text).rows, id, ID);
136
+ if (!gap) throw new GapError(2, `unknown gap ${id}`);
137
+ let closedBy;
138
+ let reqNow;
139
+ if (decision !== undefined) {
140
+ const p = kitPaths(root, cfg).decisions;
141
+ const rows = exists(p) ? readDecisions(fs.readFileSync(p, 'utf8')).rows : [];
142
+ const d = byNumber(rows, by, /^D-(\d+)$/);
143
+ if (!d) throw new GapError(2, `unknown decision ${by}`);
144
+ if (d.table === 'open') throw new GapError(2, `${d.id} is open; settle it first (slicekit decide settle ${d.id})`);
145
+ closedBy = d.id;
146
+ } else {
147
+ reqNow = reqBlocks(root, cfg).find((r) => r.id === by);
148
+ if (!reqNow) throw new GapError(2, `unknown requirement ${by}`);
149
+ closedBy = by;
150
+ }
151
+ if (gap.closedBy !== '') throw new GapError(1, `${gap.id} is closed by ${gap.closedBy}`);
152
+ if (reqNow) assertReqChanged(root, cfg, reqNow);
153
+ const cells = [...table.rows.find((r) => r.line === gap.line).cells];
154
+ while (cells.length <= CLOSED) cells.push('');
155
+ cells[CLOSED] = closedBy;
156
+ save(file, replaceLine(text, gap.line, row(cells)));
157
+ return { id: gap.id, closedBy };
158
+ }
159
+
160
+ const NOT_YET_KNOWN = /^not yet known\.?$/i;
161
+
162
+ // Each `##` section of the platform, observability and runbook files whose body is the one line
163
+ // `Not yet known` (REQ-1.11), at its heading line.
164
+ function notYetKnown(root, cfg) {
165
+ const p = kitPaths(root, cfg);
166
+ const out = [];
167
+ for (const file of [p.platform, p.observability, p.runbook]) {
168
+ if (!exists(file)) continue;
169
+ const text = readText(file);
170
+ const all = lines(text);
171
+ const hs = headings(text);
172
+ hs.forEach((h, i) => {
173
+ if (h.level !== 2) return;
174
+ const next = hs.slice(i + 1).find((n) => n.level <= 2);
175
+ const body = all.slice(h.line, next ? next.line - 1 : all.length).filter((l) => l.trim() !== '');
176
+ if (body.length !== 1 || !NOT_YET_KNOWN.test(body[0].trim())) return;
177
+ out.push({ cls: 'unknown', where: `${posix(path.relative(root, file))}:${h.line}`, what: `${h.text} not yet known` });
178
+ });
179
+ }
180
+ return out;
181
+ }
182
+
183
+ // Each Open decision row (REQ-1.4), each REQ whose `Cites:` names one, and each interface named at
184
+ // intake that no contract cites.
185
+ function fromDecisions(root, cfg) {
186
+ const p = kitPaths(root, cfg);
187
+ if (!exists(p.decisions)) return [];
188
+ const where = posix(path.relative(root, p.decisions));
189
+ const open = readDecisions(readText(p.decisions)).rows.filter((r) => r.table === 'open');
190
+ const openIds = new Set(open.map((r) => r.id));
191
+ const out = open.map((r) => ({ cls: 'unknown', where: `${where}:${r.line}`, what: `${r.id} is open: ${r.question}` }));
192
+ for (const { id, file, line, block } of reqBlocks(root, cfg)) {
193
+ const cited = citedRefs([...prose(block)].map(([l, n]) => [l, n + line]));
194
+ const names = [...new Set(cited.filter((r) => r.kind === 'decision' && openIds.has(r.name)).map((r) => r.name))];
195
+ for (const d of names) out.push({ cls: 'unknown', where: `${file}:${line}`, what: `${id} rests on open ${d}` });
196
+ }
197
+ for (const i of interfacesWithoutContract(root, cfg)) {
198
+ out.push({ cls: 'missing', where: i.source ?? `${where}:${i.line}`, what: `interface ${i.name} named at intake has no contract` });
199
+ }
200
+ return out;
201
+ }
202
+
203
+ // Every gap a script can find, in candidate order. Judgement classes (contradiction, unrequested,
204
+ // and missing beyond named interfaces) are the auditor's.
205
+ const candidates = (root, cfg) => [...notYetKnown(root, cfg), ...fromDecisions(root, cfg)];
206
+
207
+ // A scan candidate matches a row of the same class, file and What, whatever the line: an edit above
208
+ // a candidate moves its line, and that is not a new gap.
209
+ const fileOf = (where) => where.replace(/:\d+$/, '');
210
+ const key = (g) => `${g.cls}\u0000${fileOf(g.where)}\u0000${g.what}`;
211
+
212
+ const today = () => new Date().toISOString().slice(0, 10);
213
+
214
+ function shortHead(root) {
215
+ try {
216
+ return git(root, ['rev-parse', '--short=7', 'HEAD']);
217
+ } catch (e) {
218
+ if (e instanceof GitError) return 'no-commit';
219
+ throw e;
220
+ }
221
+ }
222
+
223
+ // Writes the `Scanned: <date> at <short sha>` line the gap-scan stage requires, just above the
224
+ // table, or replaces the one there when the scan added rows. A scan that added nothing leaves an
225
+ // existing line, so a re-scan on a clean checkout leaves the tree clean.
226
+ function markScanned(root, cfg, added) {
227
+ const { file, text, table } = load(root, cfg);
228
+ const line = `Scanned: ${today()} at ${shortHead(root)}`;
229
+ const at = [...prose(text)].find(([l]) => SCANNED_LINE.test(l.trim()));
230
+ if (at) {
231
+ if (added && at[0].trim() !== line) save(file, replaceLine(text, at[1], line));
232
+ return;
233
+ }
234
+ const blankBefore = table.header === 1 || lines(text)[table.header - 2].trim() === '';
235
+ let out = insertAfter(text, table.header - 1, '');
236
+ out = insertAfter(out, table.header - 1, line);
237
+ if (!blankBefore) out = insertAfter(out, table.header - 1, '');
238
+ save(file, out);
239
+ }
240
+
241
+ // Writes a row for each gap a script can find, through `addGap`, then the scan line, so a second
242
+ // run adds nothing. Returns `[{id, added, cls, where, what}]` in candidate order.
243
+ export function scanGaps(root, cfg) {
244
+ const out = [];
245
+ for (const c of candidates(root, cfg)) {
246
+ const same = readGaps(load(root, cfg).text).rows.find((r) => key(r) === key(c));
247
+ out.push({ ...(same ? { id: same.id, added: false } : addGap(root, cfg, c)), ...c });
248
+ }
249
+ markScanned(root, cfg, out.some((g) => g.added));
250
+ return out;
251
+ }
252
+
253
+ // What stands between the gaps file and a finished gap scan, without the spec-review check (the
254
+ // spec differs from the default branch while a REQ change closes a gap): `[{where, message}]`, one
255
+ // per open row, per candidate a fresh scan would add, and for a file no scan has marked.
256
+ export function verifyGaps(root, cfg) {
257
+ const { file, text } = load(root, cfg);
258
+ const rel = posix(path.relative(root, file));
259
+ const out = [];
260
+ if (![...prose(text)].some(([l]) => SCANNED_LINE.test(l.trim()))) {
261
+ out.push({ where: `${rel}:1`, message: 'gaps scan has not run; run slicekit gaps scan' });
262
+ }
263
+ // Open rows as the gap-scan stage counts them: in any table with a Closed by column.
264
+ for (const r of openGapRows(text).open) out.push({ where: `${rel}:${r.line}`, message: `${r.id} is not closed` });
265
+ const { rows } = readGaps(text);
266
+ const known = new Set(rows.map(key));
267
+ for (const c of candidates(root, cfg).filter((g) => !known.has(key(g)))) {
268
+ out.push({ where: c.where, message: `${c.cls} gap not in gaps.md: ${c.what}` });
269
+ }
270
+ return out;
271
+ }