SLOPSHOPPER

issue-forge

Takes one GitHub issue to a pull request test-first: red, green and refactor subagents, each phase checked by commands and a 95% diff-coverage gate; pushes…

paneguardcommandpromptprocesstimer
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · issue-forge
│ ┃ Issue Forge ✕ › fix the failing auth test and add an audit log call │ ┃ I S S U E F O R G E │ ┃ ────────────────────────────────────────── ⏺ Read(src/auth.ts) │ ┃ ──────────── ⎿ Read 6 lines │ ┃ No run here. /issue-forge <issue number or ⏺ Update(src/auth.ts) │ ┃ URL> starts one, ⎿ Added 2 lines, removed 1 line │ ┃ /issue-forge demo shows every state. ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ ctrl+x tab: keys, again: next tab │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /issue-forge │ ⎿ issue-forge: opened. /issue-forge <issue number or URL> · status │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Issue Forge
I S S U E F O R G E ────────────────────────────────────────────────────── No run here. /issue-forge <issue number or URL> starts one, /issue-forge demo shows every state. ctrl+x tab: keys, again: next tab
README

Issue Forge

Hand it a GitHub issue number or URL and it comes back with a pull request, built test-first and checked by commands rather than by the model's word. Three subagents work in turn: red writes tests that fail, green makes them pass, refactor tidies. Between phases the mod checks the work: only test files changed in red, the tests failed and then passed, nobody edited the tests to make them pass, and at least 95% of the changed lines and branches are covered. Nothing is pushed until you say yes.

 I S S U E   F O R G E  bankielewicz/mod-builder#16 Mod Lab: Fix prompt a…
 ──────────────────────────────────────────────────────────────────────────
 ✓ red       3 test files, failing as intended · a1b2c3d             2m10s
 ● green     attempt 2/3 · gate G: diff branch 91.30% < 95           4m02s
 · refactor
 · publish
 ──────────────────────────────────────────────────────────────────────────
 coverage   changed lines 100.00% · branches 91.30% · total 99.36% / 83.69%
 branch     issue-16-mod-lab-fix-prompt-and-path-header-hardc → main
 also       #44 blocked at gateG · #52 refactor (another session)
 [ Hand off ]  [ Stop ]  [ Status ]

Several sessions can each run an issue in the same repository at once, each in its own worktree.

It fixes code; it doesn't build new plugins. An issue that asks for its plugin to be built with /mod-builder:build gets next steps that lead there, and nothing starts. A phase agent that tries to create a .claude-plugin/plugin.json outside the test folders is refused (a sample plugin under the profile's testGlobs is a test fixture, and is fine), and the run stops with the same kind of steps before the phase's work is committed. Such a stop is final: /issue-forge stop <N> ends it.

Try it

/issue-forge demo
  • /issue-forge <N or issue URL>: starts a run on issue N, or on the issue a pasted URL names (Which repository a run uses). If another run in the repository is active, or this session is driving one, it asks first (Parallel runs)
  • /issue-forge status [N]: where the run is (and its worktree), and the repository's other runs; with no run, whether .issue-forge.json validates
  • /issue-forge resume [N]: restarts a blocked or interrupted step
  • /issue-forge publish [N]: pushes the run's branch and opens the pull request
  • /issue-forge handoff [N]: ends this session's drive and stops its agents, but keeps the step, so any session can resume it (with N, only when this session drives #N)
  • /issue-forge stop [N]: ends the run and stops its agents that are still going, then says which stopped; its branch and commits are kept
  • /issue-forge demo [state]: every state of the pane, with nothing real running
  • /issue-forge: opens the pane, or closes it when it is shown. When it is open as a tab behind another pane, it comes to the front with the keyboard instead of closing; Esc returns the keyboard to the prompt

Without N, a command means the run the pane shows, even a finished one. If the pane shows none, it means the repository's only active run; with several, it lists them and asks you to name one. With no active run, status and publish mean the newest run started from this checkout, even a finished one.

