@warren-dean/code-kit 0.26.2 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,8 @@ import { loadConfig, mergeDelegation } from './config.mjs';
8
8
  import { buildStatus, readStories, DESIGN, LEAD } from './plan.mjs';
9
9
  import { pendingSetup } from './adapters/index.mjs';
10
10
  import { CONFIG_FILE, SETUP_VERSION } from './config.mjs';
11
- import { readQueue, waiting } from './queue.mjs';
11
+ import { mergingNow, nextToMerge, readQueue, waiting } from './queue.mjs';
12
+ import { handedOver, readRegister, toolOf } from './designs.mjs';
12
13
  import { decidedBy, laneOf, openRequests } from './rules.mjs';
13
14
  import { instructionsState } from './instructions.mjs';
14
15
  import { SECURITY_AGENT_FILE } from './security.mjs';
@@ -273,7 +274,13 @@ export function nextStep(root, base) {
273
274
  );
274
275
 
275
276
  // A branch already in the merge queue has passed its review: it isn't reviewed again.
276
- const queued = waiting(readQueue(root)).map((e) => e.branch);
277
+ const entries = readQueue(root);
278
+ const inQueue = waiting(entries);
279
+ // MQ-7: what can merge next; a branch queued with partners waits until they're queued too.
280
+ const { head: mergeHead, held: heldGroups } = nextToMerge(entries);
281
+ const queued = inQueue.map((e) => e.branch);
282
+ // MQ-1: a queue merge running now (its verify takes minutes) isn't asked for again.
283
+ const merging = mergingNow(inQueue[0]) ? inQueue[0].branch : null;
277
284
  const ids = (state) =>
278
285
  status.stories
279
286
  .filter((s) => s.state === state && !(state === 'review' && queued.includes(s.branch)))
