@warren-dean/code-kit 0.31.1 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.33.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.33.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,23 @@
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.33.0 (2026-11-06)
6
+
7
+ - **A running budget.** Projects were being designed on each provider's production defaults, with nothing adding up what they'd cost a month. spec-design now asks how much a month each environment may cost, in your currency, and the load to plan for; init writes it to `cost` in the config, with the project's infrastructure files. spec-design costs each architecture it proposes against it and, when your preferred one doesn't fit, offers options that do, each with what it gives up. The costs go in `docs/costs.md`, a row per paid thing with where its price came from, and `code-kit cost` adds them up against the budget. A branch that changes the infrastructure has to change the register (verify), lanes may write it, and a commit that takes an environment past its budget waits for your `cost` approval, which the lead can't give, under vibe either. `next` asks a project with infrastructure and no budget for one. It works for any provider: code-kit holds no prices, and the lead cites where each came from. Reading real spend from an account comes later.
8
+ - **A branch made where the checkout stands, then a commit.** `git checkout -b <branch> main && git add … && git commit …`, run with the checkout already at main, was refused as a command that may write files the commit can't see, because the branch named a start point. A start point that is the commit the checkout is at changes no file, so it now passes like a branch made with no start point. One at any other commit is still refused.
9
+ - **Reverting a commit that logged approvals.** A `git revert` of a merge, or of any commit that appended to `.claude/approval-log.jsonl`, takes those entries back out with the rest, so verify failed the branch as an edited log, and no shell command was allowed to put the log back: the only way out was to make the branch again by hand. A command that doesn't commit may now put the log back as the last commit has it (`git restore --staged --worktree .claude/approval-log.jsonl`, or `git checkout HEAD -- …`), which can lose only what isn't committed. Verify's problem now says what took the entries out and how to make the revert again: `git revert --no-commit <commit>`, then that restore, then commit. A restore from any other commit, or in the same command as a commit, is still refused, since the commit hook appends before the command runs.
10
+
11
+ ## 0.32.0 (2026-11-06)
12
+
13
+ - **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.
14
+ - **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.
15
+ - **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.
16
+ - **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.
17
+ - **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.
18
+ - **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.
19
+ - **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.
20
+ - **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.
21
+
5
22
  ## 0.31.1 (2026-11-05)
6
23
 