Give the pane the keyboard with ctrl+x tab. Its keys are p publish, r resume, h hand off, s stop, t status, and in the demo n next and e end. A key acts at once, so the two that change a live run ask first: Stop ("Stop run #N? Its branch and commits are kept.") and Publish (the question that names the branch and base), whatever confirmPublish says. They ask only once the command would act, so a press it would refuse says why at once. A run another session drives is named in that one question (#N is driven by another session (for 2m05s). Stop run #N? …). Answer no, or dismiss it, and a toast says the run was left as it is. Typed as /issue-forge stop or /issue-forge publish, they are immediate. A start or a resume while the pane is behind another tab says so in its answer and leaves the keyboard alone.

Reaching the pane when other panes are open: ctrl+x tab shows the first tab and gives it the keyboard, each press after moves one tab right, and after the last tab the keyboard goes back to the prompt. Esc hands it back from any tab. A letter that is one of the pane's keys acts at once. To cycle without going through the first tab, bind pane:next and pane:previous (no default key) in ~/.claude/keybindings.json; it works while a pane holds the keyboard:

{"bindings":[{"context":"Pane","bindings":{"ctrl+x n":"pane:next","ctrl+x p":"pane:previous"}}]}

Set up a repository

Commit a .issue-forge.json at the repository root. Commands are argument vectors, and the coverage command must write LCOV:

{
  "testCommand": ["npx", "vitest", "run"],
  "coverageCommand": ["npx", "vitest", "run", "--coverage.enabled", "--coverage.provider=v8", "--coverage.reporter=lcov", "--coverage.reportsDirectory=/tmp/issue-forge/cov"],
  "lcovPath": "/tmp/issue-forge/cov/lcov.info",
  "sourceGlobs": ["src/**/*.ts"],
  "testGlobs": ["src/**/*.test.ts", "test/**"]
}

Every field, with Python and pilot examples, is in the design. This repository's own profile is .issue-forge.json at its root.

A formatter your commit hook runs

If a pre-commit hook rewrites files and stages them again (husky with lint-staged, say), name that formatter in formatCommand (0.8.0), an argument vector like the other commands:

"formatCommand": ["npx", "lint-staged"]

Each gate then stages the phase's work, runs the command, stages again, and only then records the tree it tests, so the hook finds nothing left to change when the gate commits. A command that fails (a non-zero exit, or past commandTimeoutMinutes) fails the gate as a failing check does, as R5 at gate R or G9 at gates G and F: the phase gets another attempt, with the command's output in its prompt. Without the key, nothing extra runs.

  • The base branch must already be formatted. A formatter that rewrites the whole tree (prettier --write .) on a base that isn't changes files the phase didn't touch, and at gate R those fail R1. lint-staged formats only the staged files, so it avoids this.
  • A command that exits non-zero after it changes files fails the gate each time it formats.

Where a run works

Two profile fields decide whether a run branches the checkout you start it from or gets a git worktree of its own. They are committed with the profile, so they hold for everyone, and they are read from origin/<base>'s copy before anything is switched or created:

FieldDefaultWhat it does
workspace"ask""here": branch the checkout you start from; if it's busy (uncommitted changes, not on the base, or another run working there), block. "ask": the same when it isn't busy; when it is, ask whether to use a new worktree (no answer blocks). "worktree": always add a new worktree from origin/<base> and never touch your checkout
worktreeDir"scratch/issue-forge"where new worktrees go, relative to the repository root. It must be gitignored

A worktree run lives in <worktreeDir>/<branch>/. /issue-forge status names it, with the git worktree remove <path> to run once the pull request merges. The mod never deletes a worktree's files or a branch. On resume it asks git worktree list about a kept worktree: one git has is reused, and one with nothing at its path is added again, after a git worktree remove that only clears git's entry for a folder deleted by hand. A folder at that path that git doesn't have as the worktree blocks the run, and nothing runs inside it, since git there would work on the checkout above. A relative lcovPath resolves against the run's folder, so runs in separate worktrees each write their own coverage file. Before it asks to publish, the run checks the result with git merge-tree against a freshly fetched origin/<base>, and the question names any files that would conflict.

This repository sets "workspace": "worktree": the installed plugins load from the main folder's branch, so a run must never switch it.

Which repository a run uses

A run works in the clone your session started in. Its issue and its pull request go to the repository gh repo view shows there, and every gh call of the run names it with --repo, so a stray GH_REPO or a second remote can't send the run elsewhere. The masthead and /issue-forge status name it (o/r#16; host/o/r#16 on GitHub Enterprise). A run started with a number is pinned to it as soon as origin agrees, so a later block keeps it across a resume; a run that origin blocks is pinned once the remotes are fixed and it resumes.

  • origin must be that repository, for fetching and for every push URL (git push sends to all of them), as the folder that fetches and pushes reads it (a run's worktree can have its own config). It is read from an https://, http:// or ssh remote (ssh://… or [user@]host:owner/repo); any other form (git://, file://, a path) blocks the run. An https or http remote must name the repository's host. An ssh remote may name an alias of it from ~/.ssh/config, so the same owner and repository is enough there (an ssh remote on another real host with the same owner and repository passes too: #71). A renamed or transferred repository passes: when the name differs on the same host, gh is asked what it calls it; gh is never asked about another host. A URL is never printed or passed on, since it can hold a token. GitHub Enterprise Server on a non-default port isn't supported (#71).
  • A fork clone, where origin is your fork and another remote (usually upstream) is the project gh names, runs against the project. The run reads its issue there, fetches and branches from that remote's base (upstream/main), pushes the branch to your fork, and opens the pull request on the project with your fork's owner as the head (gh pr create --repo <project> --head <you>:<branch>). Before anything is fetched, preflight checks that exactly one remote besides origin names the project (two block, naming both), that origin fetches from and pushes to one fork, that gh repo view calls it a fork of the project, and that its owner is a user: gh pr create can't name an organization's fork as the head (cli/cli#10093), so that blocks. An ssh host nickname from ~/.ssh/config (git@gh-personal:me/r.git) counts as the host ssh -G says it reaches, which never connects; a mirror with the project's name on another host isn't the project. The run stores the remote and the fork, checks the remote still names the project before each fetch from it, and publish blocks if origin stops pushing to that fork. Anything else that gh and origin disagree on still blocks the run before it fetches or switches. With the fork as the only remote, or after gh repo set-default <fork>, gh names the fork itself, so the run stays inside the fork as before. The whole flow is checked by the tests; no live pull request from a fork has been opened (the live probe is #102).
  • A pasted issue URL must name that same repository, or the command answers x/y#16 is in another repository: this checkout's GitHub repository is o/r. … and starts nothing. Only https://<host>/<owner>/<repo>/issues/<N> is read.
  • A pull request's number is refused (#24 is a pull request, not an issue), since gh issue view answers for those too.
  • A run started by 0.3 or earlier has no repository recorded: it resumes and publishes as before, with no --repo and no check of origin. A run started by 0.4 has no fork recorded: it fetches from and pushes to origin and names the branch alone as the head.

Parallel runs

Runs belong to the repository, not to the folder a session started in. Every worktree of a repository shares git's common folder, and that keys the runs. So every session in the repository sees every run: /issue-forge status lists them, and the pane's also line names the others. A session drives one run at a time. To work on two issues at once, open a second Claude Code session in the repository. With "workspace": "worktree", each run gets a worktree of its own.

/issue-forge <N> (or an issue URL) asks one question when it would meet another run:

SituationChoices (the first is the default)
Another session drives #44Start #N in a new worktree · Take over #44 here · Cancel
#44 is blocked, interrupted or ready, and no session drives itStart #N in a new worktree · Resume #44 here · Stop #44, then start #N · Cancel
This session drives #44Keep #44 (and start #N from another session) · Hand #44 off and start #N here · Cancel

Esc, or text typed under Other, cancels. Only where nobody can answer (claude -p) does a start go ahead with what you typed; in a session driving a run, it then explains how to start #N elsewhere and starts nothing. If #N has an active run already, you get its status instead.

The run you chose to hand off or stop can end while the question is open, as when another session stops it or takes it over. #N then starts anyway, and the answer begins with what became of that run: #44 was stopped in another session while you chose; starting #N; …. If the run is still active and you say no to taking it over, nothing starts.

A run records which session drives it. In any other session, Resume, Publish and Stop on that run ask If that session has ended, take it over? before they act (a press of the pane's Stop or Publish asks its own question instead, which names the other session). The mod can't tell a crashed session from a live one, so it asks rather than assumes. The driving session checks every 5 seconds and stops its drive, and its agents, when another session stopped or took over its run; before a commit, a stash, the push and the pull request it checks at once. Resume writes only if the run is still as it read it. A session that ends lets go of its run, but /clear and /resume don't, because the process and the drive go on.

Hand off (/issue-forge handoff or h) ends this session's drive and its agents at once, as Stop does, but keeps the step: the run reads interrupted everywhere, and /issue-forge resume <N> continues it in any session. A stopped run can't be resumed.

Parallel runs share git's refs. A git fetch that finds another process holding a lock is retried twice; a git stash or git commit waits a second and retries, five attempts in all (see "Limits worth knowing"). One coverage file can't serve two runs at once, so an absolute lcovPath (wherever it points) blocks a run's baseline and gates while another run is being driven: make it relative (and gitignored), as this repository's coverage/issue-forge.lcov is. When a run starts, finished runs beyond the repository's 20 newest are deleted from the store; their agents stay on the guard's list.

Claude Code keeps one store per plugin, shared by every repository's runs, and refuses a write once its JSON would pass 4,194,304 characters (4 Mi). issue-forge keeps it under 3 Mi (0.9.0):

  • A run that is done or stopped is kept without its test output or the red agent's answer, and with the first 500 characters of the issue's text. Status and the pane show it as before.
  • Before a new run is saved, the store is measured. Finished runs saved by older versions, under 0.2's checkout keys too, are trimmed the same way. While the store is over 3 Mi characters, the finished runs of any repository are deleted, those that finished longest ago first. An unfinished run is never deleted. If the store is still over, a toast says so once a session, as a share of the limit, with each cause: trims or deletes that didn't go through, keys that couldn't be read, and the unfinished runs left in how many repositories. A sweep that fails writes a transcript line. When unfinished runs alone leave no room and Claude Code refuses the new run, the start answers that it wasn't started, with Claude Code's reason, and that /issue-forge stop <N> in a run's repository ends one.
  • A command's output is kept to its last 200 lines and 20,000 characters.
  • /issue-forge status names unfinished runs that started more than 7 days ago, other than the one this session drives, with the /issue-forge stop <N> that ends each one and keeps its branch.

Runs stored by 0.2 or earlier, keyed by the checkout, move to the repository's keys when a session first starts in that checkout or in another worktree git lists.

A run needs an interactive session (claude -p exits before the agents finish), a checkout that isn't busy or a worktree run (above), gh signed in, <base> on origin, and origin is the repository gh repo view shows. If an issue names another base (a line Base branch: <name>), the run asks before using it, because the tests would run from that branch. A name git could read as an option or a forced refspec (starting with - or +, or holding :) is ignored. Globs use *, ** and ? only; braces, brackets and ! are refused.

Limits worth knowing:

  • With agent teams on (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1), Claude Code runs the mod's named agents as teammates. Inside tmux they default to pane teammates, which can't run them: the red phase blocks with a pane-based teammate cannot run it, and --settings '{"teammateMode":"in-process"}' lets it start. An in-process teammate hands back through session.receive, and the mod consumes the run's own idle notices, so the end of each phase leaves the main model idle (#27). Anything else a phase agent sends, such as a message it writes, still reaches the main model. With agent teams off, neither applies.
  • A new worktree has only what is committed: no node_modules or other untracked setup. Profile commands that need them fail in a worktree run (there's no setup command yet).
  • Agents ignore the folder they're spawned in, so in a worktree run the mod moves the live agent's Bash, Grep and Glob into the worktree, makes its relative Edit, Write and Read paths absolute there, and refuses an edit outside it. A path it can't place (\x, \\server\share, ~, D:x) is refused in every run. That catches honest mistakes; it isn't a sandbox. The check reads paths as text, so a symlink inside the worktree can still lead an edit outside it. A Bash command that cds elsewhere or names an absolute path still reaches it, and a here run's agents can't Write outside the repository either (/tmp included).
  • A red type that isn't the mod's own (redAgentType) can't run in a worktree: a plugin that routes it elsewhere (to Codex, say) may run it in the session's folder whatever the spawn says, so a worktree run with one blocks before it starts.
  • A run started in a linked worktree puts its new worktree under that checkout's worktreeDir, so the agents' writes stay under the session's folder.
  • The merge check at ready needs git 2.38 or later (merge-tree --write-tree); with an older git it reads merge check unavailable and the run goes on.
  • Resuming a kept worktree whose folder was deleted needs git 2.31 or later, which marks it prunable in git worktree list. An older git lists it as there, so the resume fails instead of adding it again.
  • Runs were checked with Claude Code's auto permission mode. In other modes a phase agent's Edit or Bash may wait on a permission prompt nobody sees; the pane then shows agent working until you /issue-forge stop. There's no agent timeout yet.
  • A stop ends the run's agents with Claude Code's TaskStop tool. That was checked under auto mode on 2.1.310, for a subagent and an in-process teammate, and not in other permission modes. The stop's answer says which agents stopped, and names any that didn't, with the reason.
  • G6 checks that a behaviour test file (behaviourTestGlobs) is in the red commit, not what it tests.
  • Command lookup uses sh -c 'command -v …', so sh must be on PATH (Git Bash on Windows).
  • The profile that runs is the one on origin/<base>, read after the switch; the checkout you start from only names the base.
  • The run works in the session's own checkout (or its worktree). A git command in that checkout from any session while the run is between steps, a plain git status included, can take .git/index.lock just as the run writes the index; another run of the repository can hold a branch's lock or refs/stash's. The run's add, commit, stash, switch and merge retry for 4 s (five attempts, a second apart); if the lock is still there the run blocks with another git process is using <path> (5 attempts over 4 s), and /issue-forge resume continues once it is gone. A Stop during the wait ends it at once. The run's own git calls take no optional locks (GIT_OPTIONAL_LOCKS=0), so its git status doesn't hold the lock against yours. A lock in the main checkout doesn't affect a linked worktree, which has its own index. When other sessions share the checkout, start issue-forge in a dedicated worktree ("workspace": "worktree").
  • If two sessions start the same issue at the same moment, the second write wins, and the other session's run stops at its next step.
  • A crashed session leaves its run marked as driven until another session answers Take over.
  • After /clear and then a reload, your own interrupted run reads as if another session drove it.
  • A gate commits only the tree it tested (0.7.5), and its checks judge that tree: when another process stages a path after the gate staged, or the commit holds another tree, the gate blocks and names both trees. issue-forge never resets a commit itself, and /issue-forge resume stages everything again and tests it. A pre-commit hook that rewrites and re-stages files (husky with lint-staged, say) blocks each gate once this way: resume tests the commit as it stands and keeps it. Naming the hook's formatter in formatCommand (0.8.0, under "Set up a repository") avoids the block, and so does a check-only hook (lint-staged --fail-on-changes, black --check). A pre-commit hook that fails the commit (the pre-commit framework, when a hook changes files) blocks the gate as before 0.7.5, now saying the gate passed and naming the hook as the likely cause.
  • Profile commands must leave the tree as they found it: a gate that sees files changed after staging (a formatter, a snapshot update) blocks rather than commit bytes it didn't test. A formatter belongs in formatCommand, which runs before the gate records the tree it tests. The run's branch is cut from origin/<base>, so

the profile and anything its commands use must already be there.

Install

From the GitHub marketplace:

/plugin install issue-forge --marketplace bankielewicz/mod-builder

From a local clone (claude plugin marketplace add <folder> once):

/plugin install issue-forge@claudemod

While developing, from its folder:

claude --plugin-dir <path-to>/issue-forge

Changes load with /reload-plugins or a new session.

Options

OptionDefaultWhat it does
redModelopusmodel for the red agent
greenModelsonnetmodel for the green agent
refactorModelopusmodel for the refactor agent

| redAgentType | issue-forge:red | another type runs red as that agent, unnamed, so a plugin that routes agent types (to Codex, say) can take it. The routed run has to be able to write tests and to answer before the phase ends; one that answers in the background ends the phase at once with nothing

Source 3 files
hooks/register.tsx 2394 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ProcessRunResult, Register } from 'claude-code'
3
4import {
5  AGENT_DESCRIPTIONS,
6  DEFAULT_COMMAND_MINUTES,
7  DEMO_STATES,
8  NAME,
9  PHASES,
10  PROFILE_FILE,
11  STASH_LIST_ARGV,
12  STORE_BUDGET,
13  TAKE_OVER,
14  USAGE,
15  advance,
16  afterBlock,
17  agentName,
18  isInlineAnswer,
19  lateSpawnRefs,
20  withLateAgent,
21  agentsKey,
22  agentsToEnd,
23  agentPrompt,
24  badgeOf,
25  baseOf,
26  baseRefOf,
27  baseRemoteOf,
28  baseRemoteOfRun,
29  branchLine,
30  branchName,
31  branchMoved,
32  canRetry,
33  checkoutBaseOf,
34  checkoutState,
35  checkoutWorkspaceOf,
36  cleanupLine,
37  commitFields,
38  commitMessage,
39  commitRefused,
40  commonDirOf,
41  coverageLine,
42  demoRun,
43  elsewhereLine,
44  elsewhereText,
45  endOutcome,
46  endedClause,
47  endedWhileAsked,
48  handOffAnswer,
49  lateAnswer,
50  movedOnAnswer,
51  stopAnswer,
52  findStash,
53  finishedRecord,
54  foreignChange,
55  forkOfOrigin,
56  forkRemoteVerdict,
57  formatGate,
58  gateG,
59  gateR,
60  guardAction,
61  hasSourceRecord,
62  hasStash,
63  headArg,
64  hostOf,
65  isAbsolutePath,
66  isActive,
67  isDrivenElsewhere,
68  isForkOf,
69  isLockError,
70  isOwnHandback,
71  isOwnMailboxHandback,
72  isPluginManifest,
73  isPullUrl,
74  isSameRepo,
75  isWorking,
76  isWorktreeRun,
77  issueLabel,
78  keepText,
79  keptCommit,
80  keptForkBlock,
81  keptWorktreePlan,
82  layoutOf,
83  lcovFileOf,
84  leftAfter,
85  legacyAgentsKey,
86  lineOf,
87  lockPathOf,
88  manifestOf,
89  mergeLine,
90  migrationPlan,
91  newModLine,
92  newModReply,
93  newPluginGate,
94  newPluginOf,
95  newPluginRecord,
96  newPluginRefusal,
97  newRun,
98  nextDemoState,
99  normalizePath,
100  openCounts,
101  othersLine,
102  othersOf,
103  outputTail,
104  outsideChecks,
105  ownerOf,
106  parseCommand,
107  parseLcov,
108  parseMergeTree,
109  parseProfile,
110  parseRunKey,
111  phasePrompt,
112  phaseRows,
113  pickRun,
114  prBody,
115  profileProblems,
116  profileStatusText,
117  promptExtraOf,
118  pruneKeys,
119  publishAsk,
120  paneAction,
121  pressQuestion,
122  publishQuestion,
123  readdWorktreeCommand,
124  recheckOf,
125  releasesOnEnd,
126  remoteVerdict,
127  repoLabel,
128  repoOfView,
129  repoAgentsKeys,
130  repoRunKeys,
131  routedRedBlock,
132  runKey,
133  severalText,
134  sharedLcovBlock,
135  spawnRefs,
136  splitZ,
137  sshHostToResolve,
138  sshHostname,
139  staleLine,
140  stashApplyArgv,
141  stashMessage,
142  startAnswer,
143  startChoices,
144  statusText,
145  storeWarning,
146  sweepPlan,
147  takeOverQuestion,
148  totals,
149  treeDrift,
150  truncate,
151  unstagedOf,
152  viewOf,
153  withRefusal,
154  workOf,
155  workspacePlan,
156  worktreeAddFailure,
157  worktreePath,
158  worktreeStateOf,
159} from './issue-forge-logic'
160import type { Activity, BaseRemote, CheckoutState, Command, CommandResult, DemoState, DemoView, EndedAgents, Gate, Kept, KeptWorktreePlan, LegacyEntry, LineContext, ListedAgent, MergeCheck, OtherRun, Phase, Profile, RemoteFound, RemoteVerdict, Run, RunEvent, RunPick, StashRef, Step, Tone, TurnEnd } from './issue-forge-logic'
161
162/**
163 * Issue Forge: one GitHub issue to a pull request, test-first (SPEC.md "How it works").
164 * Every `$` call lives here; every rule lives in issue-forge-logic.ts.
165 */
166
167const PANE = 'issue-forge'
168const TITLE = 'Issue Forge'
169/** The pane as every open asks for it; bringing it to the front adds only `focus`. */
170const PANE_ARGS = { id: PANE, title: TITLE, columns: 76 }
171const SHOW_TEXT = 'bringing the pane to the front; it takes the keyboard if your prompt is empty (Esc gives it back).'
172const STILL_BEHIND_TOAST = `${TITLE} is still behind another tab: ctrl+x tab, then again until it shows.`
173/** After a start or a resume opened the pane behind another tab: where it is and how to reach it. */
174const BEHIND_TEXT = 'its pane is behind another tab (ctrl+x tab, then again until it shows)'
175/** How long after asking for the front the pane is read again (#31). */
176const FRONT_CHECK_MS = 500
177const GIT_TIMEOUT = 60_000
178/** The attempts a git call that writes the index or a ref makes against a held lock, a second apart (#28). */
179const LOCK_ATTEMPTS = 5
180const LOCK_WAIT_MS = 1000
181/** Why a phase agent's report is kept from the main model: shown for prompt.submit's drop, only logged for session.receive's consumed (d.ts). */
182const HANDBACK_DROP = 'issue-forge: a phase agent finished; the pane has the result.'
183const COLORS: Record<Tone, string | undefined> = { success: '#7FB685', accent: '#D97757', warn: '#E0B15A', error: '#E06C6C', dim: undefined }
184
185const runAtom = atom({ plugin: 'issue-forge', key: 'run' } as const, null)
186const activityAtom = atom({ plugin: 'issue-forge', key: 'activity' } as const, null)
187const nowAtom = atom({ plugin: 'issue-forge', key: 'now' } as const, 0)
188const demoAtom = atom({ plugin: 'issue-forge', key: 'demo' } as const, null)
189/** The issue whose run the pane shows: the one this session last started, resumed, published, stopped or asked about (Change 0.3.0). */
190const focusAtom = atom({ plugin: 'issue-forge', key: 'focus' } as const, null)
191/** The repository's other active runs: the pane's also line. */
192const othersAtom = atom({ plugin: 'issue-forge', key: 'others' } as const, [] as OtherRun[])
193
194type Options = { redModel: string; greenModel: string; refactorModel: string; redAgentType: string; confirmPublish: boolean }
195
196let options: Options = { redModel: 'opus', greenModel: 'sonnet', refactorModel: 'opus', redAgentType: 'issue-forge:red', confirmPublish: true }
197let sessionCwd = ''
198/** Whether a person is at the prompt: a dismissed start menu then means Cancel (PR #51 review). */
199let isInteractive = true
200let home = ''
201/** This session's id, read once at session start: what a run's driver names (Change 0.3.0). */
202let sessionId = ''
203/** The issue the pane shows, kept in the module: /clear, /resume and /branch reset focusAtom (#119). */
204let focusKept: number | null = null
205/** The drive's activity line, kept in the module for the same reason (#119). */
206let activityKept: Activity | null = null
207/**
208 * A drive: its run, the run's store key and issue, whether it was stopped or handed off, and its generation. A new
209 * drive of the same run (a hand-off, then a resume) has a new one, so the old drive's step in flight fails every
210 * ownership check (PR #51 review).
211 */
212type Drive = { runId: string; key: string; issue: number; isStopped: boolean; gen: number }
213/** The run as a drive hands it to a step: stamped with the drive's generation (never stored). */
214type Stamped = Run & { driveGen: number }
215let drives = 0
216/** The run this module is driving (one per session); null after a reload (the run then reads as interrupted). */
217let driving: Drive | null = null
218/** The driven run as last written: the status line's badge. */
219let drivenLast: Run | null = null
220/** The run whose drive has its publish question open; a Publish or Stop press then asks no second one (PR #96 review). */
221let publishAsking: string | null = null
222/** Ends the long command running now (a stop, or its timeout). */
223let stopCommand: (() => void) | null = null
224/** The one agent of the run allowed to call tools; the run's other agents are refused (SPEC 9). */
225let liveAgent: string | null = null
226/** The live agent's run: where the guard keeps it (Change 0.2.0; an agent's cwd is ignored, P4). */
227let liveWork: { root: string; workRoot: string; testGlobs: readonly string[]; baseManifests: readonly string[] } | null = null
228/**
229 * Every agent id and name a run of this repository has started, in memory for the tool.call guard,
230 * the hand-back drop and the end of a drive (which ends them with TaskStop, #40), and in the store so a
231 * new run or a reload never forgets one: one TaskStop didn't end is still refused by the guard.
232 */
233let knownRefs = new Set<string>()
234/** The last run write queued: updateRun chains each one after it. */
235let runWrites: Promise<void> = Promise.resolve()
236/** Whether the store warning was shown (#140): once a session, or once more after a reload. */
237let isStoreWarned = false
238/** Where git keeps each folder's lock files, asked once per folder and file (PR #88 review). */
239const lockFiles: Record<string, string> = {}
240/** An agent's final answer and how its turn ended, for the phase waiting on it. */
241type AgentTurn = { answer: string; reason?: TurnEnd }
242const waiting: Record<string, { resolve: (turn: AgentTurn) => void; reject: (err: Error) => void }> = {}
243
244function readOptions(raw: unknown): Options {
245  const o = (raw ?? {}) as Record<string, unknown>
246  const text = (key: string, fallback: string) => (typeof o[key] === 'string' && (o[key] as string).trim() !== '' ? (o[key] as string).trim() : fallback)
247  return {
248    redModel: text('redModel', 'opus'),
249    greenModel: text('greenModel', 'sonnet'),
250    refactorModel: text('refactorModel', 'opus'),
251    redAgentType: text('redAgentType', 'issue-forge:red'),
252    confirmPublish: o.confirmPublish !== false && o.confirmPublish !== 'false',
253  }
254}
255
256const MAX_KNOWN = 500
257
258/** A run's store key; runs stored before 0.3.0 had no repo until session start moved them. */
259const keyOf = (run: Run) => runKey(run.repo ?? run.root, run.issue)
260
261function refsOf(run: Run | null): string[] {
262  return run ? run.agents.flatMap(a => (a.name ? [a.id, a.name] : [a.id])) : []
263}
264
265// ── Outside world ─────────────────────────────────────────────────────────
266
267/** git takes no optional locks, so the run's own `git status` doesn't refresh the index while an agent's or the user's git needs it (#28). */
268const GIT_ENV = { GIT_OPTIONAL_LOCKS: '0' }
269
270async function git($: EngineInterface, root: string, args: string[], stdin?: string) {
271  return $.process.run(['git', ...args], { cwd: root, timeoutMs: GIT_TIMEOUT, env: GIT_ENV, ...(stdin === undefined ? {} : { stdin }) })
272}
273
274/**
275 * git that another process may hold a lock against (a parallel run's fetch): retried twice at once (Change 0.3.0).
276 * A fetch spends seconds on the network first, so the other is done. The index has gitWrite (#28).
277 */
278async function gitRetry($: EngineInterface, root: string, args: string[], stdin?: string) {
279  let r = await git($, root, args, stdin)
280  for (let i = 0; i < 2 && r.exitCode !== 0 && isLockError(`${r.stderr}\n${r.stdout}`); i++) r = await git($, root, args, stdin)
281  return r
282}
283
284/** A git call's output: a failure throws, naming the subcommand and the first line git printed. */
285function outputOf(args: string[], r: ProcessRunResult): string {
286  // Named by its subcommand, not a global option before it (`--no-replace-objects cat-file`).
287  if (r.exitCode !== 0) throw new Error(`git ${args.find(arg => !arg.startsWith('-')) ?? args[0]} failed: ${firstLine(r.stderr || r.stdout)}`)
288  return r.stdout
289}
290
291async function gitOut($: EngineInterface, root: string, args: string[]): Promise<string> {
292  return outputOf(args, await git($, root, args))
293}
294
295/** Thrown when a git lock (the index's or a ref's) is still held after the last attempt: the drive blocks with its reason and next step. */
296class Locked extends Error {
297  readonly next: string
298  constructor(lockPath: string) {
299    super(`another git process is using ${lockPath} (${LOCK_ATTEMPTS} attempts over ${((LOCK_ATTEMPTS - 1) * LOCK_WAIT_MS) / 1000} s)`)
300    this.next = `wait for the other git process to finish, or delete ${lockPath} if none is running`
301  }
302}
303
304/**
305 * git that writes the index or a ref (add, commit, stash, switch, merge): another process holding .git/index.lock, or a
306 * ref's lock, fails it at once, so a failure caused by a lock waits a second and tries again, five attempts in all (#28,
307 * PR #88 review). Stash prints nothing when it meets the index lock, so that file is looked for too. Any other failure
308 * comes back as it is.
309 */
310async function gitWrite($: EngineInterface, run: Run, root: string, args: string[], stdin?: string) {
311  // Known before the call: a lock file is a silent failure's only sign, and the other process may let it go soon after.
312  // stash push names no lock when refs/stash's is held (git 2.53: only "Cannot save the current status").
313  const files = [await lockFileOf($, root, 'index.lock'), ...(args[0] === 'stash' && args[1] === 'push' ? [await lockFileOf($, root, 'refs/stash.lock')] : [])]
314  for (let attempt = 1; ; attempt++) {
315    const r = await git($, root, args, stdin)
316    if (r.exitCode === 0) return r
317    const text = `${r.stderr}\n${r.stdout}`
318    const held = lockPathOf(text) ?? (await heldOf($, files))
319    if (!held && !isLockError(text)) return r
320    // A lock refusal that no lock file explains (a broken ref) comes back as git said it once the attempts are spent.
321    if (attempt === LOCK_ATTEMPTS) {
322      if (!held) return r
323      throw new Locked(held)
324    }
325    await lockWait($)
326    // The 5 s watch is too slow for a takeover during the waits: the stored run is read before each attempt.
327    await stillOwned($, run)
328  }
329}
330
331/**
332 * One of the folder's lock files: a linked worktree's index lock is under the main .git folder, and refs/stash is
333 * shared by every worktree, so git says where. Without `--path-format=absolute`, which git before 2.31 prints back
334 * instead of reading, so a relative answer is joined here.
335 */
336async function lockFileOf($: EngineInterface, root: string, name: 'index.lock' | 'refs/stash.lock'): Promise<string> {
337  const key = `${root}\0${name}`
338  const known = lockFiles[key]
339  if (known) return known
340  const r = await git($, root, ['rev-parse', '--git-path', name])
341  const path = r.exitCode === 0 ? r.stdout.trim() : ''
342  if (!path) return `${root}/.git/${name}`
343  return (lockFiles[key] = isAbsolutePath(path) ? path : `${root}/${path}`)
344}
345
346/** The first of `files` that exists, or null. */
347async function heldOf($: EngineInterface, files: string[]): Promise<string | null> {
348  for (const file of files) if (await $.fs.exists(file)) return file
349  return null
350}
351
352/**
353 * The second between lock attempts, as a timer: `$.clock.sleep` would count against a hook's budget. The timer may never
354 * fire (a hook refuses it, a reload cancels it), so a Stop, hand-off or takeover ends the wait itself, as it ends a command.
355 */
356async function lockWait($: EngineInterface): Promise<void> {
357  try {
358    await new Promise<void>((resolve, reject) => {
359      const timer = $.clock.after(LOCK_WAIT_MS, () => resolve())
360      stopCommand = () => {
361        timer.cancel()
362        reject(new Stopped())
363      }
364    })
365  } finally {
366    stopCommand = null
367  }
368}
369
370/** gitWrite for a call that must succeed: a failure throws, as gitOut's does. */
371async function gitWriteOut($: EngineInterface, run: Run, root: string, args: string[], stdin?: string): Promise<string> {
372  return outputOf(args, await gitWrite($, run, root, args, stdin))
373}
374
375function firstLine(text: string): string {
376  return text.trim().split('\n')[0] ?? ''
377}
378
379async function rootOf($: EngineInterface): Promise<string | null> {
380  const r = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { cwd: sessionCwd || undefined, timeoutMs: GIT_TIMEOUT, env: GIT_ENV }).catch(() => null)
381  return r && r.exitCode === 0 ? r.stdout.trim() : null
382}
383
384/** The session's checkout and git's common folder, which every worktree of the repository shares (Change 0.3.0). */
385type Repo = { root: string; repo: string }
386
387async function repoOf($: EngineInterface): Promise<Repo | null> {
388  const root = await rootOf($)
389  if (!root) return null
390  const r = await git($, root, ['rev-parse', '--git-common-dir']).catch(() => null)
391  const repo = r && r.exitCode === 0 ? commonDirOf(root, r.stdout) : null
392  return repo ? { root, repo } : null
393}
394
395async function loadRun($: EngineInterface, key: string): Promise<Run | null> {
396  return ((await $.store.get(key)) as Run | undefined) ?? null
397}
398
399/** The repository's runs, read from the store each time: other sessions write it too. */
400async function listRuns($: EngineInterface, repo: string): Promise<{ key: string; run: Run }[]> {
401  const out: { key: string; run: Run }[] = []
402  for (const key of repoRunKeys(await $.store.keys(), repo)) {
403    const run = await loadRun($, key)
404    if (run) out.push({ key, run })
405  }
406  return out
407}
408
409async function runsOf($: EngineInterface, repo: string): Promise<Run[]> {
410  return (await listRuns($, repo)).map(e => e.run)
411}
412
413/**
414 * Every write of a stored run, one at a time, so none is computed from a read another write has since made stale
415 * (PR #41 round 4). `change` gets the run as stored now and returns what to store, or null to write nothing.
416 * Resolves to the run written, or null.
417 */
418async function updateRun($: EngineInterface, key: string, change: (stored: Run | null) => Run | null): Promise<Run | null> {
419  const before = runWrites
420  let done = () => {}
421  runWrites = new Promise<void>(resolve => (done = resolve))
422  try {
423    await before
424    const next = change(await loadRun($, key))
425    if (!next) return null
426    await $.store.set(key, next)
427    await reflect($, next)
428    return next
429  } finally {
430    done()
431  }
432}
433
434/** A run just written: its agents are known, the pane redraws it when it is the one shown, the badge when it is driven. */
435async function reflect($: EngineInterface, run: Run): Promise<void> {
436  for (const ref of refsOf(run)) knownRefs.add(ref)
437  if (driving && run.id === driving.runId) drivenLast = run
438  if ((await read($, focusAtom)) === run.issue) await update($, runAtom, () => run)
439}
440
441/** Another session drives the stored run now: it took it over (Change 0.3.0). */
442function isTakenOver(stored: Run): boolean {
443  return !!stored.driver && stored.driver.session !== sessionId
444}
445
446/**
447 * A drive's write, by generation `gen`. Resolves to the run written, or null when it was dropped: the drive then has
448 * nothing left to drive. A stop wins every race, a write lands only on the same run, never on one another session
449 * took over (Change 0.3.0), and never from a drive that was stopped, handed off or replaced (PR #51 review). A refusal
450 * the guard stored meanwhile is kept (Codex 4290653342).
451 */
452async function saveRun($: EngineInterface, run: Run, gen: number): Promise<Run | null> {
453  return updateRun($, keyOf(run), stored =>
454    !stored || stored.id !== run.id || (run.step !== 'stopped' && stored.step === 'stopped') || isTakenOver(stored) || driving?.gen !== gen || driving.isStopped ? null : withRefusal(stored, run),
455  )
456}
457
458/**
459 * The branch and folder preflight just made, written onto the stored run at once, even over a stop, so a
460 * Stop pressed before preflight returns never loses them (Codex, PR #41 round 3). Never onto a run another
461 * session took over meanwhile: it makes its own (Codex 4278707576).
462 */
463async function recordMade($: EngineInterface, run: Run, made: Kept): Promise<void> {
464  const now = await $.clock.now()
465  await updateRun($, keyOf(run), stored => (stored?.id === run.id && !isTakenOver(stored) ? advance(stored, { type: 'made', keep: made }, now) : null))
466}
467
468/** A number start's repository, written onto the stored run at once, as recordMade writes the branch (PR #68 review 2). */
469async function recordPinned($: EngineInterface, run: Run, repo: string): Promise<void> {
470  const now = await $.clock.now()
471  await updateRun($, keyOf(run), stored => (stored?.id === run.id && !isTakenOver(stored) ? advance(stored, { type: 'pinned', repo }, now) : null))
472}
473
474/** Adds agents to the run's known list (memory and store); they are refused tools unless live. */
475async function rememberAgents($: EngineInterface, run: Run, refs: readonly string[]): Promise<void> {
476  for (const ref of refs) knownRefs.add(ref)
477  const key = agentsKey(run.repo ?? run.root, run.issue)
478  const stored = ((await $.store.get(key)) as string[] | undefined) ?? []
479  const merged = [...new Set([...stored, ...refs])].slice(-MAX_KNOWN)
480  await $.store.set(key, merged)
481}
482
483async function setActivity($: EngineInterface, label: string | null): Promise<void> {
484  const since = await $.clock.now()
485  const activity = label ? { label, since } : null
486  activityKept = activity
487  await update($, activityAtom, () => activity)
488}
489
490/**
491 * A long command (tests, coverage, checks) through `$.process.spawn`, killed at the profile's
492 * timeout by ending its stream (C0 P3). Where spawn can't start (always under `claude plugin
493 * test`), the same command runs through `$.process.run`, capped at ten minutes.
494 */
495async function runLong($: EngineInterface, argv: string[], root: string, minutes: number, env?: Record<string, string>): Promise<CommandResult> {
496  let text = ''
497  let isTimedOut = false
498  let isStopped = false
499  let hasStarted = false
500  const stream = $.process.spawn({ argv, cwd: root, ...(env ? { env } : {}) })
501  const end = () => void stream.return(undefined as never).catch(() => undefined)
502  const timer = $.clock.after(minutes * 60_000, () => {
503    isTimedOut = true
504    end()
505  })
506  stopCommand = () => {
507    isStopped = true
508    end()
509  }
510  try {
511    let result: CommandResult
512    try {
513      for await (const piece of stream) {
514        hasStarted = true
515        text = (text + piece.text).slice(-200_000)
516      }
517      if (isTimedOut || isStopped) result = { exit: null, isTimedOut, tail: outputTail(text) }
518      else result = { exit: (await stream.result).code, isTimedOut: false, tail: outputTail(text) }
519    } catch (err) {
520      result = hasStarted || isTimedOut || isStopped ? { exit: null, isTimedOut, tail: outputTail(text) } : await runShort($, argv, root, minutes, err, env)
521    }
522    if (isStopped) throw new Stopped()
523    return result
524  } finally {
525    timer.cancel()
526    stopCommand = null
527  }
528}
529
530/** Thrown when /issue-forge stop (or a takeover) ends the run mid-step: nothing after it may change the repository. */
531class Stopped extends Error {
532  constructor() {
533    super('stopped')
534  }
535}
536
537/** Whether this module is still driving `run`: false once it was stopped, or another drive (a later one included) took it over. */
538function isDriving(run: Run): boolean {
539  return driving !== null && driving.runId === run.id && !driving.isStopped && (run as Partial<Stamped>).driveGen === driving.gen
540}
541
542function stillDriving(run: Run): void {
543  if (!isDriving(run)) throw new Stopped()
544}
545
546/** Before a commit or a stash: a run another session stopped, took over or replaced is left alone (Change 0.3.0). */
547async function stillOwned($: EngineInterface, run: Run): Promise<void> {
548  stillDriving(run)
549  if (foreignChange(await loadRun($, keyOf(run)), run.id, sessionId)) {
550    endLocalDrive()
551    await endAgents($, knownRefs)
552    throw new Stopped()
553  }
554}
555
556/**
557 * Ends this session's drive at once, as a Stop does, writing nothing: the command is ended and the guard refuses the
558 * agent from now on. Ending the agent itself is `endAgents`, which every caller runs next (#40).
559 */
560function endLocalDrive(): void {
561  if (driving) driving.isStopped = true
562  stopCommand?.()
563  liveAgent = null
564  liveWork = null
565  for (const [id, w] of Object.entries(waiting)) {
566    delete waiting[id]
567    w.reject(new Error('stopped'))
568  }
569}
570
571/**
572 * Ends this session's issue-forge agents still going whose id, name or teammate name is in `refs`, with the built-in
573 * TaskStop, then lists them again: each outcome is what that listing shows, never a promise (#40).
574 */
575async function endAgents($: EngineInterface, refs: Iterable<string>): Promise<EndedAgents> {
576  const wanted = [...refs]
577  if (wanted.length === 0) return []
578  let listed: ListedAgent[]
579  try {
580    listed = await $.agent.list()
581  } catch (err) {
582    return { unlisted: err instanceof Error ? err.message : String(err) }
583  }
584  const targets = agentsToEnd(wanted, listed)
585  if (targets.length === 0) return []
586  const answers = new Map(await Promise.all(targets.map(async agent => [agent.id, await stopAgent($, agent.id)] as const)))
587  const outcomesBy = (rows: readonly ListedAgent[] | null) =>
588    targets.map(agent => endOutcome(agent, answers.get(agent.id)?.refused ?? null, rows, answers.get(agent.id)?.said ?? undefined))
589  let after: readonly ListedAgent[] | null = await $.agent.list().catch(() => null)
590  let outcomes = outcomesBy(after)
591  // TaskStop's kill may land a moment after its answer: an agent it didn't refuse that still reads as going is listed once more.
592  if (after && outcomes.some(o => !o.isEnded && answers.get(o.agent.id)?.refused === null)) {
593    // A timer, not `$.clock.sleep`, which counts against a hook's budget (as lockWait). A refused timer skips the re-check,
594    // and the first listing stands (PR #151 review round 2, finding 6); a reload ends this wait with the module.
595    const isWaited = await new Promise<boolean>(resolve => {
596      try {
597        $.clock.after(RECHECK_MS, () => resolve(true))
598      } catch {
599        resolve(false)
600      }
601    })
602    if (isWaited) {
603      after = await $.agent.list().catch(() => after)
604      outcomes = outcomesBy(after)
605    }
606  }
607  return outcomes
608}
609
610/** What one TaskStop came to: its refusal, or null and what it said. */
611type StopAnswer = { refused: string | null; said: string | null }
612
613/** How long to wait before listing again an agent TaskStop answered for that still reads as going (PR #151 review round 1). */
614const RECHECK_MS = 1000
615
616/** One TaskStop by the agent's id, the form #40's probe showed ends a subagent and a teammate. */
617async function stopAgent($: EngineInterface, id: string): Promise<StopAnswer> {
618  try {
619    const answer = await $.tool.call({ tool: 'TaskStop', task_id: id })
620    if (answer.deny !== undefined) return { refused: answer.deny, said: null }
621    if (answer.isError) return { refused: truncate(answer.text ?? 'TaskStop failed', 120), said: null }
622    const message = (answer.result as { message?: unknown } | undefined)?.message
623    return { refused: null, said: truncate(typeof message === 'string' ? message : (answer.text ?? ''), 120) || null }
624  } catch (err) {
625    return { refused: err instanceof Error ? err.message : String(err), said: null }
626  }
627}
628
629/** The drive under way in this session, if any (a stopped or handed-off one isn't). */
630function drivingNow(): Drive | null {
631  return driving && !driving.isStopped ? driving : null
632}
633
634async function hasBranch($: EngineInterface, root: string, branch: string): Promise<boolean> {
635  return (await git($, root, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`])).exitCode === 0
636}
637
638/** A gate commits only on the run's own branch: an agent may have switched branches. */
639async function offBranch($: EngineInterface, run: Run): Promise<Blocked | null> {
640  const head = (await gitOut($, workOf(run), ['rev-parse', '--abbrev-ref', 'HEAD'])).trim()
641  return head === run.branch ? null : block(`HEAD is on ${head}, not ${run.branch}`, `git switch ${run.branch}`)
642}
643
644async function runShort($: EngineInterface, argv: string[], root: string, minutes: number, why: unknown, env?: Record<string, string>): Promise<CommandResult> {
645  try {
646    const r = await $.process.run(argv, { cwd: root, timeoutMs: Math.min(minutes * 60_000, 600_000), ...(env ? { env } : {}) })
647    return { exit: r.exitCode, isTimedOut: false, tail: outputTail(`${r.stdout}\n${r.stderr}`) }
648  } catch (err) {
649    return { exit: null, isTimedOut: /time/i.test(String(err)), tail: `could not run ${argv.join(' ')}: ${String(err)} (spawn: ${String(why)})` }
650  }
651}
652
653/** The LCOV file's text if the coverage command wrote it after `since`; a stale or missing file is null. */
654async function readLcov($: EngineInterface, path: string, since: number): Promise<string | null> {
655  try {
656    const st = await $.fs.stat(path)
657    if (st.mtimeMs < since - 2000) return null
658    return await $.fs.read(path)
659  } catch {
660    return null
661  }
662}
663
664/** The index's tree; `write-tree` takes the index lock, so it goes through gitWrite (#101 probe, git 2.53). */
665async function indexTree($: EngineInterface, run: Run, root: string): Promise<string> {
666  return (await gitWriteOut($, run, root, ['write-tree'])).trim()
667}
668
669/**
670 * HEAD, its tree and its parents, from the commit object itself: `rev-parse --verify HEAD`, then `cat-file commit` with
671 * replacement refs off, so the tree is that commit's own (PR #136 review rounds 1 and 2; Codex 4350587226, 4351786036).
672 * Plumbing: neither log.showSignature nor another log setting adds lines, and no git newer than the gates' needs it.
673 */
674async function headAndTree($: EngineInterface, root: string): Promise<{ head: string; tree: string; parents: string[] }> {
675  const head = (await gitOut($, root, ['rev-parse', '--verify', 'HEAD'])).trim()
676  return { head, ...commitFields(await gitOut($, root, ['--no-replace-objects', 'cat-file', 'commit', head])) }
677}
678
679/**
680 * Commits the tree gate `gate` tested (#101): a block when the index changed since, or when the commit made holds another
681 * tree (another process staged during a lock wait, or a hook re-staged). Else `head`, a commit whose tree is the tested one,
682 * and `commit` when this call made it: nothing to commit means HEAD's tree is the tested one already.
683 */
684async function commitAll($: EngineInterface, run: Run, message: string, gate: 'R' | 'G' | 'F', tested: string): Promise<Blocked | { commit?: string; head: string }> {
685  // A lock that outlasts the retries, or a commit a hook failed, comes back as a block, so the gate's result is kept (round 2).
686  try {
687    return await commitTested($, run, message, gate, tested)
688  } catch (err) {
689    if (err instanceof Locked) return block(err.message, err.next)
690    if (err instanceof Error && err.message.startsWith('git commit failed:')) {
691      const refused = commitRefused(gate, err.message)
692      return block(refused.reason, refused.next)
693    }
694    throw err
695  }
696}
697
698async function commitTested($: EngineInterface, run: Run, message: string, gate: 'R' | 'G' | 'F', tested: string): Promise<Blocked | { commit?: string; head: string }> {
699  await stillOwned($, run)
700  const root = workOf(run)
701  const before = treeDrift(gate, tested, await indexTree($, run, root))
702  if (before) return block(before.reason, before.next)
703  const now = await headAndTree($, root)
704  if (now.tree === tested) return { head: now.head }
705  await gitWriteOut($, run, root, ['commit', '-q', '-F', '-'], message)
706  const made = await headAndTree($, root)
707  // Another process committed on the branch around this commit: HEAD isn't the one this call made (round 2).
708  if (made.parents[0] !== now.head) {
709    const moved = branchMoved(gate, now.head, made.head, made.parents[0] ?? '')
710    return block(moved.reason, moved.next)
711  }
712  const after = treeDrift(gate, tested, made.tree, made.head)
713  return after ? block(after.reason, after.next) : { commit: made.head, head: made.head }
714}
715
716/** Stashes the tree under a unique message and records the entry's SHA (the list is shared by every worktree). */
717async function stashAll($: EngineInterface, run: Run, message: string): Promise<StashRef | undefined> {
718  await stillOwned($, run)
719  const root = workOf(run)
720  await gitWriteOut($, run, root, ['stash', 'push', '--include-untracked', '-m', message])
721  const sha = findStash(await gitOut($, root, STASH_LIST_ARGV.slice(1)), message)
722  return sha ? { sha, message } : undefined
723}
724
725// ── Steps ─────────────────────────────────────────────────────────────────
726
727type Blocked = Extract<RunEvent, { type: 'block' }>
728const block = (reason: string, next: string): Blocked => ({ type: 'block', reason, next })
729
730async function authCheck($: EngineInterface, run: Run): Promise<Blocked | null> {
731  const auth = await $.process.run(['gh', 'auth', 'status'], { cwd: run.root, timeoutMs: GIT_TIMEOUT }).catch(() => null)
732  return !auth || auth.exitCode !== 0 ? block('gh is not signed in', 'run gh auth login') : null
733}
734
735/** `gh issue view` of an issue, in `repo` when one is named, else in the repository gh resolves. */
736const issueViewArgv = (issue: number, repo: string | null | undefined): string[] => ['gh', 'issue', 'view', String(issue), ...(repo ? ['--repo', repo] : []), '--json', 'number,title,body,state,url']
737
738/** The issue as gh reads it from `repo` (the run's pinned repository, or gh's own choice for a run stored before #25). */
739async function issueCheck($: EngineInterface, run: Run, repo: string | null): Promise<Blocked | { title: string; body: string; url: string }> {
740  const view = await $.process.run(issueViewArgv(run.issue, repo), { cwd: run.root, timeoutMs: GIT_TIMEOUT })
741  if (view.exitCode !== 0) return block(`issue #${run.issue} not found: ${firstLine(view.stderr)}`, 'check the issue number or URL')
742  const issue = JSON.parse(view.stdout) as { title: string; body: string; state: string; url: string }
743  // gh issue view answers for a pull request's number too.
744  // Final: a pull request's number never becomes an issue's, so resume can't clear it (Change 0.7.0).
745  if (isPullUrl(issue.url)) return { ...block(`#${run.issue} is a pull request, not an issue`, 'pick another issue'), isFinal: true }
746  if (issue.state !== 'OPEN') return block(`issue #${run.issue} is ${issue.state.toLowerCase()}`, 'reopen it or pick another issue')
747  return { title: issue.title, body: issue.body ?? '', url: issue.url }
748}
749
750/** The GitHub repository gh resolves in `root` (`host/owner/repo`), or why it can't say. */
751async function ghRepoOf($: EngineInterface, root: string): Promise<Blocked | { repo: string }> {
752  const view = await $.process.run(['gh', 'repo', 'view', '--json', 'nameWithOwner,url'], { cwd: root, timeoutMs: GIT_TIMEOUT }).catch(() => null)
753  if (!view || view.exitCode !== 0) return block(`could not tell which GitHub repository this checkout belongs to: ${firstLine(view?.stderr ?? 'gh repo view did not finish')}`, 'give the checkout a GitHub remote named origin')
754  const repo = repoOfView(view.stdout)
755  return repo ? { repo } : block("could not read gh repo view's output", 'check gh')
756}
757
758/**
759 * Whether a remote URL names `repo`. The URL itself is parsed here and never passed on: it can hold a token. A renamed or
760 * transferred repository differs from the URL, so gh is asked for the name it gives `host/owner/repo`.
761 */
762async function remoteRepo($: EngineInterface, root: string, url: string, repo: string, views: Views = new Map()): Promise<RemoteFound> {
763  return foundOf($, root, remoteVerdict(url, repo), repo, views)
764}
765
766/**
767 * `remoteRepo` for a fork clone's remotes (the fork, the base remote): an ssh host other than `repo`'s is resolved with
768 * `ssh -G`, never taken for a nickname (PR #87 review, the owner's choice).
769 */
770async function forkRemoteRepo($: EngineInterface, root: string, url: string, repo: string, views: Views = new Map()): Promise<RemoteFound> {
771  const host = sshHostToResolve(url, repo)
772  return foundOf($, root, forkRemoteVerdict(url, repo, host === null ? undefined : await sshHostOf($, root, host)), repo, views)
773}
774
775/** `ssh -G <host>`: the host ssh reaches for it, ~/.ssh/config applied, without connecting; null when ssh can't say. */
776async function sshHostOf($: EngineInterface, root: string, host: string): Promise<string | null> {
777  const shown = await $.process.run(['ssh', '-G', host], { cwd: root, timeoutMs: GIT_TIMEOUT }).catch(() => null)
778  return shown?.exitCode === 0 ? sshHostname(shown.stdout) : null
779}
780
781/** A verdict settled: another repository on `repo`'s host is asked about, since gh may call it `repo` renamed. */
782async function foundOf($: EngineInterface, root: string, verdict: RemoteVerdict, repo: string, views: Views): Promise<RemoteFound> {
783  if (verdict.kind === 'match') return 'match'
784  if (verdict.kind === 'unrecognised') return { other: null }
785  if (verdict.kind === 'other') return { other: verdict.repo }
786  const canonical = await canonicalOf($, root, verdict.repo, views)
787  return isSameRepo(canonical, repo) ? 'match' : { other: canonical ?? verdict.repo }
788}
789
790/** gh's names for `host/owner/repo`s, asked once each within one check (PR #87 review). */
791type Views = Map<string, Promise<string | null>>
792
793/** The name gh gives `host/owner/repo` (a renamed or transferred repository's new one), or null when gh can't say. */
794function canonicalOf($: EngineInterface, root: string, repo: string, views: Views): Promise<string | null> {
795  const known = views.get(repo)
796  if (known) return known
797  const asked = $.process
798    .run(['gh', 'repo', 'view', repo, '--json', 'nameWithOwner,url'], { cwd: root, timeoutMs: GIT_TIMEOUT })
799    .then(view => (view.exitCode === 0 ? repoOfView(view.stdout) : null))
800    .catch(() => null)
801  views.set(repo, asked)
802  return asked
803}
804
805/** The distinct, non-empty lines of a command's output, in order. */
806function linesOf(stdout: string): string[] {
807  return [...new Set(stdout.split('\n').map(line => line.trim()).filter(line => line !== ''))]
808}
809
810/** `git remote get-url --push --all origin`: every URL git pushes origin to, one line each, and git's exit code. */
811async function pushUrlsOf($: EngineInterface, root: string): Promise<{ exitCode: number; urls: string[] }> {
812  const pushed = await git($, root, ['remote', 'get-url', '--push', '--all', 'origin'])
813  return { exitCode: pushed.exitCode, urls: linesOf(pushed.stdout) }
814}
815
816/** Origin's fetch URL and every URL git pushes it to, or null without an origin. Kept in memory only: a URL can hold a token. */
817type OriginUrls = { fetch: string; pushes: string[] }
818
819async function originUrls($: EngineInterface, root: string): Promise<OriginUrls | null> {
820  const fetched = await git($, root, ['remote', 'get-url', 'origin'])
821  const pushed = await pushUrlsOf($, root)
822  return fetched.exitCode !== 0 || pushed.exitCode !== 0 ? null : { fetch: fetched.stdout.trim(), pushes: pushed.urls }
823}
824
825/**
826 * Origin fetches from and pushes to `repo`, the repository gh sends the issue and the pull request to. git pushes to every push
827 * URL, so each is checked (PR #68 review), and one that is the fetch URL only once. Preflight passes the URLs it read.
828 */
829async function originCheck($: EngineInterface, root: string, repo: string, read?: OriginUrls | null, views: Views = new Map()): Promise<Blocked | null> {
830  const urls = read === undefined ? await originUrls($, root) : read
831  if (!urls) return block('this checkout has no remote named origin', `add a remote named origin for ${repoLabel(repo)}`)
832  const fetchUrl = urls.fetch
833  const pushUrls = urls.pushes.filter(u => u !== fetchUrl)
834  for (const [url, isPush] of [[fetchUrl, false] as const, ...pushUrls.map(u => [u, true] as const)]) {
835    const found = await remoteRepo($, root, url, repo, views)
836    if (found === 'match') continue
837    const label = found.other === null ? 'an unrecognised URL' : repoLabel(found.other)
838    const next = found.other === null ? `give origin an https, http or ssh URL for ${repoLabel(repo)}` : `work from a clone whose origin is ${repoLabel(repo)}, or whose origin is your fork of ${repoLabel(repo)} with another remote for ${repoLabel(repo)}`
839    return block(`origin ${isPush ? 'pushes to' : 'fetches from'} ${label}, but gh sends issues and pull requests to ${repoLabel(repo)}`, next)
840  }
841  return null
842}
843
844/** A fork clone's remotes (#26): the one the base is fetched from, and the fork origin pushes to (`host/owner/repo`). */
845type Fork = { baseRemote: string; headRepo: string }
846
847/** The fork origin pushes to, from the URLs preflight read: each is resolved once, all at once (PR #87 review). */
848async function forkOf($: EngineInterface, root: string, repo: string, urls: OriginUrls | null, views: Views): Promise<string | null> {
849  if (!urls) return null
850  const unique = [...new Set([urls.fetch, ...urls.pushes])]
851  const found = new Map((await Promise.all(unique.map(url => forkRemoteRepo($, root, url, repo, views)))).map((f, i) => [unique[i], f]))
852  const of = (url: string) => found.get(url) ?? { other: null }
853  return forkOfOrigin(of(urls.fetch), urls.pushes.map(of), repo)
854}
855
856/** Whether remote `name`'s fetch URL names `repo`. */
857async function remoteNames($: EngineInterface, root: string, name: string, repo: string, views: Views): Promise<boolean> {
858  const url = await git($, root, ['remote', 'get-url', name])
859  return url.exitCode === 0 && (await forkRemoteRepo($, root, url.stdout.trim(), repo, views)) === 'match'
860}
861
862/** The remotes besides origin whose fetch URL names `repo`, looked up together: a fork clone fetches the base from the one there is. */
863async function baseRemoteFor($: EngineInterface, root: string, repo: string, views: Views): Promise<BaseRemote> {
864  const names = linesOf((await git($, root, ['remote'])).stdout).filter(n => n !== 'origin')
865  const named = await Promise.all(names.map(name => remoteNames($, root, name, repo, views)))
866  return baseRemoteOf(names.filter((_, i) => named[i]))
867}
868
869/**
870 * A clone whose origin isn't `repo` may be a fork clone (#26): origin pushes to a fork of `repo` and another remote is `repo`. The
871 * fork must be a user's, not an organization's, which `gh pr create --head` can't name. This runs before anything is fetched. Any
872 * other clone gets `stray`, the origin block.
873 */
874async function forkCheck($: EngineInterface, root: string, repo: string, stray: Blocked, urls: OriginUrls | null, views: Views): Promise<Blocked | Fork> {
875  const headRepo = await forkOf($, root, repo, urls, views)
876  if (!headRepo) return stray
877  const base = await baseRemoteFor($, root, repo, views)
878  if (base.kind === 'none') return stray
879  if (base.kind === 'several') return block(`remotes ${base.remotes.slice(0, -1).join(', ')} and ${base.remotes.slice(-1).join('')} both point at ${repoLabel(repo)}`, 'remove one of them')
880  const view = await $.process.run(['gh', 'repo', 'view', headRepo, '--json', 'isFork,parent'], { cwd: root, timeoutMs: GIT_TIMEOUT }).catch(() => null)
881  if (!view || view.exitCode !== 0) return block(`could not read ${repoLabel(headRepo)} from gh: ${firstLine(view?.stderr ?? 'gh repo view did not finish')}`, 'check gh and your access to the fork')
882  if (!isForkOf(view.stdout, repo)) return block(`origin ${repoLabel(headRepo)} isn't a fork of ${repoLabel(repo)}`, `point origin at your fork of ${repoLabel(repo)}`)
883  const owner = ownerOf(headRepo)
884  // gh api asks github.com unless told the host (Codex on PR #87).
885  const type = await $.process.run(['gh', 'api', '--hostname', hostOf(headRepo), `users/${owner}`, '--jq', '.type'], { cwd: root, timeoutMs: GIT_TIMEOUT }).catch(() => null)
886  if (!type || type.exitCode !== 0) return block(`could not tell whether ${owner} is a user or an organization: ${firstLine(type?.stderr ?? 'gh api did not finish')}`, 'check gh')
887  if (type.stdout.trim() === 'Organization') return block("gh pr create can't name an organization's fork as the head (cli/cli#10093)", `point origin at a fork in a personal account, not ${owner}'s`)
888  return { baseRemote: base.remote, headRepo }
889}
890
891/** A fork run's origin still pushes only to the fork it was preflighted for: git pushes to every push URL (#26). */
892async function forkPushCheck($: EngineInterface, root: string, headRepo: string): Promise<Blocked | null> {
893  const pushed = await pushUrlsOf($, root)
894  const moved = block(`origin no longer pushes to ${repoLabel(headRepo)}`, 'point origin back at it, or start a new run')
895  if (pushed.exitCode !== 0 || pushed.urls.length === 0) return moved
896  for (const url of pushed.urls) if ((await forkRemoteRepo($, root, url, headRepo)) !== 'match') return moved
897  return null
898}
899
900/** Origin still pushes where the run's branch goes: the fork it was preflighted for (#26), else `repo` itself (#25). */
901async function pushCheck($: EngineInterface, root: string, repo: string | undefined, headRepo: string | undefined): Promise<Blocked | null> {
902  if (headRepo) return forkPushCheck($, root, headRepo)
903  return repo ? originCheck($, root, repo) : null
904}
905
906/** Reads and validates the profile, the outside checks included (§4.2). */
907async function loadProfile($: EngineInterface, root: string): Promise<{ profile: Profile | null; errors: string[] }> {
908  const path = `${root}/${PROFILE_FILE}`
909  if (!(await $.fs.exists(path))) return { profile: null, errors: [] }
910  const parsed = parseProfile(await $.fs.read(path), home)
911  if (!parsed.profile) return { profile: null, errors: parsed.errors }
912  const p = parsed.profile
913  const outside = outsideChecks(p, root)
914  const isLcovIgnored = outside.lcovInside === null ? null : (await git($, root, ['check-ignore', '-q', '--', outside.lcovInside])).exitCode === 0
915  const missing: string[] = []
916  for (const c of outside.commands) {
917    const found =
918      c.kind === 'path'
919        ? await $.fs.exists(isAbsolutePath(c.argv0) ? c.argv0 : `${root}/${c.argv0}`)
920        : (await $.process.run(['sh', '-c', 'command -v "$1"', '_', c.argv0], { cwd: root, timeoutMs: GIT_TIMEOUT })).exitCode === 0
921    if (!found) missing.push(c.argv0)
922  }
923  const problems = profileProblems(p, { isLcovIgnored, missing })
924  return problems.length > 0 ? { profile: null, errors: problems } : { profile: p, errors: [] }
925}
926
927/**
928 * A fork run's base remote still fetches from `repo`, as the folder that fetches reads it: the run stores only its name, and a
929 * resume, a kept worktree's own config or the publish merge check would fetch whatever it points at now (Codex on PR #87).
930 * Origin is checked by `originCheck` and `pushCheck`.
931 */
932async function baseRemoteCheck($: EngineInterface, cwd: string, remote: string, repo: string | undefined): Promise<Blocked | null> {
933  if (remote === 'origin' || !repo) return null
934  const url = await git($, cwd, ['remote', 'get-url', remote])
935  if (url.exitCode === 0 && (await forkRemoteRepo($, cwd, url.stdout.trim(), repo)) === 'match') return null
936  return block(`${remote} no longer fetches from ${repoLabel(repo)}`, `point ${remote} back at ${repoLabel(repo)}, or start a new run`)
937}
938
939/** `git fetch <remote> <base>` once the remote is still `repo`'s, or the block naming why it can't be or failed. */
940async function fetchBase($: EngineInterface, cwd: string, remote: string, base: string, repo?: string): Promise<Blocked | null> {
941  const moved = await baseRemoteCheck($, cwd, remote, repo)
942  if (moved) return moved
943  await setActivity($, `git fetch ${remote} ${base}`)
944  const fetched = await gitRetry($, cwd, ['fetch', remote, base])
945  return fetched.exitCode === 0 ? null : block(`git fetch ${remote} ${base} failed: ${firstLine(fetched.stderr)}`, 'check the base branch and the network')
946}
947
948/** A branch with no commits of its own fast-forwards to <remote>/<base>, so a fix pushed there reaches it. */
949async function catchUp($: EngineInterface, run: Run, cwd: string, remote: string, base: string): Promise<Blocked | null> {
950  const hasNoOwnCommits = (await git($, cwd, ['merge-base', '--is-ancestor', 'HEAD', `${remote}/${base}`])).exitCode === 0
951  if (!hasNoOwnCommits) return null
952  stillDriving(run)
953  await setActivity($, `catching up with ${remote}/${base}`)
954  const ff = await gitWrite($, run, cwd, ['merge', '--ff-only', '-q', `${remote}/${base}`])
955  return ff.exitCode === 0 ? null : block(`could not fast-forward to ${remote}/${base}: ${firstLine(ff.stderr)}`, 'check the branch')
956}
957
958type Where = { kind: 'here' } | { kind: 'worktree'; worktreeDir: string; minutes: number }
959
960/** Whether the session's checkout has changes or isn't on the base: one `git status` and one `rev-parse`. */
961async function checkoutOf($: EngineInterface, root: string, base: string, heldBy?: number): Promise<CheckoutState> {
962  await setActivity($, 'checking the checkout')
963  const porcelain = await gitOut($, root, ['status', '--porcelain'])
964  const head = (await gitOut($, root, ['rev-parse', '--abbrev-ref', 'HEAD'])).trim()
965  return checkoutState({ porcelain, head, base, ...(heldBy === undefined ? {} : { heldBy }) })
966}
967
968/**
969 * Here or in a new worktree (Change 0.2.0). The base's profile decides, read from <remote>/<base> before
970 * anything is made or switched; a busy checkout is never branched in place.
971 */
972async function whereToWork($: EngineInterface, run: Run, root: string, remote: string, base: string): Promise<Blocked | Where> {
973  const issue = run.issue
974  await setActivity($, `reading ${PROFILE_FILE} from ${remote}/${base}`)
975  const shown = await git($, root, ['show', `${remote}/${base}:${PROFILE_FILE}`])
976  const atBase = shown.exitCode === 0 ? parseProfile(shown.stdout, home) : { profile: undefined, errors: [firstLine(shown.stderr) || 'missing'] }
977  if (!atBase.profile) return block(`${remote}/${base} has no valid ${PROFILE_FILE}: ${atBase.errors[0] ?? 'missing'}`, `commit ${PROFILE_FILE} to ${base}`)
978  const { workspace, worktreeDir, commandTimeoutMinutes } = atBase.profile
979  // `worktree` makes one whatever the checkout holds, so it isn't looked at (a status is slow on a big tree or a Windows mount).
980  // Another active run working in this checkout makes it busy (Change 0.3.0).
981  const holder = workspace === 'worktree' ? undefined : (await runsOf($, run.repo ?? root)).find(r => r.id !== run.id && isActive(r) && normalizePath(workOf(r)) === normalizePath(root))
982  const state = workspace === 'worktree' ? { isBusy: false, why: '' } : await checkoutOf($, root, base, holder?.issue)
983  // Start in the menu under `ask` was the answer to the worktree question: it isn't asked twice.
984  const plan = workspacePlan(run.chosenWorktree && workspace === 'ask' ? 'worktree' : workspace, state, base, `${remote}/${base}`)
985  if (plan.kind === 'block') return block(plan.reason, plan.next)
986  if (plan.kind === 'here') return { kind: 'here' }
987  // Everything a worktree needs is checked before anyone is asked for one.
988  const routed = routedRedBlock(options.redAgentType, true)
989  if (routed) return block(routed.reason, routed.next)
990  if ((await git($, root, ['check-ignore', '-q', '--', `${worktreeDir}/`])).exitCode !== 0) return block(`${worktreeDir} isn't gitignored`, `add ${worktreeDir}/ to .gitignore`)
991  if (plan.kind === 'ask' && !(await chooseWorktree($, issue, root, state.why, worktreeDir))) {
992    return block(`${root} is busy (${state.why}) and no new worktree was chosen`, `answer New worktree in an interactive session, set "workspace" to "worktree" in ${PROFILE_FILE} on ${base}, or clean the checkout`)
993  }
994  return { kind: 'worktree', worktreeDir, minutes: commandTimeoutMinutes }
995}
996
997/**
998 * Step 2: the base, where the run works, and the run's branch, cut here or in a new worktree from `remote`'s base. `repo` is
999 * the pinned repository: the base question can wait on the person, so the base remote is read again before the fetch.
1000 */
1001async function makeBranch($: EngineInterface, run: Run, issueBody: string, remote: string, repo: string, headRepo?: string): Promise<Blocked | Kept> {
1002  const root = run.root
1003  // This checkout's profile only names the base; the profile that is checked and runs is <remote>/<base>'s.
1004  await setActivity($, `reading ${PROFILE_FILE}`)
1005  const profileBase = checkoutBaseOf(await readLocalProfile($, root))
1006  const asked = baseOf({ baseBranch: profileBase }, issueBody)
1007  const base = asked === profileBase ? asked : await chooseBase($, run.issue, asked, profileBase)
1008  if (!base) return block(`issue #${run.issue} asks for base ${asked}, not ${profileBase}, and nobody confirmed it`, "answer the question in an interactive session, or remove the issue's Base branch line")
1009  stillDriving(run)
1010  const unfetched = await fetchBase($, root, remote, base, repo)
1011  if (unfetched) return unfetched
1012  const where = await whereToWork($, run, root, remote, base)
1013  if ('type' in where) return where
1014  const local = splitZ((await gitOut($, root, ['for-each-ref', '--format=%(refname:short)%00', `refs/heads/issue-${run.issue}-*`, `refs/heads/issue-${run.issue}`])).replace(/\n/g, ''))
1015  // A fork clone's branch name must be free on the fork it is pushed to and on the project it is cut from (#26).
1016  const remoteHeads: string[] = []
1017  for (const name of new Set(['origin', remote])) {
1018    const listed = await gitOut($, root, ['ls-remote', '--heads', name, `issue-${run.issue}*`])
1019    remoteHeads.push(...listed.split('\n').map(line => line.split('refs/heads/')[1] ?? '').filter(Boolean))
1020  }
1021  const branch = branchName(run.issue, run.title, [...local, ...remoteHeads])
1022  // A fork clone's branch is kept with the fork its name was checked on, so a resume can't take it elsewhere (Codex on PR #87).
1023  const forked = headRepo ? { baseRemote: remote, headRepo } : {}
1024  stillDriving(run)
1025  if (where.kind === 'here') {
1026    await setActivity($, `git switch -c ${branch}`)
1027    const switched = await gitWrite($, run, root, ['switch', '--no-track', '-c', branch, `${remote}/${base}`])
1028    if (switched.exitCode !== 0) return block(`git switch failed: ${firstLine(switched.stderr)}`, 'check the repository state')
1029    const here = { branch, workRoot: root, base, ...forked }
1030    await recordMade($, run, here)
1031    return here
1032  }
1033  const workRoot = worktreePath(root, where.worktreeDir, branch)
1034  if (await $.fs.exists(workRoot)) return block(`${workRoot} already exists`, 'remove it, or set another worktreeDir')
1035  await setActivity($, `git worktree add ${where.worktreeDir}/${branch}`)
1036  // A full checkout can outlast git's 60 s on a slow disk: it runs like the profile's commands, on their timeout.
1037  const made = { branch, workRoot, base, ...forked }
1038  let added: CommandResult
1039  try {
1040    added = await runLong($, ['git', 'worktree', 'add', '--no-track', '-b', branch, workRoot, `${remote}/${base}`], root, where.minutes, GIT_ENV)
1041  } catch (err) {
1042    // A Stop during the add: the branch git already made is kept on the stopped run, like one made before it.
1043    if (err instanceof Stopped && (await hasBranch($, root, branch))) await recordMade($, run, made)
1044    throw err
1045  }
1046  if (added.exit !== 0) {
1047    const failed = block(worktreeAddFailure(added, where.minutes), `check ${workRoot} (git worktree remove --force removes a half-made one)`)
1048    // git creates the branch before it fills the folder: a branch left behind is kept, and resume adds the worktree for it.
1049    if (!(await hasBranch($, root, branch))) return failed
1050    await recordMade($, run, made)
1051    return { ...failed, keep: made }
1052  }
1053  await recordMade($, run, made)
1054  return made
1055}
1056
1057/**
1058 * What to do with a run's kept worktree, from git's own list: `fs.exists` can be wrong, and git run in a
1059 * folder at that path that isn't the worktree works on the checkout above it (round 6).
1060 */
1061async function keptWorktree($: EngineInterface, root: string, workRoot: string): Promise<KeptWorktreePlan | Blocked> {
1062  const listed = await git($, root, ['worktree', 'list', '--porcelain'])
1063  if (listed.exitCode !== 0) return block(`git worktree list failed: ${firstLine(listed.stderr || listed.stdout) || `exit ${listed.exitCode}`}`, 'check git in this checkout')
1064  return keptWorktreePlan(worktreeStateOf(listed.stdout, workRoot), await $.fs.exists(workRoot))
1065}
1066
1067const strayFolder = (workRoot: string): Blocked => block(`${workRoot} is there but isn't the run's git worktree`, `move ${workRoot} aside`)
1068
1069/**
1070 * Steps 1 and 2. A preflight that blocked after making its branch recorded it with the block, so a
1071 * resume reuses that branch and folder instead of making another (Codex, PR #41).
1072 */
1073async function preflight($: EngineInterface, run: Run): Promise<RunEvent> {
1074  await setActivity($, 'checking gh and the issue')
1075  const unauthed = await authCheck($, run)
1076  if (unauthed) return unauthed
1077  // Every gh call of the run names this repository, and origin must be it (#25).
1078  const resolved = run.ghRepo ? { repo: run.ghRepo } : await ghRepoOf($, run.root)
1079  if ('type' in resolved) return resolved
1080  const { repo } = resolved
1081  // Origin is the project, or (#26) the contributor's fork with the project as another remote.
1082  // Origin's URLs are read once and each repository named is asked about once (PR #87 review).
1083  const urls = await originUrls($, run.root)
1084  const views: Views = new Map()
1085  const stray = await originCheck($, run.root, repo, urls, views)
1086  const fork = stray ? await forkCheck($, run.root, repo, stray, urls, views) : null
1087  if (fork && 'type' in fork) return fork
1088  const remote = fork?.baseRemote ?? 'origin'
1089  // Pinned once origin agrees (or is a fork of it), so a later block keeps it; an origin block leaves it open to a fix of the remotes.
1090  if (!run.ghRepo) await recordPinned($, run, repo)
1091  const issue = await issueCheck($, run, repo)
1092  if ('type' in issue) return issue
1093  let made: Kept
1094  if (run.branch) {
1095    made = { branch: run.branch, workRoot: workOf(run), base: run.base }
1096    const moved = keptForkBlock(run.headRepo, fork?.headRepo, repo)
1097    if (moved) return { ...block(moved.reason, moved.next), keep: made }
1098    // A kept worktree that is gone (removed by hand, or never filled) is made again for the kept branch.
1099    const kept = isWorktreeRun(run) ? await keptWorktree($, run.root, made.workRoot) : 'reuse'
1100    if (typeof kept !== 'string') return { ...kept, keep: made }
1101    if (kept === 'block') return { ...strayFolder(made.workRoot), keep: made }
1102    if (kept === 'add') {
1103      stillDriving(run)
1104      // git refuses to add a folder deleted by hand while it is still registered: only this path's entry is cleared (no
1105      // prune of others'). A folder git never registered just fails the remove.
1106      await git($, run.root, ['worktree', 'remove', made.workRoot])
1107      await setActivity($, `git worktree add ${made.workRoot}`)
1108      const minutes = run.profile?.commandTimeoutMinutes ?? DEFAULT_COMMAND_MINUTES
1109      const again = await runLong($, ['git', 'worktree', 'add', made.workRoot, made.branch], run.root, minutes, GIT_ENV)
1110      if (again.exit !== 0) return { ...block(worktreeAddFailure(again, minutes), `check ${made.workRoot}`), keep: made }
1111    }
1112    // A kept worktree's own config can give origin other URLs (extensions.worktreeConfig): it is checked where it fetches.
1113    const strayThere = made.workRoot === run.root ? null : await pushCheck($, made.workRoot, repo, fork?.headRepo)
1114    if (strayThere) return { ...strayThere, keep: made }
1115    const unfetched = await fetchBase($, made.workRoot, remote, made.base, repo)
1116    if (unfetched) return { ...unfetched, keep: made }
1117    // A fix pushed to the base (the profile, a missing command) reaches the kept branch before it is checked again.
1118    const behind = await catchUp($, run, made.workRoot, remote, made.base)
1119    if (behind) return { ...behind, keep: made }
1120  } else {
1121    const fresh = await makeBranch($, { ...run, title: issue.title }, issue.body, remote, repo, fork?.headRepo)
1122    if ('type' in fresh) return fresh
1123    made = fresh
1124  }
1125  try {
1126    const mergeBase = (await gitOut($, made.workRoot, ['merge-base', 'HEAD', `${remote}/${made.base}`])).trim()
1127    // The profile whose commands run is the base's, not the checkout the run started from (which anyone may have pushed).
1128    await setActivity($, `reading ${PROFILE_FILE} from ${remote}/${made.base}`)
1129    const trusted = await loadProfile($, made.workRoot)
1130    if (!trusted.profile) return { ...block(`${remote}/${made.base} has no valid ${PROFILE_FILE}: ${trusted.errors[0] ?? 'missing'}`, `commit ${PROFILE_FILE} to ${made.base}`), keep: made }
1131    return { type: 'preflighted', title: issue.title, body: issue.body, url: issue.url, base: made.base, branch: made.branch, mergeBase, profile: trusted.profile, workRoot: made.workRoot, repo, ...fork }
1132  } catch (err) {
1133    if (err instanceof Stopped) throw err
1134    return { ...block(`unexpected: ${err instanceof Error ? err.message : String(err)}`, 'see /issue-forge status'), keep: made }
1135  }
1136}
1137
1138/**
1139 * Before each step that runs coverage (baseline, gates G and F), on a fresh start or a resume: one LCOV file can't
1140 * serve two runs at once (Change 0.3.0; Codex 4278707573).
1141 */
1142async function lcovShared($: EngineInterface, run: Run, p: Profile): Promise<Blocked | null> {
1143  const shared = sharedLcovBlock(p, (await runsOf($, run.repo ?? run.root)).filter(r => r.id !== run.id))
1144  return shared ? block(shared.reason, shared.next) : null
1145}
1146
1147/**
1148 * Step 3. A branch with no commits of its own first catches up with the base (so "fix main, then resume"
1149 * works), and the merge base is computed afresh every time, so a blocked baseline never leaves a stale one.
1150 */
1151async function baseline($: EngineInterface, run: Run, p: Profile): Promise<RunEvent> {
1152  const shared = await lcovShared($, run, p)
1153  if (shared) return shared
1154  const root = workOf(run)
1155  const remote = baseRemoteOfRun(run)
1156  const unfetched = await fetchBase($, root, remote, run.base, run.ghRepo)
1157  if (unfetched) return unfetched
1158  const behind = await catchUp($, run, root, remote, run.base)
1159  if (behind) return behind
1160  const mergeBase = (await gitOut($, root, ['merge-base', 'HEAD', baseRefOf(run)])).trim()
1161  await setActivity($, 'running tests')
1162  const tests = await runLong($, p.testCommand, root, p.commandTimeoutMinutes)
1163  if (tests.exit !== 0) return block(tests.isTimedOut ? 'tests time out before any change' : 'tests fail before any change', `fix ${run.base}`)
1164  await setActivity($, 'running coverage')
1165  const since = await $.clock.now()
1166  const cov = await runLong($, p.coverageCommand, root, p.commandTimeoutMinutes)
1167  const text = cov.exit === 0 ? await readLcov($, lcovFileOf(p, root), since) : null
1168  const lcov = text === null ? null : parseLcov(text, root)
1169  if (!lcov || !hasSourceRecord(p, lcov)) return block('coverage produced no data', `check coverageCommand and lcovPath in ${PROFILE_FILE}`)
1170  return { type: 'baselined', baseline: totals(p, lcov), mergeBase }
1171}
1172
1173function waitForAnswer(agentId: string): Promise<AgentTurn> {
1174  return new Promise((resolve, reject) => {
1175    waiting[agentId] = { resolve, reject }
1176  })
1177}
1178
1179/** A phase: spawn its agent (named, so a routing plugin leaves it on Claude) and wait for its turn.complete. */
1180async function phase($: EngineInterface, run: Run, which: Phase, p: Profile): Promise<RunEvent | null> {
1181  const redTestPaths = which === 'green' && run.redCommit ? splitZ(await gitOut($, workOf(run), ['diff', '--name-only', '-z', run.mergeBase, run.redCommit])) : undefined
1182  const prompt = phasePrompt(which, run, promptExtraOf(which, run, redTestPaths))
1183  const subagentType = which === 'red' ? options.redAgentType : `issue-forge:${which}`
1184  const isOwn = subagentType.startsWith('issue-forge:')
1185  const routed = routedRedBlock(subagentType, isWorktreeRun(run))
1186  if (routed) return block(routed.reason, routed.next)
1187  const name = isOwn ? agentName(run, which) : undefined
1188  // Known before the spawn returns, so an agent that stops sooner still has its hand-back taken.
1189  if (name) knownRefs.add(name)
1190  const model = which === 'red' ? options.redModel : which === 'green' ? options.greenModel : options.refactorModel
1191  await setActivity($, `starting the ${which} agent`)
1192  const baseManifests = [...(await manifestsAt($, workOf(run), run.mergeBase)), ...(await manifestsAt($, workOf(run), baseRefOf(run)))]
1193  const spawned = await $.agent.spawn({ subagentType, prompt, description: `issue-forge #${run.issue} ${which}`, model, cwd: workOf(run), ...(name ? { name } : {}) })
1194  const agentId = spawned.agentId
1195  // An agent another plugin answered in-line (a Codex router, say) has no loop and no turn.complete (C0).
1196  const isInline = !!agentId && isInlineAnswer(agentId, spawned.model)
1197  // Wait before any other await, so a fast agent's turn.complete finds its waiter.
1198  const answer = agentId && !isInline ? waitForAnswer(agentId) : null
1199  void answer?.catch(() => undefined)
1200  // Steer the agent from its first tool call: set before any other await, like the waiter.
hooks/issue-forge-logic.ts 2660 lines
1/**
2 * Issue Forge's rules, free of `$` so tests can call them (SPEC "How it works").
3 * Sections: profile, globs and paths, coverage, gates, state, prompts, view, demo.
4 * Section numbers like §4 refer to docs/specs/issue-forge.md.
5 */
6
7import type { Activity, AgentRef, Baseline, Check, Coverage, Driver, Gate, MergeCheck, NewPlugin, OtherRun, Pct, Phase, Profile, Run, StashRef, Step, Workspace } from '../types'
8
9export type { Activity, AgentRef, Baseline, Check, Coverage, Driver, Gate, MergeCheck, NewPlugin, OtherRun, Pct, Phase, Profile, Run, StashRef, Step, Workspace }
10
11export const NAME = 'issue-forge'
12export const PROFILE_FILE = '.issue-forge.json'
13export const PHASES: Phase[] = ['red', 'green', 'refactor']
14
15// ── Profile (§4) ──────────────────────────────────────────────────────────
16
17const DEFAULTS = {
18  baseBranch: 'main',
19  excludeGlobs: [] as string[],
20  unmeasuredGlobs: [] as string[],
21  behaviourTestGlobs: [] as string[],
22  checks: [] as string[][],
23  threshold: 95,
24  regressionTolerance: 0,
25  attempts: { red: 2, green: 3, refactor: 1 },
26  commandTimeoutMinutes: 15,
27  notes: '',
28  commitTrailers: [] as string[],
29  workspace: 'ask' as Workspace,
30  worktreeDir: 'scratch/issue-forge',
31}
32
33export const WORKSPACES: readonly Workspace[] = ['ask', 'worktree', 'here']
34/** The command timeout before a run has its profile (a preflight blocked before it was read). */
35export const DEFAULT_COMMAND_MINUTES = DEFAULTS.commandTimeoutMinutes
36
37/** `.git` as a case-insensitive filesystem and Windows read it: any case, trailing dots and spaces dropped. */
38const isGitDir = (segment: string): boolean => segment.toLowerCase().replace(/[. ]+$/, '') === '.git'
39
40/** A relative path with no `..` segment that names a folder inside the repository's working tree (`D:tmp` is on drive D; `.git` is git's own). */
41function isInsideDir(v: unknown): v is string {
42  if (typeof v !== 'string' || isAbsolutePath(v) || /^[\\/]/.test(v) || /^[A-Za-z]:/.test(v)) return false
43  const parts = normalizePath(v).split('/')
44  return parts[0] !== '' && !parts.includes('..') && !parts.some(isGitDir)
45}
46
47
48const isStrings = (v: unknown): v is string[] => Array.isArray(v) && v.every(x => typeof x === 'string')
49
50/**
51 * A branch name safe to hand git as an argument: letters, digits, `.`, `_`, `-`, `/`; not starting
52 * with `-` (an option) or `+` (a forced refspec), no `..`, `//` or `@{`, no trailing `/`, `.` or `.lock`.
53 */
54export function isSafeBranch(name: string): boolean {
55  return (
56    /^[A-Za-z0-9._/-]+$/.test(name) &&
57    !/^[-+./]/.test(name) &&
58    !/\.\.|\/\/|@\{/.test(name) &&
59    !/[/.]$/.test(name) &&
60    !name.endsWith('.lock')
61  )
62}
63
64/** The glob syntax the design promises (§4.1): `*`, `**`, `?`. Braces, brackets and `!` are refused, not matched literally. */
65const isGlobs = (v: unknown): v is string[] => isStrings(v) && v.every(g => g.trim() !== '' && !/[{}[\]!]/.test(g))
66const isArgv = (v: unknown): v is string[] => isStrings(v) && v.length > 0 && v[0] !== ''
67
68/** `~` or `~/x` from `home`; anything else unchanged. */
69export function expandHome(path: string, home: string): string {
70  if (path === '~') return home
71  if (path.startsWith('~/')) return `${home.replace(/\/+$/, '')}/${path.slice(2)}`
72  return path
73}
74
75/**
76 * Parses and type-checks `.issue-forge.json` (§4.1, §4.2's first two rules). The rules that need
77 * the outside world (lcovPath ignored, commands on PATH) are `outsideChecks` + `profileProblems`.
78 */
79export function parseProfile(text: string, home: string): { profile?: Profile; errors: string[] } {
80  let raw: unknown
81  try {
82    raw = JSON.parse(text)
83  } catch (err) {
84    return { errors: [`${PROFILE_FILE} is not valid JSON: ${(err as Error).message}`] }
85  }
86  if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return { errors: [`${PROFILE_FILE} must hold a JSON object`] }
87  const o = raw as Record<string, unknown>
88  const errors: string[] = []
89  const need = (key: string, ok: (v: unknown) => boolean, what: string) => {
90    if (o[key] === undefined) errors.push(`${key} is required (${what})`)
91    else if (!ok(o[key])) errors.push(`${key} must be ${what}`)
92  }
93  const may = (key: string, ok: (v: unknown) => boolean, what: string) => {
94    if (o[key] !== undefined && !ok(o[key])) errors.push(`${key} must be ${what}`)
95  }
96  const nonEmptyStrings = (v: unknown) => isStrings(v) && v.length > 0
97  need('testCommand', isArgv, 'a non-empty array of strings (argv)')
98  need('coverageCommand', isArgv, 'a non-empty array of strings (argv)')
99  may('formatCommand', isArgv, 'a non-empty array of strings (argv)')
100  need('lcovPath', v => typeof v === 'string' && v !== '', 'a non-empty string')
101  const nonEmptyGlobs = (v: unknown) => isGlobs(v) && v.length > 0
102  const GLOBS = 'non-empty globs using only * ** ? (no braces, brackets or !)'
103  need('sourceGlobs', nonEmptyGlobs, `a non-empty array of ${GLOBS}`)
104  need('testGlobs', nonEmptyGlobs, `a non-empty array of ${GLOBS}`)
105  may('baseBranch', v => typeof v === 'string' && isSafeBranch(v), 'a branch name (letters, digits, . _ - /; not starting with - or +)')
106  for (const key of ['excludeGlobs', 'unmeasuredGlobs', 'behaviourTestGlobs']) may(key, isGlobs, `an array of ${GLOBS}`)
107  may('commitTrailers', isStrings, 'an array of strings')
108  may('checks', v => Array.isArray(v) && v.every(isArgv), 'an array of argv arrays')
109  may('threshold', v => typeof v === 'number' && v >= 0 && v <= 100, 'a number from 0 to 100')
110  may('regressionTolerance', v => typeof v === 'number' && v >= 0, 'a number ≥ 0')
111  may('commandTimeoutMinutes', v => typeof v === 'number' && v > 0, 'a number > 0')
112  may('notes', v => typeof v === 'string', 'a string')
113  may('workspace', v => WORKSPACES.includes(v as Workspace), 'one of "ask", "worktree", "here"')
114  may('worktreeDir', isInsideDir, 'a relative path inside the repository (no .. segment)')
115  const isCount = (v: unknown) => v === undefined || (typeof v === 'number' && Number.isInteger(v) && v >= 1)
116  may(
117    'attempts',
118    v => v !== null && typeof v === 'object' && !Array.isArray(v) && ['red', 'green', 'refactor'].every(k => isCount((v as Record<string, unknown>)[k])),
119    'an object { red, green, refactor } of whole numbers ≥ 1',
120  )
121  const nonEmpty = (v: unknown) => Array.isArray(v) && v.length > 0
122  if (nonEmpty(o.unmeasuredGlobs) && !nonEmpty(o.behaviourTestGlobs)) errors.push('behaviourTestGlobs must name at least one glob when unmeasuredGlobs does (G6 could never pass)')
123  if (errors.length > 0) return { errors }
124  const attempts = (o.attempts ?? {}) as Partial<Profile['attempts']>
125  const profile: Profile = {
126    baseBranch: (o.baseBranch as string | undefined) ?? DEFAULTS.baseBranch,
127    testCommand: o.testCommand as string[],
128    coverageCommand: o.coverageCommand as string[],
129    ...(o.formatCommand === undefined ? {} : { formatCommand: o.formatCommand as string[] }),
130    lcovPath: expandHome(o.lcovPath as string, home),
131    sourceGlobs: o.sourceGlobs as string[],
132    testGlobs: o.testGlobs as string[],
133    excludeGlobs: (o.excludeGlobs as string[] | undefined) ?? DEFAULTS.excludeGlobs,
134    unmeasuredGlobs: (o.unmeasuredGlobs as string[] | undefined) ?? DEFAULTS.unmeasuredGlobs,
135    behaviourTestGlobs: (o.behaviourTestGlobs as string[] | undefined) ?? DEFAULTS.behaviourTestGlobs,
136    checks: (o.checks as string[][] | undefined) ?? DEFAULTS.checks,
137    threshold: (o.threshold as number | undefined) ?? DEFAULTS.threshold,
138    regressionTolerance: (o.regressionTolerance as number | undefined) ?? DEFAULTS.regressionTolerance,
139    attempts: {
140      red: attempts.red ?? DEFAULTS.attempts.red,
141      green: attempts.green ?? DEFAULTS.attempts.green,
142      refactor: attempts.refactor ?? DEFAULTS.attempts.refactor,
143    },
144    commandTimeoutMinutes: (o.commandTimeoutMinutes as number | undefined) ?? DEFAULTS.commandTimeoutMinutes,
145    notes: (o.notes as string | undefined) ?? DEFAULTS.notes,
146    commitTrailers: (o.commitTrailers as string[] | undefined) ?? DEFAULTS.commitTrailers,
147    workspace: (o.workspace as Workspace | undefined) ?? DEFAULTS.workspace,
148    worktreeDir: normalizePath((o.worktreeDir as string | undefined) ?? DEFAULTS.worktreeDir),
149  }
150  return { profile, errors: [] }
151}
152
153/** What the module must look up before the profile counts as valid (§4.2's last two rules). */
154export type OutsideChecks = {
155  /** The LCOV path relative to the root when it is inside: `git check-ignore -q` must pass. */
156  lcovInside: string | null
157  /** Commands named by a path (must exist, relative to the root) or a name (must be on PATH). */
158  commands: { argv0: string; kind: 'path' | 'name' }[]
159}
160
161export function outsideChecks(p: Profile, root: string): OutsideChecks {
162  const abs = isAbsolutePath(p.lcovPath) ? normalizePath(p.lcovPath) : normalizePath(`${root}/${p.lcovPath}`)
163  const format = p.formatCommand ? [p.formatCommand[0] as string] : []
164  const argv0s = [...new Set([p.testCommand[0] as string, p.coverageCommand[0] as string, ...format, ...p.checks.map(c => c[0] as string)])]
165  return {
166    lcovInside: relativeTo(root, abs),
167    commands: argv0s.map(argv0 => ({ argv0, kind: /[\\/]/.test(argv0) ? 'path' : 'name' })),
168  }
169}
170
171/** The §4.2 failures the outside checks found; empty when the profile holds. */
172export function profileProblems(p: Profile, facts: { isLcovIgnored: boolean | null; missing: string[] }): string[] {
173  const problems: string[] = []
174  if (facts.isLcovIgnored === false) problems.push(`lcovPath ${p.lcovPath} is inside the repository and not ignored by git; git add -A would commit it`)
175  for (const argv0 of facts.missing) problems.push(`command not found: ${argv0}`)
176  return problems
177}
178
179/**
180 * The base the starting checkout's profile names. That copy only picks the base: the run checks
181 * origin/<base>'s, so a stale, broken or missing one here reads as the default, and an unsafe name too.
182 */
183export function checkoutBaseOf(text: string | null): string {
184  try {
185    const o = text === null ? null : (JSON.parse(text) as unknown)
186    const named = o !== null && typeof o === 'object' && !Array.isArray(o) ? (o as Record<string, unknown>).baseBranch : undefined
187    return typeof named === 'string' && isSafeBranch(named) ? named : DEFAULTS.baseBranch
188  } catch {
189    return DEFAULTS.baseBranch
190  }
191}
192
193/**
194 * §2: the issue's first `Base branch: x` line, else the profile's. The name reaches git, and anyone who
195 * can file an issue writes it, so a name `isSafeBranch` refuses is ignored (the profile's base stands).
196 */
197export function baseOf(p: Pick<Profile, 'baseBranch'>, issueBody: string): string {
198  for (const line of issueBody.split(/\r?\n/)) {
199    const m = line.match(/^Base branch: (\S+)$/)
200    if (m?.[1]) return isSafeBranch(m[1]) ? m[1] : p.baseBranch
201  }
202  return p.baseBranch
203}
204
205// ── Globs and paths ───────────────────────────────────────────────────────
206
207/** `*` within a segment, `**` any depth (a leading `**\/` also matches none), `?` one character. */
208export function globToRegExp(glob: string): RegExp {
209  let out = ''
210  for (let i = 0; i < glob.length; i++) {
211    const c = glob.charAt(i)
212    if (c === '*' && glob.charAt(i + 1) === '*') {
213      const before = i === 0 || glob.charAt(i - 1) === '/'
214      const after = glob.charAt(i + 2)
215      if (before && after === '/') {
216        out += '(?:.*/)?'
217        i += 2
218      } else {
219        out += '.*'
220        i += 1
221      }
222    } else if (c === '*') out += '[^/]*'
223    else if (c === '?') out += '[^/]'
224    else out += c.replace(/[.+^${}()|[\]\\]/g, '\\$&')
225  }
226  return new RegExp(`^${out}$`)
227}
228
229export function matchesAny(path: string, globs: readonly string[]): boolean {
230  return globs.some(glob => globToRegExp(glob).test(path))
231}
232
233export type PathKind = 'test' | 'measured' | 'unmeasured' | 'other'
234
235/** §2: test files win; source is sourceGlobs minus testGlobs and excludeGlobs. */
236export function kindOf(p: Profile, path: string): PathKind {
237  if (matchesAny(path, p.testGlobs)) return 'test'
238  if (!matchesAny(path, p.sourceGlobs) || matchesAny(path, p.excludeGlobs)) return 'other'
239  return matchesAny(path, p.unmeasuredGlobs) ? 'unmeasured' : 'measured'
240}
241
242/** Where the coverage command writes LCOV: a relative `lcovPath` is relative to the repository root, as the command runs there. */
243export function lcovFileOf(p: Profile, root: string): string {
244  return isAbsolutePath(p.lcovPath) ? p.lcovPath : `${root.replace(/\/+$/, '')}/${p.lcovPath}`
245}
246
247/** `/x` or a Windows drive path (`C:\x`, `C:/x`). */
248export function isAbsolutePath(path: string): boolean {
249  return path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path)
250}
251
252/** `/`-separated, `.` and `..` resolved, no trailing `/`; a UNC root's two leading slashes are kept. */
253export function normalizePath(path: string): string {
254  const isAbsolute = isAbsolutePath(path)
255  const parts: string[] = []
256  for (const part of path.replace(/\\/g, '/').split('/')) {
257    if (part === '' || part === '.') continue
258    if (part === '..') {
259      if (parts.length > 0 && parts[parts.length - 1] !== '..') parts.pop()
260      else if (!isAbsolute) parts.push('..')
261    } else parts.push(part)
262  }
263  const joined = parts.join('/')
264  const lead = /^\/\/(?!\/)/.test(path) ? '//' : path.startsWith('/') ? '/' : ''
265  return `${lead}${joined}`
266}
267
268/** `abs` relative to `root`, or null when it is outside. */
269export function relativeTo(root: string, abs: string): string | null {
270  const r = normalizePath(root)
271  const a = normalizePath(abs)
272  if (a === r) return ''
273  const prefix = r.endsWith('/') ? r : `${r}/`
274  return a.startsWith(prefix) ? a.slice(prefix.length) : null
275}
276
277/**
278 * From `git status --porcelain -z`: paths whose working-tree bytes differ from the index (Y column) or
279 * that are untracked. After `git add -A` there should be none; any left were written by a command since.
280 */
281export function unstagedOf(porcelainZ: string): string[] {
282  const out: string[] = []
283  const entries = porcelainZ.split('\0')
284  for (let i = 0; i < entries.length; i++) {
285    const e = entries[i] as string
286    if (e.length < 4) continue
287    const [x, y, path] = [e.charAt(0), e.charAt(1), e.slice(3)]
288    if (x === 'R' || x === 'C') i++
289    if (y !== ' ') out.push(path)
290  }
291  return out
292}
293
294/**
295 * A gate commits only the tree it tested (#101, Change 0.7.5). `tested` is the index's tree when the gate staged, and `seen`
296 * the index's tree just before the commit or, with `commit`, the tree of the commit made. Null when they are the same tree.
297 * The reason shows short trees; the commands to run name the whole tested tree, which no repository finds ambiguous.
298 */
299export function treeDrift(gate: 'R' | 'G' | 'F', tested: string, seen: string, commit?: string): { reason: string; next: string } | null {
300  if (seen === tested) return null
301  const [t, s] = [tested.slice(0, 7), seen.slice(0, 7)]
302  // Resume stages everything again (git add -A), so a stray path has to leave the folder, not just the index (PR #136 review).
303  if (commit === undefined) return { reason: `the index changed after gate ${gate} tested it (tested ${t}, now ${s})`, next: `see what was staged since (git diff --cached --stat ${tested}) and take what isn't the run's out of the run's folder (resume stages everything again)` }
304  return {
305    reason: `commit ${commit.slice(0, 7)} holds a tree gate ${gate} didn't test (${s}, tested ${t}): a commit hook that rewrites files, or another process during the commit`,
306    next: `see what wasn't tested (git diff ${tested} HEAD); a commit hook's change needs nothing (resume tests the commit as it stands), anything else needs git reset HEAD~1 and taking it out of the run's folder`,
307  }
308}
309
310/**
311 * A commit object's tree and parents, as `git cat-file commit` prints it (PR #136 review round 2): header lines only, up to
312 * the blank line before the message. A signature's continuation lines start with a space, so they aren't fields.
313 */
314export function commitFields(text: string): { tree: string; parents: string[] } {
315  const end = text.indexOf('\n\n')
316  const header = end < 0 ? text : text.slice(0, end)
317  const fields = header.split('\n').filter(line => !line.startsWith(' '))
318  const valueOf = (name: string) => fields.filter(line => line.startsWith(`${name} `)).map(line => line.slice(name.length + 1).trim())
319  return { tree: valueOf('tree')[0] ?? '', parents: valueOf('parent') }
320}
321
322/**
323 * A `git commit` that failed after the gate passed (PR #136 review round 2): a commit hook is the likely cause. git's own
324 * refusal (`fatal:` or `error:`: an identity, a broken ref) isn't a hook's, so it stays the unexpected block it was.
325 */
326export function commitRefused(gate: 'R' | 'G' | 'F', message: string): { reason: string; next: string } {
327  if (/^git commit failed: (?:fatal|error):/.test(message)) return { reason: `unexpected: ${message}`, next: 'see /issue-forge status' }
328  return {
329    reason: `gate ${gate} passed, but ${message}`,
330    next: "see the commit hook's output (git commit in the run's folder): it may have refused the commit, or changed files and failed, as pre-commit does",
331  }
332}
333
334/** Another commit moved the branch during a gate's commit: HEAD's parent isn't the HEAD from before it (PR #136 review round 2). */
335export function branchMoved(gate: 'R' | 'G' | 'F', before: string, head: string, parent: string): { reason: string; next: string } {
336  return {
337    reason: `another commit moved the branch during gate ${gate}'s commit (HEAD ${head.slice(0, 7)}, whose parent is ${parent.slice(0, 7) || 'none'}, not ${before.slice(0, 7)})`,
338    next: `see what landed (git log -3) and put the branch back on gate ${gate}'s commit by hand`,
339  }
340}
341
342/**
343 * The commit a passing gate keeps when nothing was left to commit: HEAD, if it is new since the phase before (a replay after a
344 * reload, or a resume after an after-the-commit block, #101); else none.
345 */
346export function keptCommit(head: string, before: string | undefined): string | undefined {
347  return head === before ? undefined : head
348}
349
350/** NUL-separated `git … -z` output as paths. */
351export function splitZ(out: string): string[] {
352  return out.split('\0').filter(path => path !== '')
353}
354
355// ── Branch name (§3 step 2) ───────────────────────────────────────────────
356
357export function slugOf(title: string): string {
358  return title
359    .toLowerCase()
360    .replace(/[^a-z0-9]+/g, '-')
361    .replace(/^-+|-+$/g, '')
362    .slice(0, 40)
363    .replace(/-+$/, '')
364}
365
366/** `issue-<N>-<slug>`, then `-2`, `-3`, … past every name in `taken`. */
367export function branchName(issue: number, title: string, taken: readonly string[]): string {
368  const slug = slugOf(title)
369  const first = slug ? `issue-${issue}-${slug}` : `issue-${issue}`
370  const used = new Set(taken)
371  if (!used.has(first)) return first
372  for (let k = 2; ; k++) if (!used.has(`${first}-${k}`)) return `${first}-${k}`
373}
374
375// ── Coverage (§5) ─────────────────────────────────────────────────────────
376
377/** Undoes git's C-style quoting of an unusual path (`"b/t\303\251st"`). */
378function unquote(path: string): string {
379  if (!path.startsWith('"') || !path.endsWith('"')) return path
380  const bytes: number[] = []
381  const body = path.slice(1, -1)
382  for (let i = 0; i < body.length; i++) {
383    const c = body.charAt(i)
384    if (c !== '\\') {
385      for (const b of new TextEncoder().encode(c)) bytes.push(b)
386      continue
387    }
388    const next = body.charAt(i + 1)
389    const octal = body.slice(i + 1, i + 4)
390    if (/^[0-7]{3}$/.test(octal)) {
391      bytes.push(parseInt(octal, 8))
392      i += 3
393    } else {
394      const map: Record<string, string> = { n: '\n', t: '\t', '"': '"', '\\': '\\' }
395      for (const b of new TextEncoder().encode(map[next] ?? next)) bytes.push(b)
396      i += 1
397    }
398  }
399  return new TextDecoder().decode(new Uint8Array(bytes))
400}
401
402/**
403 * Added line numbers per file from `git diff -U0` (§2 "Changed lines"): `@@ -a,b +c,d @@` adds
404 * `c … c+d−1`; `+c` alone is one line; `d = 0` adds none. A deleted file has none.
405 */
406export function parseDiff(text: string): Record<string, number[]> {
407  const changed: Record<string, number[]> = Object.create(null)
408  let current: string | null = null
409  for (const line of text.split('\n')) {
410    if (line.startsWith('diff --git ')) current = null
411    else if (line.startsWith('+++ ')) {
412      const target = line.slice(4).replace(/\t$/, '')
413      current = target === '/dev/null' ? null : unquote(target).replace(/^b\//, '')
414      if (current !== null) changed[current] = changed[current] ?? []
415    } else if (line.startsWith('@@') && current !== null) {
416      const m = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/)
417      if (!m?.[1]) continue
418      const start = Number(m[1])
419      const count = m[2] === undefined ? 1 : Number(m[2])
420      const lines = changed[current] as number[]
421      for (let n = start; n < start + count; n++) lines.push(n)
422      changed[current] = lines
423    }
424  }
425  return changed
426}
427
428/** A count from LCOV text; anything that isn't a number (`-` included) is 0. */
429const num = (text: string | undefined): number => Number(text) || 0
430
431export type LcovFile = {
432  path: string
433  lines: Record<number, number>
434  branches: { line: number; taken: number }[]
435  lf: number
436  lh: number
437  brf: number
438  brh: number
439}
440
441/**
442 * The §5.2 records, each `SF` made repository-relative (a path outside the repository is
443 * dropped). `BRDA` taken `-` counts as 0. Two records for one file are merged.
444 */
445export function parseLcov(text: string, root: string): Record<string, LcovFile> {
446  const files: Record<string, LcovFile> = Object.create(null)
447  let cur: LcovFile | null = null
448  let isDuplicate = false
449  const finish = () => {
450    if (!cur) return
451    const prev = files[cur.path]
452    if (prev) {
453      isDuplicate = true
454      for (const [line, hits] of Object.entries(cur.lines)) prev.lines[Number(line)] = (prev.lines[Number(line)] ?? 0) + hits
455      prev.branches.push(...cur.branches)
456    } else files[cur.path] = cur
457    cur = null
458  }
459  for (const raw of text.split(/\r?\n/)) {
460    const line = raw.trim()
461    if (line.startsWith('SF:')) {
462      finish()
463      const sf = line.slice(3)
464      const isAbs = isAbsolutePath(sf)
465      const rel = isAbs ? relativeTo(root, sf) : normalizePath(sf)
466      cur = rel === null || rel.startsWith('..') ? null : { path: rel, lines: {}, branches: [], lf: 0, lh: 0, brf: 0, brh: 0 }
467      if (cur === null) cur = { path: '\0dropped', lines: {}, branches: [], lf: 0, lh: 0, brf: 0, brh: 0 }
468    } else if (!cur) continue
469    else if (line.startsWith('DA:')) {
470      const [n, hits] = line.slice(3).split(',')
471      cur.lines[num(n)] = num(hits)
472    } else if (line.startsWith('BRDA:')) {
473      const parts = line.slice(5).split(',')
474      cur.branches.push({ line: num(parts[0]), taken: num(parts[3]) })
475    } else if (line.startsWith('LF:')) cur.lf = num(line.slice(3))
476    else if (line.startsWith('LH:')) cur.lh = num(line.slice(3))
477    else if (line.startsWith('BRF:')) cur.brf = num(line.slice(4))
478    else if (line.startsWith('BRH:')) cur.brh = num(line.slice(4))
479    else if (line === 'end_of_record') finish()
480  }
481  finish()
482  delete files['\0dropped']
483  if (isDuplicate) {
484    for (const f of Object.values(files)) {
485      const hits = Object.values(f.lines)
486      f.lf = hits.length
487      f.lh = hits.filter(h => h > 0).length
488      f.brf = f.branches.length
489      f.brh = f.branches.filter(b => b.taken > 0).length
490    }
491  }
492  return files
493}
494
495export function round2(x: number): number {
496  return Math.round(x * 100) / 100
497}
498
499export function pct(part: number, whole: number): Pct {
500  return whole === 0 ? null : round2((part / whole) * 100)
501}
502
503export function pctText(x: Pct): string {
504  return x === null ? 'n/a' : `${x.toFixed(2)}%`
505}
506
507/** `[3,4,5,9]` → `3-5, 9`. */
508export function ranges(lines: readonly number[]): string {
509  const sorted = [...new Set(lines)].sort((a, b) => a - b)
510  const out: string[] = []
511  for (let i = 0; i < sorted.length; ) {
512    let j = i
513    while (j + 1 < sorted.length && sorted[j + 1] === (sorted[j] as number) + 1) j++
514    out.push(i === j ? `${sorted[i]}` : `${sorted[i]}-${sorted[j]}`)
515    i = j + 1
516  }
517  return out.join(', ')
518}
519
520export type DiffCoverage = {
521  lines: { covered: number; measured: number; pct: Pct }
522  branches: { taken: number; total: number; pct: Pct }
523  uncovered: string[]
524}
525
526/** §5.3 steps 2–4 and 6. A changed measured file missing from LCOV counts every changed line uncovered. */
527export function diffCoverage(p: Profile, changed: Record<string, number[]>, lcov: Record<string, LcovFile>): DiffCoverage {
528  let covered = 0
529  let measured = 0
530  let taken = 0
531  let total = 0
532  const uncovered: string[] = []
533  for (const [path, lines] of Object.entries(changed).sort(([a], [b]) => a.localeCompare(b))) {
534    if (kindOf(p, path) !== 'measured' || lines.length === 0) continue
535    const file = lcov[path]
536    const missed: number[] = []
537    if (!file) {
538      measured += lines.length
539      missed.push(...lines)
540    } else {
541      const set = new Set(lines)
542      for (const n of lines) {
543        const hits = file.lines[n]
544        if (hits === undefined) continue
545        measured++
546        if (hits > 0) covered++
547        else missed.push(n)
548      }
549      for (const b of file.branches) {
550        if (!set.has(b.line)) continue
551        total++
552        if (b.taken > 0) taken++
553      }
554    }
555    if (missed.length > 0) uncovered.push(`${path}: ${ranges(missed)}${file ? '' : ' (not in the coverage report)'}`)
556  }
557  return { lines: { covered, measured, pct: pct(covered, measured) }, branches: { taken, total, pct: pct(taken, total) }, uncovered }
558}
559
560/** §5.3 step 5: Σ LH / Σ LF and Σ BRH / Σ BRF over measured source files. */
561export function totals(p: Profile, lcov: Record<string, LcovFile>): Baseline {
562  let lf = 0
563  let lh = 0
564  let brf = 0
565  let brh = 0
566  for (const f of Object.values(lcov)) {
567    if (kindOf(p, f.path) !== 'measured') continue
568    lf += f.lf
569    lh += f.lh
570    brf += f.brf
571    brh += f.brh
572  }
573  return { lines: pct(lh, lf), branches: pct(brh, brf) }
574}
575
576/** §3 step 3: whether the report has any record for source the profile names. */
577export function hasSourceRecord(p: Profile, lcov: Record<string, LcovFile>): boolean {
578  return Object.keys(lcov).some(path => matchesAny(path, p.sourceGlobs))
579}
580
581// ── Gates (§3) ────────────────────────────────────────────────────────────
582
583/** How a command ended: its exit code (null when killed), whether the timeout killed it, its last lines. */
584export type CommandResult = { exit: number | null; isTimedOut: boolean; tail: string }
585
586export function tailLines(text: string, n = 200): string {
587  const lines = text.trimEnd().split('\n')
588  return lines.slice(Math.max(0, lines.length - n)).join('\n')
589}
590
591/** Why a git command failed: its first `fatal:` or `error:` line (git prints progress before it), else its last line. */
592export function gitFailure(text: string): string {
593  const lines = text.split('\n').map(line => line.trim()).filter(Boolean)
594  return lines.find(line => /^(fatal|error):/.test(line)) ?? lines[lines.length - 1] ?? ''
595}
596
597/** A failed `git worktree add` in words: its timeout, git's own reason, or that it said nothing. */
598export function worktreeAddFailure(r: CommandResult, minutes: number): string {
599  return `git worktree add failed: ${r.isTimedOut ? `timed out after ${minutes} min` : gitFailure(r.tail) || 'no output'}`
600}
601
602function ended(r: CommandResult, minutes: number): string {
603  return r.isTimedOut ? `timed out after ${minutes} min` : `exit ${r.exit ?? 'killed'}`
604}
605
606function list(paths: readonly string[], max = 5): string {
607  return paths.length <= max ? paths.join(', ') : `${paths.slice(0, max).join(', ')} and ${paths.length - max} more`
608}
609
610const check = (id: string, passed: boolean, detail: string): Check => ({ id, passed, detail })
611
612/** R5 (gate R) or G9 (gates G and F), Change 0.8.0: the profile's format command, run before the gate records its tree. */
613function formatCheck(which: 'R' | 'G' | 'F', p: Profile, r: CommandResult): Check {
614  const passed = r.exit === 0 && !r.isTimedOut
615  // Set: a gate runs the format command only when the profile names one.
616  return check(which === 'R' ? 'R5' : 'G9', passed, passed ? 'format command ran (exit 0)' : `format command failed: ${(p.formatCommand as string[]).join(' ')} (${ended(r, p.commandTimeoutMinutes)})`)
617}
618
619/** A format command that failed fails the gate alone, before anything is tested; not final, so the phase gets another attempt. Null when it passed. */
620export function formatGate(which: 'R' | 'G' | 'F', p: Profile, r: CommandResult): Gate | null {
621  const c = formatCheck(which, p, r)
622  return c.passed ? null : { gate: which, passed: false, checks: [c] }
623}
624
625export type GateRFacts = { staged: string[]; tests: CommandResult; format?: CommandResult }
626
627/** R1 only test files changed, R2 at least one, R3 the tests now fail; R5 the format command ran, when there is one. */
628export function gateR(p: Profile, f: GateRFacts): Gate {
629  const notTests = f.staged.filter(path => !matchesAny(path, p.testGlobs))
630  const checks = [
631    check('R1', notTests.length === 0, notTests.length === 0 ? `${f.staged.length} staged, all test files` : `not test files: ${list(notTests)}`),
632    check('R2', f.staged.length > 0, f.staged.length > 0 ? `${f.staged.length} test files` : 'nothing staged: red wrote no tests'),
633    check(
634      'R3',
635      !f.tests.isTimedOut && f.tests.exit !== null && f.tests.exit !== 0,
636      f.tests.isTimedOut
637        ? `tests ${ended(f.tests, p.commandTimeoutMinutes)}`
638        : f.tests.exit === null
639          ? "tests didn't run to the end (killed, or the command couldn't start)"
640          : f.tests.exit === 0
641            ? 'tests pass; the new tests must fail first'
642            : `tests fail as intended (exit ${f.tests.exit})`,
643    ),
644    ...(f.format ? [formatCheck('R', p, f.format)] : []),
645  ]
646  return { gate: 'R', passed: checks.every(c => c.passed), checks }
647}
648
649export type GateGFacts = {
650  /** Staged paths since the merge base. */
651  staged: string[]
652  /** Staged paths that differ from the red commit. */
653  changedSinceRed: string[]
654  /** Paths the red commit changed since the merge base. */
655  redPaths: string[]
656  tests: CommandResult
657  coverage: CommandResult
658  /** The LCOV file's text, null when it wasn't there. */
659  lcov: string | null
660  /** `git diff -U0 --cached <merge base>`. */
661  diff: string
662  checks: { argv: string[]; result: CommandResult }[]
663  /** The format command's result, when the profile has one (Change 0.8.0). */
664  format?: CommandResult
665}
666
667/** G1–G7, and G9 when there is a format command (gate F is the same checks). */
668export function gateG(p: Profile, baseline: Baseline | null, f: GateGFacts, root: string, which: 'G' | 'F' = 'G'): Gate {
669  const min = p.commandTimeoutMinutes
670  const changedTests = f.changedSinceRed.filter(path => matchesAny(path, p.testGlobs))
671  const lcov = f.lcov === null ? null : parseLcov(f.lcov, root)
672  const hasCoverage = f.coverage.exit === 0 && !f.coverage.isTimedOut && lcov !== null && hasSourceRecord(p, lcov)
673  const cov = lcov ? diffCoverage(p, parseDiff(f.diff), lcov) : null
674  const total = lcov ? totals(p, lcov) : null
675  const below = (x: Pct) => x !== null && x < p.threshold
676  const unmeasured = f.staged.filter(path => kindOf(p, path) === 'unmeasured')
677  const behaviourTests = f.redPaths.filter(path => matchesAny(path, p.behaviourTestGlobs))
678  const tol = p.regressionTolerance
679  const was = baseline ?? { lines: null, branches: null }
680  const drop = (now: Pct, then: Pct) => now !== null && then !== null && now < round2(then - tol)
681
682  const g4: Check = !hasCoverage || !cov
683    ? check('G4', false, 'no coverage data')
684    : below(cov.lines.pct)
685      ? check('G4', false, `diff line ${pctText(cov.lines.pct)} < ${p.threshold}`)
686      : below(cov.branches.pct)
687        ? check('G4', false, `diff branch ${pctText(cov.branches.pct)} < ${p.threshold}`)
688        : check('G4', true, `diff lines ${pctText(cov.lines.pct)} · branches ${pctText(cov.branches.pct)}`)
689  const g5: Check = !hasCoverage || !total
690    ? check('G5', false, 'no coverage data')
691    : drop(total.lines, was.lines)
692      ? check('G5', false, `total lines ${pctText(total.lines)} < baseline ${pctText(was.lines)} − ${tol}`)
693      : drop(total.branches, was.branches)
694        ? check('G5', false, `total branches ${pctText(total.branches)} < baseline ${pctText(was.branches)} − ${tol}`)
695        : check('G5', true, `total ${pctText(total.lines)} / ${pctText(total.branches)}`)
696  const failedChecks = f.checks.filter(c => c.result.exit !== 0 || c.result.isTimedOut)
697  const checks: Check[] = [
698    check('G1', changedTests.length === 0, changedTests.length === 0 ? 'tests unchanged since the red commit' : `tests changed since the red commit: ${list(changedTests)}`),
699    check('G2', f.tests.exit === 0 && !f.tests.isTimedOut, f.tests.exit === 0 && !f.tests.isTimedOut ? 'tests pass' : `tests fail (${ended(f.tests, min)})`),
700    check(
701      'G3',
702      hasCoverage,
703      hasCoverage
704        ? 'coverage written'
705        : f.coverage.exit !== 0 || f.coverage.isTimedOut
706          ? `coverage command failed (${ended(f.coverage, min)})`
707          : lcov === null
708            ? `no LCOV at ${p.lcovPath}`
709            : 'the LCOV report has no source records',
710    ),
711    g4,
712    g5,
713    check(
714      'G6',
715      unmeasured.length === 0 || behaviourTests.length > 0,
716      unmeasured.length === 0
717        ? 'no unmeasured source changed'
718        : behaviourTests.length > 0
719          ? `behaviour test ${list(behaviourTests, 2)} covers ${list(unmeasured, 2)}`
720          : `no behaviour test in the red commit for ${list(unmeasured)}`,
721    ),
722    check('G7', failedChecks.length === 0, failedChecks.length === 0 ? `${f.checks.length} checks pass` : `check failed: ${failedChecks.map(c => `${c.argv.join(' ')} (${ended(c.result, min)})`).join('; ')}`),
723    ...(f.format ? [formatCheck(which, p, f.format)] : []),
724  ]
725  const failed = checks.filter(c => !c.passed)
726  return {
727    gate: which,
728    passed: failed.length === 0,
729    checks,
730    coverage: { diffLines: cov?.lines.pct ?? null, diffBranches: cov?.branches.pct ?? null, totalLines: total?.lines ?? null, totalBranches: total?.branches ?? null, uncovered: cov?.uncovered ?? [] },
731    isBehaviourOnly: failed.length === 1 && failed[0]?.id === 'G6',
732    unmeasured,
733  }
734}
735
736// ── New plugins (Change 0.7.0) ──────────────────────────────────────────
737
738const BUILD = /(?<![\w:/-])build\b/i
739const WITH = /\bwith\b/i
740const MOD_BUILDER = /\/mod-builder:build\b/i
741
742/**
743 * `build … with /mod-builder:build` on one line; not the `build` of `/mod-builder:build` itself. Each word is found
744 * after the one before it, in linear time: one regex with two lazy `.*?` backtracks cubically on issue text anyone
745 * can write (PR #103 /code-review). The earliest `build` and `with` leave the most line for the next word.
746 */
747function asksForModBuilder(line: string): boolean {
748  const build = line.search(BUILD)
749  if (build < 0) return false
750  const afterBuild = line.slice(build + 'build'.length)
751  const withAt = afterBuild.search(WITH)
752  return withAt >= 0 && MOD_BUILDER.test(afterBuild.slice(withAt + 'with'.length))
753}
754const LINE_CHARS = 1200
755
756/**
757 * The line of the issue that asks for its plugin to be built with mod-builder, cut at 1,200 characters (marked `…`);
758 * null when no line does. Only that line is shown, as the reason, never the lines after it: issue text is anyone's to
759 * write (the owner's decision after PR #103's review).
760 */
761export function newModLine(body: string): string | null {
762  const line = body.replace(/\r\n?/g, '\n').split('\n').find(asksForModBuilder)?.trimEnd()
763  if (line === undefined) return null
764  return line.length > LINE_CHARS ? `${line.slice(0, LINE_CHARS)}…` : line
765}
766
767/** A Claude Code plugin's manifest: `plugin.json` in a `.claude-plugin` folder, at any depth, in any case (a case-insensitive drive opens it). */
768export function isPluginManifest(path: string): boolean {
769  return /(^|\/)\.claude-plugin\/plugin\.json$/i.test(path.replace(/\\/g, '/'))
770}
771
772/**
773 * The new plugin a phase made: the first manifest added since the merge base, else the one the guard refused. A manifest
774 * under the test globs is a fixture (test data), not a new plugin; one on the base branch's tip (`onBase`) is someone
775 * else's, merged in (the owner's decision after PR #103's review).
776 */
777export function newPluginOf(added: readonly string[], refused?: string, testGlobs: readonly string[] = [], onBase: readonly string[] = []): NewPlugin | null {
778  const path = added.find(p => isPluginManifest(p) && !matchesAny(p, testGlobs) && !onBase.includes(p))
779  if (path) return { path, isCreated: true }
780  return refused && !onBase.includes(refused) ? { path: refused, isCreated: false } : null
781}
782
783/** R4 (gate R) or G8 (gates G and F), checked first: a new plugin fails the gate before any test runs. */
784export function newPluginGate(which: 'R' | 'G' | 'F', np: NewPlugin): Gate {
785  const id = which === 'R' ? 'R4' : 'G8'
786  return { gate: which, passed: false, checks: [check(id, false, `${np.isCreated ? 'a new' : 'a refused'} Claude Code plugin: ${np.path}`)], newPlugin: np }
787}
788
789/**
790 * The stored run with the guard's refusal on it, or null to write nothing: never onto a run another session took over,
791 * one that stopped, or another run (Codex 4290574833 on PR #103).
792 */
793export function newPluginRecord(stored: Run | null, runId: string, me: string, path: string, now: number): Run | null {
794  return stored && !foreignChange(stored, runId, me) && isActive(stored) ? advance(stored, { type: 'newPlugin', path }, now) : null
795}
796
797/**
798 * A drive's write, keeping a refusal the guard stored after the drive read the run: nothing clears `newPlugin`, and a
799 * write computed from the earlier read would drop it, so the gate would see neither the file nor the refusal (Codex 4290653342).
800 */
801export function withRefusal(stored: Run | null, next: Run): Run {
802  return stored?.newPlugin && !next.newPlugin ? { ...next, newPlugin: stored.newPlugin } : next
803}
804
805/** What the guard tells a phase agent that would create a manifest. */
806export function newPluginRefusal(path: string): string {
807  return `issue-forge: creating a new Claude Code plugin (${path}) is mod-builder's job, not this run's. End your turn now; the run stops with next steps for the person.`
808}
809
810export type StartIssue = { issue: number; title: string; url: string; ghRepo?: string }
811/** No case carries the issue's text: the start's reply shows its matched line apart, as the reason (owner, after PR #103's review). */
812export type NewPluginCase = { kind: 'start'; issue: StartIssue } | { kind: 'gate'; run: Run }
813
814/** The next steps, one item each, for a start the issue refused or a run a gate blocked; no repository-specific path. */
815export function newPluginSteps(c: NewPluginCase): string[] {
816  if (c.kind === 'start') {
817    const { issue, title, url, ghRepo } = c.issue
818    return [
819      `Run /mod-builder:build and ask for the plugin #${issue} describes: "${title}" (${url}). Read it first with gh issue view ${issue}${ghRepo ? ` --repo ${ghRepo}` : ''}.`,
820      'Approve the SPEC mod-builder writes; it then scaffolds, tests and verifies the plugin.',
821      `Open a pull request that closes #${issue}.`,
822    ]
823  }
824  const run = c.run
825  const isWorktree = isWorktreeRun(run)
826  // What was committed comes from the run's commits, not its gate: G6's detour returns to gate R after red's commit (Codex 4290574818).
827  const red = run.redCommit?.slice(0, 7)
828  const green = run.greenCommit?.slice(0, 7)
829  const stash = run.behaviourFor && run.greenStash ? ` Green's work is in stash ${run.greenStash.sha.slice(0, 7)} "${run.greenStash.message}" (git stash apply ${run.greenStash.sha.slice(0, 7)}).` : ''
830  const left = red
831    ? `Nothing past ${green ? "green's" : "red's"} commit was committed, and nothing was pushed. ${
832        isWorktree
833          ? `This run's worktree ${run.workRoot} holds red's tests at ${red}${green ? `, green's change at ${green},` : ''} and the phase's uncommitted files.`
834          : `This run's branch ${run.branch} holds red's tests at ${red}${green ? ` and green's change at ${green}` : ''}, and the checkout's uncommitted files (git status lists them) are the phase's.`
835      }${stash}`
836    : `Nothing was committed, and nothing was pushed. ${isWorktree ? `This run's worktree ${run.workRoot} holds red's uncommitted files.` : "The checkout's uncommitted files (git status lists them) are red's."}`
837  const cleanup = cleanupCommand(run)
838  return [
839    left,
840    `Stop this run: /issue-forge stop ${run.issue}`,
841    `Build the plugin with /mod-builder:build in a clean checkout of ${run.base} or a new worktree from it, not in this run's ${isWorktree ? 'worktree' : 'branch'}, whose files would be in the way (mod-builder's scaffold refuses a plugin folder that already holds files).`,
842    ...(red ? [`Red's tests can serve the build's logic-first step as reference: git show ${red}`] : []),
843    ...(cleanup ? [`When you no longer need this run's worktree, remove it from a plain shell: ${cleanup}`] : []),
844    `Open a pull request that closes #${run.issue}.`,
845  ]
846}
847
848/** Steps as the person reads them: `1. …`, one per line (a step's own lines follow it). */
849export function numberedSteps(steps: readonly string[]): string {
850  return steps.map((step, i) => `${i + 1}. ${step}`).join('\n')
851}
852
853/** The answer to a start whose issue asks for a new plugin: nothing was started; the matched line is the reason, in its author's words. */
854export function newModReply(issue: StartIssue, line: string): string {
855  return [
856    `#${issue.issue} asks for a new Claude Code plugin. issue-forge doesn't build new plugins: it takes an issue to a fix, test-first. New plugins are built with mod-builder, whose SPEC is the one approval. Nothing was started.`,
857    '',
858    "It matched this line of the issue (the author's words; issue-forge hasn't checked them). If it doesn't ask for a new plugin, reword it and start again:",
859    `  > ${line}`,
860    '',
861    'Next steps:',
862    numberedSteps(newPluginSteps({ kind: 'start', issue })),
863  ].join('\n')
864}
865
866/** A gate found a new plugin: the run blocks final, with the steps, and is never retried. */
867function newPluginBlocked(run: Run, at: Step, np: NewPlugin): Run {
868  const reason = `a phase agent ${np.isCreated ? 'created' : 'tried to create'} a new Claude Code plugin (${np.path}); issue-forge doesn't build new plugins`
869  const steps = newPluginSteps({ kind: 'gate', run: { ...run, step: at } })
870  return blockedAt(run, at, reason, 'build it with /mod-builder:build', { steps, isFinal: true })
871}
872
873/** The first failed check's detail, or '' when none failed. */
874export function firstFailure(g: Gate): string {
875  return g.checks.find(c => !c.passed)?.detail ?? ''
876}
877
878/** The failed checks as the next attempt's prompt lists them, uncovered lines included. */
879export function failuresOf(g: Gate): string[] {
880  const out = g.checks.filter(c => !c.passed).map(c => `${c.id}: ${c.detail}`)
881  if (g.checks.some(c => c.id === 'G4' && !c.passed)) for (const u of g.coverage?.uncovered ?? []) out.push(`  uncovered ${u}`)
882  return out
883}
884
885// ── Repository (#25) ──────────────────────────────────────────────────────
886
887/** `host/owner/repo` from `gh repo view --json nameWithOwner,url`: the host from the url (lowercased), the rest from nameWithOwner. */
888export function repoOfView(stdout: string): string | null {
889  let view: { nameWithOwner?: unknown; url?: unknown }
890  try {
891    view = JSON.parse(stdout) as typeof view
892  } catch {
893    return null
894  }
895  const host = typeof view?.url === 'string' ? /^https?:\/\/([^/@]+)\//.exec(view.url)?.[1] : undefined
896  return host && typeof view.nameWithOwner === 'string' && /^[^/]+\/[^/]+$/.test(view.nameWithOwner) ? `${host.toLowerCase()}/${view.nameWithOwner}` : null
897}
898
899// The scheme is group 1 and the host group 2 in a URL, the host group 3 in the scp-like form; then owner (4) and repository (5).
900const REMOTE_URL = /^(?:(https?|ssh):\/\/(?:[^/@]+@)?([A-Za-z0-9][A-Za-z0-9.-]*)(?::\d+)?\/|(?:[^/@:\s]+@)?([A-Za-z0-9][A-Za-z0-9.-]*):(?!\/))([^/\s?#]+)\/([^/\s?#]+?)(?:\.git)?\/?$/i
901
902/** A remote's `host/owner/repo`, and whether git reaches it over ssh (an ssh:// URL or the scp-like form). */
903function parseRemote(url: string): { repo: string; isSsh: boolean } | null {
904  const m = url.trim().match(REMOTE_URL)
905  return m ? { repo: `${String(m[2] ?? m[3]).toLowerCase()}/${m[4]}/${m[5]}`, isSsh: m[1] === undefined || m[1].toLowerCase() === 'ssh' } : null
906}
907
908/**
909 * `host/owner/repo` from a git remote URL: https, http and ssh URLs (the scheme in any case; userinfo, port, `.git` and a
910 * trailing slash dropped, the host lowercased) and scp-like `[user@]host:owner/repo`. Any other form (git://, file://, a
911 * path) is null.
912 */
913export function repoOfRemoteUrl(url: string): string | null {
914  return parseRemote(url)?.repo ?? null
915}
916
917export type RemoteVerdict = { kind: 'match' } | { kind: 'unrecognised' } | { kind: 'ask'; repo: string } | { kind: 'other'; repo: string }
918
919export const hostOf = (repo: string) => repo.slice(0, repo.indexOf('/')).toLowerCase()
920
921/**
922 * Whether a remote URL names `repo` (PR #68 review). An https host is the host; git hands an ssh remote's host to ssh, and
923 * ~/.ssh/config may alias it, so there the same owner and repository is enough. Another owner or repository on the pinned
924 * host may be `repo` renamed, which only gh can say (`ask`); gh is never asked about another host.
925 */
926export function remoteVerdict(url: string, repo: string): RemoteVerdict {
927  const remote = parseRemote(url)
928  if (!remote) return { kind: 'unrecognised' }
929  if (isSameRepo(remote.repo, repo) || (remote.isSsh && isSameOwnerRepo(remote.repo, repo))) return { kind: 'match' }
930  return hostOf(remote.repo) === hostOf(repo) ? { kind: 'ask', repo: remote.repo } : { kind: 'other', repo: remote.repo }
931}
932
933/** The host `ssh -G` is asked about for a fork clone's URL: an ssh URL's host when it isn't `repo`'s; any other needs none. */
934export function sshHostToResolve(url: string, repo: string): string | null {
935  const remote = parseRemote(url)
936  return remote?.isSsh && hostOf(remote.repo) !== hostOf(repo) ? hostOf(remote.repo) : null
937}
938
939/** `ssh -G <host>`'s `hostname` line: the host ssh connects to once ~/.ssh/config is applied (a nickname's HostName). */
940export function sshHostname(stdout: string): string | null {
941  const host = stdout
942    .split(/\r?\n/)
943    .find(line => /^hostname\s/i.test(line))
944    ?.trim()
945    .split(/\s+/)[1]
946  return host ? host.toLowerCase() : null
947}
948
949/**
950 * What a fork clone's remote URL names (PR #87 review, the owner's choice). Unlike `remoteVerdict`, an ssh host other than
951 * `repo`'s is never assumed to be its nickname: it counts only as ssh resolves it (`resolved`, from `ssh -G`; null or absent
952 * when ssh couldn't say), with GitHub's ssh-over-443 host taken for github.com. Origin's own check keeps #25's rule (#71).
953 */
954export function forkRemoteVerdict(url: string, repo: string, resolved?: string | null): RemoteVerdict {
955  const remote = parseRemote(url)
956  if (!remote) return { kind: 'unrecognised' }
957  let named = remote.repo
958  if (sshHostToResolve(url, repo) !== null) {
959    if (!resolved) return { kind: 'unrecognised' }
960    named = `${resolved === 'ssh.github.com' ? 'github.com' : resolved}${named.slice(named.indexOf('/'))}`
961  }
962  if (isSameRepo(named, repo)) return { kind: 'match' }
963  return hostOf(named) === hostOf(repo) ? { kind: 'ask', repo: named } : { kind: 'other', repo: named }
964}
965
966/** The same host, owner and repository, in any case; a null side never matches. */
967export function isSameRepo(a: string | null, b: string | null): boolean {
968  return a !== null && b !== null && a.toLowerCase() === b.toLowerCase()
969}
970
971/** The same owner and repository on any host: an SSH alias from ~/.ssh/config stands in for the host. */
972export function isSameOwnerRepo(a: string | null, b: string | null): boolean {
973  const ownerRepo = (repo: string) => repo.slice(repo.indexOf('/') + 1).toLowerCase()
974  return a !== null && b !== null && ownerRepo(a) === ownerRepo(b)
975}
976
977/** Whether an issue's url is a pull request's: `gh issue view` answers for both. */
978export function isPullUrl(url: string): boolean {
979  return /^https?:\/\/[^/]+\/[^/]+\/[^/]+\/pull\/\d+$/.test(url)
980}
981
982/** `owner/repo` on github.com, `host/owner/repo` anywhere else. */
983export function repoLabel(repo: string): string {
984  return repo.replace(/^github\.com\//i, '')
985}
986
987/** `#16`, or `o/r#16` for a run pinned to a repository. */
988export function issueLabel(run: Run): string {
989  return `${run.ghRepo ? repoLabel(run.ghRepo) : ''}#${run.issue}`
990}
991
992// ── Fork clones (#26) ─────────────────────────────────────────────────────
993
994/** What a remote URL names once resolved: the run's repository, another (gh's name for it), or nothing readable (null). */
995export type RemoteFound = 'match' | { other: string | null }
996
997/**
998 * The fork a fork clone's origin pushes to: every push URL names one repository on `repo`'s host that isn't `repo`, and the
999 * fetch URL is that fork too, so `git ls-remote origin`, which reads the fetch URL, lists the fork's branches (PR #87 review;
1000 * Codex P1 4290274553: fetching from `repo` itself hid them).
1001 */
1002export function forkOfOrigin(fetch: RemoteFound, pushes: readonly RemoteFound[], repo: string): string | null {
1003  let fork: string | null = null
1004  for (const found of pushes) {
1005    if (found === 'match' || found.other === null || hostOf(found.other) !== hostOf(repo)) return null
1006    if (fork !== null && !isSameRepo(fork, found.other)) return null
1007    fork ??= found.other
1008  }
1009  if (fork === null) return null
1010  return fetch !== 'match' && isSameRepo(fetch.other, fork) ? fork : null
1011}
1012
1013/** The remotes whose fetch URL names the project: none, one (the base remote), or several (a block). */
1014export type BaseRemote = { kind: 'none' } | { kind: 'one'; remote: string } | { kind: 'several'; remotes: string[] }
1015
1016export function baseRemoteOf(matching: readonly string[]): BaseRemote {
1017  const [first, ...rest] = matching
1018  if (first === undefined) return { kind: 'none' }
1019  return rest.length === 0 ? { kind: 'one', remote: first } : { kind: 'several', remotes: [...matching] }
1020}
1021
1022/**
1023 * Whether `gh repo view <fork> --json isFork,parent` says a fork of `repo`: the parent's owner login and name are
1024 * `repo`'s, in any case. gh prints no host for the parent: it is the fork's own, which the caller has found to be
1025 * `repo`'s, so `repo`'s host stands in for it.
1026 */
1027export function isForkOf(stdout: string, repo: string): boolean {
1028  let view: { isFork?: unknown; parent?: { name?: unknown; owner?: { login?: unknown } | null } | null }
1029  try {
1030    view = JSON.parse(stdout) as typeof view
1031  } catch {
1032    return false
1033  }
1034  const login = view?.parent?.owner?.login
1035  const name = view?.parent?.name
1036  if (view?.isFork !== true || typeof login !== 'string' || typeof name !== 'string') return false
1037  return isSameRepo(`${hostOf(repo)}/${login}/${name}`, repo)
1038}
1039
1040/** The owner of a `host/owner/repo`. */
1041export function ownerOf(repo: string): string {
1042  return repo.slice(repo.indexOf('/') + 1, repo.lastIndexOf('/'))
1043}
1044
1045/** `gh pr create --head`: `<owner>:<branch>` for a fork's branch (its owner is not the project's), the branch alone otherwise. */
1046export function headArg(branch: string, headRepo?: string): string {
1047  return headRepo === undefined ? branch : `${ownerOf(headRepo)}:${branch}`
1048}
1049
1050/**
1051 * A kept branch is reused only while origin pushes where its name was checked: the fork it was made for (`kept`), or the
1052 * project itself when there was none; `now` is the fork preflight finds (Codex on PR #87).
1053 */
1054export function keptForkBlock(kept: string | undefined, now: string | undefined, repo: string): { reason: string; next: string } | null {
1055  if (kept === undefined ? now === undefined : isSameRepo(kept, now ?? null)) return null
1056  const was = repoLabel(kept ?? repo)
1057  return { reason: `origin now pushes to ${repoLabel(now ?? repo)}, not ${was}, where the run's branch was named`, next: `point origin back at ${was}, or start a new run` }
1058}
1059
1060/** The remote a run fetches its base from: the project's in a fork clone, origin in every other run. */
1061export function baseRemoteOfRun(run: { baseRemote?: string }): string {
1062  return run.baseRemote ?? 'origin'
1063}
1064
1065/** The remote-tracking ref of the base, `<remote>/<base>`. */
1066export function baseRefOf(run: { base: string; baseRemote?: string }): string {
1067  return `${baseRemoteOfRun(run)}/${run.base}`
1068}
1069
1070// ── State (§7.4) ──────────────────────────────────────────────────────────
1071
1072/**
1073 * The run's branch, the folder it is checked out in, and its base, once preflight has made them; in a fork clone also the base
1074 * remote and the fork the branch's name was checked on (Codex on PR #87).
1075 */
1076export type Kept = { branch: string; workRoot: string; base: string; baseRemote?: string; headRepo?: string }
1077
1078/** How an agent's turn ended (`turn.complete`'s `reason`); an answer given in-line by another plugin has none. */
1079export type TurnEnd = 'answer' | 'aborted' | 'refusal' | 'error'
1080
1081export type RunEvent =
1082  | { type: 'preflighted'; title: string; body: string; url: string; base: string; branch: string; mergeBase: string; profile: Profile; workRoot?: string; repo: string; baseRemote?: string; headRepo?: string }
1083  | { type: 'baselined'; baseline: Baseline; mergeBase?: string }
1084  | { type: 'spawned'; agent: AgentRef }
1085  | { type: 'agentDone'; answer: string; reason?: TurnEnd }
1086  | { type: 'gated'; gate: Gate; commit?: string; stash?: StashRef; testTail?: string; head?: string; blockAfter?: { reason: string; next: string } }
1087  | { type: 'block'; reason: string; next: string; keep?: Kept; isFinal?: boolean; gate?: Gate; testTail?: string }
1088  | { type: 'newPlugin'; path: string }
1089  | { type: 'merged'; merge: MergeCheck }
1090  | { type: 'made'; keep: Kept }
1091  | { type: 'pinned'; repo: string }
1092  | { type: 'resume' }
1093  | { type: 'stop' }
1094  | { type: 'drive'; session: string }
1095  | { type: 'release'; session: string }
1096  | { type: 'publish' }
1097  | { type: 'published'; url: string; merge?: MergeCheck }
1098
1099export const WORKING: readonly Step[] = ['preflight', 'baseline', 'red', 'gateR', 'green', 'gateG', 'refactor', 'gateF', 'publishing']
1100
1101export function isWorking(step: Step): boolean {
1102  return WORKING.includes(step)
1103}
1104
1105/** Active: anything but done and stopped holds the repository (§7.4: a second start answers with its status). */
1106export function isActive(run: Run | null): boolean {
1107  return run !== null && run.step !== 'done' && run.step !== 'stopped'
1108}
1109
1110export function phaseOf(step: Step): Phase | 'publish' | 'setup' | null {
1111  if (step === 'preflight' || step === 'baseline') return 'setup'
1112  if (step === 'red' || step === 'gateR') return 'red'
1113  if (step === 'green' || step === 'gateG') return 'green'
1114  if (step === 'refactor' || step === 'gateF') return 'refactor'
1115  if (step === 'ready' || step === 'publishing' || step === 'done') return 'publish'
1116  return null
1117}
1118
1119/** `ghRepo` (`host/owner/repo`) pins a run started from an issue URL to that repository (#25). */
1120export function newRun(id: string, root: string, issue: number, now: number, ghRepo?: string): Run {
1121  return {
1122    id,
1123    root,
1124    ...(ghRepo === undefined ? {} : { ghRepo }),
1125    issue,
1126    title: '',
1127    body: '',
1128    url: '',
1129    branch: '',
1130    base: '',
1131    mergeBase: '',
1132    profile: null,
1133    step: 'preflight',
1134    used: { red: 0, green: 0, refactor: 0 },
1135    baseline: null,
1136    gates: {},
1137    times: {},
1138    startedAt: now,
1139    agents: [],
1140  }
1141}
1142
1143function attemptsOf(run: Run, phase: Phase): number {
1144  return run.profile?.attempts[phase] ?? DEFAULTS.attempts[phase]
1145}
1146
1147/** Whether a failed gate in `phase` gets another spawn. */
1148export function canRetry(run: Run, phase: Phase): boolean {
1149  return run.used[phase] < attemptsOf(run, phase)
1150}
1151
1152const start = (run: Run, phase: Phase | 'publish', now: number): Run['times'] => ({ ...run.times, [phase]: { startedAt: now } })
1153const end = (run: Run, phase: Phase | 'publish', now: number): Run['times'] => ({ ...run.times, [phase]: { startedAt: run.times[phase]?.startedAt ?? now, endedAt: now } })
1154
1155function blockedAt(run: Run, at: Step, reason: string, next: string, more: { steps?: string[]; isFinal?: boolean } = {}): Run {
1156  return { ...run, step: 'blocked', blocked: { at, reason, next, ...more } }
1157}
1158
1159/** A gate's result carried by a block from its commit step (PR #136 review, finding 3), recorded under the step it ends. */
1160function gateRecord(run: Run, ev: { gate?: Gate; testTail?: string }): Partial<Run> {
1161  const at = run.step === 'gateR' ? 'R' : run.step === 'gateG' ? 'G' : run.step === 'gateF' ? 'F' : null
1162  return ev.gate && at ? { lastGate: ev.gate, gates: { ...run.gates, [at]: ev.gate }, lastTestTail: ev.testTail } : {}
1163}
1164
1165/** The single transition function: every step change goes through here. */
1166export function advance(run: Run, ev: RunEvent, now: number): Run {
1167  if (ev.type === 'stop') return isActive(run) ? finishedRecord({ ...run, step: 'stopped', finishedAt: now }) : run
1168  // Who drives the run (Change 0.3.0): set when a drive starts; only that session's release clears it.
1169  if (ev.type === 'drive') return { ...run, driver: { session: ev.session, since: now } }
1170  if (ev.type === 'release') {
1171    if (run.driver?.session !== ev.session) return run
1172    const { driver: _, ...rest } = run
1173    return rest
1174  }
1175  // The branch and folder preflight made land at any step, a stopped one too, so a Stop never loses them.
1176  if (ev.type === 'made') return { ...run, ...ev.keep }
1177  // A number start's repository, once origin agrees with it: kept over a block, so resume can't move the run (PR #68 review 2).
1178  if (ev.type === 'pinned') return run.ghRepo ? run : { ...run, ghRepo: ev.repo }
1179  // A preflight that made the branch before it blocked keeps it, so resume reuses it.
1180  if (ev.type === 'block') return isWorking(run.step) || run.step === 'ready' ? blockedAt({ ...run, ...ev.keep, ...gateRecord(run, ev) }, run.step, ev.reason, ev.next, ev.isFinal ? { isFinal: true } : {}) : run
1181  // The guard refused a manifest: the phase's gate blocks on it (Change 0.7.0).
1182  if (ev.type === 'newPlugin') return isActive(run) ? { ...run, newPlugin: ev.path } : run
1183  if (ev.type === 'resume') {
1184    if (isWorking(run.step)) {
1185      const phase = phaseOf(run.step)
1186      return phase === 'red' || phase === 'green' || phase === 'refactor' ? { ...run, used: { ...run.used, [phase]: 0 } } : run
1187    }
1188    if (run.step !== 'blocked' || !run.blocked || run.blocked.isFinal) return run
1189    const at = run.blocked.at === 'publishing' ? 'ready' : run.blocked.at
1190    const phase = phaseOf(at)
1191    const used = phase === 'red' || phase === 'green' || phase === 'refactor' ? { ...run.used, [phase]: 0 } : run.used
1192    const { blocked: _, ...rest } = run
1193    return { ...rest, step: at, used }
1194  }
1195  switch (run.step) {
1196    case 'preflight':
1197      if (ev.type !== 'preflighted') return run
1198      return { ...run, title: ev.title, body: ev.body, url: ev.url, base: ev.base, branch: ev.branch, mergeBase: ev.mergeBase, profile: ev.profile, ...(ev.workRoot ? { workRoot: ev.workRoot } : {}), ghRepo: ev.repo, ...(ev.baseRemote ? { baseRemote: ev.baseRemote } : {}), ...(ev.headRepo ? { headRepo: ev.headRepo } : {}), step: 'baseline' }
1199    case 'baseline':
1200      if (ev.type !== 'baselined') return run
types/index.d.ts 175 lines
1// Issue Forge's state contract. Self-contained: no imports.
2
3export type Phase = 'red' | 'green' | 'refactor'
4
5/** Where a run is (SPEC "How it works" 14). `blocked` and `stopped` hold no work. */
6export type Step =
7  | 'preflight'
8  | 'baseline'
9  | 'red'
10  | 'gateR'
11  | 'green'
12  | 'gateG'
13  | 'refactor'
14  | 'gateF'
15  | 'ready'
16  | 'publishing'
17  | 'done'
18  | 'blocked'
19  | 'stopped'
20
21/** `.issue-forge.json`, validated, defaults filled, `~` expanded (§4). */
22export type Profile = {
23  baseBranch: string
24  testCommand: string[]
25  coverageCommand: string[]
26  /** Change 0.8.0 (#137): the repository's formatter; each gate runs it between two `git add -A`. Absent, no format step. */
27  formatCommand?: string[]
28  lcovPath: string
29  sourceGlobs: string[]
30  testGlobs: string[]
31  excludeGlobs: string[]
32  unmeasuredGlobs: string[]
33  behaviourTestGlobs: string[]
34  checks: string[][]
35  threshold: number
36  regressionTolerance: number
37  attempts: { red: number; green: number; refactor: number }
38  commandTimeoutMinutes: number
39  notes: string
40  commitTrailers: string[]
41  /** Where a run works: `here` (this checkout, never when busy), `worktree` (always a new one), `ask` (when busy). */
42  workspace: Workspace
43  /** Where new worktrees go, relative to the repository root (gitignored). */
44  worktreeDir: string
45}
46
47export type Workspace = 'ask' | 'worktree' | 'here'
48
49/** `git merge-tree` of the gated commit against the freshly fetched base, at ready. */
50export type MergeCheck = { isClean: boolean; files: string[]; error?: string }
51
52/** A percentage rounded to two decimals, or null for "n/a". */
53export type Pct = number | null
54
55export type Check = { id: string; passed: boolean; detail: string }
56
57export type Coverage = {
58  diffLines: Pct
59  diffBranches: Pct
60  totalLines: Pct
61  totalBranches: Pct
62  /** `path: 3-5, 9` for each changed measured file with uncovered lines. */
63  uncovered: string[]
64}
65
66export type Gate = {
67  gate: 'R' | 'G' | 'F'
68  passed: boolean
69  checks: Check[]
70  coverage?: Coverage
71  /** G6 failed and nothing else did: the run goes back to red once. */
72  isBehaviourOnly?: boolean
73  /** Unmeasured source files changed since the merge base. */
74  unmeasured?: string[]
75  /** R4 or G8 failed: a phase agent created a plugin manifest, or the guard refused one (Change 0.7.0). */
76  newPlugin?: NewPlugin
77}
78
79/** A new Claude Code plugin's manifest a phase agent made (`isCreated`) or the guard refused it (Change 0.7.0). */
80export type NewPlugin = { path: string; isCreated: boolean }
81
82export type Baseline = { lines: Pct; branches: Pct }
83
84export type AgentRef = { id: string; name?: string; phase: Phase }
85
86/** A stash entry the mod made, found by its unique message and kept by its commit. */
87export type StashRef = { sha: string; message: string }
88
89export type PhaseTime = { startedAt: number; endedAt?: number }
90
91/** The session whose drive is under way (Change 0.3.0): its `$.session.id()` at session start, and since when. */
92export type Driver = { session: string; since: number }
93
94/** One of the repository's other active runs, as the pane's `also` line shows it (Change 0.3.0). */
95export type OtherRun = { issue: number; step: Step; line: string; isElsewhere: boolean }
96
97export type Run = {
98  id: string
99  /** git's common folder: every worktree of the repository shares it, and it keys the store (Change 0.3.0). Absent in runs stored before. */
100  repo?: string
101  /** The GitHub repository (`host/owner/repo`) every gh call of the run names with `--repo` (#25). Absent in runs stored before. */
102  ghRepo?: string
103  /** The remote the base is fetched from, in a fork clone where origin is the contributor's fork (#26). Absent: origin. */
104  baseRemote?: string
105  /** The fork origin pushes to (`host/owner/repo`), whose owner heads the pull request (#26). Absent: the branch alone. */
106  headRepo?: string
107  /** Set while a session drives the run; cleared when the drive ends (Change 0.3.0). */
108  driver?: Driver
109  /** Started from the menu's Start under `ask`: it works in a new worktree, asked once (Change 0.3.0). */
110  chosenWorktree?: boolean
111  /** The checkout the run was started from (it keyed the store before 0.3.0). */
112  root: string
113  /** Where git, the profile's commands and the agents work: a new worktree, or `root`. Absent in runs stored before 0.2.0. */
114  workRoot?: string
115  issue: number
116  title: string
117  /** The issue's text; a `done` or `stopped` record keeps its first 500 characters and `…` (0.9.0). */
118  body: string
119  url: string
120  branch: string
121  base: string
122  mergeBase: string
123  profile: Profile | null
124  step: Step
125  /** Spawns used in each phase since it last started or was resumed. */
126  used: { red: number; green: number; refactor: number }
127  redCommit?: string
128  greenCommit?: string
129  refactorCommit?: string
130  baseline: Baseline | null
131  /** The latest result of each gate. */
132  gates: { R?: Gate; G?: Gate; F?: Gate }
133  lastGate?: Gate
134  /** Last 200 lines, at most 20,000 characters, of the test output red's gate saw: green's first prompt gets them. Dropped once `done` or `stopped` (0.9.0). */
135  redTestTail?: string
136  /** Last 200 lines, at most 20,000 characters, of the latest gate's test output, or of its format command's when that failed it (R5, G9; 0.8.0): a retry's prompt gets them. Dropped once `done` or `stopped` (0.9.0). */
137  lastTestTail?: string
138  /** The red agent's final answer, plus a behaviour detour's once its gate R passed: each green prompt and the PR body get it. Dropped once `done` or `stopped` (0.9.0). */
139  redAnswer?: string
140  /** Set while red adds a behaviour test for these files (G6's one return). */
141  behaviourFor?: string[]
142  /** The detour's latest red answer, held until its gate R passes, then added to `redAnswer` (PR #89 review). */
143  behaviourAnswer?: string
144  isBehaviourDone?: boolean
145  /** The stash entry holding green's work during that return; applied by its SHA only. */
146  greenStash?: StashRef
147  isRefactorRejected?: boolean
148  refactorStash?: StashRef
149  times: { red?: PhaseTime; green?: PhaseTime; refactor?: PhaseTime; publish?: PhaseTime }
150  startedAt: number
151  /** When the run became `done` or `stopped` (0.9.0, PR #145 review round 1): the store's budget deletes the longest finished first. */
152  finishedAt?: number
153  agents: AgentRef[]
154  prUrl?: string
155  /** HEAD when the run reached ready (after gate F): publish pushes exactly this commit, and refuses if HEAD moved. */
156  gatedHead?: string
157  merge?: MergeCheck
158  /** The manifest the guard refused a phase agent, relative to the run's folder: the phase's gate blocks on it (Change 0.7.0). */
159  newPlugin?: string
160  /**
161   * `steps`: what the person does next, one item each; `isFinal`: resume can't clear it, so the hint says stop
162   * (Change 0.7.0). Both absent in runs stored before.
163   */
164  blocked?: { at: Step; reason: string; next: string; steps?: string[]; isFinal?: boolean }
165}
166
167/** What the module is doing right now inside a step: a label and since when. */
168export type Activity = { label: string; since: number }
169
170declare module 'claude-code' {
171  interface PluginState {
172    'issue-forge': { run: Run | null; activity: Activity | null; now: number; demo: string | null; focus: number | null; others: OtherRun[] }
173  }
174}
175