slicekit 0.7.1 → 0.7.3

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.1",
3
+ "version": "0.7.3",
4
4
  "description": "Spec-driven agentic workflow kit",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -10,7 +10,9 @@ import { configSubject, namesConfigAt } from './config.js';
10
10
  import { freshAt, renderPathsOnly, renderSubject } from './render.js';
11
11
  import { stateFileName, verdictFilePattern } from '../ids.js';
12
12
  import { kitPaths } from '../paths.js';
13
- import { TransitionError, readSlice, unfreeze } from '../state/index.js';
13
+ import { SliceFileError, parseSliceFile } from '../slicefile.js';
14
+ import { TransitionError, frozenOf, isFrozen, readSlice, unfreeze } from '../state/index.js';
15
+ import { SEP, TestNameError, entryLabel, findTest, isUnfrozen } from '../testnames.js';
14
16
  import { isKitFile, posixRel, runCommand, sliceIn, toWorktreePath, unusableRun } from './red.js';
15
17
  import { commitState, recordAmendment } from './record.js';
16
18
  import { BuildError, findWorktree } from './worktree.js';
@@ -65,23 +67,76 @@ function stateFileProblem(wt, stateRel, held) {
65
67
  return null;
66
68
  }
67
69
 
70
+ // The file's text at `rev` (`''` for the index), or null when it has no such file.
71
+ const textAt = (wt, rev, file) => {
72
+ try {
73
+ return git(wt, ['show', `${rev}:${file}`]);
74
+ } catch (e) {
75
+ if (e instanceof GitError) return null;
76
+ throw e;
77
+ }
78
+ };
79
+
80
+ // The slice file as it was at the red commit, read from git: a path entry of a state file written
81
+ // before P8/S-60 is read with this evaluation set, never the working tree's, which an agent can edit
82
+ // (D-102). Null when the red commit has no such file or it does not parse: every path entry is then
83
+ // the whole file, frozen for any change.
84
+ function sliceAtRed(wt, current, slice) {
85
+ if (typeof current.redCommit !== 'string' || current.redCommit === '') return null;
86
+ const rel = posixRel(wt, slice.path);
87
+ const text = textAt(wt, current.redCommit, rel);
88
+ if (text === null) return null;
89
+ try {
90
+ return parseSliceFile(text, rel);
91
+ } catch (e) {
92
+ if (e instanceof SliceFileError) return null;
93
+ throw e;
94
+ }
95
+ }
96
+
97
+ // The text of the test named `name` in `text`: null when the file or the test is missing; undefined
98
+ // when the file cannot be read by name (unparseable, or the name given twice), which never matches.
99
+ function bodyOf(text, name) {
100
+ if (text === null) return null;
101
+ try {
102
+ return findTest(text, name)?.text ?? null;
103
+ } catch (e) {
104
+ if (e instanceof TestNameError) return undefined;
105
+ throw e;
106
+ }
107
+ }
108
+
68
109
  // The first frozen test (not unfrozen) that differs from the red commit, and how: hidden from git by
