@warren-dean/code-kit 0.31.1 → 0.33.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.
@@ -3,12 +3,31 @@
3
3
  // taken out (REG-1). It's a temporary worktree with its own copy of the installs (node_modules and
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
+ // MQ-9: the checkout is kept between runs, one per project and use, with its installs: copying a
7
+ // project's installs in and deleting them again on every merge is millions of files each time, which
8
+ // keeps the machine's file-change tracking and search indexing busy. Each run checks out the tree it
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.
11
+ import { createHash } from 'node:crypto';
6
12
  import { execFileSync, spawnSync } from 'node:child_process';
7
- import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
13
+ import {
14
+ closeSync,
15
+ existsSync,
16
+ mkdirSync,
17
+ mkdtempSync,
18
+ openSync,
19
+ readFileSync,
20
+ realpathSync,
21
+ rmSync,
22
+ writeFileSync,
23
+ } from 'node:fs';
8
24
  import { platform, tmpdir } from 'node:os';
9
- import { basename, dirname, join } from 'node:path';
25
+ import { basename, dirname, join, resolve } from 'node:path';
10
26
  import { isDependencyFile } from './dependencies.mjs';
11
27
 
28
+ /** Where the kept checkouts live: in the temporary folder, out of Spotlight's index. */
29
+ export const CHECKOUTS_DIR = join(tmpdir(), 'code-kit-checkouts.noindex');
30
+
12
31
  // The folders an install puts beside the code, which a fresh checkout lacks.
13
32
  const INSTALLS = new Set(['node_modules', '.venv', 'venv']);
14
33
 
@@ -51,32 +70,155 @@ export function copyInstalls(root, dir) {
51
70
  }
52
71
  }
53
72
 
73
+ const real = (p) => {
74
+ try {
75
+ return realpathSync(p);
76
+ } catch {
77
+ return p;
78
+ }
79
+ };
80
+
81
+ /** The kept checkout for `root` and this use (`prefix`), the project's main checkout's. */
82
+ export function keptCheckoutOf(root, prefix) {
83
+ let main = root;
84
+ try {
85
+ main = dirname(real(resolve(root, git(root, 'rev-parse', '--git-common-dir').trim())));
86
+ } catch {
87
+ // not a repository: its own folder names it
88
+ }
89
+ const id = createHash('sha256').update(real(main)).digest('hex').slice(0, 10);
90
+ return join(CHECKOUTS_DIR, `${basename(main)}-${id}-${prefix.replace(/^code-kit-|-$/g, '')}`);
91
+ }
92
+
93
+ /** The manifests and lockfiles the installs in a kept checkout were made for, by content hash. */
94
+ const stampOf = (dir) => `${dir}.installs.json`;
95
+ function dependencyHashes(dir) {
96
+ const hashes = {};
97
+ for (const f of trackedDependencies(dir)) {
98
+ try {
99
+ hashes[f] = createHash('sha256')
100
+ .update(readFileSync(join(dir, f)))
101
+ .digest('hex');
102
+ } catch {
103
+ hashes[f] = null;
104
+ }
105
+ }
106
+ return hashes;
107
+ }
108
+
109
+ /** Takes the kept checkout's lock for this process, or false while another live process holds it. */
110
+ function lock(slot) {
111
+ const file = `${slot}.lock`;
112
+ for (let tries = 0; tries < 2; tries++) {
113
+ try {
114
+ const fd = openSync(file, 'wx');
115
+ writeFileSync(fd, String(process.pid));
116
+ closeSync(fd);
117
+ return () => rmSync(file, { force: true });
118
+ } catch {
119
+ const pid = Number(readFileSafe(file));
120
+ let alive = false;
121
+ try {
122
+ alive = pid > 0 && process.kill(pid, 0);
123
+ } catch {
124
+ alive = false;
125
+ }
126
+ if (alive) return false;
127
+ rmSync(file, { force: true });
128
+ }
129
+ }
130
+ return false;
131
+ }
132
+ const readFileSafe = (f) => {
133
+ try {
134
+ return readFileSync(f, 'utf8');
135
+ } catch {
136
+ return '';
137
+ }
138
+ };
139
+
140
+ /** Whether `dir` is one of `root`'s worktrees now. */
141
+ const isWorktreeOf = (root, dir) => {
142
+ try {
143
+ return git(root, 'worktree', 'list', '--porcelain')
144
+ .split('\n')
145
+ .some((l) => l.startsWith('worktree ') && real(l.slice(9)) === real(dir));
146
+ } catch {
147
+ return false;
148
+ }
149
+ };
150
+
54
151
  /**
55
- * A temporary worktree of `ref` (detached), with `merge` merged into it when given, and the installs
56
- * of `installsFrom` copied in. `{ dir, remove }`; a merge that conflicts throws a `conflict` error
57
- * after removing what it made. `remove` never throws: a folder that won't go is left to the OS.
152
+ * A worktree of `ref` (detached), with `merge` merged into it when given, and installs that were made
153
+ * for a tree: the project's kept checkout for this use (MQ-9), its installs kept from its last run, or
154
+ * where another run holds that one, a temporary worktree. Installs are copied from `installsFrom` only
155
+ * into a checkout that has none (null copies none). `{ dir, remove }`; a merge that conflicts throws a
156
+ * `conflict` error after putting things back. `remove` never throws: it frees the kept checkout, or
157
+ * takes the temporary one away, leaving a folder that won't go to the OS.
58
158
  */
