@warren-dean/code-kit 0.25.0 → 0.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +24 -0
  4. package/README.md +70 -59
  5. package/bin/code-kit.mjs +113 -3
  6. package/hooks/act.mjs +96 -0
  7. package/hooks/guard-bash.mjs +27 -1
  8. package/hooks/hooks.json +42 -1
  9. package/hooks/lib/config.mjs +26 -2
  10. package/hooks/lib/events.mjs +626 -0
  11. package/hooks/lib/harness.mjs +8 -0
  12. package/hooks/lib/instructions.mjs +1 -1
  13. package/hooks/lib/next.mjs +22 -0
  14. package/hooks/lib/plan.mjs +45 -9
  15. package/hooks/lib/publish.mjs +144 -0
  16. package/hooks/lib/queue.mjs +36 -0
  17. package/hooks/lib/snapshot.mjs +33 -3
  18. package/hooks/lib/storymap.mjs +54 -17
  19. package/hooks/lib/timeline.mjs +94 -44
  20. package/hooks/lib/worktrees.mjs +19 -11
  21. package/hooks/mod/art.mjs +0 -81
  22. package/hooks/mod/board.mjs +1743 -0
  23. package/hooks/mod/characters.mjs +516 -0
  24. package/hooks/mod/loop.mjs +17 -3
  25. package/hooks/mod/mission.mjs +2 -93
  26. package/hooks/mod/panes.mjs +111 -422
  27. package/hooks/mod/register.mjs +482 -184
  28. package/hooks/mod/surface/character.mjs +79 -0
  29. package/hooks/mod/surface/clock.mjs +37 -0
  30. package/hooks/mod/surface/rail.mjs +33 -0
  31. package/hooks/mod/view.mjs +30 -602
  32. package/hooks/session.mjs +14 -11
  33. package/package.json +2 -1
  34. package/skills/decide/SKILL.md +1 -1
  35. package/skills/dispatch/SKILL.md +1 -1
  36. package/skills/init/SKILL.md +1 -1
  37. package/skills/next/SKILL.md +1 -1
  38. package/skills/review/SKILL.md +1 -1
  39. package/templates/agent.md +1 -1
  40. package/templates/claude-md.md +2 -2
  41. package/hooks/mod/register.test.ts +0 -4932
