@warren-dean/code-kit 0.22.1 → 0.24.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.
@@ -16,9 +16,9 @@ import {
16
16
  } from './lib/dependencies.mjs';
17
17
  import { CODE_KIT, GIT, codeOf, commandsOf, runs } from './lib/shell.mjs';
18
18
  import { block, start } from './lib/hook.mjs';
19
- import { CONFIG_FILE } from './lib/config.mjs';
19
+ import { CONFIG_FILE, committedConfig } from './lib/config.mjs';
20
20
  import { laneOfBranch, storyOfBranch, teamOf, teamProvider, whoami } from './lib/team.mjs';
21
- import { matchesAny } from './lib/glob.mjs';
21
+ import { globToRegExp, matchesAny } from './lib/glob.mjs';
22
22
  import { noteBefore } from './lane-audit.mjs';
23
23
  import { TESTS_APPROVAL, commitWeakenings } from './lib/regression.mjs';
24
24
  import {
@@ -162,14 +162,36 @@ if ((switchesToProtected && writesHistory) || movesProtected) {
162
162
  `Blocked: never commit to, merge into or move ${config.branches.protected.join(' or ')}, even by switching to it first. Work on a branch; a person merges after review${config.approvals.delegate?.merge ? ', or the lead merges a verified branch with `code-kit merge <branch> --delegated`' : ''}.\nCommand: ${cmd}`,
163
163
  );
164
164
  }