59
159
  export function freshCheckout(
60
160
  root,
61
161
  ref,
62
162
  { merge = null, installsFrom = root, prefix = 'code-kit-' } = {},
63
163
  ) {
64
- const dir = mkdtempSync(join(tmpdir(), prefix));
65
- rmSync(dir, { recursive: true });
66
- git(root, 'worktree', 'add', '--quiet', '--detach', dir, ref);
67
- const remove = () => {
68
- try {
69
- git(root, 'worktree', 'remove', '--force', dir);
70
- } catch {
71
- // git leaves it when a process still writes there; the folder goes, and git prunes its record
164
+ // Named in the project, not in the kept checkout, where HEAD is the last run's.
165
+ ref = git(root, 'rev-parse', '--verify', '--quiet', `${ref}^{commit}`).trim();
166
+ const slot = keptCheckoutOf(root, prefix);
167
+ mkdirSync(CHECKOUTS_DIR, { recursive: true });
168
+ const unlock = lock(slot);
169
+ let dir;
170
+ let remove;
171
+ if (unlock) {
172
+ dir = slot;
173
+ let ready = false;
174
+ if (existsSync(dir) && isWorktreeOf(root, dir)) {
175
+ try {
176
+ // What the last run left (a merge, files a check wrote) goes; the installs stay.
177
+ git(dir, 'reset', '--hard', '--quiet');
178
+ git(dir, 'checkout', '--quiet', '--force', '--detach', ref);
179
+ git(dir, 'clean', '-ffdxq', ...[...INSTALLS].flatMap((i) => ['-e', i]));
180
+ ready = true;
181
+ } catch {
182
+ ready = false;
183
+ }
72
184
  }
73
- try {
185
+ if (!ready) {
186
+ try {
187
+ git(root, 'worktree', 'remove', '--force', dir);
188
+ } catch {
189
+ // not registered, or already gone
190
+ }
74
191
  rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
192
+ rmSync(stampOf(dir), { force: true });
75
193
  git(root, 'worktree', 'prune');
76
- } catch {
77
- // the OS clears its temporary folder
194
+ git(root, 'worktree', 'add', '--quiet', '--detach', dir, ref);
78
195
  }
79
- };
196
+ remove = () => {
197
+ try {
198
+ git(dir, 'merge', '--abort');
199
+ } catch {
200
+ // no merge in progress
201
+ }
202
+ unlock();
203
+ };
204
+ } else {
205
+ dir = mkdtempSync(join(CHECKOUTS_DIR, prefix));
206
+ rmSync(dir, { recursive: true });
207
+ git(root, 'worktree', 'add', '--quiet', '--detach', dir, ref);
208
+ remove = () => {
209
+ try {
210
+ git(root, 'worktree', 'remove', '--force', dir);
211
+ } catch {
212
+ // git leaves it when a process still writes there; the folder goes, and git prunes its record
213
+ }
214
+ try {
215
+ rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
216
+ git(root, 'worktree', 'prune');
217
+ } catch {
218
+ // the OS clears its temporary folder
219
+ }
220
+ };
221
+ }
80
222
  if (merge) {
81
223
  const merged = spawnSync(
82
224
  'git',
@@ -101,24 +243,45 @@ export function freshCheckout(
101
243
  throw Object.assign(new Error(why || 'the merge conflicts'), { conflict: true });
102
244
  }
103
245
  }
104
- copyInstalls(installsFrom, dir);
246
+ if (installsFrom && !installsOf(dir).length) {
247
+ copyInstalls(installsFrom, dir);
248
+ // The copied installs were made for installsFrom's manifests and lockfiles.
249
+ if (dir === slot) writeFileSync(stampOf(dir), JSON.stringify(dependencyHashes(installsFrom)));
250
+ }
105
251
  return { dir, remove };
106
252
  }
107
253
 
254
+ /** The manifests and lockfiles git tracks in `d`. */
255
+ function trackedDependencies(d) {
256
+ try {
257
+ return git(d, 'ls-files')
258
+ .split('\n')
259
+ .filter((f) => f && isDependencyFile(f));
260
+ } catch {
261
+ return [];
262
+ }
263
+ }
264
+
108
265
  /**
109
266
  * The manifests and lockfiles tracked in either checkout whose content differs between the two working
110
267
  * trees: where installs copied from `from` may not match the code in `dir`.
111
268
  */
112
269
  export function dependencyDifferences(from, dir) {
113
- const tracked = (d) => {
270
+ // A kept checkout's installs were made for the files its stamp records, whatever `from` holds now.
271
+ const stamp = readFileSafe(stampOf(dir));
272
+ if (stamp) {
273
+ let made = {};
114
274
  try {
115
- return git(d, 'ls-files')
116
- .split('\n')
117
- .filter((f) => f && isDependencyFile(f));
275
+ made = JSON.parse(stamp);
118
276
  } catch {
119
- return [];
277
+ made = {};
120
278
  }
121
- };
279
+ const now = dependencyHashes(dir);
280
+ return [...new Set([...Object.keys(made), ...Object.keys(now)])]
281
+ .filter((f) => (made[f] ?? null) !== (now[f] ?? null))
282
+ .sort();
283
+ }
284
+ const tracked = trackedDependencies;
122
285
  const read = (d, f) => {
123
286
  try {
124
287
  return readFileSync(join(d, f), 'utf8');
@@ -185,7 +348,17 @@ export function matchInstalls(dir, from, { prepare = null, timeout = 900000 } =
185
348
  const facts = { differ, copied, lockfile: present };
186
349
  if (!command) return { ...facts, command: null, failed: null };
187
350
  const res = spawnSync(command, { cwd: dir, shell: true, encoding: 'utf8', timeout });
188
- if (res.status === 0) return { ...facts, command, failed: null };
351
+ const stamp = stampOf(dir);
352
+ if (res.status === 0) {
353
+ // A kept checkout's installs now match this tree.
354
+ if (existsSync(stamp)) writeFileSync(stamp, JSON.stringify(dependencyHashes(dir)));
355
+ return { ...facts, command, failed: null };
356
+ }
357
+ // What a failed install left can't be trusted: the next run copies the installs afresh.
358
+ if (existsSync(stamp)) {
359
+ rmSync(stamp, { force: true });
360
+ for (const rel of installsOf(dir)) rmSync(join(dir, rel), { recursive: true, force: true });
361
+ }
189
362
  const output = `${res.stdout ?? ''}${res.stderr ?? ''}`.trim().split('\n').slice(-20).join('\n');
190
363
  return {
191
364
  ...facts,
@@ -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
 
@@ -0,0 +1,217 @@
1
+ // Spec 29: what a project costs to run each month. The person sets a budget per environment in the
2
+ // config (`cost`); the lead keeps a register of estimated costs (docs/costs.md, a table with a row per
3
+ // paid thing); code-kit adds the register up against the budget. It knows no provider's prices: every
4
+ // figure is the lead's estimate, with where it came from.
5
+ import { execFileSync } from 'node:child_process';
6
+ import { existsSync, readFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { matchesAny } from './glob.mjs';
9
+
10
+ export const COST_APPROVAL = 'cost';
11
+ export const DEFAULT_REGISTER = 'docs/costs.md';
12
+ // A price older than this is rechecked (COST-7).
13
+ export const STALE_DAYS = 90;
14
+
15
+ /**
16
+ * Infrastructure files, whatever tool defines them, for init's draft of `cost.paths` and for `next`
17
+ * to notice a project with infrastructure and no budget (COST-1, COST-6).
18
+ */
19
+ export const INFRA_GLOBS = [
20
+ '**/*.tf',
21
+ '**/*.tfvars',
22
+ '**/cdk.json',
23
+ '**/Pulumi*.yaml',
24
+ '**/serverless.yml',
25
+ '**/serverless.yaml',
26
+ '**/sst.config.ts',
27
+ '**/docker-compose*.yml',
28
+ '**/docker-compose*.yaml',
29
+ '**/compose.yml',
30
+ '**/compose.yaml',
31
+ '**/fly.toml',
32
+ '**/vercel.json',
33
+ '**/netlify.toml',
34
+ '**/render.yaml',
35
+ '**/wrangler.toml',
36
+ '**/app.yaml',
37
+ '**/supabase/config.toml',
38
+ '**/k8s/**',
39
+ '**/kubernetes/**',
40
+ '**/helm/**',
41
+ 'infra/**',
42
+ 'infrastructure/**',
43
+ 'terraform/**',
44
+ ];
45
+
46
+ /** Where the project keeps its cost register. */
47
+ export const registerFile = (config) => config?.docs?.costs ?? DEFAULT_REGISTER;
48
+
49
+ const cells = (line) =>
50
+ line
51
+ .split('|')
52
+ .slice(1, -1)
53
+ .map((c) => c.trim());
54
+
55
+ /** A Monthly cell as a number (`25`, `7.80`, `$1,200`, `€30`), or null when it isn't one. */
56
+ export function amountOf(text) {
57
+ const m = String(text ?? '')
58
+ .trim()
59
+ .match(/^[$€£¥]?\s*(\d[\d,]*(?:\.\d+)?)$/);
60
+ return m ? Number(m[1].replaceAll(',', '')) : null;
61
+ }
62
+
63
+ /**
64
+ * The register's rows: { line, item, provider, environment, size, monthly, amount, basis }, `amount`
65
+ * null where Monthly isn't a number. `table` is false when the text has no table whose header starts
66
+ * `| Item |` with a Monthly column.
67
+ */
68
+ export function parseRegister(text) {
69
+ const lines = String(text ?? '').split('\n');
70
+ const at = lines.findIndex((l) => /^\|\s*Item\s*\|/i.test(l));
71
+ if (at < 0) return { table: false, rows: [] };
72
+ const columns = cells(lines[at]).map((c) => c.toLowerCase());
73
+ const col = (name) => columns.findIndex((c) => c.startsWith(name));
74
+ if (col('monthly') < 0) return { table: false, rows: [] };
75
+ const rows = [];
76
+ for (let i = at + 1; i < lines.length && /^\|/.test(lines[i]); i++) {
77
+ if (/^\|\s*:?-/.test(lines[i])) continue;
78
+ const c = cells(lines[i]);
79
+ const get = (name) => (col(name) >= 0 ? (c[col(name)] ?? '') : '');
80
+ if (!get('item')) continue;
81
+ rows.push({
82
+ line: i + 1,
83
+ item: get('item'),
84
+ provider: get('provider'),
85
+ environment: get('env').toLowerCase(),
86
+ size: get('size'),
87
+ monthly: get('monthly'),
88
+ amount: amountOf(get('monthly')),
89
+ basis: get('basis'),
90
+ });
91
+ }
92
+ return { table: true, rows };
93
+ }
94
+
95
+ /** Each environment the budget names: { name, total, budget, over }, `all` rows counting in every one. */
96
+ export function totals(rows, cost) {
97
+ return Object.entries(cost?.monthly ?? {}).map(([name, budget]) => {
98
+ const total = rows
99
+ .filter((r) => r.amount !== null && (r.environment === name || r.environment === 'all'))
100
+ .reduce((sum, r) => sum + r.amount, 0);
101
+ const rounded = Math.round(total * 100) / 100;
102
+ return { name, total: rounded, budget, over: Math.round((rounded - budget) * 100) / 100 };
103
+ });
104
+ }
105
+
106
+ /** The money in the budget's currency, as people write it: `130`, `32.80`. */
107
+ export const money = (n, currency) =>
108
+ `${Number.isInteger(n) ? n : n.toFixed(2)}${currency ? ` ${currency}` : ''}`;
109
+
110
+ /** The newest date (YYYY-MM-DD) a Basis names, or null. */
111
+ function basisDate(basis) {
112
+ const dates = String(basis).match(/\d{4}-\d{2}-\d{2}/g);
113
+ const t = dates ? Math.max(...dates.map((d) => Date.parse(d))) : NaN;
114
+ return Number.isFinite(t) ? t : null;
115
+ }
116
+
117
+ /**
118
+ * The register against the budget (COST-3, COST-7): { file, exists, environments, rows, problems, stale }.
119
+ * `problems` are what's wrong (an unreadable row, one without its basis or for an environment the budget
120
+ * doesn't name, no table, a total over its budget); `stale`, the rows whose price is more than 90 days
121
+ * old, to recheck.
122
+ */
123
+ export function costReport(root, config, now = Date.now()) {
124
+ const file = registerFile(config);
125
+ const exists = existsSync(join(root, file));
126
+ return {
127
+ file,
128
+ exists,
129
+ ...readCosts(exists ? readFileSync(join(root, file), 'utf8') : null, config, now),
130
+ };
131
+ }
132
+
133
+ /** costReport's reading of a register's text (null when there's none). */
134
+ export function readCosts(text, config, now = Date.now()) {
135
+ const cost = config?.cost;
136
+ const file = registerFile(config);
137
+ const { table, rows } = parseRegister(text ?? '');
138
+ const environments = totals(rows, cost);
139
+ const names = new Set([...environments.map((e) => e.name), 'all']);
140
+ const problems = [];
141
+ const stale = [];
142
+ if (text !== null && !table)
143
+ problems.push(
144
+ `${file} has no cost table: a table whose header row starts \`| Item |\`, with Provider, Environment, Size, Monthly and Basis columns.`,
145
+ );
146
+ for (const r of rows) {
147
+ const where = `${file}:${r.line} (${r.item})`;
148
+ if (r.amount === null)
149
+ problems.push(
150
+ `${where}: Monthly is "${r.monthly}", not a number. Write the estimate as a number in ${cost?.currency ?? "the budget's currency"}, such as 25 or 7.80.`,
151
+ );
152
+ if (!r.basis)
153
+ problems.push(
154
+ `${where} has no Basis: say where the price came from (the provider's pricing page and the date you read it).`,
155
+ );
156
+ if (!names.has(r.environment))
157
+ problems.push(
158
+ `${where} is for "${r.environment || '(none)'}", which the budget doesn't name. Environments: ${[...names].join(', ')}.`,
159
+ );
160
+ const dated = r.basis ? basisDate(r.basis) : null;
161
+ if (r.basis && (dated === null || now - dated > STALE_DAYS * 86_400_000))
162
+ stale.push(
163
+ `${where}: ${dated === null ? 'its Basis has no date' : `its price was read ${Math.floor((now - dated) / 86_400_000)} days ago`}; recheck it and date the Basis (YYYY-MM-DD).`,
164
+ );
165
+ }
166
+ for (const e of environments)
167
+ if (e.over > 0)
168
+ problems.push(
169
+ `${e.name} is estimated at ${money(e.total, cost.currency)} a month, ${money(e.over, cost.currency)} over its budget of ${money(e.budget, cost.currency)}.`,
170
+ );
171
+ return { environments, rows, problems, stale };
172
+ }
173
+
174
+ /**
175
+ * COST-5: the environments a change to the register takes over budget, or further over it:
176
+ * [{ name, before, after, budget }]. A change that leaves every total within budget, or lowers one
177
+ * that was already over, needs nothing.
178
+ */
179
+ export function overBudget(beforeText, afterText, cost) {
180
+ const before = new Map(
181
+ totals(parseRegister(beforeText ?? '').rows, cost).map((e) => [e.name, e.total]),
182
+ );
183
+ return totals(parseRegister(afterText ?? '').rows, cost)
184
+ .filter((e) => e.over > 0 && e.total > (before.get(e.name) ?? 0))
185
+ .map((e) => ({
186
+ name: e.name,
187
+ before: before.get(e.name) ?? 0,
188
+ after: e.total,
189
+ budget: e.budget,
190
+ }));
191
+ }
192
+
193
+ /** The words for overBudget's environments: "prod would be 130 of 100, 30 over". */
194
+ export const overWords = (over, currency) =>
195
+ over
196
+ .map(
197
+ (e) =>
198
+ `${e.name} would be ${money(e.after, currency)} a month against its budget of ${money(e.budget, currency)}, ${money(Math.round((e.after - e.budget) * 100) / 100, currency)} over (it was ${money(e.before, currency)})`,
199
+ )
200
+ .join('; ');
201
+
202
+ /** The project's tracked files that look like infrastructure (`globs`, INFRA_GLOBS by default). */
203
+ export function infraFiles(root, globs = INFRA_GLOBS) {
204
+ let files = [];
205
+ try {
206
+ files = execFileSync('git', ['-C', root, 'ls-files'], {
207
+ encoding: 'utf8',
208
+ stdio: ['ignore', 'pipe', 'ignore'],
209
+ maxBuffer: 64 * 1024 * 1024,
210
+ })
211
+ .split('\n')
212
+ .filter(Boolean);
213
+ } catch {
214
+ return [];
215
+ }
216
+ return files.filter((f) => matchesAny(f, globs));
217
+ }
@@ -12,6 +12,7 @@ import {
12
12
  standardLine,
13
13
  standardsFile,
14
14
  } from './standards.mjs';
15
+ import { registerFile } from './costs.mjs';
15
16
 
16
17
  /** The version of code-kit's instructions: raised whenever the templates' rules change. */
17
18
  export const INSTRUCTIONS_VERSION = 12;
@@ -68,6 +69,9 @@ function factsOf(root, config, lane = null) {
68
69
  'docs.plan': config.docs?.plan ?? 'the plan',
69
70
  'docs.principles': config.docs?.principles ?? "the project's principles",
70
71
  'docs.standards': standardsFile(config),
72
+ // Spec 29: the running budget and its register.
73
+ cost: Boolean(config.cost),
74
+ 'docs.costs': registerFile(config),
71
75
  standards: laneStandards(root, config, lane),
72
76
  'standards.all': standardsOf(root, config)
73
77
  .map((s) => `${s.id} ${s.title}`)