@warren-dean/code-kit 0.31.1 → 0.32.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.31.1",
12
+ "version": "0.32.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.31.1",
3
+ "version": "0.32.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,17 @@
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.32.0 (2026-11-06)
6
+
7
+ - **Writes outside the checkout before a commit.** Drafting a commit message in a scratchpad and committing it in one command (`git log -1 --format=%B > /tmp/msg && sed -i '' 's/…/…/' /tmp/msg && git commit --amend -F /tmp/msg`) was refused as a command that may write files the commit can't see. A read whose output goes only to full paths outside the project and the commit's checkout, and sed's substitutions on such files in place, can't change what's committed, so they're allowed. A path from a variable, a link back into the project, a sed that writes a file or runs a command, and any write into the checkout are still refused.
8
+ - **Lane agents know the spec-check table before they write code.** A lane agent that wrote its spec-check report by hand, without the skill, often left out the requirement table. The report saved, but every code edit after it was refused, several at a time, until the agent rewrote the report. The lane agents' instructions and dispatch's brief now say the report is a table whose header row starts `| Requirement |`, one row per requirement, and that the path guard reads a report without it as none. Projects get the new wording when `code-kit next` brings their instructions up to date.
9
+ - **A lane agent stopped mid-command no longer holds its worktree for good.** `code-kit worktrees release <branch>` refused as long as the lane agent's last recorded act had no end, which is what an agent stopped in the middle of a command leaves behind. The refusal said the agent was still at work, though none was running, and nothing the lead could do would clear it. An open act now holds the worktree only while its agent may still be in it. Once `code-kit next` has reconciled the act, or the agent's session has ended, it handed back, or the act is older than the stall restart (`harness.stall.restartMinutes`, 10 by default), the release goes ahead.
10
+ - **A merged worktree holding only a tool's records goes.** A tool that writes its records in every worktree at each turn's end (Context Graph's `.ctx/` files) left each merged lane worktree with an uncommitted change, so `code-kit worktrees prune` kept every one, installs and all, for the person to decide. Those changes are now kept as a patch under `.claude/state/discarded/`, and the worktree goes; one holding anything else is still the person's.
11
+ - **The merge queue no longer copies the installs on every merge.** Each merge checked the branch in a new checkout with its own copy of `node_modules` (a copy-on-write clone, so no disk space, but every one of its files created and then deleted again). With several projects merging, that kept macOS's file-change tracking and Spotlight busy enough to slow the whole machine. The merge queue and the fix check now keep one checkout each per project, with its installs, and reuse it: each run checks out the tree it needs and installs again only where the manifests and lockfiles differ from the ones its installs were made for. It lives in the temporary folder under `code-kit-checkouts.noindex`, which Spotlight skips, and `code-kit worktrees` keeps it.
12
+ - **One worktree per lane.** Claude Code made a new worktree for every lane agent, so each story, send-back and restart got a folder and installs of its own; in one project, 25 of them held 85 GB. Each lane now has one worktree, `.claude/worktrees/lane-<lane>`, kept from story to story with its installs: code-kit's `WorktreeCreate` hook gives it to the lane's agent, detached at the main checkout's HEAD, and the agent makes or switches to its story's branch as before. Start agents that work in worktrees one per message: the hook is told only the worktree's name, so code-kit notes the lane as each agent starts and refuses a second until the first has its worktree. A lane worktree still holding uncommitted work isn't reused (the next agent gets its own); once its story is merged, `worktrees prune` keeps it and lets go of the branch. Every other agent gets the worktree Claude Code would make, with the files `.worktreeinclude` names, taken away with its branch when the agent stops having changed nothing.
13
+ - **A quoted variable before a commit is one assignment.** `K="node /path/to/code-kit.mjs"; git add … && git commit …` was refused as a command that may write files: the value's space split it, and the path after it was read as a command. A quoted value is now taken whole, in every rule that reads a command's parts.
14
+ - **The Decide pane: decisions no longer pop up mid-conversation, or get cut.** code-kit used to ask a decision in Claude Code's own question dialog whenever the lead went idle. The dialog took only the question and up to four short labels, cut what didn't fit, and came up over whatever you were reading. Now nothing pops up: a decision waits in the band and in Needs you, with a notification, until you open it with **d**, its line in Needs you, or `/lanes decide`. The Decide pane opens beside the conversation with one decision at a time, all of it: the whole question, why it's yours, the story and requirements, what was happening, what's settled, and each option on its number with what it does. Questions that take your own words have the box in the pane, with Ask about it. **n** and **p** move between decisions, and the one in view stays put as others come and go. Needs you is now a line per decision, so it no longer jumps as you move through it.
15
+
5
16
  ## 0.31.1 (2026-11-05)
6
17
 
7
18
  - **`next` in a working session says whose step it is.** When another session leads the project, `code-kit next` and `/code-kit:next` handed a working session the lead's step, such as a dispatch. The session went on to write the lead's contracts and was refused at every edit. It now gets the step `working`: which session leads and what its next step is, and what this session does instead (a task of its own, recorded with `code-kit task`, in a worktree of its own).
package/README.md CHANGED
@@ -280,7 +280,7 @@ The config's `lanes.<name>.agent` must match the agent file's `name`. That's how
280
280
 
281
281
  Editing an agent file can't loosen a rule. And the agent files are kit files (`.claude/**`), so only the lead changes them, and every change is logged.
282
282
 
283
- **Spawned per story.** Dispatch starts a fresh instance of the lane's agent for each story, in its own worktree on `<lane>/st-<n>`. Agents for different lanes run in parallel. Each starts knowing only its agent file and the story's brief, so nothing leaks between stories.
283
+ **Spawned per story, in the lane's worktree.** Dispatch starts a fresh instance of the lane's agent for each story, on `<lane>/st-<n>`. Agents for different lanes run in parallel. Each starts knowing only its agent file and the story's brief, so nothing leaks between stories. Each lane has one worktree, `.claude/worktrees/lane-<lane>`, kept from story to story with its installs: code-kit's `WorktreeCreate` hook gives it to the lane's agent in place of a new worktree per agent, so a project's installs aren't made again for every story. Agents with worktrees start one per message (code-kit refuses a second until the first has its worktree), since the hook is told only the worktree's name. A lane worktree that still holds uncommitted work isn't reused: the next agent gets a worktree of its own. Every other agent gets the worktree Claude Code would make, taken away with its branch when the agent stops having changed nothing.
284
284
 
285
285
  **How the spec is followed, step by step** (the steps a hook or `verify` enforces are marked):
286
286
 
@@ -306,7 +306,7 @@ With Claude Code 2.1.287 or later, code-kit's mod shows the project in the sessi
306
306
 
307
307
  The band sits above the prompt, and speaks only when it's needed, in at most three lines:
308
308
 
309
- - **What needs you**: the most urgent thing waiting, with the story it's for ("for ST-4 Booking form (BOOK-1)") and its buttons, and how many more wait ("2 more waiting · /lanes"). **d** ("Why, and what each choice does") opens it as a card in the pane. Most urgent first: a held call, then the lead's questions, approvals, merges and reviews that are yours, stalled lanes, your brief's open questions, then notes (usage, the plan's pause).
309
+ - **What needs you**: the most urgent thing waiting, with the story it's for ("for ST-4 Booking form (BOOK-1)") and its buttons, and how many more wait ("2 more waiting · /lanes"). **d** (Decide…) opens it in the Decide pane. Most urgent first: a held call, then the lead's questions, approvals, merges and reviews that are yours, stalled lanes, your brief's open questions, then notes (usage, the plan's pause).
310
310
  - **While the build moves** and nothing needs you, one line: the milestone, its bar of requirements tested, and how many agents are at work, with **Pause**; a paused loop says so, with **Resume**.
