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.
@@ -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
  }
@@ -1,8 +1,12 @@
1
- // frozen (03 REQ-3.15, D-10): on a slice branch, a test of the slice's evaluation set stays as it was at
2
- // the red commit recorded in the slice's state file, unless the slice file was changed in a commit
3
- // after the red commit (as `build amend` does). The state file, the red commit, the slice file and
4
- // the tests are all read from git objects of the tip judged, never the working tree: a file hidden
5
- // with `assume-unchanged` or `skip-worktree` is judged by its committed content (issue #71).
1
+ // frozen (03 REQ-3.15, D-10, D-102): on a slice branch, a test of the slice's evaluation set, found by
2
+ // its name in its file, stays as it was at the red commit recorded in the slice's state file, unless
3
+ // `build amend` unfroze that test after the red commit: the tip's state file lists it in `unfrozen`
4
+ // and the slice file was changed in a commit after red. Other tests of the same file are not
5
+ // compared. A path entry of a state file written before P8/S-60 is every evaluation test of that file
6
+ // by name in the slice file at the red commit, or the whole file when that evaluation set names none
7
+ // in it. The state file, the red commit, the slice file and the tests are all read from git objects
8
+ // (of the tip judged, or of the red commit), never the working tree: a file hidden with
9
+ // `assume-unchanged` or `skip-worktree` is judged by its committed content (issue #71).
6
10
  //
7
11
  // The tip is HEAD, or under --ci on a pull request the pull request's head (branchTip). No branch, a
8
12
  // branch that is not a slice branch, no red commit recorded in any version of the state file (a slice
@@ -22,7 +26,8 @@ import { GitError, git, resolveCommit } from '../../git.js';
22
26
  import { branchTip } from '../ci-event.js';
23
27
  import { parseSliceAddr, sliceFromBranch, stateFileName } from '../../ids.js';
24
28
  import { kitPaths } from '../../paths.js';
25
- import { phaseOfDir } from '../../slicefile.js';
29
+ import { SliceFileError, parseSliceFile, phaseOfDir } from '../../slicefile.js';
30
+ import { TestNameError, entryFile, entryLabel, evaluationRows, findTest, frozenEntries, isEntry, isUnfrozen } from '../../testnames.js';
26
31
 
27
32
  export const id = 'frozen';
28
33
  export const blocking = true;
@@ -115,22 +120,68 @@ export function run(ctx) {
115
120
  return [...removed, { file: stateRel, line: 0, message: `red commit ${red} of ${slice} is not in this repository` }];
116
121
  }
117
122
 
118
- const tests = [...new Set(listed)];
119
- const bad = tests.filter((t) => !validTest(t));
120
- if (bad.length > 0) return [...removed, { file: stateRel, line: 0, message: `frozen tests of ${slice} name a path that is not a repository path: ${bad.map(String).join(', ')}` }];
121
- if (tests.length === 0) return removed;
123
+ const bad = listed.filter((t) => !isEntry(t) || !validTest(entryFile(t)));
124
+ if (bad.length > 0) return [...removed, { file: stateRel, line: 0, message: `frozen tests of ${slice} name a path that is not a repository path: ${bad.map((t) => (isEntry(t) ? entryLabel(t) : JSON.stringify(t))).join(', ')}` }];
125
+ if (listed.length === 0) return removed;
122
126
 