7
24
  - **`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
@@ -52,7 +52,8 @@ code-kit catches each of these, most at the moment it would happen: the hook ref
52
52
 
53
53
  - **Lanes:** each lane agent writes only its own paths. The main session (the lead) writes contracts, specs and config, and delegates the rest. Any other subagent is read-only. An edit outside those paths is refused before it happens; a file a shell command writes outside them is reported straight after, for the agent to revert, and the finish check refuses to finish until it's gone.
54
54
  - **Layers:** each layer depends only on the layers it lists, and never on packages it's denied, for JavaScript and TypeScript imports. An edit that would add a violation is refused before it's written; the rules are checked again after each edit and before finishing, which is what catches a file a shell command wrote. In brownfield code, existing violations can be recorded in a baseline so only new ones block. Imports are found by pattern, not by parsing: see [the limits](#what-verify-proves-and-its-limits).
55
- - **Protected paths and the approval log:** every committed change to the kit, registers or contracts is appended to `.claude/approval-log.jsonl`, in the same commit. Only the lead writes these paths without an approval, and the person reviews them in the pull request. A lane needs an approval: the lead's for what `approvals.delegate` gives it, otherwise the person's.
55
+ - **Protected paths and the approval log:** every committed change to the kit, registers or contracts is appended to `.claude/approval-log.jsonl`, in the same commit. Nobody edits the log: a shell command may only read it, or put it back as the last commit has it (`git restore --staged --worktree .claude/approval-log.jsonl`, in a command that doesn't commit), as after a `git revert --no-commit` took a reverted commit's entries out. Only the lead writes these paths without an approval, and the person reviews them in the pull request. A lane needs an approval: the lead's for what `approvals.delegate` gives it, otherwise the person's.
56
+ - **A running budget** (spec 29): the person sets how much a month each environment may cost, and `docs/costs.md` estimates each paid thing against it. A commit that takes an environment past its budget waits for the person's `cost` approval, whatever is delegated; before asking, the lead finds options that fit.
56
57
  - **Spec-check before code:** when the project has specs, a lane can't write code on a branch until it has saved a spec-check report for that branch. The hook checks that the report exists; review checks what it says.
57
58
  - **Designs before screens** (optional): a screen file can't be written until the design register holds its approved design as files, every state exported from the design tool; the review records its screenshot of each built state beside the design, and verify checks it did.
58
59
  - **Shell rules**, matched against the command's text before it runs:
@@ -75,6 +76,7 @@ code-kit catches each of these, most at the moment it would happen: the hook ref
75
76
  - no screens without an approved design;
76
77
  - no secret files (`.env`, `secrets/`, keys and keystores) anywhere in the branch's history, including ones committed and deleted again, and, where gitleaks is installed, no secrets in any commit's content;
77
78
  - no test weakened (deleted, skipped or focused, cut down, or its snapshot rewritten) without the person's `tests` approval in the log;
79
+ - with a running budget, a branch that changes the infrastructure files changes the cost register too, and one that takes an environment past its budget has the person's `cost` approval in the log;
78
80
  - a fix (a plan story with `**Fixes:**`, or a `<lane>/fix-…` branch) comes with a test that fails without it, as the bug, and passes with it;
79
81
  - the project's checks pass.
80
82
 
@@ -280,7 +282,7 @@ The config's `lanes.<name>.agent` must match the agent file's `name`. That's how
280
282
 
281
283
  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
284
 
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.
285
+ **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
286
 
285
287
  **How the spec is followed, step by step** (the steps a hook or `verify` enforces are marked):
286
288
 
@@ -306,7 +308,7 @@ With Claude Code 2.1.287 or later, code-kit's mod shows the project in the sessi
306
308
 
307
309
  The band sits above the prompt, and speaks only when it's needed, in at most three lines:
308
310
 
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).
311
+ - **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
312
  - **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
313
  - **Nothing** while nothing is happening and nothing waits.
312
314
 
@@ -333,7 +335,7 @@ Each button has a digit: type it in an empty prompt to press it. A digit presses
333
335
  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
336
 
335
337
  - **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**.
338
+ - **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
339
  - **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
340
  - **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
341
  - **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 +344,7 @@ The loop keeps the build moving between your prompts, under `harness.autonomy`.
342
344
  - **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
345
  - **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
346
  - **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.
347
+ - **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
348
  - **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
349
  - **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
350
  - **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 +405,7 @@ Once init has switched the rules on, the lead runs the build in a loop:
403
405
  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
406
 
405
407
  - **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.
408
+ - **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
409
  - **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
410
  - **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
411
  - **One story per lane, across every session.** A lane runs one story at a time, whichever session started it (`code-kit lanes`).
@@ -424,6 +426,17 @@ For several people in one repository, each with their own agents. Not every deve
424
426
 
425
427
  It's a preview: it's tested end to end against a stand-in for GitHub, and has been run once against a real private repository (claims, leases, intents as discussions, decision records, since-you-last-looked and the Project board). Spec: `docs/specs/16-teams.md`.
426
428
 
429
+ ## What it costs to run
430
+
431
+ Spec 29. A build that nobody costs ends up on each provider's production defaults: a managed database with a standby, a NAT gateway per zone, containers that never stop. So the running cost is a guardrail, set once and checked as the work lands, for whatever providers the project uses.
432
+
433
+ - **The budget.** spec-design asks for it with the other constraints: how much a month each environment may cost, in the person's currency, and the load to plan for. 0 means free tiers only. init writes it to `cost` in the config, with the project's infrastructure files as `cost.paths`.
434
+ - **The register.** `docs/costs.md` has one table, `| Item | Provider | Environment | Size | Monthly | Basis |`: a row per paid thing, its monthly estimate as a number, and where the price came from, with the date. An `all` row counts in every environment. code-kit holds no price list: the lead estimates from each provider's published pricing, and `code-kit cost` adds it up and names a price older than 90 days.
435
+ - **The design fits first.** spec-design costs each architecture it proposes, and when the one the person prefers doesn't fit, it says by how much and offers options that do (a smaller size, a cheaper tier or provider, one environment instead of two, a service the product can do without at launch, less scope), each with what it gives up.
436
+ - **Each change is costed.** Any agent may write the register: a lane changes its row when its story adds or resizes something paid, and `verify` fails a branch that changes `cost.paths` without it. The review checks the sizes in the code against the rows.
437
+ - **Over the budget is the person's.** A commit that takes an environment past its budget, or further past it, is refused until the person approves `cost` (the lead can't, under vibe either); the log records the totals it allowed. A lane takes it to the lead, and the lead to the person with the options that fit and the cost of the one that doesn't.
438
+ - **Existing projects.** `next` names a project with infrastructure and no budget, and init's next run asks for one; the lead then costs what's built.
439
+
427
440
  ## Enforce it in CI
428
441
 
429
442
  The hooks only see Claude Code sessions. For everything else, init offers `.github/workflows/code-kit.yml` (from `templates/github-workflow.yml`). It runs `verify --no-checks` on every pull request, through `npx @warren-dean/code-kit@<version>`, pinned so CI doesn't change under you: the rules, in seconds, with a 10-minute limit, and a new push cancels the run it replaces. The project's checks aren't run again there, because the merge queue ran them before each merge; the project's full CI runs on its release branches instead, once per release (`code-kit release <version>` cuts one). `code-kit ci check` says what in the project's own workflows still runs once per story, and `code-kit ci usage` what the project spent. The workflow needs no secret. Mark the `code-kit` check as required on the protected branches, and keep its install step: a fix story's test is run without its fix (REG-1). Add gitleaks to the workflow for the secret scan of commits' content.
@@ -482,6 +495,7 @@ code-kit sent-back <branch> [--reason "…"] # record a revie
482
495
  code-kit ci check [--json] # what in the project's workflows runs once per story, or without a time limit, and the fix
483
496
  code-kit ci usage [--days N] [--json] # the project's GitHub Actions runs and minutes, by workflow and trigger
484
497
  code-kit release <version> # cut release/<version> from the base and push it: the project's full CI runs there once
498
+ code-kit cost [--json] # each environment's estimated running cost against its budget, the register's problems and the prices to recheck
485
499
  code-kit decisions [--json] [--all] # what waits on you in this session, and a count in each other one; --all lists every session's
486
500
  code-kit who # which session this is, whether it leads the project, and its task
487
501
  code-kit sessions [--json] # the sessions working the project, which one leads, and each one's task
@@ -536,6 +550,7 @@ code-kit approve <name>... --reason "…" [--lane name] [--delegated [--story ST
536
550
  | `version` | yes | `1` |
537
551
  | `docs.specs` | no | Folder of specs. With it, a lane needs a spec-check report before writing code on a branch |
538
552
  | `docs.principles`, `docs.plan` | no | The engineering principles and the implementation plan |
553
+ | `docs.costs` | no | The cost register (spec 29), default `docs/costs.md`: one table, `\| Item \| Provider \| Environment \| Size \| Monthly \| Basis \|`, a row per paid thing with its monthly estimate as a number and where the price came from, dated. Any agent may write it once `cost` is set |
539
554
  | `docs.decisions` | no | Where agreed intents are recorded as numbered decision records (`code-kit intend record`); default `docs/decisions` |
540
555
  | `docs.standards` | no | The project's standards (spec 22), default `docs/standards.md`: each a `### <id> <title>` heading with `level` (required or recommended), `applied` (enforced, checked or advice), `layers`, `why`, `source` and, when enforced, `enforced by` naming the layer rule, protected path, check or shell rule that refuses a breach. The id's prefix is its category: `PRI-` principles, `PAT-` patterns, `ARC-` architecture, `CON-` conventions, `POL-` policies. Each lane agent is given the ones for its layers; a refusal from an enforcing rule names the standard; reviews check the checked ones. Protect the file with the `standards` approval: removing a standard, or weakening a required one, always needs the person's, whatever is delegated |