311
311
  - **Nothing** while nothing is happening and nothing waits.
312
312
 
@@ -333,7 +333,7 @@ Each button has a digit: type it in an empty prompt to press it. A digit presses
333
333
  The loop keeps the build moving between your prompts, under `harness.autonomy`. `/code-kit:init` asks you how hands-off you want it. Until you've chosen, its first step waits in the band ("code-kit can keep the build moving between your prompts") with **Keep going**, **Ask each time** and **Off**, and your answer is recorded as your setting.
334
334
 
335
335
  - **Each step.** Once the lead has finished a turn, with the lead idle and nothing typed in the prompt, the loop asks `code-kit next` and prompts the lead to dispatch the ready stories, review a finished one, or build its own. It never prompts the same step twice while nothing has changed, and never a story an agent is still on: one its lane agent is building, or a reviewer is reviewing, waits until that agent finishes ("waiting: ST-10 is still with its agent").
336
- - **It reads the lead's reply first.** Before prompting again, the loop reads the lead's last reply with a side call over the lead's own conversation. A reply that waits on you (a question, a design to look at, an approval), or a turn you stopped, holds the loop until you answer or speak to the lead: the band says what the lead waits on, and its question is asked in Claude Code's own question dialog. A step the lead didn't take shows in the band as a note, with its reason and **Ask again**.
336
+ - **It reads the lead's reply first.** Before prompting again, the loop reads the lead's last reply with a side call over the lead's own conversation. A reply that waits on you (a question, a design to look at, an approval), or a turn you stopped, holds the loop until you answer or speak to the lead: the band says what the lead waits on, and the Decide pane answers it. A step the lead didn't take shows in the band as a note, with its reason and **Ask again**.
337
337
  - **Stories waiting on other work.** When the lead says a story isn't due yet because it waits on work still going (a paired story a lane is building, a rebuild, a check running), the loop parks that story and leaves it out of every step, so a step naming it with others prompts only the others. It wakes when its own branch or state moves, or when a story it waits on (one the lead named, or an unfinished one building on it) changes state; that story's commits along the way don't wake it, nor do other lanes'. A story the lead's turn left exactly where it stood is parked too, whatever the reply said. After 30 minutes with nothing moving, the lead is asked once more.
338
338
  - **Holding on purpose.** A story the lead means to leave alone for a while (it waits on something outside the build, or on a date) is held with `code-kit defer <story> --reason "…" [--until <date>]`: `next`, the loop and the merge queue don't dispatch, review or merge it until then, or until `code-kit defer release <story>`, and it isn't asked about again in the meantime. `code-kit queue pause --reason "…"` holds the whole merge queue the same way, until `code-kit queue resume`. `next` lists each hold with its reason, and the band shows them as notes.