123
- // An amendment of the slice file after the red commit lifts the freeze (REQ-3.3). Only the slice
124
- // branch's own commits count: --first-parent --no-merges leaves out a change to the slice file made on
125
- // the default branch and merged into the slice branch.
126
- const sliceFiles = sliceFilesAt(root, tip, posixRel(root, paths.phases), addr);
127
- if (sliceFiles.length > 0) {
128
- const amended = git(root, ['--literal-pathspecs', 'log', '--first-parent', '--no-merges', '--format=%H', `${red}..${tip}`, '--', ...sliceFiles]);
129
- if (amended !== '') return removed;
127
+ // The slice file at the red commit: its evaluation set reads a path entry, the form of a state file
128
+ // written before P8/S-60, as every evaluation test of that file by name (D-102). A later change to
129
+ // the slice file does not change what is frozen; with no slice file at red that parses, a path
130
+ // entry is the whole file.
131
+ const phasesRel = posixRel(root, paths.phases);
132
+ const sliceFiles = sliceFilesAt(root, tip, phasesRel, addr);
133
+ const redSliceFiles = sliceFilesAt(root, red, phasesRel, addr);
134
+ let rows = [];
135
+ if (redSliceFiles.length === 1) {
136
+ try {
137
+ rows = evaluationRows(parseSliceFile(showAt(root, red, redSliceFiles[0]) ?? '', redSliceFiles[0]));
138
+ } catch (e) {
139
+ if (!(e instanceof SliceFileError)) throw e;
140
+ }
130
141
  }
142
+ const entries = frozenEntries(listed, rows);
143
+
144
+ // A test `build amend` unfroze after the red commit is not judged (REQ-3.15): the tip's state file
145
+ // lists it in `unfrozen`, and the slice file was amended after red. An amendment of the slice file
146
+ // alone unfreezes nothing (D-102). Only the slice branch's own commits count: --first-parent
147
+ // --no-merges leaves out a change to the slice file made on the default branch and merged in.
148
+ const amended = sliceFiles.length > 0
149
+ && git(root, ['--literal-pathspecs', 'log', '--first-parent', '--no-merges', '--format=%H', `${red}..${tip}`, '--', ...sliceFiles]) !== '';
150
+ const tipState = text === null ? null : parse(text);
151
+ const unfrozen = amended && Array.isArray(tipState?.unfrozen) ? tipState.unfrozen.filter(isEntry) : [];
152
+ const judged = entries.filter((e) => !isUnfrozen(e, unfrozen));
153
+ if (judged.length === 0) return removed;
131
154
 
132
- const changed = new Set(lines(git(root, ['--literal-pathspecs', 'diff', '--name-only', '--no-renames', red, tip, '--', ...tests])));
133
- return [...removed, ...tests.filter((t) => changed.has(t)).map((t) => ({ file: t, line: 0, message: `frozen test changed after red: ${t}` }))];
155
+ const files = [...new Set(judged.map((e) => e.file))];
156
+ const changed = new Set(lines(git(root, ['--literal-pathspecs', 'diff', '--name-only', '--no-renames', red, tip, '--', ...files])));
157
+ const findings = [];
158
+ for (const e of judged) {
159
+ if (!changed.has(e.file)) continue;
160
+ if (e.name === null) {
161
+ findings.push({ file: e.file, line: 0, message: `frozen test changed after red: ${e.file}` });
162
+ continue;
163
+ }
164
+ // A test frozen by name: its text at the tip against its text at red; another test of the file,
165
+ // or any other line of it, is not compared. A file that cannot be read by name is a change.
166
+ const before = bodyOf(showAt(root, red, e.file), e.name);
167
+ const after = bodyOf(showAt(root, tip, e.file), e.name);
168
+ if (after === null || after === undefined || before === undefined || after !== before) {
169
+ findings.push({ file: e.file, line: 0, message: `frozen test changed after red: ${entryLabel(e)}` });
170
+ }
171
+ }
172
+ return [...removed, ...findings];
173
+ }
174
+
175
+ // The text of the test named `name` in `text`: null when the file or the test is missing; undefined
176
+ // when the file cannot be read by name (unparseable, or the name given twice).
177
+ function bodyOf(text, name) {
178
+ if (text === null) return null;
179
+ try {
180
+ return findTest(text, name)?.text ?? null;
181
+ } catch (e) {
182
+ if (e instanceof TestNameError) return undefined;
183
+ throw e;
184
+ }
134
185
  }
135
186
 
136
187
  export default { id, blocking, ratchet, run };
package/src/cli/build.js CHANGED
@@ -28,7 +28,7 @@ import { INDEPENDENT_MISSING } from '../state/transitions.js';
28
28
 