541
556
  | `lead.paths` | yes | What the main session writes. `.claude/**` and `.mcp.json` are always added. |
@@ -556,6 +571,7 @@ code-kit approve <name>... --reason "…" [--lane name] [--delegated [--story ST
556
571
  | `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). |
557
572
  | `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). |
558
573
  | `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 |
574
+ | `cost` | no | The running budget (spec 29): `{ currency, monthly, load?, paths? }`. `currency` is a three-letter code (USD, AUD, EUR); `monthly` maps each environment (`prod`, `dev`, …, not `all`) to what it may cost a month; `load` says in words what the budget plans for; `paths` are the infrastructure files, whatever defines them, and a branch that changes one changes the register too. A commit that takes an environment past its budget needs the person's `cost` approval, whatever is delegated |
559
575
  | `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, the specs' titles and outcome lines, approvals, token use, the rules, the design register and the sessions at work; 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. |
560
576
  | `branches.protected` | no | Default `["main", "master"]` |
561
577
  | `branches.publish` | no | How a merge reaches the remote's base: `push` (the base is pushed, fast-forward only) or `pull-request` (for a base the remote only lets change through pull requests: code-kit opens one from `code-kit/publish-<base>` after each merge, and merges it where `approvals.delegate.push` is on, otherwise it waits for you). Left out, code-kit leaves pushing the base to you |
@@ -622,7 +638,7 @@ code-kit approve pillow --lane api --delegated --story ST-138 --reason "MED-5 ne
622
638
  - **Who:** only the lead. With `"approvals": { "delegate": false }`, `--delegated` is refused, and every approval is yours.
623
639
  - **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
640
  - **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.
641
+ - 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
642
  - 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
643
  - Run from inside the lane's worktree, the merge keeps that worktree (the shell is in it); it goes at the next merge.
628
644
  - The merge commit says it was verified and delegated.
package/bin/code-kit.mjs CHANGED
@@ -246,6 +246,7 @@ import {
246
246
  } from '../hooks/lib/worktrees.mjs';
247
247
  import { decisionsFor, openDecisions } from '../hooks/lib/decisionstore.mjs';
248
248
  import { WORKFLOWS_DIR, ciFindings, ciUsage, releaseBranch } from '../hooks/lib/ci.mjs';
249
+ import { COST_APPROVAL, costReport, infraFiles, money } from '../hooks/lib/costs.mjs';
249
250
  import {
250
251
  appliesTo,
251
252
  projectStandards,
@@ -584,6 +585,7 @@ const VERIFY_GROUPS = {
584
585
  tests: 'Weakened tests',
585
586
  regression: 'Fixes and their tests',
586
587
  standards: 'Standards',
588
+ cost: 'Running cost',
587
589
  checks: 'Checks',
588
590
  };
589
591
 
@@ -972,7 +974,8 @@ function mergeOne(branch, config, byPerson, commit = null, partners = []) {
972
974
  // it) isn't held to the partner's files. A partner built on this member already holds the member's
973
975
  // commits, so it's left out of the member's base, which would otherwise show no change at all.
974
976
  for (const b of members.length ? [{ branch, tip }, ...members] : []) {
975
- const own = freshCheckout(root, into, { prefix: 'code-kit-merge-' });
977
+ // Only the lane paths are checked here, so it needs no installs.
978
+ const own = freshCheckout(root, into, { prefix: 'code-kit-merge-', installsFrom: null });
976
979
  temporary.push(own);
977
980
  const others = [{ branch, tip }, ...members].filter(
978
981
  (x) => x.branch !== b.branch && !contains(x.tip, b.tip),
@@ -1822,6 +1825,56 @@ function settings() {
1822
1825
  );
1823
1826
  }
1824
1827
 
1828
+ /**
1829
+ * COST-3: each environment's estimated running cost from the register, against the budget the person
1830
+ * set, with what's wrong with the register and the prices to recheck. Exits 1 when anything's wrong.
1831
+ */
1832
+ function costCommand() {
1833
+ const { config } = load();
1834
+ const root = resolve('.');
1835
+ const cost = config.cost;
1836
+ const some = (files) => `${files.slice(0, 3).join(', ')}${files.length > 3 ? ', …' : ''}`;
1837
+ if (!cost) {
1838
+ const infra = infraFiles(root);
1839
+ if (flag('--json'))
1840
+ return (out(JSON.stringify({ budget: null, infra }, null, 2)), process.exit(1));
1841
+ out(
1842
+ `No running budget is set${infra.length ? `, and the project has infrastructure (${some(infra)})` : ''}. The person sets how much a month each environment may cost; /code-kit:init asks for it and writes it to "cost" in ${file}.`,
1843
+ );
1844
+ process.exit(1);
1845
+ }
1846
+ const report = costReport(root, config);
1847
+ const infra = cost.paths.length ? infraFiles(root, cost.paths) : [];
1848
+ if (!report.exists && infra.length)
1849
+ report.problems.unshift(
1850
+ `There is no cost register (${report.file}), but the project has infrastructure (${some(infra)}). The lead costs it there: a row per paid thing, with its monthly estimate and where the price came from.`,
1851
+ );
1852
+ if (flag('--json')) {
1853
+ out(JSON.stringify({ budget: cost, ...report, infra }, null, 2));
1854
+ process.exit(report.problems.length ? 1 : 0);
1855
+ }
1856
+ out(
1857
+ `Running cost against the budget, ${cost.currency} a month${cost.load ? `, for ${cost.load}` : ''}${report.exists ? `, from ${report.file}` : `; no register yet (${report.file})`}:`,
1858
+ );
1859
+ for (const e of report.environments)
1860
+ out(
1861
+ ` ${e.name.padEnd(10)} ${money(e.total).padStart(9)} of ${money(e.budget)}${e.over > 0 ? `, ${money(e.over)} over` : ''}`,
1862
+ );
1863
+ for (const r of report.rows)
1864
+ out(
1865
+ ` ${r.environment.padEnd(8)} ${String(r.monthly).padStart(9)} ${r.item}${r.provider ? ` (${[r.provider, r.size].filter(Boolean).join(', ')})` : ''}`,
1866
+ );
1867
+ if (report.problems.length)
1868
+ out(`\nProblems:\n${report.problems.map((p) => ` ${p}`).join('\n')}`);
1869
+ if (report.stale.length)
1870
+ out(`\nPrices to recheck:\n${report.stale.map((p) => ` ${p}`).join('\n')}`);
1871
+ if (report.environments.some((e) => e.over > 0))
1872
+ out(
1873
+ "\nOver the budget, the lead brings the person options that fit (smaller sizes, cheaper tiers or providers, fewer environments, less at launch), each with what it gives up. A commit that raises a total past its budget needs the person's cost approval.",
1874
+ );
1875
+ if (report.problems.length) process.exit(1);
1876
+ }
1877
+
1825
1878
  /**
1826
1879
  * CIC-2, CIC-4: `ci check` lists what in the project's workflows multiplies their cost with a story per
1827
1880
  * branch; `ci usage` sums the Actions runs of the last days, by workflow and trigger.
@@ -2351,7 +2404,12 @@ async function approve(given) {
2351
2404
  );
2352
2405
  if (laneName !== undefined && !config.lanes[laneName])
2353
2406
  die(`There is no lane "${laneName}". Lanes: ${Object.keys(config.lanes).join(', ')}.`);
2354
- const known = new Set(['kit', TESTS_APPROVAL, ...config.protected.map((p) => p.approval)]);
2407
+ const known = new Set([
2408
+ 'kit',
2409
+ TESTS_APPROVAL,
2410
+ COST_APPROVAL,
2411
+ ...config.protected.map((p) => p.approval),
2412
+ ]);
2355
2413
  const isPackage = (n) => /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/.test(n);
2356
2414
  const names = given.map((n) =>
2357
2415
  n.startsWith(DEPENDENCY_APPROVAL) || known.has(n) || !isPackage(n) ? n : dependencyApproval(n),
@@ -3153,9 +3211,9 @@ function worktreesCommand() {
3153
3211
  if (rest[0] === 'release') {
3154
3212
  const w = list.find((x) => x.branch === rest[1] || x.path === rest[1]);
3155
3213
  if (!w) die(`No worktree has ${rest[1] ?? '<branch>'} checked out.`);
3156
- if (agentBusy(root, w))
3214
+ if (agentBusy(root, w, config))
3157
3215
  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.`,
3216
+ `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
3217
  );
3160
3218
  return out(`Released ${releaseWorktree(w)}. The branch and its commits stay.`);
3161
3219
  }
@@ -3441,6 +3499,7 @@ const commands = {
3441
3499
  timeline,
3442
3500
  'sent-back': () => (rest.length === 1 ? sentBackCommand(rest[0]) : usage()),
3443
3501
  ci: ciCommand,
3502
+ cost: () => (rest.length === 0 ? costCommand() : usage()),
3444
3503
  release: () => (rest.length === 1 ? releaseCommand(rest[0]) : usage()),
3445
3504
  replay: () => (rest.length === 1 ? replayCommand(rest[0]) : usage()),
3446
3505
  reconcile: () => (rest.length <= 1 ? reconcileCommand(rest[0]) : usage()),
@@ -3480,6 +3539,7 @@ function usage() {
3480
3539
  ' | who | task "<what>" --touches globs | task done | task take <session>\n' +
3481
3540
  ' | decisions [--json] [--all]\n' +
3482
3541
  ' | ci check [--json] | ci usage [--days N] [--json] | release <version>\n' +
3542
+ ' | cost [--json]\n' +
3483
3543
  ' | hold <id> [--minutes N] | hold <id> --answer approved|refused\n' +
3484
3544
  ' | queue [--json] | queue add|drop <branch> | queue rules | queue merge --delegated|--person\n' +
3485
3545
  ' | queue pause --reason "…" | queue resume\n' +
@@ -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,
@@ -35,6 +37,7 @@ import { historyWrites, storyMerges } from './lib/queue.mjs';
35
37
  import { approverOf } from './lib/journal.mjs';
36
38
  import { loginHere } from './lib/sessions.mjs';
37
39
  import { TESTS_APPROVAL, commitWeakenings } from './lib/regression.mjs';
40
+ import { COST_APPROVAL, overBudget, overWords, registerFile } from './lib/costs.mjs';
38
41
  import {
39
42
  STANDARDS_APPROVAL,
40
43
  noteFor,
@@ -98,7 +101,7 @@ const ALWAYS = [
98
101
  ],
99
102
  [
100
103
  /approval-log\.jsonl/,
101
- "The approval audit log is appended only by the commit hook; nobody edits it. A shell command may name it only to read it: git diff, log, show or blame, or cat, head, tail, grep, wc, jq, cut, sort, uniq, awk or sed -n printing lines, piped only into each other, with no redirect but 2>&1 or into /dev/null, no command's output in its arguments ($(…) or backticks) and no variable set before a command; other commands may come before or after it with ; or &&, if none defines a function or alias or sets a variable. Run the read in that form, or read the file with the Read tool, which can't write.",
104
+ "The approval audit log is appended only by the commit hook; nobody edits it. A shell command may name it only to read it: git diff, log, show or blame, or cat, head, tail, grep, wc, jq, cut, sort, uniq, awk or sed -n printing lines, piped only into each other, with no redirect but 2>&1 or into /dev/null, no command's output in its arguments ($(…) or backticks) and no variable set before a command; other commands may come before or after it with ; or &&, if none defines a function or alias or sets a variable. Run the read in that form, or read the file with the Read tool, which can't write. To put it back as the last commit has it (after a `git revert --no-commit` or `git cherry-pick --no-commit` took entries out), run `git restore --staged --worktree .claude/approval-log.jsonl` in the same form, and commit in a command after it.",
102
105
  unreadNames(cmd, /approval-log\.jsonl/).join('\n'),
103
106
  ],
104
107
  ];
@@ -655,6 +658,39 @@ function recordApprovals() {
655
658
  );
656
659
  }
657
660
  }
661
+ // COST-5: a commit that takes an environment's estimated running cost past its budget, or further
662
+ // past it, waits for the person's cost approval (never the lead's), which records what it allowed.
663
+ const costRegister = config.cost ? registerFile(config) : null;
664
+ const overCost =
665
+ costRegister &&
666
+ files.includes(costRegister) &&
667
+ !arrivesWithMerge(root, costRegister, { staged: true })
668
+ ? overBudget(
669
+ git('show', `HEAD:${costRegister}`),
670
+ existsSync(join(root, costRegister))
671
+ ? readFileSync(join(root, costRegister), 'utf8')
672
+ : '',
673
+ config.cost,
674
+ )
675
+ : [];
676
+ if (overCost.length) {
677
+ const granted = approval(root, COST_APPROVAL, actor);
678
+ if (!granted || granted.reason.includes(delegatedMark('').slice(0, -1))) {
679
+ const over = overWords(overCost, config.cost.currency);
680
+ recordRequest(root, actor, COST_APPROVAL, costRegister, `Over the running budget: ${over}.`);
681
+ const personOnly = { ...config, approvals: { ...config.approvals, delegate: null } };
682
+ block(
683
+ `Blocked: this commit takes the estimated running cost past the budget the person set: ${over}. Going past the budget is the person's call, never the lead's. First find options that fit it: a smaller size, a cheaper tier or provider, one environment instead of two, a service the product can do without at launch, or less scope, each with what it gives up. ${askHowTo(COST_APPROVAL, actor, root, personOnly, { allows: 'one commit over the running budget', need: 'the change, what it costs a month against the budget, and the options that fit, each with what it gives up' })}`,
684
+ );
685
+ }
686
+ record(costRegister, {
687
+ approval: COST_APPROVAL,
688
+ reason: granted.reason,
689
+ grantedAt: granted.grantedAt,
690
+ over: overCost,
691
+ });
692
+ useApproval(root, COST_APPROVAL, actor);
693
+ }
658
694
  // The commit that switches code-kit on: the person approved the setup it holds as init showed it.
659
695
  const setup = settingUp && files.includes(CONFIG_FILE) && beforeSetup(root);
660
696
  for (const file of files) {
@@ -794,9 +830,10 @@ ${approvalHowTo(TESTS_APPROVAL, actor, root, 'weakening tests in one commit', pe
794
830
  // The commit hook judges what the commit holds before the command runs, so a file a command earlier in
795
831
  // the chain writes (a formatter, a script, a heredoc) can't be seen, and would go in unjudged and
796
832
  // unlogged. Before the commit, a chain may only move into the checkout, make a branch where it stands
797
- // (no start point, so no file changes), stage or unstage, make folders, take away a worktree (keepsFiles)
833
+ // (no start point, or one at the commit the checkout is at, so no file changes), stage or unstage, make folders, take away a worktree (keepsFiles)
798
834
  // 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.
835
+ // with no output file), or that write only outside the checkout (writesOutside). Errors sent into the
836
+ // output or /dev/null write no file.
800
837
  const BEFORE_COMMIT = new RegExp(
801
838
  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
839
  );
@@ -809,15 +846,25 @@ const assignsOnly = (c) => ASSIGNS_ONLY.test(c.code) && !/`|\$\(|<\(/.test(c.tex
809
846
  const recordsOnly = (c) =>
810
847
  !/[<>]/.test(c.code) && (config.shell.records ?? []).some((re) => new RegExp(re).test(c.text));
811
848
  // What changes no file a commit could take: making folders (git keeps no empty folder), taking away a
812
- // worktree, which is a checkout of its own, and unstaging (`git reset [HEAD] [--] [<paths>]`, which
813
- // leaves the files as they are). A reset to another commit with no paths moves HEAD, so it counts.
849
+ // worktree, which is a checkout of its own, unstaging (`git reset [HEAD] [--] [<paths>]`, which
850
+ // leaves the files as they are) and making a branch at the commit the checkout is at. A reset to another commit with no paths moves HEAD, so it counts.
814
851
  const KEEPS_FILES = new RegExp(String.raw`^(?:mkdir\s|${GIT}worktree\s+(?:remove|prune)(?![\w-]))`);
852
+ // A branch made at a start point that is the commit the checkout is at already: no file changes.
853
+ const BRANCHES_AT =
854
+ /^git\s+(?:switch\s+(?:-q\s+|--quiet\s+)*(?:-c|--create)|checkout\s+(?:-q\s+|--quiet\s+)*-b)\s+[^\s-]\S*\s+([^\s-$`]\S*)\s*$/;
855
+ const commitOf = (ref) =>
856
+ spawnSync('git', ['-C', root, 'rev-parse', '--verify', '--quiet', `${ref}^{commit}`], {
857
+ encoding: 'utf8',
858
+ }).stdout.trim();
815
859
  const RESETS = new RegExp(String.raw`^${GIT}reset((?:\s+\S+)*)\s*$`);
816
860
  const isCommit = (w) =>
817
861
  spawnSync('git', ['-C', root, 'rev-parse', '--verify', '--quiet', `${w}^{commit}`]).status === 0;
818
862
  function keepsFiles(c) {
819
863
  if (/[<>]/.test(c.code)) return false;
820
864
  if (KEEPS_FILES.test(c.text)) return true;
865
+ const start = c.text.match(BRANCHES_AT)?.[1];
866
+ if (start && !/[$`]/.test(start))
867
+ return commitOf(start) !== '' && commitOf(start) === commitOf('HEAD');
821
868
  const reset = c.text.match(RESETS);
822
869
  if (!reset) return false;
823
870
  const words = reset[1].trim().split(/\s+/).filter(Boolean);
@@ -828,6 +875,32 @@ function keepsFiles(c) {
828
875
  const named = before.filter((w) => !w.startsWith('-'));
829
876
  return !(paths < 0 && named.length === 1 && named[0] !== 'HEAD' && isCommit(named[0]));
830
877
  }
878
+ // A path the commit can't take: written out in full, outside this project and the checkout the commit
879
+ // is in (a session's scratchpad, the system's temporary folder). The real path of what's there counts,
880
+ // so a link back into the project doesn't pass.
881
+ function realOf(p) {
882
+ let at = resolve(p);
883
+ const tail = [];
884
+ while (!existsSync(at) && dirname(at) !== at) {
885
+ tail.unshift(basename(at));
886
+ at = dirname(at);
887
+ }
888
+ return join(realpathSync(at), ...tail);
889
+ }
890
+ const within = (p, dir) => p === dir || p.startsWith(dir.endsWith(sep) ? dir : dir + sep);
891
+ function outsideCheckout(p) {
892
+ if (!p.startsWith('/') || /[$`*?{}[\]~]/.test(p)) return false;
893
+ const real = realOf(p);
894
+ return ![project, root].some((r) => within(real, realOf(r)));
895
+ }
896
+ // What writes only outside the checkout (a message drafted in a scratchpad for `git commit -F`): a read
897
+ // whose output goes only to such paths, or sed's substitutions on such files in place.
898
+ function writesOutside(c) {
899
+ const out = outputRedirects(c.whole);
900
+ if (!out?.targets.every(outsideCheckout)) return false;
901
+ if (out.targets.length && readsOnly(out.rest)) return true;
902
+ return sedInPlaceFiles(out.rest.trim())?.every(outsideCheckout) ?? false;
903
+ }
831
904
  function writesBeforeCommit() {
832
905
  const pieces = commandsOf(withoutHarmlessRedirects(cmd));
833
906
  const at = pieces.findIndex((c) => new RegExp(String.raw`^${GIT}commit(?![\w-])`).test(c.text));
@@ -839,7 +912,8 @@ function writesBeforeCommit() {
839
912
  !readsOnly(c.whole) &&
840
913
  !assignsOnly(c) &&
841
914
  !recordsOnly(c) &&
842
- !keepsFiles(c),
915
+ !keepsFiles(c) &&
916
+ !writesOutside(c),
843
917
  );
844
918
  }
845
919
 
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
  }