@warren-dean/code-kit 0.22.1 → 0.23.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.
@@ -9,7 +9,7 @@
9
9
  "name": "code-kit",
10
10
  "source": "./",
11
11
  "description": "Keeps AI coding agents inside your project's rules, from idea to merged code: spec design, lanes, layer rules, protected paths with an approval log, spec-check and design gates, proof-before-finish checks, dispatch, review, build status and CI verification, configured per project from its docs",
12
- "version": "0.22.1",
12
+ "version": "0.23.0",
13
13
  "category": "development",
14
14
  "tags": ["guardrails", "architecture", "lanes", "layers", "spec-driven", "ci", "multi-agent"],
15
15
  "license": "MIT"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "code-kit",
3
- "version": "0.22.1",
3
+ "version": "0.23.0",
4
4
  "description": "Keeps AI coding agents inside your project's rules, from idea to merged code: spec design, lanes, layer rules, protected paths with an approval log, spec-check and design gates, proof-before-finish checks, dispatch, review, build status and CI verification, configured per project from its docs",
5
5
  "author": {
6
6
  "name": "Warren Langeveldt"
package/CHANGELOG.md CHANGED
@@ -2,6 +2,22 @@
2
2
 
3
3
  What changed in each release of code-kit, newest first. Versions follow the plugin manifest and the npm package `@warren-dean/code-kit`. Each release is also on [GitHub Releases](https://github.com/warrendeanlangeveldt/code-kit/releases).
4
4
 
5
+ ## 0.23.0 (2026-10-23)
6
+
7
+ Worktrees no longer fill the disk, bug reports send once, and a batch of reported bugs is fixed.
8
+
9
+ - A worktree goes once it's done with: its branch's own commits are merged, it holds nothing uncommitted, and no agent of its lane still holds the story. This happens after each merge and, in the background, as each session starts, along with an interrupted merge's temporary checkout, worktrees whose folder is gone, and stray folders under `.claude/worktrees`. `code-kit worktrees` says why each one that stays is staying.
10
+ - A merged worktree that still holds uncommitted changes waits in the band for you, with what it holds. Keep leaves it; Discard removes it and keeps the changes as a patch under `.claude/state/discarded`. No agent can discard one.
11
+ - A branch made for an agent just dispatched, with no commits of its own, is no longer taken as merged (#61).
12
+ - Sending a bug report claims it first, so pressing Send again while GitHub is still filing it files nothing more. The report leaves the band at once, and the result is a toast; a pane opens only when it fails.
13
+ - `approvals.delegate.push` (or `code-kit settings set approvals.push lead`) lets the lead push the protected branch, read from the config committed there, never by force or delete. Left out, pushing stays yours (#63).
14
+ - A Python lane's packages are checked on PyPI for the delegated rules: licence, downloads, last release, and whether a release has wheels (#70).
15
+ - A check that runs out of time leaves its branch at the head of the merge queue instead of sending it back, and says how to give it longer with `timeoutSeconds` (#62). A failed check's output leaves out Node's warnings and leads with the lines that name the failure, and the queue records which check failed (#57).
16
+ - The commit hook logs a renamed protected file's old path (#74), and counts files staged in the same command by a brace list, a glob, a variable or a soft reset (#76), and a commit made with `cd <worktree> && git commit` in that worktree (#55). A branch's spec-check report is kept in the main checkout when its worktree goes (#55).
17
+ - No hand-back or restart prompt for a story that's merged and done (#59).
18
+ - `instructions --write` keeps the blank lines Prettier puts inside code-kit's markers (#77).
19
+ - `requests drop` drops requests that carry a session (#78).
20
+
5
21
  ## 0.22.1 (2026-10-23)
6
22
 
7
23
  For projects on the hosted team provider, which is in preview:
package/README.md CHANGED
@@ -133,7 +133,7 @@ Set it up at the start of a new build, straight from the architecture docs, or b
133
133
  - **For the main session and every subagent**, including agents in worktrees under `.claude/worktrees/`.
134
134
  - **In front of you, in the terminal and the Desktop app,** through the code-kit mod (Claude Code 2.1.287 or later; see [In the session](#in-the-session)). It shows and acts, and never enforces: the hooks above do that everywhere, the mod or not.
135
135
  - **In CI**, through `code-kit verify` in a GitHub Actions workflow that init can install (`templates/github-workflow.yml`).
136
- - **Locally, with Node 22 or later.** The CLI in `bin/` runs the same rules from a terminal. The rules themselves send nothing over the network. Three features do, and only when you use them: delegated dependency approvals read the package from the npm registry, the team features (`team`, `intend`) talk to GitHub through your `gh`, or to the team provider you configure, and a bug report you send goes to code-kit's GitHub through your `gh`.
136
+ - **Locally, with Node 22 or later.** The CLI in `bin/` runs the same rules from a terminal. The rules themselves send nothing over the network. Three features do, and only when you use them: delegated dependency approvals read the package from the npm registry or PyPI, the team features (`team`, `intend`) talk to GitHub through your `gh`, or to the team provider you configure, and a bug report you send goes to code-kit's GitHub through your `gh`.
137
137
 
138
138
  ## Install
139
139
 
@@ -452,7 +452,8 @@ code-kit verify [--base ref] [--branch name] [--no-checks] [--json] # a branch'
452
452
  code-kit security [--base ref] [--branch name] [--json] # whether a branch needs the security review, and why: sign-in, permissions, outside input, personal data, payments, secrets, dependencies
453
453
  code-kit status [--base ref] [--json] # stories and requirements against the spec
454
454
  code-kit next [--base ref] [--json] # the step to take now, from the project's state
455
- code-kit worktrees [--json] | worktrees release <branch> | worktrees prune # the project's worktrees; free one for a fresh agent on its story, or remove every merged and clean one, keeping their reports
455
+ code-kit worktrees [--json] | worktrees release <branch> | worktrees prune [--quiet] # the project's worktrees and why each stays; free one for a fresh agent on its story, or remove every one that's done with, keeping their reports (also after each merge and as a session starts)
456
+ code-kit worktrees discard <branch> # the person's, from the band: remove a merged worktree that still holds changes, kept as a patch
456
457
  code-kit instructions [--write] [--json] | instructions show lead|lane [<lane>] # code-kit's part of CLAUDE.md and the lane agents: where each stands, brought up to date, or printed
457
458
  code-kit standards [--json] [--for <path>...] # the project's standards with any its organisation's provider supplies, and what's wrong with them; --for keeps the ones for those files' layers
458
459
  code-kit trace <path>... [--json] # what a file is for: requirements, lane, layer rules
@@ -530,10 +531,10 @@ code-kit approve <name>... --reason "…" [--lane name] [--delegated [--story ST
530
531
  | `postEdit[]` | no | `{ files, exclude?, run }`: after each edit of a matching file. `{file}` is the file. Exit 127 (tool not installed) is skipped. |
531
532
  | `tests[]` | no | Globs naming the test files, for the weakened-test and fix rules. Default: the usual conventions (`*.test.*`, `*.spec.*`, `__tests__/`, `test/`, `tests/`, `e2e/`, `*_test.go`, `test_*.py`). |
532
533
  | `regression.prepare` | no | A command run in a fresh checkout before a fix's tests run there without the fix, such as `npm ci`. Without it, the checkout's `node_modules` and virtualenvs are linked in. |
533
- | `checks[]` | no | `{ name, files, exclude?, run[], each?, owners?, ifMissing?, timeoutSeconds? }`: before finishing, when matching files changed. `each` runs the commands in every changed folder matching that glob. `owners` limits who may change the files (the lead always may). `ifMissing: "fail"` makes a missing tool an error (the default is to skip the check, which `verify` and a merge list as not run). |
534
+ | `checks[]` | no | `{ name, files, exclude?, run[], each?, owners?, ifMissing?, timeoutSeconds? }`: before finishing, when matching files changed. `each` runs the commands in every changed folder matching that glob. `owners` limits who may change the files (the lead always may). `ifMissing: "fail"` makes a missing tool an error (the default is to skip the check, which `verify` and a merge list as not run). `timeoutSeconds` (240 unless set) is how long each command may run; one that runs out of time leaves its branch at the head of the merge queue rather than sending it back. |
534
535
  | `adapters` | no | `{ "<adapter>": false }` switches off an adapter that would otherwise be detected; `true` says the project wants that tool, so until it's set up here `next` gives its setup before any code. See [Adapters](#adapters). |
535
536
  | `approvals.lead` | no | `true` lets the lead act on what the person says in chat, for when `!` isn't available (on a phone, say): it records their approvals with `code-kit approve`, and runs `shell.block` commands marked `person`. Default `false`. See [Approvals](#approvals). |
536
- | `approvals.delegate` | no | `false`, or `{ protected?: [approval names], merge?: true, tests?: true, dependencies?: { licences?, minWeeklyDownloads?, maxMonthsSinceRelease?, allowInstallScripts?: true \| false \| [kinds] } }`: what the lead decides, inside the guardrails you keep: the protected approvals it grants, and packages it approves for a story, with `code-kit approve --delegated`; with `merge`, merges into a protected branch with `code-kit merge --delegated`; with `tests`, weakened tests on a lane's branch. Left out, the lead decides everything technical: every protected approval but `spec`, `design`, `ci` and `kit`, packages, merges and weakened tests (WHO-1); `false` keeps everything for you. Lanes ask the lead for these, never you. npm packages are also checked against the registry; the defaults are MIT, Apache-2.0, BSD and ISC, 10,000 weekly downloads, a release within 18 months, and no install scripts. See [Approvals](#approvals). |
537
+ | `approvals.delegate` | no | `false`, or `{ protected?: [approval names], merge?: true, push?: true, tests?: true, dependencies?: { licences?, minWeeklyDownloads?, maxMonthsSinceRelease?, allowInstallScripts?: true \| false \| [kinds] } }`: what the lead decides, inside the guardrails you keep: the protected approvals it grants, and packages it approves for a story, with `code-kit approve --delegated`; with `merge`, merges into a protected branch with `code-kit merge --delegated`; with `push`, pushes the protected branch, never by force (yours unless you set it, since a push can deploy; read from the config committed on that branch); with `tests`, weakened tests on a lane's branch. Left out, the lead decides everything technical: every protected approval but `spec`, `design`, `ci` and `kit`, packages, merges and weakened tests (WHO-1); `false` keeps everything for you. Lanes ask the lead for these, never you. npm packages are also checked against the npm registry, and a Python lane's against PyPI; the defaults are MIT, Apache-2.0, BSD and ISC, 10,000 weekly downloads, a release within 18 months, and no install scripts. See [Approvals](#approvals). |
537
538
  | `setup` | no | The version of init's setup the project has (3 now). Without it, or lower, `next` names what the project is missing (the design gate, design stories before screens, a QA lane, a security reviewer) and starts no new story until re-running init adds it |
538
539
  | `team` | no | Preview. For several people in one repository: `{ techLead, staleDays?, intents?, board?, provider?, report? }`. `techLead` is the GitHub handle of the person who owns the plan, specs and contracts; `staleDays` is how many working days without a push make a claim stale (default 3); `intents` is the discussion category intents go in (default `Intents`; create it once in the repository's Settings › Discussions); `board` is `{ owner, number }`, a GitHub Project the plan is mirrored onto; `provider` is `"github"` (default), `{ command, fallback? }` for another team provider, or, in preview, a hosted provider's adapter as `{ "<name>": "<https address>" }`, which keeps the intents (Discussions only when `intents` is set) and has GitHub as its fallback; with `fallback: "github"`, claims go through GitHub whenever that provider can't be reached; `report` (default true) is whether the project reports its facts (stories' stages, send-backs, the requirement trail, approvals, token use and the rules; never code) to a provider that isn't GitHub. A provider may also supply an organisation's standards (`standards`, answering `{ standards, waivers, version }`, each standard in `docs.standards`' fields, each waiver `{ standard, paths?, expires?, reason?, approvedBy? }`): they apply as if in the project's file, which may extend or tighten one but weaken a required one only under a waiver. See docs/specs/16-teams.md, docs/specs/21-hub-adapter-and-reports.md and docs/specs/22-standards.md. |
539
540
  | `branches.protected` | no | Default `["main", "master"]` |
package/bin/code-kit.mjs CHANGED
@@ -44,7 +44,6 @@
44
44
  // --config <file> reads a draft (.claude/code-kit.draft.json) instead of .claude/code-kit.json.
45
45
  import { execFileSync, spawnSync } from 'node:child_process';
46
46
  import {
47
- copyFileSync,
48
47
  existsSync,
49
48
  mkdirSync,
50
49
  mkdtempSync,
@@ -138,7 +137,13 @@ import {
138
137
  reviewerOf,
139
138
  } from '../hooks/lib/rules.mjs';
140
139
  import { DEPENDENCY_APPROVAL, dependencyApproval } from '../hooks/lib/dependencies.mjs';
141
- import { dependencyRuleProblems, npmFacts, packageOf } from '../hooks/lib/registry.mjs';
140
+ import {
141
+ PYPI_MANAGERS,
142
+ dependencyRuleProblems,
143
+ npmFacts,
144
+ packageOf,
145
+ pypiFacts,
146
+ } from '../hooks/lib/registry.mjs';
142
147
  import { heldTo, laneOfBranch, verifyBranch } from '../hooks/lib/verify.mjs';
143
148
  import { skippedLine } from '../hooks/lib/checks.mjs';
144
149
  import { TESTS_APPROVAL } from '../hooks/lib/regression.mjs';
@@ -155,6 +160,14 @@ import {
155
160
  takeTask,
156
161
  } from '../hooks/lib/sessions.mjs';
157
162
  import { globsOverlap } from '../hooks/lib/teamfacts.mjs';
163
+ import {
164
+ cleanOf,
165
+ discardWorktree,
166
+ keptBecause,
167
+ pruneWorktrees,
168
+ removeWorktree,
169
+ worktrees,
170
+ } from '../hooks/lib/worktrees.mjs';
158
171
  import { decisionsFor, openDecisions } from '../hooks/lib/decisionstore.mjs';
159
172
  import {
160
173
  appliesTo,
@@ -575,12 +588,30 @@ const firstMerge = (into, branch) =>
575
588
 
576
589
  /** Why a merge didn't happen: `refused` (the rules), `verify` (problems) or `conflict`. */
577
590
  class MergeStop extends Error {
578
- constructor(kind, message) {
591
+ /** `first`: the first problem's first line, for the queue's record of why (#57). */
592
+ constructor(kind, message, first = null) {
579
593
  super(message);
580
594
  this.kind = kind;
595
+ this.first = first;
581
596
  }
582
597
  }
583
598
 
599
+ /**
600
+ * #70: the ecosystem a lane's packages come from, by the manifests in its paths: `uv` for a lane with a
601
+ * pyproject.toml, requirements file or uv.lock and no package.json, otherwise `npm`.
602
+ */
603
+ function laneEcosystem(config, lane) {
604
+ const paths = lane ? (config.lanes[lane]?.paths ?? []) : (config.lead?.paths ?? []);
605
+ const tracked = (spawnSync('git', ['ls-files'], { encoding: 'utf8' }).stdout ?? '')
606
+ .split('\n')
607
+ .filter((f) => f && matchesAny(f, paths));
608
+ const named = (re) => tracked.some((f) => re.test(f.split('/').at(-1)));
609
+ return named(/^(pyproject\.toml|uv\.lock|requirements[\w.-]*\.txt|Pipfile)$/) &&
610
+ !named(/^package\.json$/)
611
+ ? 'uv'
612
+ : 'npm';
613
+ }
614
+
584
615
  /** Who merges, from the flags: the lead within the delegated rules, or the person. */
585
616
  function mergeMode() {
586
617
  const byPerson = flag('--person');
@@ -653,9 +684,9 @@ function mergeOne(branch, config, byPerson, commit = null) {
653
684
  }
654
685
  }
655
686
  };
656
- const fail = (message, kind = 'refused') => {
687
+ const fail = (message, kind = 'refused', first = null) => {
657
688
  cleanup();
658
- throw new MergeStop(kind, message);
689
+ throw new MergeStop(kind, message, first);
659
690
  };
660
691
  const worktree = (b, detach) => {
661
692
  const dir = mkdtempSync(join(tmpdir(), 'code-kit-merge-'));
@@ -676,7 +707,7 @@ function mergeOne(branch, config, byPerson, commit = null) {
676
707
  'moved',
677
708
  );
678
709
  const lane = laneOfBranch(branch, config);
679
- const { changed, found, skipped } = verifyBranch({
710
+ const { changed, found, skipped, unfinished } = verifyBranch({
680
711
  root: verifyIn,
681
712
  base: into,
682
713
  config,
@@ -687,10 +718,17 @@ function mergeOne(branch, config, byPerson, commit = null) {
687
718
  const problems = Object.entries(VERIFY_GROUPS).flatMap(([key, title]) =>
688
719
  found[key].map((p) => `${title}: ${p.split('\n').join('\n ')}`),
689
720
  );
721
+ // #62: a check that only ran out of time says nothing against the branch: it's tried again.
722
+ if (problems.length === 1 && unfinished)
723
+ fail(
724
+ `Nothing was merged: a check on ${branch} didn't finish, which says nothing against the branch (checked in ${verifyIn}):\n ${problems[0]}\nIt stays at the head of the queue; merge again once fewer suites are running.`,
725
+ 'unfinished',
726
+ );
690
727
  if (problems.length)
691
728
  fail(
692
729
  `Nothing was merged. code-kit verify found ${problems.length} problem(s) on ${branch} (checked in ${verifyIn}):\n ${problems.join('\n ')}\nSend it back to its lane, or fix it, then merge again.`,
693
730
  'verify',
731
+ problems[0].split('\n')[0],
694
732
  );
695
733
  const mergeIn = checkedOut(into) ?? worktree(into, false);
696
734
  clean(mergeIn, into);
@@ -720,21 +758,11 @@ function mergeOne(branch, config, byPerson, commit = null) {
720
758
  const team = teamOf(config);
721
759
  const story = storyOfBranch(branch);
722
760
  if (team && story) teamProvider(resolve('.'), team).release(story, { merged: true });
723
- // A lane agent's worktree has done its work once its branch is merged: removed when it holds
724
- // nothing uncommitted (the branch stays), so finished lanes don't pile up checkouts.
725
- let removed = '';
726
- const agentTree = checkedOut(branch);
727
- if (
728
- agentTree?.includes('/.claude/worktrees/') &&
729
- !g(agentTree, 'status', '--porcelain').trim()
730
- ) {
731
- try {
732
- g(root, 'worktree', 'remove', agentTree);
733
- removed = ` Removed its worktree, ${agentTree}.`;
734
- } catch {
735
- // in use, or locked: left as it is
736
- }
737
- }
761
+ // LEAN-8: the merged branch's worktree, and any other that's done with, go now.
762
+ const pruned = pruneWorktrees(root, config).removed;
763
+ const removed = pruned.length
764
+ ? ` Removed ${pruned.length} worktree${pruned.length === 1 ? '' : 's'} that ${pruned.length === 1 ? 'was' : 'were'} done with.`
765
+ : '';
738
766
  return {
739
767
  into,
740
768
  message: `Merged ${branch} into ${into}: verify passed on ${changed.length} file(s)${lane ? `, held to ${heldTo(lane)}` : ''}, at ${tip.slice(0, 7)}.${skipped.length ? ` ${notRun(skipped)}` : ''}${removed}`,
@@ -800,6 +828,7 @@ function queue() {
800
828
  if (e.kind === 'refused') die(e.message);
801
829
  // A branch that moved after its review leaves the queue for the lead to review it again; it
802
830
  // isn't sent back, since nothing is wrong with it yet.
831
+ if (e.kind === 'unfinished') die(e.message);
803
832
  if (e.kind === 'moved') {
804
833
  settle(root, head.branch, 'moved', 'changed after its review');
805
834
  die(`${e.message}\n${head.branch} leaves the queue until then.`);
@@ -809,7 +838,7 @@ function queue() {
809
838
  const why =
810
839
  e.kind === 'conflict'
811
840
  ? `conflicts with ${into}${after ? ` after ${after}` : ''}`
812
- : `fails verify against ${into}${after ? ` after ${after}` : ''}`;
841
+ : `fails verify against ${into}${after ? ` after ${after}` : ''}${e.first ? `: ${e.first}` : ''}`;
813
842
  const sha = execFileSync('git', ['rev-parse', '--verify', `${head.branch}^{commit}`], {
814
843
  encoding: 'utf8',
815
844
  }).trim();
@@ -1669,19 +1698,23 @@ async function approve(given) {
1669
1698
  continue;
1670
1699
  }
1671
1700
  const pkg = packageOf(name);
1672
- // HELM-3: the registry rules are npm's; a package from another ecosystem is the lead's judgement.
1673
- const registries = new Set(
1701
+ // HELM-3: the registry rules are npm's and PyPI's (#70); a package from another ecosystem is the
1702
+ // lead's judgement. Which one is the request's, or else the lane's own manifests'.
1703
+ const asked = new Set(
1674
1704
  openRequests(resolve('.'))
1675
1705
  .filter((r) => r.names.includes(name) && (r.lane ?? undefined) === laneName)
1676
1706
  .map((r) => r.registries?.[pkg])
1677
1707
  .filter(Boolean),
1678
1708
  );
1679
- const npm = !registries.size || registries.has('npm');
1680
- const problems = npm ? dependencyRuleProblems(await npmFacts(pkg), rules.dependencies) : [];
1709
+ const registries = asked.size ? asked : new Set([laneEcosystem(config, laneName)]);
1710
+ const npm = registries.has('npm');
1711
+ const pypi = !npm && [...registries].some((r) => PYPI_MANAGERS.has(r));
1712
+ const facts = npm ? await npmFacts(pkg) : pypi ? await pypiFacts(pkg) : null;
1713
+ const problems = facts ? dependencyRuleProblems(facts, rules.dependencies) : [];
1681
1714
  if (problems.length) outside.push(`${name}: ${problems.join('; ')}`);
1682
1715
  else
1683
1716
  marks[name] = delegatedMark(
1684
- `dependencies (${pkg}${npm ? '' : `, from ${[...registries].join(', ')}, judged by the lead`}) for ${story.id}`,
1717
+ `dependencies (${pkg}${npm ? '' : pypi ? ', from PyPI' : `, from ${[...registries].join(', ')}, judged by the lead`}) for ${story.id}`,
1685
1718
  );
1686
1719
  } else if (rules.protected.includes(name))
1687
1720
  marks[name] = delegatedMark(`protected: ${name}${story ? ` for ${story.id}` : ''}`);
@@ -2335,78 +2368,71 @@ function instructionsCommand() {
2335
2368
  );
2336
2369
  }
2337
2370
 
2338
- /** LEAN-6: a worktree of the project, with its branch, story, report and whether it's merged and clean. */
2339
- function worktreeList(config) {
2340
- const root = resolve('.');
2341
- const run = (...a) => spawnSync('git', a, { cwd: root, encoding: 'utf8' }).stdout?.trim() ?? '';
2342
- const from = findBase(config, false);
2343
- const blocks = run('worktree', 'list', '--porcelain').split('\n\n').filter(Boolean);
2344
- return blocks.slice(1).map((b) => {
2345
- const path = /^worktree (.+)$/m.exec(b)?.[1];
2346
- const branch = /^branch refs\/heads\/(.+)$/m.exec(b)?.[1] ?? null;
2347
- const report = branch ? `.claude/state/reports/${branch.replace(/[^\w.-]+/g, '_')}.md` : null;
2348
- const status = spawnSync('git', ['-C', path, 'status', '--porcelain'], { encoding: 'utf8' });
2349
- return {
2350
- path,
2351
- branch,
2352
- story: branch ? storyOfBranch(branch) : null,
2353
- merged: Boolean(
2354
- branch &&
2355
- from &&
2356
- spawnSync('git', ['merge-base', '--is-ancestor', branch, from], { cwd: root }).status === 0,
2357
- ),
2358
- clean: status.status === 0 && !status.stdout.trim(),
2359
- report: report && existsSync(join(path, report)) ? report : null,
2360
- };
2361
- });
2362
- }
2363
-
2364
- /** LEAN-6: releases a worktree: its report kept in the main checkout, the worktree removed, its branch kept. */
2371
+ /** LEAN-6: releases a worktree for a fresh agent: its report kept in the main checkout, its branch kept. */
2365
2372
  function releaseWorktree(w) {
2366
- if (!w.clean)
2373
+ if (!cleanOf(w))
2367
2374
  die(
2368
2375
  `${w.branch ?? w.path} has uncommitted changes; nothing was removed. Commit them on the branch, or have its agent do so, then release it.`,
2369
2376
  );
2370
- if (w.report) {
2371
- mkdirSync(join(resolve('.'), '.claude/state/reports'), { recursive: true });
2372
- copyFileSync(join(w.path, w.report), join(resolve('.'), w.report));
2373
- }
2374
- const removed = spawnSync('git', ['worktree', 'remove', w.path], {
2375
- cwd: resolve('.'),
2376
- encoding: 'utf8',
2377
- });
2378
- if (removed.status !== 0) die(`git worktree remove failed: ${removed.stderr.trim()}`);
2377
+ const r = removeWorktree(resolve('.'), w);
2378
+ if (!r.ok) die(`git worktree remove failed: ${r.why}`);
2379
2379
  return `${w.branch ?? w.path}${w.report ? ` (its report kept at ${w.report})` : ''}`;
2380
2380
  }
2381
2381
 
2382
2382
  /**
2383
- * LEAN-6: `worktrees` lists the project's worktrees; `release <branch>` frees one for a fresh agent on the
2384
- * same story; `prune` releases every one whose branch is merged and that holds nothing uncommitted.
2383
+ * LEAN-6, LEAN-8: `worktrees` lists the project's worktrees and why each one stays; `release <branch>`
2384
+ * frees one for a fresh agent on the same story; `prune` takes away every one that's done with;
2385
+ * `discard <branch>`, the person's act, takes away a merged one that still holds changes, keeping them
2386
+ * as a patch.
2385
2387
  */
2386
2388
  function worktreesCommand() {
2387
2389
  const { config } = load();
2388
- const list = worktreeList(config);
2390
+ const root = resolve('.');
2391
+ const list = worktrees(root, config);
2389
2392
  if (rest[0] === 'release') {
2390
2393
  const w = list.find((x) => x.branch === rest[1] || x.path === rest[1]);
2391
2394
  if (!w) die(`No worktree has ${rest[1] ?? '<branch>'} checked out.`);
2392
2395
  return out(`Released ${releaseWorktree(w)}. The branch and its commits stay.`);
2393
2396
  }
2397
+ if (rest[0] === 'discard') {
2398
+ if (!rest[1]) die('code-kit worktrees discard <branch>');
2399
+ const r = discardWorktree(root, config, rest[1]);
2400
+ if (!r.ok) die(`${r.why} Nothing was removed.`);
2401
+ return out(
2402
+ `Removed ${rest[1]}'s worktree.${r.patch ? ` What it held is kept in ${r.patch}: \`git apply ${r.patch}\` on the branch brings it back.` : ''}${r.report ? ` Its report is kept at ${r.report}.` : ''}`,
2403
+ );
2404
+ }
2394
2405
  if (rest[0] === 'prune') {
2395
- const done = list.filter((w) => w.merged && w.clean);
2396
- if (!done.length) return out('No worktree is both merged and clean; nothing was removed.');
2397
- for (const w of done) out(`Released ${releaseWorktree(w)}.`);
2406
+ const { removed, kept } = pruneWorktrees(root, config);
2407
+ if (flag('--quiet')) return;
2408
+ if (!removed.length) out('Nothing was done with; nothing was removed.');
2409
+ for (const r of removed) out(`Removed ${r}.`);
2410
+ const decide = kept.filter((k) => k.kind === 'agent' && /uncommitted/.test(k.why));
2411
+ if (decide.length)
2412
+ out(
2413
+ `\n${decide.length} merged worktree${decide.length === 1 ? ' still holds' : 's still hold'} uncommitted changes, so ${decide.length === 1 ? 'it stays' : 'they stay'} for the person to keep or discard: ${decide.map((k) => k.label).join(', ')}.`,
2414
+ );
2398
2415
  return;
2399
2416
  }
2400
- if (flag('--json')) return out(JSON.stringify(list, null, 2));
2417
+ if (flag('--json'))
2418
+ return out(
2419
+ JSON.stringify(
2420
+ list.map((w) => ({ ...w, kept: keptBecause(w) })),
2421
+ null,
2422
+ 2,
2423
+ ),
2424
+ );
2401
2425
  if (!list.length) return out('No worktrees besides the main checkout.');
2402
- for (const w of list)
2426
+ for (const w of list) {
2427
+ const why = keptBecause(w);
2403
2428
  out(
2404
- ` ${w.branch ?? '(detached)'}${w.story ? ` · ${w.story}` : ''}: ${w.merged ? 'merged' : 'not merged'}, ${w.clean ? 'clean' : 'uncommitted changes'} ${w.path}`,
2429
+ ` ${w.branch ?? '(detached)'}${w.story ? ` · ${w.story}` : ''}: ${why ? `stays, as ${why}` : 'done with'} ${w.path}`,
2405
2430
  );
2406
- const prunable = list.filter((w) => w.merged && w.clean).length;
2407
- if (prunable)
2431
+ }
2432
+ const done = list.filter((w) => !keptBecause(w)).length;
2433
+ if (done)
2408
2434
  out(
2409
- `\n${prunable} merged and clean: \`code-kit worktrees prune\` removes them, keeping their reports.`,
2435
+ `\n${done} done with: \`code-kit worktrees prune\` removes ${done === 1 ? 'it' : 'them'}, keeping their reports. It runs by itself after each merge and as a session starts.`,
2410
2436
  );
2411
2437
  }
2412
2438
 
@@ -2526,7 +2552,7 @@ function usage() {
2526
2552
  ' | next [--base ref] [--json] | adapters | trace <path>... [--json]\n' +
2527
2553
  ' | instructions [--write] [--json] | instructions show lead|lane [<lane>]\n' +
2528
2554
  ' | standards [--json] [--for <path>...]\n' +
2529
- ' | worktrees [--json] | worktrees release <branch> | worktrees prune\n' +
2555
+ ' | worktrees [--json] | worktrees release|discard <branch> | worktrees prune [--quiet]\n' +
2530
2556
  ' | approve <name>... --reason "…" [--lane name] [--config file]\n' +
2531
2557
  ' | merge <branch> --delegated|--person [--into branch] | requests [--json] | requests drop <n>|all\n' +
2532
2558
  ' | ask "<question>" [--story ST-n] [--blocks] [--why "…"] [--option "Label: effect"]... | ask [--json]\n' +
@@ -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),