slicekit 0.0.0-stage → 0.1.1

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 +253 -2
  3. package/bin/slicekit.js +4 -0
  4. package/package.json +23 -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 +276 -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 +59 -0
  154. package/templates/githooks/pre-merge-commit +59 -0
  155. package/templates/githooks/prepare-commit-msg +74 -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/intake.js ADDED
@@ -0,0 +1,409 @@
1
+ // `slicekit intake` (REQ-1.2, REQ-2.2): frozen snapshots of the source documents. A snapshot is
2
+ // written once, next to a sidecar that pins its bytes, and committed by the command (D-19).
3
+ import crypto from 'node:crypto';
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { addDecision, readDecisions } from './decisions.js';
7
+ import { listFiles } from './fs.js';
8
+ import { GitError, commitPaths, currentBranch, git, gitUser } from './git.js';
9
+ import { kitPaths } from './paths.js';
10
+
11
+ // `code` 1: refused (a protected branch, a failed fetch, a text rule on the target). `code` 2: bad
12
+ // input (no such file, a bad slug, a URL with a password, a source over the size cap).
13
+ export class IntakeError extends Error {
14
+ constructor(code, message) {
15
+ super(message);
16
+ this.name = 'IntakeError';
17
+ this.code = code;
18
+ }
19
+ }
20
+
21
+ const FETCH_TIMEOUT_MS = 30_000;
22
+ export const MAX_BYTES = 50 * 1024 * 1024;
23
+ const CONTENT_TYPES = {
24
+ 'text/markdown': 'md',
25
+ 'text/plain': 'txt',
26
+ 'text/html': 'html',
27
+ 'application/pdf': 'pdf',
28
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
29
+ };
30
+ const EXT = /^[a-z0-9]{1,10}$/;
31
+ const SLUG = /^[a-z0-9][a-z0-9-]{0,59}$/;
32
+ const SECRET_PARAMS = new Set(['token', 'key', 'sig', 'signature', 'auth', 'password', 'secret', 'access_token', 'code']);
33
+
34
+ const posix = (p) => p.split(path.sep).join('/');
35
+ const sha256 = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
36
+ const isUrl = (source) => /^https?:\/\//i.test(source);
37
+ const tooBig = (what) => new IntakeError(2, `${what} is larger than ${MAX_BYTES / 1024 / 1024} MB`);
38
+
39
+ // Lower-cased, each run of characters other than a-z0-9 one dash, dashes trimmed, at most 60
40
+ // characters; `source` when nothing is left.
41
+ export function slugify(text) {
42
+ const slug = String(text)
43
+ .toLowerCase()
44
+ .replace(/[^a-z0-9]+/g, '-')
45
+ .replace(/^-+|-+$/g, '')
46
+ .slice(0, 60)
47
+ .replace(/-+$/, '');
48
+ return slug === '' ? 'source' : slug;
49
+ }
50
+
51
+ const secretParam = (name) => {
52
+ const n = name.toLowerCase();
53
+ return SECRET_PARAMS.has(n) || n.startsWith('x-amz-');
54
+ };
55
+
56
+ // `a=1&token=x` with each secret value replaced by `***`; the other pairs are kept as written.
57
+ function maskPairs(text) {
58
+ if (!text.includes('=')) return text;
59
+ return text
60
+ .split('&')
61
+ .map((pair) => {
62
+ const i = pair.indexOf('=');
63
+ if (i < 0) return pair;
64
+ const key = pair.slice(0, i);
65
+ let name = key;
66
+ try {
67
+ name = decodeURIComponent(key.replace(/\+/g, ' '));
68
+ } catch {
69
+ // A malformed escape: judge the name as written.
70
+ }
71
+ return secretParam(name) ? `${key}=***` : pair;
72
+ })
73
+ .join('&');
74
+ }
75
+
76
+ // The form of a URL that may be written down: no user name or password, and the value of each
77
+ // query (or fragment) parameter that names a secret replaced by `***`.
78
+ export function maskUrl(url) {
79
+ const u = new URL(url);
80
+ u.username = '';
81
+ u.password = '';
82
+ if (u.search) u.search = maskPairs(u.search.slice(1));
83
+ if (u.hash) u.hash = maskPairs(u.hash.slice(1));
84
+ return u.href;
85
+ }
86
+
87
+ // A base name's extension, lower-cased, or null when it has none fit for a file name.
88
+ function extOf(base) {
89
+ const ext = path.posix.extname(base).slice(1).toLowerCase();
90
+ return EXT.test(ext) ? ext : null;
91
+ }
92
+
93
+ function urlBase(url) {
94
+ const { pathname } = new URL(url);
95
+ try {
96
+ return path.posix.basename(decodeURIComponent(pathname));
97
+ } catch {
98
+ return path.posix.basename(pathname);
99
+ }
100
+ }
101
+
102
+ async function readCapped(res, shown) {
103
+ if (Number(res.headers.get('content-length')) > MAX_BYTES) throw tooBig(shown);
104
+ if (!res.body) return Buffer.from(await res.arrayBuffer());
105
+ const chunks = [];
106
+ let total = 0;
107
+ for await (const chunk of res.body) {
108
+ total += chunk.length;
109
+ if (total > MAX_BYTES) throw tooBig(shown);
110
+ chunks.push(chunk);
111
+ }
112
+ return Buffer.concat(chunks);
113
+ }
114
+
115
+ async function fetchSource(source, fetchImpl) {
116
+ let parsed;
117
+ try {
118
+ parsed = new URL(source);
119
+ } catch {
120
+ throw new IntakeError(2, 'the source is not a valid URL');
121
+ }
122
+ if (parsed.username !== '' || parsed.password !== '') {
123
+ throw new IntakeError(2, 'the URL carries a user name or password; remove it');
124
+ }
125
+ const shown = maskUrl(source);
126
+ let res;
127
+ let bytes;
128
+ try {
129
+ res = await fetchImpl(parsed.href, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), redirect: 'follow' });
130
+ if (res.ok) bytes = await readCapped(res, shown);
131
+ } catch (e) {
132
+ if (e instanceof IntakeError) throw e;
133
+ const reason = String(e.cause?.message ?? e.message).split(source).join(shown).split(parsed.href).join(shown);
134
+ throw new IntakeError(1, `could not fetch ${shown}: ${reason}`);
135
+ }
136
+ if (!res.ok) throw new IntakeError(1, `could not fetch ${shown}: ${res.status}`);
137
+ const final = typeof res.url === 'string' && res.url !== '' && res.url !== parsed.href ? res.url : null;
138
+ const base = urlBase(final ?? parsed.href);
139
+ const type = (res.headers.get('content-type') ?? '').split(';')[0].trim().toLowerCase();
140
+ return {
141
+ bytes,
142
+ base,
143
+ ext: extOf(base) ?? CONTENT_TYPES[type] ?? 'bin',
144
+ origin: { origin: shown, ...(final ? { finalUrl: maskUrl(final) } : {}) },
145
+ };
146
+ }
147
+
148
+ function readSource(root, source) {
149
+ const abs = path.resolve(root, source);
150
+ let stat;
151
+ try {
152
+ stat = fs.statSync(abs);
153
+ } catch (e) {
154
+ if (e.code === 'ENOENT' || e.code === 'ENOTDIR') throw new IntakeError(2, `no such file ${source}`);
155
+ throw e;
156
+ }
157
+ if (!stat.isFile()) throw new IntakeError(2, `not a file ${source}`);
158
+ if (stat.size > MAX_BYTES) throw tooBig(source);
159
+ const base = path.basename(abs);
160
+ return { bytes: fs.readFileSync(abs), base, ext: extOf(base) ?? 'bin', origin: { origin: posix(abs) } };
161
+ }
162
+
163
+ // The `.gitattributes` rule that keeps every intake file byte for byte in every clone: without it a
164
+ // `text=auto` or `core.autocrlf` setting rewrites line endings and the sidecar's SHA-256 stops
165
+ // matching. init writes it too (S-14); a snapshot adds it when it is missing.
166
+ const squash = (line) => line.trim().replace(/\s+/g, ' ');
167
+ const holdsRule = (text, rule) => text.split(/\r?\n/).some((l) => squash(l) === rule || squash(l) === `/${rule}`);
168
+
169
+ // Appends `rule` when the file lacks it; returns the function that puts the file back.
170
+ function ensureAttribute(file, rule) {
171
+ const before = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
172
+ if (before !== null && holdsRule(before, rule)) return () => {};
173
+ const eol = before?.includes('\r\n') ? '\r\n' : '\n';
174
+ const sep = before === null || before === '' || before.endsWith('\n') ? '' : eol;
175
+ fs.writeFileSync(file, `${before ?? ''}${sep}${rule}${eol}`);
176
+ return () => (before === null ? fs.rmSync(file, { force: true }) : fs.writeFileSync(file, before));
177
+ }
178
+
179
+ // HEAD's `.gitattributes` (trimmed, as git() returns it), or null when HEAD has none.
180
+ function committedAttributes(root) {
181
+ try {
182
+ return git(root, ['show', 'HEAD:./.gitattributes']);
183
+ } catch (e) {
184
+ if (e instanceof GitError) return null;
185
+ throw e;
186
+ }
187
+ }
188
+
189
+ const committedHoldsRule = (root, rule) => holdsRule(committedAttributes(root) ?? '', rule);
190
+
191
+ // Whether `.gitattributes` differs from HEAD by anything other than the intake rule: the one change
192
+ // a snapshot may commit is the rule itself (left over when an earlier snapshot commit was refused).
193
+ function othersEdited(root, current, rule) {
194
+ if (git(root, ['status', '--porcelain', '--', '.gitattributes']) === '') return false;
195
+ if (current === null || !holdsRule(current, rule)) return true;
196
+ const norm = (t) => t.replace(/\r\n/g, '\n').trim();
197
+ const without = current.split(/\r?\n/).filter((l) => squash(l) !== rule && squash(l) !== `/${rule}`).join('\n');
198
+ return norm(without) !== norm(committedAttributes(root) ?? '');
199
+ }
200
+
201
+ function textAttribute(root, rel) {
202
+ const out = git(root, ['--literal-pathspecs', 'check-attr', 'text', '--', rel]);
203
+ return out.slice(out.lastIndexOf(': ') + 2);
204
+ }
205
+
206
+ function onWorkBranch(root, cfg, what) {
207
+ const branch = currentBranch(root);
208
+ if (branch === null || branch === cfg.defaultBranch || cfg.protectedBranches.includes(branch)) {
209
+ throw new IntakeError(1, `${what} on a work branch; run slicekit branch spec <slug>`);
210
+ }
211
+ }
212
+
213
+ // Copies `source` (a file path, or an http(s) URL) into `<docsRoot>/intake/` as
214
+ // `<UTC date>-<slug>.<ext>` with a sidecar `<name>.meta.json` holding {origin, [finalUrl,] sha256,
215
+ // by, at}, and commits both. A snapshot is never overwritten: the same bytes under the same name are
216
+ // reported with `created: false` (and committed, when an earlier commit was refused); other bytes
217
+ // take the next free `-2`, `-3`, ... name.
218
+ export async function snapshot(root, cfg, source, { slug, who, now = new Date(), fetchImpl = fetch } = {}) {
219
+ if (slug !== undefined && !SLUG.test(slug)) {
220
+ throw new IntakeError(2, `slug '${slug}' must be lowercase letters, digits and dashes, at most 60, not starting with a dash`);
221
+ }
222
+ onWorkBranch(root, cfg, 'snapshot');
223
+ const dir = kitPaths(root, cfg).intake;
224
+ const rule = `${posix(path.relative(root, dir))}/** -text`;
225
+ // The snapshot commit carries .gitattributes when it adds the rule: a person's other edits to it
226
+ // must not ride along.
227
+ const attributes = path.join(root, '.gitattributes');
228
+ const current = fs.existsSync(attributes) ? fs.readFileSync(attributes, 'utf8') : null;
229
+ if (othersEdited(root, current, rule)) {
230
+ throw new IntakeError(1, '.gitattributes has uncommitted changes; commit or stash them first');
231
+ }
232
+ const src = isUrl(source) ? await fetchSource(source, fetchImpl) : readSource(root, source);
233
+ const digest = sha256(src.bytes);
234
+ const stem = `${now.toISOString().slice(0, 10)}-${slug ?? slugify(path.posix.basename(src.base, path.posix.extname(src.base)))}`;
235
+
236
+ let name;
237
+ let created = true;
238
+ for (let n = 1; ; n++) {
239
+ name = `${stem}${n === 1 ? '' : `-${n}`}.${src.ext}`;
240
+ const candidate = path.join(dir, name);
241
+ if (fs.existsSync(candidate)) {
242
+ if (sha256(fs.readFileSync(candidate)) !== digest) continue;
243
+ created = false;
244
+ break;
245
+ }
246
+ if (!fs.existsSync(`${candidate}.meta.json`)) break;
247
+ }
248
+ const file = path.join(dir, name);
249
+ const sidecar = `${file}.meta.json`;
250
+ const fileRel = posix(path.relative(root, file));
251
+ const sidecarRel = posix(path.relative(root, sidecar));
252
+
253
+ const restore = ensureAttribute(attributes, rule);
254
+ const text = textAttribute(root, fileRel);
255
+ if (text !== 'unset') {
256
+ restore();
257
+ throw new IntakeError(1, `${fileRel} would not be stored byte for byte: git check-attr text gives '${text}'; a .gitattributes rule overrides '${rule}'`);
258
+ }
259
+
260
+ if (created) {
261
+ fs.mkdirSync(dir, { recursive: true });
262
+ fs.writeFileSync(file, src.bytes, { flag: 'wx' });
263
+ const meta = { ...src.origin, sha256: digest, by: who || gitUser(root) || 'unknown', at: now.toISOString() };
264
+ fs.writeFileSync(sidecar, `${JSON.stringify(meta, null, 2)}\n`, { flag: 'wx' });
265
+ }
266
+ const paths = [fileRel, sidecarRel, ...(committedHoldsRule(root, rule) ? [] : ['.gitattributes'])];
267
+ commitPaths(root, paths, `docs(intake): snapshot ${name}`);
268
+ return { file, sidecar, created };
269
+ }
270
+
271
+ // ---- the interview (REQ-2.2) ----
272
+ // One question waits at a time, and it cannot be followed by another until its answer is a D row.
273
+ // The product pass comes first; the first platform question closes it. The session lives in this
274
+ // worktree's own git directory, `<git-dir>/slicekit/interview.json`, as {startedAt, specFiles,
275
+ // pending, asked}: never in the work tree, so `git add -A` cannot stage it, and one per worktree.
276
+ // pre-edit denies the file, so an agent cannot rewrite `pending` by hand.
277
+
278
+ const PASSES = ['product', 'platform'];
279
+
280
+ function sessionPath(root) {
281
+ return path.join(git(root, ['rev-parse', '--path-format=absolute', '--git-dir']), 'slicekit', 'interview.json');
282
+ }
283
+
284
+ // Each file under the spec directory, root-relative and POSIX, with the SHA-256 of its bytes.
285
+ function specFilesNow(root, cfg) {
286
+ const dir = kitPaths(root, cfg).spec;
287
+ if (!fs.existsSync(dir)) return {};
288
+ const base = posix(path.relative(root, dir));
289
+ return Object.fromEntries(listFiles(dir).map((f) => [`${base}/${f}`, sha256(fs.readFileSync(path.join(dir, f)))]));
290
+ }
291
+
292
+ function readSession(root) {
293
+ const file = sessionPath(root);
294
+ if (!fs.existsSync(file)) return null;
295
+ try {
296
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
297
+ } catch {
298
+ throw new IntakeError(1, `${posix(file)} is not valid JSON; delete it to start the interview again`);
299
+ }
300
+ }
301
+
302
+ function writeSession(root, session) {
303
+ const file = sessionPath(root);
304
+ fs.mkdirSync(path.dirname(file), { recursive: true });
305
+ fs.writeFileSync(file, `${JSON.stringify(session, null, 2)}\n`);
306
+ }
307
+
308
+ const waiting = (session) =>
309
+ new IntakeError(1, `answer the last question first: "${session.pending.question}" has no decision row`);
310
+
311
+ function oneLineText(field, value) {
312
+ if (typeof value !== 'string' || value.trim() === '') throw new IntakeError(2, `${field} is required`);
313
+ if (/[\r\n]/.test(value)) throw new IntakeError(2, `${field} must be one line`);
314
+ return value.trim();
315
+ }
316
+
317
+ // Holds `question` as the one waiting for an answer; returns its number in the session.
318
+ export function ask(root, cfg, { pass, topic, question, now = new Date() } = {}) {
319
+ if (!PASSES.includes(pass)) throw new IntakeError(2, `pass must be product or platform, not '${pass}'`);
320
+ const t = oneLineText('topic', topic);
321
+ const q = oneLineText('question', question);
322
+ onWorkBranch(root, cfg, 'the interview');
323
+ const session = readSession(root) ?? { startedAt: now.toISOString(), specFiles: specFilesNow(root, cfg), pending: null, asked: [] };
324
+ if (session.pending) throw waiting(session);
325
+ if (pass === 'platform' && !session.asked.some((a) => a.pass === 'product')) {
326
+ throw new IntakeError(1, 'ask the product questions first');
327
+ }
328
+ if (pass === 'product' && session.asked.some((a) => a.pass === 'platform')) {
329
+ throw new IntakeError(1, 'the product pass is closed; ask platform questions now');
330
+ }
331
+ session.pending = { pass, topic: t, question: q };
332
+ writeSession(root, session);
333
+ return { n: session.asked.length + 1 };
334
+ }
335
+
336
+ // Whether the row `id` in `text` holds `question`, as addDecision writes it: escaped, and perhaps
337
+ // after an `Interface: <name>. ` or `Replaces D-<n>. ` lead.
338
+ function rowHolds(text, id, question) {
339
+ const row = readDecisions(text).rows.find((r) => r.id === id);
340
+ if (!row) return false;
341
+ const forms = [question, question.replace(/\|/g, '\\|')];
342
+ return forms.some((f) => row.question === f || row.question.endsWith(`. ${f}`));
343
+ }
344
+
345
+ // Writes the waiting question's answer as a D row through addDecision, then clears it. An `open`
346
+ // answer is an Open row with `why` and `recommendation`. The row's ID is saved in the session first,
347
+ // so a run that stopped after the row and before the session finishes the bookkeeping here instead
348
+ // of writing a second row.
349
+ export function answer(root, cfg, { answer: text, type, who, open = false, why, recommendation, iface, now = new Date() } = {}) {
350
+ onWorkBranch(root, cfg, 'the interview');
351
+ const session = readSession(root);
352
+ if (!session?.pending) throw new IntakeError(1, 'no question is waiting for an answer');
353
+ const file = kitPaths(root, cfg).decisions;
354
+ const before = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
355
+ const finish = (id) => {
356
+ const { decision, ...asked } = session.pending;
357
+ session.asked.push({ ...asked, decision: id });
358
+ session.pending = null;
359
+ writeSession(root, session);
360
+ return { id };
361
+ };
362
+ if (before !== null && session.pending.decision && rowHolds(before, session.pending.decision, session.pending.question)) {
363
+ return finish(session.pending.decision);
364
+ }
365
+ if (before !== null) {
366
+ session.pending.decision = readDecisions(before).next;
367
+ writeSession(root, session);
368
+ }
369
+ const { id } = addDecision(root, cfg, {
370
+ type: type ?? (open ? 'Open' : 'Decision'),
371
+ open,
372
+ question: session.pending.question,
373
+ ...(open ? { why, recommendation } : { answer: text }),
374
+ who: who || undefined,
375
+ iface,
376
+ today: now.toISOString().slice(0, 10),
377
+ });
378
+ return finish(id);
379
+ }
380
+
381
+ // Ends the interview: refuses while a question waits, while a pass asked nothing, or when a file
382
+ // under the spec directory appeared or changed; otherwise commits the answers and returns the
383
+ // session's open rows.
384
+ export function done(root, cfg) {
385
+ const session = readSession(root);
386
+ if (!session) throw new IntakeError(1, 'no interview is under way; run slicekit intake ask first');
387
+ if (session.pending) throw waiting(session);
388
+ for (const pass of PASSES) {
389
+ if (!session.asked.some((a) => a.pass === pass)) throw new IntakeError(1, `the ${pass} pass asked nothing`);
390
+ }
391
+ const known = session.specFiles ?? {};
392
+ for (const [f, digest] of Object.entries(specFilesNow(root, cfg))) {
393
+ if (!Object.hasOwn(known, f)) throw new IntakeError(1, `intake writes no spec text; remove ${f}`);
394
+ if (known[f] !== digest) throw new IntakeError(1, `intake writes no spec text; ${f} changed during the interview`);
395
+ }
396
+ onWorkBranch(root, cfg, 'interview answers');
397
+
398
+ const paths = kitPaths(root, cfg);
399
+ const rows = readDecisions(fs.readFileSync(paths.decisions, 'utf8')).rows;
400
+ const open = session.asked
401
+ .filter((a) => rows.some((r) => r.id === a.decision && r.table === 'open'))
402
+ .map((a) => ({ id: a.decision, question: a.question }));
403
+ const files = [paths.decisions, paths.platform, paths.observability]
404
+ .filter((f) => fs.existsSync(f))
405
+ .map((f) => posix(path.relative(root, f)));
406
+ const commit = commitPaths(root, files, 'docs(intake): interview answers');
407
+ fs.rmSync(sessionPath(root), { force: true });
408
+ return { open, commit };
409
+ }