@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.
@@ -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
+ }
@@ -28,6 +28,21 @@ export const SETTINGS = {
28
28
  about:
29
29
  "How the lead loop acts: on its own, by proposing each step, or not at all; vibe is on its own with every decision the lead's, and you only asked for accounts, keys and payments",
30
30
  },
31
+ 'loop.quietMinutes': {
32
+ default: 10,
33
+ problem: (v) =>
34
+ Number.isFinite(v) && v >= 0 && v <= 120
35
+ ? null
36
+ : 'must be a number of minutes from 0 (off) to 120',
37
+ about:
38
+ "How long the loop waits after you last spoke, while you're talking with the lead about something other than the build; 0 for not at all",
39
+ },
40
+ 'loop.check': {
41
+ default: true,
42
+ problem: (v) => (typeof v === 'boolean' ? null : 'must be true or false'),
43
+ about:
44
+ "Check each step against the project as it is now (git, the queue, the agents at work, the lead's last replies) before the lead is prompted with it",
45
+ },
31
46
  'hold.minutes': {
32
47
  default: 2,
33
48
  problem: (v) =>
@@ -12,9 +12,10 @@ 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
- export const INSTRUCTIONS_VERSION = 12;
18
+ export const INSTRUCTIONS_VERSION = 13;
18
19
 
19
20
  const TEMPLATES = fileURLToPath(new URL('../../templates/', import.meta.url));
20
21
  const BEGIN = (v) => `<!-- code-kit:begin v${v} -->`;
@@ -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}`)
@@ -107,12 +111,14 @@ const AGENT_LEGACY = /^Always:\s*$/;
107
111
 
108
112
  /**
109
113
  * Where a file's code-kit part stands: `current`; `stale` (marked, from an older code-kit or an older
110
- * config); `legacy` (written before the markers, often tailored by hand, so merged once by the lead, not
114
+ * config); `ahead` (marked by a newer code-kit than this one, as when a teammate has updated: never
115
+ * written back to this one's older rules); `legacy` (written before the markers, often tailored by hand, so merged once by the lead, not
111
116
  * overwritten); or `missing` (none yet).
112
117
  */
113
118
  function stateOf(text, block, legacy) {
114
119
  const m = MARKED.exec(text);
115
120
  // A formatter that rewraps the project's markdown doesn't make code-kit's part out of date.
121
+ if (m && Number(m[1]) > INSTRUCTIONS_VERSION) return { state: 'ahead', version: Number(m[1]) };
116
122
  if (m) return { state: same(m[0], block) ? 'current' : 'stale', version: Number(m[1]) };
117
123
  if (text.split('\n').some((l) => legacy.test(l))) return { state: 'legacy', version: 0 };
118
124
  return { state: 'missing', version: null };
@@ -19,6 +19,7 @@ import { isTestFile } from './testfiles.mjs';
19
19
  import { laneClaims } from './laneclaims.mjs';
20
20
  import { keptBecause, worktrees } from './worktrees.mjs';
21
21
  import { ciFindings } from './ci.mjs';
22
+ import { costReport, infraFiles, money } from './costs.mjs';
22
23
  import { storyModels } from './dispatches.mjs';
23
24
  import { pickPerLane } from './schedule.mjs';
24
25
  import { reconcileAll } from './events.mjs';
@@ -78,6 +79,43 @@ export function readBrief(root, config) {
78
79
  return { path, status: status ?? null, openQuestions: open.map((q) => q.question), open };
79
80
  }
80
81
 
82
+ /**
83
+ * Spec 29: the running budget and the cost register, as next's attention. A project with infrastructure
84
+ * and no budget is asked for one (COST-6); with one, an estimate over it goes to the person with options
85
+ * (COST-5), and the register's other problems are named (COST-3).
86
+ */
87
+ export function costAttention(root, config) {
88
+ const some = (files) => `${files.slice(0, 3).join(', ')}${files.length > 3 ? ', …' : ''}`;
89
+ if (!config.cost) {
90
+ const infra = infraFiles(root);
91
+ return infra.length
92
+ ? [
93
+ `No running budget is set, and the project has infrastructure (${some(infra)}). Ask the person how much a month each environment may cost and the load to plan for; /code-kit:init records it, and the lead then costs what's built in the register.`,
94
+ ]
95
+ : [];
96
+ }
97
+ const report = costReport(root, config);
98
+ const infra = config.cost.paths.length ? infraFiles(root, config.cost.paths) : [];
99
+ if (!report.exists)
100
+ return infra.length
101
+ ? [
102
+ `There is no cost register (${report.file}) for the project's infrastructure (${some(infra)}). Cost it there, a row per paid thing with its monthly estimate and where the price came from; \`code-kit cost\` adds it up against the budget.`,
103
+ ]
104
+ : [];
105
+ const words = [];
106
+ const over = report.environments.filter((e) => e.over > 0);
107
+ if (over.length)
108
+ words.push(
109
+ `The running cost is over the budget: ${over.map((e) => `${e.name} ${money(e.total, config.cost.currency)} a month against ${money(e.budget, config.cost.currency)}`).join(', ')}. Bring the person options that fit (smaller sizes, cheaper tiers or providers, fewer environments, less at launch), each with what it gives up, and let them decide.`,
110
+ );
111
+ const other = report.problems.length - over.length;
112
+ if (other > 0)
113
+ words.push(
114
+ `${report.file} has ${other} problem${other === 1 ? '' : 's'} (\`code-kit cost\` says which): an estimate that isn't a number, a row without where its price came from, or one for an environment the budget doesn't name.`,
115
+ );
116
+ return words;
117
+ }
118
+
81
119
  const hasMarkdown = (dir) => {
82
120
  try {
83
121
  return readdirSync(dir, { recursive: true }).some((f) => String(f).endsWith('.md'));
@@ -390,6 +428,7 @@ export function nextStep(root, base) {
390
428
  `${ci.length} thing${ci.length === 1 ? '' : 's'} in the project's CI (${files.join(', ')}) ${ci.length === 1 ? 'runs' : 'run'} once per story or without a time limit; \`code-kit ci check\` says what, and the fix for the person to approve.`,
391
429
  );
392
430
  }
431
+ attention.push(...costAttention(root, config));
393
432
  const instructions = instructionsState(root, config);
394
433
  const behind = instructions.filter((f) => ['stale', 'legacy'].includes(f.state));
395
434
  // A file with no code-kit part may be one the project keeps without it: said, not insisted on.
@@ -398,6 +437,12 @@ export function nextStep(root, base) {
398
437
  attention.push(
399
438
  `${none.map((f) => f.file).join(', ')} ${none.length === 1 ? 'has' : 'have'} none of code-kit's instructions; \`code-kit instructions --write\` adds them.`,
400
439
  );
440
+ // Newer than this code-kit: a teammate updated first. The session's own code-kit is what's behind.
441
+ const ahead = instructions.filter((f) => f.state === 'ahead');
442
+ if (ahead.length)
443
+ attention.push(
444
+ `code-kit's instructions in ${ahead.map((f) => f.file).join(', ')} come from a newer code-kit than this session's: don't write them back. Run /plugin marketplace update code-kit and restart Claude Code.`,
445
+ );
401
446
  if (behind.length) {
402
447
  const legacy = behind.filter((f) => f.state === 'legacy');
403
448
  return result(
@@ -9,6 +9,7 @@ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
9
9
  import { isAbsolute, join } from 'node:path';
10
10
  import { readEvents } from './events.mjs';
11
11
  import { laneClaims } from './laneclaims.mjs';
12
+ import { readQueue, waiting } from './queue.mjs';
12
13
  import { waitingStories } from './questions.mjs';
13
14
  import { sentBack } from './reviews.mjs';
14
15
  import { isTestFile } from './testfiles.mjs';
@@ -405,7 +406,7 @@ function worktrees(root) {
405
406
  /**
406
407
  * Where each story is. The plan's `done` stands (the lead marks it after merging, and merged
407
408
  * branches are often deleted or squashed). Otherwise git decides: a branch with commits not in
408
- * `base` is in review. A branch still at the commit a review sent back is `sent back`, waiting for
409
+ * `base` is in review. A branch with commits ahead, still at the commit a review sent back, is `sent back`, waiting for
409
410
  * its lane's fix. Without a branch, the plan's status stands. A story is `blocked` while a story it
410
411
  * depends on isn't done, whatever its branch holds; a todo story whose dependencies are done is `ready`.
411
412
  * A story with an open question for the person that holds it (`code-kit ask --blocks`) is `waiting on
@@ -426,6 +427,10 @@ function worktrees(root) {
426
427
  export function storyStates(root, stories, base, { designing = null } = {}) {
427
428
  const trees = worktrees(root);
428
429
  const backs = sentBack(root);
430
+ // Queued again since its send-back, at that same commit: a review passed it, and it waits to merge.
431
+ const queued = waiting(readQueue(root));
432
+ const requeued = (branch, back) =>
433
+ queued.some((e) => e.branch === branch && e.commit === back.sha && e.passed > back.at);
429
434
  const refs = branchRefs(root, base);
430
435
  const claims = laneClaims(root).filter((c) => !c.stale);
431
436
  const live = new Set(claims.map((c) => `${c.lane}|${c.story ?? ''}`));
@@ -464,7 +469,8 @@ export function storyStates(root, stories, base, { designing = null } = {}) {
464
469
  let stopped = false;
465
470
  if (ref && !['done', DROPPED].includes(story.status)) {
466
471
  const head = backs[branch] ? refs[ref].sha : null;
467
- if (head && head === backs[branch].sha) state = 'sent back';
472
+ if (ahead > 0 && head && head === backs[branch].sha && !requeued(branch, backs[branch]))
473
+ state = 'sent back';
468
474
  else if (ahead > 0)
469
475
  state =
470
476
  building(story) || (story.lane === DESIGN && designing?.(story, ref))
@@ -275,10 +275,18 @@ export function readsOnly(cmd) {
275
275
  );
276
276
  }
277
277
 
278
- // What could change what a later command in the line runs: a function or alias defined, a variable
279
- // set (PATH among them), a file sourced, a shell option.
278
+ // What could change what a later command in the line runs: a function or alias defined, a file sourced,
279
+ // a shell option, a variable exported, or one the shell or a command reads (PATH among them).
280
280
  const REDEFINES =
281
- /(?:^|[;&|\n(]\s*)(?:[\w.-]+\s*\(\s*\)|function\s|alias\s|unalias\s|source\s|\.\s|hash\s|enable\s|builtin\s|set\s|setopt\s|shopt\s|unset\s|export\s|typeset\s|declare\s|local\s|readonly\s|[A-Za-z_]\w*=)/;
281
+ /(?:^|[;&|\n(]\s*)(?:[\w.-]+\s*\(\s*\)|function\s|alias\s|unalias\s|source\s|\.\s|hash\s|enable\s|builtin\s|set\s|setopt\s|shopt\s|unset\s|export\s|typeset\s|declare\s|local\s|readonly\s)/;
282
+ const SHELL_READS =
283
+ /^(?:PATH|path|FPATH|fpath|CDPATH|cdpath|IFS|ENV|BASH_ENV|ZDOTDIR|HOME|LD_\w*|DYLD_\w*|GIT_\w*|XDG_\w*)$/;
284
+ // Any other variable set in the line (`CK=…/code-kit.mjs`) stays in the shell: no command it runs sees
285
+ // it, unless it was exported already, and what names it is judged on its own.
286
+ const setsWhatRuns = (code) =>
287
+ [...code.matchAll(/(?:^|[;&|\n(]\s*)([A-Za-z_]\w*)(?:\[[^\]]*\])?\+?=/g)].some(
288
+ ([, name]) => SHELL_READS.test(name) || name in process.env,
289
+ );
282
290
 
283
291
  /**
284
292
  * The parts of `cmd` that name `pattern`, each a pipeline (`a | b`) of its own, that don't only read
@@ -289,7 +297,8 @@ export function unreadNames(cmd, pattern) {
289
297
  const read = withoutHarmlessRedirects(cmd);
290
298
  const code = codeOf(read);
291
299
  if (!pattern.test(cmd)) return [];
292
- if (/<</.test(cmd) || REDEFINES.test(code)) return readsOnly(cmd) ? [] : [cmd];
300
+ if (/<</.test(cmd) || REDEFINES.test(code) || setsWhatRuns(code))
301
+ return readsOnly(cmd) ? [] : [cmd];
293
302
  const text = withoutHeredocs(read);
294
303
  const parts = [];
295
304
  let start = 0;
@@ -304,7 +313,45 @@ export function unreadNames(cmd, pattern) {
304
313
  if (andOr) i++;
305
314
  }
306
315
  }
307
- return parts.filter((p) => pattern.test(p) && !readsOnly(p));
316
+ // The commit hook appends to the log before the command runs: a restore beside a commit could drop that.
317
+ const restores = !runs(
318
+ cmd,
319
+ new RegExp(String.raw`^${GIT}(?:commit|merge|revert|cherry-pick|rebase|am|pull)(?![\w-])`),
320
+ );
321
+ return parts.filter(
322
+ (p) => pattern.test(p) && !readsOnly(p) && !(restores && restoresFromHead(p, pattern)),
323
+ );
324
+ }
325
+
326
+ // git restore's flags that keep its source the last commit (or the index), and change nothing else.
327
+ const RESTORE_FLAG = /^(?:--staged|-S|--worktree|-W|-SW|-WS|--source=HEAD|-q|--quiet|--)$/;
328
+
329
+ /**
330
+ * Whether `part` only puts a file `pattern` names back as the last commit (or the index) has it:
331
+ * `git restore [--staged] [--worktree] <file>` or `git checkout [HEAD] -- <file>`. That can lose only
332
+ * what isn't committed, never what the history holds, as after `git revert --no-commit` took a file's
333
+ * committed lines out.
334
+ */
335
+ export function restoresFromHead(part, pattern) {
336
+ const pieces = commandsOf(part);
337
+ if (pieces.length !== 1 || /[|<>`$]/.test(codeOf(part))) return false;
338
+ const words = wordsOf(pieces[0].text);
339
+ if (words[0] !== 'git' || words.length < 3) return false;
340
+ const file = words.at(-1);
341
+ if (!pattern.test(file) || /[*?[]/.test(file)) return false;
342
+ const flags = words.slice(2, -1);
343
+ if (words[1] === 'restore') {
344
+ for (let i = 0; i < flags.length; i++) {
345
+ if ((flags[i] === '-s' || flags[i] === '--source') && flags[i + 1] === 'HEAD') i++;
346
+ else if (!RESTORE_FLAG.test(flags[i])) return false;
347
+ }
348
+ return true;
349
+ }
350
+ if (words[1] === 'checkout')
351
+ return (
352
+ flags.join(' ') === '--' || flags.join(' ') === 'HEAD --' || flags.join(' ') === '-q HEAD --'
353
+ );
354
+ return false;
308
355
  }
309
356
 
310
357
  // What may come before a command it runs: a package runner (`npx`, `pnpm exec`, `uv run`…) or a wrapper
@@ -7,6 +7,7 @@ import { join } from 'node:path';
7
7
  import { BASELINE_FILE, loadBaseline, newProblems } from './baseline.mjs';
8
8
  import { runChecks } from './checks.mjs';
9
9
  import { CONFIG_FILE } from './config.mjs';
10
+ import { COST_APPROVAL, overBudget, overWords, registerFile } from './costs.mjs';
10
11
  import { isDependencyFile } from './dependencies.mjs';
11
12
  import { entryProblems, freshEntries, readRegister, statesWithoutEvidence } from './designs.mjs';
12
13
  import { evidenceRecords } from './reviews.mjs';
@@ -117,7 +118,9 @@ function logEntries(root, base) {
117
118
  if (added === null)
118
119
  return {
119
120
  entries: [],
120
- problems: [`${APPROVAL_LOG} was edited, not appended to; it is append-only.`],
121
+ problems: [
122
+ `${APPROVAL_LOG} was edited, not appended to; it is append-only. An entry it has where the branch left the base is gone or changed, as a \`git revert\` of a commit that logged approvals leaves it. Take that commit out of the branch and make it again without the log's change: \`git revert --no-commit <commit>\`, then \`git restore --staged --worktree ${APPROVAL_LOG}\`, then commit.`,
123
+ ],
121
124
  };
122
125
  const entries = [];
123
126
  const problems = [];
@@ -237,6 +240,7 @@ export function verifyBranch({
237
240
  tests: [],
238
241
  regression: [],
239
242
  standards: [],
243
+ cost: [],
240
244
  checks: [],
241
245
  };
242
246
  const { entries, problems: logProblems } = logEntries(root, from);
@@ -402,6 +406,29 @@ export function verifyBranch({
402
406
  );
403
407
  }
404
408
 
409
+ // COST-4: a branch that changes the infrastructure says in the register what that costs. COST-5: one
410
+ // that takes an environment past its budget carries the person's cost approval, which the commit logs.
411
+ if (config.cost) {
412
+ const register = registerFile(config);
413
+ const infra = changed.filter((f) => matchesAny(f, config.cost.paths));
414
+ if (infra.length && !changed.includes(register))
415
+ found.cost.push(
416
+ `${infra.slice(0, 3).join(', ')}${infra.length > 3 ? `, and ${infra.length - 3} more,` : ''} changed the infrastructure, but ${register} didn't change. Say there what the change costs a month: a new or changed row for each paid thing it adds or resizes, or a Basis saying why the cost didn't move.`,
417
+ );
418
+ if (changed.includes(register)) {
419
+ const over = overBudget(
420
+ showAt(root, from, register),
421
+ showAt(root, 'HEAD', register),
422
+ config.cost,
423
+ );
424
+ const approved = entries.some((e) => e.file === register && e.approval === COST_APPROVAL);
425
+ if (over.length && !approved)
426
+ found.cost.push(
427
+ `${register}: ${overWords(over, config.cost.currency)}. Going past the budget is the person's call: bring them options that fit, each with what it gives up, and the cost of this one; their cost approval is recorded in ${APPROVAL_LOG} by the commit.`,
428
+ );
429
+ }
430
+ }
431
+
405
432
  // REG-1: a fix's tests fail without it, as the bug.
406
433
  const fix = fixes ? fixOf(root, branch ?? currentBranchOf(root), config) : null;
407
434
  if (fix) found.regression.push(...proveFix({ root, from, base, changed, config, fix }));
@@ -237,6 +237,8 @@ const NOTES = new Set([
237
237
  'drift',
238
238
  'queuePaused',
239
239
  'deferred',
240
+ 'talking',
241
+ 'holding',
240
242
  ]);
241
243
 
242
244
  /** What a line is, in a word or two, for the Needs you panel. */
@@ -113,6 +113,13 @@ export function storiesSignature(ids, stories = [], heads = new Map(), inFlight
113
113
  .join('|');
114
114
  }
115
115
 
116
+ /**
117
+ * LOOP-15: what the lead is told about stories it was asked about before, that waited the park's half
118
+ * hour with nothing they watch moving.
119
+ */
120
+ export const holdHint = (ids, { cli = 'code-kit' } = {}) =>
121
+ `${ids.join(', ')} ${ids.length === 1 ? 'was' : 'were'} left half an hour ago with nothing ${ids.length === 1 ? 'it waits' : 'they wait'} on moving since. If ${ids.length === 1 ? 'it waits' : 'they wait'} on a date or on something outside the build, hold ${ids.length === 1 ? 'it' : 'each'} instead, so the loop stops asking: node "${cli}" defer ${ids[0]} --reason "<what it waits on>" [--until <date>].`;
122
+
116
123
  /** The story ids a step names, upper-cased: `review ST-158 ST-172` gives ST-158 and ST-172. */
117
124
  export const stepStories = (step) =>
118
125
  STORY_STEPS.has(step?.stepKind ?? step?.kind ?? step?.step)
@@ -260,25 +267,37 @@ const ANSWER_SHOWN = 4000;
260
267
  * lead's own conversation (so it knows the whole exchange), with the reply itself for a call that
261
268
  * can't fork. `prompt` is the loop's own prompt for that turn, or null when the person started it.
262
269
  */
263
- export function outcomePrompt({ prompt = null, answer = '' }) {
270
+ export function outcomePrompt({ prompt = null, answer = '', said = null }) {
264
271
  const reply = String(answer ?? '').trim();
265
272
  const shown =
266
273
  reply.length > ANSWER_SHOWN ? `${reply.slice(0, ANSWER_SHOWN)}\n[… cut short]` : reply;
274
+ const person = !prompt && String(said ?? '').trim() ? clip(String(said).trim()) : null;
267
275
  return [
268
276
  prompt
269
277
  ? `code-kit's lead loop prompted you: "${prompt}"`
270
- : "The person prompted you, and code-kit's lead loop is about to prompt you with the build's next step.",
278
+ : person
279
+ ? `The person prompted you:\n"""\n${person}\n"""\ncode-kit's lead loop is about to prompt you with the build's next step.`
280
+ : "The person prompted you, and code-kit's lead loop is about to prompt you with the build's next step.",
271
281
  `Your reply ended your turn. It read:\n"""\n${shown}\n"""`,
272
282
  'Say where that reply left things, so the loop knows whether to prompt you again. Answer with one JSON object and nothing else:',
273
- '{"outcome": "done" | "started" | "needs-person" | "blocked" | "waiting", "question": "…", "options": [{"label": "…", "effect": "…"}], "reason": "…", "waits": [{"story": "ST-n", "on": ["ST-n"], "why": "…"}]}',
283
+ `{"outcome": "done" | "started" | "needs-person" | "blocked" | "waiting", "question": "…", "options": [{"label": "…", "effect": "…"}], "reason": "…", "waits": [{"story": "ST-n", "on": ["ST-n"], "why": "…"}]${person ? ', "talk": "build" | "conversation"' : ''}}`,
274
284
  '- done: you finished what was asked, or there was nothing to do.',
275
285
  '- started: you started work that carries on without you, such as lane agents.',
276
286
  "- needs-person: you asked the person something, or wait on their answer, approval or feedback before you go on. question: what you wait on, as one question; options: 2 to 4 answers they could give (a label of at most five words, and what it does), or [] when it's theirs to put in words.",
277
287
  "- waiting: the step isn't due yet for some or all of its stories: they wait on other work still going (a lane building a story they merge with, a rebuild, a check running). waits: one entry per story that waits, with the stories it waits on (their ST ids, [] when it's other work) and why, in a few words. Use this, not done, when you said a story can't be taken yet.",
278
288
  "- blocked: you didn't take the step, for a reason no answer from the person settles now and no work in flight will change. reason: why, in a sentence.",
289
+ ...(person
290
+ ? [
291
+ "- talk (LOOP-16): build when the person asked you to carry on with the build or to do its work; conversation when they're talking with you about something else (a question, a discussion, another task) or said not to build now, so a prompt from the loop would cut in.",
292
+ ]
293
+ : []),
279
294
  ].join('\n');
280
295
  }
281
296
 
297
+ /** A text cut to what a side call is shown. */
298
+ const clip = (text) =>
299
+ text.length > ANSWER_SHOWN ? `${text.slice(0, ANSWER_SHOWN)}\n[… cut short]` : text;
300
+
282
301
  /**
283
302
  * LOOP-11: the side call's answer: { outcome, question, options: [{ label, effect }], reason }, or
284
303
  * null when it isn't one (the loop then goes on as before).
@@ -314,9 +333,53 @@ export function readOutcome(text) {
314
333
  options: options.length >= 2 ? options : [],
315
334
  reason: words(parsed.reason, 300),
316
335
  waits,
336
+ talk: ['build', 'conversation'].includes(parsed.talk) ? parsed.talk : null,
317
337
  };
318
338
  }
319
339
 
340
+ /** LOOP-16: the band's words while the person talks with the lead. */
341
+ export const talkingText = (minutes) =>
342
+ `You're talking with the lead: the loop waits until you've been quiet for ${minutes} minute${minutes === 1 ? '' : 's'}`;
343
+
344
+ /** LOOP-17: the steps checked against the project before the lead is prompted (a design is the person's). */
345
+ export const CHECKED_STEPS = new Set([...LEAD_STEPS].filter((s) => s !== 'design'));
346
+
347
+ /** LOOP-17: how long a step judged not due waits before it's checked again, with the project moving. */
348
+ export const RECHECK_MS = 5 * 60_000;
349
+
350
+ /**
351
+ * LOOP-17: the side call that checks a step against the project as it is now, before the lead is
352
+ * prompted with it. `facts` is what the mod read itself: the step's stories and branches, the merge
353
+ * queue, the agents at work, the base's and this checkout's latest commits, and the lead's last replies.
354
+ */
355
+ export function checkPrompt({ prompt, facts }) {
356
+ return [
357
+ `code-kit's lead loop is about to prompt the lead: "${prompt}"`,
358
+ "The loop's step comes from code-kit's records, which can lag the work: a story already merged or committed, work already under way in an agent or a background run, or a step the lead already said why it won't take. Judge from the project as it is now, below, whether prompting the lead is still useful.",
359
+ `The project now:\n"""\n${clip(String(facts ?? '').trim())}\n"""`,
360
+ 'Answer with one JSON object and nothing else: {"due": true | false, "why": "…"}',
361
+ '- due false: the step is done already (its branch merged, its change on the base or this checkout), its work is under way (an agent at work on it, or the lead said a run is going and nothing since shows it finished), or the lead said why it is not taking the step and nothing it named has changed since. why: what shows it, in one sentence.',
362
+ '- due true: none of that shows; when unsure, due. why: what makes it due, in a few words.',
363
+ ].join('\n');
364
+ }
365
+
366
+ /** LOOP-17: the check's answer: { due, why }, or null when it isn't one (the step is then prompted). */
367
+ export function readCheck(text) {
368
+ const raw = String(text ?? '');
369
+ let parsed;
370
+ try {
371
+ parsed = JSON.parse(raw.slice(raw.indexOf('{'), raw.lastIndexOf('}') + 1));
372
+ } catch {
373
+ return null;
374
+ }
375
+ if (typeof parsed?.due !== 'boolean') return null;
376
+ const why =
377
+ typeof parsed.why === 'string' && parsed.why.trim()
378
+ ? parsed.why.replace(/\s+/g, ' ').trim().slice(0, 300)
379
+ : null;
380
+ return { due: parsed.due, why };
381
+ }
382
+
320
383
  /**
321
384
  * LOOP-12: a design is made with the person, so the loop hands a design story to the lead once; while
322
385
  * the stories `next` names have all been handed over, it leaves them to the person and the lead.