29
29
  const SUBCOMMANDS = ['next', 'start', 'red', 'commit', 'render', 'config', 'amend', 'pr', 'verdict', 'decline', 'finish', 'sync', 'parallel'];
30
30
  const USAGE =
31
- 'build next | build start <id> [--descr <d>] | build parallel P<n> | build red <id> --tests <a,b> [--worktree <p>] | build commit <id> --message <m> [--require-green] [--worktree <p>] (commits the staged paths; with nothing staged, every changed path) | build render <id> [--worktree <p>] | build config <id> [--worktree <p>] | build amend <id> [--test <path>] --reason <r> [--worktree <p>] (no --test: the slice file alone, once every test it names is unfrozen) | build pr <id> [--notes <file>] [--worktree <p>] | build verdict <id> <file> [--independent] [--worktree <p>] | build decline <id> <H-n> [--worktree <p>] | build finish <id> [--wait <s>, default 90] [--worktree <p>] | build sync <id> [--worktree <p>]';
31
+ 'build next | build start <id> [--descr <d>] | build parallel P<n> | build red <id> --tests <a,b> [--worktree <p>] | build commit <id> --message <m> [--require-green] [--worktree <p>] (commits the staged paths; with nothing staged, every changed path) | build render <id> [--worktree <p>] | build config <id> [--worktree <p>] | build amend <id> [--test "<file> » <name>" | --test <file>] --reason <r> [--worktree <p>] (no --test: the slice file alone, every frozen test stays frozen) | build pr <id> [--notes <file>] [--worktree <p>] | build verdict <id> <file> [--independent] [--worktree <p>] | build decline <id> <H-n> [--worktree <p>] | build finish <id> [--wait <s>, default 90] [--worktree <p>] | build sync <id> [--worktree <p>]';
32
32
 
