slicekit 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +15 -13
  2. package/package.json +3 -2
  3. package/src/adapters/githost/fixture.js +24 -1
  4. package/src/adapters/githost/gh-json.js +69 -2
  5. package/src/adapters/githost/github.js +16 -1
  6. package/src/build/commit.js +152 -26
  7. package/src/build/config.js +50 -0
  8. package/src/build/pr.js +30 -15
  9. package/src/build/record.js +8 -2
  10. package/src/build/red.js +4 -3
  11. package/src/build/render.js +155 -0
  12. package/src/build/verdict.js +29 -0
  13. package/src/build/worktree.js +26 -5
  14. package/src/check/ci-event.js +17 -0
  15. package/src/check/rules/citations.js +53 -2
  16. package/src/check/rules/commands.js +32 -4
  17. package/src/check/rules/trailer.js +5 -16
  18. package/src/check/rules/workspace.js +86 -0
  19. package/src/cli/build.js +34 -8
  20. package/src/cli/ci.js +150 -0
  21. package/src/cli/decide.js +4 -3
  22. package/src/cli/gaps.js +6 -5
  23. package/src/cli/graph.js +79 -0
  24. package/src/cli/history.js +17 -0
  25. package/src/cli/hook.js +1 -1
  26. package/src/cli/impact.js +17 -0
  27. package/src/cli/index.js +28 -3
  28. package/src/cli/instructions.js +1 -1
  29. package/src/cli/intake.js +3 -3
  30. package/src/cli/query.js +39 -0
  31. package/src/cli/shipped.js +32 -0
  32. package/src/cli/state.js +42 -2
  33. package/src/cli/trace.js +21 -0
  34. package/src/cli/uncovered.js +32 -0
  35. package/src/cli/visualize.js +88 -0
  36. package/src/cli/workflow.js +6 -2
  37. package/src/config.js +85 -0
  38. package/src/graph/build.js +312 -0
  39. package/src/graph/docs.js +241 -0
  40. package/src/graph/git-walk.js +91 -0
  41. package/src/graph/history.js +60 -0
  42. package/src/graph/impact.js +143 -0
  43. package/src/graph/kitfiles.js +60 -0
  44. package/src/graph/load.js +93 -0
  45. package/src/graph/prs.js +136 -0
  46. package/src/graph/render.js +28 -0
  47. package/src/graph/schema.js +108 -0
  48. package/src/graph/shipped.js +32 -0
  49. package/src/graph/tests.js +45 -0
  50. package/src/graph/trace.js +83 -0
  51. package/src/graph/uncovered.js +16 -0
  52. package/src/graph/workspace.js +188 -0
  53. package/src/hook-cli.js +1 -1
  54. package/src/init.js +2 -0
  55. package/src/instructions.js +26 -8
  56. package/src/state/index.js +35 -4
  57. package/src/verdict.js +14 -2
  58. package/src/visualize/client.js +489 -0
  59. package/src/visualize/page.js +100 -0
  60. package/src/visualize/server.js +46 -0
  61. package/src/workflow.js +87 -9
  62. package/templates/instructions/agents/reviewer.md +7 -7
  63. package/templates/instructions/commands/build.md +34 -4
  64. package/templates/workflow/pins.json +2 -1
  65. package/templates/workflow/slicekit.yml +32 -1
package/src/build/pr.js CHANGED
@@ -6,15 +6,16 @@
6
6
  import fs from 'node:fs';
7
7
  import path from 'node:path';
8
8
  import { check } from '../check/index.js';
9
+ import { buildTestCommand } from '../config.js';
9
10
  import { git, headSha, pushBranch, pushTarget } from '../git.js';
10
11
  import { stateFileName } from '../ids.js';
11
12
  import { kitPaths } from '../paths.js';
12
13
  import { openOrUpdate } from '../pr.js';
13
14
  import { PrBodyError, getSection, renderPrBody } from '../prbody.js';
14
- import { readSlice } from '../state/index.js';
15
+ import { readSlice, recordHead } from '../state/index.js';
15
16
  import { headCovers } from '../state/covers.js';
16
17
  import { posixRel, runCommand, sliceIn, unusableRun } from './red.js';
17
- import { commitBookkeeping, recordState } from './record.js';
18
+ import { commitBookkeeping, commitState, recordState } from './record.js';
18
19
  import { overlapWith, planDefectLine } from './overlap.js';
19
20
  import { assertNotBehind } from './sync.js';
20
21
  import { nextVerdictPath } from './verdict.js';
@@ -119,9 +120,12 @@ function proofSummary(run) {
119
120
  return pass && fail && pass !== fail ? `${pass} · ${fail}` : run.summary;
120
121
  }
121
122
 