339
339
  - **A step that doesn't move.** One the lead was prompted with three times in a row that is still next shows as a note, not a decision: "Merge lead/st-1: still next after 3 prompts to the lead", with **Ask again** if you want it.
@@ -342,7 +342,7 @@ The loop keeps the build moving between your prompts, under `harness.autonomy`.
342
342
  - **Designs.** A design story is handed to the lead once a session; while you and the lead design it, the loop leaves it to you.
343
343
  - **One session leads.** The loop runs in the project's lead session: the one that started when no other led, or the one you chose with **Lead from here** (or `/code-kit:lead`). See [Several sessions in one project](#several-sessions-in-one-project).
344
344
  - **Modes.** **Pause** and **Resume** stop and start it. Under `propose`, each step waits for **Go**; under `off`, the loop does nothing. When every story is done, the band says so and the loop stops.
345
- - **Choices in Claude Code's dialog.** A decision you settle by choosing (how hands-off the loop is, a step to take under `propose`, a stale claim, a question from the lead with answers offered) is asked in Claude Code's own question dialog while the lead is idle, once; dismissed, it stays in the band and the pane's Needs you. Approvals, send-backs and settings, which need your reason, stay in the pane.
345
+ - **The Decide pane.** Nothing pops up over the conversation: a decision waits in the band and Needs you, with a notification, until you open it with **d**, its line in Needs you, or `/lanes decide`. The Decide pane sits beside the conversation and shows one decision at a time, all of it: the whole question, why it's yours, the story and requirements, what was happening, and each option on its number with what it does. A question that takes your own words has a box for them, and an **Ask about it** box first. **n** and **p** move between decisions; each stays in view as others come and go.
346
346
  - **Stalled lanes.** A lane agent with no tool call for `harness.stall.nudgeMinutes` (5) is messaged, unless its work is done (it handed back, or its branch is in review or the merge queue). At `stall.restartMinutes` (10) the lead is asked to stop it and dispatch its story again, at most `stall.maxRestarts` (2) times; after that the lead decides how the story goes on (a narrower brief, smaller stories, or handing it back), and the band shows a note.
347
347
  - **The reviewer agent**, with `harness.agents.reviewer.on`. A finished branch is first reviewed in the background by code-kit's reviewer agent, which the lead starts: it runs `verify` and the review checklist, read-only, and grades each finding blocker, concern or nit. The lead's review prompt then carries the findings, and a blocker means the branch is sent back. The pane shows each review, running with its clock or what it found. If the reviewer hasn't reported within 15 minutes, or the plan's 5-hour use is past `harness.background.pauseAtPercent`, the lead reviews without it.
348
348
  - **The merge queue** (`code-kit queue`). A branch the lead's review passes joins the queue. Branches merge one at a time, in the order they passed, each verified against the base as it is then: the lead merges where `approvals.delegate.merge` is on under `autonomous`, otherwise the band shows the head with **Merge** for you. Who may merge is read from the config committed on the base, so a branch can't grant itself merges. The queue records the commit each review passed, and merges exactly that commit: a branch that moves on after its review leaves the queue (`moved`) for the lead to review it again. A head that conflicts or fails verify goes back to its lane. A merged lane's worktree is removed when it holds nothing uncommitted. Where `branches.publish` is set, each merge then reaches the remote's base: pushed, or, where the remote only takes pull requests, as one code-kit opens and (where you delegate pushing) merges. A story's branch merges only into the base, through the queue: an agent's `git merge` of it into any other branch (an integration branch such as `lead/next`) is refused, since the story would look unmerged and its worktree would never be cleaned up. The pane lists the queue, and lanes whose branch waits in it read `queued`.
@@ -403,7 +403,7 @@ Once init has switched the rules on, the lead runs the build in a loop:
403
403
  You can open several Claude Code sessions in one project: one building the plan, others auditing, checking merges or looking into something ad hoc. code-kit treats each session as a member of the team, as it treats each developer in a team:
404
404
 
405
405
  - **One lead session.** The loop runs there, and the plan's stories are dispatched from it. The first session to start leads; one started while it's open is a working session. When the lead session ends, no other takes over by itself: the next session to start leads, or you choose one with **Lead from here** or `/code-kit:lead`. `code-kit who` says which this session is.
406
- - **Working sessions stay quiet.** Their band shows only their own: their refusals and held calls, their lead's questions, their task. No loop prompts, no other session's decisions, dialogs or notifications. Every rule still applies.
406
+ - **Working sessions stay quiet.** Their band shows only their own: their refusals and held calls, their lead's questions, their task. No loop prompts, no other session's decisions or notifications. Every rule still applies.
407
407
  - **Ad hoc work records a task.** A working session records what it's doing before it changes code, with the paths it'll change: `code-kit task "Integration readiness" --touches "src/integrations/**"`. The task leases those paths: another session's agents writing there are refused, naming the session and its task. `code-kit sessions` lists the sessions and their tasks; `task done` ends one, and `task take <session>` moves a task whose session ended to yours.
