@warren-dean/code-kit 0.29.0 → 0.30.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.
@@ -14,11 +14,20 @@ import {
14
14
  ecosystemOf,
15
15
  isDependencyFile,
16
16
  } from './lib/dependencies.mjs';
17
- import { CODE_KIT, GIT, codeOf, commandsOf, runs } from './lib/shell.mjs';
17
+ import {
18
+ CODE_KIT,
19
+ GIT,
20
+ codeOf,
21
+ commandsOf,
22
+ readsOnly,
23
+ ruleMatches,
24
+ runs,
25
+ withoutHarmlessRedirects,
26
+ } from './lib/shell.mjs';
18
27
  import { block, start } from './lib/hook.mjs';
19
28
  import { CONFIG_FILE, committedConfig } from './lib/config.mjs';
20
29
  import { laneOfBranch, storyOfBranch, teamOf, teamProvider, whoami } from './lib/team.mjs';
21
- import { entryProblems, readRegister } from './lib/designs.mjs';
30
+ import { entryProblems, freshEntries, readRegister } from './lib/designs.mjs';
22
31
  import { globToRegExp, matchesAny } from './lib/glob.mjs';
23
32
  import { noteBefore } from './lane-audit.mjs';
24
33
  import { storyMerges } from './lib/queue.mjs';