122
- // Each declared command in the worktree; -> the test run's pass and fail totals.
123
- function runCommands(wt, cfg) {
124
- const commands = cfg.commands ?? {};
123
+ // Each declared command in the worktree, the test command from .slicekit/local.json when the session
124
+ // root has one (D-43); -> { summary, command, local }: the test run's pass and fail totals, the test
125
+ // command run, and whether it was the local one.
126
+ function runCommands(root, wt, cfg, env) {
127
+ const tests = buildTestCommand(root, cfg, env);
128
+ const commands = { ...(cfg.commands ?? {}), test: tests.command };
125
129
  if (!text(commands.test)) throw new BuildError('commands.test is not declared in .slicekit/config.json');
126
130
  let summary = '';
127
131
  for (const name of COMMANDS) {
@@ -133,7 +137,7 @@ function runCommands(wt, cfg) {
133
137
  if (run.exit !== 0) throw new BuildError(`${name} failed (exit ${run.exit}): ${run.summary}`);
134
138
  if (name === 'test') summary = proofSummary(run);
135
139
  }
136
- return summary;
140
+ return { summary, command: tests.command, local: tests.local };
137
141
  }
138
142
 
139
143
  function assertNoOverlap(wt, cfg, id) {
@@ -141,8 +145,8 @@ function assertNoOverlap(wt, cfg, id) {
141
145
  if (defects.length > 0) throw new BuildError(defects.map((d) => planDefectLine(id, d)).join('\n'));
142
146
  }
143
147
 
144
- function checkClean(wt) {
145
- const result = check(wt);
148
+ function checkClean(wt, env) {
149
+ const result = check(wt, { env });
146
150
  if (result.exitCode === 0) return;
147
151
  const found = result.lines.slice(0, -1).filter((l) => !l.startsWith('(baseline) '));
148
152
  throw new BuildError(['slicekit check failed:', ...found.slice(0, 10), result.lines.at(-1)].join('\n'));
@@ -150,7 +154,7 @@ function checkClean(wt) {
150
154
 
151
155
  // `notes` may be left out for a slice that already has a pull request (the reviewing session does not
152
156
  // have the building session's notes): each section the notes do not give keeps the live body's text.
153
- export function openSlicePr(root, cfg, host, id, { notes, worktree } = {}) {
157
+ export function openSlicePr(root, cfg, host, id, { notes, worktree, env = process.env } = {}) {
154
158
  const given = notes === undefined ? null : readNotes(root, notes);
155
159
  const held = findWorktree(root, id, { worktree });
156
160
  const wt = held.path;
@@ -206,8 +210,8 @@ export function openSlicePr(root, cfg, host, id, { notes, worktree } = {}) {
206
210
  if (slice.runbook && !changed && !(runbookNote ?? '').trim().startsWith('no operational change')) {
207
211
  throw new BuildError(RUNBOOK_REFUSAL);
208
212
  }
209
- const summary = runCommands(wt, cfg);
210
- checkClean(wt);
213
+ const { summary, command: testCommand, local } = runCommands(root, wt, cfg, env);
214
+ checkClean(wt, env);
211
215
 
212
216
  // The pull request already open for the branch: the recorded one once there is a recording.
213
217
  const { open, livePr } = openPr();
@@ -223,7 +227,7 @@ export function openSlicePr(root, cfg, host, id, { notes, worktree } = {}) {
223
227
  name: slice.name,
224
228
  sections: {
225
229
  'Done when': slice.doneWhen.map((c, i) => `${i + 1}. ${c}`).join(' '),
226
- Proof: `\`${cfg.commands.test}\` → ${summary} · CI: pending`,
230
+ Proof: `\`${testCommand}\` → ${summary} · CI: pending`,
227
231
  Decisions: given?.decisions === undefined ? kept('Decisions', 'none') : given.decisions.join('; ') || 'none',
228
232
  Runbook: changed ? `changed: ${runbookRel}` : (runbookNote ?? NO_CHANGE),
229
233
  'Infra / migration': noted('infra', 'Infra / migration', 'none'),
@@ -248,11 +252,22 @@ export function openSlicePr(root, cfg, host, id, { notes, worktree } = {}) {
248
252
  const verdictPath = nextVerdictPath(root, id, current.verdicts ?? []);
249
253
  // The reviewer writes there at once: its directory is made here, as the path is printed.
250
254
  if (verdictPath) fs.mkdirSync(path.dirname(verdictPath), { recursive: true });
251
- const result = { number: made.number, url: made.url, created: made.created, verdictPath };
255
+ const result = { number: made.number, url: made.url, created: made.created, verdictPath, local: local ? testCommand : null, movedHead: null };
252
256
  // `build finish` marked it ready; a slice back at draft-pr has a draft pull request again.
253
257
  if (livePr?.draft === false) host.markDraft(made.number);
254
- // At draft-pr there is no draft-pr → draft-pr move: the reviewer reads the live head.
255
- if (current.state === 'draft-pr') return result;
258
+ // At draft-pr a head that moved since the recorded one (a merge of the default branch, any commit)
259
+ // is recorded in a bookkeeping commit and pushed, so the next verdict is taken on it (D-43). A head
260
+ // that adds only bookkeeping to the recorded one is the same work: nothing is recorded.
261
+ if (current.state === 'draft-pr') {
262
+ const head = headSha(wt);
263
+ if (current.pr?.headSha && !headCovers(wt, current.pr.headSha, head)) {
264
+ recordHead(wt, cfg, id, { number: made.number, url: made.url, headSha: head });
265
+ commitState(wt, cfg, id, 'head');
266
+ pushBranch(wt, { protectedBranches: cfg.protectedBranches, defaultBranch: cfg.defaultBranch });
267
+ result.movedHead = head;
268
+ }
269
+ return result;
270
+ }
256
271
  recordState(wt, cfg, id, 'draft-pr', {
257
272
  testExit: 0,
258
273
  checkExit: 0,
@@ -17,12 +17,18 @@ export function commitBookkeeping(wt, id, what, paths) {
17
17
  // A TransitionError from setState passes through unchanged, before anything is written.
18
18
  export function recordState(wt, cfg, id, to, evidence) {
19
19
  const state = setState(wt, cfg, id, to, evidence);
20
+ commitState(wt, cfg, id, to);
21
+ return state;
22
+ }
23
+
24
+ // BUILD.md rendered again from the state files, then one bookkeeping commit of the slice's state file
25
+ // and BUILD.md: `chore(slicekit): <id> <what>`.
26
+ export function commitState(wt, cfg, id, what) {
20
27
  const paths = kitPaths(wt, cfg);
21
28
  const before = exists(paths.build) ? readText(paths.build) : '';
22
29
  const after = renderBuild(wt, cfg, before);
23
30
  if (after !== before) writeText(paths.build, after);
24
31
  const files = [posixRel(wt, path.join(paths.state, stateFileName(id)))];
25
32
  if (exists(paths.build)) files.push(posixRel(wt, paths.build));
26
- commitBookkeeping(wt, id, to, files);
27
- return state;
33
+ return commitBookkeeping(wt, id, what, files);
28
34
  }
package/src/build/red.js CHANGED
@@ -4,6 +4,7 @@
4
4
  import { spawnSync } from 'node:child_process';
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
+ import { buildTestCommand } from '../config.js';
7
8
  import { readText } from '../fs.js';
8
9
  import { commitPaths, git, headSha } from '../git.js';
9
10
  import { stateFileName } from '../ids.js';
@@ -179,12 +180,12 @@ function finishRed(wt, cfg, id, current, tests) {
179
180
  return { commit: current.redCommit, tests: current.frozenTests };
180
181
  }
181
182
 
182
- export function red(root, cfg, id, { tests, worktree } = {}) {
183
+ export function red(root, cfg, id, { tests, worktree, env = process.env } = {}) {
183
184
  const wt = findWorktree(root, id, { worktree }).path;
184
185
  const current = readSlice(wt, cfg, id);
185
186
  if (current.state === 'tests-red') return finishRed(wt, cfg, id, current, tests);
186
187
  if (current.state !== 'todo') throw new BuildError(`${id} is ${current.state}; red runs from todo`);
187
- const command = cfg.commands?.test ?? '';
188
+ const { command, local } = buildTestCommand(root, cfg, env);
188
189
  if (command.trim() === '') throw new BuildError('commands.test is not declared in .slicekit/config.json');
189
190
  const files = resolveTests(wt, tests);
190
191
  const slice = sliceIn(wt, cfg, id);
@@ -203,5 +204,5 @@ export function red(root, cfg, id, { tests, worktree } = {}) {
203
204
  const commit = made ?? headSha(wt);
204
205
  recordState(wt, cfg, id, 'tests-red', { commit, testExit: run.exit, tests: files });
205
206
  recordState(wt, cfg, id, 'building', {});
206
- return { commit, tests: files };
207
+ return { commit, tests: files, local: local ? command : null };
207
208
  }
@@ -0,0 +1,155 @@
1
+ // `build render` (REQ-2.6, D-43): a slice that changes the kit's version lands the re-render that
2
+ // `slicekit update --yes` makes, in the slice worktree, as one commit of only the files update writes:
3
+ // `chore(slicekit): <id> render`. `build commit` accepts that commit when its files equal a fresh
4
+ // render of the commit before it, made by the kit that runs the check; any other file in it, or a
5
+ // rendered file that differs, is a kit file changed by hand.
6
+ import { execFileSync } from 'node:child_process';
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { ConfigError, loadConfig } from '../config.js';
11
+ import { GitError, commitPaths, git } from '../git.js';
12
+ import { RENDERED, SETTINGS, kitVersion } from '../render/index.js';
13
+ import { entriesForShape } from '../render/manifest.js';
14
+ import { applyUpdate, planUpdate } from '../render/update.js';
15
+ import { readSlice } from '../state/index.js';
16
+ import { BuildError, findWorktree } from './worktree.js';
17
+
18
+ // The states a render is committed from: the states `build commit` commits from, and draft-pr
19
+ // (build pr then records the moved head).
20
+ const RENDER_FROM = ['building', 'draft-pr', 'in-review', 'changes-requested', 'ci-green', 'ready'];
21
+ const CONFIG = '.slicekit/config.json';
22
+ const lines = (out) => out.split('\0').filter((l) => l !== '');
23
+
24
+ export const renderSubject = (id) => `chore(slicekit): ${id} render`;
25
+
26
+ // The paths `update` may write for this config: each manifest entry, the settings file, and the
27
+ // reference copies under .slicekit/rendered/.
28
+ function owner(cfg) {
29
+ const dests = new Set([...entriesForShape(cfg.shape).map((e) => e.dest), SETTINGS]);
30
+ return (f) => dests.has(f) || f.startsWith(`${RENDERED}/`);
31
+ }
32
+
33
+ // Every changed path in the worktree (tracked against HEAD, and untracked), POSIX.
34
+ function changedPaths(wt) {
35
+ const tracked = lines(git(wt, ['diff', '--name-only', '--no-renames', '-z', 'HEAD']));
36
+ const untracked = lines(git(wt, ['ls-files', '--others', '--exclude-standard', '-z']));
37
+ return [...new Set([...tracked, ...untracked])];
38
+ }
39
+
40
+ // -> { sha, files }: the render commit, or sha null when the worktree already holds this kit's render.
41
+ export function renderSlice(root, rootCfg, id, { worktree } = {}) {
42
+ const wt = findWorktree(root, id, { worktree }).path;
43
+ const current = readSlice(wt, rootCfg, id);
44
+ if (!RENDER_FROM.includes(current.state)) throw new BuildError(`${id} is ${current.state}; render runs from ${RENDER_FROM.join(', ')}`);
45
+ // The worktree's own config: the one the slice commits and CI renders against.
46
+ const cfg = loadConfig(wt);
47
+ const owns = owner(cfg);
48
+ // Uncommitted work elsewhere (a template fix the render picks up) stays as it is; a change to a
49
+ // file update writes, or to the config, would be committed as the kit's.
50
+ const before = changedPaths(wt);
51
+ const blocked = before.filter((f) => owns(f) || f === CONFIG);
52
+ if (blocked.length > 0) throw new BuildError(`the worktree has uncommitted changes to ${blocked.slice(0, 5).join(', ')}; build render writes those files`);
53
+ const version = kitVersion();
54
+ const plan = planUpdate(wt, cfg, { version });
55
+ // A drifted file is the team's edit: update leaves it, so the render would be partial.
56
+ const edited = plan.filter((p) => p.status === 'drifted');
57
+ if (edited.length > 0) {
58
+ throw new BuildError(`${edited.map((p) => p.dest).join(', ')} ${edited.length === 1 ? 'was' : 'were'} edited since slicekit wrote ${edited.length === 1 ? 'it' : 'them'}; build render does not overwrite an edit`);
59
+ }
60
+ applyUpdate(wt, cfg, plan, { version });
61
+ const files = changedPaths(wt).filter((f) => !before.includes(f));
62
+ if (files.length === 0) return { sha: null, files: [] };
63
+ const stray = files.find((f) => !owns(f));
64
+ if (stray) throw new BuildError(`update wrote ${stray}, which is not a file it renders`);
65
+ const sha = commitPaths(wt, files, `${renderSubject(id)}\n\nran: slicekit update --yes (${version})\n\nSlice: ${id}`);
66
+ return { sha, files };
67
+ }
68
+
69
+ // Commit `sha` changes only files `update` writes, for the config of the commit before it.
70
+ export function renderPathsOnly(wt, sha) {
71
+ const config = blob(wt, `${sha}^`, CONFIG);
72
+ if (config === null) return false;
73
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'slicekit-render-'));
74
+ try {
75
+ fs.mkdirSync(path.join(tmp, '.slicekit'), { recursive: true });
76
+ fs.writeFileSync(path.join(tmp, ...CONFIG.split('/')), config);
77
+ const owns = owner(loadConfig(tmp));
78
+ const changed = lines(git(wt, ['diff-tree', '--no-commit-id', '--name-only', '--no-renames', '-r', '-z', sha]));
79
+ return changed.length > 0 && changed.every(owns);
80
+ } catch (e) {
81
+ if (e instanceof GitError || e instanceof ConfigError) return false;
82
+ throw e;
83
+ } finally {
84
+ fs.rmSync(tmp, { recursive: true, force: true });
85
+ }
86
+ }
87
+
88
+ // The bytes of `rev:file`, or null when the file is not in that commit.
89
+ function blob(wt, rev, file) {
90
+ try {
91
+ return execFileSync('git', ['cat-file', 'blob', `${rev}:${file}`], { cwd: wt, stdio: ['ignore', 'pipe', 'ignore'] });
92
+ } catch {
93
+ return null;
94
+ }
95
+ }
96
+
97
+ function tree(wt, rev) {
98
+ return lines(git(wt, ['ls-tree', '-r', '-z', '--name-only', rev]));
99
+ }
100
+
101
+ function walk(dir, base = '') {
102
+ if (!fs.existsSync(dir)) return [];
103
+ const out = [];
104
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
105
+ const rel = base === '' ? e.name : `${base}/${e.name}`;
106
+ if (e.isDirectory()) out.push(...walk(path.join(dir, e.name), rel));
107
+ else out.push(rel);
108
+ }
109
+ return out;
110
+ }
111
+
112
+ // The first file `update` writes that, in commit `rev`, is not what a fresh render from the running
113
+ // kit writes, or null when every one is: `update --check` of that commit, made in a scratch copy of the
114
+ // files it reads. A file the team edited (drift), a missing one, a changed one, or a reference copy
115
+ // that `update --yes` would rewrite is named; a file slicekit does not manage is not.
116
+ export function freshAt(wt, rev) {
117
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'slicekit-render-'));
118
+ try {
119
+ const config = blob(wt, rev, CONFIG);
120
+ if (config === null) return CONFIG;
121
+ fs.mkdirSync(path.join(tmp, '.slicekit'), { recursive: true });
122
+ fs.writeFileSync(path.join(tmp, ...CONFIG.split('/')), config);
123
+ let cfg;
124
+ try {
125
+ cfg = loadConfig(tmp);
126
+ } catch (e) {
127
+ if (e instanceof ConfigError) return CONFIG;
128
+ throw e;
129
+ }
130
+ const owns = owner(cfg);
131
+ const held = tree(wt, rev).filter(owns);
132
+ for (const f of held) {
133
+ const abs = path.join(tmp, ...f.split('/'));
134
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
135
+ fs.writeFileSync(abs, blob(wt, rev, f));
136
+ }
137
+ const version = kitVersion();
138
+ const plan = planUpdate(tmp, cfg, { version });
139
+ const off = plan.find((p) => p.status !== 'same' && p.status !== 'unmanaged');
140
+ if (off) return off.dest;
141
+ applyUpdate(tmp, cfg, plan, { version });
142
+ const written = new Set(walk(tmp).filter(owns));
143
+ for (const f of [...new Set([...written, ...held])]) {
144
+ const want = written.has(f) ? fs.readFileSync(path.join(tmp, ...f.split('/'))) : null;
145
+ const got = blob(wt, rev, f);
146
+ if (want === null || got === null ? want !== got : !want.equals(got)) return f;
147
+ }
148
+ return null;
149
+ } catch (e) {
150
+ if (e instanceof GitError) return CONFIG;
151
+ throw e;
152
+ } finally {
153
+ fs.rmSync(tmp, { recursive: true, force: true });
154
+ }
155
+ }
@@ -20,6 +20,10 @@ import { readSlice } from '../state/index.js';
20
20
  import { headCovers } from '../state/covers.js';
21
21
  import { INDEPENDENT_ONLY } from '../state/transitions.js';
22
22
  import { bannedPhrasesIn } from '../check/rules/style.js';
23
+ import { buildContext } from '../check/context.js';
24
+ import references from '../check/rules/references.js';
25
+ import { loadConfig } from '../config.js';
26
+ import { lines as splitLines } from '../markdown.js';
23
27
  import { PrBodyError, getSection, prBodyProblems, setSection } from '../prbody.js';
24
28
  import { parseVerdict, verdictProblems } from '../verdict.js';
25
29
  import { posixRel } from './red.js';
@@ -303,6 +307,28 @@ function reviewWorktreeOf(root, id) {
303
307
  }
304
308
 
305
309
  // The verdict is given on the recorded head; code committed since has not been through build pr.
310
+ // One line per finding the `references` rule would make on the verdict once it sits at `rel` in the
311
+ // worktree: an unknown slice, requirement or decision ID, or a backticked path the worktree does not
312
+ // hold. Judged before the file moves, so `slicekit check` never fails on a recorded verdict (D-43).
313
+ function referenceProblems(wt, rel, text, shown) {
314
+ const ctx = buildContext(wt, loadConfig(wt));
315
+ const doc = { path: path.join(wt, ...rel.split('/')), rel, text, lines: splitLines(text) };
316
+ return references.run({ ...ctx, docs: [doc] }).map((f) => `verdict ${shown} line ${f.line}: ${f.message}`);
317
+ }
318
+
319
+ // The verdict reviewed the recorded head, or a head that adds only the kit's bookkeeping to it
320
+ // (D-35): a verdict written before the head moved is refused, naming both (D-43).
321
+ // The verdict's head is compared as a string, never looked up: it is the recorded head, or a full id
322
+ // on the recorded head's descendants up to HEAD (from git log of that range) that adds only bookkeeping.
323
+ function assertReviewedHead(wt, v, shown, current) {
324
+ const recorded = current.pr?.headSha ?? '';
325
+ const reviewed = String(v.head);
326
+ if (reviewed === recorded) return;
327
+ const later = recorded === '' ? [] : git(wt, ['log', '--format=%H', `${recorded}..HEAD`]).split('\n');
328
+ if (later.includes(reviewed) && headCovers(wt, recorded, reviewed)) return;
329
+ throw new BuildError(`verdict ${shown} reviewed head ${String(v.head).slice(0, 7)}; the recorded head is ${recorded.slice(0, 7)}: review the recorded head`);
330
+ }
331
+
306
332
  function assertBuilt(wt, id, current) {
307
333
  if (!headCovers(wt, current.pr?.headSha ?? '', headSha(wt))) {
308
334
  throw new BuildError(`${id} has commits since build pr; run slicekit build pr ${id} first`);
@@ -386,10 +412,13 @@ export function recordVerdict(root, cfg, host, id, file, { worktree, independent
386
412
 
387
413
  const { text, here, moved } = verdictSource(wt, id, k, src, dest, rel, shown);
388
414
  const v = checked(text, shown, name, independent);
415
+ assertReviewedHead(wt, v, shown, current);
389
416
  const reused = reusedNumbers(shown, v.findings.map((f) => f.id), earlierIds(wt, verdicts));
390
417
  if (reused.length > 0) throw new BuildError(reused.join('\n'));
391
418
  const banned = bannedProblems(cfg, v, text, shown);
392
419
  if (banned.length > 0) throw new BuildError(banned.join('\n'));
420
+ const unknown = referenceProblems(wt, rel, text, shown);
421
+ if (unknown.length > 0) throw new BuildError(unknown.join('\n'));
393
422
  // The line this round would write, judged against the live body before anything moves.
394
423
  const stuck = outcome(k, v, [...verdicts, { independent }], independent).next === 'stuck';
395
424
  const line = reviewerBlocked([...parsedVerdicts(wt, verdicts), { round: k, findings: v.findings, headSha: current.pr.headSha, independent }], {
@@ -4,6 +4,7 @@
4
4
  import { randomBytes } from 'node:crypto';
5
5
  import fs from 'node:fs';
6
6
  import path from 'node:path';
7
+ import { loadConfig } from '../config.js';
7
8
  import { GitError, assertRef, git, hasRemote, pushBranch } from '../git.js';
8
9
  import { parseSliceAddr, sliceFromBranch } from '../ids.js';
9
10
  import { findSliceFiles } from '../slicefile.js';
@@ -25,17 +26,37 @@ export { REVIEW_DESCR, branchPrefix, listWorktrees, reviewBranch, reviewWorktree
25
26
  // The review worktree `review start` makes for the slice at `addr`, known by its branch or its path.
26
27
  export const isReviewWorktree = (root, addr, w) => w.branch === reviewBranch(addr) || samePath(w.path, reviewWorktreeDir(root, addr));
27
28
 
29
+ // The pull request number the state file in `dir` records for `id`, read through `dir`'s own config,
30
+ // or `<PR>` when none is recorded or the file cannot be read.
31
+ function recordedPr(dir, id) {
32
+ try {
33
+ const n = readSlice(dir, loadConfig(dir), id).pr?.number;
34
+ return Number.isInteger(n) ? String(n) : '<PR>';
35
+ } catch {
36
+ return '<PR>';
37
+ }
38
+ }
39
+
28
40
  // The worktree holding `id`: the one `--worktree` names, else the build worktree. Without
29
41
  // `--worktree` the review worktree is never picked, so the building session needs no flag while a
30
42
  // review session runs; the review session always names its worktree.
31
43
  export function findWorktree(root, id, { worktree } = {}) {
32
- const all = listWorktrees(root).filter((w) => w.branch !== null && sliceFromBranch(w.branch) === id);
44
+ const every = listWorktrees(root);
45
+ const all = every.filter((w) => w.branch !== null && sliceFromBranch(w.branch) === id);
46
+ const addr = parseSliceAddr(id);
33
47
  if (worktree !== undefined) {
34
- const match = all.find((w) => samePath(w.path, path.resolve(root, worktree)));
35
- if (!match) throw new BuildError(`${worktree} is not a worktree holding ${id}`);
36
- return match;
48
+ const given = path.resolve(root, worktree);
49
+ const match = all.find((w) => samePath(w.path, given));
50
+ if (match) return match;
51
+ // The review worktree moved to a detached HEAD (issue #61) is never accepted, since build verdict
52
+ // pushes the review branch; review start moves it to the pull request's head.
53
+ const main = every[0]?.path;
54
+ const detached = every.find((w) => w.branch === null && samePath(w.path, given));
55
+ if (addr && main && detached && samePath(given, reviewWorktreeDir(main, addr))) {
56
+ throw new BuildError(`${worktree} is the review worktree of ${id} on a detached HEAD; run slicekit review start ${recordedPr(detached.path, id)} to move it to the pull request's head`);
57
+ }
58
+ throw new BuildError(`${worktree} is not a worktree holding ${id}`);
37
59
  }
38
- const addr = parseSliceAddr(id);
39
60
  const held = addr ? all.filter((w) => !isReviewWorktree(root, addr, w)) : all;
40
61
  if (held.length === 0) throw new BuildError(`no worktree holds ${id}; run slicekit build start ${id}`);
41
62
  if (held.length > 1) {
@@ -3,6 +3,7 @@
3
3
  // Locally, with no event file, `SLICEKIT_PR_TITLE` / `SLICEKIT_PR_BODY` stand in for one.
4
4
  import fs from 'node:fs';
5
5
  import { DEFAULT_BOT_ACTORS } from '../config.js';
6
+ import { resolveCommit } from '../git.js';
6
7
 
7
8
  // The pseudo-path the ci rules attach their findings to (line 0): the title and body live in the
8
9
  // GitHub event, not in a file of the repository, and this reads clearly in CI output.
@@ -50,3 +51,19 @@ export function isBotAuthor(cfg, pr) {
50
51
 
51
52
  // A `[spec] ` or `[plan] ` title: a spec or plan pull request, not a slice's.
52
53
  export const EXEMPT_TITLE = /^\[(spec|plan)\] /;
54
+
55
+ // The branch a rule judges and the tip it judges it at, or null with no repository, no commits or no
56
+ // branch (moved from the trailer rule in P3/S-18, so trailer and citations share it). Under --ci on
57
+ // a pull request, actions/checkout leaves a detached merge commit whose first parent is the base: the
58
+ // branch is GITHUB_HEAD_REF and the tip the pull request's head, from the event's head sha (or the
59
+ // merge commit's second parent when the event has none). Otherwise the current branch and HEAD.
60
+ export function branchTip(ctx) {
61
+ if (!ctx.git?.isRepo || !ctx.git.hasCommits) return null;
62
+ const ref = ctx.env?.GITHUB_HEAD_REF;
63
+ if (ctx.ci && typeof ref === 'string' && ref !== '') {
64
+ const headSha = readCiEvent(ctx.env)?.headSha;
65
+ const tip = (headSha && /^[0-9a-f]{7,40}$/.test(headSha) && resolveCommit(ctx.root, headSha)) || resolveCommit(ctx.root, 'HEAD^2') || 'HEAD';
66
+ return { branch: ref, tip };
67
+ }
68
+ return ctx.git.branch ? { branch: ctx.git.branch, tip: 'HEAD' } : null;
69
+ }
@@ -1,12 +1,17 @@
1
1
  // citations (03 REQ-3.7): every requirement has the shape of 01 REQ-1.3 (a ## or ### heading) and
2
2
  // cites a decision or an intake file that exists; every slice file (REQ-1.5) names only requirements and decisions that
3
3
  // exist, and every test in its evaluation set covers a requirement; no D or REQ id is defined twice
4
- // (REQ-1.4).
4
+ // (REQ-1.4). On a slice branch, each test file (testFiles, D-46) the branch adds or modifies names a
5
+ // REQ ID at the branch tip (REQ-4.3); deleted files and the default branch are not judged.
6
+ import { execFileSync } from 'node:child_process';
5
7
  import fs from 'node:fs';
6
8
  import path from 'node:path';
7
- import { re } from '../../ids.js';
9
+ import { re, sliceFromBranch } from '../../ids.js';
8
10
  import { headings, tables } from '../../markdown.js';
9
11
  import { findSliceFiles, parseSliceFile } from '../../slicefile.js';
12
+ import { assertRef, git, GitError } from '../../git.js';
13
+ import { isTestFile, reqMentions } from '../../graph/tests.js';
14
+ import { branchTip } from '../ci-event.js';
10
15
 
11
16
  export const id = 'citations';
12
17
  export const blocking = true;
@@ -211,6 +216,51 @@ function checkSlices(ctx, out) {
211
216
  }
212
217
  }
213
218
 
219
+ const tryGit = (root, args) => {
220
+ try {
221
+ return git(root, args);
222
+ } catch (e) {
223
+ if (e instanceof GitError) return null;
224
+ throw e;
225
+ }
226
+ };
227
+
228
+ // A test file's text at a revision. Not through git(), whose output is capped at Node's 1 MiB
229
+ // default: a larger test file must still be judged (S-18 review H-1).
230
+ function blobText(root, spec) {
231
+ try {
232
+ return execFileSync('git', ['show', spec], { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 256 * 1024 * 1024 });
233
+ } catch {
234
+ return null;
235
+ }
236
+ }
237
+
238
+ export const TEST_FILE_MESSAGE = 'test file names no requirement (REQ-4.3)';
239
+
240
+ // REQ-4.3: the test files a slice branch adds or modifies against its merge base with the default
241
+ // branch (local, else origin's), judged at the branch tip.
242
+ export function testFileFindings(ctx) {
243
+ const at = branchTip(ctx);
244
+ if (!at || !sliceFromBranch(at.branch)) return [];
245
+ const { root, cfg } = ctx;
246
+ const def = assertRef(cfg.defaultBranch ?? 'main');
247
+ const base = tryGit(root, ['merge-base', at.tip, `refs/heads/${def}`]) || tryGit(root, ['merge-base', at.tip, `refs/remotes/origin/${def}`]);
248
+ if (!base) return [];
249
+ const diff = tryGit(root, ['-c', 'core.quotePath=false', 'diff', '-z', '--name-status', '--no-renames', base, at.tip, '--']);
250
+ if (!diff) return [];
251
+ const parts = diff.split('\0');
252
+ const out = [];
253
+ for (let i = 0; i + 1 < parts.length; i += 2) {
254
+ const status = parts[i].trim();
255
+ const rel = parts[i + 1];
256
+ if ((status !== 'A' && status !== 'M') || !isTestFile(rel, cfg)) continue;
257
+ const text = blobText(root, `${at.tip}:${rel}`);
258
+ if (text === null || reqMentions(text).length > 0) continue;
259
+ out.push({ file: rel, line: 1, message: TEST_FILE_MESSAGE });
260
+ }
261
+ return out;
262
+ }
263
+
214
264
  export function run(ctx) {
215
265
  const out = [];
216
266
  const defs = [];
@@ -218,6 +268,7 @@ export function run(ctx) {
218
268
  decisionDefs(ctx, defs);
219
269
  checkDuplicates(defs, out);
220
270
  checkSlices(ctx, out);
271
+ out.push(...testFileFindings(ctx));
221
272
  return out;
222
273
  }
223
274
 
@@ -11,8 +11,10 @@
11
11
  // A token with a path separator must be a regular file, relative to the root or absolute. On win32
12
12
  // it is tried with the PATHEXT suffixes and bare, as `which()` does; on POSIX bare only. So a
13
13
  // Windows-only `.cmd` passes on Windows and fails on POSIX.
14
+ import { execFileSync } from 'node:child_process';
14
15
  import fs from 'node:fs';
15
16
  import path from 'node:path';
17
+ import { ConfigError, LOCAL_PATH, localTestCommand, mainCheckout } from '../../config.js';
16
18
  import { which, extensions } from '../../which.js';
17
19
 
18
20
  export const id = 'commands';
@@ -126,17 +128,43 @@ function keyLine(root, name) {
126
128
  return lineAt(open.index);
127
129
  }
128
130
 
131
+ // Outside CI the test command judged is the one this machine runs: .slicekit/local.json's testCommand
132
+ // in the main checkout when it sets one (D-43). CI (`check --ci`) judges the committed command it runs.
133
+ function localTest(ctx) {
134
+ if (ctx.ci) return null;
135
+ try {
136
+ return localTestCommand(mainCheckout(ctx.root), ctx.env ?? process.env);
137
+ } catch (e) {
138
+ if (e instanceof ConfigError) return { error: e.message };
139
+ throw e;
140
+ }
141
+ }
142
+
143
+ // The local file is one machine's: tracked by git, it would change every clone's test command.
144
+ function trackedLocal(ctx) {
145
+ try {
146
+ execFileSync('git', ['ls-files', '--error-unmatch', '--', LOCAL_PATH], { cwd: ctx.root, stdio: 'ignore' });
147
+ return true;
148
+ } catch {
149
+ return false;
150
+ }
151
+ }
152
+
129
153
  export function run(ctx) {
130
154
  const out = [];
155
+ if (trackedLocal(ctx)) out.push({ file: LOCAL_PATH, line: 1, message: `${LOCAL_PATH} is tracked by git; it holds one machine's settings: remove it from the index` });
156
+ const local = localTest(ctx);
157
+ if (local?.error) out.push({ file: LOCAL_PATH, line: 1, message: local.error });
131
158
  for (const name of NAMES) {
132
- const value = ctx.cfg?.commands?.[name];
159
+ const own = name === 'test' && typeof local === 'string';
160
+ const value = own ? local : ctx.cfg?.commands?.[name];
133
161
  if (typeof value !== 'string' || value.trim() === '') continue;
134
162
  for (const token of commandWords(value)) {
135
163
  if (resolves(token, ctx)) continue;
136
164
  out.push({
137
- file: CONFIG,
138
- line: keyLine(ctx.root, name),
139
- message: `commands.${name}: "${token}" not found on PATH or under node_modules/.bin`,
165
+ file: own ? LOCAL_PATH : CONFIG,
166
+ line: own ? 1 : keyLine(ctx.root, name),
167
+ message: `${own ? `${LOCAL_PATH} testCommand` : `commands.${name}`}: "${token}" not found on PATH or under node_modules/.bin`,
140
168
  });
141
169
  }
142
170
  }
@@ -10,8 +10,8 @@
10
10
  // Under --ci on a pull request, actions/checkout leaves a detached merge commit whose first parent is
11
11
  // the base: the branch is GITHUB_HEAD_REF and the tip judged is the pull request's head, from the
12
12
  // event's head sha (or the merge commit's second parent when the event has none).
13
- import { assertRef, git, GitError, resolveCommit } from '../../git.js';
14
- import { readCiEvent } from '../ci-event.js';
13
+ import { assertRef, git, GitError } from '../../git.js';
14
+ import { branchTip } from '../ci-event.js';
15
15
  import { sliceFromBranch } from '../../ids.js';
16
16
 
17
17
  export const id = 'trailer';
@@ -30,22 +30,11 @@ const refExists = (root, ref) => {
30
30
  }
31
31
  };
32
32
 
33
- // The pull request's branch and head under --ci, or null outside a pull_request run.
34
- function pullRequestTip(ctx) {
35
- const ref = ctx.env?.GITHUB_HEAD_REF;
36
- if (!ctx.ci || typeof ref !== 'string' || ref === '') return null;
37
- const headSha = readCiEvent(ctx.env)?.headSha;
38
- const tip = (headSha && /^[0-9a-f]{7,40}$/.test(headSha) && resolveCommit(ctx.root, headSha)) || resolveCommit(ctx.root, 'HEAD^2') || 'HEAD';
39
- return { branch: ref, tip };
40
- }
41
-
42
33
  export function run(ctx) {
43
34
  const { root, cfg } = ctx;
44
- if (!ctx.git?.isRepo || !ctx.git.hasCommits) return [];
45
- const pr = pullRequestTip(ctx);
46
- const branch = pr?.branch ?? ctx.git.branch;
47
- const tip = pr?.tip ?? 'HEAD';
48
- if (!branch) return [];
35
+ const at = branchTip(ctx);
36
+ if (!at) return [];
37
+ const { branch, tip } = at;
49
38
  const slice = sliceFromBranch(branch);
50
39
  if (!slice) return [];
51
40