@warren-dean/code-kit 0.32.0 → 0.34.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.
package/bin/code-kit.mjs CHANGED
@@ -246,6 +246,7 @@ import {
246
246
  } from '../hooks/lib/worktrees.mjs';
247
247
  import { decisionsFor, openDecisions } from '../hooks/lib/decisionstore.mjs';
248
248
  import { WORKFLOWS_DIR, ciFindings, ciUsage, releaseBranch } from '../hooks/lib/ci.mjs';
249
+ import { COST_APPROVAL, costReport, infraFiles, money } from '../hooks/lib/costs.mjs';
249
250
  import {
250
251
  appliesTo,
251
252
  projectStandards,
@@ -584,6 +585,7 @@ const VERIFY_GROUPS = {
584
585
  tests: 'Weakened tests',
585
586
  regression: 'Fixes and their tests',
586
587
  standards: 'Standards',
588
+ cost: 'Running cost',
587
589
  checks: 'Checks',
588
590
  };
589
591
 
@@ -1823,6 +1825,56 @@ function settings() {
1823
1825
  );
1824
1826
  }
1825
1827
 
1828
+ /**
1829
+ * COST-3: each environment's estimated running cost from the register, against the budget the person
1830
+ * set, with what's wrong with the register and the prices to recheck. Exits 1 when anything's wrong.
1831
+ */
1832
+ function costCommand() {
1833
+ const { config } = load();
1834
+ const root = resolve('.');
1835
+ const cost = config.cost;
1836
+ const some = (files) => `${files.slice(0, 3).join(', ')}${files.length > 3 ? ', …' : ''}`;
1837
+ if (!cost) {
1838
+ const infra = infraFiles(root);
1839
+ if (flag('--json'))
1840
+ return (out(JSON.stringify({ budget: null, infra }, null, 2)), process.exit(1));
1841
+ out(
1842
+ `No running budget is set${infra.length ? `, and the project has infrastructure (${some(infra)})` : ''}. The person sets how much a month each environment may cost; /code-kit:init asks for it and writes it to "cost" in ${file}.`,
1843
+ );
1844
+ process.exit(1);
1845
+ }
1846
+ const report = costReport(root, config);
1847
+ const infra = cost.paths.length ? infraFiles(root, cost.paths) : [];
1848
+ if (!report.exists && infra.length)
1849
+ report.problems.unshift(
1850
+ `There is no cost register (${report.file}), but the project has infrastructure (${some(infra)}). The lead costs it there: a row per paid thing, with its monthly estimate and where the price came from.`,
1851
+ );
1852
+ if (flag('--json')) {
1853
+ out(JSON.stringify({ budget: cost, ...report, infra }, null, 2));
1854
+ process.exit(report.problems.length ? 1 : 0);
1855
+ }
1856
+ out(
1857
+ `Running cost against the budget, ${cost.currency} a month${cost.load ? `, for ${cost.load}` : ''}${report.exists ? `, from ${report.file}` : `; no register yet (${report.file})`}:`,
1858
+ );
1859
+ for (const e of report.environments)
1860
+ out(
1861
+ ` ${e.name.padEnd(10)} ${money(e.total).padStart(9)} of ${money(e.budget)}${e.over > 0 ? `, ${money(e.over)} over` : ''}`,
1862
+ );
1863
+ for (const r of report.rows)
1864
+ out(
1865
+ ` ${r.environment.padEnd(8)} ${String(r.monthly).padStart(9)} ${r.item}${r.provider ? ` (${[r.provider, r.size].filter(Boolean).join(', ')})` : ''}`,
1866
+ );
1867
+ if (report.problems.length)
1868
+ out(`\nProblems:\n${report.problems.map((p) => ` ${p}`).join('\n')}`);
1869
+ if (report.stale.length)
1870
+ out(`\nPrices to recheck:\n${report.stale.map((p) => ` ${p}`).join('\n')}`);
1871
+ if (report.environments.some((e) => e.over > 0))
1872
+ out(
1873
+ "\nOver the budget, the lead brings the person options that fit (smaller sizes, cheaper tiers or providers, fewer environments, less at launch), each with what it gives up. A commit that raises a total past its budget needs the person's cost approval.",
1874
+ );
1875
+ if (report.problems.length) process.exit(1);
1876
+ }
1877
+
1826
1878
  /**
1827
1879
  * CIC-2, CIC-4: `ci check` lists what in the project's workflows multiplies their cost with a story per
1828
1880
  * branch; `ci usage` sums the Actions runs of the last days, by workflow and trigger.
@@ -2352,7 +2404,12 @@ async function approve(given) {
2352
2404
  );
2353
2405
  if (laneName !== undefined && !config.lanes[laneName])
2354
2406
  die(`There is no lane "${laneName}". Lanes: ${Object.keys(config.lanes).join(', ')}.`);
2355
- const known = new Set(['kit', TESTS_APPROVAL, ...config.protected.map((p) => p.approval)]);
2407
+ const known = new Set([
2408
+ 'kit',
2409
+ TESTS_APPROVAL,
2410
+ COST_APPROVAL,
2411
+ ...config.protected.map((p) => p.approval),
2412
+ ]);
2356
2413
  const isPackage = (n) => /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(n);
2357
2414
  const names = given.map((n) =>
2358
2415
  n.startsWith(DEPENDENCY_APPROVAL) || known.has(n) || !isPackage(n) ? n : dependencyApproval(n),
@@ -3119,6 +3176,8 @@ function instructionsCommand() {
3119
3176
  const said = {
3120
3177
  current: 'up to date',
3121
3178
  stale: 'from an older code-kit or config; --write brings it up to date',
3179
+ ahead:
3180
+ 'from a newer code-kit than this one; --write leaves it. Run /plugin marketplace update code-kit and restart Claude Code',
3122
3181
  missing: 'none yet; --write adds it',
3123
3182
  legacy: 'written before code-kit marked its part; merge it once, by hand (below)',
3124
3183
  };
@@ -3442,6 +3501,7 @@ const commands = {
3442
3501
  timeline,
3443
3502
  'sent-back': () => (rest.length === 1 ? sentBackCommand(rest[0]) : usage()),
3444
3503
  ci: ciCommand,
3504
+ cost: () => (rest.length === 0 ? costCommand() : usage()),
3445
3505
  release: () => (rest.length === 1 ? releaseCommand(rest[0]) : usage()),
3446
3506
  replay: () => (rest.length === 1 ? replayCommand(rest[0]) : usage()),
3447
3507
  reconcile: () => (rest.length <= 1 ? reconcileCommand(rest[0]) : usage()),
@@ -3481,6 +3541,7 @@ function usage() {
3481
3541
  ' | who | task "<what>" --touches globs | task done | task take <session>\n' +
3482
3542
  ' | decisions [--json] [--all]\n' +
3483
3543
  ' | ci check [--json] | ci usage [--days N] [--json] | release <version>\n' +
3544
+ ' | cost [--json]\n' +
3484
3545
  ' | hold <id> [--minutes N] | hold <id> --answer approved|refused\n' +
3485
3546
  ' | queue [--json] | queue add|drop <branch> | queue rules | queue merge --delegated|--person\n' +
3486
3547
  ' | queue pause --reason "…" | queue resume\n' +
@@ -8,6 +8,7 @@
8
8
  import { appendFileSync, existsSync, readFileSync, realpathSync } from 'node:fs';
9
9
  import { spawnSync } from 'node:child_process';
10
10
  import { basename, dirname, join, resolve, sep } from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
11
12
  import {
12
13
  addedPackages,
13
14
  dependencyApproval,
@@ -37,6 +38,7 @@ import { historyWrites, storyMerges } from './lib/queue.mjs';
37
38
  import { approverOf } from './lib/journal.mjs';
38
39
  import { loginHere } from './lib/sessions.mjs';
39
40
  import { TESTS_APPROVAL, commitWeakenings } from './lib/regression.mjs';
41
+ import { COST_APPROVAL, overBudget, overWords, registerFile } from './lib/costs.mjs';
40
42
  import {
41
43
  STANDARDS_APPROVAL,
42
44
  noteFor,
@@ -100,7 +102,7 @@ const ALWAYS = [
100
102
  ],
101
103
  [
102
104
  /approval-log\.jsonl/,
103
- "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, piped 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; other commands may come before or after it with ; or &&, if none defines a function or alias or sets a variable. Run the read in that form, or read the file with the Read tool, which can't write.",
105
+ "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, piped 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; other commands may come before or after it with ; or &&, if none defines a function or alias, exports a variable or sets one a command reads, such as PATH. Run the read in that form, or read the file with the Read tool, which can't write. To put it back as the last commit has it (after a `git revert --no-commit` or `git cherry-pick --no-commit` took entries out), run `git restore --staged --worktree .claude/approval-log.jsonl` in the same form, and commit in a command after it.",
104
106
  unreadNames(cmd, /approval-log\.jsonl/).join('\n'),
105
107
  ],
106
108
  ];
@@ -657,6 +659,39 @@ function recordApprovals() {
657
659
  );
658
660
  }
659
661
  }
662
+ // COST-5: a commit that takes an environment's estimated running cost past its budget, or further
663
+ // past it, waits for the person's cost approval (never the lead's), which records what it allowed.
664
+ const costRegister = config.cost ? registerFile(config) : null;
665
+ const overCost =
666
+ costRegister &&
667
+ files.includes(costRegister) &&
668
+ !arrivesWithMerge(root, costRegister, { staged: true })
669
+ ? overBudget(
670
+ git('show', `HEAD:${costRegister}`),
671
+ existsSync(join(root, costRegister))
672
+ ? readFileSync(join(root, costRegister), 'utf8')
673
+ : '',
674
+ config.cost,
675
+ )
676
+ : [];
677
+ if (overCost.length) {
678
+ const granted = approval(root, COST_APPROVAL, actor);
679
+ if (!granted || granted.reason.includes(delegatedMark('').slice(0, -1))) {
680
+ const over = overWords(overCost, config.cost.currency);
681
+ recordRequest(root, actor, COST_APPROVAL, costRegister, `Over the running budget: ${over}.`);
682
+ const personOnly = { ...config, approvals: { ...config.approvals, delegate: null } };
683
+ block(
684
+ `Blocked: this commit takes the estimated running cost past the budget the person set: ${over}. Going past the budget is the person's call, never the lead's. First find options that fit it: a smaller size, a cheaper tier or provider, one environment instead of two, a service the product can do without at launch, or less scope, each with what it gives up. ${askHowTo(COST_APPROVAL, actor, root, personOnly, { allows: 'one commit over the running budget', need: 'the change, what it costs a month against the budget, and the options that fit, each with what it gives up' })}`,
685
+ );
686
+ }
687
+ record(costRegister, {
688
+ approval: COST_APPROVAL,
689
+ reason: granted.reason,
690
+ grantedAt: granted.grantedAt,
691
+ over: overCost,
692
+ });
693
+ useApproval(root, COST_APPROVAL, actor);
694
+ }
660
695
  // The commit that switches code-kit on: the person approved the setup it holds as init showed it.
661
696
  const setup = settingUp && files.includes(CONFIG_FILE) && beforeSetup(root);
662
697
  for (const file of files) {
@@ -796,12 +831,12 @@ ${approvalHowTo(TESTS_APPROVAL, actor, root, 'weakening tests in one commit', pe
796
831
  // The commit hook judges what the commit holds before the command runs, so a file a command earlier in
797
832
  // the chain writes (a formatter, a script, a heredoc) can't be seen, and would go in unjudged and
798
833
  // unlogged. Before the commit, a chain may only move into the checkout, make a branch where it stands
799
- // (no start point, so no file changes), stage or unstage, make folders, take away a worktree (keepsFiles)
834
+ // (no start point, or one at the commit the checkout is at, so no file changes), stage or unstage, make folders, take away a worktree (keepsFiles)
800
835
  // and run commands that only read (lib/shell.mjs readsOnly: git's status, diff, log and show among them,
801
836
  // with no output file), or that write only outside the checkout (writesOutside). Errors sent into the
802
837
  // output or /dev/null write no file.
803
838
  const BEFORE_COMMIT = new RegExp(
804
- String.raw`^(?:cd\s|${GIT}(?:add|rm|mv|restore\s+--staged|reset\s+--soft)(?![\w-])|${GIT}(?:switch\s+(?:-q\s+|--quiet\s+)*(?:-c|--create)|checkout\s+(?:-q\s+|--quiet\s+)*-b)\s+[^\s-]\S*\s*$)`,
839
+ String.raw`^(?:cd\s|${GIT}(?:add|rm|mv|restore\s+--staged|reset\s+--soft)(?![\w-])|${GIT}(?:switch\s+(?:-q\s+|--quiet\s+)*(?:-q?c|--create)|checkout\s+(?:-q\s+|--quiet\s+)*-q?b)\s+[^\s-]\S*\s*$)`,
805
840
  );
806
841
  // Setting shell variables (`f=docs/x.md`, `export MSG="…"`) writes no file, unless a value runs a
807
842
  // command. What a later `git add "$f"` stages can't be read, so it counts as every changed file.
@@ -812,15 +847,25 @@ const assignsOnly = (c) => ASSIGNS_ONLY.test(c.code) && !/`|\$\(|<\(/.test(c.tex
812
847
  const recordsOnly = (c) =>
813
848
  !/[<>]/.test(c.code) && (config.shell.records ?? []).some((re) => new RegExp(re).test(c.text));
814
849
  // What changes no file a commit could take: making folders (git keeps no empty folder), taking away a
815
- // worktree, which is a checkout of its own, and unstaging (`git reset [HEAD] [--] [<paths>]`, which
816
- // leaves the files as they are). A reset to another commit with no paths moves HEAD, so it counts.
850
+ // worktree, which is a checkout of its own, unstaging (`git reset [HEAD] [--] [<paths>]`, which
851
+ // leaves the files as they are) and making a branch at the commit the checkout is at. A reset to another commit with no paths moves HEAD, so it counts.
817
852
  const KEEPS_FILES = new RegExp(String.raw`^(?:mkdir\s|${GIT}worktree\s+(?:remove|prune)(?![\w-]))`);
853
+ // A branch made at a start point that is the commit the checkout is at already: no file changes.
854
+ const BRANCHES_AT =
855
+ /^git\s+(?:switch\s+(?:-q\s+|--quiet\s+)*(?:-q?c|--create)|checkout\s+(?:-q\s+|--quiet\s+)*-q?b)\s+[^\s-]\S*\s+([^\s-$`]\S*)\s*$/;
856
+ const commitOf = (ref) =>
857
+ spawnSync('git', ['-C', root, 'rev-parse', '--verify', '--quiet', `${ref}^{commit}`], {
858
+ encoding: 'utf8',
859
+ }).stdout.trim();
818
860
  const RESETS = new RegExp(String.raw`^${GIT}reset((?:\s+\S+)*)\s*$`);
819
861
  const isCommit = (w) =>
820
862
  spawnSync('git', ['-C', root, 'rev-parse', '--verify', '--quiet', `${w}^{commit}`]).status === 0;
821
863
  function keepsFiles(c) {
822
864
  if (/[<>]/.test(c.code)) return false;
823
865
  if (KEEPS_FILES.test(c.text)) return true;
866
+ const start = c.text.match(BRANCHES_AT)?.[1];
867
+ if (start && !/[$`]/.test(start))
868
+ return commitOf(start) !== '' && commitOf(start) === commitOf('HEAD');
824
869
  const reset = c.text.match(RESETS);
825
870
  if (!reset) return false;
826
871
  const words = reset[1].trim().split(/\s+/).filter(Boolean);
@@ -843,20 +888,64 @@ function realOf(p) {
843
888
  }
844
889
  return join(realpathSync(at), ...tail);
845
890
  }
891
+ const STATE_DIR = '.claude/state';
846
892
  const within = (p, dir) => p === dir || p.startsWith(dir.endsWith(sep) ? dir : dir + sep);
847
893
  function outsideCheckout(p) {
848
894
  if (!p.startsWith('/') || /[$`*?{}[\]~]/.test(p)) return false;
849
895
  const real = realOf(p);
850
896
  return ![project, root].some((r) => within(real, realOf(r)));
851
897
  }
852
- // What writes only outside the checkout (a message drafted in a scratchpad for `git commit -F`): a read
853
- // whose output goes only to such paths, or sed's substitutions on such files in place.
898
+ // A path in code-kit's own state folder (a lane's report), which the project's .gitignore keeps out of
899
+ // any commit. A relative path is read from where the command runs, so one that moves elsewhere on the
900
+ // way, or commits in another repository, doesn't pass.
901
+ function inOwnState(p) {
902
+ if (/[$`*?{}[\]~]/.test(p)) return false;
903
+ if (!p.startsWith('/')) {
904
+ const moves = commandsOf(cmd).filter((c) => /^(?:cd|pushd|popd)\b/.test(c.text));
905
+ if (/\bgit\s+-C\b/.test(cmd) || moves.length > (/^\s*cd\s/.test(cmd) ? 1 : 0)) return false;
906
+ }
907
+ const real = realOf(resolve(input.cwd || project, gitDir ?? '.', p));
908
+ if (within(real, join(realOf(project), STATE_DIR)) && realOf(project) !== realOf(root))
909
+ return true;
910
+ if (!within(real, join(realOf(root), STATE_DIR))) return false;
911
+ return spawnSync('git', ['-C', root, 'check-ignore', '-q', real]).status === 0;
912
+ }
913
+ // What writes only where no commit can take it (a message drafted in a scratchpad for `git commit -F`,
914
+ // a lane's report): a read whose output goes only to such paths, or sed's substitutions in place on
915
+ // files outside the checkout.
854
916
  function writesOutside(c) {
855
917
  const out = outputRedirects(c.whole);
856
- if (!out?.targets.every(outsideCheckout)) return false;
918
+ if (!out?.targets.every((t) => outsideCheckout(t) || inOwnState(t))) return false;
857
919
  if (out.targets.length && readsOnly(out.rest)) return true;
858
920
  return sedInPlaceFiles(out.rest.trim())?.every(outsideCheckout) ?? false;
859
921
  }
922
+ // code-kit's own commands that write only its state folder (a question, a hold, a send-back, the merge
923
+ // queue's entries), or only read: run by this code-kit's own CLI, by its path or through a variable the
924
+ // line sets to it, with no redirect of their own, where the project ignores the state folder.
925
+ const KIT_CLI = realOf(join(dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'code-kit.mjs'));
926
+ const KIT_RECORDS =
927
+ /^(?:ask|defer|sent-back|reconcile|requests\s+drop|queue(?:\s+(?:add|drop|pause|resume))?|next|status|who|trace)(?:\s|$)/;
928
+ function kitRecordsOnly(c) {
929
+ if (/[<>]/.test(c.code) || /(?:^|\s)--write(?:\s|$)/.test(c.code)) return false;
930
+ const run = c.text.match(/^node\s+(?:"([^"]+)"|'([^']+)'|(\S+))\s+(.*)$/s);
931
+ if (!run || !KIT_RECORDS.test(run[4])) return false;
932
+ let path = run[1] ?? run[2] ?? run[3];
933
+ const variable = path.match(/^\$\{?([A-Za-z_]\w*)\}?$/)?.[1];
934
+ if (variable) {
935
+ const set = [
936
+ ...cmd.matchAll(
937
+ new RegExp(
938
+ String.raw`(?:^|[;&|\n]\s*)(?:export\s+)?${variable}=(?:"([^"$\`]+)"|'([^']+)'|([^\s"'$\`;&|]+))`,
939
+ 'g',
940
+ ),
941
+ ),
942
+ ];
943
+ if (set.length !== 1) return false;
944
+ path = set[0][1] ?? set[0][2] ?? set[0][3];
945
+ }
946
+ if (/[$\`]/.test(path) || realOf(resolve(input.cwd || project, path)) !== KIT_CLI) return false;
947
+ return spawnSync('git', ['-C', root, 'check-ignore', '-q', join(root, STATE_DIR)]).status === 0;
948
+ }
860
949
  function writesBeforeCommit() {
861
950
  const pieces = commandsOf(withoutHarmlessRedirects(cmd));
862
951
  const at = pieces.findIndex((c) => new RegExp(String.raw`^${GIT}commit(?![\w-])`).test(c.text));
@@ -868,6 +957,7 @@ function writesBeforeCommit() {
868
957
  !readsOnly(c.whole) &&
869
958
  !assignsOnly(c) &&
870
959
  !recordsOnly(c) &&
960
+ !kitRecordsOnly(c) &&
871
961
  !keepsFiles(c) &&
872
962
  !writesOutside(c),
873
963
  );
@@ -7,7 +7,9 @@
7
7
  // project's installs in and deleting them again on every merge is millions of files each time, which
8
8
  // keeps the machine's file-change tracking and search indexing busy. Each run checks out the tree it
9
9
  // needs, and installs again only where its manifests and lockfiles differ from the ones the kept
10
- // installs were made for. The folder's name ends in .noindex, which Spotlight leaves alone.
10
+ // installs were made for. The folder's name ends in .noindex, which Spotlight leaves alone. The OS
11
+ // empties old files out of its temporary folder and leaves the folders and links, so a run counts the
12
+ // kept installs' files, and copies them again when any have gone.
11
13
  import { createHash } from 'node:crypto';
12
14
  import { execFileSync, spawnSync } from 'node:child_process';
13
15
  import {
@@ -16,6 +18,7 @@ import {
16
18
  mkdirSync,
17
19
  mkdtempSync,
18
20
  openSync,
21
+ readdirSync,
19
22
  readFileSync,
20
23
  realpathSync,
21
24
  rmSync,
@@ -106,6 +109,26 @@ function dependencyHashes(dir) {
106
109
  return hashes;
107
110
  }
108
111
 
112
+ // The files in a kept checkout's installs, and how many there were when they were made. Tools' caches
113
+ // come and go on their own, so they don't count. A folder that can't be read counts as empty.
114
+ const countOf = (dir) => `${dir}.installs.count`;
115
+ function installedFiles(dir) {
116
+ let files = 0;
117
+ for (const rel of installsOf(dir)) {
118
+ try {
119
+ for (const e of readdirSync(join(dir, rel), { recursive: true, withFileTypes: true }))
120
+ if (e.isFile() && !/[\\/]\.cache(?:[\\/]|$)/.test(e.parentPath)) files++;
121
+ } catch {
122
+ // gone while being read: fewer files, so it's copied again
123
+ }
124
+ }
125
+ return files;
126
+ }
127
+ const recordInstalled = (dir) => writeFileSync(countOf(dir), String(installedFiles(dir)));
128
+ /** Whether a kept checkout's installs have lost files, or lost the records of what they were made for. */
129
+ const hollow = (dir) =>
130
+ !existsSync(stampOf(dir)) || !(installedFiles(dir) >= Number(readFileSafe(countOf(dir)) || NaN));
131
+
109
132
  /** Takes the kept checkout's lock for this process, or false while another live process holds it. */