@@ -0,0 +1,626 @@
1
+ // Durable lanes (docs/specs/26-durable-lanes.md): each act recorded before and after it runs (an event
2
+ // sandwich), in a log per story, so after a crash the next session can rebuild where each story stands
3
+ // (replay), check each act left open against git (reconcile), and brief the fresh agent that carries the
4
+ // story on. Replay only reads; nothing here runs an act again.
5
+ import {
6
+ appendFileSync,
7
+ existsSync,
8
+ mkdirSync,
9
+ readFileSync,
10
+ readdirSync,
11
+ rmSync,
12
+ statSync,
13
+ writeFileSync,
14
+ } from 'node:fs';
15
+ import { spawnSync } from 'node:child_process';
16
+ import { randomUUID } from 'node:crypto';
17
+ import { join } from 'node:path';
18
+ import { CODE_KIT, GIT, commandsOf } from './shell.mjs';
19
+ import { addedPackages } from './dependencies.mjs';
20
+ import { storyOfBranch } from './teamfacts.mjs';
21
+ import { globToRegExp } from './glob.mjs';
22
+ import { projectWorktrees } from './rules.mjs';
23
+ import { readQueue, settle, waiting } from './queue.mjs';
24
+ import { sessions } from './sessions.mjs';
25
+
26
+ export const EVENTS_DIR = '.claude/state/events';
27
+ const OPEN_DIR = `${EVENTS_DIR}/.open`;
28
+ /** DUR-6: a log past this is trimmed to its first agent event and its last KEEP events. */
29
+ export const MAX_LOG_BYTES = 5 * 1024 * 1024;
30
+ export const KEEP_EVENTS = 2000;
31
+ /** DUR-6: a merged story's log is kept this long after its last event. */
32
+ export const KEEP_MERGED_MS = 30 * 24 * 60 * 60_000;
33
+ const TARGET_MAX = 300;
34
+
35
+ // The main checkout, looked up once per root: a hook writes several events, each asking.
36
+ const mains = new Map();
37
+ const mainOf = (root) => {
38
+ if (!mains.has(root)) mains.set(root, projectWorktrees(root)[0] ?? root);
39
+ return mains.get(root);
40
+ };
41
+ const logFile = (root, story) => join(mainOf(root), EVENTS_DIR, `${story ?? 'lead'}.jsonl`);
42
+ const git = (cwd, ...args) =>
43
+ spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
44
+ const out = (r) => (r.status === 0 ? r.stdout.trim() : '');
45
+
46
+ /** DUR-2: a command as recorded: credentials masked, at most 300 characters. */
47
+ export function maskCommand(text) {
48
+ return String(text ?? '')
49
+ .replace(/\b(Bearer|Basic)\s+\S+/g, '$1 ***')
50
+ .replace(
51
+ /\b((?:[\w-]*(?:token|secret|password|passwd|api[_-]?key|auth)[\w-]*)\s*[=:]\s*)(?:"[^"]*"|'[^']*'|\S+)/gi,
52
+ '$1***',
53
+ )
54
+ .replace(/(--(?:token|password|key|secret)[= ])\S+/gi, '$1***')
55
+ .replace(/(\/\/[^/\s:@]+:)[^@\s]+@/g, '$1***@')
56
+ .slice(0, TARGET_MAX);
57
+ }
58
+
59
+ const TEST =
60
+ /^(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:npx\s+|pnpm\s+exec\s+|uv\s+run\s+)?(?:vitest|jest|mocha|pytest|playwright\s+test)\b|python3?\s+-m\s+pytest\b|go\s+test\b|cargo\s+test\b|node\s+--test\b)/;
61
+
62
+ /**
63
+ * Whether a command can't safely run twice (DUR-4): a migration (it names a file the `migration`
64
+ * approval protects), one the project blocks or restricts, or one in `execution.unrepeatable`.
65
+ */
66
+ export function unrepeatable(command, config) {
67
+ const patterns = [
68
+ ...(config.shell?.block ?? []).map((b) => b.pattern),
69
+ ...(config.shell?.restricted ?? []).map((r) => r.pattern),
70
+ ...(config.execution?.unrepeatable ?? []),
71
+ ];
72
+ if (patterns.some((p) => safeTest(p, command))) return true;
73
+ const migrations = (config.protected ?? []).filter((p) => p.approval === 'migration');
74
+ return command
75
+ .split(/\s+/)
76
+ .some((w) => migrations.some((p) => globToRegExp(p.glob).test(w.replace(/^\.\//, ''))));
77
+ }
78
+ function safeTest(pattern, text) {
79
+ try {
80
+ return new RegExp(pattern).test(text);
81
+ } catch {
82
+ return false;
83
+ }
84
+ }
85
+
86
+ /**
87
+ * DUR-1: what a tool call is, as the log records it: { kind, target }. `kind` is edit, read, run, test,
88
+ * commit, install, merge, push, unrepeatable, dispatch, or one of the lead's acts on a story (queue,
89
+ * send-back, release, approve, review).
90
+ */
91
+ export function classify(tool, input, config) {
92
+ const i = input ?? {};
93
+ if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit'].includes(tool))
94
+ return { kind: 'edit', target: String(i.file_path ?? i.notebook_path ?? '') };
95
+ if (['Read', 'Grep', 'Glob'].includes(tool))
96
+ return { kind: 'read', target: String(i.file_path ?? i.path ?? i.pattern ?? '') };
97
+ if (tool === 'Agent' || tool === 'Task') {
98
+ const reviewer = /review/i.test(String(i.subagent_type ?? ''));
99
+ return {
100
+ kind: reviewer ? 'review' : 'dispatch',
101
+ target: String(i.description ?? i.subagent_type ?? '').slice(0, TARGET_MAX),
102
+ };
103
+ }
104
+ if (tool !== 'Bash') return { kind: 'run', target: tool };
105
+ const command = String(i.command ?? '');
106
+ const target = maskCommand(command);
107
+ const parts = commandsOf(command).map((c) => c.text);
108
+ const any = (re) => parts.some((p) => re.test(p));
109
+ const kit = (sub) => new RegExp(String.raw`^${CODE_KIT}\s+${sub}`);
110
+ if (any(kit(String.raw`(?:queue\s+)?merge\b`))) return { kind: 'merge', target };
111
+ if (any(kit(String.raw`queue\s+add\b`))) return { kind: 'queue', target };
112
+ if (any(kit(String.raw`sent-back\b`))) return { kind: 'send-back', target };
113
+ if (any(kit(String.raw`worktrees\s+release\b`))) return { kind: 'release', target };
114
+ if (any(kit(String.raw`approve\b`))) return { kind: 'approve', target };
115
+ if (any(kit(String.raw`publish\b`))) return { kind: 'push', target };
116
+ if (any(kit(String.raw`(?:verify|security)\b.*\s--branch\b`))) return { kind: 'review', target };
117
+ if (any(new RegExp(String.raw`^${GIT}commit\b`))) return { kind: 'commit', target };
118
+ if (any(new RegExp(String.raw`^${GIT}push\b`))) return { kind: 'push', target };
119
+ if (any(new RegExp(String.raw`^${GIT}merge\b`))) return { kind: 'merge', target };
120
+ if (addedPackages(command).length) return { kind: 'install', target };
121
+ if (unrepeatable(command, config)) return { kind: 'unrepeatable', target };
122
+ const checks = (config.checks ?? []).flatMap((c) => c.run ?? []);
123
+ if (parts.some((p) => TEST.test(p) || checks.includes(p))) return { kind: 'test', target };
124
+ return { kind: 'run', target };
125
+ }
126
+
127
+ /** The story a call belongs to: the branch a lead's act names, a dispatch's story, else the branch it runs on. */
128
+ export function storyOf({ kind, target, branch, root }) {
129
+ const named = String(target).match(/\b([a-z][a-z0-9-]*\/st-\d+)\b/i)?.[1];
130
+ if (['merge', 'queue', 'send-back', 'release', 'review', 'push'].includes(kind) && named)
131
+ return { story: storyOfBranch(named), branch: named };
132
+ if (kind === 'merge' && /queue\s+merge/.test(target) && root) {
133
+ const head = waiting(readQueue(root))[0]?.branch;
134
+ if (head) return { story: storyOfBranch(head), branch: head };
135
+ }
136
+ if (kind === 'dispatch' || kind === 'review') {
137
+ const id = String(target).match(/\bST-\d+\b/i)?.[0];
138
+ if (id) return { story: id.toUpperCase(), branch: null };
139
+ }
140
+ return { story: storyOfBranch(branch), branch };
141
+ }
142
+
143
+ /** Appends one event to its story's log (the lead's when it has none), trimming a log grown past MAX_LOG_BYTES. */
144
+ export function appendEvent(root, event) {
145
+ const file = logFile(root, event.story);
146
+ mkdirSync(join(mainOf(root), EVENTS_DIR), { recursive: true });
147
+ appendFileSync(file, `${JSON.stringify(event)}\n`);
148
+ if (statSync(file).size > MAX_LOG_BYTES) trimLog(file);
149
+ }
150
+
151
+ /** DUR-6: keeps the first agent event and the last KEEP_EVENTS, with a line saying how many went. */
152
+ export function trimLog(file, keep = KEEP_EVENTS) {
153
+ const lines = readFileSync(file, 'utf8').split('\n').filter(Boolean);
154
+ if (lines.length <= keep + 1) return;
155
+ const last = lines.slice(-keep);
156
+ const found = lines.find((l) => /"kind":"(?:dispatch|agent)"/.test(l));
157
+ const first = found && !last.includes(found) ? [found] : [];
158
+ const note = JSON.stringify({
159
+ id: randomUUID(),
160
+ at: new Date().toISOString(),
161
+ kind: 'trimmed',
162
+ phase: 'note',
163
+ result: { dropped: lines.length - last.length - first.length },
164
+ });
165
+ writeFileSync(file, `${[...first, note, ...last].join('\n')}\n`);
166
+ }
167
+
168
+ /** A story's events, oldest first; [] for none. Unreadable lines are skipped. */
169
+ export function readEvents(root, story) {
170
+ try {
171
+ return readFileSync(logFile(root, story), 'utf8')
172
+ .split('\n')
173
+ .flatMap((l) => {
174
+ try {
175
+ return l ? [JSON.parse(l)] : [];
176
+ } catch {
177
+ return [];
178
+ }
179
+ });
180
+ } catch {
181
+ return [];
182
+ }
183
+ }
184
+
185
+ /** The stories with a log. */
186
+ export function loggedStories(root) {
187
+ try {
188
+ return readdirSync(join(mainOf(root), EVENTS_DIR))
189
+ .filter((f) => /^ST-\d+\.jsonl$/i.test(f))
190
+ .map((f) => f.replace(/\.jsonl$/, ''));
191
+ } catch {
192
+ return [];
193
+ }
194
+ }
195
+
196
+ const openFile = (root, session, agent) =>
197
+ join(
198
+ mainOf(root),
199
+ OPEN_DIR,
200
+ `${session ?? 'session'}-${agent ?? 'main'}`.replace(/[^\w.-]+/g, '_') + '.json',
201
+ );
202
+
203
+ /**
204
+ * DUR-1, before a call: closes the same agent's previous act if it never got its end (a failed or
205
+ * refused tool: the agent went on, so it wasn't a crash), then records this one's start.
206
+ */
207
+ export function recordStart(root, ctx, now = Date.now()) {
208
+ const pointer = openFile(root, ctx.session, ctx.agent);
209
+ if (existsSync(pointer)) {
210
+ try {
211
+ const prev = JSON.parse(readFileSync(pointer, 'utf8'));
212
+ appendEvent(root, {
213
+ ...base(prev, now),
214
+ phase: 'end',
215
+ result: { ok: null, ended: 'without a result' },
216
+ });
217
+ } catch {
218
+ // a pointer half-written: nothing to close
219
+ }
220
+ }
221
+ const event = { ...base(ctx, now), phase: 'start' };
222
+ appendEvent(root, event);
223
+ mkdirSync(join(mainOf(root), OPEN_DIR), { recursive: true });
224
+ writeFileSync(pointer, JSON.stringify(ctx));
225
+ return event;
226
+ }
227
+
228
+ /** DUR-1, after a call: its end, with what came of it. */
229
+ export function recordEnd(root, ctx, result, now = Date.now()) {
230
+ rmSync(openFile(root, ctx.session, ctx.agent), { force: true });
231
+ const event = { ...base(ctx, now), phase: 'end', result };
232
+ appendEvent(root, event);
233
+ return event;
234
+ }
235
+
236
+ /** An event that stands alone: a hand-back, a reconciliation. */
237
+ export function recordNote(root, ctx, now = Date.now()) {
238
+ const event = { ...base(ctx, now), phase: 'note', ...(ctx.result ? { result: ctx.result } : {}) };
239
+ appendEvent(root, event);
240
+ return event;
241
+ }
242
+
243
+ function base(ctx, now) {
244
+ return {
245
+ id: randomUUID(),
246
+ at: new Date(now).toISOString(),
247
+ story: ctx.story ?? null,
248
+ act: ctx.act ?? null,
249
+ actor: ctx.actor ?? null,
250
+ agent: ctx.agent ?? null,
251
+ session: ctx.session ?? null,
252
+ kind: ctx.kind,
253
+ target: ctx.target ?? null,
254
+ branch: ctx.branch ?? null,
255
+ head: ctx.head ?? null,
256
+ };
257
+ }
258
+
259
+ /** The commit a checkout is at, short; null outside git. */
260
+ export const headOf = (cwd) => out(git(cwd, 'rev-parse', '--short', 'HEAD')) || null;
261
+
262
+ /** DUR-1: what came of a call, from PostToolUse (`failure` null) or PostToolUseFailure. */
263
+ export function resultOf(kind, failure, cwd) {
264
+ if (failure !== null && failure !== undefined) {
265
+ const text = maskCommand(String(failure)).split('\n')[0].slice(0, 200);
266
+ const exit = Number(String(failure).match(/Exit code (\d+)/)?.[1] ?? NaN);
267
+ return {
268
+ ok: false,
269
+ ...(Number.isNaN(exit) ? {} : { exit }),
270
+ error: text,
271
+ ...(kind === 'test' ? { test: 'failed' } : {}),
272
+ };
273
+ }
274
+ return {
275
+ ok: true,
276
+ ...(kind === 'test' ? { test: 'passed' } : {}),
277
+ ...(kind === 'commit' && cwd ? { sha: headOf(cwd) } : {}),
278
+ };
279
+ }
280
+
281
+ // --- replay (DUR-3) -------------------------------------------------------------------------------
282
+
283
+ const LEAD_PHASE = {
284
+ dispatch: 'dispatched',
285
+ review: 'in review',
286
+ queue: 'queued',
287
+ 'send-back': 'sent back',
288
+ };
289
+
290
+ /**
291
+ * A story's state rebuilt from its events, reading only: { phase, branch, lastCommit: { sha, at },
292
+ * lastTest: { target, ok, at }, changed: [paths edited since the last commit], open: [acts with a start
293
+ * and no end, not reconciled], reconciled: [...], recent: [the last ten acts], trimmed }.
294
+ */
295
+ export function replay(events) {
296
+ const acts = new Map();
297
+ const state = {
298
+ phase: null,
299
+ branch: null,
300
+ lastCommit: null,
301
+ lastTest: null,
302
+ changed: [],
303
+ open: [],
304
+ reconciled: [],
305
+ recent: [],
306
+ trimmed: 0,
307
+ lastAt: null,
308
+ };
309
+ const changed = new Set();
310
+ for (const e of events) {
311
+ state.lastAt = e.at ?? state.lastAt;
312
+ if (e.branch && /\/st-\d+$/i.test(e.branch)) state.branch = e.branch;
313
+ if (e.kind === 'trimmed') {
314
+ state.trimmed += e.result?.dropped ?? 0;
315
+ continue;
316
+ }
317
+ if (e.kind === 'reconciled') {
318
+ state.reconciled.push(e);
319
+ const act = acts.get(e.target);
320
+ if (act) act.reconciled = e;
321
+ // An interrupted commit that happened is the last commit, as if its end had come.
322
+ if (act?.start?.kind === 'commit' && e.result?.sha) {
323
+ state.lastCommit = { sha: e.result.sha, at: e.at };
324
+ changed.clear();
325
+ }
326
+ continue;
327
+ }
328
+ if (e.kind === 'handback') {
329
+ state.phase = 'handed back';
330
+ continue;
331
+ }
332
+ if (!e.act) continue;
333
+ const act = acts.get(e.act) ?? { start: null, end: null, reconciled: null };
334
+ acts.set(e.act, act);
335
+ if (e.phase === 'start') {
336
+ act.start = e;
337
+ if (e.actor === 'lead' && LEAD_PHASE[e.kind]) state.phase = LEAD_PHASE[e.kind];
338
+ else if (e.actor === 'lead' && e.kind === 'merge') state.phase = 'merging';
339
+ else if (e.actor !== 'lead' && ['edit', 'run', 'test', 'commit', 'install'].includes(e.kind))
340
+ state.phase = 'building';
341
+ continue;
342
+ }
343
+ act.end = e;
344
+ const ok = e.result?.ok === true;
345
+ if (e.kind === 'commit' && ok) {
346
+ state.lastCommit = { sha: e.result.sha ?? e.head, at: e.at };
347
+ changed.clear();
348
+ }
349
+ if (e.kind === 'edit' && ok && e.target) changed.add(e.target);
350
+ if (e.kind === 'test' && e.result?.ok !== null)
351
+ state.lastTest = { target: e.target, ok, at: e.at };
352
+ if (e.actor === 'lead' && e.kind === 'merge' && ok) state.phase = 'merged';
353
+ }
354
+ state.changed = [...changed];
355
+ const all = [...acts.entries()].filter(([, a]) => a.start);
356
+ state.open = all
357
+ .filter(([, a]) => !a.end && !a.reconciled)
358
+ .map(([id, a]) => ({ act: id, ...pick(a.start) }));
359
+ state.recent = all.slice(-10).map(([id, a]) => ({
360
+ act: id,
361
+ ...pick(a.start),
362
+ result: a.end?.result ?? (a.reconciled ? { reconciled: a.reconciled.result } : null),
363
+ }));
364
+ return state;
365
+ }
366
+ const pick = (e) => ({
367
+ at: e.at,
368
+ kind: e.kind,
369
+ target: e.target,
370
+ actor: e.actor,
371
+ agent: e.agent,
372
+ session: e.session,
373
+ branch: e.branch,
374
+ });
375
+
376
+ // --- reconcile (DUR-4) ----------------------------------------------------------------------------
377
+
378
+ /** Whether a story is merged: its log says so, or the base contains its branch (merged from the pane). */
379
+ export function isMerged(root, state, base) {
380
+ if (state.phase === 'merged') return true;
381
+ return Boolean(
382
+ state.branch &&
383
+ base &&
384
+ git(root, 'rev-parse', '--verify', '--quiet', state.branch).status === 0 &&
385
+ git(root, 'merge-base', '--is-ancestor', state.branch, base).status === 0 &&
386
+ git(root, 'rev-list', '--count', `${base}..${state.branch}`).stdout.trim() === '0',
387
+ );
388
+ }
389
+
390
+ /** Kinds that can safely run again: the fresh agent re-reads and re-runs them. */
391
+ const REPEATABLE = new Set(['edit', 'read', 'run', 'test', 'install', 'dispatch', 'review']);
392
+
393
+ /**
394
+ * Whether an open act's agent has stopped: its session isn't live, a later event from the same agent
395
+ * says it handed back or went on, or it's older than the stall restart (LOOP-3).
396
+ */
397
+ export function stopped(act, events, { liveSessions, restartMs, now }) {
398
+ if (act.session && !liveSessions.has(act.session)) return true;
399
+ if (now - Date.parse(act.at) >= restartMs) return true;
400
+ return events.some(
401
+ (e) =>
402
+ e.kind === 'handback' &&
403
+ e.session === act.session &&
404
+ (e.agent ?? null) === (act.agent ?? null) &&
405
+ Date.parse(e.at) >= Date.parse(act.at),
406
+ );
407
+ }
408
+
409
+ /** The worktree a branch is checked out in, or null. */
410
+ function worktreeOf(root, branch) {
411
+ if (!branch) return null;
412
+ const list = out(git(root, 'worktree', 'list', '--porcelain'));
413
+ return (
414
+ list
415
+ .split('\n\n')
416
+ .find((w) => w.includes(`\nbranch refs/heads/${branch}`))
417
+ ?.match(/^worktree (.+)$/m)?.[1] ?? null
418
+ );
419
+ }
420
+
421
+ /**
422
+ * What an open act came to, from git and the worktree: { found: 'done' | 'not done' | 'unknown', how,
423
+ * next }. Reads only.
424
+ */
425
+ export function checkAct(root, act, base) {
426
+ const branch = act.branch;
427
+ const tree = worktreeOf(root, branch);
428
+ if (act.kind === 'commit') {
429
+ const after = branch
430
+ ? out(git(root, 'log', '-1', '--format=%h', `--since=${act.at}`, branch))
431
+ : '';
432
+ return after
433
+ ? {
434
+ found: 'done',
435
+ how: `${branch} has a commit made after it started (${after})`,
436
+ next: 'carry on from it',
437
+ sha: after,
438
+ }
439
+ : {
440
+ found: 'not done',
441
+ how: `${branch ?? 'the branch'} has no commit made after it started`,
442
+ next: "the fresh agent commits what's uncommitted",
443
+ };
444
+ }
445
+ if (act.kind === 'merge' && act.actor === 'lead') {
446
+ if (!branch || !base) return unknown('the branch or the base is unknown');
447
+ const merged = git(root, 'merge-base', '--is-ancestor', branch, base).status === 0;
448
+ return merged
449
+ ? {
450
+ found: 'done',
451
+ how: `${base} contains ${branch}'s head`,
452
+ next: 'its queue entry is settled as merged',
453
+ }
454
+ : {
455
+ found: 'not done',
456
+ how: `${base} doesn't contain ${branch}'s head`,
457
+ next: 'it stays at the head of the queue',
458
+ };
459
+ }
460
+ if (act.kind === 'push') {
461
+ const pushed = branch ?? out(git(tree ?? root, 'rev-parse', '--abbrev-ref', 'HEAD'));
462
+ const local = out(git(root, 'rev-parse', pushed));
463
+ const remote = out(git(root, 'rev-parse', `origin/${pushed}`));
464
+ return local && local === remote
465
+ ? { found: 'done', how: `origin/${pushed} is at ${local.slice(0, 7)}`, next: 'nothing' }
466
+ : {
467
+ found: 'not done',
468
+ how: `origin/${pushed} isn't at the local ${pushed}`,
469
+ next: 'the lead pushes again',
470
+ };
471
+ }
472
+ if (act.kind === 'edit' && tree) {
473
+ const rel = act.target?.startsWith(tree) ? act.target.slice(tree.length + 1) : act.target;
474
+ const changed = out(git(tree, 'status', '--porcelain', '--', rel));
475
+ return {
476
+ found: changed ? 'done' : 'not done',
477
+ how: changed ? `${rel} holds uncommitted changes` : `${rel} is as committed`,
478
+ next: 'the fresh agent re-reads it',
479
+ };
480
+ }
481
+ if (REPEATABLE.has(act.kind))
482
+ return {
483
+ found: 'not done',
484
+ how: `${act.kind === 'install' ? 'an install' : 'it'} can safely run again`,
485
+ next: 'the fresh agent runs it again if it needs it',
486
+ };
487
+ return unknown(`git can't say whether ${act.kind === 'unrepeatable' ? 'it' : act.kind} ran`);
488
+ }
489
+ const unknown = (how) => ({ found: 'unknown', how, next: 'the lead decides' });
490
+
491
+ /**
492
+ * DUR-4: reconciles every unfinished story's acts left open by an agent that has stopped. What git can
493
+ * settle is recorded as `reconciled` (a merge found done also settles its queue entry); what it can't
494
+ * is returned as unknown, for the lead. Uncommitted work is never touched.
495
+ */
496
+ export function reconcileAll(root, config, { base = null, now = Date.now() } = {}) {
497
+ const liveSessions = new Set(
498
+ sessions(root, now)
499
+ .filter((s) => s.live)
500
+ .map((s) => s.id),
501
+ );
502
+ const restartMs = (config.harness?.stall?.restartMinutes ?? 10) * 60_000;
503
+ const reconciled = [];
504
+ const unknowns = [];
505
+ for (const story of loggedStories(root)) {
506
+ const events = readEvents(root, story);
507
+ // A merged story is reconciled too: its own merge may be what was interrupted.
508
+ for (const act of replay(events).open) {
509
+ if (!stopped(act, events, { liveSessions, restartMs, now })) continue;
510
+ const found = checkAct(root, act, base);
511
+ if (found.found === 'unknown') {
512
+ unknowns.push({ story, ...act, ...found });
513
+ continue;
514
+ }
515
+ if (act.kind === 'merge' && found.found === 'done' && act.branch) {
516
+ const entry = readQueue(root).find(
517
+ (e) => e.branch === act.branch && ['waiting', 'merging'].includes(e.state),
518
+ );
519
+ if (entry) settle(root, act.branch, 'merged');
520
+ }
521
+ recordNote(
522
+ root,
523
+ {
524
+ story,
525
+ kind: 'reconciled',
526
+ target: act.act,
527
+ actor: 'code-kit',
528
+ branch: act.branch,
529
+ result: found,
530
+ },
531
+ now,
532
+ );
533
+ reconciled.push({ story, ...act, ...found });
534
+ }
535
+ }
536
+ return { reconciled, unknowns };
537
+ }
538
+
539
+ /** The lead's own reconciliation of an act git couldn't settle: what it found, and how. */
540
+ export function recordFinding(root, story, act, found, how, now = Date.now()) {
541
+ const open = replay(readEvents(root, story)).open.find((a) => a.act === act);
542
+ if (!open) return null;
543
+ return recordNote(
544
+ root,
545
+ {
546
+ story,
547
+ kind: 'reconciled',
548
+ target: act,
549
+ actor: 'lead',
550
+ branch: open.branch,
551
+ result: {
552
+ found,
553
+ how,
554
+ next: found === 'done' ? 'carry on from it' : 'run it again if needed',
555
+ },
556
+ },
557
+ now,
558
+ );
559
+ }
560
+
561
+ // --- the hand-over brief (DUR-5) ------------------------------------------------------------------
562
+
563
+ const ago = (at, now) => {
564
+ const m = Math.max(0, Math.round((now - Date.parse(at)) / 60000));
565
+ return m < 60 ? `${m} min ago` : `${Math.round(m / 60)} h ago`;
566
+ };
567
+
568
+ /**
569
+ * DUR-5: what the log says, for the brief of the agent that carries a story on: the last commit, the
570
+ * tests last run, what changed since the commit, what was reconciled, and the last ten acts. With the
571
+ * stopped agent's report's time, it says which is newer.
572
+ */
573
+ export function briefOf(story, state, { now = Date.now(), reportAt = null } = {}) {
574
+ const lines = [`What the log says about ${story}:`];
575
+ if (state.trimmed) lines.push(`- (${state.trimmed} older events were trimmed.)`);
576
+ lines.push(
577
+ state.lastCommit
578
+ ? `- Last commit: ${state.lastCommit.sha} (${ago(state.lastCommit.at, now)}).`
579
+ : '- No commit recorded yet.',
580
+ );
581
+ if (state.lastTest)
582
+ lines.push(
583
+ `- Tests last run: \`${state.lastTest.target}\`, ${state.lastTest.ok ? 'passed' : 'failed'} (${ago(state.lastTest.at, now)}).`,
584
+ );
585
+ if (state.changed.length)
586
+ lines.push(`- Changed since that commit: ${state.changed.join(', ')}. Re-read them first.`);
587
+ for (const r of state.reconciled.slice(-5))
588
+ lines.push(
589
+ `- Reconciled: ${r.result?.found} (${r.result?.how}); ${r.result?.next ?? 'nothing to do'}.`,
590
+ );
591
+ for (const o of state.open)
592
+ lines.push(`- Left open: ${o.kind} \`${o.target}\`, waiting on the lead's reconciliation.`);
593
+ if (state.recent.length) {
594
+ lines.push('- The last acts, oldest first:');
595
+ for (const a of state.recent)
596
+ lines.push(
597
+ ` - ${a.kind} \`${a.target ?? ''}\`: ${a.result ? (a.result.ok === true ? 'ok' : a.result.ok === false ? `failed${a.result.error ? ` (${a.result.error})` : ''}` : a.result.reconciled ? `reconciled ${a.result.reconciled.found}` : 'ended without a result') : 'no result'}`,
598
+ );
599
+ }
600
+ if (reportAt && state.lastAt)
601
+ lines.push(
602
+ Date.parse(state.lastAt) > Date.parse(reportAt)
603
+ ? "- The log's last act came after the report: trust the log where they differ."
604
+ : "- The report is newer than the log's last act.",
605
+ );
606
+ return lines.join('\n');
607
+ }
608
+
609
+ // --- keeping the logs (DUR-6) ---------------------------------------------------------------------
610
+
611
+ /** Removes the logs of stories merged more than KEEP_MERGED_MS ago; returns the stories removed. */
612
+ export function pruneLogs(root, { base = null, now = Date.now() } = {}) {
613
+ const removed = [];
614
+ for (const story of loggedStories(root)) {
615
+ const state = replay(readEvents(root, story));
616
+ if (
617
+ state.lastAt &&
618
+ now - Date.parse(state.lastAt) > KEEP_MERGED_MS &&
619
+ isMerged(root, state, base)
620
+ ) {
621
+ rmSync(logFile(root, story), { force: true });
622
+ removed.push(story);
623
+ }
624
+ }
625
+ return removed;
626
+ }
@@ -8,6 +8,8 @@ export const MODELS = ['haiku', 'sonnet', 'opus'];
8
8
  /** Each setting by its dotted key: its default, and why a value is wrong (or null when it's right). */
9
9
  /** LEAN-3: what the loop does with the lead's context when a milestone finishes. */
10
10
  export const COMPACT = ['ask', 'auto', 'off'];
11
+ /** UI-12: whether the mod's characters and clocks move while work flows, or stay still. */
12
+ export const MOTION = ['while-active', 'off'];
11
13
 
12
14
  export const SETTINGS = {
13
15
  autonomy: {
@@ -103,6 +105,12 @@ export const SETTINGS = {
103
105
  about:
104
106
  'A system notification when something new needs you: an approval, a question, a stalled lane',
105
107
  },
108
+ motion: {
109
+ default: 'while-active',
110
+ problem: (v) => (MOTION.includes(v) ? null : `must be one of ${MOTION.join(', ')}`),
111
+ about:
112
+ "Whether the pane's characters, clocks and the lead's rail move while work flows, or stay still",
113
+ },
106
114
  'report.on': {
107
115
  default: false,
108
116
  problem: (v) => (typeof v === 'boolean' ? null : 'must be true or false'),
@@ -14,7 +14,7 @@ import {
14
14
  } from './standards.mjs';
15
15
 
16
16
  /** The version of code-kit's instructions: raised whenever the templates' rules change. */
17
- export const INSTRUCTIONS_VERSION = 8;
17
+ export const INSTRUCTIONS_VERSION = 11;
18
18
 
19
19
  const TEMPLATES = fileURLToPath(new URL('../../templates/', import.meta.url));
20
20
  const BEGIN = (v) => `<!-- code-kit:begin v${v} -->`;
@@ -17,6 +17,7 @@ import { keptBecause, worktrees } from './worktrees.mjs';
17
17
  import { ciFindings } from './ci.mjs';
18
18
  import { storyModels } from './dispatches.mjs';
19
19
  import { pickPerLane } from './schedule.mjs';
20
+ import { reconcileAll } from './events.mjs';
20
21
 
21
22
  export const DRAFT_FILE = '.claude/code-kit.draft.json';
22
23
  export const BRIEF_STATES = ['framed', 'explored', 'scoped', 'specified', 'planned', 'ready'];
@@ -233,6 +234,27 @@ export function nextStep(root, base) {
233
234
  const from = base(config);
234
235
  if (!from)
235
236
  attention.push('The base branch has no commits yet, so story branches are read against HEAD.');
237
+ // DUR-4: every act an agent left open when it stopped is checked against git before any work is
238
+ // chosen; what git can't settle, the lead decides before anything else on that story.
239
+ let unsettled = [];
240
+ try {
241
+ const { reconciled, unknowns } = reconcileAll(root, config, { base: from });
242
+ unsettled = unknowns;
243
+ for (const r of reconciled)
244
+ attention.push(
245
+ `${r.story}: an interrupted ${r.kind} was reconciled as ${r.found} (${r.how}).`,
246
+ );
247
+ } catch {
248
+ // an unreadable log: recovery falls back to git, as before
249
+ }
250
+ if (unsettled.length) {
251
+ const stories = [...new Set(unsettled.map((u) => u.story))];
252
+ return result(
253
+ 'reconcile',
254
+ `${unsettled.map((u) => `${u.story}'s agent stopped during ${u.kind === 'unrepeatable' ? "a command that can't safely run twice" : `a ${u.kind}`} (\`${u.target}\`), and git can't say whether it ran`).join('; ')}. Find out before anything else on ${stories.length === 1 ? 'that story' : 'those stories'}.`,
255
+ { args: stories.join(' '), acts: unsettled },
256
+ );
257
+ }
236
258
  const status = buildStatus(root, config, from ?? 'HEAD', files);
237
259
  if (status.problems.length)
238
260
  attention.push(