@@ -371,11 +378,19 @@ export function nextStep(root, base) {
371
378
  attention.push(
372
379
  `${queued.join(', ')} passed review and ${queued.length === 1 ? 'waits' : 'wait'} for the person to merge (code-kit queue merge --person, or Merge in the code-kit band).`,
373
380
  );
374
- if (queued.length && leadMerges)
381
+ if (merging)
382
+ attention.push(
383
+ `${merging} is being merged now (queue merge is running); it says when it's done.`,
384
+ );
385
+ for (const h of heldGroups)
386
+ attention.push(
387
+ `${h.branch} passed review and merges together with ${h.missing.join(', ')}: it waits until ${h.missing.length === 1 ? 'that is' : 'they are'} reviewed and queued.`,
388
+ );
389
+ if (mergeHead && leadMerges && !merging)
375
390
  return result(
376
391
  'merge',
377
- `${queued[0]} passed review and is next in the merge queue${queued.length > 1 ? ` (then ${queued.slice(1).join(', ')})` : ''}.`,
378
- { args: queued[0] },
392
+ `${mergeHead.branch} passed review and is next in the merge queue${queued.length > 1 ? ` (then ${queued.filter((b) => b !== mergeHead.branch).join(', ')})` : ''}.`,
393
+ { args: mergeHead.branch },
379
394
  );
380
395
  // SCHED-1, SCHED-2: one story for each free lane, across every session; the open slice's first.
381
396
  const busy = new Set([
@@ -400,6 +415,12 @@ export function nextStep(root, base) {
400
415
  attention.push(
401
416
  `${sched.waiting.join(', ')} ${sched.waiting.length === 1 ? 'waits' : 'wait'} for ${sched.waiting.length === 1 ? 'its lane' : 'their lanes'}: a lane runs one story at a time.`,
402
417
  );
418
+ // HAND-5: approved designs still only in a design tool, which no lane can read, are handed over once.
419
+ const toolOnly = readRegister(root, config).entries.filter((e) => !handedOver(e));
420
+ if (toolOnly.length)
421
+ attention.push(
422
+ `${toolOnly.length} approved screen${toolOnly.length === 1 ? ' is' : 's are'} only in ${[...new Set(toolOnly.map(toolOf))].join(', ')}, not as files a lane can build from: hand ${toolOnly.length === 1 ? 'it' : 'them'} over with /code-kit:design --hand-over.`,
423
+ );
403
424
  const then = [];
404
425
  // A sent-back story goes back to its lane with the review's findings, before new work starts.
405
426
  const toDispatch = [...fixes, ...ready];
@@ -7,6 +7,7 @@
7
7
  import { execFileSync } from 'node:child_process';
8
8
  import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
9
9
  import { isAbsolute, join } from 'node:path';
10
+ import { readEvents } from './events.mjs';
10
11
  import { laneClaims } from './laneclaims.mjs';
11
12
  import { waitingStories } from './questions.mjs';
12
13
  import { sentBack } from './reviews.mjs';
@@ -16,6 +17,8 @@ export const REQUIREMENT = /\b(?!ST-)([A-Z][A-Z0-9]*-\d+)\b/g;
16
17
  const STORY_HEADING = /^###\s+(ST-\d+)\b\s*(.*)$/;
17
18
  const REQUIREMENT_HEADING = /^###\s+((?!ST-)[A-Z][A-Z0-9]*-\d+)\b\s*(.*)$/;
18
19
  export const STATES = ['todo', 'in progress', 'review', 'done'];
20
+ /** A story taken out of the plan (folded into another, or no longer wanted): never built, never waited on. */
21
+ export const DROPPED = 'dropped';
19
22
  export const LEAD = 'lead';
20
23
  /** ONB-2: the pseudo-lane for design stories, which the lead designs with the person before any screen is built. */
21
24
  export const DESIGN = 'design';
@@ -94,7 +97,7 @@ export function readStories(root, planPath) {
94
97
  // REG-1: what a fix story fixes, or null.
95
98
  fixes: field(body, 'Fixes') || null,
96
99
  dependsOn: [...field(body, 'Depends on').matchAll(/\bST-\d+\b/g)].map((r) => r[0]),
97
- status: STATES.includes(status) ? status : 'todo',
100
+ status: STATES.includes(status) || status === DROPPED ? status : 'todo',
98
101
  milestone,
99
102
  // SCHED-2: the slice it belongs to, a feature built across lanes, or null.
100
103
  slice: field(body, 'Slice') || null,
@@ -252,11 +255,18 @@ export function storyStates(root, stories, base) {
252
255
  const trees = worktrees(root);
253
256
  const backs = sentBack(root);
254
257
  const refs = branchRefs(root, base);
255
- const live = new Set(
256
- laneClaims(root)
257
- .filter((c) => !c.stale)
258
- .map((c) => `${c.lane}|${c.story ?? ''}`),
259
- );
258
+ const claims = laneClaims(root).filter((c) => !c.stale);
259
+ const live = new Set(claims.map((c) => `${c.lane}|${c.story ?? ''}`));
260
+ // A lane agent dispatched on the story and not handed back since: its commits are work in progress,
261
+ // even where the branch moved only by taking in the base (a re-dispatch after a send-back).
262
+ const building = (story) => {
263
+ const claim = claims.find((c) => c.lane === story.lane && c.story === story.id);
264
+ if (!claim) return false;
265
+ const since = Date.parse(claim.since);
266
+ return !readEvents(root, story.id).some(
267
+ (e) => e.kind === 'handback' && Date.parse(e.at) >= since,
268
+ );
269
+ };
260
270
  // What the base already holds: the stories its commits name, and the story branches merged into it.
261
271
  const onBase = { stories: new Set(), branches: new Set() };
262
272
  for (const m of (git(root, 'log', base, '--format=%B%x1e') ?? '').matchAll(
@@ -280,10 +290,10 @@ export function storyStates(root, stories, base) {
280
290
  : (refs[ref].ahead ?? Number(git(root, 'rev-list', '--count', `${base}..${ref}`) ?? 0));
281
291
  let state = story.status;
282
292
  let stopped = false;
283
- if (ref && story.status !== 'done') {
293
+ if (ref && !['done', DROPPED].includes(story.status)) {
284
294
  const head = backs[branch] ? refs[ref].sha : null;
285
295
  if (head && head === backs[branch].sha) state = 'sent back';
286
- else if (ahead > 0) state = 'review';
296
+ else if (ahead > 0) state = building(story) ? 'in progress' : 'review';
287
297
  else if (story.status === 'review') state = 'done';
288
298
  else if (builtBy(story, branch)) state = 'in progress';
289
299
  else {
@@ -310,11 +320,12 @@ export function storyStates(root, stories, base) {
310
320
  waitingOn: [],
311
321
  };
312
322
  });
313
- const done = new Set(states.filter((s) => s.state === 'done').map((s) => s.id));
323
+ // A dropped story is as good as done for the stories that depend on it: it won't be built.
324
+ const done = new Set(states.filter((s) => ['done', DROPPED].includes(s.state)).map((s) => s.id));
314
325
  // ASK-3: a story whose question for the person is open waits on them, whatever its branch holds.
315
326
  const asked = waitingStories(root);
316
327
  for (const s of states) {
317
- if (s.state === 'done') continue;
328
+ if (['done', DROPPED].includes(s.state)) continue;
318
329
  s.waitingOn = s.dependsOn.filter((d) => !done.has(d));
319
330
  s.waitingFor = asked.has(s.id)
320
331
  ? { id: asked.get(s.id).id, question: asked.get(s.id).question }
@@ -342,7 +353,7 @@ export function traceProblems(requirements, stories, lanes) {
342
353
  if (!s.lane) problems.push(`${s.id} has no **Lane:**`);
343
354
  else if (s.lane !== LEAD && s.lane !== DESIGN && !lanes.includes(s.lane))
344
355
  problems.push(`${s.id} names an unknown lane "${s.lane}"`);
345
- if (!s.requirements.length && !s.noRequirements)
356
+ if (!s.requirements.length && !s.noRequirements && s.status !== DROPPED)
346
357
  problems.push(`${s.id} cites no requirements (write "none" if it delivers none)`);
347
358
  for (const r of s.requirements)
348
359
  if (!ids.has(r)) problems.push(`${s.id} cites ${r}, which no spec defines`);
@@ -350,7 +361,9 @@ export function traceProblems(requirements, stories, lanes) {
350
361
  if (!stories.some((o) => o.id === d))
351
362
  problems.push(`${s.id} depends on ${d}, which isn't in the plan`);
352
363
  }
353
- const covered = new Set(stories.flatMap((s) => s.requirements));
364
+ const covered = new Set(
365
+ stories.filter((s) => s.status !== DROPPED).flatMap((s) => s.requirements),
366
+ );
354
367
  for (const r of requirements)
355
368
  if (!r.removed && !covered.has(r.id)) problems.push(`${r.id} is in no story (${r.file})`);
356
369
  return problems;
@@ -364,7 +377,7 @@ export function buildStatus(root, config, base, files) {
364
377
  const tested = testedRequirements(root, files, specs);
365
378
  const problems = traceProblems(requirements, stories, Object.keys(config.lanes));
366
379
  const byRequirement = requirements.map((r) => {
367
- const covering = stories.filter((s) => s.requirements.includes(r.id));
380
+ const covering = stories.filter((s) => s.state !== DROPPED && s.requirements.includes(r.id));
368
381
  let state = 'no story';
369
382
  if (r.removed) state = 'removed';
370
383
  else if (covering.length && covering.every((s) => s.state === 'done')) state = 'done';
@@ -90,6 +90,91 @@ export function settle(root, branch, state, reason = null, now = Date.now()) {
90
90
  writeQueue(root, [...entries.filter((e) => !settled.includes(e)), ...settled]);
91
91
  }
92
92
 
93
+ /**
94
+ * MQ-1: the head being merged by a running `queue merge` (process `pid`), in its place; `null` puts it
95
+ * back to waiting, in its place too.
96
+ */
97
+ export function markMerging(root, branch, pid, now = Date.now()) {
98
+ writeQueue(
99
+ root,
100
+ readQueue(root).map((e) => {
101
+ if (e.branch !== branch || !['waiting', 'merging'].includes(e.state)) return e;
102
+ const { pid: _pid, ...rest } = e;
103
+ return pid
104
+ ? { ...rest, state: 'merging', pid, at: new Date(now).toISOString() }
105
+ : { ...rest, state: 'waiting' };
106
+ }),
107
+ );
108
+ }
109
+
110
+ /** Whether `entry` is being merged now: marked merging by a process still running. */
111
+ export function mergingNow(entry) {
112
+ if (entry?.state !== 'merging' || !entry.pid) return false;
113
+ try {
114
+ process.kill(entry.pid, 0);
115
+ return true;
116
+ } catch (e) {
117
+ return e.code === 'EPERM';
118
+ }
119
+ }
120
+
121
+ /**
122
+ * MQ-7: what the queue merges next. A branch queued `with` others merges only together with them, once
123
+ * each is queued too: verified as one tree, merged one after another. Until then it waits, and the
124
+ * queue goes on with the next. `{ head, partners, held }`: `head` null when nothing can merge yet;
125
+ * `held` lists each waiting branch with the partners it still needs queued.
126
+ */
127
+ export function nextToMerge(entries) {
128
+ const queue = waiting(entries);
129
+ const queued = new Set(queue.map((e) => e.branch));
130
+ // A partner already merged on its own is no longer waited for.
131
+ const merged = new Set(entries.filter((e) => e.state === 'merged').map((e) => e.branch));
132
+ const groupOf = (e) => {
133
+ const group = new Set([e.branch]);
134
+ for (let grew = true; grew;) {
135
+ grew = false;
136
+ for (const x of queue)
137
+ if (
138
+ !group.has(x.branch) &&
139
+ ((x.with ?? []).some((b) => group.has(b)) ||
140
+ [...group].some((b) =>
141
+ (queue.find((y) => y.branch === b)?.with ?? []).includes(x.branch),
142
+ ))
143
+ ) {
144
+ group.add(x.branch);
145
+ grew = true;
146
+ }
147
+ }
148
+ return group;
149
+ };
150
+ const held = [];
151
+ for (const e of queue) {
152
+ const group = groupOf(e);
153
+ const missing = [...group]
154
+ .flatMap((b) => queue.find((y) => y.branch === b)?.with ?? [])
155
+ .filter((b) => !queued.has(b) && !merged.has(b));
156
+ if (missing.length) {
157
+ held.push({ branch: e.branch, missing: [...new Set(missing)] });
158
+ continue;
159
+ }
160
+ const partners = queue.filter((x) => x.branch !== e.branch && group.has(x.branch));
161
+ return { head: e, partners, held };
162
+ }
163
+ return { head: null, partners: [], held };
164
+ }
165
+
166
+ /** MQ-7: a queued branch's partners, which it merges together with. */
167
+ export function setPartners(root, branch, partners) {
168
+ writeQueue(
169
+ root,
170
+ readQueue(root).map((e) =>
171
+ e.branch === branch && ['waiting', 'merging'].includes(e.state)
172
+ ? { ...e, with: [...new Set([...(e.with ?? []), ...partners])] }
173
+ : e,
174
+ ),
175
+ );
176
+ }
177
+
93
178
  /** The branch merged last, for a send-back's reason ("conflicts with main after web/st-4"). */
94
179
  export function lastMerged(entries) {
95
180
  return [...entries].reverse().find((e) => e.state === 'merged')?.branch ?? null;
@@ -109,7 +194,7 @@ export function storyMerges(cmd, branch) {
109
194
  const switches = new RegExp(
110
195
  String.raw`^${GIT}(?:switch|checkout)\s+((?:-\S+\s+)*)([^\s-]\S*)\s*$`,
111
196
  );
112
- const merges = new RegExp(String.raw`^${GIT}merge\b(.*)$`);
197
+ const merges = new RegExp(String.raw`^${GIT}merge(?![\w-])(.*)$`);
113
198
  for (const { text, code } of commandsOf(cmd)) {
114
199
  const moved = code.match(switches);
115
200
  if (moved) {
@@ -4,9 +4,9 @@
4
4
  // WHO-2), the person's otherwise and always on the lead's own. The commit hook
5
5
  // refuses a weakening commit; verify finds what a branch weakened, from git.
6
6
  import { execFileSync, spawnSync } from 'node:child_process';
7
- import { existsSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from 'node:fs';
8
- import { tmpdir } from 'node:os';
9
- import { basename, dirname, join } from 'node:path';
7
+ import { existsSync, readFileSync, rmSync } from 'node:fs';
8
+ import { join } from 'node:path';
9
+ import { freshCheckout } from './checkout.mjs';
10
10
  import { runChecks } from './checks.mjs';
11
11
  import { matchesAny } from './glob.mjs';
12
12
  import { readStories } from './plan.mjs';
@@ -39,8 +39,9 @@ const SKIPS = [
39
39
  /\bt\.Skip(?:f|Now)?\s*\(/,
40
40
  /@(?:Disabled|Ignore)\b/,
41
41
  ];
42
+ // `expect(` and its retrying and soft forms (`expect.poll(`, `expect.soft(`), each one assertion.
42
43
  const ASSERTION =
43
- /\bexpect\s*\(|\bassert\w*\s*[.(]|\bt\.(?:Error|Errorf|Fatal|Fatalf|Fail)\b|\bshould\.\w/g;
44
+ /\bexpect(?:\.(?:poll|soft))?\s*\(|\bassert\w*\s*[.(]|\bt\.(?:Error|Errorf|Fatal|Fatalf|Fail)\b|\bshould\.\w/g;
44
45
 
45
46
  const skipLines = (text) =>
46
47
  String(text ?? '')
@@ -178,10 +179,22 @@ export function branchWeakenings(root, from, config) {
178
179
 
179
180
  /**
180
181
  * REG-2 for a commit about to be made: `files` as the commit hook lists them, HEAD against the
181
- * working tree.
182
+ * working tree. `gone`: files the commit's own command takes away first (`git rm`, `git mv`), which
183
+ * are still on disk as the hook runs. `base`: the branch the work merges into; a test the branch
184
+ * added itself since it left it isn't the base's to lose, so moving or deleting it weakens nothing.
182
185
  */
183
- export function commitWeakenings(root, files, config) {
186
+ export function commitWeakenings(root, files, config, gone = new Set(), base = null) {
187
+ let from = null;
188
+ try {
189
+ from = base ? git(root, 'merge-base', base, 'HEAD').trim() : null;
190
+ } catch {
191
+ // no common history with the base: every test counts
192
+ }
193
+ // What this commit adds stays, to pair a moved test with where it went.
194
+ if (from)
195
+ files = files.filter((f) => showAt(root, 'HEAD', f) === null || showAt(root, from, f) !== null);
184
196
  const read = (rel) => {
197
+ if (gone.has(rel)) return null;
185
198
  try {
186
199
  return readFileSync(join(root, rel), 'utf8');
187
200
  } catch {
@@ -190,7 +203,7 @@ export function commitWeakenings(root, files, config) {
190
203
  };
191
204
  const changes = files.map((file) => {
192
205
  const was = showAt(root, 'HEAD', file) !== null;
193
- const is = existsSync(join(root, file));
206
+ const is = !gone.has(file) && existsSync(join(root, file));
194
207
  return { status: !was ? 'A' : is ? 'M' : 'D', file };
195
208
  });
196
209
  return weakenedTests(changes, (rel) => showAt(root, 'HEAD', rel), read, config);
@@ -219,38 +232,24 @@ const UNREACHABLE =
219
232
  const ASSERTED =
220
233
  /AssertionError|AssertionFailedError|Expected:|Received:|expected .+ to |toBe|toEqual|assert\w* failed|^\s*--- FAIL|Error: expect\(/m;
221
234
 
235
+ /** The names a failure says can't be reached: quoted ones on its unreachable lines. */
236
+ function missingNames(output) {
237
+ const names = new Set();
238
+ for (const line of output.split('\n').filter((l) => UNREACHABLE.test(l)))
239
+ for (const m of line.matchAll(
240
+ /['"`‘’]([A-Za-z_$][\w$]*)['"`‘’]|ReferenceError: ([A-Za-z_$][\w$]*)|undefined: (\w+)|import name '?(\w+)/g,
241
+ ))
242
+ names.add(m[1] ?? m[2] ?? m[3] ?? m[4]);
243
+ return names;
244
+ }
245
+
222
246
  /** Whether a failure's output only shows the tests couldn't reach what the fix adds. */
223
247
  export const onlyUnreachable = (output) =>
224
248
  UNREACHABLE.test(output) && !ASSERTED.test(output.replace(UNREACHABLE, ''));
225
249
 
226
- // The folders an install puts beside the code, which a fresh checkout lacks.
227
- const INSTALLS = new Set(['node_modules', '.venv', 'venv']);
228
-
229
- /** Links the checkout's installs (node_modules and the like, wherever git ignores them) into `dir`. */
230
- function linkInstalls(root, dir) {
231
- let ignored = [];
232
- try {
233
- ignored = git(root, 'ls-files', '--others', '--ignored', '--exclude-standard', '--directory')
234
- .split('\n')
235
- .map((l) => l.replace(/\/$/, ''))
236
- .filter((l) => l && INSTALLS.has(basename(l)));
237
- } catch {
238
- return;
239
- }
240
- for (const rel of ignored) {
241
- const to = join(dir, rel);
242
- if (!existsSync(dirname(to)) || existsSync(to)) continue;
243
- try {
244
- symlinkSync(join(root, rel), to, 'dir');
245
- } catch {
246
- // the check then says what it couldn't run
247
- }
248
- }
249
- }
250
-
251
250
  /**
252
- * REG-1: whether a fix's tests prove its bug. In a temporary worktree of the branch (with the
253
- * checkout's installs linked in, after `regression.prepare`), the checks covering the tests it added
251
+ * REG-1: whether a fix's tests prove its bug. In a fresh checkout of the branch (with its own copy of
252
+ * the checkout's installs, after `regression.prepare`), the checks covering the tests it added
254
253
  * or changed must pass, and fail, as the bug, once every change outside the tests goes back to `from`.
255
254
  * Problems in words; empty when the tests prove it.
256
255
  */
@@ -263,6 +262,9 @@ export function proveFix({ root, from, base, changed, config, fix }) {
263
262
  return [
264
263
  `${what}, but it adds or changes no test. Add a test that fails without the fix: it's what stops the bug coming back.`,
265
264
  ];
265
+ // A fix made wholly in the tests (a flaky test, a broken helper) has no code to take back: its tests
266
+ // are the fix. REG-2 still holds them, so it can't be made by weakening one.
267
+ if (changed.every((f) => isTestFile(f, config) || SNAPSHOT.test(f))) return [];
266
268
  const covering = config.checks.filter((c) =>
267
269
  tests.some((f) => matchesAny(f, c.files) && !matchesAny(f, c.exclude)),
268
270
  );
@@ -272,11 +274,8 @@ export function proveFix({ root, from, base, changed, config, fix }) {
272
274
  ];
273
275
  const strict = { ...config, checks: covering.map((c) => ({ ...c, ifMissing: 'fail' })) };
274
276
  const actor = { kind: 'lead', label: 'lead' };
275
- const dir = mkdtempSync(join(tmpdir(), 'code-kit-fix-'));
276
- rmSync(dir, { recursive: true });
277
+ const { dir, remove } = freshCheckout(root, 'HEAD', { prefix: 'code-kit-fix-' });
277
278
  try {
278
- git(root, 'worktree', 'add', '--quiet', '--detach', dir, 'HEAD');
279
- linkInstalls(root, dir);
280
279
  const prepare = config.regression?.prepare;
281
280
  if (prepare) {
282
281
  const res = spawnSync(prepare, { cwd: dir, shell: true, encoding: 'utf8', timeout: 900000 });
@@ -300,7 +299,22 @@ export function proveFix({ root, from, base, changed, config, fix }) {
300
299
  return [
301
300
  `${what}, but its tests (${tests.join(', ')}) also pass without the fix, so they don't prove the bug and it can come back. Write a test that fails on ${base} and passes here.`,
302
301
  ];
303
- const output = `${without.title}\n${without.output ?? ''}`;
302
+ let output = `${without.title}\n${without.output ?? ''}`;
303
+ // Tests that call what the fix adds can stop a whole run (a typecheck) before a test through the
304
+ // existing code fails on its assertion: set them aside, and run the rest without the fix.
305
+ if (onlyUnreachable(output)) {
306
+ const missing = missingNames(output);
307
+ const aside = tests.filter((f) => {
308
+ const text = showAt(root, 'HEAD', f) ?? '';
309
+ return [...missing].some((n) => new RegExp(String.raw`\b${n}\b`).test(text));
310
+ });
311
+ const rest = tests.filter((f) => !aside.includes(f));
312
+ if (aside.length && rest.length) {
313
+ for (const f of aside) rmSync(join(dir, f), { force: true });
314
+ const { failure: again } = runChecks(strict, rest, dir, actor);
315
+ if (again) output = `${again.title}\n${again.output ?? ''}`;
316
+ }
317
+ }
304
318
  if (onlyUnreachable(output)) {
305
319
  const line =
306
320
  output
@@ -313,10 +327,6 @@ export function proveFix({ root, from, base, changed, config, fix }) {
313
327
  }
314
328
  return [];
315
329
  } finally {
316
- try {
317
- git(root, 'worktree', 'remove', '--force', dir);
318
- } catch {
319
- rmSync(dir, { recursive: true, force: true });
320
- }
330
+ remove();
321
331
  }
322
332
  }
@@ -93,6 +93,18 @@ export function leadDecides(name, config, actor) {
93
93
  return (rules.protected ?? []).includes(name);
94
94
  }
95
95
 
96
+ /**
97
+ * WHO-1: whether the lead needs an approval in force to change a file protected by `name` itself. Where
98
+ * the person merges, they review the lead's change in the pull request, so it needs none. Where merges
99
+ * are delegated to the lead nobody else sees it, so what the person keeps (not delegated to the lead)
100
+ * needs the person's approval, as it would from a lane. The kit is the lead's to change either way: the
101
+ * person approved the setup, and code-kit writes most of it.
102
+ */
103
+ export const leadNeedsApproval = (name, config) =>
104
+ name !== 'kit' &&
105
+ Boolean(config?.approvals?.delegate?.merge) &&
106
+ !leadDecides(name, config, { kind: 'lead' });
107
+
96
108
  /** HELM-2: whose decision approvals `names` are: the lead's when it may grant every one, else the person's. */
97
109
  export const decidedBy = (names, config, actor) =>
98
110
  [names].flat().every((n) => leadDecides(n, config, actor)) ? 'lead' : 'person';
@@ -186,6 +198,25 @@ function noteGiven(root, entries) {
186
198
  }
187
199
  }
188
200
 
201
+ /**
202
+ * Why an approval for `name` given to `actor` lately isn't in force any more: used up by an earlier
203
+ * commit, or out of time. A sentence for a refusal, or '' when none was given lately.
204
+ */
205
+ export function approvalEnded(root, name, actor, now = Date.now()) {
206
+ const lane = actor?.kind === 'lane' ? actor.lane : null;
207
+ const last = approvalsGiven(root)
208
+ .filter((e) => e.name === name && (!e.lane || e.lane === lane))
209
+ .at(-1);
210
+ if (!last?.at) return '';
211
+ const at = (t) => new Date(t).toTimeString().slice(0, 5);
212
+ const given = Date.parse(last.at);
213
+ if (now - given > 24 * 3600_000) return '';
214
+ if (last.usedAt)
215
+ return ` The ${name} approval given at ${at(given)} was used up at ${at(last.usedAt)} by an earlier commit${last.usedBy ? ` (${last.usedBy})` : ''}, so another is needed.`;
216
+ const ends = given + approvalMinutes(name) * 60_000;
217
+ return now >= ends ? ` The ${name} approval given at ${at(given)} ran out at ${at(ends)}.` : '';
218
+ }
219
+
189
220
  /** The approvals given through code-kit (and those used up), oldest first. */
190
221
  export function approvalsGiven(root) {
191
222
  try {
@@ -353,6 +384,7 @@ export function useApproval(root, name, actor) {
353
384
  ...(file !== join(dir, name) ? { lane: actor.lane } : {}),
354
385
  reason: a.reason,
355
386
  usedAt: new Date().toISOString(),
387
+ ...(actor?.label ? { usedBy: actor.label } : {}),
356
388
  },
357
389
  ]);
358
390
  return rmSync(file, { force: true });
@@ -438,6 +470,9 @@ export function recordRequest(root, actor, names, what, why, now = Date.now(), e
438
470
  why: String(why).slice(0, 300),
439
471
  ...extra,
440
472
  };
473
+ // The file's commits already made in the second it's asked, which don't answer it.
474
+ const before = commitsFrom(root, request.what, request.at);
475
+ if (before?.length) request.before = before;
441
476
  if (openRequests(root, now).some((r) => sameRequest(r, request))) return;
442
477
  const file = requestsFile(root);
443
478
  mkdirSync(dirname(file), { recursive: true });
@@ -528,32 +563,38 @@ function installedSince(root, r) {
528
563
  });
529
564
  }
530
565
 
531
- /** Whether the file a request named has been committed, on any branch, since it was asked. */
532
- function committedSince(root, r) {
533
- const path = String(r.what);
534
- if (/\s/.test(path) || (!path.includes('/') && !path.includes('.'))) return false;
566
+ /** The commits of `path`, on any branch, in or after the second `at` falls in; null when it isn't a path. */
567
+ function commitsFrom(root, path, at) {
568
+ if (/\s/.test(path) || (!path.includes('/') && !path.includes('.'))) return null;
535
569
  try {
536
- const out = execFileSync(
570
+ return execFileSync(
537
571
  'git',
538
572
  [
539
- '-C',
540
- root,
541
- 'log',
542
- '--all',
543
- '-1',
544
- '--format=%ct',
545
- `--since=@${Math.floor(Date.parse(r.at) / 1000)}`,
546
- '--',
547
- path,
573
+ ...['-C', root, 'log', '--all', '--format=%H'],
574
+ `--since=@${Math.floor(Date.parse(at) / 1000)}`,
575
+ ...['--', path],
548
576
  ],
549
577
  { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] },
550
- );
551
- return Boolean(out.trim());
578
+ )
579
+ .split('\n')
580
+ .filter(Boolean);
552
581
  } catch {
553
- return false;
582
+ return [];
554
583
  }
555
584
  }
556
585
 
586
+ /**
587
+ * Whether the file a request named has been committed, on any branch, since it was asked. Git dates are
588
+ * whole seconds, so the commits already there in the second it was asked (the one before the refused
589
+ * commit) are the request's `before`, and don't answer it.
590
+ */
591
+ function committedSince(root, r) {
592
+ const commits = commitsFrom(root, String(r.what), r.at);
593
+ if (!commits) return false;
594
+ const before = new Set(r.before ?? []);
595
+ return commits.some((c) => !before.has(c));
596
+ }
597
+
557
598
  /**
558
599
  * CARD-6: every approval given, newest first: { at, name, lane, reason, by, files, branches, used,
559
600
  * expired }. From the approvals given through code-kit, the approvals on disk (a person's own `!` echo
@@ -766,9 +807,11 @@ export function writeProblem(actor, rel, root, config) {
766
807
  const guarded = protectedEntry(rel, config);
767
808
  if (actor.kind === 'readonly' && (guarded || !matchesAny(rel, config.anyActor)))
768
809
  return readonlyProblem(actor, rel);
769
- // The lead writes protected files without an approval: the person reviews them in the pull request,
770
- // and every committed change is in the audit log. Anyone else needs a person's approval as well.
771
- if (guarded && actor.kind !== 'lead' && !approval(root, guarded.approval, actor)) {
810
+ // The lead writes protected files without an approval where the person merges: they review them in
811
+ // the pull request, and every committed change is in the audit log. Where the lead merges, what the
812
+ // person keeps needs their approval (WHO-1). Anyone else needs an approval as well.
813
+ const leadFree = actor.kind === 'lead' && !leadNeedsApproval(guarded?.approval, config);
814
+ if (guarded && !leadFree && !approval(root, guarded.approval, actor)) {
772
815
  recordRequest(root, actor, guarded.approval, rel, guarded.why);
773
816
  const who =
774
817
  decidedBy(guarded.approval, config, actor) === 'lead'
@@ -202,12 +202,19 @@ export function teamProvider(root, team) {
202
202
  ? { ...g, fallback: r?.why ?? "The team provider can't be reached." }
203
203
  : g;
204
204
  };
205
+ // A claim taken while the provider was down lives only on GitHub; one the provider doesn't know is
206
+ // released there too, so it can't outlive its story (a merged story's claim, stuck and going stale).
207
+ const eitherRelease = (story, opts) => {
208
+ const r = either('release')(story, opts);
209
+ if (!r?.ok || r.released) return r;
210
+ const g = github.release(story, opts);
211
+ return g?.ok && g.released ? g : r;
212
+ };
205
213
  return {
206
214
  ...Object.fromEntries(
207
215
  [
208
216
  'whoami',
209
217
  'claim',
210
- 'release',
211
218
  'state',
212
219
  'intend',
213
220
  'settle',
@@ -218,6 +225,7 @@ export function teamProvider(root, team) {
218
225
  'standards',
219
226
  ].map((op) => [op, either(op)]),
220
227
  ),
228
+ release: eitherRelease,
221
229
  forget: () => (command.forget(), github.forget()),
222
230
  };
223
231
  }
@@ -790,6 +798,24 @@ function commandProvider(root, team, command) {
790
798
  }
791
799
 
792
800
  /** The team's state as last read, for the hooks and the mod between polls. */
801
+ /**
802
+ * TEAM-1: the claimed stories whose branch has merged into `base`, by the merge commits' subjects
803
+ * ("Merge web/st-12 into main", "Merge pull request #4 from owner/web/st-12"): their claims outlived their merge and end now. A commit that only
804
+ * mentions a story doesn't end its claim.
805
+ */
806
+ export function mergedClaims(root, claims, base) {
807
+ if (!claims?.length) return [];
808
+ const log = spawnSync('git', ['-C', root, 'log', base, '--merges', '--format=%s'], {
809
+ encoding: 'utf8',
810
+ maxBuffer: 64 * 1024 * 1024,
811
+ });
812
+ if (log.status !== 0) return [];
813
+ const merged = new Set(
814
+ [...log.stdout.matchAll(/[\w.-]+\/(st-\d+)(?![\w-])/gi)].map((m) => m[1].toUpperCase()),
815
+ );
816
+ return claims.map((c) => c.story).filter((story) => merged.has(String(story).toUpperCase()));
817
+ }
818
+
793
819
  export function readCache(root) {
794
820
  try {
795
821
  const s = JSON.parse(readFileSync(join(root, TEAM_STATE), 'utf8'));