110
133
  function lock(slot) {
111
134
  const file = `${slot}.lock`;
@@ -243,10 +266,19 @@ export function freshCheckout(
243
266
  throw Object.assign(new Error(why || 'the merge conflicts'), { conflict: true });
244
267
  }
245
268
  }
269
+ // MQ-9: the OS took files out of the kept installs: they can't be trusted, so they're copied again.
270
+ // What they're copied from may be behind the base by now, so the stamp names nothing, and the
271
+ // project's install runs over the copy for this tree.
272
+ const emptied = installsFrom && dir === slot && installsOf(dir).length > 0 && hollow(dir);
273
+ if (emptied)
274
+ for (const rel of installsOf(dir)) rmSync(join(dir, rel), { recursive: true, force: true });
246
275
  if (installsFrom && !installsOf(dir).length) {
247
276
  copyInstalls(installsFrom, dir);
248
277
  // The copied installs were made for installsFrom's manifests and lockfiles.
249
- if (dir === slot) writeFileSync(stampOf(dir), JSON.stringify(dependencyHashes(installsFrom)));
278
+ if (dir === slot) {
279
+ writeFileSync(stampOf(dir), JSON.stringify(emptied ? {} : dependencyHashes(installsFrom)));
280
+ recordInstalled(dir);
281
+ }
250
282
  }