408
408
  - **Each in its own worktree.** A working session that changes code works in a worktree of its own (`claude --worktree`); its writes in the main checkout are refused, so its uncommitted files never block another session's git. Where git does refuse because of another session's uncommitted files, code-kit says whose they are.
409
409
  - **One story per lane, across every session.** A lane runs one story at a time, whichever session started it (`code-kit lanes`).
@@ -622,7 +622,7 @@ code-kit approve pillow --lane api --delegated --story ST-138 --reason "MED-5 ne
622
622
  - **Who:** only the lead. With `"approvals": { "delegate": false }`, `--delegated` is refused, and every approval is yours.
623
623
  - **Weakened tests:** with `"tests": true` (the default), the lead approves a weakened test on a lane's branch for the story it reviewed, with `--lane` and `--story`; on its own branches it's yours.
624
624
  - **Merges:** with `"merge": true`, the lead merges a reviewed branch into a protected branch with `code-kit merge <branch> --delegated`.
625
- - It runs `code-kit verify` on the branch first, checks included, and merges only if it passes. The checks run on the branch merged with the base, in a fresh checkout with a copy of the base's checkout's installs (`node_modules`, virtualenvs). Where the merged tree's manifests or lockfiles differ from them, the install runs in that checkout first: `regression.prepare` if set, else the one its lockfile calls for (pnpm, npm, yarn, bun, uv). An install that fails there keeps the branch in its place in the queue; where code-kit knows no install, the merge says the installs it used may not match. A branch the base already holds is merged already: it leaves the queue as merged, never verified again.
625
+ - It runs `code-kit verify` on the branch first, checks included, and merges only if it passes. The checks run on the branch merged with the base, in code-kit's own checkout of the project, kept between merges with its installs (`node_modules`, virtualenvs), copied in from the base's checkout the first time. Keeping it means a merge doesn't copy millions of files in and delete them again each time, which keeps macOS's file-change tracking and Spotlight busy; it lives in the temporary folder under `code-kit-checkouts.noindex`, which Spotlight skips. Where the merged tree's manifests or lockfiles differ from them, the install runs in that checkout first: `regression.prepare` if set, else the one its lockfile calls for (pnpm, npm, yarn, bun, uv). An install that fails there keeps the branch in its place in the queue; where code-kit knows no install, the merge says the installs it used may not match. A branch the base already holds is merged already: it leaves the queue as merged, never verified again.
626
626
  - Only uncommitted changes to files the merge changes stop it, in the base's checkout; it checks before the verify and again after. Other changes there, such as a log another tool appends to each turn, are carried as they are.
627
627
  - Run from inside the lane's worktree, the merge keeps that worktree (the shell is in it); it goes at the next merge.
628
628
  - The merge commit says it was verified and delegated.