@@ -72,21 +81,6 @@ const RUNS = [
72
81
  for (const [re, why] of RUNS) {
73
82
  if (runs(cmd, re, { quoted: false })) block(`Blocked: ${why}\nCommand: ${cmd}`);
74
83
  }
75
- /**
76
- * Whether `cmd` only reads git's history, with what it prints piped into read-only filters: `git diff
77
- * main...HEAD -- .claude/approval-log.jsonl`, `git log -p -- … | head`. No redirect, no tee, nothing else.
78
- */
79
- function gitReadsOnly(cmd) {
80
- const code = codeOf(cmd);
81
- if (/>|\btee\b|`|\$\(/.test(code)) return false;
82
- const parts = commandsOf(cmd);
83
- return (
84
- parts.length > 0 &&
85
- new RegExp(String.raw`^${GIT}(?:diff|log|show|blame)\b`).test(parts[0].code) &&
86
- parts.slice(1).every((c) => /^(?:grep|head|tail|wc|cat|sort|uniq|less)\b/.test(c.code))
87
- );
88
- }
89
-
90
84
  // These read the command whole: a pipe spans commands, and an approval or the log can be written
91
85
  // through a quoted path.
92
86
  const ALWAYS = [
@@ -102,8 +96,8 @@ const ALWAYS = [
102
96
  ],
103
97
  [
104
98
  /approval-log\.jsonl/,
105
- "The approval audit log is appended only by the commit hook; nobody edits it. A shell command may not name it except to read its history with git (git diff, log or show, piped only into grep, head, tail or wc); read the file itself with the Read tool, which can't write.",
106
- gitReadsOnly(cmd) ? '' : cmd,
99
+ "The approval audit log is appended only by the commit hook; nobody edits it. A shell command may name it only to read it: git diff, log, show or blame, or cat, head, tail, grep, wc, jq, cut, sort, uniq, awk or sed -n printing lines, after a `cd` and piped or chained only into each other, with no redirect but 2>&1 or into /dev/null, no command's output in its arguments ($(…) or backticks) and no variable set before a command. Run the read in that form, or read the file with the Read tool, which can't write.",
100
+ readsOnly(cmd) ? '' : cmd,
107
101
  ],
108
102
  ];
109
103
  for (const [re, why, text] of ALWAYS) {
@@ -209,8 +203,9 @@ const forPerson = actor.kind === 'lead' && config.approvals.lead;
209
203
 
210
204
  for (const { pattern, why, person, command } of config.shell.block) {
211
205
  // `command: true`: the pattern names a command, matched from the start of each one the line runs, so a
212
- // heredoc or a quoted message that mentions it isn't refused. Otherwise it reads the whole text.
213
- const matched = command ? runs(cmd, new RegExp(pattern)) : new RegExp(pattern).test(cmd);
206
+ // heredoc, an argument or a quoted message that mentions it isn't refused. Otherwise it reads the whole
207
+ // text, except a read's quoted arguments (lib/shell.mjs ruleMatches).
208
+ const matched = ruleMatches({ pattern, command }, cmd);
214
209
  if (!matched || (person && forPerson)) continue;
215
210
  const hint =
216
211
  person && actor.kind === 'lead'
@@ -371,7 +366,7 @@ if (packages.length) {
371
366
  }
372
367
  for (const { pattern, lanes, why } of config.shell.restricted) {
373
368
  const allowed = actor.kind === 'lead' || (actor.kind === 'lane' && lanes.includes(actor.lane));
374
- if (!allowed && new RegExp(pattern).test(cmd))
369
+ if (!allowed && ruleMatches({ pattern }, cmd))
375
370
  block(`Blocked: the ${actor.label} may not run this. ${why}\nCommand: ${cmd}`);
376
371
  }
377
372
 
@@ -519,7 +514,7 @@ function committedFiles() {
519
514
  l.slice(3),
520
515
  );
521
516
  // Each git command of the chain, however it's run (`git -C <worktree> add`).
522
- const pieces = commandsOf(cmd).map((c) => c.text);
517
+ const pieces = commandsOf(withoutHarmlessRedirects(cmd)).map((c) => c.text);
523
518
  const gitRun = (sub) =>
524
519
  pieces.map((p) => p.match(new RegExp(String.raw`^${GIT}${sub}`))).filter(Boolean);
525
520
  const commitAll = gitRun(String.raw`commit(?![\w-])(.*)`).some((m) =>
@@ -532,7 +527,14 @@ function committedFiles() {
532
527
  .filter((a) => a && !a.startsWith('-'))
533
528
  .map((a) => a.replace(/^(['"])(.*)\1$/, '$2'));
534
529
  const addRuns = gitRun(String.raw`add\b(.*)`);
535
- const addAll = addRuns.some((m) => /\s(-A|--all|\.)(\s|$)/.test(` ${m[1]}`));
530
+ // `-A` stages everything only without paths: `git add -A <paths>` stages those paths. A pathspec with
531
+ // magic (`:/`, `:(top)…`) could name any file, so it counts as everything.
532
+ const addAll = addRuns.some(
533
+ (m) =>
534
+ /\s\.(\s|$)/.test(` ${m[1]}`) ||
535
+ argsOf(m).some((a) => a.startsWith(':')) ||
536
+ (/\s(-A|--all)(\s|$)/.test(` ${m[1]}`) && argsOf(m).length === 0),
537
+ );
536
538
  // `git rm` and `git mv` stage as they run: their files count though nothing has changed them yet, and
537
539
  // what they take away is gone from the commit though it's still on disk now.
538
540
  const rmArgs = gitRun(String.raw`rm\b(.*)`).flatMap(argsOf);
@@ -564,6 +566,26 @@ function committedFiles() {
564
566
  return { files: [...new Set([...staged, ...added, ...removed, ...reset])], gone, git };
565
567
  }
566
568
 
569
+ /** The approval log's last entry for each file, as the checkout has the log. */
570
+ function lastEntries(root) {
571
+ const last = new Map();
572
+ let text = '';
573
+ try {
574
+ text = readFileSync(join(root, APPROVAL_LOG), 'utf8');
575
+ } catch {
576
+ return last;
577
+ }
578
+ for (const line of text.split('\n').filter(Boolean)) {
579
+ try {
580
+ const e = JSON.parse(line);
581
+ if (e?.file) last.set(e.file, e);
582
+ } catch {
583
+ // an unreadable line records nothing; verify reports it
584
+ }
585
+ }
586
+ return last;
587
+ }
588
+
567
589
  // Every committed protected file is recorded in the audit log, with the person's reason when an
568
590
  // approval is in force. So is a lane's manifest or lockfile change, outside its own paths, made under a
569
591
  // dependency approval: that entry is how `code-kit verify` accepts it. The log is staged into the same
@@ -652,6 +674,27 @@ function recordApprovals() {
652
674
  grantedAt: null,
653
675
  });
654
676
  }
677
+ // WHO-1: where the lead merges, its own change to what the person keeps needs the person's approval.
678
+ // Given after the change was committed, it has nothing left to commit: so the lead's next commit, one
679
+ // of its own if need be, records it for each such file as the branch holds it, by its content's hash,
680
+ // and verify accepts that entry while the file is unchanged.
681
+ if (actor.kind === 'lead') {
682
+ const inThisCommit = new Set(files);
683
+ for (const [file, last] of lastEntries(root)) {
684
+ if (last.approval !== 'lead' || last.branch !== branch || inThisCommit.has(file)) continue;
685
+ const entry = protectedEntry(file, config);
686
+ if (!entry || !leadNeedsApproval(entry.approval, config)) continue;
687
+ const granted = approval(root, entry.approval, actor);
688
+ const blob = git('rev-parse', '--verify', '-q', `HEAD:${file}`).trim();
689
+ if (granted && blob)
690
+ record(file, {
691
+ approval: entry.approval,
692
+ reason: granted.reason,
693
+ grantedAt: granted.grantedAt,
694
+ blob,
695
+ });
696
+ }
697
+ }
655
698
  // REG-2: a commit that weakens a test waits for a `tests` approval: WHO-2, the lead's on a lane's
656
699
  // branch where tests are delegated, otherwise the person's (always on the lead's own). It's recorded in
657
700
  // the log, so verify accepts the branch, and used up by this commit.
@@ -719,16 +762,18 @@ ${approvalHowTo(TESTS_APPROVAL, actor, root, 'weakening tests in one commit', pe
719
762
 
720
763
  // The commit hook judges what the commit holds before the command runs, so a file a command earlier in
721
764
  // the chain writes (a formatter, a script, a heredoc) can't be seen, and would go in unjudged and
722
- // unlogged. Before the commit, a chain may only move into the checkout and stage.
765
+ // unlogged. Before the commit, a chain may only move into the checkout, stage, and run commands that
766
+ // only read (lib/shell.mjs readsOnly: git's status, diff, log and show among them, with no output
767
+ // file). Errors sent into the output or /dev/null write no file.
723
768
  const BEFORE_COMMIT = new RegExp(
724
- String.raw`^(?:cd\s|${GIT}(?:add|rm|mv|status|diff|log|show|restore\s+--staged|reset\s+--soft)(?![\w-]))`,
769
+ String.raw`^(?:cd\s|${GIT}(?:add|rm|mv|restore\s+--staged|reset\s+--soft)(?![\w-]))`,
725
770
  );
726
771
  function writesBeforeCommit() {
727
- const pieces = commandsOf(cmd);
772
+ const pieces = commandsOf(withoutHarmlessRedirects(cmd));
728
773
  const at = pieces.findIndex((c) => new RegExp(String.raw`^${GIT}commit(?![\w-])`).test(c.text));
729
774
  return pieces
730
775
  .slice(0, Math.max(at, 0))
731
- .find((c) => !BEFORE_COMMIT.test(c.text) || /[<>]/.test(c.code));
776
+ .find((c) => (!BEFORE_COMMIT.test(c.text) || /[<>]/.test(c.code)) && !readsOnly(c.whole));
732
777
  }
733
778
 
734
779
  if (commits) {
@@ -738,14 +783,22 @@ if (commits) {
738
783
  `Blocked: this commit runs after \`${writer.text.slice(0, 80)}\` in the same command, which may write files code-kit can't see before the commit, so they would go in without their checks or their entry in the approval log. Run that first, on its own; then commit in a command of its own (\`git add … && git commit …\` is fine).\nCommand: ${cmd}`,
739
784
  );
740
785
  // HAND-2: a register entry this commit adds or changes names the approved design's files, as approved.
786
+ // HAND-11: one the branch already has, the base has, or a merge being concluded brings in isn't this
787
+ // commit's: a lane merging the base into its branch isn't held to the base's entries.
741
788
  const register = config.designGate?.register;
742
789
  if (register && committedFiles().files.includes(register)) {
743
- const before = spawnSync('git', ['-C', root, 'show', `HEAD:${register}`], { encoding: 'utf8' });
744
- const old = before.status === 0 ? readRegister(root, config, before.stdout).entries : [];
745
- const same = (e) => old.some((o) => JSON.stringify(o) === JSON.stringify(e));
746
- const problems = readRegister(root, config)
747
- .entries.filter((e) => !same(e))
748
- .flatMap((e) => entryProblems(root, e, config.docs?.specs));
790
+ const at = (ref) => {
791
+ const shown = spawnSync('git', ['-C', root, 'show', `${ref}:${register}`], {
792
+ encoding: 'utf8',
793
+ });
794
+ return shown.status === 0 ? readRegister(root, config, shown.stdout).entries : [];
795
+ };
796
+ const problems = freshEntries(
797
+ readRegister(root, config).entries,
798
+ at('HEAD'),
799
+ at(config.branches.protected[0]),
800
+ at('MERGE_HEAD'),
801
+ ).flatMap((e) => entryProblems(root, e, config.docs?.specs));
749
802
  if (problems.length)
750
803
  block(
751
804
  `Blocked: ${register} names approved designs a lane can't build from as approved:\n ${problems.join('\n ')}\nEach screen's design is files in the repository, every state, with its hash (docs/specs/24-designs-handed-over.md).\nCommand: ${cmd}`,
@@ -4,9 +4,10 @@
4
4
  // the like): a link back to a worktree's installs resolves outside the checkout, which path-sensitive
5
5
  // tools refuse, and an install run in it would rewrite the worktree's own.
6
6
  import { execFileSync, spawnSync } from 'node:child_process';
7
- import { existsSync, mkdtempSync, rmSync } from 'node:fs';
7
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
8
8
  import { platform, tmpdir } from 'node:os';
9
9
  import { basename, dirname, join } from 'node:path';
10
+ import { isDependencyFile } from './dependencies.mjs';
10
11
 
11
12
  // The folders an install puts beside the code, which a fresh checkout lacks.
12
13
  const INSTALLS = new Set(['node_modules', '.venv', 'venv']);
@@ -103,3 +104,79 @@ export function freshCheckout(
103
104
  copyInstalls(installsFrom, dir);
104
105
  return { dir, remove };
105
106
  }
107
+
108
+ /**
109
+ * The manifests and lockfiles tracked in either checkout whose content differs between the two working
110
+ * trees: where installs copied from `from` may not match the code in `dir`.
111
+ */
112
+ export function dependencyDifferences(from, dir) {
113
+ const tracked = (d) => {
114
+ try {
115
+ return git(d, 'ls-files')
116
+ .split('\n')
117
+ .filter((f) => f && isDependencyFile(f));
118
+ } catch {
119
+ return [];
120
+ }
121
+ };
122
+ const read = (d, f) => {
123
+ try {
124
+ return readFileSync(join(d, f), 'utf8');
125
+ } catch {
126
+ return null;
127
+ }
128
+ };
129
+ return [...new Set([...tracked(from), ...tracked(dir)])]
130
+ .filter((f) => read(from, f) !== read(dir, f))
131
+ .sort();
132
+ }
133
+
134
+ // The install each lockfile at the top of a checkout calls for, run without changing the lockfile, and
135
+ // the manifests and lockfiles of its ecosystem, whose changes it installs.
136
+ const JS = [
137
+ 'package.json',
138
+ 'pnpm-lock.yaml',
139
+ 'package-lock.json',
140
+ 'npm-shrinkwrap.json',
141
+ 'yarn.lock',
142
+ ];
143
+ const INSTALLERS = [
144
+ ['pnpm-lock.yaml', 'pnpm install --frozen-lockfile --prefer-offline', JS],
145
+ ['package-lock.json', 'npm ci --prefer-offline --no-audit --no-fund', JS],
146
+ ['npm-shrinkwrap.json', 'npm ci --prefer-offline --no-audit --no-fund', JS],
147
+ ['yarn.lock', 'yarn install --frozen-lockfile', JS],
148
+ ['bun.lock', 'bun install --frozen-lockfile', [...JS, 'bun.lock']],
149
+ ['bun.lockb', 'bun install --frozen-lockfile', [...JS, 'bun.lockb']],
150
+ ['uv.lock', 'uv sync --frozen', ['pyproject.toml', 'uv.lock']],
151
+ ];
152
+
153
+ /**
154
+ * MQ-1: makes the installs in the fresh checkout `dir` match its tree. Installs copied from `from` match
155
+ * only while their manifests and lockfiles are the same: where they differ (the base gained a workspace
156
+ * package since they were installed), the project's install runs in `dir`, never in `from`: `prepare`
157
+ * where the project sets one, else the install its lockfile calls for, when the files that differ are
158
+ * that lockfile's ecosystem's. `{ differ, copied, lockfile, command, failed }`: `differ`, the files that
159
+ * differ; `copied`, whether any installs were copied in; `lockfile`, whether a lockfile code-kit knows
160
+ * is there; `command`, the install run (null when none was needed or none is known); `failed`,
161
+ * { missing, output } when it didn't succeed.
162
+ */
163
+ export function matchInstalls(dir, from, { prepare = null, timeout = 900000 } = {}) {
164
+ const differ = dependencyDifferences(from, dir);
165
+ const copied = installsOf(dir).length > 0;
166
+ const present = INSTALLERS.filter(([lock]) => existsSync(join(dir, lock)));
167
+ const known = present.find(([, , files]) => differ.some((f) => files.includes(basename(f))));
168
+ const command = differ.length ? (prepare ?? known?.[1] ?? null) : null;
169
+ const facts = { differ, copied, lockfile: present.length > 0 };
170
+ if (!command) return { ...facts, command: null, failed: null };
171
+ const res = spawnSync(command, { cwd: dir, shell: true, encoding: 'utf8', timeout });
172
+ if (res.status === 0) return { ...facts, command, failed: null };
173
+ const output = `${res.stdout ?? ''}${res.stderr ?? ''}`.trim().split('\n').slice(-20).join('\n');
174
+ return {
175
+ ...facts,
176
+ command,
177
+ failed: {
178
+ missing: res.status === 127,
179
+ output: output || (res.error ? String(res.error.code ?? res.error.message) : ''),
180
+ },
181
+ };
182
+ }
@@ -36,6 +36,9 @@ function runCommand(command, cwd, timeout) {
36
36
  }
37
37
  }
38
38
 
39
+ // pnpm exec's word for a command that isn't installed, which it exits 254 with (after a bare "undefined").
40
+ const MISSING_TOOL = /ERR_PNPM_\w+\s+Command "([^"]+)" not found/;
41
+
39
42
  /** The directories a check runs in: each changed one matching `each` that still exists, or the worktree. */
40
43
  function directories(check, files, root) {
41
44
  if (!check.each) return [root];
@@ -63,13 +66,20 @@ function runCheck(check, files, root, actor, skipped) {
63
66
  for (const command of check.run) {
64
67
  const res = runCommand(command, cwd, (check.timeoutSeconds ?? 240) * 1000);
65
68
  const where = cwd === root ? '' : ` in ${cwd.slice(root.length + 1)}`;
66
- if (res.status === 127) {
69
+ // A tool that isn't there: the shell's 127, or a package manager's own word for it (pnpm exec's).
70
+ const tool = res.status === 254 ? res.output.match(MISSING_TOOL)?.[1] : null;
71
+ if (res.status === 127 || tool) {
72
+ const what = tool ?? command;
67
73
  if (check.ifMissing === 'fail')
68
74
  return {
69
75
  check: check.name,
70
- title: `${check.name}: \`${command}\` is not installed${where}. Install it so the check can run.`,
76
+ title: `${check.name}: \`${what}\` is not installed${where}. Install it so the check can run.`,
71
77
  };
72
- skipped.push({ check: check.name, command, where: where.replace(/^ in /, '') || null });
78
+ skipped.push({
79
+ check: check.name,
80
+ command: what,
81
+ where: where.replace(/^ in /, '') || null,
82
+ });
73
83
  return null; // not installed yet (fresh clone): the check can't run
74
84
  }
75
85
  // #62: a check that ran out of time didn't fail; it's marked so a merge can try it again.
package/hooks/lib/ci.mjs CHANGED
@@ -31,6 +31,32 @@ const stripComment = (line) => {
31
31
  }
32
32
  return line;
33
33
  };
34
+ /** A one-line map's entries (`group: x, cancel-in-progress: true`), split at commas outside quotes and `${{ }}`. */
35
+ function flowMap(body) {
36
+ const parts = [];
37
+ let quote = null;
38
+ let depth = 0;
39
+ let start = 0;
40
+ for (let i = 0; i < body.length; i++) {
41
+ const c = body[i];
42
+ if (quote) {
43
+ if (c === quote) quote = null;
44
+ } else if (c === '"' || c === "'") quote = c;
45
+ else if (c === '{' || c === '[') depth += 1;
46
+ else if (c === '}' || c === ']') depth -= 1;
47
+ else if (c === ',' && depth === 0) {
48
+ parts.push(body.slice(start, i));
49
+ start = i + 1;
50
+ }
51
+ }
52
+ parts.push(body.slice(start));
53
+ const out = {};
54
+ for (const part of parts) {
55
+ const m = /^\s*("[^"]*"|'[^']*'|[^:]+?):(?:\s+|$)(.*)$/s.exec(part);
56
+ if (m) out[unquote(m[1])] = scalar(m[2]);
57
+ }
58
+ return out;
59
+ }
34
60
  const scalar = (v) => {
35
61
  const t = v.trim();
36
62
  if (t === '') return null;
@@ -40,7 +66,7 @@ const scalar = (v) => {
40
66
  .split(',')
41
67
  .map((x) => unquote(x))
42
68
  .filter(Boolean);
43
- if (t.startsWith('{') && t.endsWith('}')) return {};
69
+ if (t.startsWith('{') && t.endsWith('}')) return flowMap(t.slice(1, -1));
44
70
  if (t === 'true') return true;
45
71
  if (t === 'false') return false;
46
72
  if (/^-?\d+(\.\d+)?$/.test(t)) return Number(t);
@@ -206,7 +232,14 @@ export function workflowFindings(file, text, base) {
206
232
  `${untimed.length === 1 ? 'job' : 'jobs'} ${untimed.join(', ')} ${untimed.length === 1 ? 'has' : 'have'} no timeout-minutes, so a hung step runs up to GitHub's ${GITHUB_LIMIT_MINUTES / 60} hours`,
207
233
  'give each job a timeout-minutes a little over its usual run',
208
234
  );
209
- const cancels = (c) => c && typeof c === 'object' && c['cancel-in-progress'] === true;
235
+ // Concurrency is decided when cancel-in-progress is set: true, an expression (`${{ … }}`, such as
236
+ // cancelling pull requests' runs but never an apply), or false on purpose, for a workflow that must
237
+ // never be stopped half-way (a deploy, an infrastructure apply). Left out, every push runs to the end.
238
+ const cancels = (c) =>
239
+ c &&
240
+ typeof c === 'object' &&
241
+ (typeof c['cancel-in-progress'] === 'boolean' ||
242
+ /^\s*\$\{\{[\s\S]*\}\}\s*$/.test(String(c['cancel-in-progress'] ?? '')));
210
243
  if (
211
244
  onPr &&
212
245
  !cancels(doc.concurrency) &&
@@ -9,11 +9,8 @@ import { ADAPTERS, applyAdapters } from './adapters/index.mjs';
9
9
 
10
10
  export const CONFIG_FILE = '.claude/code-kit.json';
11
11
  // Claude's own memory and session scratchpad, which the lead always writes.
12
- export const CLAUDE_OWN = [
13
- '~/.claude/projects/*/memory/**',
14
- '/private/tmp/claude-*/**',
15
- '/tmp/claude-*/**',
16
- ];
12
+ // Claude's memory. The session's own temporary folder is the lead's and the lanes' too (rules.mjs).
13
+ export const CLAUDE_OWN = ['~/.claude/projects/*/memory/**'];
17
14
  const KIT = { glob: '.claude/**', approval: 'kit', why: 'the rules that constrain agents' };
18
15
 
19
16
  /** `{ config }` when the project has a valid config, `{ error }` when it is invalid, `{}` when it has none. */
@@ -0,0 +1,107 @@
1
+ // LOOP-15: stories the lead holds on purpose, until a date or until it releases them, with why. A held
2
+ // story isn't dispatched, reviewed or merged by `code-kit next`, the loop or the merge queue, so a lead
3
+ // waiting on something outside the build (a person's answer elsewhere, a partner's release, a date) isn't
4
+ // asked about the same story again every half hour. Kept in the main checkout beside the merge queue, so
5
+ // every worktree and a restarted session see the same.
6
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+ import { projectWorktrees } from './rules.mjs';
9
+
10
+ export const DEFERRED_FILE = '.claude/state/deferred.json';
11
+
12
+ const deferredFile = (root) => join(projectWorktrees(root)[0] ?? root, DEFERRED_FILE);
13
+
14
+ /** Every hold recorded, past ones included: [{ story, reason, until, at, session? }]. */
15
+ function readAll(root) {
16
+ try {
17
+ const list = JSON.parse(readFileSync(deferredFile(root), 'utf8'));
18
+ return Array.isArray(list) ? list.filter((h) => h && typeof h.story === 'string') : [];
19
+ } catch {
20
+ return [];
21
+ }
22
+ }
23
+
24
+ function writeAll(root, list) {
25
+ const file = deferredFile(root);
26
+ mkdirSync(dirname(file), { recursive: true });
27
+ writeFileSync(file, `${JSON.stringify(list, null, 2)}\n`);
28
+ }
29
+
30
+ /** Whether a hold is still in force at `now`: no end, or an end still to come. */
31
+ const inForce = (h, now) => !h.until || Date.parse(h.until) > now;
32
+
33
+ /** The holds in force, in the order they were made: [{ story, reason, until, at, session? }]. */
34
+ export function activeDeferrals(root, now = Date.now()) {
35
+ return readAll(root).filter((h) => inForce(h, now));
36
+ }
37
+
38
+ /**
39
+ * What `--until` says, as an ISO time, or { error } in words. A date (2026-11-10) holds until that day
40
+ * begins, in local time; an ISO time holds until then. A time already past holds nothing.
41
+ */
42
+ export function parseUntil(text, now = Date.now()) {
43
+ if (text === undefined || text === null) return { until: null };
44
+ const date = /^\d{4}-\d{2}-\d{2}$/.test(text) ? new Date(`${text}T00:00:00`) : new Date(text);
45
+ if (Number.isNaN(date.getTime()))
46
+ return {
47
+ error: `--until ${text} isn't a date (2026-11-10) or an ISO time (2026-11-10T09:00:00+10:00).`,
48
+ };
49
+ if (date.getTime() <= now)
50
+ return { error: `--until ${text} has already passed; give a date or time still to come.` };
51
+ return { until: date.toISOString() };
52
+ }
53
+
54
+ /**
55
+ * Holds each of `stories` (upper-cased ids) with `reason`, until `until` (ISO) or until released. A
56
+ * story already held takes the new reason and end. Returns the holds made.
57
+ */
58
+ export function deferStories(
59
+ root,
60
+ stories,
61
+ { reason, until = null, session = null },
62
+ now = Date.now(),
63
+ ) {
64
+ const ids = [...new Set(stories.map((s) => s.toUpperCase()))];
65
+ const at = new Date(now).toISOString();
66
+ const made = ids.map((story) => ({
67
+ story,
68
+ reason,
69
+ until,
70
+ at,
71
+ ...(session ? { session } : {}),
72
+ }));
73
+ // Holds that ended are dropped as the list is written: only those in force are worth keeping.
74
+ writeAll(root, [
75
+ ...readAll(root).filter((h) => inForce(h, now) && !ids.includes(h.story)),
76
+ ...made,
77
+ ]);
78
+ return made;
79
+ }
80
+
81
+ /** Releases each of `stories`; returns the holds it ended (none for a story that wasn't held). */
82
+ export function releaseStories(root, stories, now = Date.now()) {
83
+ const ids = new Set(stories.map((s) => s.toUpperCase()));
84
+ const all = readAll(root);
85
+ const ended = all.filter((h) => ids.has(h.story) && inForce(h, now));
86
+ if (ended.length || all.some((h) => !inForce(h, now)))
87
+ writeAll(
88
+ root,
89
+ all.filter((h) => !ids.has(h.story) && inForce(h, now)),
90
+ );
91
+ return ended;
92
+ }
93
+
94
+ /** A local time as "2026-11-10", or "2026-11-10 09:30" when it isn't midnight. */
95
+ function localTime(iso) {
96
+ const d = new Date(iso);
97
+ const two = (n) => String(n).padStart(2, '0');
98
+ const day = `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())}`;
99
+ return d.getHours() || d.getMinutes()
100
+ ? `${day} ${two(d.getHours())}:${two(d.getMinutes())}`
101
+ : day;
102
+ }
103
+
104
+ /** A hold in words: "ST-4 is held until 2026-11-10: waiting on the partner's API". */
105
+ export function deferralWords(h) {
106
+ return `${h.story} is held${h.until ? ` until ${localTime(h.until)}` : ''}: ${h.reason}`;
107
+ }