251
283
  return { dir, remove };
252
284
  }
@@ -351,7 +383,10 @@ export function matchInstalls(dir, from, { prepare = null, timeout = 900000 } =
351
383
  const stamp = stampOf(dir);
352
384
  if (res.status === 0) {
353
385
  // A kept checkout's installs now match this tree.
354
- if (existsSync(stamp)) writeFileSync(stamp, JSON.stringify(dependencyHashes(dir)));
386
+ if (existsSync(stamp)) {
387
+ writeFileSync(stamp, JSON.stringify(dependencyHashes(dir)));
388
+ recordInstalled(dir);
389
+ }
355
390
  return { ...facts, command, failed: null };
356
391
  }
357
392
  // What a failed install left can't be trusted: the next run copies the installs afresh.
@@ -5,6 +5,7 @@ import { existsSync, readFileSync } from 'node:fs';
5
5
  import { VIBE, harnessProblems, harnessSettings } from './harness.mjs';
6
6
  import { teamProblems } from './team.mjs';
7
7
  import { join } from 'node:path';
8
+ import { DEFAULT_REGISTER } from './costs.mjs';
8
9
  import { ADAPTERS, applyAdapters } from './adapters/index.mjs';
9
10
 
10
11
  export const CONFIG_FILE = '.claude/code-kit.json';
@@ -82,7 +83,12 @@ export function withDefaults(c) {
82
83
  paths: [...c.lead.paths, '.claude/**', '.mcp.json'],
83
84
  outside: [...(c.lead.outside ?? []), ...CLAUDE_OWN],
84
85
  },
85
- anyActor: [...(c.anyActor ?? []).map(anyActorGlob), '.claude/state/**'],
86
+ // Spec 29: the cost register, which a lane changes with the infrastructure its story adds.
87
+ anyActor: [
88
+ ...(c.anyActor ?? []).map(anyActorGlob),
89
+ '.claude/state/**',
90
+ ...(c.cost ? [c.docs?.costs ?? DEFAULT_REGISTER] : []),
91
+ ],
86
92
  // Who reviews changes to files any agent may write; the lead unless an entry names a lane.
87
93
  anyActorReviewers: (c.anyActor ?? [])
88
94
  .filter((e) => typeof e === 'object' && e?.reviewer)
@@ -108,6 +114,14 @@ export function withDefaults(c) {
108
114
  : delegateRules(c.approvals?.delegate, c.protected ?? []),
109
115
  },
110
116
  harness: harnessSettings(c.harness),
117
+ cost: c.cost
118
+ ? {
119
+ currency: c.cost.currency,
120
+ monthly: c.cost.monthly,
121
+ load: c.cost.load ?? null,
122
+ paths: c.cost.paths ?? [],
123
+ }
124
+ : null,
111
125
  };