69
- // skip-worktree or assume-unchanged, different bytes or missing on disk (an edit through Bash never
70
- // meets the pre-edit hook), or different in the index or a commit since (a mode change, a removal).
71
- function frozenProblem(wt, current) {
72
- for (const t of current.frozenTests) {
73
- if (current.unfrozen.includes(t)) continue;
110
+ // skip-worktree or assume-unchanged, different or missing on disk (an edit through Bash never meets
111
+ // the pre-edit hook), or different in the index or a commit since (a mode change, a removal). A test
112
+ // frozen by name (D-102) is compared by its text on disk, in the index and at HEAD; a file frozen
113
+ // whole (a state file written before P8/S-60 whose evaluation set names no test in it), by its bytes.
114
+ function frozenProblem(wt, current, slice) {
115
+ const entries = frozenOf(current, sliceAtRed(wt, current, slice)).filter((e) => !isUnfrozen(e, current.unfrozen));
116
+ const changed = (t, what = t) => `frozen test ${what} changed since ${short(current.redCommit)}; amend the slice file to change the evaluation set`;
117
+ for (const t of [...new Set(entries.map((e) => e.file))]) {
74
118
  const flag = git(wt, ['--literal-pathspecs', 'ls-files', '-v', '--', t]).slice(0, 1);
75
119
  if (flag === 'S' || (flag !== '' && flag !== flag.toUpperCase())) {
76
120
  return `frozen test ${t} is marked skip-worktree or assume-unchanged, so git cannot see its changes; clear the mark`;
77
121
  }
78
- const red = blobAt(wt, current.redCommit, t);
79
- const onDisk = fs.existsSync(path.join(wt, ...t.split('/'))) ? git(wt, ['hash-object', '--', t]) : null;
80
- const elsewhere = ['--cached', 'HEAD'].some(
81
- (where) => git(wt, ['--literal-pathspecs', 'diff', '--name-only', ...(where === 'HEAD' ? [current.redCommit, 'HEAD'] : [where, current.redCommit]), '--', t]) !== '',
82
- );
83
- if (onDisk !== red || elsewhere) {
84
- return `frozen test ${t} changed since ${short(current.redCommit)}; amend the slice file to change the evaluation set`;
122
+ const exists = fs.existsSync(path.join(wt, ...t.split('/')));
123
+ const names = entries.filter((e) => e.file === t).map((e) => e.name);
124
+ if (names.includes(null)) {
125
+ const red = blobAt(wt, current.redCommit, t);
126
+ const onDisk = exists ? git(wt, ['hash-object', '--', t]) : null;
127
+ const elsewhere = ['--cached', 'HEAD'].some(
128
+ (where) => git(wt, ['--literal-pathspecs', 'diff', '--name-only', ...(where === 'HEAD' ? [current.redCommit, 'HEAD'] : [where, current.redCommit]), '--', t]) !== '',
129
+ );
130
+ if (onDisk !== red || elsewhere) return changed(t);
131
+ continue;
132
+ }
133
+ // The file that holds the tests is gone: the file is named, as for a file frozen whole.
134
+ if (!exists || textAt(wt, '', t) === null || textAt(wt, 'HEAD', t) === null) return changed(t);
135
+ const versions = [fs.readFileSync(path.join(wt, ...t.split('/')), 'utf8'), textAt(wt, '', t), textAt(wt, 'HEAD', t)];
136
+ const atRed = textAt(wt, current.redCommit, t);
137
+ for (const name of names) {
138
+ const red = bodyOf(atRed, name);
139
+ if (versions.some((v) => { const b = bodyOf(v, name); return b === undefined || red === undefined || b !== red; })) return changed(t, entryLabel({ file: t, name }));
85
140
  }
86
141
  }
87
142
  return null;
@@ -327,7 +382,7 @@ export function commitWork(root, cfg, id, { message, requireGreen = false, workt
327
382
  const paths = staged.length > 0 ? staged : changedPaths(wt);
328
383
  const hidden = stateFileProblem(wt, stateRel, paths.includes(stateRel));
329
384
  if (hidden) throw new BuildError(hidden);
330
- const frozen = frozenProblem(wt, current);
385
+ const frozen = frozenProblem(wt, current, slice);
331
386
  if (frozen) throw new BuildError(frozen);
332
387
  const kit = paths.find((p) => isKitFile(wt, cfg, slice, p));
333
388
  if (kit) {
@@ -389,7 +444,8 @@ function isAmendment(wt, id, sliceRel, sha) {
389
444
  // The state file on disk differs from HEAD's copy only by this unfreeze (and its move to building),
390
445
  // its amendment commit is on HEAD's history, and HEAD's state is one amend runs from: its bookkeeping
391
446
  // commit did not land.
392
- function pendingUnfreeze(wt, id, stateRel, sliceRel, file) {
447
+ // `test` is the entry as unfreeze stores it: a path, or { file, name }.
448
+ function pendingUnfreeze(wt, id, stateRel, sliceRel, test) {
393
449
  const committed = committedState(wt, stateRel);
394
450
  if (!committed || !AMEND_FROM.includes(committed.state)) return false;
395
451
  const now = JSON.parse(fs.readFileSync(path.join(wt, ...stateRel.split('/')), 'utf8'));
@@ -398,10 +454,10 @@ function pendingUnfreeze(wt, id, stateRel, sliceRel, file) {
398
454
  return (
399
455
  strip(now) === strip(committed) &&
400
456
  (now.state === committed.state || now.state === 'building') &&
401
- JSON.stringify(now.unfrozen) === JSON.stringify([...committed.unfrozen, file]) &&
457
+ JSON.stringify(now.unfrozen) === JSON.stringify([...committed.unfrozen, test]) &&
402
458
  now.history.length === committed.history.length + 1 &&
403
459
  JSON.stringify(now.history.slice(0, -1)) === JSON.stringify(committed.history) &&
404
- added?.evidence?.unfreeze === file &&
460
+ added?.evidence?.unfreeze === entryLabel(test) &&
405
461
  isAmendment(wt, id, sliceRel, added?.evidence?.amendCommit)
406
462
  );
407
463
  }
@@ -427,22 +483,19 @@ function pendingAmendment(wt, id, stateRel, sliceRel) {
427
483
  return pending ? sha : null;
428
484
  }
429
485
 
430
- // `build amend` with no test named (issue #72): the slice file alone is amended and committed, and
431
- // the reason recorded in the state file. Refused while any test the slice file names is still
432
- // frozen: a frozen test changes only when amend names it. A run that stopped after the slice file's
433
- // commit, or after the record was written but before it was committed, is finished.
434
- function amendSliceOnly(wt, cfg, id, current, reason, stateRel) {
435
- const frozen = current.frozenTests.filter((t) => !current.unfrozen.includes(t));
436
- if (frozen.length > 0) {
437
- throw new BuildError(`${frozen.join(', ')} ${frozen.length === 1 ? 'is' : 'are'} frozen; name the test amend changes with --test`);
438
- }
439
- const sliceRel = posixRel(wt, sliceIn(wt, cfg, id).path);
486
+ // An amendment of the slice file that unfreezes nothing (issue #72, issue #187, D-102): the slice file
487
+ // alone is committed and the reason recorded in the state file; every frozen test stays frozen, and
488
+ // the state stays where it is. `again`, the label of a test already unfrozen that the call named, joins
489
+ // the record as `test`: a second amendment of that test. A run that stopped after the slice file's
490
+ // commit, or after the record was written but before it was committed, is finished. `none` is the
491
+ // refusal when the slice file has no change.
492
+ function amendSliceFile(wt, cfg, id, current, reason, stateRel, sliceRel, { again, none = 'amend the slice file first; it has no change' } = {}) {
440
493
  const sliceChanged = git(wt, ['--literal-pathspecs', 'status', '--porcelain', '--', sliceRel]) !== '';
441
494
  const recorded = sliceChanged ? null : pendingAmendment(wt, id, stateRel, sliceRel);
442
495
  if (recorded) {
443
496
  // The record is written; only its bookkeeping commit is left.
444
497
  commitState(wt, cfg, id, 'amend');
445
- return { sha: recorded, test: null };
498
+ return { sha: recorded, test: again ?? null, again: again !== undefined };
446
499
  }
447
500
  let sha;
448
501
  if (sliceChanged) {
@@ -451,12 +504,26 @@ function amendSliceOnly(wt, cfg, id, current, reason, stateRel) {
451
504
  // A run that committed the slice file and stopped before its record is finished.
452
505
  sha = git(wt, ['rev-parse', 'HEAD']);
453
506
  } else {
454
- throw new BuildError('amend the slice file first; it has no change');
507
+ throw new BuildError(none);
455
508
  }
456
- recordAmendment(wt, cfg, id, { amendCommit: sha, reason });
457
- return { sha, test: null };
509
+ recordAmendment(wt, cfg, id, { amendCommit: sha, reason, ...(again === undefined ? {} : { test: again }) });
510
+ return { sha, test: again ?? null, again: again !== undefined };
511
+ }
512
+
513
+ // The test `--test` names: `<file> » <name>` as { file, name } (D-102), or a bare path, the whole file.
514
+ function namedTest(wt, given) {
515
+ const text = String(given).trim();
516
+ const at = text.indexOf(SEP.trim());
517
+ if (at === -1) return toWorktreePath(wt, text);
518
+ const name = text.slice(at + SEP.trim().length).trim();
519
+ if (name === '') throw new BuildError(`--test ${text} names no test after »`, 2);
520
+ return { file: toWorktreePath(wt, text.slice(0, at).trim()), name };
458
521
  }
459
522
 
523
+ // Whether `current.unfrozen` already lifts the freeze on `test`.
524
+ const alreadyUnfrozen = (current, test) =>
525
+ typeof test === 'string' ? current.unfrozen.includes(test) : isUnfrozen(test, current.unfrozen);
526
+
460
527
  // -> { sha, test }: the slice file's amendment commit, and the test as stored. A run that stopped part
461
528
  // way (the slice file committed, or the state written but not committed) is finished, not refused.
462
529
  export function amend(root, cfg, id, { test, reason, worktree } = {}) {
@@ -467,16 +534,35 @@ export function amend(root, cfg, id, { test, reason, worktree } = {}) {
467
534
  // Where amend runs from is read from HEAD's state file, never the copy on disk.
468
535
  const committed = committedState(wt, stateRel) ?? current;
469
536
  if (!AMEND_FROM.includes(committed.state)) throw new BuildError(`${id} is ${committed.state}; amend runs from ${AMEND_FROM.join(', ')}`);
470
- if (test === undefined || (typeof test === 'string' && test.trim() === '')) return amendSliceOnly(wt, cfg, id, current, reason.trim(), stateRel);
471
- const file = toWorktreePath(wt, test);
537
+ const slice = sliceIn(wt, cfg, id);
538
+ const sliceRel = posixRel(wt, slice.path);
539
+ // No test named: the slice file alone, whatever is frozen; every frozen test stays frozen (D-102).
540
+ if (test === undefined || (typeof test === 'string' && test.trim() === '')) return amendSliceFile(wt, cfg, id, current, reason.trim(), stateRel, sliceRel);
541
+ const target = namedTest(wt, test);
542
+ const label = entryLabel(target);
543
+ // A path entry is read with the evaluation set at the red commit, not the slice file being amended.
544
+ const atRed = sliceAtRed(wt, current, slice);
545
+ // A bare file whose tests are frozen by name unfreezes nothing: each test is named (REQ-1.5, D-102).
546
+ // Only a path entry, the form of a state file written before P8/S-60, unfreezes the whole file.
547
+ if (typeof target === 'string') {
548
+ const byName = current.frozenTests.filter((e) => typeof e !== 'string' && e.file === target);
549
+ if (byName.length > 0) {
550
+ throw new BuildError(`${target} holds tests frozen by name: ${byName.map(entryLabel).join(', ')}; name the one to unfreeze as --test "<file>${SEP}<name>"`);
551
+ }
552
+ }
472
553
  // Checked before the slice file is committed; the words are unfreeze's own TransitionError reason.
473
- if (!current.frozenTests.includes(file)) throw new BuildError(`${file} is not a frozen test of ${id}`);
474
- const sliceRel = posixRel(wt, sliceIn(wt, cfg, id).path);
554
+ if (!isFrozen(current, target, atRed)) throw new BuildError(`${label} is not a frozen test of ${id}`);
475
555
  const lastAmendment = () => git(wt, ['log', '-1', '--format=%H', `--grep=^docs(${id}): amend evaluation set$`, '--', sliceRel]);
476
- if (current.unfrozen.includes(file)) {
477
- if (!pendingUnfreeze(wt, id, stateRel, sliceRel, file)) throw new BuildError(`${file} is already unfrozen`);
478
- commitState(wt, cfg, id, `unfreeze ${file}`);
479
- return { sha: lastAmendment(), test: file };
556
+ if (alreadyUnfrozen(current, target)) {
557
+ if (pendingUnfreeze(wt, id, stateRel, sliceRel, target)) {
558
+ commitState(wt, cfg, id, `unfreeze ${label}`);
559
+ return { sha: lastAmendment(), test: label };
560
+ }
561
+ // A second amendment of a test already unfrozen: the slice file and the reason are recorded.
562
+ return amendSliceFile(wt, cfg, id, current, reason.trim(), stateRel, sliceRel, {
563
+ again: label,
564
+ none: `${label} is already unfrozen; a second amendment needs a change to the slice file`,
565
+ });
480
566
  }
481
567
  let sha;
482
568
  if (git(wt, ['--literal-pathspecs', 'status', '--porcelain', '--', sliceRel]) !== '') {
@@ -487,11 +573,11 @@ export function amend(root, cfg, id, { test, reason, worktree } = {}) {
487
573
  throw new BuildError('amend the slice file first; it has no change');
488
574
  }
489
575
  try {
490
- unfreeze(wt, cfg, id, file, { amendCommit: sha, reason: reason.trim() }, { to: 'building' });
576
+ unfreeze(wt, cfg, id, target, { amendCommit: sha, reason: reason.trim() }, { to: 'building', slice: atRed });
491
577
  } catch (e) {
492
578
  if (e instanceof TransitionError) throw new BuildError(e.reason);
493
579
  throw e;
494
580
  }
495
- commitState(wt, cfg, id, `unfreeze ${file}`);
496
- return { sha, test: file };
581
+ commitState(wt, cfg, id, `unfreeze ${label}`);
582
+ return { sha, test: label };
497
583
  }
package/src/build/red.js CHANGED
@@ -7,11 +7,11 @@ import path from 'node:path';
7
7
  import { buildTestCommand } from '../config.js';
8
8
  import { readText } from '../fs.js';
9
9
  import { commitPaths, git, headSha } from '../git.js';
10
- import { stateFileName } from '../ids.js';
11
10
  import { kitPaths } from '../paths.js';
12
11
  import { findSliceFiles, parseSliceFile } from '../slicefile.js';
13
12
  import { readSlice } from '../state/index.js';
14
- import { commitBookkeeping, recordState } from './record.js';
13
+ import { TestNameError, endsWithFile, entryFile, evaluationRows, findTest } from '../testnames.js';
14
+ import { commitState, recordState } from './record.js';
15
15
  import { BuildError, findWorktree } from './worktree.js';
16
16
 
17
17
  const nonEmpty = (text) => text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l !== '');
@@ -89,7 +89,6 @@ export function sliceIn(wt, cfg, id) {
89
89
  }
90
90
 
91
91
  export const posixRel = (wt, abs) => path.relative(wt, abs).split(path.sep).join('/');
92
- const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
93
92
 
94
93
  // A path (POSIX, relative to the worktree) the kit owns: anything under `.slicekit/` or `.githooks/`,
95
94
  // BUILD.md, the config, the slice file and `.claude/settings.json`. The kit's commands change these;
@@ -114,35 +113,43 @@ export function unusableRun(command, run) {
114
113
  return null;
115
114
  }
116
115
 
117
- // The rows as { row, file, name }: `<file> » <name>`, or a bare `<file>` with no name.
118
- function rows(slice) {
119
- return slice.evaluation.map(({ test }) => {
120
- const row = test.replace(/^`|`$/g, '').trim();
121
- const at = row.indexOf(' » ');
122
- return {
123
- row,
124
- file: (at === -1 ? row : row.slice(0, at)).trim(),
125
- name: at === -1 ? null : row.slice(at + ' » '.length).trim(),
126
- };
127
- });
128
- }
129
-
130
- const endsWithFile = (t, file) => t === file || t.endsWith(`/${file}`);
131
- // The name inside one string literal on one line: between matching quotes or backticks.
132
- const holdsName = (text, name) =>
133
- ["'", '"', '`'].some((q) => new RegExp(`${q}[^${q}\\n]*${escape(name)}[^${q}\\n]*${q}`).test(text));
134
-
135
- // Every row names a listed file ending in <file> that holds <name> as a string; every listed file
136
- // holds at least one row.
116
+ // Every row names a listed file ending in <file> that holds a `test(...)` or `it(...)` call named
117
+ // <name> (D-102); every listed file holds at least one row. -> the frozen entries, in row order:
118
+ // { file, name } for a named row, the file's path for a bare `<file>` row. A file the reader cannot
119
+ // parse, or one giving the name to two calls, is refused: its tests cannot be frozen by name.
137
120
  function checkEvaluation(wt, slice, tests) {
138
- const all = rows(slice);
121
+ const all = evaluationRows(slice);
122
+ const texts = new Map();
123
+ const textOf = (t) => {
124
+ if (!texts.has(t)) texts.set(t, readText(path.join(wt, t)));
125
+ return texts.get(t);
126
+ };
127
+ const frozen = [];
128
+ const add = (e) => {
129
+ if (!frozen.some((f) => JSON.stringify(f) === JSON.stringify(e))) frozen.push(e);
130
+ };
139
131
  for (const { row, file, name } of all) {
140
- const found = tests.some((t) => endsWithFile(t, file) && (name === null || holdsName(readText(path.join(wt, t)), name)));
141
- if (!found) throw new BuildError(`evaluation test "${row}" is not in the test files`);
132
+ const holders = tests.filter((t) => endsWithFile(t, file));
133
+ if (name === null) {
134
+ if (holders.length === 0) throw new BuildError(`evaluation test "${row}" is not in the test files`);
135
+ for (const t of holders) add(t);
136
+ continue;
137
+ }
138
+ const found = holders.find((t) => {
139
+ try {
140
+ return findTest(textOf(t), name) !== null;
141
+ } catch (e) {
142
+ if (e instanceof TestNameError) throw new BuildError(`${t}: ${e.message}; evaluation test "${row}" cannot be found by its name`);
143
+ throw e;
144
+ }
145
+ });
146
+ if (!found) throw new BuildError(`evaluation test "${row}" is not in the test files: no test(...) or it(...) call in ${holders.length > 0 ? holders.join(', ') : 'them'} is named "${name}"`);
147
+ add({ file: found, name });
142
148
  }
143
149
  for (const t of tests) {
144
150
  if (!all.some(({ file }) => endsWithFile(t, file))) throw new BuildError(`${t} holds no evaluation test`);
145
151
  }
152
+ return frozen;
146
153
  }
147
154
 
148
155
  // HEAD is this slice's red commit when it touches exactly the listed tests under the evaluation-set
@@ -165,19 +172,17 @@ function unchanged(wt, tests) {
165
172
  const noChange = (files) => new BuildError(`${files.join(', ')} have no change to commit; red needs the evaluation set as new or changed files`);
166
173
 
167
174
  // A run from tests-red: setState wrote tests-red but its bookkeeping commit, or the move to building,
168
- // did not land. The tests must be the frozen ones; nothing is run again.
175
+ // did not land. The tests must be the files of the frozen ones; nothing is run again. The bookkeeping
176
+ // commit holds the state file alone: a slice branch commits no BUILD.md (D-100, issue #210).
169
177
  function finishRed(wt, cfg, id, current, tests) {
170
178
  const files = resolveTests(wt, tests).sort();
171
- const frozen = [...current.frozenTests].sort();
179
+ const frozen = [...new Set(current.frozenTests.map(entryFile))].sort();
172
180
  if (files.length !== frozen.length || files.some((f, i) => f !== frozen[i])) {
173
- throw new BuildError(`${id} is tests-red with frozen tests ${current.frozenTests.join(', ')}; pass the same --tests`);
181
+ throw new BuildError(`${id} is tests-red with frozen tests ${frozen.join(', ')}; pass the same --tests`);
174
182
  }
175
- const paths = kitPaths(wt, cfg);
176
- const bookkeeping = [posixRel(wt, path.join(paths.state, stateFileName(id)))];
177
- if (fs.existsSync(paths.build)) bookkeeping.push(posixRel(wt, paths.build));
178
- commitBookkeeping(wt, id, 'tests-red', bookkeeping);
183
+ commitState(wt, cfg, id, 'tests-red');
179
184
  recordState(wt, cfg, id, 'building', {});
180
- return { commit: current.redCommit, tests: current.frozenTests };
185
+ return { commit: current.redCommit, tests: frozen };
181
186
  }
182
187
 
183
188
  export function red(root, cfg, id, { tests, worktree, env = process.env } = {}) {
@@ -190,7 +195,7 @@ export function red(root, cfg, id, { tests, worktree, env = process.env } = {})
190
195
  const files = resolveTests(wt, tests);
191
196
  const slice = sliceIn(wt, cfg, id);
192
197
  refuseKitFiles(wt, cfg, slice, files);
193
- checkEvaluation(wt, slice, files);
198
+ const frozen = checkEvaluation(wt, slice, files);
194
199
  const same = unchanged(wt, files);
195
200
  if (same.length > 0 && !headIsRedCommit(wt, id, files)) throw noChange(same);
196
201
 
@@ -202,7 +207,7 @@ export function red(root, cfg, id, { tests, worktree, env = process.env } = {})
202
207
  const made = commitPaths(wt, files, `test(${id}): evaluation set\n\nran: ${command} → exit ${run.exit}\n\nSlice: ${id}`);
203
208
  if (made === null && !headIsRedCommit(wt, id, files)) throw noChange(files);
204
209
  const commit = made ?? headSha(wt);
205
- recordState(wt, cfg, id, 'tests-red', { commit, testExit: run.exit, tests: files });
210
+ recordState(wt, cfg, id, 'tests-red', { commit, testExit: run.exit, tests: files, frozen });
206
211
  recordState(wt, cfg, id, 'building', {});
207
212
  return { commit, tests: files, local: local ? command : null };
208
213
  }
@@ -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);