33
33
  const OPTIONS = {
34
34
  descr: { type: 'string' },
@@ -140,8 +140,10 @@ function configStep(root, io, positionals, values) {
140
140
  function amendStep(root, io, positionals, values) {
141
141
  if (positionals.length !== 1 || values.reason === undefined) return usage(io);
142
142
  const cfg = loadConfig(root);
143
- const { sha, test } = amend(root, cfg, positionals[0], { test: values.test, reason: values.reason, worktree: values.worktree });
144
- io.stdout(test === null ? `${sha.slice(0, 7)} amended the slice file\n` : `unfroze ${test}\n`);
143
+ const { sha, test, again } = amend(root, cfg, positionals[0], { test: values.test, reason: values.reason, worktree: values.worktree });
144
+ // A second amendment of a test already unfrozen unfreezes nothing (D-102).
145
+ if (again) io.stdout(`${sha.slice(0, 7)} amended the slice file; ${test} was already unfrozen\n`);
146
+ else io.stdout(test === null ? `${sha.slice(0, 7)} amended the slice file\n` : `unfroze ${test}\n`);
145
147
  return 0;
146
148
  }
147
149
 
@@ -172,9 +174,11 @@ function verdictStep(root, io, positionals, values) {
172
174
  const out = [`next: ${r.next}`, `blockers: ${list(r.blockers)}`, `should-haves: ${list(r.shouldHaves)}`, `rounds: ${r.roundsUsed} of ${LOOP_ROUNDS}`];
173
175
  if (r.next === 'ask' && r.roundsUsed >= LOOP_ROUNDS) out.push('fix: not available after round 2; decline or leave for the independent review');
174
176
  if (r.verdictPath) out.push(`verdict ${r.verdictPath}`);
177
+ // D-101: the command of the next independent round, when one is left after a blocker.
178
+ if (r.reviewStart) out.push(`review: ${r.reviewStart}`);
175
179
  io.stdout(out.map((l) => `${l}\n`).join(''));
176
180
  if (r.next === 'stuck') {
177
- io.stderr(`slicekit: stopped: ${r.blockers.join(', ')} survive round ${r.round}; the pull request stays draft\n`);
181
+ io.stderr(`slicekit: stopped: ${r.blockers.join(', ')} survive round ${r.round}; the pull request stays draft\n${r.stop ? `${r.stop}\n` : ''}`);
178
182
  return 1;
179
183
  }
180
184
  return 0;
@@ -5,6 +5,7 @@ import path from 'node:path';
5
5
  import { GitError, currentBranch } from '../git.js';
6
6
  import { sliceFromBranch } from '../ids.js';
7
7
  import { readSlice } from '../state/index.js';
8
+ import { entryFile, isEntry } from '../testnames.js';
8
9
 
9
10
  export const toPosix = (p) => p.split(path.sep).join('/');
10
11
 
@@ -115,26 +116,40 @@ export function activeSlice(root, cfg) {
115
116
  // The slice states in which its frozen tests are guarded (REQ-3.3).
116
117
  export const GUARDED_STATES = new Set(['tests-red', 'building']);
117
118
 
118
- const stringList = (v) => Array.isArray(v) && v.every((s) => typeof s === 'string');
119
+ // A state file's `frozenTests` and `unfrozen`: each entry a path (a whole file, the form written before
120
+ // P8/S-60) or { file, name } (a test frozen by its name, D-102). Throws on any other shape, so a guard
121
+ // reading them fails closed.
122
+ export function checkFrozenLists(active) {
123
+ for (const field of ['frozenTests', 'unfrozen']) {
124
+ const v = active.state[field];
125
+ if (!Array.isArray(v) || !v.every(isEntry)) throw new Error(`${active.id} state: ${field} must be an array of strings (paths) or { file, name } entries`);
126
+ }
127
+ }
119
128
 
120
- // The tests frozen for root's active slice: {id, files: [POSIX path relative to root's real path]},
121
- // with `unfrozen` ones left out; null when tests are not frozen, no slice is active, or the slice is
122
- // not in a guarded state. Throws when the state file cannot be read or its lists are malformed, so a
123
- // guard calling it fails closed.
129
+ // The files that hold a test frozen for root's active slice: {id, files: [POSIX path relative to root's
130
+ // real path]}. A file is left out once `unfrozen` lists it whole, or lists every test frozen in it by
131
+ // name; a path entry is the whole file. Null when tests are not frozen, no slice is active, or the slice
132
+ // is not in a guarded state. Throws when the state file cannot be read or its lists are malformed, so
133
+ // a guard calling it fails closed.
124
134
  export function frozenTests(root, cfg) {
125
135
  if (!cfg.freezeTests) return null;
126
136
  const active = activeSlice(root, cfg);
127
137
  if (!active) return null;
128
138
  if (active.error) throw new Error(active.error);
129
- for (const field of ['frozenTests', 'unfrozen']) {
130
- if (!stringList(active.state[field])) throw new Error(`${active.id} state: ${field} must be an array of strings`);
131
- }
139
+ checkFrozenLists(active);
132
140
  if (!GUARDED_STATES.has(active.state.state)) return null;
133
141
  const canon = real(path.resolve(root));
134
142
  const rel = (f) => toPosix(path.relative(canon, real(path.resolve(canon, fromGitBash(f.replace(/\\/g, '/'))))));
135
143
  const key = (p) => (process.platform === 'win32' ? p.toLowerCase() : p);
136
- const unfrozen = new Set(active.state.unfrozen.map((f) => key(rel(f))));
137
- const files = active.state.frozenTests.map(rel).filter((f) => !unfrozen.has(key(f)));
144
+ const norm = (e) => (typeof e === 'string' ? { file: key(rel(e)), name: null } : { file: key(rel(e.file)), name: e.name });
145
+ const unfrozen = active.state.unfrozen.map(norm);
146
+ const lifted = (e) => unfrozen.some((u) => u.file === e.file && (u.name === null || (e.name !== null && u.name === e.name)));
147
+ const files = [];
148
+ for (const e of active.state.frozenTests) {
149
+ if (lifted(norm(e))) continue;
150
+ const f = rel(entryFile(e));
151
+ if (!files.some((g) => key(g) === key(f))) files.push(f);
152
+ }
138
153
  return { id: active.id, files };
139
154
  }
140
155
 
@@ -10,9 +10,13 @@
10
10
  // — always; (4) a path that matches a pattern of the root's `agents.denyPaths` (REQ-3.13) — always;
11
11
  // then, only while
12
12
  // the file's own root has an active slice (a `slice/*` branch with a state file) in `tests-red` or
13
- // `building`: (1) a frozen test of that slice, unless `unfrozen` lists it; (2) a file under the docs root
14
- // that does not exist yet (only a create can name a missing file), except the runbook and anything in
15
- // the slice's own phase directory.
13
+ // `building`: (1) a change to a frozen test of that slice, unless `unfrozen` lists it: a test frozen by
14
+ // name (D-102) is denied when the call changes its text against the red commit, removes it or renames
15
+ // it, and another test or line of the same file may change; a file frozen whole (a path entry of a
16
+ // state file written before P8/S-60 whose evaluation set names no test in it) is denied for any
17
+ // change; (2) a file under the docs root that does not exist yet (only a create can name a missing
18
+ // file), except the runbook, anything in the slice's own phase directory, and a path the slice file's
19
+ // Expected changes names (D-102).
16
20
  //
17
21
  // The file's own root is the nearest directory above it holding `.slicekit/config.json`, else its git
18
22
  // top level, else the session's root: a session in the main checkout editing a nested worktree is
@@ -29,9 +33,10 @@ import { CONFIG_PATH, loadConfig } from '../config.js';
29
33
  import { GitError, git } from '../git.js';
30
34
  import { parseSliceAddr } from '../ids.js';
31
35
  import { kitPaths } from '../paths.js';
32
- import { phaseOfDir } from '../slicefile.js';
36
+ import { findSliceFiles, parseSliceFile, phaseOfDir } from '../slicefile.js';
37
+ import { TestNameError, entryFile, evaluationRows, findTest, frozenEntries, isUnfrozen } from '../testnames.js';
33
38
  import { allow, deny } from './io.js';
34
- import { activeSlice, denyPaths, existingAncestor, fromGitBash, leaves, matchesDeny, namesUnder, real, toPosix } from './paths.js';
39
+ import { activeSlice, checkFrozenLists, denyPaths, existingAncestor, fromGitBash, leaves, matchesDeny, namesUnder, real, toPosix } from './paths.js';
35
40
 
36
41
  const WIN = process.platform === 'win32';
37
42
  const GUARDED_STATES = new Set(['tests-red', 'building']);
@@ -115,7 +120,6 @@ function ownRoot(abs) {
115
120
  return top ? { root: top, config: false } : null;
116
121
  }
117
122
 
118
- const stringList = (v) => Array.isArray(v) && v.every((s) => typeof s === 'string');
119
123
 
120
124
  // Whether rel lies inside the slice's own phase directory, `<docs>/phases/P<n>[-name]/`.
121
125
  function inOwnPhase(rel, phasesRel, sliceId) {
@@ -161,20 +165,14 @@ function judge(filePath, input, hookRoot, hookCfg) {
161
165
 
162
166
  const active = activeSlice(root, cfg);
163
167
  if (active?.error) throw new Error(active.error);
164
- if (active) {
165
- for (const field of ['frozenTests', 'unfrozen']) {
166
- if (!stringList(active.state[field])) throw new Error(`${active.id} state: ${field} must be an array of strings`);
167
- }
168
- }
168
+ if (active) checkFrozenLists(active);
169
169
  if (!active || !GUARDED_STATES.has(active.state.state)) return allow();
170
170
  const { id, state } = active;
171
+ const slice = sliceOf(root, cfg, id);
171
172
 
172
173
  // (1)
173
- if (cfg.freezeTests) {
174
- const listed = (list) => list.some((f) => same(rel, normalise(f, root) ?? ''));
175
- if (listed(state.frozenTests) && !listed(state.unfrozen)) {
176
- return deny(`frozen for ${id}; amend the slice file to change the evaluation set`);
177
- }
174
+ if (cfg.freezeTests && changesFrozen(root, rel, abs, state, slice, input)) {
175
+ return deny(`frozen for ${id}; amend the slice file to change the evaluation set`);
178
176
  }
179
177
 
180
178
  // (2)
@@ -182,12 +180,145 @@ function judge(filePath, input, hookRoot, hookCfg) {
182
180
  const docs = toPosix(path.relative(root, k.docs));
183
181
  if (under(rel, docs) && !same(rel, docs) && !fs.existsSync(abs)
184
182
  && !same(rel, toPosix(path.relative(root, k.runbook)))
185
- && !inOwnPhase(rel, toPosix(path.relative(root, k.phases)), id)) {
183
+ && !inOwnPhase(rel, toPosix(path.relative(root, k.phases)), id)
184
+ && !namedInExpected(rel, sliceAtHead(root, slice))) {
186
185
  return deny("no slice starts a document; a document changes only when this slice's code made it wrong");
187
186
  }
188
187
  return allow();
189
188
  }
190
189
 
190
+ // The active slice's parsed slice file under root, or null when none parses with that id.
191
+ function sliceOf(root, cfg, id) {
192
+ for (const f of findSliceFiles(root, cfg)) {
193
+ try {
194
+ const s = parseSliceFile(fs.readFileSync(f.path, 'utf8'), f.path);
195
+ if (s.id === id) return s;
196
+ } catch {
197
+ // A slice file that does not parse names nothing.
198
+ }
199
+ }
200
+ return null;
201
+ }
202
+
203
+ // The slice file as committed at HEAD (D-102). The guard allows an Edit of the slice file, so the
204
+ // new-document exception reads Expected changes from git: only `build amend` commits the slice file.
205
+ // Null when the file is not at HEAD or does not parse (names nothing). A repository with no commit
206
+ // yet has no HEAD to read; its slice file is the working tree's.
207
+ function sliceAtHead(root, slice) {
208
+ if (!slice?.path) return null;
209
+ const rel = relInside(root, real(slice.path));
210
+ if (rel === null) return null;
211
+ let text;
212
+ try {
213
+ text = git(root, ['show', `HEAD:./${rel}`]);
214
+ } catch (e) {
215
+ if (!(e instanceof GitError)) throw e;
216
+ try {
217
+ git(root, ['rev-parse', '--verify', '--quiet', 'HEAD']);
218
+ return null;
219
+ } catch (e2) {
220
+ if (e2 instanceof GitError) return slice;
221
+ throw e2;
222
+ }
223
+ }
224
+ try {
225
+ return parseSliceFile(text, slice.path);
226
+ } catch {
227
+ return null;
228
+ }
229
+ }
230
+
231
+ // The slice file's Expected changes name `rel` (D-102): a new document the slice was planned to write.
232
+ const namedInExpected = (rel, slice) =>
233
+ (slice?.expectedChanges ?? []).some((p) => same(rel, toPosix(path.posix.normalize(p.replace(/\\/g, '/'))).replace(/^\.\//, '')));
234
+
235
+ // The file's text after the tool call: Write's content, or Edit's and MultiEdit's replacements applied
236
+ // to the text on disk. Null when the call cannot be applied, so it cannot be judged (fails closed).
237
+ function textAfter(abs, input) {
238
+ const tool = input?.tool_name;
239
+ const ti = input?.tool_input ?? {};
240
+ if (tool === 'Write') return typeof ti.content === 'string' ? ti.content : null;
241
+ const edits = tool === 'Edit' ? [ti] : tool === 'MultiEdit' && Array.isArray(ti.edits) ? ti.edits : null;
242
+ if (!edits || !fs.existsSync(abs)) return null;
243
+ let text = fs.readFileSync(abs, 'utf8');
244
+ for (const e of edits) {
245
+ if (typeof e?.old_string !== 'string' || typeof e?.new_string !== 'string' || e.old_string === '') return null;
246
+ let from = e.old_string;
247
+ if (!text.includes(from)) {
248
+ // The tool matches across line endings; so does the guard.
249
+ text = text.replace(/\r\n/g, '\n');
250
+ from = from.replace(/\r\n/g, '\n');
251
+ if (!text.includes(from)) return null;
252
+ }
253
+ const to = e.new_string.replace(/\r\n/g, text.includes('\r\n') ? '\r\n' : '\n');
254
+ text = e.replace_all === true ? text.split(from).join(to) : text.replace(from, () => to);
255
+ }
256
+ return text;
257
+ }
258
+
259
+ // The text of the test named `name`: null when missing; undefined when the file cannot be read by name.
260
+ function bodyOf(text, name) {
261
+ if (text === null) return null;
262
+ try {
263
+ return findTest(text, name)?.text ?? null;
264
+ } catch (e) {
265
+ if (e instanceof TestNameError) return undefined;
266
+ throw e;
267
+ }
268
+ }
269
+
270
+ // The slice file as it was at the red commit, read from git (D-102): a path entry of a state file
271
+ // written before P8/S-60 is read with that evaluation set, never the working tree's, which this guard
272
+ // does not protect. Null when there is no red commit, no such file at it, or it does not parse: each
273
+ // path entry is then the whole file, frozen for any change (fails closed).
274
+ function sliceAtRed(root, state, slice) {
275
+ if (!slice?.path || typeof state.redCommit !== 'string' || state.redCommit === '') return null;
276
+ const rel = relInside(root, real(slice.path));
277
+ if (rel === null) return null;
278
+ let text;
279
+ try {
280
+ text = git(root, ['show', `${state.redCommit}:./${rel}`]);
281
+ } catch (e) {
282
+ if (e instanceof GitError) return null;
283
+ throw e;
284
+ }
285
+ try {
286
+ return parseSliceFile(text, slice.path);
287
+ } catch {
288
+ return null;
289
+ }
290
+ }
291
+
292
+ // Whether the call changes, removes or renames a test frozen in `rel` (REQ-3.3, D-102). A file frozen
293
+ // whole (a path entry the evaluation set names no test in) is denied for any change; a test frozen by
294
+ // name, only when its text after the call differs from its text at the red commit. Another test of
295
+ // the file, or any other line, may change.
296
+ function changesFrozen(root, rel, abs, state, slice, input) {
297
+ const at = (f) => normalise(f, root) ?? '';
298
+ const mine = state.frozenTests.filter((e) => same(rel, at(entryFile(e))));
299
+ if (mine.length === 0) return false;
300
+ const local = (e) => (typeof e === 'string' ? rel : { file: rel, name: e.name });
301
+ const unfrozen = state.unfrozen.filter((e) => same(rel, at(entryFile(e)))).map(local);
302
+ const rows = mine.some((e) => typeof e === 'string') ? evaluationRows(sliceAtRed(root, state, slice)) : [];
303
+ const entries = frozenEntries(mine.map(local), rows, same).filter((e) => !isUnfrozen(e, unfrozen, same));
304
+ if (entries.length === 0) return false;
305
+ if (entries.some((e) => e.name === null)) return true;
306
+ const after = textAfter(abs, input);
307
+ if (after === null) return true;
308
+ let atRed = null;
309
+ try {
310
+ atRed = git(root, ['show', `${state.redCommit}:./${rel}`]);
311
+ } catch (e) {
312
+ if (!(e instanceof GitError)) throw e;
313
+ }
314
+ if (typeof state.redCommit !== 'string' || atRed === null) return true;
315
+ return entries.some((e) => {
316
+ const before = bodyOf(atRed, e.name);
317
+ const now = bodyOf(after, e.name);
318
+ return before === undefined || before === null || now === undefined || now === null || before !== now;
319
+ });
320
+ }
321
+
191
322
  export function handle(input, { root, cfg }) {
192
323
  const given = PATH_KEYS.filter((k) => input?.tool_input?.[k] !== undefined);
193
324
  if (!given.length) throw new Error('tool_input.file_path is missing');