slicekit 0.7.0 → 0.7.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slicekit",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "Spec-driven agentic workflow kit",
5
5
  "license": "MIT",
6
6
  "repository": {
package/src/build/pr.js CHANGED
@@ -60,8 +60,8 @@ function readNotes(root, notes) {
60
60
 
61
61
  const lines = (out) => out.split('\n').filter((l) => l !== '');
62
62
 
63
- // The worktree is clean, or holds only the state file and BUILD.md of a draft-pr recording whose
64
- // bookkeeping commit did not land: that commit is made now.
63
+ // The worktree is clean, or holds only the state file of a draft-pr recording whose bookkeeping
64
+ // commit did not land: that commit is made now. A slice branch commits no BUILD.md (D-100).
65
65
  function cleanOrFinish(wt, cfg, id, current) {
66
66
  // Paths from name lists, never from status columns: git() trims its output, and a leading space
67
67
  // is part of the first porcelain line.
@@ -73,10 +73,9 @@ function cleanOrFinish(wt, cfg, id, current) {
73
73
  if (files.length === 0) return;
74
74
  const paths = kitPaths(wt, cfg);
75
75
  const stateRel = posixRel(wt, path.join(paths.state, stateFileName(id)));
76
- const buildRel = posixRel(wt, paths.build);
77
- const onlyBookkeeping = files.includes(stateRel) && files.every((f) => f === stateRel || f === buildRel);
76
+ const onlyBookkeeping = files.length === 1 && files[0] === stateRel;
78
77
  if (current.state === 'draft-pr' && onlyBookkeeping && pendingDraftPr(wt, stateRel, current)) {
79
- commitBookkeeping(wt, id, 'draft-pr', files);
78
+ commitBookkeeping(wt, id, 'draft-pr', [stateRel]);
80
79
  return;
81
80
  }
82
81
  throw new BuildError(`the worktree has uncommitted changes (${files.slice(0, 5).join(', ')}); build commit them first`);
@@ -158,9 +157,12 @@ export function openSlicePr(root, cfg, host, id, { notes, worktree, env = proces
158
157
  // here, before the push, rather than after it.
159
158
  const afterReview = current.state !== 'building' && current.state !== 'draft-pr';
160
159
  // A head that adds only bookkeeping (a verdict, the state, BUILD.md) to the reviewed one is the same work.
161
- if (afterReview && current.pr && headCovers(wt, current.pr.headSha, headSha(wt))) {
160
+ if (afterReview && current.pr && headCovers(wt, current.pr.headSha, headSha(wt), { merges: false })) {
162
161
  throw new BuildError(`${id} has nothing new since review of ${current.pr.headSha.slice(0, 7)}; push a fix to return to draft-pr`);
163
162
  }
163
+ // A head that adds to the reviewed one a merge of the default branch leaving the pull request's
164
+ // files as they were (D-100): the verdict still holds, so the head is pushed and the state kept.
165
+ const keep = afterReview && current.pr && headCovers(wt, current.pr.headSha, headSha(wt)) ? current.state : null;
164
166
  // A path another slice of the same Order step already changes on origin (D-06): a plan defect,
165
167
  // refused before the notes, the body and the commands, so a defect in the plan stops the run before
166
168
  // minutes of test runs, and before anything is pushed. After the behind-origin refusal, which a
@@ -240,10 +242,12 @@ export function openSlicePr(root, cfg, host, id, { notes, worktree, env = proces
240
242
  const made = openOrUpdate(wt, cfg, host, { title, body, draft: true });
241
243
  // The absolute session-root path the next in-loop reviewer writes (null once the loop's rounds are
242
244
  // used or an independent verdict is recorded): recording draft-pr adds no verdict, so the count read before is the count after.
245
+ // A kept state asks for no new review: no verdict path.
246
+ if (keep) return { number: made.number, url: made.url, created: made.created, verdictPath: null, local: local ? testCommand : null, movedHead: null, kept: keep };
243
247
  const verdictPath = nextVerdictPath(root, id, current.verdicts ?? []);
244
248
  // The reviewer writes there at once: its directory is made here, as the path is printed.
245
249
  if (verdictPath) fs.mkdirSync(path.dirname(verdictPath), { recursive: true });
246
- const result = { number: made.number, url: made.url, created: made.created, verdictPath, local: local ? testCommand : null, movedHead: null };
250
+ const result = { number: made.number, url: made.url, created: made.created, verdictPath, local: local ? testCommand : null, movedHead: null, kept: null };
247
251
  // `build finish` marked it ready; a slice back at draft-pr has a draft pull request again.
248
252
  if (livePr?.draft === false) host.markDraft(made.number);
249
253
  // At draft-pr a head that moved since the recorded one (a merge of the default branch, any commit)
@@ -251,7 +255,7 @@ export function openSlicePr(root, cfg, host, id, { notes, worktree, env = proces
251
255
  // that adds only bookkeeping to the recorded one is the same work: nothing is recorded.
252
256
  if (current.state === 'draft-pr') {
253
257
  const head = headSha(wt);
254
- if (current.pr?.headSha && !headCovers(wt, current.pr.headSha, head)) {
258
+ if (current.pr?.headSha && !headCovers(wt, current.pr.headSha, head, { merges: false })) {
255
259
  recordHead(wt, cfg, id, { number: made.number, url: made.url, headSha: head });
256
260
  commitState(wt, cfg, id, 'head');
257
261
  pushBranch(wt, { protectedBranches: cfg.protectedBranches, defaultBranch: cfg.defaultBranch });
@@ -1,11 +1,10 @@
1
- // State moves of a `build` step (REQ-1.8, D-35): setState, BUILD.md, and one bookkeeping commit that
2
- // touches nothing else, so a verdict given on the head before it still holds.
1
+ // State moves of a `build` step (REQ-1.8, D-35): setState and one bookkeeping commit of the slice's
2
+ // state file that touches nothing else, so a verdict given on the head before it still holds. A slice
3
+ // branch commits no BUILD.md: the sync after the merge regenerates it on the default branch (D-100).
3
4
  import path from 'node:path';
4
- import { exists, readText, writeText } from '../fs.js';
5
5
  import { commitPaths } from '../git.js';
6
6
  import { stateFileName } from '../ids.js';
7
7
  import { kitPaths } from '../paths.js';
8
- import { renderBuild } from '../state/build.js';
9
8
  import { appendHistory, setState } from '../state/index.js';
10
9
 
11
10
  const posixRel = (wt, abs) => path.relative(wt, abs).split(path.sep).join('/');
@@ -31,14 +30,8 @@ export function recordAmendment(wt, cfg, id, evidence) {
31
30
  return entry;
32
31
  }
33
32
 
34
- // BUILD.md rendered again from the state files, then one bookkeeping commit of the slice's state file
35
- // and BUILD.md: `chore(slicekit): <id> <what>`.
33
+ // One bookkeeping commit of the slice's state file alone: `chore(slicekit): <id> <what>`.
36
34
  export function commitState(wt, cfg, id, what) {
37
35
  const paths = kitPaths(wt, cfg);
38
- const before = exists(paths.build) ? readText(paths.build) : '';
39
- const after = renderBuild(wt, cfg, before);
40
- if (after !== before) writeText(paths.build, after);
41
- const files = [posixRel(wt, path.join(paths.state, stateFileName(id)))];
42
- if (exists(paths.build)) files.push(posixRel(wt, paths.build));
43
- return commitBookkeeping(wt, id, what, files);
36
+ return commitBookkeeping(wt, id, what, [posixRel(wt, path.join(paths.state, stateFileName(id)))]);
44
37
  }
@@ -12,7 +12,8 @@ import { readSlice } from '../state/index.js';
12
12
  import { titleSlice } from '../check/rules/ci-title.js';
13
13
  import { posixRel } from './red.js';
14
14
  import { commits } from './sync.js';
15
- import { independentVerdictPath } from './verdict.js';
15
+ import { extraRounds, independentBlockers, independentRoundAllowed, independentVerdictPath, stopText } from './verdict.js';
16
+ import { parseVerdict } from '../verdict.js';
16
17
  import { BuildError, listWorktrees, reviewBranch, reviewWorktreeDir, samePath } from './worktree.js';
17
18
 
18
19
  const fwd = (p) => p.replaceAll('\\', '/');
@@ -58,8 +59,8 @@ function clearOld(root, id, dir, branch) {
58
59
  if (lines(git(root, ['branch', '--list', branch])).length > 0) git(root, ['branch', '-q', '-D', branch]);
59
60
  }
60
61
 
61
- // The pull request number the slice's state on `ref` records, or null when it records none.
62
- function recordedNumber(root, cfg, id, ref) {
62
+ // The slice's state as `ref` holds it, or null when it holds none or it does not parse.
63
+ function stateOn(root, cfg, id, ref) {
63
64
  const rel = posixRel(root, path.join(kitPaths(root, cfg).state, stateFileName(id)));
64
65
  let text;
65
66
  try {
@@ -69,15 +70,39 @@ function recordedNumber(root, cfg, id, ref) {
69
70
  return null;
70
71
  }
71
72
  try {
72
- return JSON.parse(text).pr?.number ?? null;
73
+ return JSON.parse(text);
73
74
  } catch {
74
75
  return null;
75
76
  }
76
77
  }
77
78
 
79
+ // The independent round budget (REQ-2.8, D-101), judged on the slice's state on `ref`: one round, a
80
+ // second only when the first left a blocker, any later one only with a decision row for it. A refusal
81
+ // names the latest round's open blockers and the three choices.
82
+ function assertRoundLeft(root, cfg, id, number, ref, state) {
83
+ const verdicts = Array.isArray(state?.verdicts) ? state.verdicts : [];
84
+ const counts = independentBlockers(verdicts);
85
+ if (independentRoundAllowed(counts, extraRounds(root, cfg, id))) return;
86
+ const latest = verdicts.filter((v) => v.independent).sort((a, b) => a.round - b.round).at(-1);
87
+ if (counts.at(-1) === 0) {
88
+ const decisions = posixRel(root, kitPaths(root, cfg).decisions);
89
+ throw new BuildError(
90
+ `the independent review of ${id} left no blocker in round ${latest.round}; another independent round starts only after a blocker, or with a decision row in ${decisions} whose answer names ${id} and says "one more round" (D-101)`,
91
+ );
92
+ }
93
+ let blockers;
94
+ try {
95
+ blockers = parseVerdict(git(root, ['show', `${ref}:${latest.path}`]), latest.path).findings.filter((f) => f.kind === 'blocker');
96
+ } catch (e) {
97
+ if (!(e instanceof GitError)) throw e;
98
+ blockers = [];
99
+ }
100
+ throw new BuildError(stopText(root, cfg, id, number, latest.round, blockers));
101
+ }
102
+
78
103
  // -> {id, worktree, branch, round, verdictPath}: `round` is the slice's verdict count plus one, and
79
104
  // `verdictPath` the absolute session-root path of that round's independent verdict. Every refusal
80
- // comes before an earlier review worktree is touched.
105
+ // comes before an earlier review worktree is touched, the round budget's too (D-101).
81
106
  export function startReview(root, cfg, host, number) {
82
107
  const pr = host.getPullRequest(number);
83
108
  const id = titleSlice(pr.title ?? '');
@@ -108,8 +133,13 @@ export function startReview(root, cfg, host, number) {
108
133
  if (typeof pr.headSha === 'string' && pr.headSha !== '' && pr.headSha !== tip) {
109
134
  throw new BuildError(`pull request #${number}'s head ${pr.headSha.slice(0, 7)} is not origin/${headRef}; is it from a fork? If the branch was just pushed, run the same command again in a minute`);
110
135
  }
111
- const recorded = recordedNumber(root, cfg, id, tracking);
136
+ // The default branch as origin has it now: the round budget reads its decision rows there, so a row
137
+ // merged on origin since the last fetch counts (D-101).
138
+ git(root, ['fetch', '-q', 'origin', `+refs/heads/${cfg.defaultBranch}:refs/remotes/origin/${cfg.defaultBranch}`]);
139
+ const onOrigin = stateOn(root, cfg, id, tracking);
140
+ const recorded = onOrigin?.pr?.number ?? null;
112
141
  if (recorded !== null && recorded !== number) throw new BuildError(`pull request #${number} is not the one recorded for ${id} (#${recorded})`);
142
+ assertRoundLeft(root, cfg, id, number, tracking, onOrigin);
113
143
 
114
144
  const dir = reviewWorktreeDir(root, addr);
115
145
  clearOld(root, id, dir, branch);
@@ -7,14 +7,17 @@
7
7
  //
8
8
  // Two in-loop rounds (D-18): a third is refused before anything moves, and a blocker left at round 2
9
9
  // records `changes-requested` and stops the loop with the pull request still a draft. After every
10
- // verdict the body's "Reviewer blocked" names each blocker and whether it was fixed.
10
+ // verdict the body's "Reviewer blocked" names each blocker and whether it was fixed. The independent
11
+ // rounds have their own budget (D-101): one, a second only after a blocker, any later one only with a
12
+ // decision row; a blocker left at the last allowed round records `changes-requested` the same way.
11
13
  //
12
14
  // Finding IDs name one finding for the whole slice: a finding that survives keeps its ID, a new one
13
15
  // takes a number never used before in the slice (B and H counted apart). An ID absent from the
14
16
  // previous verdict is new, so a finding that vanished and came back must take a new number.
15
17
  import fs from 'node:fs';
16
18
  import path from 'node:path';
17
- import { git, headSha, pushBranch } from '../git.js';
19
+ import { GitError, git, headSha, pushBranch } from '../git.js';
20
+ import { defaultRef } from '../runbook.js';
18
21
  import { sliceFromBranch, verdictFileName, verdictFilePattern } from '../ids.js';
19
22
  import { readSlice } from '../state/index.js';
20
23
  import { headCovers } from '../state/covers.js';
@@ -23,6 +26,8 @@ import { bannedPhrasesIn } from '../check/rules/style.js';
23
26
  import { buildContext } from '../check/context.js';
24
27
  import references from '../check/rules/references.js';
25
28
  import { loadConfig } from '../config.js';
29
+ import { readDecisions } from '../decisions.js';
30
+ import { kitPaths } from '../paths.js';
26
31
  import { lines as splitLines } from '../markdown.js';
27
32
  import { PrBodyError, getSection, prBodyProblems, setSection } from '../prbody.js';
28
33
  import { parseVerdict, verdictProblems } from '../verdict.js';
@@ -133,6 +138,62 @@ function verdictSource(wt, id, k, src, dest, rel, shown) {
133
138
 
134
139
  const inLoop = (verdicts) => verdicts.filter((x) => !x.independent).length;
135
140
 
141
+ // ---- The independent round budget (REQ-2.8, D-101) ----
142
+
143
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
144
+
145
+ // The settled decision rows of `<docsRoot>/decisions.md` that allow `id` one more independent round:
146
+ // the answer names the slice ID and the words "one more round". The file is read as committed on the
147
+ // default branch (origin's tip, else the local one), so an uncommitted row or one on another branch
148
+ // allows nothing. 0 when that commit holds no file.
149
+ export function extraRounds(root, cfg, id) {
150
+ const rel = posixRel(root, kitPaths(root, cfg).decisions);
151
+ let text;
152
+ try {
153
+ text = git(root, ['show', `${defaultRef(root, cfg)}:${rel}`]);
154
+ } catch (e) {
155
+ if (!(e instanceof GitError)) throw e;
156
+ return 0;
157
+ }
158
+ const names = new RegExp(`(?<![\\w/])${escapeRe(id)}(?!\\d)`);
159
+ return readDecisions(text).rows.filter((r) => r.table === 'settled' && names.test(r.answer) && /\bone more round\b/i.test(r.answer)).length;
160
+ }
161
+
162
+ // Whether one more independent round may start after the independent verdicts recorded, given as
163
+ // their blocker counts in round order: the first always; a second only when the first left a blocker;
164
+ // any later one only with a decision row for it (`extra` rows allow `extra` rounds beyond those).
165
+ export function independentRoundAllowed(blockerCounts, extra = 0) {
166
+ const n = blockerCounts.length;
167
+ if (n === 0) return true;
168
+ const base = blockerCounts[0] > 0 ? 2 : 1;
169
+ if (n < base && blockerCounts.at(-1) > 0) return true;
170
+ return n - base < extra;
171
+ }
172
+
173
+ // The blocker counts of the independent verdicts in the slice's state entries, in round order.
174
+ export const independentBlockers = (verdicts) =>
175
+ [...verdicts]
176
+ .filter((v) => v.independent)
177
+ .sort((a, b) => a.round - b.round)
178
+ .map((v) => Number(v.blockers ?? 0));
179
+
180
+ // The three choices for a person when the independent rounds are used (REQ-2.8, D-101): `review start`
181
+ // and `build verdict --independent` both print them.
182
+ export const STOP_CHOICES = [
183
+ 'fix the open blockers by hand in the slice worktree and push them with slicekit build pr <id>',
184
+ 're-scope the slice: amend the slice file so the blockers fall outside it, or move them to a new slice',
185
+ 'allow one more round: record a decision row in <decisions> whose answer names <id> and says "one more round", commit it on the default branch and push it to origin, then run slicekit review start <n> again',
186
+ ];
187
+
188
+ // The stop text: the open blockers of the latest independent round, each with its "what is wrong",
189
+ // then the three choices.
190
+ export function stopText(root, cfg, id, number, round, blockers) {
191
+ const decisions = posixRel(root, kitPaths(root, cfg).decisions);
192
+ const open = blockers.map((f) => `- ${f.id} ${quoted(f.wrong)}`);
193
+ const choices = STOP_CHOICES.map((c, i) => `${i + 1}. ${c.replaceAll('<id>', id).replaceAll('<n>', String(number)).replaceAll('<decisions>', decisions)}`);
194
+ return [`no independent round is left for ${id} (D-101); round ${round}'s verdict holds open blockers:`, ...open, 'choose one:', ...choices].join('\n');
195
+ }
196
+
136
197
  // A verdict file's absolute path in the session root, with forward slashes: the reviewer works in
137
198
  // the worktree, so a relative path would land there.
138
199
  const inSessionRoot = (root, name) => path.resolve(root, ...REVIEWS.split('/'), name).split(path.sep).join('/');
@@ -165,18 +226,32 @@ const withNextPath = (root, id, result, verdicts, independent) => ({
165
226
  verdictPath: !independent && (result.next === 'fix' || result.next === 'ask') ? nextVerdictPath(root, id, verdicts) : null,
166
227
  });
167
228
 
168
- // An independent verdict sits outside the in-loop cap (D-18): its blockers ask for a fix, never
169
- // `stuck`, and without blockers it goes to CI; its should-haves are the review procedure's to list.
170
- function outcome(k, v, verdicts, independent) {
229
+ // An independent verdict sits outside the in-loop cap (D-18): its blockers ask for a fix while
230
+ // another independent round is left (`left`, D-101), else `stuck`; without blockers it goes to CI;
231
+ // its should-haves are the review procedure's to list.
232
+ function outcome(k, v, verdicts, independent, left = true) {
171
233
  const blockers = v.findings.filter((f) => f.kind === 'blocker').map((f) => f.id);
172
234
  const shouldHaves = v.findings.filter((f) => f.kind === 'should-have').map((f) => f.id);
173
235
  const roundsUsed = inLoop(verdicts);
174
236
  let next = 'ci';
175
- if (blockers.length > 0) next = independent || roundsUsed < LOOP_ROUNDS ? 'fix' : 'stuck';
237
+ if (blockers.length > 0) next = (independent ? left : roundsUsed < LOOP_ROUNDS) ? 'fix' : 'stuck';
176
238
  else if (shouldHaves.length > 0 && !independent) next = 'ask';
177
239
  return { round: k, blockers, shouldHaves, roundsUsed, next };
178
240
  }
179
241
 
242
+ // The independent outcome with what a person needs (D-101): on `fix`, `reviewStart`, the command of
243
+ // the next independent round; on `stuck`, `stop`, the open blockers and the three choices.
244
+ function independentOutcome(root, cfg, id, number, k, v, verdicts) {
245
+ const left = independentRoundAllowed(independentBlockers(verdicts), extraRounds(root, cfg, id));
246
+ const result = outcome(k, v, verdicts, true, left);
247
+ if (result.next === 'fix') return { ...result, reviewStart: `slicekit review start ${number}` };
248
+ if (result.next === 'stuck') return { ...result, stop: stopText(root, cfg, id, number, k, v.findings.filter((f) => f.kind === 'blocker')) };
249
+ return result;
250
+ }
251
+
252
+ const outcomeOf = (root, cfg, id, number, k, v, verdicts, independent) =>
253
+ independent ? independentOutcome(root, cfg, id, number, k, v, verdicts) : outcome(k, v, verdicts, false);
254
+
180
255
  const push = (wt, cfg) => pushBranch(wt, { protectedBranches: cfg.protectedBranches, defaultBranch: cfg.defaultBranch });
181
256
 
182
257
  const blockersOf = (v) => (v?.findings ?? []).filter((f) => f.kind === 'blocker');
@@ -338,7 +413,10 @@ function assertBuilt(wt, id, current) {
338
413
  // -> {round, blockers, shouldHaves, roundsUsed, next, verdictPath}: `blockers` and `shouldHaves` are
339
414
  // finding IDs; `next` is `fix`, `ask`, `ci`, or `stuck` when an in-loop verdict leaves blockers at the last round.
340
415
  // `stuck` is returned, not thrown: the loop has stopped and changes-requested is recorded, and a
341
- // caller must exit 1 on it (the CLI does). `verdictPath` is the next round's file (nextVerdictPath)
416
+ // caller must exit 1 on it (the CLI does). An independent verdict is `stuck` when it leaves a blocker
417
+ // and no independent round is left (D-101); it then carries `stop`, the open blockers and the three
418
+ // choices to print, and on `fix` `reviewStart`, the command of the next independent round.
419
+ // `verdictPath` is the next round's file (nextVerdictPath)
342
420
  // on `fix` or `ask` of an in-loop verdict, else null.
343
421
  //
344
422
  // `independent` (D-39): the verdict of an independent review, named `<P-S>i-r<k>.md`, recorded from
@@ -397,7 +475,8 @@ export function recordVerdict(root, cfg, host, id, file, { worktree, independent
397
475
  fs.rmSync(src);
398
476
  }
399
477
  const v = checked(text, rel, name, independent);
400
- return withNextPath(root, id, finish(wt, cfg, host, id, current, outcome(k, v, verdicts, independent), verdicts, independent), verdicts, independent);
478
+ const result = outcomeOf(root, cfg, id, current.pr.number, k, v, verdicts, independent);
479
+ return withNextPath(root, id, finish(wt, cfg, host, id, current, result, verdicts, independent), verdicts, independent);
401
480
  }
402
481
 
403
482
  // D-18: two in-loop rounds; independent verdicts (D-39) do not count against them.
@@ -420,7 +499,8 @@ export function recordVerdict(root, cfg, host, id, file, { worktree, independent
420
499
  const unknown = referenceProblems(wt, rel, text, shown);
421
500
  if (unknown.length > 0) throw new BuildError(unknown.join('\n'));
422
501
  // The line this round would write, judged against the live body before anything moves.
423
- const stuck = outcome(k, v, [...verdicts, { independent }], independent).next === 'stuck';
502
+ const blockerCount = v.findings.filter((f) => f.kind === 'blocker').length;
503
+ const stuck = outcomeOf(root, cfg, id, current.pr.number, k, v, [...verdicts, { round: k, independent, blockers: blockerCount }], independent).next === 'stuck';
424
504
  const line = reviewerBlocked([...parsedVerdicts(wt, verdicts), { round: k, findings: v.findings, headSha: current.pr.headSha, independent }], {
425
505
  stuck,
426
506
  covers: coversIn(wt),
@@ -433,7 +513,7 @@ export function recordVerdict(root, cfg, host, id, file, { worktree, independent
433
513
  if (here && moved) fs.rmSync(src);
434
514
  else if (here) move(src, dest);
435
515
  commitBookkeeping(wt, id, `verdict r${k}`, [rel]);
436
- const blockers = v.findings.filter((f) => f.kind === 'blocker').length;
437
- const state = recordState(wt, cfg, id, 'in-review', { verdict: { round: k, path: rel, blockers, independent } });
438
- return withNextPath(root, id, finish(wt, cfg, host, id, state, outcome(k, v, state.verdicts, independent), state.verdicts, independent), state.verdicts, independent);
516
+ const state = recordState(wt, cfg, id, 'in-review', { verdict: { round: k, path: rel, blockers: blockerCount, independent } });
517
+ const result = outcomeOf(root, cfg, id, state.pr.number, k, v, state.verdicts, independent);
518
+ return withNextPath(root, id, finish(wt, cfg, host, id, state, result, state.verdicts, independent), state.verdicts, independent);
439
519
  }
@@ -92,11 +92,26 @@ export const SYNC_BRANCH = /^sync\/[0-9a-f]{7,40}$/;
92
92
  // merge commit's second parent when the event has none). Otherwise the current branch and HEAD.
93
93
  export function branchTip(ctx) {
94
94
  if (!ctx.git?.isRepo || !ctx.git.hasCommits) return null;
95
- const ref = ctx.env?.GITHUB_HEAD_REF;
96
- if (ctx.ci && typeof ref === 'string' && ref !== '') {
95
+ const ref = headRef(ctx.env);
96
+ if (ctx.ci && ref) {
97
97
  const headSha = readCiEvent(ctx.env)?.headSha;
98
98
  const tip = (headSha && /^[0-9a-f]{7,40}$/.test(headSha) && resolveCommit(ctx.root, headSha)) || resolveCommit(ctx.root, 'HEAD^2') || 'HEAD';
99
99
  return { branch: ref, tip };
100
100
  }
101
101
  return ctx.git.branch ? { branch: ctx.git.branch, tip: 'HEAD' } : null;
102
102
  }
103
+
104
+ // The pull request's head branch GitHub Actions names in GITHUB_HEAD_REF, or null when unset or empty.
105
+ function headRef(env) {
106
+ const ref = env?.GITHUB_HEAD_REF;
107
+ return typeof ref === 'string' && ref !== '' ? ref : null;
108
+ }
109
+
110
+ // The name of the branch judged: branchTip's, else HEAD's branch name (a branch with no commit yet).
111
+ // With a detached HEAD, without --ci too, it is the pull request's head branch when CI names it: the
112
+ // test job checks out the pull request's merge commit detached (P8/S-58, review B-4).
113
+ export function judgedBranch(ctx) {
114
+ const branch = branchTip(ctx)?.branch ?? ctx.git?.branch ?? null;
115
+ if (branch) return branch;
116
+ return ctx.git?.isRepo ? headRef(ctx.env) : null;
117
+ }
@@ -1,11 +1,14 @@
1
1
  // layout (03 REQ-3.7, 01 REQ-1.1, REQ-1.10): every path slicekit init lays down must exist, as the
2
2
  // kind it was laid down as; and no file under .claude/ may be one the manifest ships only for
3
3
  // another shape. A file under .claude/ that no manifest entry names is the team's and never a
4
- // finding. With no .slicekit/config.json the rule is silent: there is no install to judge.
4
+ // finding. `.gitattributes` carries the BUILD.md merge rule init writes (REQ-1.6, D-100). With no
5
+ // .slicekit/config.json the rule is silent: there is no install to judge.
5
6
  import fs from 'node:fs';
6
7
  import path from 'node:path';
7
8
  import { listFiles } from '../../fs.js';
9
+ import { lines } from '../../markdown.js';
8
10
  import { loadManifest } from '../../render/manifest.js';
11
+ import { BUILD_MERGE_RULE } from '../../state/build.js';
9
12
 
10
13
  export const id = 'layout';
11
14
  export const blocking = true;
@@ -39,6 +42,12 @@ export function run(ctx) {
39
42
  }
40
43
  }
41
44
 
45
+ const squash = (line) => line.trim().replace(/\s+/g, ' ').replace(/^\//, '');
46
+ const attributes = kindOf(paths.gitattributes) === 'file' ? lines(fs.readFileSync(paths.gitattributes, 'utf8')).map(squash) : [];
47
+ if (!attributes.includes(BUILD_MERGE_RULE)) {
48
+ out.push({ file: rel(paths.gitattributes), line: 1, message: `${rel(paths.gitattributes)} lacks the line ${BUILD_MERGE_RULE}; run slicekit init` });
49
+ }
50
+
42
51
  if (kindOf(paths.claude) === 'dir') {
43
52
  const ours = new Set();
44
53
  const foreign = new Set();
@@ -1,12 +1,15 @@
1
1
  // queue (01 REQ-1.6, 03 REQ-3.7): BUILD.md is a view of the slice files and their state, so its
2
2
  // generated region must read exactly as `slicekit status --write` would write it. The text below
3
- // the marker is the team's and is never compared.
3
+ // the marker is the team's and is never compared. On a slice branch the rule is silent: the branch
4
+ // commits no BUILD.md of its own, and the sync after its merge regenerates it (D-100).
4
5
  import fs from 'node:fs';
5
6
  import path from 'node:path';
6
7
  import { readText } from '../../fs.js';
7
8
  import { lines } from '../../markdown.js';
8
9
  import { findSliceFiles } from '../../slicefile.js';
9
10
  import { generatedRegion, renderBuild, MARKER } from '../../state/build.js';
11
+ import { sliceFromBranch } from '../../ids.js';
12
+ import { judgedBranch } from '../ci-event.js';
10
13
 
11
14
  export const id = 'queue';
12
15
  export const blocking = true;
@@ -56,8 +59,15 @@ function unplanned(ctx) {
56
59
  return states.length === 0 && findSliceFiles(ctx.root, ctx.cfg).length === 0;
57
60
  }
58
61
 
62
+ // The branch judged is a slice branch: HEAD's, or with --ci or a detached HEAD the pull request's
63
+ // head branch CI names (judgedBranch).
64
+ function onSliceBranch(ctx) {
65
+ const branch = judgedBranch(ctx);
66
+ return Boolean(branch && sliceFromBranch(branch));
67
+ }
68
+
59
69
  export function run(ctx) {
60
- if (unplanned(ctx)) return [];
70
+ if (unplanned(ctx) || onSliceBranch(ctx)) return [];
61
71
  const file = toPosix(path.relative(ctx.root, ctx.paths.build));
62
72
  const at = (line, message) => ({ file, line, message });
63
73
  if (!fs.existsSync(ctx.paths.build)) return [at(0, `${file} is missing; run slicekit status --write`)];
package/src/cli/build.js CHANGED
@@ -172,9 +172,11 @@ function verdictStep(root, io, positionals, values) {
172
172
  const out = [`next: ${r.next}`, `blockers: ${list(r.blockers)}`, `should-haves: ${list(r.shouldHaves)}`, `rounds: ${r.roundsUsed} of ${LOOP_ROUNDS}`];
173
173
  if (r.next === 'ask' && r.roundsUsed >= LOOP_ROUNDS) out.push('fix: not available after round 2; decline or leave for the independent review');
174
174
  if (r.verdictPath) out.push(`verdict ${r.verdictPath}`);
175
+ // D-101: the command of the next independent round, when one is left after a blocker.
176
+ if (r.reviewStart) out.push(`review: ${r.reviewStart}`);
175
177
  io.stdout(out.map((l) => `${l}\n`).join(''));
176
178
  if (r.next === 'stuck') {
177
- io.stderr(`slicekit: stopped: ${r.blockers.join(', ')} survive round ${r.round}; the pull request stays draft\n`);
179
+ io.stderr(`slicekit: stopped: ${r.blockers.join(', ')} survive round ${r.round}; the pull request stays draft\n${r.stop ? `${r.stop}\n` : ''}`);
178
180
  return 1;
179
181
  }
180
182
  return 0;
package/src/cli/status.js CHANGED
@@ -1,24 +1,49 @@
1
+ import path from 'node:path';
1
2
  import { parseArgs } from 'node:util';
2
3
  import { ConfigError, loadConfig } from '../config.js';
3
4
  import { exists, readText, writeText } from '../fs.js';
4
5
  import { kitPaths } from '../paths.js';
5
6
  import { SliceFileError, findSliceFiles, parseSliceFile } from '../slicefile.js';
6
7
  import { programStage } from '../stage.js';
7
- import { renderBuild } from '../state/build.js';
8
+ import { mergeBuild, renderBuild } from '../state/build.js';
8
9
  import { LockError, readSlice } from '../state/index.js';
9
10
  import { syncFromHost } from '../state/sync.js';
10
11
  import { ReleaseError, applyRelease, onDefaultTip } from '../release-version.js';
11
12
  import { getHost } from '../adapters/githost/index.js';
12
13
  import { GitHostError } from '../adapters/githost/errors.js';
13
14
 
14
- const USAGE = 'status [--json] [--write] [--sync]';
15
+ const USAGE = 'status [--json] [--write] [--sync] | status --merge-driver <ancestor> <current> <other>';
15
16
 
16
17
  const OPTIONS = {
17
18
  json: { type: 'boolean' },
18
19
  write: { type: 'boolean' },
19
20
  sync: { type: 'boolean' },
21
+ 'merge-driver': { type: 'boolean' },
20
22
  };
21
23
 
24
+ // The merge driver git runs for BUILD.md on a local merge (REQ-1.6, D-100): BUILD.md rendered from
25
+ // the merged state files is written to <current>, the path git gave as %A. Exit 0 is a clean merge;
26
+ // any other exit leaves BUILD.md conflicted.
27
+ function mergeDriver(root, files, io) {
28
+ if (files.length !== 3) {
29
+ io.stderr(`slicekit: --merge-driver takes three paths, %O %A %B\nusage: slicekit ${USAGE}\n`);
30
+ return 2;
31
+ }
32
+ try {
33
+ const cfg = loadConfig(root);
34
+ const read = (f) => {
35
+ const abs = path.resolve(root, f);
36
+ return exists(abs) ? readText(abs) : '';
37
+ };
38
+ const [ancestor, current, other] = files.map(read);
39
+ writeText(path.resolve(root, files[1]), mergeBuild(root, cfg, { ancestor, current, other, env: io.env ?? process.env }));
40
+ return 0;
41
+ } catch (e) {
42
+ io.stderr(`slicekit: BUILD.md merge driver: ${e.message}\n`);
43
+ return 1;
44
+ }
45
+ }
46
+
22
47
  function slices(root, cfg) {
23
48
  return findSliceFiles(root, cfg).map((f) => {
24
49
  const slice = parseSliceFile(readText(f.path), f.path);
@@ -38,13 +63,15 @@ const expected = (e) =>
38
63
  // Without --json, changes go to stdout and warnings and errors to stderr.
39
64
  async function run(args, io) {
40
65
  let values;
66
+ let positionals;
41
67
  try {
42
- ({ values } = parseArgs({ args, options: OPTIONS, allowPositionals: false }));
68
+ ({ values, positionals } = parseArgs({ args, options: OPTIONS, allowPositionals: args.includes('--merge-driver') }));
43
69
  } catch (e) {
44
70
  io.stderr(`slicekit: ${e.message}\nusage: slicekit ${USAGE}\n`);
45
71
  return 2;
46
72
  }
47
73
  const root = io.cwd;
74
+ if (values['merge-driver']) return mergeDriver(root, positionals, io);
48
75
  const warnings = [];
49
76
  const synced = [];
50
77
  let version = null;
package/src/init.js CHANGED
@@ -7,6 +7,7 @@ import { currentBranch, detectDefaultBranch, git, GitError, hasCommits, isRepo }
7
7
  import { GITHOOKS, HOOKS_PATH, hooksPathValue, isInstalledHooksPath } from './githooks.js';
8
8
  import { probeCli } from './hook-cli.js';
9
9
  import { kitPaths } from './paths.js';
10
+ import { BUILD_MERGE_DRIVER, BUILD_MERGE_RULE, mergeDriverCommand } from './state/build.js';
10
11
  import { kitVersion, renderAll } from './render/index.js';
11
12
  import { readSettings } from './render/settings.js';
12
13
  import { WORKFLOW_DRIFT, WORKFLOW_PATH, workflowState, workflowSteps } from './workflow.js';
@@ -122,8 +123,27 @@ function attributeRules(root, cfg) {
122
123
  return [
123
124
  { rule: '.githooks/* text eol=lf', forms: new Set(['.githooks/* text eol=lf', '/.githooks/* text eol=lf']) },
124
125
  { rule: intake, forms: new Set([intake, `/${intake}`]) },
126
+ { rule: BUILD_MERGE_RULE, forms: new Set([BUILD_MERGE_RULE, `/${BUILD_MERGE_RULE}`]) },
125
127
  ];
126
128
  }
129
+
130
+ // The merge driver the BUILD.md rule names, set in this clone's git config (REQ-1.6, D-100): a local
131
+ // merge regenerates BUILD.md from the merged state files. Set once; a second init leaves one entry.
132
+ function setMergeDriver(root, cfg) {
133
+ const want = mergeDriverCommand(cfg.cli);
134
+ const key = `merge.${BUILD_MERGE_DRIVER}`;
135
+ let have = [];
136
+ try {
137
+ have = git(root, ['config', '--local', '--get-all', `${key}.driver`]).split('\n').filter(Boolean);
138
+ } catch (e) {
139
+ if (!(e instanceof GitError)) throw e;
140
+ }
141
+ if (have.length !== 1 || have[0] !== want) {
142
+ if (have.length > 0) git(root, ['config', '--local', '--unset-all', `${key}.driver`]);
143
+ git(root, ['config', '--local', `${key}.driver`, want]);
144
+ }
145
+ git(root, ['config', '--local', `${key}.name`, 'slicekit: BUILD.md rendered from the merged state files']);
146
+ }
127
147
  const NOT_A_REPO = 'not a git repository';
128
148
  const UNBORN_PROTECTED = 'commit this scaffold with ALLOW_PROTECTED_COMMIT=1 git commit …, or start on a slice branch';
129
149
 
@@ -405,6 +425,7 @@ export function init(root, { name, shape, docsRoot, commands = {}, cli, defaultB
405
425
  if (repo) {
406
426
  stageHooks(root, hooks, warnings);
407
427
  setHooksPath(root, warnings);
428
+ setMergeDriver(root, cfg);
408
429
  }
409
430
  // The CI workflow (REQ-3.11): written when absent; an existing one is the team's and stays as is.
410
431
  const workflow = workflowState(root, cfg);
package/src/paths.js CHANGED
@@ -31,5 +31,6 @@ export function kitPaths(root, cfg) {
31
31
  githooks: path.join(root, '.githooks'),
32
32
  workflow: path.join(root, '.github', 'workflows', 'slicekit.yml'),
33
33
  gitignore: path.join(root, '.gitignore'),
34
+ gitattributes: path.join(root, '.gitattributes'),
34
35
  };
35
36
  }
@@ -1,14 +1,22 @@
1
+ import { execFileSync } from 'node:child_process';
1
2
  import fs from 'node:fs';
3
+ import os from 'node:os';
2
4
  import path from 'node:path';
3
5
  import { fileURLToPath } from 'node:url';
4
6
  import { readText } from '../fs.js';
7
+ import { git, GitError } from '../git.js';
5
8
  import { headings, lines } from '../markdown.js';
6
9
  import { kitPaths } from '../paths.js';
7
10
  import { findSliceFiles, parsePhaseFile, parseSliceFile, phaseOfDir } from '../slicefile.js';
8
11
  import { readSlice } from './index.js';
9
12
 
10
13
  export const MARKER = '<!-- slicekit:generated:end -->';
11
- const LINE_MARK = /\s*<!--\s*slicekit:(?:example|pending\s+P\d+\/S-\d{2})\s*-->\s*$/;
14
+
15
+ // The merge driver of REQ-1.6 (D-100): `.gitattributes` names it for BUILD.md, and init sets its
16
+ // command in the clone's git config. git runs the command with %O %A %B on a local merge.
17
+ export const BUILD_MERGE_DRIVER = 'slicekit-build';
18
+ export const BUILD_MERGE_RULE = `BUILD.md merge=${BUILD_MERGE_DRIVER}`;
19
+ export const mergeDriverCommand = (cli) => `${cli} status --merge-driver %O %A %B`;
12
20
 
13
21
  const TEMPLATE = fileURLToPath(new URL('../../templates/docs/BUILD.md', import.meta.url));
14
22
  const TITLE = '# BUILD — the queue';
@@ -24,6 +32,7 @@ export function statusCell(state) {
24
32
  return 'Todo';
25
33
  }
26
34
 
35
+ const posixRel = (root, abs) => path.relative(root, abs).split(path.sep).join('/');
27
36
  const cell = (s) => String(s).replace(/\s*\n\s*/g, ' ').replace(/(?<!\\)\|/g, '\\|');
28
37
 
29
38
  // The text under a level-2 heading, up to the next level-2 heading, trimmed; null when absent.
@@ -131,19 +140,34 @@ export function renderBuild(root, cfg, existingText = '', { onWarning = () => {}
131
140
  for (const f of sliceFiles) {
132
141
  const slice = parseSliceFile(readText(f.path), f.path);
133
142
  const list = slicesByPhase.get(f.phaseId) ?? [];
134
- list.push({ slice, state: readSlice(root, cfg, slice.id) });
143
+ list.push({ slice, state: readSlice(root, cfg, slice.id), rel: posixRel(root, f.path) });
135
144
  slicesByPhase.set(f.phaseId, list);
136
145
  }
137
146
 
147
+ // A phase whose slices are all merged or released is one line under "Merged phases"; every other
148
+ // phase has its table, one row per slice with a link to its slice file and no Done when (D-105).
149
+ const merged = (phase) => {
150
+ const list = slicesByPhase.get(phase.id) ?? [];
151
+ return list.length > 0 && list.every(({ state }) => DONE.has(state.state));
152
+ };
153
+ const folded = found.filter(merged);
138
154
  const out = [TITLE, '', preamble(cfg)];
155
+ if (folded.length > 0) {
156
+ out.push('', '## Merged phases', '');
157
+ for (const phase of folded) {
158
+ const count = slicesByPhase.get(phase.id).length;
159
+ const folder = posixRel(root, phase.dir);
160
+ out.push(`- Phase ${phase.n} — ${phase.name}: ${count} ${count === 1 ? 'slice' : 'slices'}, all merged; slice files in \`${folder}/\`.`);
161
+ }
162
+ }
139
163
  for (const phase of found) {
164
+ if (merged(phase)) continue;
140
165
  out.push('', `## Phase ${phase.n} — ${phase.name}`, '');
141
- out.push('| Slice | Name | Done when | Group | Status |', '|---|---|---|---|---|');
142
- for (const { slice, state } of slicesByPhase.get(phase.id) ?? []) {
166
+ out.push('| Slice | Name | Group | Slice file | Status |', '|---|---|---|---|---|');
167
+ for (const { slice, state, rel } of slicesByPhase.get(phase.id) ?? []) {
143
168
  const short = slice.id.split('/')[1];
144
- // A slice file's example or pending marker stays in the slice file, which is checked bullet by bullet.
145
- const done = slice.doneWhen.map((d) => d.replace(LINE_MARK, '').replace(/(?<!\.)\.$/, '')).join('; ');
146
- out.push(`| ${short} | ${cell(slice.name)} | ${cell(done)} | ${cell(slice.group)} | ${statusCell(state)} |`);
169
+ const link = `[${cell(path.posix.basename(rel))}](${rel})`;
170
+ out.push(`| ${short} | ${cell(slice.name)} | ${cell(slice.group)} | ${link} | ${statusCell(state)} |`);
147
171
  }
148
172
  if (phase.order) out.push('', phase.order);
149
173
  }
@@ -154,3 +178,87 @@ export function renderBuild(root, cfg, existingText = '', { onWarning = () => {}
154
178
  const rest = tail === null ? migratedTail(existingText ?? '', generatedPhases) : prunedTail(tail, generatedPhases);
155
179
  return `${generated}\n${MARKER}\n${rest}`;
156
180
  }
181
+
182
+ // The other side of the merge git is running: `git merge` names each merged head in a
183
+ // GITHEAD_<sha> variable of the driver's environment. Null when there is not exactly one.
184
+ function otherHead(env) {
185
+ const heads = Object.keys(env)
186
+ .map((k) => /^GITHEAD_([0-9a-f]{40}|[0-9a-f]{64})$/i.exec(k)?.[1])
187
+ .filter(Boolean);
188
+ return heads.length === 1 ? heads[0] : null;
189
+ }
190
+
191
+ // path → blob id of every file under `dirs` in `commit`; an empty map for no commit.
192
+ function blobs(root, commit, dirs) {
193
+ const out = new Map();
194
+ if (!commit) return out;
195
+ const listed = git(root, ['ls-tree', '-r', '-z', '--full-tree', commit, '--', ...dirs]);
196
+ for (const entry of listed.split('\0').filter(Boolean)) {
197
+ const tab = entry.indexOf('\t');
198
+ const [, type, sha] = entry.slice(0, tab).split(' ');
199
+ if (type === 'blob') out.set(entry.slice(tab + 1), sha);
200
+ }
201
+ return out;
202
+ }
203
+
204
+ // The content of each blob id, read by one `git cat-file --batch`.
205
+ function readBlobs(root, shas) {
206
+ const out = new Map();
207
+ if (shas.length === 0) return out;
208
+ const raw = execFileSync('git', ['cat-file', '--batch'], { cwd: root, input: `${shas.join('\n')}\n`, maxBuffer: 1 << 28 });
209
+ let at = 0;
210
+ while (at < raw.length) {
211
+ const nl = raw.indexOf(10, at);
212
+ const [sha, , size] = raw.subarray(at, nl).toString('utf8').split(' ');
213
+ const start = nl + 1;
214
+ out.set(sha, raw.subarray(start, start + Number(size)));
215
+ at = start + Number(size) + 1;
216
+ }
217
+ return out;
218
+ }
219
+
220
+ const tryGit = (root, args) => {
221
+ try {
222
+ return git(root, args);
223
+ } catch (e) {
224
+ if (e instanceof GitError) return null;
225
+ throw e;
226
+ }
227
+ };
228
+
229
+ // BUILD.md for a local merge (the driver of REQ-1.6, D-100): `ancestor`, `current` and `other` are
230
+ // the texts of %O, %A and %B. The slice files and state files are merged path by path, the way git
231
+ // merges them (a side that left a file as the merge base had it takes the other side's), into a
232
+ // temporary tree, and BUILD.md is rendered from it. The text below the marker is the side's that
233
+ // changed it, else this side's. With no other head to read, BUILD.md is rendered from the working tree.
234
+ export function mergeBuild(root, cfg, { ancestor = '', current = '', other = '', env = process.env } = {}) {
235
+ const changedTail = generatedRegion(current).tail !== generatedRegion(ancestor).tail;
236
+ const existing = changedTail ? current : other;
237
+ const theirs = otherHead(env);
238
+ const head = tryGit(root, ['rev-parse', '--verify', '--quiet', 'HEAD']);
239
+ if (!theirs || !head || !tryGit(root, ['rev-parse', '--verify', '--quiet', `${theirs}^{commit}`])) {
240
+ return renderBuild(root, cfg, existing);
241
+ }
242
+ const paths = kitPaths(root, cfg);
243
+ const dirs = [paths.state, paths.phases].map((d) => posixRel(root, d));
244
+ const base = tryGit(root, ['merge-base', head, theirs]);
245
+ const [o, a, b] = [base, head, theirs].map((c) => blobs(root, c, dirs));
246
+ const chosen = new Map();
247
+ for (const file of new Set([...a.keys(), ...b.keys()])) {
248
+ const [was, ours, them] = [o.get(file), a.get(file), b.get(file)];
249
+ const pick = ours === was ? them : ours;
250
+ if (pick) chosen.set(file, pick);
251
+ }
252
+ const content = readBlobs(root, [...new Set(chosen.values())]);
253
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'slicekit-build-merge-'));
254
+ try {
255
+ for (const [file, sha] of chosen) {
256
+ const abs = path.join(tmp, ...file.split('/'));
257
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
258
+ fs.writeFileSync(abs, content.get(sha));
259
+ }
260
+ return renderBuild(tmp, cfg, existing);
261
+ } finally {
262
+ fs.rmSync(tmp, { recursive: true, force: true });
263
+ }
264
+ }
@@ -1,9 +1,12 @@
1
1
  // D-35: a verdict given on head `from` still holds on a later head `to` when `to` descends from
2
2
  // `from` and every change between them is the kit's own bookkeeping: the state directory, the
3
3
  // review verdicts, the journal directory (every file under it) and BUILD.md. Without this, committing the verdict and the state
4
- // file would itself make every verdict stale. Any doubt (unknown commit, no repository) is "no".
4
+ // file would itself make every verdict stale. A merge of the default branch that leaves every file
5
+ // the pull request changes as it was also keeps the verdict (D-100). Any doubt (unknown commit, no
6
+ // repository, no config) is "no".
5
7
  import path from 'node:path';
6
8
  import { isSha, sameSha } from '../evidence.js';
9
+ import { loadConfig } from '../config.js';
7
10
  import { GitError, git, resolveCommit } from '../git.js';
8
11
  import { kitPaths } from '../paths.js';
9
12
 
@@ -33,7 +36,8 @@ export function isBookkeepingPath(root, rel) {
33
36
  return bookkeepingTest(root)(rel);
34
37
  }
35
38
 
36
- export function headCovers(root, from, to) {
39
+ // `merges: false` judges by D-35 alone: a merge of the default branch is a moved head (D-43).
40
+ export function headCovers(root, from, to, { merges = true } = {}) {
37
41
  if (!isSha(from) || !isSha(to)) return false;
38
42
  if (sameSha(from, to)) return true;
39
43
  try {
@@ -47,12 +51,88 @@ export function headCovers(root, from, to) {
47
51
  if (e instanceof GitError) return false;
48
52
  throw e;
49
53
  }
50
- const out = git(root, ['diff', '--name-only', '--no-renames', a, b, '--']);
51
- const changed = out === '' ? [] : out.split('\n');
52
54
  const kept = bookkeeping(root);
53
- return changed.every((f) => inBookkeeping(kept, f));
55
+ if (names(root, ['diff', '--name-only', '--no-renames', a, b, '--']).every((f) => inBookkeeping(kept, f))) {
56
+ // A bookkeeping-only difference that a merge reached by putting back older content is no cover.
57
+ return !merges || firstParentLine(root, a, b).every(({ sha, parents }) => parents.length < 2 || keepsSecondParent(root, kept, sha, parents));
58
+ }
59
+ return merges && mergedDefaultOnly(root, kept, a, b);
54
60
  } catch (e) {
55
61
  if (e instanceof GitError) return false;
56
62
  throw e;
57
63
  }
58
64
  }
65
+
66
+ const names = (root, args) => git(root, args).split('\n').filter(Boolean);
67
+
68
+ // The default branch's tips, on origin first, then local, that resolve; none without a readable config.
69
+ function defaultTips(root) {
70
+ let name;
71
+ try {
72
+ name = loadConfig(root).defaultBranch;
73
+ } catch {
74
+ return [];
75
+ }
76
+ if (typeof name !== 'string' || name === '') return [];
77
+ return [`refs/remotes/origin/${name}`, `refs/heads/${name}`]
78
+ .map((ref) => resolveCommit(root, ref))
79
+ .filter(Boolean);
80
+ }
81
+
82
+ const isAncestor = (root, x, y) => {
83
+ try {
84
+ git(root, ['merge-base', '--is-ancestor', x, y]);
85
+ return true;
86
+ } catch (e) {
87
+ if (e instanceof GitError) return false;
88
+ throw e;
89
+ }
90
+ };
91
+
92
+ // D-100, refining D-35: B adds to A, on its first-parent line, only bookkeeping commits and merges
93
+ // whose second parent the default branch reaches and which give every file the slice branch did not
94
+ // change that parent's content, and every file the pull request changes (its
95
+ // changes against the default branch's merge base at A and at B, bookkeeping aside) has the same
96
+ // content at B as at A.
97
+ // The commits B adds to A on its first-parent line, each with its parents.
98
+ const firstParentLine = (root, a, b) =>
99
+ names(root, ['rev-list', '--first-parent', '--parents', b, `^${a}`]).map((line) => {
100
+ const [sha, ...parents] = line.split(' ');
101
+ return { sha, parents };
102
+ });
103
+
104
+ // Whether merge `sha` gives every file its first parent did not change since it met the second
105
+ // parent, bookkeeping aside, the second parent's content: a merge that puts back older content of a
106
+ // file only the default branch changed does not.
107
+ function keepsSecondParent(root, kept, sha, parents) {
108
+ const base = git(root, ['merge-base', parents[0], parents[1]]);
109
+ const ownSide = new Set(names(root, ['diff', '--name-only', '--no-renames', base, parents[0], '--']));
110
+ return names(root, ['diff', '--name-only', '--no-renames', parents[1], sha, '--']).every((f) => inBookkeeping(kept, f) || ownSide.has(f));
111
+ }
112
+
113
+ function mergedDefaultOnly(root, kept, a, b) {
114
+ const tips = defaultTips(root);
115
+ if (tips.length === 0) return false;
116
+ for (const { sha, parents } of firstParentLine(root, a, b)) {
117
+ if (parents.length >= 2) {
118
+ if (!tips.some((t) => isAncestor(root, parents[1], t))) return false;
119
+ if (!keepsSecondParent(root, kept, sha, parents)) return false;
120
+ } else {
121
+ const own = names(root, ['diff-tree', '--no-commit-id', '--name-only', '--no-renames', '-r', '--root', sha]);
122
+ if (!own.every((f) => inBookkeeping(kept, f))) return false;
123
+ }
124
+ }
125
+ const own = new Set();
126
+ for (const head of [a, b]) {
127
+ const base = git(root, ['merge-base', head, tips[0]]);
128
+ for (const f of names(root, ['diff', '--name-only', '--no-renames', base, head, '--'])) if (!inBookkeeping(kept, f)) own.add(f);
129
+ }
130
+ if (own.size === 0) return true;
131
+ const files = [...own];
132
+ const blobs = (head) => {
133
+ const listed = git(root, ['ls-tree', '--full-tree', head, '--', ...files]);
134
+ return new Map(listed.split('\n').filter(Boolean).map((l) => [l.slice(l.indexOf('\t') + 1), l.split(' ')[2].split('\t')[0]]));
135
+ };
136
+ const [at, bt] = [blobs(a), blobs(b)];
137
+ return files.every((f) => at.get(f) === bt.get(f));
138
+ }
@@ -1,10 +1,10 @@
1
1
  # Brief: reviewer
2
2
 
3
- You review one slice and write one verdict file. You try to break the change: run its tests, read its diff against the slice file, the requirements it cites and the writing rules.
3
+ You review one slice and write one verdict file. You try to break the change: run its tests and read its diff against the slice file, its requirements and the writing rules.
4
4
 
5
5
  ## You write
6
6
 
7
- One verdict file and nothing else. The command gives you the absolute path to write it at; the path ends `.slicekit/reviews/P<n>-S-<nn>[i]-r<k>.md` and is in the session root, never under the worktree. `k` is the round; the letter `i` marks an independent review. The file has this shape:
7
+ One verdict file and nothing else. The command gives you the absolute path: it ends `.slicekit/reviews/P<n>-S-<nn>[i]-r<k>.md` and is in the session root, never under the worktree. `k` is the round; the letter `i` marks an independent review. The file has this shape:
8
8
 
9
9
  ```
10
10
  Verdict: BLOCK
@@ -41,23 +41,23 @@ The rest of the file:
41
41
 
42
42
  ## Reviewing a slice
43
43
 
44
- The command gives you the pull request number, the worktree, the round `k` and the verdict file's absolute path. Write the verdict at that path.
44
+ The command gives you the pull request, the worktree, the round `k` and the verdict path. Your round budget (REQ-2.6, REQ-2.8): two build rounds, one independent round and a second only after a blocker; a blocker left in the last round stops the slice.
45
45
 
46
46
  1. Read the slice file in the worktree, the change with `git diff <base>...HEAD` run in the worktree (read only; `<base>` is `defaultBranch` in `.slicekit/config.json`), and the pull request body.
47
- 2. Run the test command and `{{cli}} check` in the worktree. Quote each one's summary line in the "How verified" column of the findings it supports.
48
- 3. A blocker is one of these: a Done when check that fails; a REQ or D row the change breaks; a rule weakened or a baseline raised (REQ-3.7); a writing-rule breach in the pull request body. Every other finding is a should-have.
49
- 4. Finding IDs are unique within the slice. A finding that survives from an earlier round keeps its ID. A new finding takes the next number never used in this slice, B and H counted apart: after B-1 and B-2, a new blocker is B-3 even when B-2 was fixed. A verdict that reuses a number, or gives a finding that went away its old ID, is refused.
50
- 5. A verdict that uses a phrase from `style.banned` in `.slicekit/config.json`, or names missing IDs or backticked paths, is refused; reword it. The pull request body quotes each "What is wrong" as a code span, so a `<!--` in it is refused.
51
- 6. A should-have whose issue the pull request body lists under "Should-haves declined" is not raised again.
52
- 7. A finding states the fault and stops: no praise, no question, no code.
47
+ 2. Run the test command and `{{cli}} check` in the worktree. Quote each summary line in the "How verified" column of the findings it supports.
48
+ 3. A blocker is: a Done when check that fails; a REQ or D row the change breaks; a rule weakened or a baseline raised (REQ-3.7); a writing-rule breach in the pull request body. Every other finding is a should-have.
49
+ 4. A finding that survives from an earlier round keeps its ID. A new finding takes the next number never used in this slice, B and H counted apart: after B-1 and B-2, a new blocker is B-3 even if B-2 was fixed. Any other ID is refused.
50
+ 5. A verdict with a phrase from `style.banned` in `.slicekit/config.json`, an unknown slice, requirement or decision ID, a missing backticked path, or a `<!--` in a "What is wrong", is refused; reword it.
51
+ 6. A should-have the pull request body lists under "Should-haves declined" is not raised again.
52
+ 7. A finding states the fault and stops; it holds no code. You report no finding on wording, formatting or naming alone, and no finding when you have none: then write `Verdict: APPROVE` with an empty findings table.
53
53
 
54
54
  ## You never
55
55
 
56
56
  - Write or change code, tests or any file other than the verdict.
57
- - Ask a question. A doubt you cannot settle is a finding or a `## Not checked` item.
57
+ - Ask a question; a doubt is a finding or a `## Not checked` item.
58
58
  - Praise the change.
59
59
  - Run git, except the read-only `git diff`, `git log`, `git show` and `git status`. You never commit or push the verdict; the command does that.
60
60
 
61
61
  ## Your report
62
62
 
63
- Your reply names the verdict file's path and its verdict line. It ends with a `Skipped:` line and then a `Not checked:` line. Each of these lines starts at the beginning of its line, with no list marker, bold or backticks. When you stop, the newest verdict file of this slice is checked against the shape above; a missing or malformed file is refused.
63
+ Your reply names the verdict file's path and verdict line. It ends with a `Skipped:` line and then a `Not checked:` line. Each of these lines starts at the beginning of its line, with no list marker, bold or backticks. When you stop, the newest verdict file of this slice is checked against the shape above.
@@ -18,6 +18,10 @@ it is left to the person who started this session. When this session built the s
18
18
  the building session's context, stop and tell the human to run `/slicekit review <PR>` in a new
19
19
  session.
20
20
 
21
+ A reviewer subagent started by `{{cli}} review start <PR>` from the main checkout, given only the
22
+ pull request and the reviewer's brief and no build context, counts as independent, and
23
+ `/slicekit review` in a new session is the stronger form (D-104).
24
+
21
25
  When the arguments are `(none)`, ask the human for the pull request's number and use it in place of
22
26
  `{{args}}` below. Call that number `<n>`.
23
27
 
@@ -39,6 +43,13 @@ refusal and stop, since the human decides each of these. A refusal that names
39
43
  `build pr <id> --worktree <dir>` means an earlier review session committed a fix it did not push:
40
44
  run `{{cli}} build pr <id> --worktree <dir>` with the path it names, then this step again.
41
45
 
46
+ The independent review has one round, and a second only when the first left a blocker (D-101). A
47
+ refusal that `no independent round is left` names the latest round's open blockers and three
48
+ choices: fix them by hand, re-scope the slice, or record a decision row that allows one more round,
49
+ committed on the default branch and pushed to origin.
50
+ A refusal that the review `left no blocker` means the slice has its independent verdict. Print
51
+ either refusal and stop: the human decides.
52
+
42
53
  ## 3. The reviewer gives the independent verdict
43
54
 
44
55
  Run `{{cli}} instructions reviewer <id> --worktree <wt>`. Spawn the reviewer with that output as its
@@ -51,7 +62,9 @@ section lets it write that one file outside the worktree.
51
62
  When the reviewer stops, run `{{cli}} build verdict <id> <path> --independent --worktree <wt>` with
52
63
  step 2's verdict path. It commits the verdict into the review worktree, pushes it to the slice
53
64
  branch, and prints `next: <step>`, `blockers: <IDs or none>`, `should-haves: <IDs or none>` and
54
- `rounds: <used> of 2`; the rounds stay as they were. By what it prints:
65
+ `rounds: <used> of 2`; the rounds stay as they were. On `next: fix` it also prints
66
+ `review: <command>`, the `review start` command of the next independent round that the budget
67
+ allows (D-101); keep it for step 5. By what it prints:
55
68
 
56
69
  - A refusal that names the verdict's content (a finding with no "How verified", a reused finding
57
70
  number, a banned phrase, a `<!--`): send the reviewer back with the printed message, then run this
@@ -60,6 +73,10 @@ branch, and prints `next: <step>`, `blockers: <IDs or none>`, `should-haves: <ID
60
73
  session pushed since step 2. Run `{{cli}} build sync <id> --worktree <wt>`, then this command again.
61
74
  - `a new verdict needs a fresh fetch`: origin could not be reached. Print it and stop; tell the
62
75
  human to run this command again once origin answers.
76
+ - Exit 1 with `stopped:` and `next: stuck`: the round was the last one allowed and left a blocker
77
+ (D-101). The slice is `changes-requested`. Print the open blockers and the three choices it
78
+ prints and stop: the human fixes them by hand, re-scopes the slice, or records a decision row that
79
+ allows one more round, committed on the default branch and pushed to origin.
63
80
  - Any other refusal goes to the human: print it and stop.
64
81
 
65
82
  When the verdict lists should-haves, ask the human once, listing each with its ID and its "What is
@@ -91,7 +108,8 @@ When the fixer reports, run these two in this order:
91
108
  `pass --notes <file>`, the body lost a section: print the refusal and stop, since the notes are the
92
109
  building session's.
93
110
 
94
- Then start again at step 2 with `{{cli}} review start <n>`: the new head needs its own independent
111
+ Then start again at step 2 with the command step 4's `review:` line printed,
112
+ `{{cli}} review start <n>`: the new head needs its own independent
95
113
  verdict, at the next round. Tell the human that the slice branch moved under the building session:
96
114
  that session syncs its worktree with `build sync <id>` before its next push.
97
115