165
+ const sessionIn = sessionRoot(input, project);
166
+ const actor = actorFor(input, sessionIn ?? project, config);
167
+ // #63: the lead may push a protected branch where the person delegated it (`approvals.delegate.push`,
168
+ // read from the config committed on that branch, so a branch can't grant it), and never by force.
165
169
  if (runs(cmd, new RegExp(String.raw`^${GIT}push\b.*\b(${branches})\b`))) {
166
- block(
167
- `Blocked: push to your own branch; a person merges to ${config.branches.protected[0]} after review.\nCommand: ${cmd}`,
170
+ const forced = runs(
171
+ cmd,
172
+ new RegExp(
173
+ String.raw`^${GIT}push\b.*(\s--force\S*|\s-[a-zA-Z]*f|\s\+\S|\s--delete\b|\s-d\b|\s--mirror\b|\s:(${branches})\b)`,
174
+ ),
175
+ );
176
+ const pushTo = config.branches.protected.find((b) =>
177
+ runs(
178
+ cmd,
179
+ new RegExp(String.raw`^${GIT}push\b.*\b${b.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\b`),
180
+ ),
168
181
  );
182
+ const delegated =
183
+ actor.kind === 'lead' &&
184
+ Boolean(
185
+ committedConfig(project, pushTo ?? config.branches.protected[0]).config?.approvals.delegate
186
+ ?.push,
187
+ );
188
+ if (!delegated || forced)
189
+ block(
190
+ forced && delegated
191
+ ? `Blocked: never force-push, delete or overwrite ${pushTo}; push it as it is, fast-forward only.\nCommand: ${cmd}`
192
+ : `Blocked: push to your own branch; a person merges to ${config.branches.protected[0]} after review${actor.kind === 'lead' ? `, and pushes it, unless they delegate pushing it to you ("approvals.delegate.push": true, committed on ${config.branches.protected[0]})` : ''}.\nCommand: ${cmd}`,
193
+ );
169
194
  }
170
-
171
- const sessionIn = sessionRoot(input, project);
172
- const actor = actorFor(input, sessionIn ?? project, config);
173
195
  // A read-only agent's command is judged afterwards by what it changed (lane-audit).
174
196
  if (actor.kind === 'readonly') noteBefore(input);
175
197
  // The lead acts for the person only where the config says the person may approve from chat.
@@ -258,6 +280,11 @@ if (
258
280
  block(
259
281
  `Blocked: releasing worktrees is the lead's, which knows which stories are still at work. Finish your story and hand back.\nCommand: ${cmd}`,
260
282
  );
283
+ // LEAN-8: discarding a worktree's uncommitted changes is the person's, from the band, whoever asks.
284
+ if (runs(cmd, new RegExp(String.raw`^${CODE_KIT}\s+worktrees\s+discard\b`)))
285
+ block(
286
+ `Blocked: discarding a worktree that still holds uncommitted changes is the person's own act, from the code-kit band. Tell them which worktree and what it holds, and carry on.\nCommand: ${cmd}`,
287
+ );
261
288
  // ONB-8: code-kit's instructions are the lead's to bring up to date, like the rest of the kit.
262
289
  if (
263
290
  runs(cmd, new RegExp(String.raw`^${CODE_KIT}\s+instructions\b.*\s--write\b`)) &&
@@ -330,9 +357,13 @@ for (const { pattern, lanes, why } of config.shell.restricted) {
330
357
  block(`Blocked: the ${actor.label} may not run this. ${why}\nCommand: ${cmd}`);
331
358
  }
332
359
 
333
- // Git commands run against the repository they name (`git -C dir`) or the one the shell is in. Another
334
- // repository (not this project or one of its worktrees) follows its own rules.
335
- const gitDir = cmd.match(/\bgit\s+-C\s+("[^"]+"|'[^']+'|\S+)/)?.[1]?.replace(/^["']|["']$/g, '');
360
+ // Git commands run against the repository they name (`git -C dir`), the one the command moves into
361
+ // first (`cd dir && git commit`, #55), or the one the shell is in. Another repository (not this project
362
+ // or one of its worktrees) follows its own rules.
363
+ const unquote = (v) => v?.replace(/^["']|["']$/g, '');
364
+ const gitDir =
365
+ unquote(cmd.match(/\bgit\s+-C\s+("[^"]+"|'[^']+'|\S+)/)?.[1]) ??
366
+ unquote(cmd.match(/^\s*cd\s+("[^"]+"|'[^']+'|[^\s;&|]+)\s*(?:&&|;)/)?.[1]);
336
367
  const root = gitDir
337
368
  ? sessionRoot({ cwd: resolve(input.cwd || project, gitDir) }, project)
338
369
  : sessionIn;
@@ -450,7 +481,8 @@ function committedFiles() {
450
481
  const git = (...args) =>
451
482
  spawnSync('git', ['-C', root, ...args], { encoding: 'utf8' }).stdout ?? '';
452
483
  const names = (out) => out.split('\n').filter(Boolean);
453
- const staged = names(git('diff', '--cached', '--name-only'));
484
+ // Both paths of a staged rename: the old one's deletion is a change to it too (#74).
485
+ const staged = names(git('diff', '--cached', '--name-only', '--no-renames'));
454
486
  // This hook runs before the command, so `git add … && git commit` and `git commit -a` have not staged yet.
455
487
  const changed = names(git('status', '--porcelain', '-uall', '--no-renames')).map((l) =>
456
488
  l.slice(3),
@@ -459,14 +491,27 @@ function committedFiles() {
459
491
  const addAll = /\bgit\s+add\b[^;&|]*\s(-A|--all|\.)(\s|$)/.test(cmd);
460
492
  const addArgs = [...cmd.matchAll(/\bgit\s+add\s+([^;&|]+)/g)]
461
493
  .flatMap((m) => m[1].trim().split(/\s+/))
462
- .filter((a) => a && !a.startsWith('-'));
494
+ .filter((a) => a && !a.startsWith('-'))
495
+ .map((a) => a.replace(/^(['"])(.*)\1$/, '$2'));
496
+ // What the shell expands before git sees it (#76): an argument it can't be read from, such as a
497
+ // variable or a command's output, could be any file, so every changed file counts.
498
+ const unknowable = addArgs.some((a) => /[$`]/.test(a));
499
+ const matches = (f, a) => {
500
+ const arg = a.replace(/^\.\//, '').replace(/\/$/, '');
501
+ if (f === arg || f.startsWith(`${arg}/`)) return true;
502
+ if (!/[*?{[]/.test(arg)) return false;
503
+ const re = globToRegExp(arg);
504
+ return f.split('/').some((_, i, parts) => re.test(parts.slice(0, i + 1).join('/')));
505
+ };
463
506
  const added = changed.filter(
464
- (f) =>
465
- commitAll ||
466
- addAll ||
467
- addArgs.some((a) => f === a || f.startsWith(`${a.replace(/\/$/, '')}/`)),
507
+ (f) => commitAll || addAll || unknowable || addArgs.some((a) => matches(f, a)),
508
+ );
509
+ // `git reset --soft <ref> && git commit` commits everything since <ref>, staged by the reset (#76).
510
+ const resetTo = [...cmd.matchAll(/\bgit\s+reset\s+--soft\s+([^\s;&|]+)/g)].map((m) => m[1]);
511
+ const reset = resetTo.flatMap((ref) =>
512
+ names(git('diff', '--name-only', '--no-renames', ref, 'HEAD')),
468
513
  );
469
- return { files: [...new Set([...staged, ...added])], git };
514
+ return { files: [...new Set([...staged, ...added, ...reset])], git };
470
515
  }
471
516
 
472
517
  // Every committed protected file is recorded in the audit log, with the person's reason when an
@@ -46,10 +46,12 @@ function runCheck(check, files, root, actor, skipped) {
46
46
  skipped.push({ check: check.name, command, where: where.replace(/^ in /, '') || null });
47
47
  return null; // not installed yet (fresh clone): the check can't run
48
48
  }
49
+ // #62: a check that ran out of time didn't fail; it's marked so a merge can try it again.
49
50
  if (res.error || res.status === null)
50
51
  return {
51
52
  check: check.name,
52
- title: `${check.name}: \`${command}\` did not finish${where} (${res.error?.code ?? res.signal}).`,
53
+ timedOut: res.error?.code === 'ETIMEDOUT' || res.signal === 'SIGTERM',
54
+ title: `${check.name}: \`${command}\` did not finish${where} (${res.error?.code ?? res.signal}) within ${check.timeoutSeconds ?? 240} seconds; \`timeoutSeconds\` on the check gives it longer.`,
53
55
  };
54
56
  if (res.status !== 0)
55
57
  return {
@@ -127,6 +127,8 @@ function delegateRules(given, protectedPaths = []) {
127
127
  return {
128
128
  protected: d.protected ?? [],
129
129
  merge: d.merge === true,
130
+ // #63: pushing the protected branch is the person's unless they delegate it: a push can deploy.
131
+ push: d.push === true,
130
132
  tests: d.tests === true,
131
133
  dependencies: d.dependencies
132
134
  ? {
@@ -236,6 +238,13 @@ export function approvalSettings(config) {
236
238
  'Who merges a reviewed branch into the base: merging is not releasing',
237
239
  ['lead', 'person'],
238
240
  ),
241
+ row(
242
+ 'approvals.push',
243
+ who(Boolean(rules?.push)),
244
+ 'person',
245
+ 'Who pushes the base to the remote once merged: a push can deploy, so it stays yours unless you say',
246
+ ['lead', 'person'],
247
+ ),
239
248
  row(
240
249
  'approvals.tests',
241
250
  who(Boolean(rules?.tests)),
@@ -253,6 +262,7 @@ export function withApprovalSetting(raw, config, key, text) {
253
262
  const delegate = {
254
263
  protected: [...(rules?.protected ?? [])],
255
264
  merge: Boolean(rules?.merge),
265
+ push: Boolean(rules?.push),
256
266
  tests: Boolean(rules?.tests),
257
267
  ...(deps ? { dependencies: { ...deps } } : {}),
258
268
  };
@@ -279,7 +289,7 @@ export function withApprovalSetting(raw, config, key, text) {
279
289
  lead
280
290
  ? (delegate.dependencies = deps ?? delegateRules({ dependencies: {} }).dependencies)
281
291
  : delete delegate.dependencies;
282
- else if (rule === 'merge' || rule === 'tests') delegate[rule] = lead;
292
+ else if (rule === 'merge' || rule === 'push' || rule === 'tests') delegate[rule] = lead;
283
293
  else if (config.protected.some((p) => p.approval === rule) && rule !== 'kit')
284
294
  delegate.protected = lead
285
295
  ? [...new Set([...delegate.protected, rule])]
@@ -381,6 +391,7 @@ export function validate(c) {
381
391
  (isObj(d) &&
382
392
  (d.protected === undefined || isList(d.protected)) &&
383
393
  [undefined, true, false].includes(d.merge) &&
394
+ [undefined, true, false].includes(d.push) &&
384
395
  [undefined, true, false].includes(d.tests) &&
385
396
  (dep === undefined ||
386
397
  (isObj(dep) &&
@@ -390,7 +401,7 @@ export function validate(c) {
390
401
  ([undefined, true, false].includes(dep.allowInstallScripts) ||
391
402
  (isList(dep.allowInstallScripts) &&
392
403
  dep.allowInstallScripts.every((k) => ['binary', 'build', 'other'].includes(k))))))),
393
- '"approvals.delegate" must be false, or { protected?: [approval names], merge?: true|false, tests?: true|false, dependencies?: { licences?, minWeeklyDownloads?, maxMonthsSinceRelease?, allowInstallScripts?: true|false|["binary","build","other"] } }',
404
+ '"approvals.delegate" must be false, or { protected?: [approval names], merge?: true|false, push?: true|false, tests?: true|false, dependencies?: { licences?, minWeeklyDownloads?, maxMonthsSinceRelease?, allowInstallScripts?: true|false|["binary","build","other"] } }',
394
405
  );
395
406
  need(
396
407
  c.branches === undefined || isList(c.branches?.protected),
@@ -0,0 +1,76 @@
1
+ // Each lane agent's model (docs/specs/23-the-team.md, SCHED-3): with `harness.agents.lanes.model` set to
2
+ // `story`, a story runs on the model its size in the plan asks for, raised for a security requirement, a
3
+ // fix or a send-back. And the dispatch log: what each lane agent was started on, so the journal can say
4
+ // whether the smaller models are sent back more often than they save. Kept in the main checkout, beside
5
+ // the reviews, so every session and worktree on the machine writes the same one.
6
+ import { appendFileSync, mkdirSync, readFileSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+ import { markdownFiles, storyBranch } from './plan.mjs';
9
+ import { sendBacks } from './reviews.mjs';
10
+ import { projectWorktrees } from './rules.mjs';
11
+ import { agentFileModel, storyModel } from './schedule.mjs';
12
+ import { securityRequirementIds } from './security.mjs';
13
+
14
+ export const DISPATCHES_FILE = '.claude/state/dispatches.jsonl';
15
+ const dispatchesFile = (root) => join(projectWorktrees(root)[0] ?? root, DISPATCHES_FILE);
16
+
17
+ const readText = (path) => {
18
+ try {
19
+ return readFileSync(path, 'utf8');
20
+ } catch {
21
+ return null;
22
+ }
23
+ };
24
+
25
+ /**
26
+ * SCHED-3: each story's model, { [id]: { model, why } }, for the stories given (each with id, lane,
27
+ * requirements, fixes and size, as the plan reads them). Empty unless the lane model is `story`; a story
28
+ * with no lane agent (the lead's, a design) has none.
29
+ */
30
+ export function storyModels(root, config, stories) {
31
+ if (config.harness?.agents?.lanes?.model !== 'story') return {};
32
+ const specs = config.docs?.specs;
33
+ const security = securityRequirementIds(
34
+ specs ? markdownFiles(root, specs).map((f) => readText(join(root, f)) ?? '') : [],
35
+ );
36
+ const backs = sendBacks(root);
37
+ const found = {};
38
+ for (const s of stories) {
39
+ const agent = config.lanes[s.lane]?.agent;
40
+ if (!agent) continue;
41
+ const branch = storyBranch(s);
42
+ found[s.id] = storyModel({
43
+ size: s.size,
44
+ security: s.requirements.some((r) => security.has(r)),
45
+ fix: Boolean(s.fixes),
46
+ sentBack: backs.filter((b) => b.branch === branch).length,
47
+ fileModel: agentFileModel(readText(join(root, '.claude/agents', `${agent}.md`))),
48
+ });
49
+ }
50
+ return found;
51
+ }
52
+
53
+ /** SCHED-3: records that a lane agent started for `story`, on `model` (null: the session's), and why. */
54
+ export function recordDispatch(root, { story, lane, branch, model, why }, now = Date.now()) {
55
+ const file = dispatchesFile(root);
56
+ mkdirSync(dirname(file), { recursive: true });
57
+ appendFileSync(
58
+ file,
59
+ `${JSON.stringify({ at: new Date(now).toISOString(), story, lane, branch, model: model ?? null, why: why ?? null })}\n`,
60
+ );
61
+ }
62
+
63
+ /** Every lane agent started, oldest first: [{ at, story, lane, branch, model, why }]. */
64
+ export function dispatches(root) {
65
+ return (readText(dispatchesFile(root)) ?? '')
66
+ .split('\n')
67
+ .filter(Boolean)
68
+ .flatMap((line) => {
69
+ try {
70
+ const d = JSON.parse(line);
71
+ return d.story ? [d] : [];
72
+ } catch {
73
+ return [];
74
+ }
75
+ });
76
+ }
@@ -60,9 +60,9 @@ export const SETTINGS = {
60
60
  problem: (v) =>
61
61
  v === null || (typeof v === 'string' && v.length > 0)
62
62
  ? null
63
- : `must be a model (${MODELS.join(', ')}, or an id), or null for the session's`,
63
+ : `must be a model (${MODELS.join(', ')}, or an id), story for each story's size, or null for the session's`,
64
64
  about:
65
- "The lane agents' model, set as each is dispatched; none means the session's. A lane's agent file with its own model keeps it",
65
+ "The lane agents' model, set as each is dispatched: story picks it from each story's size; none means the session's. A lane's agent file with its own model keeps it",
66
66
  },
67
67
  'agents.lanes.contextLimit': {
68
68
  default: 250000,
@@ -82,7 +82,8 @@ function laneStandards(root, config, lane) {
82
82
  return lines.join('');
83
83
  }
84
84
 
85
- const marked = (body) => `${BEGIN(INSTRUCTIONS_VERSION)}\n${body.trim()}\n${END}`;
85
+ // With a blank line inside each marker, as Prettier writes markdown, so a project's format check passes (#77).
86
+ const marked = (body) => `${BEGIN(INSTRUCTIONS_VERSION)}\n\n${body.trim()}\n\n${END}`;
86
87
 
87
88
  /** The lead's section of CLAUDE.md, between its markers. */
88
89
  export function leadSection(root, config) {
@@ -6,6 +6,7 @@
6
6
  import { execFileSync } from 'node:child_process';
7
7
  import { existsSync, readFileSync } from 'node:fs';
8
8
  import { join } from 'node:path';
9
+ import { dispatches } from './dispatches.mjs';
9
10
  import { APPROVAL_LOG } from './rules.mjs';
10
11
  import { sendBacks } from './reviews.mjs';
11
12
  import { storyTimes } from './timeline.mjs';
@@ -141,10 +142,19 @@ export function journal(root, status, base, docs = {}) {
141
142
  const times = storyTimes(root, status.stories, base);
142
143
  const byId = new Map(status.stories.map((s) => [s.id, s]));
143
144
  const backs = sendBacks(root);
145
+ // SCHED-3: the model each lane agent ran on, from the dispatch log; the session's isn't named.
146
+ const started = dispatches(root).filter((d) => d.model);
147
+ const modelName = (m) => (/^(haiku|sonnet|opus)$/.test(m) ? m[0].toUpperCase() + m.slice(1) : m);
148
+ const ranOn = (branch, before) =>
149
+ started.filter((d) => d.branch === branch && Date.parse(d.at) <= before).at(-1) ?? null;
144
150
  for (const t of times) {
145
151
  const s = byId.get(t.id);
146
152
  const name = `${t.id} ${s?.title ?? ''}`.trim();
147
153
  const reqText = s?.requirements?.length ? ` (${s.requirements.join(', ')})` : '';
154
+ const first = started.find((x) => x.branch === t.branch);
155
+ const onModel = first
156
+ ? ` on ${modelName(first.model)}${first.why ? ` (${first.why})` : ''}`
157
+ : '';
148
158
  if (t.started)
149
159
  events.push({
150
160
  at: t.started,
@@ -153,9 +163,11 @@ export function journal(root, status, base, docs = {}) {
153
163
  text:
154
164
  t.lane === 'lead'
155
165
  ? `The lead started ${name}${reqText} itself.`
156
- : `${name}${reqText} was handed to the ${t.lane} lane.`,
166
+ : `${name}${reqText} was handed to the ${t.lane} lane${onModel}.`,
157
167
  });
158
- for (const b of backs.filter((x) => x.branch === t.branch))
168
+ for (const b of backs.filter((x) => x.branch === t.branch)) {
169
+ const d = t.lane === 'lead' ? null : ranOn(t.branch, Date.parse(b.at));
170
+ const ran = d ? `; it had run on ${modelName(d.model)}.` : '';
159
171
  events.push({
160
172
  at: Date.parse(b.at),
161
173
  kind: 'sentBack',
@@ -163,8 +175,9 @@ export function journal(root, status, base, docs = {}) {
163
175
  text:
164
176
  t.lane === 'lead'
165
177
  ? `${t.id} needed more work from the lead${b.reason ? `: ${b.reason}` : '.'}`
166
- : `The lead sent ${t.id} back to the ${t.lane} lane${b.reason ? `: ${b.reason}` : '.'}`,
178
+ : `The lead sent ${t.id} back to the ${t.lane} lane${b.reason ? `: ${b.reason}${ran}` : ran || '.'}`,
167
179
  });
180
+ }
168
181
  if (t.merged)
169
182
  events.push({
170
183
  at: t.merged,
@@ -13,6 +13,8 @@ import { decidedBy, laneOf, openRequests } from './rules.mjs';
13
13
  import { instructionsState } from './instructions.mjs';
14
14
  import { SECURITY_AGENT_FILE } from './security.mjs';
15
15
  import { laneClaims } from './laneclaims.mjs';
16
+ import { keptBecause, worktrees } from './worktrees.mjs';
17
+ import { storyModels } from './dispatches.mjs';
16
18
  import { pickPerLane } from './schedule.mjs';
17
19
 
18
20
  export const DRAFT_FILE = '.claude/code-kit.draft.json';
@@ -77,7 +79,9 @@ const hasMarkdown = (dir) => {
77
79
  };
78
80
 
79
81
  /**
80
- * { step, why, args, then, attention, brief }. `brief`: the brief's open questions (ASK-4). `step` is a skill (spec-design, init, check, dispatch,
82
+ * { step, why, args, then, attention, brief, worktrees }. `brief`: the brief's open questions (ASK-4);
83
+ * `worktrees`: the merged ones still holding changes, { branch, story, changes, files }, for the person (LEAN-8);
84
+ * `models`: each story offered to a lane, with the model it runs on and why, { story, model, why } (SCHED-3). `step` is a skill (spec-design, init, check, dispatch,
81
85
  * review), `merge` (the head of the merge queue, where the lead merges), `wait` (lanes are
82
86
  * building) or `done`. `base(config)` resolves the branch lanes merge into.
83
87
  */
@@ -85,6 +89,10 @@ export function nextStep(root, base) {
85
89
  const attention = [];
86
90
  // ASK-4: the brief's open questions, for the person's Decisions tab.
87
91
  let briefQuestions = [];
92
+ // LEAN-8: merged worktrees still holding changes, for the person to keep or discard.
93
+ let holdingTrees = [];
94
+ // SCHED-3: the model each story offered to a lane runs on, and why.
95
+ let models = [];
88
96
  const result = (step, why, extra = {}) => ({
89
97
  step,
90
98
  why,
@@ -92,6 +100,8 @@ export function nextStep(root, base) {
92
100
  then: [],
93
101
  attention,
94
102
  brief: briefQuestions,
103
+ worktrees: holdingTrees,
104
+ models,
95
105
  ...extra,
96
106
  });
97
107
  const isRepo = git(root, 'rev-parse', '--is-inside-work-tree') === 'true';
@@ -159,6 +169,26 @@ export function nextStep(root, base) {
159
169
  );
160
170
  }
161
171
 
172
+ // LEAN-8: worktrees that are done with are only disk space; prune takes them after each merge and as a
173
+ // session starts, and those still holding changes are the person's to keep or discard.
174
+ const trees = worktrees(root, config);
175
+ const leftovers = trees.filter((w) => !keptBecause(w) && !w.missing).length;
176
+ if (leftovers)
177
+ attention.push(
178
+ `${leftovers} worktree${leftovers === 1 ? ' is' : 's are'} done with; \`code-kit worktrees prune\` removes them, keeping their reports.`,
179
+ );
180
+ const holding = trees.filter((w) => w.kind === 'agent' && w.merged && !w.clean && !w.agentAtWork);
181
+ holdingTrees = holding.map((w) => ({
182
+ branch: w.branch,
183
+ story: w.story,
184
+ changes: w.changes,
185
+ files: w.files,
186
+ }));
187
+ if (holding.length)
188
+ attention.push(
189
+ `${holding.map((w) => w.branch).join(', ')} ${holding.length === 1 ? 'is' : 'are'} merged, but ${holding.length === 1 ? 'its worktree still holds' : 'their worktrees still hold'} uncommitted changes: the person keeps or discards each, from the band (discarding keeps them as a patch).`,
190
+ );
191
+
162
192
  const { specs, plan } = config.docs ?? {};
163
193
  if (!specs || !plan)
164
194
  return result(
@@ -256,12 +286,6 @@ export function nextStep(root, base) {
256
286
  attention.push(
257
287
  `${unbuildable.join(', ')} can't be dispatched until the plan's gaps are fixed.`,
258
288
  );
259
- // LEAN-6: worktrees whose story is merged and which hold nothing uncommitted are only disk space.
260
- const leftovers = mergedWorktrees(root, config);
261
- if (leftovers)
262
- attention.push(
263
- `${leftovers} worktree${leftovers === 1 ? ' is' : 's are'} merged and clean; \`code-kit worktrees prune\` removes them, keeping their reports.`,
264
- );
265
289
  // ONB-8: code-kit's own instructions to the lead and the lanes, brought up to date before the next step:
266
290
  // a newer code-kit's rules reach the agents only through them.
267
291
  const instructions = instructionsState(root, config);
@@ -341,6 +365,12 @@ export function nextStep(root, base) {
341
365
  const then = [];
342
366
  // A sent-back story goes back to its lane with the review's findings, before new work starts.
343
367
  const toDispatch = [...fixes, ...ready];
368
+ const chosen = storyModels(
369
+ root,
370
+ config,
371
+ status.stories.filter((s) => toDispatch.includes(s.id)),
372
+ );
373
+ models = toDispatch.filter((id) => chosen[id]).map((id) => ({ story: id, ...chosen[id] }));
344
374
  if (review.length && forDesign.length) then.push({ step: 'design', args: forDesign.join(' ') });
345
375
  if (review.length && toDispatch.length)
346
376
  then.push({ step: 'dispatch', args: toDispatch.join(' ') });
@@ -524,23 +554,3 @@ export function missingSkills(root) {
524
554
  }
525
555
  return out;
526
556
  }
527
-
528
- /** LEAN-6: how many of the project's worktrees have a merged branch and nothing uncommitted. */
529
- function mergedWorktrees(root, config) {
530
- const list = git(root, 'worktree', 'list', '--porcelain');
531
- if (!list) return 0;
532
- const from = config.branches?.protected?.[0];
533
- if (!from || !git(root, 'rev-parse', '--verify', '-q', from)) return 0;
534
- let n = 0;
535
- for (const block of list.split('\n\n').slice(1)) {
536
- const path = /^worktree (.+)$/m.exec(block)?.[1];
537
- const branch = /^branch refs\/heads\/(.+)$/m.exec(block)?.[1];
538
- if (!path || !branch) continue;
539
- const merged =
540
- spawnSync('git', ['merge-base', '--is-ancestor', branch, from], { cwd: root }).status === 0;
541
- if (!merged) continue;
542
- const status = spawnSync('git', ['-C', path, 'status', '--porcelain'], { encoding: 'utf8' });
543
- if (status.status === 0 && !status.stdout.trim()) n++;
544
- }
545
- return n;
546
- }
@@ -52,7 +52,7 @@ const field = (lines, name) =>
52
52
  .trim() ?? '';
53
53
 
54
54
  /**
55
- * Every story in the plan: [{ id, title, lane, requirements, dependsOn, status, fixes, milestone, slice }]. A story's
55
+ * Every story in the plan: [{ id, title, lane, requirements, dependsOn, status, fixes, milestone, slice, size }]. A story's
56
56
  * milestone is the `## ` heading above it ("Milestone 5: Your own key"), or null.
57
57
  */
58
58
  export function readStories(root, planPath) {
@@ -82,6 +82,11 @@ export function readStories(root, planPath) {
82
82
  milestone,
83
83
  // SCHED-2: the slice it belongs to, a feature built across lanes, or null.
84
84
  slice: field(body, 'Slice') || null,
85
+ // SCHED-3: small, medium or large, as the lead judged it, or null.
86
+ size:
87
+ field(body, 'Size')
88
+ .toLowerCase()
89
+ .match(/^(small|medium|large)\b/)?.[1] ?? null,
85
90
  });
86
91
  });
87
92
  }
@@ -1,10 +1,15 @@
1
- // What the npm registry says about a package, for the lead's delegated dependency approvals: the
2
- // licence, how often it's downloaded, when it was last released, and whether installing it runs
3
- // scripts. The rule itself is a pure function, so it's tested without the network.
1
+ // What the npm registry, or PyPI for a Python package, says about a package, for the lead's delegated
2
+ // dependency approvals: the licence, how often it's downloaded, when it was last released, and whether
3
+ // installing it runs scripts. The rule itself is a pure function, so it's tested without the network.
4
4
  import { DEPENDENCY_APPROVAL } from './dependencies.mjs';
5
5
 
6
6
  const REGISTRY = () => process.env.CODE_KIT_NPM_REGISTRY ?? 'https://registry.npmjs.org';
7
7
  const DOWNLOADS = () => process.env.CODE_KIT_NPM_DOWNLOADS ?? 'https://api.npmjs.org';
8
+ const PYPI = () => process.env.CODE_KIT_PYPI ?? 'https://pypi.org';
9
+ const PYPI_STATS = () => process.env.CODE_KIT_PYPI_STATS ?? 'https://pypistats.org';
10
+
11
+ /** The package managers whose packages come from PyPI. */
12
+ export const PYPI_MANAGERS = new Set(['pip', 'uv', 'poetry', 'pipenv', 'pdm']);
8
13
 
9
14
  /** The package an approval name stands for: `dep-@scope+pkg` → `@scope/pkg`. */
10
15
  export const packageOf = (approvalName) =>
@@ -69,6 +74,68 @@ export async function npmFacts(pkg) {
69
74
  }
70
75
  }
71
76
 
77
+ // PyPI's licence words as the SPDX ids a rule names: its classifiers first, then its free-text field.
78
+ const PYPI_LICENCES = [
79
+ [/\bMIT\b/i, 'MIT'],
80
+ [/\bApache\b.*2|Apache Software License/i, 'Apache-2.0'],
81
+ [/BSD.*3|3-Clause|New BSD|Modified BSD/i, 'BSD-3-Clause'],
82
+ [/BSD.*2|2-Clause|Simplified BSD/i, 'BSD-2-Clause'],
83
+ [/\bISC\b/i, 'ISC'],
84
+ [/Python Software Foundation|\bPSF\b/i, 'PSF-2.0'],
85
+ [/Mozilla Public License 2|\bMPL[- ]?2/i, 'MPL-2.0'],
86
+ [/\bLGPL/i, 'LGPL'],
87
+ [/\bAGPL/i, 'AGPL-3.0'],
88
+ [/\bGPL.*3|GPLv3/i, 'GPL-3.0'],
89
+ [/\bGPL.*2|GPLv2/i, 'GPL-2.0'],
90
+ ];
91
+
92
+ /** A PyPI project's licence as an SPDX id: its licence expression, else its classifiers, else its text. */
93
+ export function pypiLicence(info) {
94
+ if (info?.license_expression) return info.license_expression;
95
+ const words = [
96
+ ...(info?.classifiers ?? []).filter((c) => c.startsWith('License ::')),
97
+ ...(info?.license && info.license.length <= 80 ? [info.license] : []),
98
+ ];
99
+ for (const w of words) for (const [re, id] of PYPI_LICENCES) if (re.test(w)) return id;
100
+ return info?.license && info.license.length <= 40 ? info.license : 'unknown';
101
+ }
102
+
103
+ /**
104
+ * #70: the same facts for a Python package, from PyPI: a release with no wheel builds from source as it
105
+ * installs, which is what an npm install script that compiles is.
106
+ */
107
+ export async function pypiFacts(pkg) {
108
+ const name = encodeURIComponent(pkg.replace(/\[.*\]$/, '').toLowerCase());
109
+ try {
110
+ const meta = await fetch(`${PYPI()}/pypi/${name}/json`, {
111
+ headers: { accept: 'application/json' },
112
+ });
113
+ if (meta.status === 404) return { error: `${pkg} isn't on PyPI` };
114
+ if (!meta.ok) return { error: `PyPI answered ${meta.status} for ${pkg}` };
115
+ const doc = await meta.json();
116
+ const files = doc.urls ?? [];
117
+ const stats = await fetch(`${PYPI_STATS()}/api/packages/${name}/recent`, {
118
+ headers: { accept: 'application/json' },
119
+ });
120
+ const weeklyDownloads = stats.ok ? ((await stats.json()).data?.last_week ?? 0) : 0;
121
+ const wheel = files.some((f) => f.packagetype === 'bdist_wheel');
122
+ return {
123
+ licence: pypiLicence(doc.info),
124
+ weeklyDownloads,
125
+ lastRelease:
126
+ files
127
+ .map((f) => f.upload_time_iso_8601)
128
+ .filter(Boolean)
129
+ .sort()
130
+ .at(-1) ?? null,
131
+ installScripts: files.length > 0 && !wheel,
132
+ installScriptKind: files.length > 0 && !wheel ? 'build' : null,
133
+ };
134
+ } catch (e) {
135
+ return { error: `couldn't reach PyPI (${e.message})` };
136
+ }
137
+ }
138
+
72
139
  /** Why `facts` falls outside `rule`, as sentences; empty when it's within it. */
73
140
  export function dependencyRuleProblems(facts, rule, now = Date.now()) {
74
141
  if (facts.error) return [facts.error];