112
126
  }
113
127
 
@@ -363,7 +377,7 @@ export function validate(c) {
363
377
  );
364
378
  // A brownfield project may have no specs yet: then there is no spec-check gate.
365
379
  need(c.docs === undefined || isObj(c.docs), '"docs" must be an object');
366
- for (const k of ['specs', 'principles', 'plan', 'decisions', 'standards'])
380
+ for (const k of ['specs', 'principles', 'plan', 'decisions', 'standards', 'costs'])
367
381
  need(c.docs?.[k] === undefined || isStr(c.docs[k]), `"docs.${k}" must be a path`);
368
382
  need(isObj(c.lead) && isList(c.lead?.paths), '"lead.paths" must be a list of globs');
369
383
  need(
@@ -465,11 +479,38 @@ export function validate(c) {
465
479
  [undefined, 'push', 'pull-request'].includes(c.branches?.publish),
466
480
  '"branches.publish" must be "push" or "pull-request": how merges reach the remote\'s base',
467
481
  );
482
+ if (c.cost !== undefined) validateCost(c.cost, need);
468
483
  p.push(...harnessProblems(c.harness));
469
484
  p.push(...teamProblems(c));
470
485
  return p;
471
486
  }
472
487
 
488
+ // Spec 29: the running budget the person set, per environment, in one currency.
489
+ function validateCost(cost, need) {
490
+ if (!need(isObj(cost), '"cost" must be an object: { currency, monthly, load?, paths? }')) return;
491
+ need(
492
+ /^[A-Z]{3}$/.test(cost.currency ?? ''),
493
+ '"cost.currency" must be a three-letter currency code, such as USD, AUD or EUR',
494
+ );
495
+ need(
496
+ isObj(cost.monthly) &&
497
+ Object.keys(cost.monthly).length > 0 &&
498
+ Object.entries(cost.monthly).every(
499
+ ([env, v]) =>
500
+ /^[a-z][a-z0-9-]*$/.test(env) && env !== 'all' && typeof v === 'number' && v >= 0,
501
+ ),
502
+ '"cost.monthly" must map each environment (a lower-case name such as prod or dev, not "all") to its monthly budget, a number of 0 or more',
503
+ );
504
+ need(
505
+ cost.load === undefined || isStr(cost.load),
506
+ '"cost.load" must say, in words, the load the budget plans for',
507
+ );
508
+ need(
509
+ cost.paths === undefined || isList(cost.paths),
510
+ '"cost.paths" must be a list of globs: the infrastructure files',
511
+ );
512
+ }
513
+
473
514
  /** A deliverable kind's name (a layer's or lane's `label`): one line, at most 60 characters. */
474
515
  const isLabel = (v) => isStr(v) && v.trim().length > 0 && v.length <= 60 && !/[\r\n]/.test(v);
475
516