package/bin/code-kit.mjs CHANGED
@@ -972,7 +972,8 @@ function mergeOne(branch, config, byPerson, commit = null, partners = []) {
972
972
  // it) isn't held to the partner's files. A partner built on this member already holds the member's
973
973
  // commits, so it's left out of the member's base, which would otherwise show no change at all.
974
974
  for (const b of members.length ? [{ branch, tip }, ...members] : []) {
975
- const own = freshCheckout(root, into, { prefix: 'code-kit-merge-' });
975
+ // Only the lane paths are checked here, so it needs no installs.
976
+ const own = freshCheckout(root, into, { prefix: 'code-kit-merge-', installsFrom: null });
976
977
  temporary.push(own);
977
978
  const others = [{ branch, tip }, ...members].filter(
978
979
  (x) => x.branch !== b.branch && !contains(x.tip, b.tip),
@@ -3153,9 +3154,9 @@ function worktreesCommand() {
3153
3154
  if (rest[0] === 'release') {
3154
3155
  const w = list.find((x) => x.branch === rest[1] || x.path === rest[1]);
3155
3156
  if (!w) die(`No worktree has ${rest[1] ?? '<branch>'} checked out.`);
3156
- if (agentBusy(root, w))
3157
+ if (agentBusy(root, w, config))
3157
3158
  die(
3158
- `The ${w.branch.split('/')[0]} lane's agent is still at work on ${w.branch} (its last act was under ${BUSY_MS / 60_000} minutes ago, with no hand-back); nothing was removed. Wait for it to hand back, or stop it with TaskStop, then release it.`,
3159
+ `The ${w.branch.split('/')[0]} lane's agent is still at work on ${w.branch} (its last act is still running, or came under ${BUSY_MS / 60_000} minutes ago, with no hand-back); nothing was removed. Wait for it to hand back, or stop it with TaskStop, then release it.`,
3159
3160
  );
3160
3161
  return out(`Released ${releaseWorktree(w)}. The branch and its commits stay.`);
3161
3162
  }
@@ -2,13 +2,16 @@
2
2
  // PreToolUse on Agent (docs/specs/23-the-team.md, SCHED-1): a lane runs one story at a time, across every
3
3
  // session in the project. Starting a lane's agent claims the lane; a second agent for a claimed lane is
4
4
  // refused, naming the story and the session that has it. Any other agent starts as before. A lane agent
5
- // that starts is logged with the model it runs on, and why (SCHED-3).
5
+ // that starts is logged with the model it runs on, and why (SCHED-3). LEAN-10: a lane agent started with
6
+ // a worktree gets its lane's (worktree-create.mjs): the lane is noted here for that hook, so agents
7
+ // with worktrees start one at a time, each in a message of its own.
6
8
  import { readFileSync } from 'node:fs';
7
9
  import { join } from 'node:path';
8
10
  import { recordDispatch, storyModels } from './lib/dispatches.mjs';
9
11
  import { block, start } from './lib/hook.mjs';
10
12
  import { CLI } from './lib/rules.mjs';
11
13
  import { claimLane, shortSession } from './lib/laneclaims.mjs';
14
+ import { dropNextLane, mainCheckout, nextLane, noteNextLane } from './lib/lanetrees.mjs';
12
15
  import { readStories, storyBranch } from './lib/plan.mjs';
13
16
  import { agentFileModel } from './lib/schedule.mjs';
14
17
  import { memberOf, readSession } from './lib/sessions.mjs';
@@ -18,14 +21,26 @@ const { input, project, config, error } = start();
18
21
  if (error) process.exit(0);
19
22
  const call = input.tool_input ?? {};
20
23
  const lane = Object.entries(config.lanes).find(([, l]) => l.agent === call.subagent_type)?.[0];
21
- if (!lane) process.exit(0);
24
+ const isolated = call.isolation === 'worktree';
25
+ const main = isolated ? (mainCheckout(input.cwd || project) ?? project) : project;
22
26
  const story =
23
27
  String(call.description ?? '')
24
28
  .match(/\bST-\d+\b/i)?.[0]
25
29
  ?.toUpperCase() ?? null;
30
+ // LEAN-10: the worktree hook is told only the worktree's name, so it takes the one note waiting: every
31
+ // agent with a worktree is noted, a lane's or not, and a second started before the first one's worktree
32
+ // is made is refused, so it can't take the other's.
33
+ if (isolated && !noteNextLane(main, { lane: lane ?? null, story: lane ? story : null })) {
34
+ const waiting = nextLane(main);
35
+ block(
36
+ `Blocked: ${waiting?.lane ? `the ${waiting.lane} lane's agent${waiting.story ? ` for ${waiting.story}` : ''}` : 'another agent'} is still being given its worktree. Start agents that work in worktrees one at a time, each in a message of its own: start this one again in your next message.`,
37
+ );
38
+ }
39
+ if (!lane) process.exit(0);
26
40
  const session = input.session_id ?? null;
27
41
  const claimed = claimLane(project, { lane, story, session });
28
42
  if (!claimed.ok) {
43
+ if (isolated) dropNextLane(main);
29
44
  const c = claimed.claim;
30
45
  // SESS-1: the session by its member and, where it has one, its task.
31
46
  const holder = readSession(project, c.session);
@@ -5,9 +5,9 @@
5
5
  // approval log on commit and scans commits for secrets. Shell writes are also checked afterwards by
6
6
  // lane-audit.mjs. With `approvals.lead` on, the lead may act for the person on what they say in chat:
7
7
  // record their approvals (`code-kit approve`) and run blocked commands marked `person`.
8
- import { appendFileSync, existsSync, readFileSync } from 'node:fs';
8
+ import { appendFileSync, existsSync, readFileSync, realpathSync } from 'node:fs';
9
9
  import { spawnSync } from 'node:child_process';
10
- import { join, resolve } from 'node:path';
10
+ import { basename, dirname, join, resolve, sep } from 'node:path';
11
11
  import {
12
12
  addedPackages,
13
13
  dependencyApproval,
@@ -19,7 +19,9 @@ import {
19
19
  GIT,
20
20
  codeOf,
21
21
  commandsOf,
22
+ outputRedirects,
22
23
  readsOnly,
24
+ sedInPlaceFiles,
23
25
  unreadNames,
24
26
  ruleMatches,
25
27
  runs,
@@ -796,7 +798,8 @@ ${approvalHowTo(TESTS_APPROVAL, actor, root, 'weakening tests in one commit', pe
796
798
  // unlogged. Before the commit, a chain may only move into the checkout, make a branch where it stands
797
799
  // (no start point, so no file changes), stage or unstage, make folders, take away a worktree (keepsFiles)
798
800
  // and run commands that only read (lib/shell.mjs readsOnly: git's status, diff, log and show among them,
799
- // with no output file). Errors sent into the output or /dev/null write no file.
801
+ // with no output file), or that write only outside the checkout (writesOutside). Errors sent into the
802
+ // output or /dev/null write no file.
800
803
  const BEFORE_COMMIT = new RegExp(
801
804
  String.raw`^(?:cd\s|${GIT}(?:add|rm|mv|restore\s+--staged|reset\s+--soft)(?![\w-])|${GIT}(?:switch\s+(?:-q\s+|--quiet\s+)*(?:-c|--create)|checkout\s+(?:-q\s+|--quiet\s+)*-b)\s+[^\s-]\S*\s*$)`,
802
805
  );
@@ -828,6 +831,32 @@ function keepsFiles(c) {
828
831
  const named = before.filter((w) => !w.startsWith('-'));
829
832
  return !(paths < 0 && named.length === 1 && named[0] !== 'HEAD' && isCommit(named[0]));
830
833
  }
834
+ // A path the commit can't take: written out in full, outside this project and the checkout the commit
835
+ // is in (a session's scratchpad, the system's temporary folder). The real path of what's there counts,
836
+ // so a link back into the project doesn't pass.
837
+ function realOf(p) {
838
+ let at = resolve(p);
839
+ const tail = [];
840
+ while (!existsSync(at) && dirname(at) !== at) {
841
+ tail.unshift(basename(at));
842
+ at = dirname(at);
843
+ }
844
+ return join(realpathSync(at), ...tail);
845
+ }
846
+ const within = (p, dir) => p === dir || p.startsWith(dir.endsWith(sep) ? dir : dir + sep);
847
+ function outsideCheckout(p) {
848
+ if (!p.startsWith('/') || /[$`*?{}[\]~]/.test(p)) return false;
849
+ const real = realOf(p);
850
+ return ![project, root].some((r) => within(real, realOf(r)));
851
+ }
852
+ // What writes only outside the checkout (a message drafted in a scratchpad for `git commit -F`): a read
853
+ // whose output goes only to such paths, or sed's substitutions on such files in place.
854
+ function writesOutside(c) {
855
+ const out = outputRedirects(c.whole);
856
+ if (!out?.targets.every(outsideCheckout)) return false;
857
+ if (out.targets.length && readsOnly(out.rest)) return true;
858
+ return sedInPlaceFiles(out.rest.trim())?.every(outsideCheckout) ?? false;
859
+ }
831
860
  function writesBeforeCommit() {
832
861
  const pieces = commandsOf(withoutHarmlessRedirects(cmd));
833
862
  const at = pieces.findIndex((c) => new RegExp(String.raw`^${GIT}commit(?![\w-])`).test(c.text));
@@ -839,7 +868,8 @@ function writesBeforeCommit() {
839
868
  !readsOnly(c.whole) &&
840
869
  !assignsOnly(c) &&
841
870
  !recordsOnly(c) &&
842
- !keepsFiles(c),
871
+ !keepsFiles(c) &&
872
+ !writesOutside(c),
843
873
  );
844
874
  }
845
875
 
package/hooks/hooks.json CHANGED
@@ -78,6 +78,17 @@
78
78
  ]
79
79
  }
80
80
  ],
81
+ "WorktreeCreate": [
82
+ {
83
+ "hooks": [
84
+ {
85
+ "type": "command",
86
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/worktree-create.mjs\"",
87
+ "timeout": 120
88
+ }
89
+ ]
90
+ }
91
+ ],
81
92
  "SessionStart": [
82
93
  {
83
94
  "hooks": [
@@ -134,6 +145,11 @@
134
145
  "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/act.mjs\" handback",
135
146
  "timeout": 5,
136
147
  "async": true
148
+ },
149
+ {
150
+ "type": "command",
151
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/worktree-done.mjs\"",
152
+ "timeout": 30
137
153
  }
138
154
  ]
139
155
  }
@@ -3,12 +3,31 @@
3
3
  // taken out (REG-1). It's a temporary worktree with its own copy of the installs (node_modules and
4
4
  // the like): a link back to a worktree's installs resolves outside the checkout, which path-sensitive
5
5
  // tools refuse, and an install run in it would rewrite the worktree's own.
6
+ // MQ-9: the checkout is kept between runs, one per project and use, with its installs: copying a
7
+ // project's installs in and deleting them again on every merge is millions of files each time, which
8
+ // keeps the machine's file-change tracking and search indexing busy. Each run checks out the tree it
9
+ // needs, and installs again only where its manifests and lockfiles differ from the ones the kept
10
+ // installs were made for. The folder's name ends in .noindex, which Spotlight leaves alone.
11
+ import { createHash } from 'node:crypto';
6
12
  import { execFileSync, spawnSync } from 'node:child_process';
7
- import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
13
+ import {
14
+ closeSync,
15
+ existsSync,
16
+ mkdirSync,
17
+ mkdtempSync,
18
+ openSync,
19
+ readFileSync,
20
+ realpathSync,
21
+ rmSync,
22
+ writeFileSync,
23
+ } from 'node:fs';
8
24
  import { platform, tmpdir } from 'node:os';
9
- import { basename, dirname, join } from 'node:path';
25
+ import { basename, dirname, join, resolve } from 'node:path';
10
26
  import { isDependencyFile } from './dependencies.mjs';
11
27
 
28
+ /** Where the kept checkouts live: in the temporary folder, out of Spotlight's index. */
29
+ export const CHECKOUTS_DIR = join(tmpdir(), 'code-kit-checkouts.noindex');
30
+
12
31
  // The folders an install puts beside the code, which a fresh checkout lacks.
13
32
  const INSTALLS = new Set(['node_modules', '.venv', 'venv']);
14
33
 
@@ -51,32 +70,155 @@ export function copyInstalls(root, dir) {
51
70
  }
52
71
  }
53
72
 
73
+ const real = (p) => {
74
+ try {
75
+ return realpathSync(p);
76
+ } catch {
77
+ return p;
78
+ }
79
+ };
80
+
81
+ /** The kept checkout for `root` and this use (`prefix`), the project's main checkout's. */
82
+ export function keptCheckoutOf(root, prefix) {
83
+ let main = root;
84
+ try {
85
+ main = dirname(real(resolve(root, git(root, 'rev-parse', '--git-common-dir').trim())));
86
+ } catch {
87
+ // not a repository: its own folder names it
88
+ }
89
+ const id = createHash('sha256').update(real(main)).digest('hex').slice(0, 10);
90
+ return join(CHECKOUTS_DIR, `${basename(main)}-${id}-${prefix.replace(/^code-kit-|-$/g, '')}`);
91
+ }
92
+
93
+ /** The manifests and lockfiles the installs in a kept checkout were made for, by content hash. */
94
+ const stampOf = (dir) => `${dir}.installs.json`;
95
+ function dependencyHashes(dir) {
96
+ const hashes = {};
97
+ for (const f of trackedDependencies(dir)) {
98
+ try {
99
+ hashes[f] = createHash('sha256')
100
+ .update(readFileSync(join(dir, f)))
101
+ .digest('hex');
102
+ } catch {
103
+ hashes[f] = null;
104
+ }
105
+ }
106
+ return hashes;
107
+ }
108
+
109
+ /** Takes the kept checkout's lock for this process, or false while another live process holds it. */
110
+ function lock(slot) {
111
+ const file = `${slot}.lock`;
112
+ for (let tries = 0; tries < 2; tries++) {
113
+ try {
114
+ const fd = openSync(file, 'wx');
115
+ writeFileSync(fd, String(process.pid));
116
+ closeSync(fd);
117
+ return () => rmSync(file, { force: true });
118
+ } catch {
119
+ const pid = Number(readFileSafe(file));
120
+ let alive = false;
121
+ try {
122
+ alive = pid > 0 && process.kill(pid, 0);
123
+ } catch {
124
+ alive = false;
125
+ }
126
+ if (alive) return false;
127
+ rmSync(file, { force: true });
128
+ }
129
+ }
130
+ return false;
131
+ }
132
+ const readFileSafe = (f) => {
133
+ try {
134
+ return readFileSync(f, 'utf8');
135
+ } catch {
136
+ return '';
137
+ }
138
+ };
139
+
140
+ /** Whether `dir` is one of `root`'s worktrees now. */
141
+ const isWorktreeOf = (root, dir) => {
142
+ try {
143
+ return git(root, 'worktree', 'list', '--porcelain')
144
+ .split('\n')
145
+ .some((l) => l.startsWith('worktree ') && real(l.slice(9)) === real(dir));
146
+ } catch {
147
+ return false;
148
+ }
149
+ };
150
+
54
151
  /**
55
- * A temporary worktree of `ref` (detached), with `merge` merged into it when given, and the installs
56
- * of `installsFrom` copied in. `{ dir, remove }`; a merge that conflicts throws a `conflict` error
57
- * after removing what it made. `remove` never throws: a folder that won't go is left to the OS.
152
+ * A worktree of `ref` (detached), with `merge` merged into it when given, and installs that were made
153
+ * for a tree: the project's kept checkout for this use (MQ-9), its installs kept from its last run, or
154
+ * where another run holds that one, a temporary worktree. Installs are copied from `installsFrom` only
155
+ * into a checkout that has none (null copies none). `{ dir, remove }`; a merge that conflicts throws a
156
+ * `conflict` error after putting things back. `remove` never throws: it frees the kept checkout, or
157
+ * takes the temporary one away, leaving a folder that won't go to the OS.
58
158
  */
59
159
  export function freshCheckout(
60
160
  root,
61
161
  ref,
62
162
  { merge = null, installsFrom = root, prefix = 'code-kit-' } = {},
63
163
  ) {
64
- const dir = mkdtempSync(join(tmpdir(), prefix));
65
- rmSync(dir, { recursive: true });
66
- git(root, 'worktree', 'add', '--quiet', '--detach', dir, ref);
67
- const remove = () => {
68
- try {
69
- git(root, 'worktree', 'remove', '--force', dir);
70
- } catch {
71
- // git leaves it when a process still writes there; the folder goes, and git prunes its record
164
+ // Named in the project, not in the kept checkout, where HEAD is the last run's.
165
+ ref = git(root, 'rev-parse', '--verify', '--quiet', `${ref}^{commit}`).trim();
166
+ const slot = keptCheckoutOf(root, prefix);
167
+ mkdirSync(CHECKOUTS_DIR, { recursive: true });
168
+ const unlock = lock(slot);
169
+ let dir;
170
+ let remove;
171
+ if (unlock) {
172
+ dir = slot;
173
+ let ready = false;
174
+ if (existsSync(dir) && isWorktreeOf(root, dir)) {
175
+ try {
176
+ // What the last run left (a merge, files a check wrote) goes; the installs stay.
177
+ git(dir, 'reset', '--hard', '--quiet');
178
+ git(dir, 'checkout', '--quiet', '--force', '--detach', ref);
179
+ git(dir, 'clean', '-ffdxq', ...[...INSTALLS].flatMap((i) => ['-e', i]));
180
+ ready = true;
181
+ } catch {
182
+ ready = false;
183
+ }
72
184
  }
73
- try {
185
+ if (!ready) {
186
+ try {
187
+ git(root, 'worktree', 'remove', '--force', dir);
188
+ } catch {
189
+ // not registered, or already gone
190
+ }
74
191
  rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
192
+ rmSync(stampOf(dir), { force: true });
75
193
  git(root, 'worktree', 'prune');
76
- } catch {
77
- // the OS clears its temporary folder
194
+ git(root, 'worktree', 'add', '--quiet', '--detach', dir, ref);
78
195
  }
79
- };
196
+ remove = () => {
197
+ try {
198
+ git(dir, 'merge', '--abort');
199
+ } catch {
200
+ // no merge in progress
201
+ }
202
+ unlock();
203
+ };
204
+ } else {
205
+ dir = mkdtempSync(join(CHECKOUTS_DIR, prefix));
206
+ rmSync(dir, { recursive: true });
207
+ git(root, 'worktree', 'add', '--quiet', '--detach', dir, ref);
208
+ remove = () => {
209
+ try {
210
+ git(root, 'worktree', 'remove', '--force', dir);
211
+ } catch {
212
+ // git leaves it when a process still writes there; the folder goes, and git prunes its record
213
+ }
214
+ try {
215
+ rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 200 });
216
+ git(root, 'worktree', 'prune');
217
+ } catch {
218
+ // the OS clears its temporary folder
219
+ }
220
+ };
221
+ }
80
222
  if (merge) {
81
223
  const merged = spawnSync(
82
224
  'git',
@@ -101,24 +243,45 @@ export function freshCheckout(
101
243
  throw Object.assign(new Error(why || 'the merge conflicts'), { conflict: true });
102
244
  }
103
245
  }
104
- copyInstalls(installsFrom, dir);
246
+ if (installsFrom && !installsOf(dir).length) {
247
+ copyInstalls(installsFrom, dir);
248
+ // The copied installs were made for installsFrom's manifests and lockfiles.
249
+ if (dir === slot) writeFileSync(stampOf(dir), JSON.stringify(dependencyHashes(installsFrom)));
250
+ }
105
251
  return { dir, remove };
106
252
  }
107
253
 
254
+ /** The manifests and lockfiles git tracks in `d`. */
255
+ function trackedDependencies(d) {
256
+ try {
257
+ return git(d, 'ls-files')
258
+ .split('\n')
259
+ .filter((f) => f && isDependencyFile(f));
260
+ } catch {
261
+ return [];
262
+ }
263
+ }
264
+
108
265
  /**
109
266
  * The manifests and lockfiles tracked in either checkout whose content differs between the two working
110
267
  * trees: where installs copied from `from` may not match the code in `dir`.
111
268
  */
112
269
  export function dependencyDifferences(from, dir) {
113
- const tracked = (d) => {
270
+ // A kept checkout's installs were made for the files its stamp records, whatever `from` holds now.
271
+ const stamp = readFileSafe(stampOf(dir));
272
+ if (stamp) {
273
+ let made = {};
114
274
  try {
115
- return git(d, 'ls-files')
116
- .split('\n')
117
- .filter((f) => f && isDependencyFile(f));
275
+ made = JSON.parse(stamp);
118
276
  } catch {
119
- return [];
277
+ made = {};
120
278
  }
121
- };
279
+ const now = dependencyHashes(dir);
280
+ return [...new Set([...Object.keys(made), ...Object.keys(now)])]
281
+ .filter((f) => (made[f] ?? null) !== (now[f] ?? null))
282
+ .sort();
283
+ }
284
+ const tracked = trackedDependencies;
122
285
  const read = (d, f) => {
123
286
  try {
124
287
  return readFileSync(join(d, f), 'utf8');
@@ -185,7 +348,17 @@ export function matchInstalls(dir, from, { prepare = null, timeout = 900000 } =
185
348
  const facts = { differ, copied, lockfile: present };
186
349
  if (!command) return { ...facts, command: null, failed: null };
187
350
  const res = spawnSync(command, { cwd: dir, shell: true, encoding: 'utf8', timeout });
188
- if (res.status === 0) return { ...facts, command, failed: null };
351
+ const stamp = stampOf(dir);
352
+ if (res.status === 0) {
353
+ // A kept checkout's installs now match this tree.
354
+ if (existsSync(stamp)) writeFileSync(stamp, JSON.stringify(dependencyHashes(dir)));
355
+ return { ...facts, command, failed: null };
356
+ }
357
+ // What a failed install left can't be trusted: the next run copies the installs afresh.
358
+ if (existsSync(stamp)) {
359
+ rmSync(stamp, { force: true });
360
+ for (const rel of installsOf(dir)) rmSync(join(dir, rel), { recursive: true, force: true });
361
+ }
189
362
  const output = `${res.stdout ?? ''}${res.stderr ?? ''}`.trim().split('\n').slice(-20).join('\n');
190
363
  return {
191
364
  ...facts,