From 4e73944f829fcf5f9a29af9e9a38647b421cd20a Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 10:53:58 -0800 Subject: [PATCH 01/94] chore(porch): 1951 init spir --- .../status.yaml | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 codev/projects/1951-read-only-pr-check-for-archite/status.yaml diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml new file mode 100644 index 000000000..bbbbe31ab --- /dev/null +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -0,0 +1,20 @@ +id: '1951' +title: read-only-pr-check-for-archite +protocol: spir +phase: specify +plan_phases: [] +current_plan_phase: null +gates: + spec-approval: + status: pending + plan-approval: + status: pending + pr: + status: pending + verify-approval: + status: pending +iteration: 1 +build_complete: false +history: [] +started_at: '2026-11-23T18:53:58.201Z' +updated_at: '2026-11-23T18:53:58.203Z' From 74cdab609b4682a72b5dca0f1543a34c3638476d Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 11:04:15 -0800 Subject: [PATCH 02/94] [Spec 1951] Initial specification draft --- .../1951-read-only-pr-check-for-archite.md | 562 ++++++++++++++++++ codev/state/spir-1951_thread.md | 14 + 2 files changed, 576 insertions(+) create mode 100644 codev/specs/1951-read-only-pr-check-for-archite.md create mode 100644 codev/state/spir-1951_thread.md diff --git a/codev/specs/1951-read-only-pr-check-for-archite.md b/codev/specs/1951-read-only-pr-check-for-archite.md new file mode 100644 index 000000000..89b58b6a6 --- /dev/null +++ b/codev/specs/1951-read-only-pr-check-for-archite.md @@ -0,0 +1,562 @@ +# Specification: Read-only PR check for architects — merge readiness, deploy status, worktree removability + + + +## Problem Statement + +Before an architect asks the owner for a merge word at a `pr` gate, they collect a set of +mechanical facts about the builder's pull request: which commit is actually being merged, +whether it merges cleanly into the *current* base, whether CI passed on *that* code, whether +anything forbidden (attribution trailers) is about to reach the base branch, how big it is, +and which files a human still has to read. After the merge they ask whether it has reached +the deploy branch; before cleanup they ask whether the builder's worktree can go without +losing anything. + +Today every one of those facts is gathered by hand, one `gh` / `git` command at a time, and +the misses are **silent**: a trial merge nobody ran, a check that was green on the wrong +commit, an attribution line that reaches `main`, a worktree removed with evidence still in +it. An adopter's architect counted one week of their own shell history (16,117 commands) and +found these sequences typed hundreds of times; they wrote local helpers (`check`, `merged`, +`lane`) and asked that Codev ship the equivalent. + +Who is affected: every architect at every `pr` gate and every cleanup, in every Codev +workspace; builders who want to verify their own PR before announcing it; and the owner, who +receives a merge recommendation built on facts nobody checked. + +## Current State + +- **Merge readiness is assembled by hand.** The architect role's integration review + (`codev/roles/architect.md`) and `codev/resources/risk-triage.md` Step 1 tell the architect + to run `gh pr diff --stat` / `gh pr view --json files` and judge size, then read or + `consult`. Nothing collects head SHA, mergeability, a trial merge, CI-on-the-right-commit, + attribution, or overlap with base in one place. +- **Attribution leaks.** On this repository, **361 commits since 2026-06-01** carry a + `Co-Authored-By` trailer against the owner's standing rule (verified: + `git log --since=2026-06-01 --grep='Co-Authored-By' -i origin/main | wc -l` → 361). + Nothing checks for it before merge. +- **Porch-only heads hide CI.** A builder's last commits are usually porch bookkeeping + (`chore(porch): 1911 pr gate-requested`, `… review build-complete`), each touching only + `codev/projects/-*/status.yaml`. The checks on the PR head then say nothing about the + code — or nothing at all when CI ignores those paths — and the architect has to find the + commit that carried the code and look up its runs by hand. +- **Trial merges are rarely run**, and when run by hand they usually use a stale local + `origin/main`, or check out a branch and mutate the index/working tree of the architect's + checkout. +- **Deploy status** ("has PR #N reached production / the latest green deploy run?") is a + manual `git branch --contains` plus a scan of the Actions page. +- **Worktree removability.** `afx cleanup` force-removes bugfix/task worktrees + (`git worktree remove --force`, `git branch -D`) and only *preserves* SPIR-family + worktrees with a hint to remove them by hand. Neither path answers, read-only, "would + removing this lose anything?" A recent cleanup question turned on an untracked review file + nobody could see without `cd`-ing into the worktree — which the architect role forbids. + Issue #1950 (in flight as `air-1950`) adds `afx cleanup --keep-ignored`, which copies + untracked and keep-listed ignored files out before removal; it does not tell you *in + advance* what is there. +- **Forge reach.** The existing `pr-view` concept returns title, body, state, url, author, + base/head ref names and additions/deletions — no head SHA, mergeability, draft flag or + merge commit. There is no forge concept for per-commit check results or for workflow runs. + +## Desired State + +One read-only command family, `codev check`, with three subcommands: + +| Command | Question it answers | Adopter's name | +|---|---|---| +| `codev check pr ` | Can I recommend merging PR N, and if not, what specifically blocks it? | `check` | +| `codev check deploy […]` | Has each merged PR reached the deploy branch / the latest green deploy run? | `merged` | +| `codev check worktree ` | Can this builder's worktree be removed without losing anything? | `lane` | + +The headline path: **an architect runs `codev check pr ` on a builder's PR and, in one +screen, sees everything needed to recommend the merge — or the specific thing that blocks +it.** Every command: + +- **never** merges, approves, cleans up, deletes, pushes, comments, or moves a ref; +- runs only commands on an explicit read-only allow-list, enforced at runtime and in tests; +- reports a check it could not run **by name, with the reason** — never as passing; +- prints a ten-second summary (verdict first), offers `--json` for agents, and exits + **0** (clear) / **1** (needs attention) / **2** (the command itself failed). + +### Sample: `codev check pr` + +``` +$ codev check pr 1957 +ATTENTION PR #1957 — attribution, checks, watched (flagged) + +PR #1957 Read-only PR check for architects OPEN builder/spir-1951 → main +head a1b2c3d (local builder/spir-1951 matches) base main @ 7c0f3ab (origin, live) + + ATTN attribution 2 lines: commit 9f8e7d6 "Co-Authored-By: Claude …"; description line 41 + ok trial merge clean into main @ 7c0f3ab + ok forge MERGEABLE, CLEAN + ATTN checks code 57d2ec5: 7 passed, 1 failed (test.yml / unit) + head a1b2c3d: no runs — 3 porch-state commits above the code + ATTN watched CLAUDE.md (flagged); codev/roles/architect.md + info overlap 2 files also changed on main since branch point: CHANGELOG.md, packages/codev/src/cli.ts + info size +1,204 −88 in 23 files + info to read 14 files (9 not for reading): packages/codev/src/commands/check/pr.ts, … +12 +``` + +A clear PR prints `CLEAR PR #N — ready to recommend` on its first line and exits 0. + +### Sample: `codev check deploy` + +With `check.deploy` configured (`branch: production`, `workflow: deploy.yml`): + +``` +$ codev check deploy 1948 1949 +ATTENTION #1949 not deployed + +#1948 merged 2026-11-22 → main merge 7c0f3ab + ok on production origin/production @ 9d8c7b6 contains 7c0f3ab + ok deploy run latest green deploy.yml run (2026-11-22 18:04, 9d8c7b6) contains 7c0f3ab +#1949 merged 2026-11-23 → main merge 4e5f6a7 + ATTN on production origin/production @ 9d8c7b6 does not contain 4e5f6a7 + ATTN deploy run latest green deploy.yml run (9d8c7b6) does not contain 4e5f6a7 +``` + +With nothing configured (no deploy workflow) it is still useful — it confirms the merge +landed on the live base branch and reports CI on the merge commit itself: + +``` +$ codev check deploy 1948 +CLEAR #1948 on main; checks on the merge commit passed + +#1948 merged 2026-11-22 → main merge 7c0f3ab + ok on main origin/main @ 3aeb295 contains 7c0f3ab + ok merge checks 7c0f3ab: 8 passed + off deploy run no deploy workflow configured (check.deploy.workflow) +``` + +### Sample: `codev check worktree` + +``` +$ codev check worktree spir-1951 +NOT REMOVABLE spir-1951 — 1 uncommitted file + +worktree .builders/spir-1951 branch builder/spir-1951 base main @ 7c0f3ab (origin, live) + ATTN uncommitted 1 file: codev/state/spir-1951_thread.md (modified) [5 scaffold files not counted] + ok commits all 31 commits are on origin/main + ok remote origin/builder/spir-1951 matches local (a1b2c3d); PR #1957 MERGED + ATTN ignored 3 keep-list files would be lost: codev/projects/1951-…/1951-specify-iter1-codex.txt, … +2 + → copy them out first, or use `afx cleanup --keep-ignored` (#1950) +``` + +Verdicts: `REMOVABLE` (exit 0), `REMOVABLE AFTER KEEPING N FILES` (exit 1), +`NOT REMOVABLE` (exit 1). + +## Success Criteria + +- [ ] `codev check pr `, `codev check deploy …` and `codev check worktree ` exist, are listed in `codev --help`, and produce the sections and verdicts described in this spec. +- [ ] **Headline path verified end-to-end**: `codev check pr` is run against a real open PR in this repository (this project's own PR at minimum) and its output is recorded in the review; at least one run exercises the porch-only-head case and one exercises an attribution hit. +- [ ] **Read-only, enforced at runtime**: every subprocess the commands start goes through one runner that refuses (throws, exit 2) any git argv or forge concept not on the allow-list (§ Read-only enforcement). A unit test proves a non-allowed command is refused before it is spawned. +- [ ] **Read-only, enforced in tests**: the suite runs all three commands with stub `gh` and `git` executables first on `PATH`; each stub records its argv and fails the test on any invocation not on the read-only list (including `gh api` with a method other than GET or with field flags). +- [ ] **No state change, proven on a real repository**: a test builds a real git repository with a bare "remote", runs each command (including a conflicting trial merge and a run that must fetch missing objects), and asserts that the output of `git for-each-ref`, `HEAD`, the index file's bytes, `FETCH_HEAD`'s absence/contents, and `git status --porcelain` are identical before and after. +- [ ] **Live base**: when the local `origin/` is behind the remote, `check pr` trial-merges against the remote's current tip (test with a deliberately stale local ref). +- [ ] **Exact head**: every head-dependent result is computed for the head SHA the forge reports; if the forge's head SHA changes during the run, the verdict is attention with "head moved during check (old → new); re-run" (test). +- [ ] **Porch-only head**: with N porch-state-only commits above the last code commit, the last code commit is identified per § Porch-only heads, its runs are shown beside the head's, and the checks verdict is driven by them (tests for: runs only on head; runs only on an earlier code-equivalent commit; runs on neither; a failed run on either). +- [ ] **Never reported as passing**: for each forge-dependent check, a test with the concept disabled (`null`) and a test with the concept failing show that check as `not run: …` and exit 1 — never `ok`. +- [ ] **Exit codes**: 0 / 1 / 2 exactly as defined in § Output, each covered by a test per command; `--json` carries the same verdict as the human form. +- [ ] **`--json`** output for each command matches the documented schema (`schema: 1`), including on exit 2 (an `error` object on stdout). +- [ ] **Configuration**: each `check.*` key and the shared `cleanup.keepIgnored` changes behavior as specified; arrays replace defaults; an invalid value (wrong type, unparseable regex) exits 2 naming the key and the file it came from. +- [ ] **Forge contract**: `pr-view` gains the optional fields listed in § Forge; two new concepts `commit-checks` and `workflow-runs` exist with documented contracts; every shipped preset (github, gitlab, gitea; linear and jira fall through to github) either implements each new concept/field or explicitly disables it — `codev doctor` lists the new concepts. +- [ ] **Docs in both trees**: the architect role, `risk-triage.md`, the `codev` command reference and the `codev` skill change in both `codev/` and `codev-skeleton/`; `forge.md` documents the new concepts and fields; shipped skill hashes are regenerated. +- [ ] Full test suite passes; the on-demand Windows workflow is dispatched on the branch and linked in the PR (the commands spawn processes). + +## Constraints + +From the issue (fixed): + +- It never merges, approves, cleans up, deletes, pushes or comments. +- End-to-end usable: the headline path is "an architect runs one command on a builder's PR + and sees everything needed to recommend a merge, or the specific thing that blocks it". +- Server/client isolation (#1189) if any of it is exposed to the VS Code extension or the + dashboard. **This spec exposes nothing to either**: it is CLI-only. The `--json` form is the + integration surface; a future dashboard or extension view is a separate spec and would go + through Tower and `codev-types` like every other surface. +- Framework docs change in both `codev/` and `codev-skeleton/`. +- Fail fast, no fallbacks: a check that cannot run says so by name. It is never reported as + passing. + +From the codebase: + +- **Forge concept layer only.** PR and CI data come through forge concepts (`.codev/config.json` + `forge`, provider presets) — never a hard-coded `gh` call outside a concept script. +- **Git version.** The trial merge needs `git merge-tree --write-tree` (git ≥ 2.38); the + ref-neutral fetch needs `--no-write-fetch-head` (git ≥ 2.29). On an older git the dependent + checks are `not run: requires git 2.38+ (found X)`; nothing falls back to a mutating merge. +- **Remote.** Base and head are read from the remote `origin`, as `afx cleanup` and + `consult --type integration` already assume. No `origin` → exit 2. +- **Platform.** No shell for git (argv only); forge concepts run through the existing + dispatcher (Git Bash on native Windows). The PR touches process spawning, so the + on-demand Windows workflow runs on the branch. +- **Config layering.** Configuration uses the existing five-layer loader (defaults → cache → + `~/.codev/config.json` → `.codev/config.json` → `.codev/config.local.json`); arrays replace, + never concatenate. Note: in *this* repository `.codev/config.json` is gitignored, so the + owner's attribution rule belongs in `~/.codev/config.json` (it applies to all their + projects anyway) or the local config — not in a committed file. +- **Coordination with #1950.** The keep list for ignored files is `cleanup.keepIgnored` and + the never-copy list (dependency/build output) is #1950's. `check worktree` reads the same + definitions — one source of truth — whichever PR lands second adopts the first's. + +## Assumptions + +- A builder's PR head commit can be fetched by SHA from `origin` (true for GitHub and GitLab, + including fork PR heads on GitHub, which are reachable through `refs/pull/*`). Where it + cannot, the dependent checks say so. +- Porch writes its project state only under `codev/projects/` (status.yaml and review + artifacts); a commit touching nothing else is bookkeeping, not code. +- Builder worktrees share their object store with the main checkout, so a builder's local + commits are usually already present and no fetch is needed. +- `afx spawn` writes a known, enumerable set of scaffold files into a worktree + (`.builder-*`, the `.claude/hooks/` write guard, and the other generated files spawn + marks); that list is exported from spawn so `check worktree` and cleanup agree on it. +- Issue #1950 lands `cleanup.keepIgnored` and the never-copy list as described in its body. + +## Solution Approaches + +### Approach 1: `codev check` — a read-only subcommand group on the `codev` CLI (recommended) + +`codev check pr|deploy|worktree`, one noun with three objects. The noun is the issue's own +verb and says "read-only" on its face; the objects replace the adopter's jargon (`lane`) with +Codev's vocabulary (worktree, deploy). + +**Pros** +- `codev` is global and works from anywhere — the architect role already says so. Builders + can run `codev check pr ` on their own PR from inside their worktree before announcing + it, without breaking the "run `afx` only from the main workspace root" rule (that rule + exists because `afx spawn` nests builders; carving read-only exceptions into it erodes a + safety rule). +- Sits beside `codev doctor`, the other read-only diagnostic. +- No Tower dependency: works when Tower is down, in CI, and in a plain clone. +- Its own module with its own runner makes the allow-list provable over the whole command. + +**Cons** +- Architects think of builder lifecycle as `afx` (`afx status`, `afx cleanup`); the worktree + check lives one binary away from cleanup. +- Adds a config key named `check` next to porch's unrelated `porch.checks`. + +Risk/complexity: medium — mostly git plumbing and two new forge concepts. + +### Approach 2: `afx` subcommands (`afx check …`, or the adopter's `check`/`merged`/`lane`) + +**Pros:** next to `afx cleanup` and `afx status`; matches architects' mental model. +**Cons:** `afx` is the Agent Farm/Tower tool and is to be run only from the main workspace +root, so builders could not self-check; three new top-level `afx` verbs is three nouns, not +one; `lane` is jargon in Codev. Risk: low, but it puts a read-only tool in a binary whose +other verbs spawn, kill and delete. + +### Approach 3: Fold into existing commands + +`check pr` as a preamble of `consult --type integration`; `lane` as `afx cleanup --dry-run`. +**Cons:** `consult` costs model time and money and reviews *content* — mechanics should be +seconds and free, and must run even when no model review is warranted (low-risk PRs). A +`--dry-run` on cleanup shares a code path with `git worktree remove --force` and +`git branch -D`: one wrong branch in the flag handling and the "read-only" mode destroys +work, and the allow-list could not be enforced over the module. Rejected. + +### Approach 4: Ship the adopter's shell scripts in the skeleton + +**Cons:** no forge abstraction (GitHub-only), no JSON contract, no Windows, no tests that can +prove read-only. Rejected. + +### Decisions within the recommended approach + +#### `worktree` is a separate command, not cleanup's dry run + +For the reason above (no shared code path with destructive commands), and because the two +answer different questions: `check worktree` says *whether* removal loses anything; +`afx cleanup --keep-ignored` (#1950) *does* the removal and keeps what the keep list says. +They share the keep list and never-copy list, so `check worktree` reports exactly the files +`--keep-ignored` would keep. Cleanup's behavior is not changed by this spec. + +#### Read-only enforcement — how + +1. **One runner.** Every subprocess the commands start goes through a single runner that + receives an argv (never a shell string) and checks it against an allow-list *before* + spawning. A non-allowed argv throws; the command exits 2 naming it. There is no other + path to a subprocess in the command's code. +2. **Git allow-list** (subcommand plus required/forbidden flags): + `version`; `rev-parse`; `rev-list`; `merge-base`; `log`; `show`; `diff`, `diff-tree` + (output only — no `--output`); `cat-file`; `for-each-ref`; `ls-files`; `ls-remote`; + `check-attr`; `worktree list`; `config --get`/`--get-regexp`; `symbolic-ref` with one + argument (the read form); `status` only with the global `--no-optional-locks` flag (a + plain `git status` may rewrite the index's stat cache); `merge-tree` only with + `--write-tree`; `fetch` only in the ref-neutral form below. +3. **Forge allow-list**: the commands invoke only the read concepts `pr-view`, `pr-search`, + `commit-checks` and `workflow-runs`. `pr-merge`, `pr-create`, `issue-comment` and every + other concept are refused by the runner. The shipped github preset scripts for these + concepts call only `gh pr view`, `gh pr list`, `gh run list` and `gh api` with GET. + *Limit, stated honestly*: a project's own concept override is a script Codev does not + control; the runner governs which concepts are called, not what a hand-written override + does inside — the same trust Codev extends to overrides everywhere. +4. **Tests** put stub `gh` and `git` executables first on `PATH`. Each records its argv and + fails the test on anything outside the read-only list (for `gh api`: any `-X`/`--method` + other than GET, any `-f`/`-F`/`--field`/`--raw-field`/`--input`). A separate real-git + test proves no ref, index, worktree or `FETCH_HEAD` change. + +#### The trial merge moves no ref — how + +1. **Live tips, read without moving refs.** The base tip is read with + `git ls-remote origin refs/heads/`; the head SHA comes from the forge (`pr-view`). + The local `origin/` is never trusted — it is usually stale. +2. **Objects only.** If either commit is missing from the local object store, it is fetched + with + `git -c gc.auto=0 -c maintenance.auto=false fetch --no-write-fetch-head --refmap= origin …`. + `--refmap=` (empty) disables the opportunistic update of remote-tracking refs, and + `--no-write-fetch-head` suppresses `FETCH_HEAD`; with both, the fetch adds objects and + moves no ref. Disabling auto-gc keeps the run from triggering housekeeping. (Verified on + git 2.50: refs and `FETCH_HEAD` unchanged, objects present.) If the fetch fails, every + check that needs the commit is `not run: not available locally ()`. +3. **Merge in the object store.** + `git merge-tree --write-tree --name-only --no-messages ` computes the + merge without touching `HEAD`, any ref, the index or the working tree; exit 1 plus a file + list means conflicts. It writes the result's tree and blob objects into the object + store; they are unreachable and are collected by normal gc. That is the only write any + command performs, and it is stated in the docs. + +#### Forge — what each check needs, and what happens without it + +| Check | From the forge | Concept | When the forge cannot provide it | +|---|---|---|---| +| head SHA (anchors everything) | PR head SHA | `pr-view` field `headRefOid` | **exit 2**: "pr-view did not return headRefOid (provider X / override in )". Nothing is reported against a guessed head. | +| state, draft, title, description | PR metadata | `pr-view` (`state`, `body`, new `isDraft`) | the missing field's line is `not run` | +| forge mergeability | the forge's own verdict | `pr-view` new `mergeable`, `mergeStateStatus` | `not run` (the local trial merge still runs) | +| attribution, size, overlap, trial merge, watched, to read | nothing — computed locally on the exact head SHA | — | — | +| checks (head and code commit) | check results for a given commit | new **`commit-checks`** (`CODEV_COMMIT_SHA` → `[{name, state, url?, workflow?}]`, `state` normalized to `pass`/`fail`/`pending`/`skipped`/`neutral`) | `not run: commit-checks unavailable on ` | +| deploy: merged, merge commit | merge state and commit | `pr-view` new `mergeCommit`, `mergedAt` | `not run` for that PR | +| deploy: latest green run | runs of a named workflow on a branch | new **`workflow-runs`** (`CODEV_WORKFLOW`, `CODEV_BRANCH` → `[{headSha, status, conclusion, url, createdAt}]`, newest first) | `not run: workflow-runs unavailable on ` | +| worktree: the branch's PR | PR for a head branch, and its state | `pr-search` (existing) | `info: PR state not available` — the git facts alone decide, conservatively | + +The new `pr-view` fields are optional in the contract (additive; existing consumers are +unaffected). The github preset implements everything. The gitlab and gitea presets either +implement each new field/concept from their CLI's output or explicitly disable it (`null`); +none is left silently absent. The hybrid providers (linear, jira) keep their PR concepts on +the github default and so get GitHub behavior. + +A concept that is disabled or fails is a `not run` (attention, exit 1), never `ok`. A +project that knowingly lacks something — no CI, or a forge without workflow runs — says so +with `check.skip` (below); the check then shows as `skip (config)` by name. + +#### What is configurable, and where + +All under `.codev/config.json` (and the other config layers), key `check`, except the keep +list, which is #1950's `cleanup.keepIgnored`. + +| Key | Meaning | Default | +|---|---|---| +| `check.attribution` | Regexes (JavaScript syntax, case-insensitive, matched per line) for forbidden attribution in the PR description and every commit message not already on the base | `[]` — **off**, shown as `off: no patterns configured (check.attribution)`. See Open Question 2. | +| `check.watch` | Globs of files whose movement is always listed | the agent-instruction surface: `CLAUDE.md`, `AGENTS.md`, `.codev/**`, `.claude/**`, `codev/roles/**`, `codev/protocols/**`, `codev/templates/**`, `codev/resources/arch-critical.md`, `codev/resources/lessons-critical.md` | +| `check.flag` | Globs, a subset of what you watch, whose movement needs attention | `[]` | +| `check.notForReading` | Globs excluded from "files a person still has to read" | see below | +| `check.deploy.branch` | Deploy branch for `check deploy` | the PR's base branch | +| `check.deploy.workflow` | Workflow (file name or name) whose latest green run on the deploy branch must contain the merge | unset → `deploy run` is `off`; `merge checks` is reported instead | +| `check.skip` | Check ids to skip by declaration (e.g. `["checks"]` on a project with no CI) | `[]` | +| `cleanup.keepIgnored` | (#1950) ignored-file globs worth keeping | #1950's default: `codev/projects/**`, `codev/state/**`, `.builder-*`, `tmp/**`, `scratch/**` | + +Watched files are diffed directly from git (merge-base → head); no hash file is needed, +because git already knows exactly which files moved. + +#### "Files a person still has to read" + +The files the PR changes (merge-base → head, i.e. what the forge's diff view shows) minus: + +1. files matching `check.notForReading` — default: `codev/projects/**` (porch state and + review artifacts), `codev/state/**` (thread logs and architect state), and lockfiles + (`**/pnpm-lock.yaml`, `**/package-lock.json`, `**/yarn.lock`, `**/Cargo.lock`, + `**/poetry.lock`, `**/uv.lock`, `**/go.sum`, `**/Gemfile.lock`, `**/composer.lock`); +2. files the project marks generated in `.gitattributes` with `linguist-generated` (read with + `git check-attr`, at the head commit) — the same marker the forge uses to collapse them + in its diff view. + +A project changes the rule by setting `check.notForReading` (replaces the default list) or by +marking files `linguist-generated`. The summary shows the count of files to read and of files +excluded, and lists the files to read (largest first, truncated to fit); `--json` lists all +of them with their line counts. + +#### Porch-only heads — finding the last code commit + +- A commit is **porch-only** when every path it changes relative to its first parent is under + `codev/projects/`. Merge commits (e.g. main merged into the branch) are never porch-only. +- The **last code commit** C is the first commit that is not porch-only, walking the head's + first-parent chain from head back to the merge-base. +- Every commit from C to head has the same code; they differ only in porch state. The + **code runs** are those on the newest commit in that range (head included) that has any + check result — normally the tip of the push that carried C. +- Display: when head = C, or when head itself carries the code runs, one `checks` line. + Otherwise two lines: `code : …` and `head : …` with the count of + porch-state commits above the code (sample above). +- Verdict: `ok` only when the code runs exist and all passed (skipped/neutral count as + passed) and nothing on head failed or is pending. Any failure or pending run on either + commit is attention. No runs anywhere in C..head is attention ("no checks ran on this + code"). The walk and the per-commit lookups are bounded (at most 10 commits queried); + beyond the bound the check is `not run: more than 10 porch-only commits`. + +#### Output and exit codes + +- **Human form**: first line is the verdict and the names of what needs attention; then a + header (PR / head / base, or worktree / branch / base); then one line per check with a + status word — `ok`, `ATTN`, `info`, `not run`, `off`, `skip`. Fits one screen for a typical + PR; long lists are truncated with a count. +- **Statuses**: `ok`; `attention` (blocks a recommendation, or the project flagged it); + `info` (worth knowing, never changes the verdict: size, overlap, to-read, unflagged watched + files); `not run` (could not run — always counts as attention); `off` (no configuration + for it); `skip` (declared skipped in `check.skip`). +- **Exit codes**: `0` = clear (no attention, no not-run); `1` = something needs attention, + including any check that could not run; `2` = the command failed and produced no report + (usage error, not in a git repository, no `origin`, PR not found, forge auth failure on + the anchoring `pr-view`, invalid configuration, head SHA unavailable, or the runner + refused a command). +- **`--json`**: one object on stdout, `schema: 1`, with `command`, `verdict` + (`clear`/`attention`), the target (PR, PRs, or worktree), and `checks: [{id, status, + summary, details}]`; on exit 2, `{schema: 1, command, error: {message, cause}}`. Human + output goes to stdout only without `--json`; diagnostics go to stderr. +- **Check ids** — `pr`: `head`, `state`, `forge`, `attribution`, `trial-merge`, `checks`, + `watched`, `overlap`, `size`, `to-read`. `deploy` (per PR): `merged`, `on-branch`, + `deploy-run`, `merge-checks`. `worktree`: `uncommitted`, `commits`, `remote`, `ignored`. +- **What counts as attention, per check**: head moved during the run; PR not OPEN, or draft; + forge mergeability other than its clean state (`UNKNOWN` included — reported as "forge has + not computed mergeability yet", and the plan may re-read once); any attribution hit; any + trial-merge conflict; checks per the porch-only rule; a flagged watched file moved. + +#### `check worktree` — what "removable" means + +"Removable" means **removing it loses nothing**, not merely that `git worktree remove` would +not need `--force` (the scaffold files alone make plain `git worktree remove` refuse on every +builder worktree). The check reports: + +- **uncommitted** — staged, unstaged and untracked-not-ignored files (via + `git --no-optional-locks status`), excluding spawn's scaffold files, which are counted + separately and never block; +- **commits** — commits on the branch not reachable from the live remote base tip (read with + `ls-remote`; objects fetched ref-neutrally if missing). When some are not on the base, the + branch's PR state is looked up (`pr-search`): merged with differing commits (a squash or + rebase merge) is attention with that explanation; otherwise they are unmerged work; +- **remote** — local branch vs `origin/` via `ls-remote`: matches / local ahead + (unpushed) / behind / diverged / no remote branch (fine when every commit is on the base); +- **ignored** — ignored files matching `cleanup.keepIgnored` and not on the never-copy list: + these are deleted silently by any removal, forced or not. + +Verdict: `NOT REMOVABLE` when there are uncommitted files, or commits that exist neither on +the base nor on the remote branch, or the PR is still open; `REMOVABLE AFTER KEEPING N FILES` +when only keep-list ignored files stand in the way; otherwise `REMOVABLE`. The argument is a +builder id (resolved to `/.builders/` and confirmed against +`git worktree list`) or a path to a registered worktree. + +#### Relation to existing tools and guidance + +- **`consult --type integration`** reviews *content* with a model; `codev check pr` checks + *merge mechanics* in seconds, for free. Order: `codev check pr` first (its size line is + risk-triage Step 1, and a blocker found here makes a model review premature), then the + integration review at the depth the risk tier calls for. +- **Architect role** (both trees): the integration-review section tells the architect to run + `codev check pr ` before choosing review depth and before bringing a merge word to the + owner, and to put its verdict line in the PRFT **Testing** paragraph; the closing-the-loop + guidance tells them to run `codev check worktree ` before `afx cleanup`, and + `codev check deploy ` where the project deploys. +- **`risk-triage.md`** (both trees): Step 1 becomes `codev check pr ` (size and file + count), keeping the raw `gh` commands as what it reads. +- **`pr` gate guidance**: the gate notification itself is not changed by this spec (see Open + Question 3); the architect role is where the instruction lives. +- **Builder role**: unchanged by this spec (see Open Question 4). + +## Open Questions + +**Critical** (blocks progress) +- None. Every question the issue lists is decided above; the items below are choices the + owner may want to overrule at spec approval. + +**Important** (shapes design) +1. **Placement: `codev check` (recommended) vs `afx`.** The recommendation rests on builders + being able to run it from their worktree and on `afx`'s "main workspace root only" rule. + If the owner prefers it under `afx` next to `cleanup`, the design is otherwise unchanged. +2. **Attribution default: off (recommended) vs AI-attribution patterns on by default.** + Attribution policy differs by organization — some *require* AI attribution — so Codev + should not impose one; the check is visibly `off` until configured, and the owner's rule + goes in `~/.codev/config.json` (`["^\\s*Co-Authored-By:", "Generated with \\[Claude Code\\]"]`). + Alternative: ship default patterns for AI-tool trailers (`Co-Authored-By: … Claude|Codex| + Gemini|Copilot`, `Generated with [Claude Code]`) and let projects that want them set `[]`. +3. **Should porch's `pr` gate notification name the command** (e.g. "run `codev check pr N`")? + Recommended: not in this spec — the architect role carries the instruction, and gate + message text is porch's surface. A one-line follow-up if wanted. +4. **Should builders be told to run `codev check pr ` before announcing "PR ready"?** + It is possible by design (Approach 1). Recommended: leave the builder role unchanged here + and decide after architects have used it. + +**Nice-to-know** (optimization) +5. `codev check pr` with no number inferring the PR from the current branch. +6. `check worktree` also showing the porch phase/gate (e.g. "verify-approval still pending"). +7. `check deploy` also reporting whether the PR's linked issue is closed (the architect + role's "closing the loop"). +8. Running `codev check pr` as a porch check in the Review phase. + +## Test Scenarios + +**`check pr` — functional** +1. Clean PR, all runs green on head → `CLEAR`, exit 0, every check `ok`/`info`/`off`. +2. Trial merge conflicts → `trial-merge` attention listing the conflicted files and their count; refs/index/worktree unchanged. +3. Local `origin/main` stale, remote main has a conflicting commit → conflict found (live base used). +4. Head object not local → ref-neutral fetch, then results; `FETCH_HEAD` and refs unchanged. +5. Head object cannot be fetched → head-dependent checks `not run`, exit 1. +6. Attribution hit in a commit message and in the description → both reported with location; commits already on base are not scanned. +7. Porch-only head with runs only on the code commit; only on head; on a push tip between them; on none; failure on head while code commit green → displays and verdicts per § Porch-only heads. +8. Flagged watched file moved → attention; unflagged watched → info. +9. `.gitattributes` `linguist-generated` file and lockfile excluded from "to read"; `check.notForReading` replaces the default. +10. Draft PR, closed PR, merged PR → `state` attention. +11. Forge head SHA changes between start and end of run → attention "head moved". +12. Local builder branch ahead of the PR head → `head` attention ("not pushed"). + +**`check deploy`** +13. Merged, on deploy branch, inside latest green run → `ok`; not on branch → attention; on branch but newer than latest green run → attention. +14. No `check.deploy` → base branch used; `merge-checks` reported; `deploy-run` `off`. +15. PR not merged → `merged` attention; several PRs → verdict is the worst. + +**`check worktree`** +16. Clean, merged (`--merge`), remote branch deleted → `REMOVABLE`. +17. Modified thread file → `NOT REMOVABLE`; only scaffold files untracked → not counted. +18. Unpushed commit not on base → `NOT REMOVABLE`. +19. Squash-merged PR (commits not on base, PR merged) → attention with explanation. +20. Keep-list ignored files present; never-copy paths (`node_modules/`) excluded → `REMOVABLE AFTER KEEPING N FILES`. +21. Builder id not found / path not a registered worktree → exit 2. + +**Read-only and errors (all commands)** +22. Stub `gh`/`git` on `PATH`: every invocation in scenarios above is on the read-only list; a deliberately injected `git update-ref` / `gh pr merge` / `gh api -X POST` is refused by the runner and caught by the stub. +23. Real-repo snapshot test (refs, `HEAD`, index bytes, `FETCH_HEAD`, `status`) identical before/after each command. +24. Concept disabled (`null`) and concept failing → `not run: …`, exit 1, never `ok`. +25. `pr-view` override without `headRefOid` → exit 2 naming the concept and field. +26. Invalid config (non-array `check.watch`, bad regex) → exit 2 naming key and file. +27. git older than 2.38 (stubbed `git version`) → trial merge `not run: requires git 2.38+`. +28. `--json` for every scenario parses and matches the schema; exit 2 emits the `error` object. + +**Non-functional** +29. A 25-file PR with a 3-commit porch tail completes in under 30 s against GitHub on a normal connection (the forge calls dominate). +30. The human summary for scenario 1 fits in 25 lines. + +## Risks and Mitigation + +| Risk | Probability | Impact | Mitigation | +|------|-------------|--------|------------| +| A mutating git command slips into the code path | Low | High | Single argv runner with allow-list (refuses before spawn); stubbed-`PATH` tests; real-repo snapshot test | +| GitHub reports `mergeable: UNKNOWN` right after a push, so `check pr` often says attention | Medium | Low | Reported in plain words ("not computed yet"); the plan may re-read once; local trial merge is authoritative for conflicts | +| Fetch by SHA refused by a server | Low | Medium | Dependent checks `not run` with the git error; the architect can `git fetch` and re-run | +| Forge presets other than GitHub lack per-commit checks / workflow runs | High | Medium | Each preset implements or explicitly disables; disabled shows `not run` by name; `check.skip` lets a project acknowledge it | +| Older git (< 2.38) on adopter machines | Medium | Medium | Trial merge `not run` naming the version; `codev doctor` reports git version | +| Users read `info` lines as passes, or exit 1 becomes routine noise | Medium | Medium | `info` never claims a pass; `not run` and `off` are spelled out; `check.skip` exists so a project can make exit 0 meaningful for itself | +| `cleanup.keepIgnored` definition diverges between #1950 and this spec | Medium | Medium | One shared definition; whichever PR lands second reuses the first's; a test asserts `check worktree` lists exactly what `--keep-ignored` would keep | +| A project's own concept override performs writes | Low | Medium | Documented limit: the runner governs which concepts are called; overrides are trusted as elsewhere in Codev | +| Unreachable objects from `merge-tree`/fetch accumulate | Low | Low | Collected by normal `git gc`; documented as the only write | + +## References + +- Issue #1951 (this spec) and issue #1950 (`afx cleanup --keep-ignored`, in flight as `air-1950`) +- Spec 589 — non-GitHub repository support (forge concept layer); `codev/resources/commands/forge.md` +- `codev/roles/architect.md` — integration review, PRFT, boundaries (identical in `codev-skeleton/`) +- `codev/resources/risk-triage.md` — Step 1 size assessment (also in `codev-skeleton/`) +- `consult --type integration` and `consult.integrationBranch` (#1113) — `codev/resources/commands/consult.md` +- Issue #1189 — server/client isolation (not engaged: CLI only) +- git documentation: `git merge-tree --write-tree` (2.38+), `git fetch --refmap`, `--no-write-fetch-head` (2.29+), `git --no-optional-locks` diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md new file mode 100644 index 000000000..d2639f5dc --- /dev/null +++ b/codev/state/spir-1951_thread.md @@ -0,0 +1,14 @@ +# spir-1951 thread — read-only PR check (`codev check`) + +## 2026-11-23 — specify +- No spec existed; issue #1951 has no Baked Decisions. Drafted spec from scratch. +- Recommended placement: `codev check pr|deploy|worktree` (not `afx`): codev runs from anywhere, + so builders can self-check without breaking the "afx only from main root" rule. +- `worktree` (the adopter's `lane`) is a separate command, not `afx cleanup --dry-run`: no shared + code path with `worktree remove --force` / `branch -D`. Shares `cleanup.keepIgnored` with #1950 + (in flight as air-1950). +- Verified in a scratch repo (git 2.50): `git fetch --no-write-fetch-head --refmap= origin ` + moves no ref and writes no FETCH_HEAD; `git merge-tree --write-tree` leaves refs + index untouched. +- Verified: 361 commits on origin/main since 2026-06-01 carry Co-Authored-By. +- Surprise: this repo gitignores `.codev/config.json`, so the owner's attribution rule must live in + `~/.codev/config.json` or the local layer — attribution check proposed off by default. From 93da5f35e0147047f37256edd8dcad7b8564af55 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 11:04:16 -0800 Subject: [PATCH 03/94] chore(porch): 1951 specify build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index bbbbe31ab..a7b6cb7ce 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -14,7 +14,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T18:53:58.203Z' +updated_at: '2026-11-23T19:04:16.165Z' From 3e1f34edfdad2c39838caf8e155977f7bb52acd4 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 11:11:19 -0800 Subject: [PATCH 04/94] [Spec 1951] Specification with multi-agent review --- .../1951-read-only-pr-check-for-archite.md | 303 +++++++++++++----- codev/state/spir-1951_thread.md | 12 + 2 files changed, 239 insertions(+), 76 deletions(-) diff --git a/codev/specs/1951-read-only-pr-check-for-archite.md b/codev/specs/1951-read-only-pr-check-for-archite.md index 89b58b6a6..e96c1cf0a 100644 --- a/codev/specs/1951-read-only-pr-check-for-archite.md +++ b/codev/specs/1951-read-only-pr-check-for-archite.md @@ -97,6 +97,7 @@ head a1b2c3d (local builder/spir-1951 matches) base main @ 7c0f3ab (orig ATTN checks code 57d2ec5: 7 passed, 1 failed (test.yml / unit) head a1b2c3d: no runs — 3 porch-state commits above the code ATTN watched CLAUDE.md (flagged); codev/roles/architect.md + info linked issue "Fixes #1951" — matches builder/spir-1951 info overlap 2 files also changed on main since branch point: CHANGELOG.md, packages/codev/src/cli.ts info size +1,204 −88 in 23 files info to read 14 files (9 not for reading): packages/codev/src/commands/check/pr.ts, … +12 @@ -142,13 +143,16 @@ NOT REMOVABLE spir-1951 — 1 uncommitted file worktree .builders/spir-1951 branch builder/spir-1951 base main @ 7c0f3ab (origin, live) ATTN uncommitted 1 file: codev/state/spir-1951_thread.md (modified) [5 scaffold files not counted] ok commits all 31 commits are on origin/main - ok remote origin/builder/spir-1951 matches local (a1b2c3d); PR #1957 MERGED + ok remote origin/builder/spir-1951 matches local (a1b2c3d) + ok pr #1957 MERGED ATTN ignored 3 keep-list files would be lost: codev/projects/1951-…/1951-specify-iter1-codex.txt, … +2 + (1,204 other ignored files treated as regenerable: node_modules/, dist/, …) → copy them out first, or use `afx cleanup --keep-ignored` (#1950) ``` -Verdicts: `REMOVABLE` (exit 0), `REMOVABLE AFTER KEEPING N FILES` (exit 1), -`NOT REMOVABLE` (exit 1). +Verdicts describe **data** only: `REMOVABLE`, `REMOVABLE AFTER KEEPING N FILES`, +`NOT REMOVABLE`. Exit 0 only for `REMOVABLE` with nothing else needing attention (an open PR +is attention even when no data would be lost). Exit 1 otherwise. ## Success Criteria @@ -158,14 +162,16 @@ Verdicts: `REMOVABLE` (exit 0), `REMOVABLE AFTER KEEPING N FILES` (exit 1), - [ ] **Read-only, enforced in tests**: the suite runs all three commands with stub `gh` and `git` executables first on `PATH`; each stub records its argv and fails the test on any invocation not on the read-only list (including `gh api` with a method other than GET or with field flags). - [ ] **No state change, proven on a real repository**: a test builds a real git repository with a bare "remote", runs each command (including a conflicting trial merge and a run that must fetch missing objects), and asserts that the output of `git for-each-ref`, `HEAD`, the index file's bytes, `FETCH_HEAD`'s absence/contents, and `git status --porcelain` are identical before and after. - [ ] **Live base**: when the local `origin/` is behind the remote, `check pr` trial-merges against the remote's current tip (test with a deliberately stale local ref). -- [ ] **Exact head**: every head-dependent result is computed for the head SHA the forge reports; if the forge's head SHA changes during the run, the verdict is attention with "head moved during check (old → new); re-run" (test). +- [ ] **Exact head, live base, no race**: every head-dependent result is computed for the head SHA the forge reports and every base-dependent result for the base tip `ls-remote` reports; both are re-read when the checks finish, and if either moved the verdict is attention with "head|base moved during check (old → new); re-run" (a test for each). +- [ ] **Bounded time**: every forge call and every networked git call (`ls-remote`, `fetch`) has a timeout; a call that times out makes its check `not run: timed out after Ns` (exit 1), or exit 2 when it is the anchoring `pr-view` (test with a stub that hangs). - [ ] **Porch-only head**: with N porch-state-only commits above the last code commit, the last code commit is identified per § Porch-only heads, its runs are shown beside the head's, and the checks verdict is driven by them (tests for: runs only on head; runs only on an earlier code-equivalent commit; runs on neither; a failed run on either). - [ ] **Never reported as passing**: for each forge-dependent check, a test with the concept disabled (`null`) and a test with the concept failing show that check as `not run: …` and exit 1 — never `ok`. -- [ ] **Exit codes**: 0 / 1 / 2 exactly as defined in § Output, each covered by a test per command; `--json` carries the same verdict as the human form. -- [ ] **`--json`** output for each command matches the documented schema (`schema: 1`), including on exit 2 (an `error` object on stdout). +- [ ] **Exit codes**: 0 / 1 / 2 exactly as defined in § Output, each covered by a test per command; `--json` carries the same verdict as the human form. For `check deploy` with several PRs, one PR that cannot be read is a per-PR `not run` (exit 1) and the others are still reported. +- [ ] **`--json`** output for each command matches the schema in § JSON schema (`schema: 1`), including on exit 2 (an `error` object on stdout). +- [ ] **Input validation**: PR numbers, SHAs and config values are validated before any subprocess runs (§ Input validation); a violation exits 2 naming the value. - [ ] **Configuration**: each `check.*` key and the shared `cleanup.keepIgnored` changes behavior as specified; arrays replace defaults; an invalid value (wrong type, unparseable regex) exits 2 naming the key and the file it came from. - [ ] **Forge contract**: `pr-view` gains the optional fields listed in § Forge; two new concepts `commit-checks` and `workflow-runs` exist with documented contracts; every shipped preset (github, gitlab, gitea; linear and jira fall through to github) either implements each new concept/field or explicitly disables it — `codev doctor` lists the new concepts. -- [ ] **Docs in both trees**: the architect role, `risk-triage.md`, the `codev` command reference and the `codev` skill change in both `codev/` and `codev-skeleton/`; `forge.md` documents the new concepts and fields; shipped skill hashes are regenerated. +- [ ] **Docs in both trees**: the architect role, `risk-triage.md` and the `codev` command reference change in both `codev/` and `codev-skeleton/`; the `codev` skill changes in all four of its copies (`.claude/skills/codev/`, `.codex/skills/codev/`, `codev-skeleton/.claude/skills/codev/`, `codev-skeleton/.codex/skills/codev/`) and the shipped skill hashes are regenerated (`generate-shipped-skill-hashes`); `forge.md` documents the new concepts and fields. - [ ] Full test suite passes; the on-demand Windows workflow is dispatched on the branch and linked in the PR (the commands spawn processes). ## Constraints @@ -202,7 +208,7 @@ From the codebase: projects anyway) or the local config — not in a committed file. - **Coordination with #1950.** The keep list for ignored files is `cleanup.keepIgnored` and the never-copy list (dependency/build output) is #1950's. `check worktree` reads the same - definitions — one source of truth — whichever PR lands second adopts the first's. + definitions — one source of truth. See Assumptions for the order-of-landing rule. ## Assumptions @@ -217,6 +223,14 @@ From the codebase: (`.builder-*`, the `.claude/hooks/` write guard, and the other generated files spawn marks); that list is exported from spawn so `check worktree` and cleanup agree on it. - Issue #1950 lands `cleanup.keepIgnored` and the never-copy list as described in its body. + **If #1950 has not merged when this is implemented**, this project defines + `cleanup.keepIgnored` (with #1950's defaults) and the never-copy list in one shared place + that cleanup can import, and #1950 adopts it; whichever PR lands second adds the test that + `check worktree` reports exactly the files `afx cleanup --keep-ignored` would keep. This + project is not blocked on #1950. +- A builder branch named `builder/-` belongs to issue `` (the `afx spawn` + convention); the linked-issue check uses that, and says nothing about branches that do not + follow it. ## Solution Approaches @@ -284,22 +298,37 @@ They share the keep list and never-copy list, so `check worktree` reports exactl 2. **Git allow-list** (subcommand plus required/forbidden flags): `version`; `rev-parse`; `rev-list`; `merge-base`; `log`; `show`; `diff`, `diff-tree` (output only — no `--output`); `cat-file`; `for-each-ref`; `ls-files`; `ls-remote`; - `check-attr`; `worktree list`; `config --get`/`--get-regexp`; `symbolic-ref` with one - argument (the read form); `status` only with the global `--no-optional-locks` flag (a - plain `git status` may rewrite the index's stat cache); `merge-tree` only with - `--write-tree`; `fetch` only in the ref-neutral form below. + `worktree list`; `config --get`/`--get-regexp`; `symbolic-ref` with one argument (the + read form); `status` only with the global `--no-optional-locks` flag (a plain + `git status` may rewrite the index's stat cache); `merge-tree` only with `--write-tree`; + `fetch` only in the ref-neutral form below. 3. **Forge allow-list**: the commands invoke only the read concepts `pr-view`, `pr-search`, `commit-checks` and `workflow-runs`. `pr-merge`, `pr-create`, `issue-comment` and every - other concept are refused by the runner. The shipped github preset scripts for these - concepts call only `gh pr view`, `gh pr list`, `gh run list` and `gh api` with GET. - *Limit, stated honestly*: a project's own concept override is a script Codev does not - control; the runner governs which concepts are called, not what a hand-written override - does inside — the same trust Codev extends to overrides everywhere. -4. **Tests** put stub `gh` and `git` executables first on `PATH`. Each records its argv and + other concept are refused by the runner. +4. **The trust boundary, stated precisely.** Runtime enforcement covers (a) every git argv + the commands run themselves and (b) *which* forge concepts they invoke. A concept is a + script the existing dispatcher runs through a shell, and the commands inside it are not + validated at runtime. For the **shipped** preset scripts of these four concepts, that gap + is closed by tests and review: the github scripts may call only `gh pr view`, + `gh pr list`, `gh run list` and `gh api` with GET, and the stub-`PATH` tests below see + every call they make. A project's **own** concept override is trusted, as Codev trusts + overrides everywhere; the docs say so. +5. **Tests** put stub `gh` and `git` executables first on `PATH`. Each records its argv and fails the test on anything outside the read-only list (for `gh api`: any `-X`/`--method` other than GET, any `-f`/`-F`/`--field`/`--raw-field`/`--input`). A separate real-git test proves no ref, index, worktree or `FETCH_HEAD` change. +#### Input validation + +Before any subprocess runs: a PR number must be a positive integer; a SHA must be 7–40 hex +characters; a builder id must match the ids `afx spawn` creates and a path must be a +registered worktree; config strings passed to git or a concept (`check.deploy.branch`, +`check.deploy.workflow`) may not begin with `-` and may not contain control characters. +Any violation exits 2 naming the value and, for config, the file it came from. +`check.attribution` patterns are trusted configuration; they are compiled once, rejected +when they do not parse (exit 2), and applied per line, which bounds the input any one match +sees. + #### The trial merge moves no ref — how 1. **Live tips, read without moving refs.** The base tip is read with @@ -316,22 +345,29 @@ They share the keep list and never-copy list, so `check worktree` reports exactl 3. **Merge in the object store.** `git merge-tree --write-tree --name-only --no-messages ` computes the merge without touching `HEAD`, any ref, the index or the working tree; exit 1 plus a file - list means conflicts. It writes the result's tree and blob objects into the object - store; they are unreachable and are collected by normal gc. That is the only write any - command performs, and it is stated in the docs. + list means conflicts. +4. **No race.** When every check has finished, the base tip (`ls-remote`) and the head SHA + (`pr-view`) are read again. If either moved, the verdict is attention: "base|head moved + during check (old → new); re-run". A `CLEAR` therefore always describes the tips that + were live when the command finished. + +**The only writes** any `codev check` command makes are additions to the object store: the +packs a ref-neutral fetch downloads, and the tree and blob objects `merge-tree` writes for +its result (unreachable, collected by normal gc). No ref, `HEAD`, index, working-tree file +or `FETCH_HEAD` is created, changed or removed. The docs say exactly this. #### Forge — what each check needs, and what happens without it | Check | From the forge | Concept | When the forge cannot provide it | |---|---|---|---| | head SHA (anchors everything) | PR head SHA | `pr-view` field `headRefOid` | **exit 2**: "pr-view did not return headRefOid (provider X / override in )". Nothing is reported against a guessed head. | -| state, draft, title, description | PR metadata | `pr-view` (`state`, `body`, new `isDraft`) | the missing field's line is `not run` | +| state, draft, title, description, linked issue | PR metadata | `pr-view` (`state`, `body`, `headRefName`, new `isDraft`) | the missing field's line is `not run` | | forge mergeability | the forge's own verdict | `pr-view` new `mergeable`, `mergeStateStatus` | `not run` (the local trial merge still runs) | | attribution, size, overlap, trial merge, watched, to read | nothing — computed locally on the exact head SHA | — | — | | checks (head and code commit) | check results for a given commit | new **`commit-checks`** (`CODEV_COMMIT_SHA` → `[{name, state, url?, workflow?}]`, `state` normalized to `pass`/`fail`/`pending`/`skipped`/`neutral`) | `not run: commit-checks unavailable on ` | | deploy: merged, merge commit | merge state and commit | `pr-view` new `mergeCommit`, `mergedAt` | `not run` for that PR | | deploy: latest green run | runs of a named workflow on a branch | new **`workflow-runs`** (`CODEV_WORKFLOW`, `CODEV_BRANCH` → `[{headSha, status, conclusion, url, createdAt}]`, newest first) | `not run: workflow-runs unavailable on ` | -| worktree: the branch's PR | PR for a head branch, and its state | `pr-search` (existing) | `info: PR state not available` — the git facts alone decide, conservatively | +| worktree: the branch's PR | PR for a head branch, its state, and (when merged) its head SHA | `pr-search` (existing), then `pr-view` | `not run: PR state not available` — the git facts alone decide the data verdict, conservatively | The new `pr-view` fields are optional in the contract (additive; existing consumers are unaffected). The github preset implements everything. The gitlab and gitea presets either @@ -364,20 +400,29 @@ because git already knows exactly which files moved. #### "Files a person still has to read" -The files the PR changes (merge-base → head, i.e. what the forge's diff view shows) minus: - -1. files matching `check.notForReading` — default: `codev/projects/**` (porch state and - review artifacts), `codev/state/**` (thread logs and architect state), and lockfiles - (`**/pnpm-lock.yaml`, `**/package-lock.json`, `**/yarn.lock`, `**/Cargo.lock`, - `**/poetry.lock`, `**/uv.lock`, `**/go.sum`, `**/Gemfile.lock`, `**/composer.lock`); -2. files the project marks generated in `.gitattributes` with `linguist-generated` (read with - `git check-attr`, at the head commit) — the same marker the forge uses to collapse them - in its diff view. - -A project changes the rule by setting `check.notForReading` (replaces the default list) or by -marking files `linguist-generated`. The summary shows the count of files to read and of files -excluded, and lists the files to read (largest first, truncated to fit); `--json` lists all -of them with their line counts. +The files the PR changes (merge-base → head, i.e. what the forge's diff view shows) minus the +files matching `check.notForReading`. Default: `codev/projects/**` (porch state and review +artifacts), `codev/state/**` (thread logs and architect state), and lockfiles +(`**/pnpm-lock.yaml`, `**/package-lock.json`, `**/yarn.lock`, `**/Cargo.lock`, +`**/poetry.lock`, `**/uv.lock`, `**/go.sum`, `**/Gemfile.lock`, `**/composer.lock`). + +A project changes the rule by setting `check.notForReading`, which replaces the default list — +e.g. adding its generated files (`packages/*/dist/**`, a generated hash table). The rule is +deliberately globs only: honoring `.gitattributes`' `linguist-generated` *as of the head +commit* needs `git check-attr --source` (git ≥ 2.40), and reading it from the architect's +working tree would apply the wrong attributes to a PR that changes them. The summary shows +the count of files to read and of files excluded, and lists the files to read (largest first, +truncated to fit); `--json` lists all of them with their line counts. + +#### Linked issue + +The architect role requires that the issue closes when the PR merges. `check pr` reads the +PR description for a closing keyword (`Fixes`, `Closes`, `Resolves` and their inflections, +followed by `#`, the forms Codev's views already recognize). Result: `info` naming the +keyword and the issue when one is present and, for a `builder/-` branch, it +names that ``; `info` "no closing keyword — close # by hand after merge" when none is +present (a partial fix legitimately has none); **attention** when the keyword names a +different issue than the branch's id. #### Porch-only heads — finding the last code commit @@ -408,44 +453,143 @@ of them with their line counts. files); `not run` (could not run — always counts as attention); `off` (no configuration for it); `skip` (declared skipped in `check.skip`). - **Exit codes**: `0` = clear (no attention, no not-run); `1` = something needs attention, - including any check that could not run; `2` = the command failed and produced no report - (usage error, not in a git repository, no `origin`, PR not found, forge auth failure on - the anchoring `pr-view`, invalid configuration, head SHA unavailable, or the runner - refused a command). -- **`--json`**: one object on stdout, `schema: 1`, with `command`, `verdict` - (`clear`/`attention`), the target (PR, PRs, or worktree), and `checks: [{id, status, - summary, details}]`; on exit 2, `{schema: 1, command, error: {message, cause}}`. Human - output goes to stdout only without `--json`; diagnostics go to stderr. + including any check that could not run; `2` = the command failed and produced no report: + usage or input-validation error, not in a git repository, no `origin`, invalid + configuration, the runner refused a command, or — for `check pr` — the PR was not found or + the anchoring `pr-view` failed, timed out, or returned no head SHA; for `check worktree`, + the worktree was not found. For `check deploy`, a PR that cannot be read is a per-PR + `not run` (exit 1) and the other PRs are still reported; exit 2 is reserved for the + repository-, configuration- and usage-level failures above. +- **Time bound**: every forge call uses the dispatcher's existing 30 s limit, and `ls-remote` + and `fetch` get the same limit. A call that times out makes the checks that needed it + `not run: timed out after 30s`. - **Check ids** — `pr`: `head`, `state`, `forge`, `attribution`, `trial-merge`, `checks`, - `watched`, `overlap`, `size`, `to-read`. `deploy` (per PR): `merged`, `on-branch`, - `deploy-run`, `merge-checks`. `worktree`: `uncommitted`, `commits`, `remote`, `ignored`. -- **What counts as attention, per check**: head moved during the run; PR not OPEN, or draft; - forge mergeability other than its clean state (`UNKNOWN` included — reported as "forge has - not computed mergeability yet", and the plan may re-read once); any attribution hit; any - trial-merge conflict; checks per the porch-only rule; a flagged watched file moved. + `watched`, `linked-issue`, `overlap`, `size`, `to-read`. `deploy` (per PR): `merged`, + `on-branch`, `deploy-run`, `merge-checks`. `worktree`: `uncommitted`, `commits`, `remote`, + `pr`, `ignored`. These ids are what `check.skip` names. +- **What counts as attention, per check**: base or head moved during the run; local branch + ahead of the PR head (unpushed); PR not OPEN, or draft; forge mergeability other than its + clean state (`UNKNOWN` included — reported as "forge has not computed mergeability yet", + and the plan may re-read once); any attribution hit; any trial-merge conflict; checks per + the porch-only rule; a flagged watched file moved; a closing keyword naming the wrong + issue. + +#### JSON schema + +`--json` prints exactly one JSON object on stdout; nothing else goes to stdout. Diagnostics go +to stderr. Version 1: + +```ts +type Status = 'ok' | 'attention' | 'info' | 'not-run' | 'off' | 'skip'; + +interface Check { + id: string; // a check id from the list above + status: Status; + summary: string; // the one-line text the human form prints + details: object; // per-id shape below; {} when there is nothing more + reason?: string; // for not-run / off / skip: why, naming the concept, key or git version +} + +interface Report { + schema: 1; + command: 'pr' | 'deploy' | 'worktree'; + verdict: 'clear' | 'attention'; + generatedAt: string; // ISO 8601 +} + +interface PrReport extends Report { + command: 'pr'; + pr: { number: number; title: string; url?: string; state: string; draft: boolean | null; + headRef: string; head: string; baseRef: string; baseTip: string; + localBranch: { name: string; sha: string } | null }; + checks: Check[]; +} + +interface DeployReport extends Report { + command: 'deploy'; + deployBranch: string | null; // check.deploy.branch; null = each PR's own base branch + workflow: string | null; + prs: Array<{ number: number; mergedAt: string | null; mergeCommit: string | null; + baseRef: string | null; verdict: 'clear' | 'attention'; checks: Check[] }>; +} + +interface WorktreeReport extends Report { + command: 'worktree'; + removable: 'removable' | 'removable-after-keeping' | 'not-removable'; + worktree: { path: string; builderId: string | null; branch: string; + baseRef: string; baseTip: string }; + checks: Check[]; +} + +interface ErrorReport { // exit 2 + schema: 1; + command: 'pr' | 'deploy' | 'worktree'; + error: { message: string; cause?: string }; +} +``` + +`details` per id (all paths repo-relative, all SHAs full 40-hex): + +| id | `details` | +|---|---| +| `head` | `{ forgeHead, localBranchSha?, aheadOfPr?, movedTo? }` | +| `state` | `{ state, draft }` | +| `forge` | `{ mergeable, mergeStateStatus }` (forge's words, verbatim) | +| `attribution` | `{ patterns: string[], hits: [{ where: 'description' \| 'commit', sha?, line: number, text }] }` | +| `trial-merge` | `{ baseTip, head, conflicts: number, files: string[] }` | +| `checks` | `{ head: CommitRuns, code?: CommitRuns, lastCodeCommit, porchOnlyAbove: number }` where `CommitRuns = { sha, runs: [{ name, state, url?, workflow? }], passed, failed, pending }` | +| `watched` | `{ files: [{ path, flagged: boolean }] }` | +| `linked-issue` | `{ keyword?, issue?, branchIssue? }` | +| `overlap` | `{ files: string[] }` | +| `size` | `{ additions, deletions, files }` | +| `to-read` | `{ files: [{ path, additions, deletions }], excluded: string[] }` | +| `merged` | `{ state, mergedAt, mergeCommit }` | +| `on-branch` | `{ branch, tip, contains: boolean }` | +| `deploy-run` | `{ workflow, run?: { headSha, url, createdAt }, contains?: boolean }` | +| `merge-checks` | `CommitRuns` | +| `uncommitted` | `{ files: [{ path, change }], scaffold: string[] }` | +| `commits` | `{ total, notOnBase: string[] }` | +| `remote` | `{ remoteSha: string \| null, relation: 'matches' \| 'ahead' \| 'behind' \| 'diverged' \| 'absent' }` | +| `pr` | `{ number?, state?, mergedHead? }` | +| `ignored` | `{ keep: string[], regenerable: number }` | #### `check worktree` — what "removable" means -"Removable" means **removing it loses nothing**, not merely that `git worktree remove` would -not need `--force` (the scaffold files alone make plain `git worktree remove` refuse on every -builder worktree). The check reports: +The verdict answers one question: **would removing this worktree and its local branch lose +data?** Not merely whether `git worktree remove` would need `--force` — spawn's scaffold +files alone make a plain `git worktree remove` refuse on every builder worktree. + +What counts as data, and how each is judged: - **uncommitted** — staged, unstaged and untracked-not-ignored files (via - `git --no-optional-locks status`), excluding spawn's scaffold files, which are counted - separately and never block; -- **commits** — commits on the branch not reachable from the live remote base tip (read with - `ls-remote`; objects fetched ref-neutrally if missing). When some are not on the base, the - branch's PR state is looked up (`pr-search`): merged with differing commits (a squash or - rebase merge) is attention with that explanation; otherwise they are unmerged work; -- **remote** — local branch vs `origin/` via `ls-remote`: matches / local ahead - (unpushed) / behind / diverged / no remote branch (fine when every commit is on the base); -- **ignored** — ignored files matching `cleanup.keepIgnored` and not on the never-copy list: - these are deleted silently by any removal, forced or not. - -Verdict: `NOT REMOVABLE` when there are uncommitted files, or commits that exist neither on -the base nor on the remote branch, or the PR is still open; `REMOVABLE AFTER KEEPING N FILES` -when only keep-list ignored files stand in the way; otherwise `REMOVABLE`. The argument is a -builder id (resolved to `/.builders/` and confirmed against + `git --no-optional-locks status`). Spawn's scaffold files are counted separately and are + not data. Any other file here is data that would be lost. +- **commits** — a branch commit is safe when it is reachable from the live remote base tip + or from the live remote branch tip (both read with `ls-remote`; objects fetched + ref-neutrally if missing). One more case is safe: when the branch's PR is merged by squash + or rebase, its commits are not on the base, but if the local branch tip **equals the + merged PR's head SHA** (from `pr-view`), every local commit was part of what merged. A + local tip that differs from the merged head means commits were made after the merge: + those are data. +- **remote** — local branch vs `origin/`: matches / local ahead (unpushed) / behind / + diverged / absent. Reported for context; the commits rule above already decides whether + anything is lost (an absent remote branch is fine when every commit is on the base). +- **ignored** — ignored files are data **only if they match the keep list** + (`cleanup.keepIgnored`) and are not on the never-copy list. Every other ignored file is + treated as regenerable — dependency and build output, caches — which is what the keep + list means; the summary still prints their count, so nothing is lost unseen. A project + that keeps something else worth saving adds it to the keep list. + +Verdict: `NOT REMOVABLE` when there is uncommitted data or an unsafe commit; +`REMOVABLE AFTER KEEPING N FILES` when the only data is keep-list ignored files; otherwise +`REMOVABLE`. + +Separately from the data verdict, **lifecycle** is reported through the `pr` check: the +branch's PR still OPEN is attention ("builder not finished") even when no data would be lost, +and a PR state the forge cannot provide is `not run`. Either makes the exit 1 without +changing the verdict word, so "removable" never silently means "finished". + +The argument is a builder id (resolved to `/.builders/` and confirmed against `git worktree list`) or a path to a registered worktree. #### Relation to existing tools and guidance @@ -506,22 +650,26 @@ builder id (resolved to `/.builders/` and confirmed against 6. Attribution hit in a commit message and in the description → both reported with location; commits already on base are not scanned. 7. Porch-only head with runs only on the code commit; only on head; on a push tip between them; on none; failure on head while code commit green → displays and verdicts per § Porch-only heads. 8. Flagged watched file moved → attention; unflagged watched → info. -9. `.gitattributes` `linguist-generated` file and lockfile excluded from "to read"; `check.notForReading` replaces the default. +9. Lockfile and `codev/projects/**` excluded from "to read"; `check.notForReading` replaces the default list. 10. Draft PR, closed PR, merged PR → `state` attention. -11. Forge head SHA changes between start and end of run → attention "head moved". +11. Forge head SHA changes between start and end of run → attention "head moved"; remote base tip changes between start and end → attention "base moved". 12. Local builder branch ahead of the PR head → `head` attention ("not pushed"). +12a. Linked issue: `Fixes #1951` on `builder/spir-1951` → info; no keyword → info with the close-by-hand note; `Fixes #1950` on `builder/spir-1951` → attention. +12b. A forge stub that never answers → that check `not run: … timed out after 30s`; a hanging anchoring `pr-view` → exit 2. **`check deploy`** 13. Merged, on deploy branch, inside latest green run → `ok`; not on branch → attention; on branch but newer than latest green run → attention. 14. No `check.deploy` → base branch used; `merge-checks` reported; `deploy-run` `off`. 15. PR not merged → `merged` attention; several PRs → verdict is the worst. +15a. `check deploy 1948 99999` where 99999 does not exist → #1948 fully reported, #99999 `not run: PR not found`, exit 1. **`check worktree`** -16. Clean, merged (`--merge`), remote branch deleted → `REMOVABLE`. +16. Clean, merged (`--merge`), remote branch deleted → `REMOVABLE`, exit 0. 17. Modified thread file → `NOT REMOVABLE`; only scaffold files untracked → not counted. 18. Unpushed commit not on base → `NOT REMOVABLE`. -19. Squash-merged PR (commits not on base, PR merged) → attention with explanation. -20. Keep-list ignored files present; never-copy paths (`node_modules/`) excluded → `REMOVABLE AFTER KEEPING N FILES`. +19. Squash-merged PR, local tip equals the merged head → `REMOVABLE`; local tip has a commit after the merged head → `NOT REMOVABLE`. +20. Keep-list ignored files present; never-copy paths (`node_modules/`) excluded and counted as regenerable → `REMOVABLE AFTER KEEPING N FILES`. +20a. Clean and fully pushed, PR still OPEN → verdict `REMOVABLE`, `pr` attention, exit 1. 21. Builder id not found / path not a registered worktree → exit 2. **Read-only and errors (all commands)** @@ -532,6 +680,7 @@ builder id (resolved to `/.builders/` and confirmed against 26. Invalid config (non-array `check.watch`, bad regex) → exit 2 naming key and file. 27. git older than 2.38 (stubbed `git version`) → trial merge `not run: requires git 2.38+`. 28. `--json` for every scenario parses and matches the schema; exit 2 emits the `error` object. +28a. Input validation: PR `12a`, SHA `zz12`, `check.deploy.workflow: "--repo=x"` → exit 2 naming the value, with no subprocess started. **Non-functional** 29. A 25-file PR with a 3-commit porch tail completes in under 30 s against GitHub on a normal connection (the forge calls dominate). @@ -548,8 +697,10 @@ builder id (resolved to `/.builders/` and confirmed against | Older git (< 2.38) on adopter machines | Medium | Medium | Trial merge `not run` naming the version; `codev doctor` reports git version | | Users read `info` lines as passes, or exit 1 becomes routine noise | Medium | Medium | `info` never claims a pass; `not run` and `off` are spelled out; `check.skip` exists so a project can make exit 0 meaningful for itself | | `cleanup.keepIgnored` definition diverges between #1950 and this spec | Medium | Medium | One shared definition; whichever PR lands second reuses the first's; a test asserts `check worktree` lists exactly what `--keep-ignored` would keep | -| A project's own concept override performs writes | Low | Medium | Documented limit: the runner governs which concepts are called; overrides are trusted as elsewhere in Codev | -| Unreachable objects from `merge-tree`/fetch accumulate | Low | Low | Collected by normal `git gc`; documented as the only write | +| A project's own concept override performs writes | Low | Medium | Documented trust boundary: the runner governs git argv and which concepts are called; shipped scripts are covered by stub tests; overrides are trusted as elsewhere in Codev | +| A stalled network makes the command hang at the `pr` gate | Medium | Medium | Every forge and networked git call has a 30 s limit; a timeout is a named `not run`, never a hang | +| The base or head moves while the command runs, so a `CLEAR` describes stale tips | Low | High | Both are re-read at the end; any movement is attention "re-run" | +| Unreachable objects from `merge-tree`/fetch accumulate | Low | Low | Collected by normal `git gc`; documented as the only writes | ## References diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index d2639f5dc..353dd72be 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -12,3 +12,15 @@ - Verified: 361 commits on origin/main since 2026-06-01 carry Co-Authored-By. - Surprise: this repo gitignores `.codev/config.json`, so the owner's attribution rule must live in `~/.codev/config.json` or the local layer — attribution check proposed off by default. + +## 2026-11-23 — specify, CMAP iter 1 (codex REQUEST_CHANGES, claude COMMENT) +All points accepted and folded in: +- base tip re-read at the end alongside head (race); per-call 30 s timeouts → named `not run`. +- Dropped `linguist-generated` from "to read": needs `git check-attr --source` (git 2.40); rule is globs only. +- Worktree verdict is now strictly *data* (uncommitted, unsafe commits, keep-list ignored); open PR is a + separate `pr` lifecycle attention item. Squash merges are judged exactly: local tip == merged PR head. +- Concrete `--json` schema (per-command reports + per-check `details`). +- Trust boundary stated precisely (runtime = git argv + concept names; shipped scripts via stub tests). +- Added `linked-issue` check (closing keyword vs builder branch id), input validation, deploy + multi-PR error semantics (per-PR `not run`, exit 1), the #1950 landing-order rule, and all four + `codev` skill copies + hash regeneration in the docs criterion. From 19aff4a3df0dc928b81fbfaa8cba65d7c9a0a048 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 11:11:39 -0800 Subject: [PATCH 05/94] chore(porch): 1951 spec-approval gate-requested --- codev/projects/1951-read-only-pr-check-for-archite/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index a7b6cb7ce..540e63cb4 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -7,6 +7,7 @@ current_plan_phase: null gates: spec-approval: status: pending + requested_at: '2026-11-23T19:11:38.967Z' plan-approval: status: pending pr: @@ -17,4 +18,4 @@ iteration: 1 build_complete: true history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T19:04:16.165Z' +updated_at: '2026-11-23T19:11:38.967Z' From b1289074fc2c2fbda6981ab887eea5ee34f17615 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 13:21:55 -0800 Subject: [PATCH 06/94] chore(porch): 1951 spec-approval gate-approved --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 540e63cb4..b4ca28fcb 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -6,8 +6,9 @@ plan_phases: [] current_plan_phase: null gates: spec-approval: - status: pending + status: approved requested_at: '2026-11-23T19:11:38.967Z' + approved_at: '2026-11-23T21:21:55.621Z' plan-approval: status: pending pr: @@ -18,4 +19,4 @@ iteration: 1 build_complete: true history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T19:11:38.967Z' +updated_at: '2026-11-23T21:21:55.622Z' From 8f5c5f45a306a5a5c95f41e14932ce9348554011 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 13:21:59 -0800 Subject: [PATCH 07/94] chore(porch): 1951 plan phase-transition --- .../1951-read-only-pr-check-for-archite/status.yaml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index b4ca28fcb..00dc6b10a 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -1,7 +1,7 @@ id: '1951' title: read-only-pr-check-for-archite protocol: spir -phase: specify +phase: plan plan_phases: [] current_plan_phase: null gates: @@ -16,7 +16,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T21:21:55.622Z' +updated_at: '2026-11-23T21:21:59.026Z' +context_refreshes: + - boundary: enter:plan + at: '2026-11-23T21:21:59.024Z' From d35fed15886ff4372a92da8f42e87c50134380b8 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 13:23:07 -0800 Subject: [PATCH 08/94] chore(porch): 1951 acknowledge context refresh --- codev/projects/1951-read-only-pr-check-for-archite/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 00dc6b10a..5de3bff30 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -19,7 +19,8 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T21:21:59.026Z' +updated_at: '2026-11-23T21:23:07.115Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' + acknowledged_at: '2026-11-23T21:23:07.115Z' From 9fbc2374cea8d3d9d97faf8b9f95044ab3c6bb07 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 13:31:52 -0800 Subject: [PATCH 09/94] [Spec 1951] Initial implementation plan --- .../1951-read-only-pr-check-for-archite.md | 751 ++++++++++++++++++ 1 file changed, 751 insertions(+) create mode 100644 codev/plans/1951-read-only-pr-check-for-archite.md diff --git a/codev/plans/1951-read-only-pr-check-for-archite.md b/codev/plans/1951-read-only-pr-check-for-archite.md new file mode 100644 index 000000000..d550bc50b --- /dev/null +++ b/codev/plans/1951-read-only-pr-check-for-archite.md @@ -0,0 +1,751 @@ +# Plan: Read-only PR check for architects — `codev check pr | deploy | worktree` + +**Specification**: [codev/specs/1951-read-only-pr-check-for-archite.md](../specs/1951-read-only-pr-check-for-archite.md) + +## Executive Summary + +The plan implements the spec's Approach 1: a read-only command group, `codev check`, on the +`codev` CLI, with three subcommands (`pr`, `deploy`, `worktree`). The owner approved the +spec's recommended answers to Open Questions 1–4, and the plan treats them as settled: + +1. Placement is **`codev check`**, not `afx`. +2. **`check.attribution` is off by default** (`[]`, shown as `off`). Default patterns would + impose one attribution policy on every adopter. +3. **Porch's `pr` gate message is not changed.** The architect role carries the instruction. +4. **The builder role is not changed.** + +Nice-to-know items 5–8 are out of scope. + +The work goes in dependency order: + +1. **Forge data first.** The checks cannot be computed without it: the head SHA, draft flag, + mergeability and merge commit from `pr-view`, plus two new read concepts, `commit-checks` + and `workflow-runs`. +2. **The read-only core next.** This is one argv runner with the allow-list. It is the only + path to a subprocess in the module, and a structural test proves that. The core also holds + the configuration, input validation, the report model, the renderers and the shared + git-plumbing facts (live tips, ref-neutral fetch, git version gate). +3. **The three commands**, each in its own phase, on top of the core. +4. **Guidance and docs** in both trees, after merging `origin/main`, because the sibling + PR #1954 (`afx cleanup --keep-ignored`, issue #1950) touches the skill files and the + shipped-skill hashes. + +**Glob semantics, decided here.** Every glob in `check.*` and `cleanup.keepIgnored` is a git +pathspec with `:(glob)` magic, and git itself does the matching, through `git diff … -- +:(glob)

` and `git ls-files … -- :(glob)

`. #1950's `listKeepCandidates` already matches +the keep list this way. So `check worktree` and `afx cleanup --keep-ignored` agree by +construction, and no glob library is added. Node ≥ 20 has no stable `path.matchesGlob`, and +`minimatch` is only a transitive dependency here. + +## Phases (Machine Readable) + +```json +{ + "phases": [ + {"id": "forge_read_concepts", "title": "Forge read concepts for PR mechanics"}, + {"id": "readonly_core", "title": "Read-only runner, configuration and report core"}, + {"id": "check_pr", "title": "codev check pr"}, + {"id": "check_deploy", "title": "codev check deploy"}, + {"id": "check_worktree", "title": "codev check worktree"}, + {"id": "docs_guidance", "title": "Architect guidance and command documentation"} + ] +} +``` + +## Module layout (all phases) + +``` +packages/codev/src/commands/check/ + allow-list.ts pure: git argv grammar + allowed forge concepts (Phase 2) + runner.ts the ONLY subprocess path: git(argv), forge(concept, env); timeouts (Phase 2) + validate.ts PR number, SHA, builder id, config-string validation (Phase 2) + settings.ts check.* (and cleanup.keepIgnored) load + validate, naming key and file (Phase 2/5) + report.ts schema-1 types, statuses, verdict, exit code, check.skip (Phase 2) + render.ts human summary, --json, error report (Phase 2) + git-facts.ts git version gate, live tip (ls-remote), ensureObjects (ref-neutral fetch), + merge-base, pathspec-filtered diffs, ancestry (Phase 2) + index.ts `codev check` commander group, --json, exit-code mapping (Phase 3; grows in 4, 5) + pr.ts, porch-only.ts, linked-issue.ts (Phase 3) + deploy.ts (Phase 4) + worktree.ts (Phase 5) + __tests__/helpers/git-fixture.ts real repos: bare "origin", clones, worktrees, state snapshot + __tests__/helpers/stub-bin.ts stub gh (fixtures) + stub git (recorder → real git) +``` + +`cli.ts` registers the group with `program.addCommand(buildCheckCommand())`. The group calls +`exitOverride()`, so a commander usage error exits **2**, not commander's default 1. When +`--json` is in argv, the error goes out as the `ErrorReport` object. Each command function +takes `{ cwd, workspaceRoot, timeoutMs }` and returns `{ report, exitCode }`. Tests call it in +process, and the CLI wrapper prints the result and exits. + +The workspace root comes from `findWorkspaceRoot()`, as the other `codev` commands do. From a +builder worktree that is still the main checkout, so config and `.builders/` resolve the same +way. `codev check` does not require a `codev/` directory. It does require a git repository +with an `origin` remote, and without one it exits 2. + +## Phase Breakdown + +### Phase 1: Forge read concepts for PR mechanics + +**Dependencies**: None + +#### Objective + +Give the forge layer the data the checks need, with every shipped preset either implementing +each new field or concept, or explicitly disabling it. Nothing is left silently absent. + +#### Files to Create / Modify + +- `packages/codev/src/lib/forge-contracts.ts`: + - `PrViewResult` gains optional fields: + - `headRefOid?: string` + - `isDraft?: boolean` + - `mergeable?: 'MERGEABLE' | 'CONFLICTING' | 'UNKNOWN'` + - `mergeStateStatus?: string`, using GitHub's vocabulary. `CLEAN` is the clean state. + Other presets map their clean state to `CLEAN` and pass any other state through + upper-cased. + - `mergeCommit?: { oid: string } | null` + - `mergedAt?: string | null` + - New `CommitCheckItem` `{ name, state: 'pass'|'fail'|'pending'|'skipped'|'neutral', url?, workflow? }` + and `CommitChecksResult`. + - New `WorkflowRunItem` `{ headSha, status, conclusion, url, createdAt }` and + `WorkflowRunsResult`, newest first. +- `packages/codev/src/lib/forge.ts`: + - `KNOWN_CONCEPTS` += `commit-checks`, `workflow-runs`. + - The gitlab and gitea presets pass both new concepts in their explicit disabled list. + Without that, `buildPresetFromScripts` would omit them and let them fall through to the + GitHub default. + - `ForgeCommandOptions.timeoutMs?`, default `30_000`. The dispatcher's existing limit stays + the default. + - `ForgeCommandError.timedOut: boolean`, derived from the exec error's `killed`/`signal`. + - All of these are additive. Existing callers are unchanged. +- `packages/codev/scripts/forge/github/pr-view.sh`: add + `headRefOid,isDraft,mergeable,mergeStateStatus,mergeCommit,mergedAt` to the `--json` list. +- `packages/codev/scripts/forge/github/commit-checks.sh` (new). Input `CODEV_COMMIT_SHA`. + - Makes read-only `gh api` GET calls: + - `repos/{owner}/{repo}/commits/$SHA/check-runs` (paginated) + - `…/commits/$SHA/status` (legacy commit statuses) + - `…/actions/runs?head_sha=$SHA`, which supplies the workflow name of each check run + through its `check_suite_id` + - Normalizes everything to `CommitCheckItem[]`: + - completed + success → `pass` + - skipped → `skipped` + - neutral → `neutral` + - failure, cancelled, timed_out, action_required, stale or startup_failure → `fail` + - not completed → `pending` + - status `success` → `pass`; `failure` or `error` → `fail`; `pending` → `pending` + - Uses the capture-then-`jq` shape with `# forge-executable: gh`, like `pr-list.sh`. +- `packages/codev/scripts/forge/github/workflow-runs.sh` (new). Inputs `CODEV_WORKFLOW` and + `CODEV_BRANCH`. Runs + `exec gh run list --workflow "$CODEV_WORKFLOW" --branch "$CODEV_BRANCH" --limit 50 --json headSha,status,conclusion,url,createdAt`. +- `packages/codev/scripts/forge/gitlab/pr-view.sh`: add the new fields from glab's MR object, + marked UNVERIFIED like its siblings: + - `sha` → `headRefOid` + - `draft` → `isDraft` + - `merge_commit_sha // squash_commit_sha` → `mergeCommit.oid` + - `merged_at` → `mergedAt` + - `detailed_merge_status` → `mergeable`: `conflict` → `CONFLICTING`; `checking`, + `unchecked` or `preparing` → `UNKNOWN`; anything else → `MERGEABLE` + - `detailed_merge_status` → `mergeStateStatus`: `mergeable` → `CLEAN`; anything else + upper-cased +- `packages/codev/scripts/forge/gitea/pr-view.sh`: add the new fields from the REST pull + object it already fetches: `head.sha`, `draft`, `mergeable` (bool → `MERGEABLE` or + `CONFLICTING`), `merge_commit_sha`, `merged_at`. +- Concepts not shipped, and why: gitlab and gitea set `commit-checks` and `workflow-runs` to + `null`. They cannot be verified in this environment, which has no glab and no Gitea server. + A disabled concept shows as `not run: … unavailable on `, which is honest. A + project can supply its own override. +- `codev/resources/commands/forge.md`: document the two new concepts (inputs, output contract, + state normalization), the new optional `pr-view` fields, which presets provide what, and + that `codev check` is their consumer. +- Tests (new): `packages/codev/src/__tests__/spec-1951-forge-read-concepts.test.ts`. + +#### Deliverables + +- [ ] Contract types for the new fields and the two concepts +- [ ] `commit-checks` and `workflow-runs` registered. The github scripts implement them; the + gitlab and gitea presets disable them explicitly. +- [ ] `pr-view` returns the new fields on github, gitlab and gitea +- [ ] `timeoutMs` option and `timedOut` error flag on the dispatcher +- [ ] `forge.md` updated +- [ ] Tests for this phase + +#### Acceptance Criteria + +- [ ] `getKnownConcepts()` includes both new concepts. `resolveAllConcepts({provider})` shows + them as `default` for github, linear and jira (they fall through to github), and as + `disabled` for gitlab and gitea. So `codev doctor`, which lists `resolveAllConcepts`, + shows them. +- [ ] With a stub `gh` on `PATH`, the github `pr-view`, `commit-checks` and `workflow-runs` + scripts emit JSON that matches the contract. Fixtures cover mixed conclusions, legacy + statuses, two pages of check runs and a run with no workflow match. The stub fails the + test on any `gh` call other than `pr view`, `run list`, or `api` with GET and no field + flags. +- [ ] The gitlab and gitea `pr-view` mappings are verified against a stub `glab` and `tea` + (skipped when `jq` is absent, as the existing preset tests are). +- [ ] A concept that sleeps past `timeoutMs` returns `error.timedOut === true`, in both the + `exec gh` script shape and the capture-pattern shape. +- [ ] Existing forge and doctor tests still pass, with any concept-count expectations updated. + +#### Test Plan + +- Unit: concept registration and preset resolution, table-driven over the providers. +- Script contract: run each script through `executeForgeCommandDetailed`, with stub CLIs first + on `PATH`. POSIX only for the stub cases, as in `bugfix-1455-pr-create-concept.test.ts`. +- Timeout: a stub that sleeps 5 s, with `timeoutMs: 300`. + +### Phase 2: Read-only runner, configuration and report core + +**Dependencies**: Phase 1 (the runner wraps the dispatcher's `timeoutMs` and `timedOut`) + +#### Objective + +The read-only guarantee as code: one runner that refuses any non-allowed command before +spawning it, plus everything the three commands share. That shared part is validated +configuration and input, the schema-1 report with its verdict and exit codes, both renderers, +and the git plumbing that reads live tips and fetches objects without moving a ref. + +#### Files to Create / Modify + +- `packages/codev/src/commands/check/allow-list.ts` + - **Git grammar**: `git [--no-optional-locks] [-C

] [-c gc.auto=0] [-c maintenance.auto=false] …`. + No other global option is accepted. + - **Allowed subcommands**: the spec's list exactly. `version`, `rev-parse`, `rev-list`, + `merge-base`, `log`, `show`, `cat-file` and `for-each-ref` are allowed without + conditions. The others carry a rule: + + | Subcommand | Rule | + |---|---| + | `diff`, `diff-tree` | `--output` is refused | + | `ls-files` | read flags only | + | `ls-remote` | the remote must be `origin`; `--symref` is allowed | + | `worktree` | `list` only | + | `config` | `--get` or `--get-regexp` only | + | `symbolic-ref` | read form only: one positional argument | + | `status` | only with the global `--no-optional-locks` | + | `merge-tree` | must include `--write-tree` | + | `fetch` | only the exact ref-neutral form: `-c gc.auto=0 -c maintenance.auto=false fetch --no-write-fetch-head --refmap= origin …`, every `` validated | + + - **Allowed forge concepts**: `pr-view`, `pr-search`, `commit-checks`, `workflow-runs`. +- `packages/codev/src/commands/check/runner.ts` + - `createRunner({ cwd, timeoutMs = 30_000, spawn? })`. Two methods: + - `git(args, { network? })` → `{ stdout, stderr, exitCode }`. It uses argv `spawn`, + never a shell, with `windowsHide`. + - `forge(concept, env)` → `{ data } | { notRun: reason }`. Possible reasons are disabled, + failed (with stderr), timed out and invalid JSON. + - Allow-list violations throw `RunnerRefusal`, which the commands map to exit 2. + - Networked git calls (`ls-remote`, `fetch`) and every forge call get `timeoutMs`. + - The runner also races each call against its own deadline. A grandchild holding a stdio + pipe therefore cannot keep a call alive past the bound. A late result is discarded, and + the CLI exits explicitly at the end. + - `spawn` is injectable for unit tests. +- `packages/codev/src/commands/check/validate.ts` + - A PR number must be a positive integer (`^[1-9]\d*$`). + - A SHA must be 7–40 hex characters. + - A builder id must be `^[A-Za-z0-9][A-Za-z0-9._-]*$`, with no `..` and no path separator. + Registration in `git worktree list` is confirmed later. + - A config string passed to git or a concept may not begin with `-` and may not contain a + control character. + - A violation throws `InputError` naming the value, and for config, the key and file. +- `packages/codev/src/commands/check/settings.ts` + - `loadCheckSettings(workspaceRoot)` reads `check.attribution`, `watch`, `flag`, + `notForReading`, `deploy.branch`, `deploy.workflow` and `skip`, and applies the spec's + defaults. + - Validation: + - each type + - `attribution` regexes compile, case-insensitive + - `skip` entries are known check ids + - `deploy.*` strings go through `validate.ts` + - Errors name the key and the file `findConfigSource()` reports. +- `packages/codev/src/lib/config.ts`: add `check?: { … }` to `CodevConfig`. Type only, since the + loader already merges arbitrary keys and arrays replace. +- `packages/codev/src/commands/check/report.ts` + - The schema-1 types from the spec: `Check`, `PrReport`, `DeployReport`, `WorktreeReport`, + `ErrorReport`. + - `applySkips()`: a skipped check becomes `skip` with reason `check.skip`. + - `verdictOf(checks)`: any `attention` or `not-run` → `attention`. + - `exitCodeOf(report)`: 0 when clear, 1 when attention. +- `packages/codev/src/commands/check/render.ts` + - The human form: + - The verdict line comes first, naming each check that needs attention. A qualifier is + added where it tells the architect what to do, e.g. `checks (running)` versus + `checks (failed)`, or `watched (flagged)`. + - Then the header lines, then one line per check with its status word (`ok`, `ATTN`, + `info`, `not run`, `off`, `skip`). + - Lists are truncated with `… +N`. + - `--json` writes exactly one object to stdout. Diagnostics go to stderr. +- `packages/codev/src/commands/check/git-facts.ts` + - `gitVersion()` and `requireGit(major.minor)`. Below 2.38 the trial merge is `not run`; + below 2.29 the ref-neutral fetch is unavailable, so checks that need a missing object are + `not run`. + - `requireOrigin()`: no `origin` → exit 2. + - `liveTip(branch)`, via `ls-remote origin refs/heads/`. + - `remoteDefaultBranch()`, via `ls-remote --symref origin HEAD`. + - `hasCommit(sha)`, via `cat-file -e ^{commit}`. + - `ensureCommits(shas)`: fetches only the missing SHAs, in the ref-neutral form. On failure + it returns a per-SHA `not available locally ()`. + - Also `mergeBase`, `isAncestor` (`merge-base --is-ancestor`), and + `changedFiles(from, to, { include?, exclude? })` and `numstat(…)`, which use + `-- :(glob)…` and `:(exclude,glob)…` pathspecs. +- Test helpers: `__tests__/helpers/git-fixture.ts` and `__tests__/helpers/stub-bin.ts`. + - `git-fixture.ts` builds a bare remote, clones and worktrees. Its + `snapshotRepoState(repo)` captures `for-each-ref` output, `HEAD`, the index file's bytes, + whether `FETCH_HEAD` exists and what it holds, and `status --porcelain`. + - `stub-bin.ts` writes a `git` stub that records argv and checks it against a read-only list + the stub keeps itself. Because the list is independent of the runner's, a runner bug cannot + hide behind a matching stub. The stub then execs the real git, whose absolute path is + resolved before `PATH` changes. + - `stub-bin.ts` also writes a `gh` stub that records argv, refuses anything that is not + read-only, and answers from a fixtures file. It can sleep on demand, for the timeout + cases. +- Tests (new): `__tests__/allow-list.test.ts`, `runner.test.ts`, `validate.test.ts`, + `settings.test.ts`, `report-render.test.ts`, `git-facts.test.ts`, `structure.test.ts`. + +#### Deliverables + +- [ ] Allow-list, runner, validation, settings, report, renderers, git facts +- [ ] Test helpers: fixture repos, state snapshot, stub `gh`/`git` +- [ ] Tests for this phase + +#### Acceptance Criteria + +- [ ] A table of refused argv is refused, with the spawn spy never called: + - `update-ref` + - `push` + - `fetch origin main` + - `fetch` without `--refmap=` + - `merge-tree` without `--write-tree` + - `status` without `--no-optional-locks` + - `diff --output=x` + - `config --unset` + - `symbolic-ref HEAD refs/heads/x` + - `worktree remove` + - `branch -D` + - `-c core.hooksPath=x log` +- [ ] Each allowed form of every subcommand passes. +- [ ] The concept `pr-merge` is refused before dispatch. +- [ ] **Structural test.** Within `commands/check/`, only `runner.ts` imports + `node:child_process`, `child_process` or the forge dispatcher (`lib/forge.js`). The + runner is then the only subprocess path, as spec § Read-only enforcement 1 requires. +- [ ] An `ls-remote` or forge call past `timeoutMs` yields `not run: timed out after Ns`. +- [ ] Settings: + - A non-array `check.watch` exits 2 naming `check.watch` and the file. + - So does an unparseable `check.attribution` regex. + - So does an unknown `check.skip` id. + - `check.notForReading` replaces the default list rather than adding to it. +- [ ] Input validation: `12a`, SHA `zz12` and `check.deploy.workflow: "--repo=x"` each exit 2 + naming the value, with no subprocess started. +- [ ] Real repository: `ensureCommits` fetches a missing SHA from the bare remote. `for-each-ref`, + `HEAD`, the index bytes, `FETCH_HEAD`'s absence and `status` are all identical before and + after. +- [ ] `--json` output parses and has the schema-1 shape for a hand-built report and for an + error report. + +#### Test Plan + +- Unit: allow-list tables, runner with injected spawn, validation, settings with temp config + layers, renderers. +- Integration (real git, every platform): `git-facts.test.ts` against `git-fixture.ts` repos. + +### Phase 3: `codev check pr` + +**Dependencies**: Phase 2 + +#### Objective + +The headline path. An architect runs `codev check pr ` and, in one screen, sees everything +needed to recommend the merge, or the specific thing that blocks it. + +#### Files to Create / Modify + +- `packages/codev/src/commands/check/pr.ts`: the command. The flow: + 1. Validate N. Load the settings. Check the git version. Require `origin`. + 2. Anchor on `pr-view`. Exit 2 when the PR is not found, the call fails or times out, or + `headRefOid` is missing. The message names the concept, the provider, and the override + file when there is one. + 3. Read `baseTip` with `ls-remote`, then `ensureCommits(head, baseTip)`. + 4. Compute the local checks on the exact head: + - `attribution`: the PR description, then each commit in `log baseTip..head`, matched + line by line. + - `trial-merge`: `merge-tree --write-tree --name-only --no-messages baseTip head`. Exit 1 + means conflicts, and the output lists the files. + - `watched`: files matching `check.watch`; matches of `check.flag` are flagged. + - `overlap`: files changed on both sides since the merge-base. + - `size` and `to-read`: numstat between the merge-base and head. `to-read` excludes + `check.notForReading` and is sorted largest first. + 5. Fill the forge checks from `pr-view`: + - `state`, from state and draft. Normalization: upper-case it; `OPENED` → `OPEN`; a + non-null `mergedAt` → `MERGED`. + - `forge` is `ok` only for `MERGEABLE` with a `mergeStateStatus` that is absent, `CLEAN` + or `HAS_HOOKS`. Anything else is attention, in the forge's own words. + - `linked-issue`. + 6. Fill `checks` from the porch-only walk (below). + 7. Re-read `pr-view` and `ls-remote`. + - If the head moved, the `head` check carries `movedTo` and is attention. + - If the base moved, `trial-merge` carries `movedTo` and is attention. The spec + designates no id for base movement; `trial-merge` is the base-anchored check, so this + is an additive key in its `details`. + - An `UNKNOWN` mergeability takes the second read's value. That is the spec's "re-read + once". + 8. `head` also compares the local `refs/heads/` with the forge head: matches, + local ahead (unpushed, attention), behind, diverged, or absent. +- `packages/codev/src/commands/check/porch-only.ts`, mostly pure: + - A commit is porch-only when it is not a merge commit (one parent, from + `rev-list --parents`) and `diff-tree -r --name-only` against its first parent shows only + paths under `codev/projects/`. + - The walk follows the head's first-parent chain down to the merge-base, looking for the + last code commit C. It queries at most 10 commits. When C is not found within that bound, + the check is `not run: more than 10 porch-only commits`. + - `commit-checks` runs on head first, then on each commit below head down to C. It stops at + the first commit that has results. + - **The display carries the architect's standing order.** Right after a builder reaches the + `pr` gate, porch's status commit is head and its CI is still running. The checks line + must then let an architect tell "wait a few minutes" from "something failed". + - Head is C, or head is porch-only with all its runs complete: one line. + - Head is porch-only and its runs are absent or still pending: two lines. The newest + completed code runs at or below head show as `code : 8 passed`. The head line + reads `head : porch-only, 8 still running` or `head : no runs — 3 porch-state + commits above the code`. + - The verdict is the spec's: `ok` only when code runs exist and all passed (skipped and + neutral count as passed) and nothing on head failed or is pending. The attention + qualifier in the verdict line is `checks (running)` when the only problem is pending + runs, and `checks (failed)` or `checks (none)` otherwise. +- `packages/codev/src/commands/check/linked-issue.ts` + - The keyword regex: `\b(close[sd]?|fix(e[sd])?|resolve[sd]?)\b:?\s+#(\d+)`, + case-insensitive. These are GitHub's documented closing keywords. + - The branch id comes from `^builder/[a-z]+-(\d+)$`. + - A keyword alone is `info`. No keyword is `info` with the close-by-hand note. A keyword + naming a different issue than the branch's id is attention. +- `packages/codev/src/commands/check/index.ts` (new): `buildCheckCommand()`, the `check` group + with `pr [--json]`, plus the exit-2 mapping. +- `packages/codev/src/cli.ts`: register the group. +- Tests (new): + - `__tests__/check-pr.test.ts`: POSIX, with stub `gh` fixtures and the stub `git` passing + through to a real fixture repo. + - `__tests__/check-pr-readonly.test.ts`: every platform, real repos, the forge supplied + through config overrides (`forge: { "pr-view": "", … }`), so no `gh` is + needed. + - `__tests__/porch-only.test.ts`: pure selection and display tables. + - `__tests__/check-cli.test.ts`: the commander wiring, including usage errors → exit 2 and a + JSON error. + +#### Deliverables + +- [ ] `codev check pr [--json]`, listed in `codev --help` and `codev check --help` +- [ ] All eleven checks: `head`, `state`, `forge`, `attribution`, `trial-merge`, `checks`, + `watched`, `linked-issue`, `overlap`, `size`, `to-read` +- [ ] Porch-only walk and the two-line display +- [ ] Re-read race detection +- [ ] Tests for this phase + +#### Acceptance Criteria + +- [ ] Spec Test Scenarios 1–12b pass as automated tests, covering each functional case listed + there. +- [ ] Spec Test Scenarios 22–28a pass for `check pr`: + - the stub `gh` and `git` see only read-only invocations + - an injected `update-ref` or `gh pr merge` is refused by the runner + - the real-repo snapshot is identical before and after, including a conflicting trial + merge and a run that must fetch the head + - a `null` concept and a failing concept give `not run` + - a `pr-view` override with no `headRefOid` gives exit 2 + - git older than 2.38 gives `not run: requires git 2.38+` + - `--json` matches the schema +- [ ] Each `forge-dependent` check (`state`, `forge`, `checks`) shows `not run: …` and + exit 1 with its concept disabled or failing. It is never `ok`. +- [ ] The human summary for Scenario 1 fits in 25 lines (Scenario 30). +- [ ] **Live run.** `codev check pr` is run against at least one real open PR in this + repository, e.g. #1954, from both the main checkout and this worktree. The output is + recorded in the thread log. One run uses a temporary, gitignored + `.codev/config.local.json` with attribution patterns, to exercise an attribution hit; the + file is removed afterwards. `~/.codev/config.json` is never touched. The run on this + project's own PR, where porch-only commits sit on head at the `pr` gate, happens in the + Review phase and goes into the review. + +#### Test Plan + +- Integration (POSIX): `check-pr.test.ts`, scenario by scenario. The fixtures model the forge + responses; the git side is real. +- Integration (every platform): `check-pr-readonly.test.ts`, with snapshots taken around + clean, conflicting, stale-local-base and missing-head runs. +- Unit: porch-only selection, linked-issue parsing, state normalization, forge mergeability + mapping. + +### Phase 4: `codev check deploy` + +**Dependencies**: Phase 3 (the `check` group in `index.ts`, the shared `CommitRuns` summary) + +#### Objective + +Answer, for one or more merged PRs, whether each merge reached the deploy branch and, where a +deploy workflow is configured, the latest green deploy run. With nothing configured the command +is still useful: it confirms the merge is on the live base branch and reports CI on the merge +commit. + +#### Files to Create / Modify + +- `packages/codev/src/commands/check/deploy.ts`. For each PR: + - `pr-view` is read for state, `mergeCommit`, `mergedAt` and `baseRefName`. A PR that + cannot be read is a per-PR `not run`. It does not exit 2. + - `merged`: `ok` when the PR is merged and has a merge commit; otherwise attention. + - `on-branch`: the branch is `check.deploy.branch`, or else the PR's base. `ls-remote` gives + its tip, `ensureCommits` fetches what is missing, and `merge-base --is-ancestor` decides. + - `deploy-run`, when `check.deploy.workflow` is set: + - `workflow-runs(workflow, branch)` is read, and the newest run with `status=completed` + and `conclusion=success` is taken. Is the merge an ancestor of that run's `headSha`? + - No green run among those returned is attention. + - When `check.deploy.workflow` is unset, `deploy-run` is `off` with reason + `check.deploy.workflow`. + - `merge-checks`, shown only when no workflow is configured: `commit-checks` on the merge + commit, summarized with the Phase 3 `CommitRuns` logic. + - The overall verdict is the worst across all PRs. +- `packages/codev/src/commands/check/index.ts`: add `deploy [--json]`. +- Tests (new): `__tests__/check-deploy.test.ts` (POSIX stubs) and + `__tests__/check-deploy-readonly.test.ts` (real repos, config forge overrides, every + platform). + +#### Deliverables + +- [ ] `codev check deploy … [--json]`, with the checks `merged`, `on-branch`, `deploy-run` + and `merge-checks` +- [ ] Tests for this phase + +#### Acceptance Criteria + +- [ ] Spec Test Scenarios 13, 14, 15 and 15a pass. 15a: `check deploy 1948 99999` reports #1948 + in full, reports #99999 as `not run: PR not found`, and exits 1. +- [ ] `workflow-runs` disabled or failing makes `deploy-run` `not run` (exit 1), never `ok`. + The same holds for `commit-checks` and `merge-checks`. +- [ ] Real-repo snapshot identical before and after, including a run that must fetch the + deploy-branch tip. +- [ ] `--json` matches `DeployReport`. Exit 2 is reserved for usage, repository and + configuration failures. + +#### Test Plan + +- Integration (POSIX): `check-deploy.test.ts`, with the deploy branch ahead of, behind, and + missing the merge, and the latest green run before and after the merge. +- Integration (every platform): the snapshot test. + +### Phase 5: `codev check worktree` + +**Dependencies**: Phase 2 (core). It also uses the `pr-search` and `pr-view` concepts, and the +#1950 keep-list definitions (see coordination). + +#### Objective + +Answer read-only whether a builder's worktree and its local branch can be removed without +losing data. Report the lifecycle separately: an open PR is attention even when nothing would +be lost. + +#### Coordination with #1950 (PR #1954, open at plan time) + +At the start of this phase, check whether PR #1954 has merged. + +- **Merged**: merge `origin/main` into this branch. Reuse `DEFAULT_KEEP_IGNORED` and + `keepPatterns()` from `packages/codev/src/agent-farm/lib/keep-files.ts`. Export its + never-copy segment set (`NEVER_KEEP`, today module-private) along with a pure + `isNeverKeep(path)`. That is the only change to that file. Then add the spec's agreement + test: the files `check worktree` lists as keep equal the ignored subset of + `listKeepCandidates()` for the same worktree. +- **Not merged**: tell the architect, then follow the spec's rule. This project defines + `DEFAULT_KEEP_IGNORED` (with #1950's defaults), the never-copy set and `keepPatterns()` in + one shared module, `packages/codev/src/lib/keep-ignored.ts`, for cleanup to import, and + #1950 adopts it. Whichever PR lands second adds the agreement test. + +#### Files to Create / Modify + +- `packages/codev/src/agent-farm/lib/builder-scaffold.ts` (new). Exports the spawn scaffold + set: `.builder-*` plus `GUARD_SCRIPT_RELPATH` and `GUARD_SETTINGS_RELPATH` from + `utils/worktree-write-guard.ts`, built from the constants spawn already writes so the two + cannot drift. Also exports `isBuilderScaffold(path)`. +- `packages/codev/src/commands/check/worktree.ts` + - **Resolving the target.** A builder id resolves to `/.builders/`; a + path is resolved to its real path. Either must appear in `git worktree list --porcelain` + and must not be the main worktree, or the command exits 2. The branch comes from the + porcelain entry. + - **`pr`**: `pr-search` with `head:`, keeping exact `headRefName` matches and + preferring OPEN, then the newest MERGED, then CLOSED. Then `pr-view` for `headRefOid`, + which is `mergedHead`, and for the base. OPEN is attention ("builder not finished"). + Unavailable is `not run: PR state not available`. + - **Base**: the PR's `baseRefName`. With no PR, the remote default branch from + `ls-remote --symref origin HEAD`. Its tip comes from `ls-remote`. When it cannot be read, + `commits` is `not run`, and the data verdict is conservative: `NOT REMOVABLE` unless the + local tip is on the live remote branch. + - **`uncommitted`**: `git --no-optional-locks -C status --porcelain=v1 -z + --untracked-files=all`. Scaffold paths are counted separately and are not data. + - **`commits`**: `rev-list --not []`. The live remote + branch tip comes from `ls-remote`; `ensureCommits` fetches what is missing. A remaining + commit is unsafe unless the PR is MERGED and `localTip == mergedHead`, the squash/rebase + rule. + - **`remote`**: matches, ahead, behind, diverged or absent, via `merge-base --is-ancestor` + both ways. Context only. + - **`ignored`**: + - The keep files come from `git -C ls-files --others --ignored --exclude-standard -z + -- :(glob)…`, minus never-keep paths. + - The regenerable count is the remaining entries of + `ls-files --others --ignored --exclude-standard --directory -z`, with directories + collapsed. That keeps the command fast with a large `node_modules/`. + - The summary names the first few entries and points to `afx cleanup --keep-ignored`. + - **Verdict**: `not-removable` when there is uncommitted data or an unsafe commit; + `removable-after-keeping` when the only data is keep-list files; otherwise `removable`. + The exit code is 0 only when the verdict is `removable` and no check needs attention or + did not run. +- `packages/codev/src/commands/check/settings.ts`: read `cleanup.keepIgnored` through the + shared `keepPatterns()`. Errors name the key and the file. +- `packages/codev/src/commands/check/index.ts`: add `worktree [--json]`. +- Tests (new): + - `__tests__/check-worktree.test.ts`: real worktrees made with `git worktree add` in a + fixture repo, forge through config overrides, every platform. + - `__tests__/check-worktree-stubs.test.ts`: POSIX, the stub-`PATH` read-only audit. + - `__tests__/builder-scaffold.test.ts`. + +#### Deliverables + +- [ ] `codev check worktree [--json]`, with the checks `uncommitted`, + `commits`, `remote`, `pr` and `ignored`, and the three verdict words +- [ ] Exported scaffold set; shared keep-list definitions (per the coordination rule) +- [ ] Tests for this phase + +#### Acceptance Criteria + +- [ ] Spec Test Scenarios 16–21 pass, including 19 (squash-merged with tip equal to the merged + head → `REMOVABLE`; one commit after it → `NOT REMOVABLE`) and 20a (clean, PR OPEN → + `REMOVABLE`, `pr` attention, exit 1). +- [ ] The real-repo snapshot is identical before and after, for the main checkout and for the + inspected worktree. That covers refs, `HEAD`, both index files, `FETCH_HEAD` and + `status`. +- [ ] Keep-list agreement test (see coordination), or a note in the thread and the PR body + saying which PR will add it. +- [ ] `pr-search` disabled (as on gitea) → `pr` is `not run`, and the data verdict still comes + from the git facts. + +#### Test Plan + +- Integration (every platform): real worktrees covering clean+merged, modified thread file, + scaffold-only untracked files, an unpushed commit, squash merge, keep-list ignored files + next to `node_modules/`, and an unregistered path. +- Integration (POSIX): the stub-`PATH` audit of every invocation. + +### Phase 6: Architect guidance and command documentation + +**Dependencies**: Phases 3–5 (it documents shipped behavior). First merge `origin/main` +(standing order: #1953 and #1954 touch adjacent files and the skill hashes). + +#### Objective + +Tell architects when to run each command, in both trees, and document the commands everywhere +the `codev` CLI is documented, so the feature is usable end to end by someone who has not +read the spec. + +#### Files to Create / Modify + +- `codev/roles/architect.md` and `codev-skeleton/roles/architect.md`: + - Integration review: run `codev check pr ` before choosing review depth and before + bringing a merge word to the owner, and put its verdict line in the PRFT **Testing** + paragraph. + - Closing the loop: run `codev check worktree ` before `afx cleanup`, and + `codev check deploy ` where the project deploys. + - `consult --type integration` reviews content; `codev check pr` checks mechanics. Run the + check first. +- `codev/resources/risk-triage.md` and `codev-skeleton/resources/risk-triage.md`: Step 1 + becomes `codev check pr ` (its `size` and `to-read` lines), keeping the raw `gh` commands + as what it reads. +- `codev/resources/commands/codev.md` and `codev-skeleton/resources/commands/codev.md`: + - a `codev check` section with the three subcommands, sample output, statuses, exit codes + and `--json` + - every `check.*` key with its default, and `cleanup.keepIgnored` + - the only writes the commands make: objects added to the store + - the trust boundary for project concept overrides +- `codev/resources/commands/overview.md` and `codev-skeleton/resources/commands/overview.md`: + a quick-reference row for each subcommand. +- The `codev` skill, in all four copies: `.claude/skills/codev/SKILL.md`, + `.codex/skills/codev/SKILL.md`, `codev-skeleton/.claude/skills/codev/SKILL.md` and + `codev-skeleton/.codex/skills/codev/SKILL.md`. Each gets a `codev check` section with the + exact syntax. Then regenerate `packages/codev/src/lib/shipped-skill-hashes.ts` with + `pnpm --filter @cluesmith/codev generate-skill-hashes`. +- `codev/resources/arch.md` (COLD tier): one entry under Core Components for + `commands/check/`, covering the read-only runner, its allow-list and the forge concepts it + uses. The HOT tier is unchanged; any routing decision is made at review time with the + update-arch-docs skill. +- `CLAUDE.md` and `AGENTS.md` are **not** changed. + +#### Deliverables + +- [ ] Architect role and risk triage in both trees +- [ ] Command reference and overview in both trees; `forge.md` (Phase 1) +- [ ] The `codev` skill in four copies, plus regenerated hashes +- [ ] Cold-tier arch note + +#### Acceptance Criteria + +- [ ] `grep -rn "codev check" codev/ codev-skeleton/ .claude/skills .codex/skills` shows every + file listed above. Each `codev/` and `codev-skeleton/` pair carries the same guidance. +- [ ] The shipped-skill-hash test passes, and so does the skill-refresh/drift test suite. +- [ ] Every sample in the docs is pasted from a real run of the built CLI (`pnpm build`, then + `node packages/codev/dist/cli.js check …`), not written by hand. +- [ ] Full test suite passes. If it fails only on tests unrelated to this change, each of which + passes alone, stop and tell the architect (owner ruling main-32). + +#### Test Plan + +- Existing doc-integrity tests (skill hashes, framework-ref audit and any skeleton/instance + parity checks) run in the full suite. +- Manual: read each changed doc against the shipped CLI's `--help` output. + +## Review-phase obligations (from the spec's success criteria) + +These belong to the Review phase, not to an implementation phase, because each one needs this +project's PR to exist: + +- Run `codev check pr ` at the `pr` gate, where porch status commits sit on head + (the porch-only case), and record its output in the review. Also record the attribution-hit + run from Phase 3. +- Spec Scenario 29: time a run on a 25-file PR with a 3-commit porch tail against GitHub, and + record the time in the review. +- Dispatch the on-demand Windows workflow on the branch and link the run in the PR body. The + commands spawn processes. The command: + `gh workflow run windows.yml --ref builder/spir-1951 -f purpose='codev check runner, git plumbing and forge scripts' -f suites=true`. + +## Testing approach (all phases) + +- **Two kinds of test.** + - **Stub-`PATH` tests** (POSIX only): prove every `gh` and `git` invocation is read-only. The + stubs keep their own allow-list, separate from the runner's. + - **Real-repo tests** (every platform, including the Windows workflow): prove no state change. + They take the forge from `forge` config overrides, so they need neither `gh` nor a + network. + + Runner unit tests inject `spawn` and run everywhere. The stub-`PATH` tests are POSIX-only + because an `sh` stub on `PATH` cannot be run through argv `spawn` on Windows; existing preset + tests skip on Windows for the same reason. +- **Running tests.** Targeted tests while iterating: + `pnpm --filter @cluesmith/codev exec vitest run src/commands/check`. Porch's full suite runs + at each phase boundary. +- **Timeouts** are injected (`timeoutMs`), so no test waits 30 s. + +## Risks and Mitigation + +| Risk | Probability | Impact | Mitigation | +|------|-------------|--------|------------| +| A mutating git command reaches the code path | Low | High | One runner with the allow-list, refusing before spawn. A structural test that nothing else in `commands/check/` imports `child_process` or the dispatcher. Stub tests with an independent list. Real-repo snapshots. | +| A grandchild process holds a pipe, so the dispatcher's timeout does not bound a forge call | Medium | Medium | The runner races each call against its own deadline. A capture-pattern hang test in Phase 1/2. | +| Git pathspec `:(glob)` semantics differ from what users expect, e.g. whether `**/x` matches at the root | Medium | Low | One table test for each default glob in Phase 2, run against real git. The docs say "git pathspec glob". | +| The GitHub `check-runs` and `actions/runs` join is awkward in `jq` | Medium | Low | `workflow` is optional in the contract. If the join proves brittle, the script omits it, and the summary names the check run alone. | +| gitlab and gitea `pr-view` mappings are unverified (no glab or Gitea server here) | High | Medium | Mapped from the documented API fields and marked UNVERIFIED like the sibling scripts. Stub-CLI tests pin the mapping. `commit-checks` and `workflow-runs` are explicitly disabled there, so nothing is guessed. | +| PR #1954 lands `cleanup.keepIgnored` in a different shape, or late | Medium | Medium | The Phase 5 coordination rule: reuse it if merged, otherwise define the shared module and notify. The agreement test is owned by whichever PR lands second. | +| `afx cleanup`'s scaffold regex (`^\?\? \.builder-`) is narrower than the exported scaffold set, which also has the write-guard files | Medium | Low | The spec says cleanup's behavior does not change, and #1954 is editing `cleanup.ts`, so cleanup is left alone here. The plan-approval message flags the discrepancy for the architect to decide: switch cleanup to `isBuilderScaffold()` in this PR, or not. | +| Exit 1 becomes routine noise, e.g. `mergeable: UNKNOWN` just after a push, or CI still running at the `pr` gate | Medium | Medium | The end-of-run `pr-view` re-read replaces `UNKNOWN`. The verdict line says `checks (running)` rather than a bare `checks`. `check.skip` lets a project make exit 0 meaningful. | +| Merge conflicts with sibling PRs in `forge.ts`, `config.ts` or the skill hashes | Medium | Low | Merge `origin/main` before Phases 5 and 6. Edits to shared files stay small and additive. | + +## Documentation Updates + +- `codev/resources/commands/forge.md`: new concepts and `pr-view` fields (Phase 1). +- `codev/roles/architect.md`, `codev/resources/risk-triage.md`, + `codev/resources/commands/codev.md` and `codev/resources/commands/overview.md`, each mirrored + in `codev-skeleton/` (Phase 6). +- The `codev` skill, four copies, plus regenerated `shipped-skill-hashes.ts` (Phase 6). +- `codev/resources/arch.md`, cold tier: a `commands/check/` entry (Phase 6). Lessons are routed + at review time. +- Not changed: `CLAUDE.md`/`AGENTS.md`, porch's `pr` gate text, and the builder role. These + are the owner's decisions on Open Questions 3–4. From c3fb8e6197e9aca94fdf2fb5c3788f97d4716f21 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 13:31:53 -0800 Subject: [PATCH 10/94] chore(porch): 1951 plan build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 5de3bff30..975227f32 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -16,10 +16,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T21:23:07.115Z' +updated_at: '2026-11-23T21:31:53.045Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From cbc82c02ab87892bfb975d32dcc2d442921660c4 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 13:32:09 -0800 Subject: [PATCH 11/94] [Spec 1951] Thread log: plan phase --- codev/state/spir-1951_thread.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 353dd72be..733dc34bf 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -24,3 +24,20 @@ All points accepted and folded in: - Added `linked-issue` check (closing keyword vs builder branch id), input validation, deploy multi-PR error semantics (per-PR `not run`, exit 1), the #1950 landing-order rule, and all four `codev` skill copies + hash regeneration in the docs criterion. + +## 2026-11-23 — plan +- spec-approval approved by the owner (relayed by architect main); owner adopted the recommended + answers to Open Questions 1–4 (`codev check`; attribution off by default; gate text and builder + role unchanged). +- Plan: 6 phases — forge read concepts → read-only core → `check pr` → `check deploy` → + `check worktree` → docs/guidance. Commit 9fbc2374c. +- Decision: every glob (`check.*`, `cleanup.keepIgnored`) is a git `:(glob)` pathspec matched by git + itself — same semantics as #1950's `listKeepCandidates`, no glob dependency (Node 20 has no stable + `path.matchesGlob`). +- gitlab/gitea get the new `pr-view` fields but explicitly disable `commit-checks`/`workflow-runs` + (unverifiable here; shows as a named `not run`). +- Found: `afx cleanup`'s scaffold regex `^\?\? \.builder-` misses the write-guard files + (`.claude/hooks/…`); spec says cleanup unchanged and #1954 edits cleanup.ts — flagged for the + architect rather than changed. +- PR #1954 (#1950, keep-files.ts with DEFAULT_KEEP_IGNORED) still open; Phase 5 has a + merged/not-merged rule. From d213afdc3f5e77b526c7ffa7aea29cd89e7e05f3 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 13:40:45 -0800 Subject: [PATCH 12/94] [Spec 1951] Plan with multi-agent review --- .../1951-read-only-pr-check-for-archite.md | 645 +++++++++++------- 1 file changed, 404 insertions(+), 241 deletions(-) diff --git a/codev/plans/1951-read-only-pr-check-for-archite.md b/codev/plans/1951-read-only-pr-check-for-archite.md index d550bc50b..44a564458 100644 --- a/codev/plans/1951-read-only-pr-check-for-archite.md +++ b/codev/plans/1951-read-only-pr-check-for-archite.md @@ -9,8 +9,7 @@ The plan implements the spec's Approach 1: a read-only command group, `codev che spec's recommended answers to Open Questions 1–4, and the plan treats them as settled: 1. Placement is **`codev check`**, not `afx`. -2. **`check.attribution` is off by default** (`[]`, shown as `off`). Default patterns would - impose one attribution policy on every adopter. +2. **`check.attribution` is off by default** (`[]`, shown as `off`). 3. **Porch's `pr` gate message is not changed.** The architect role carries the instruction. 4. **The builder role is not changed.** @@ -21,21 +20,52 @@ The work goes in dependency order: 1. **Forge data first.** The checks cannot be computed without it: the head SHA, draft flag, mergeability and merge commit from `pr-view`, plus two new read concepts, `commit-checks` and `workflow-runs`. -2. **The read-only core next.** This is one argv runner with the allow-list. It is the only - path to a subprocess in the module, and a structural test proves that. The core also holds - the configuration, input validation, the report model, the renderers and the shared - git-plumbing facts (live tips, ref-neutral fetch, git version gate). -3. **The three commands**, each in its own phase, on top of the core. -4. **Guidance and docs** in both trees, after merging `origin/main`, because the sibling +2. **The read-only core next.** This is one argv runner with a closed allow-list. It is the + only path to a subprocess in the module, and an audited-imports test keeps it that way. The + core also holds the configuration, input validation, the report model, the renderers and the + shared git-plumbing facts (live tips, ref-neutral fetch, git version gate). +3. **`check pr`**, in two phases: the merge mechanics computed locally, then the forge-fed + state and CI checks. +4. **`check deploy`**, then **`check worktree`**. +5. **Guidance and docs** in both trees, after merging `origin/main`, because the sibling PR #1954 (`afx cleanup --keep-ignored`, issue #1950) touches the skill files and the shipped-skill hashes. -**Glob semantics, decided here.** Every glob in `check.*` and `cleanup.keepIgnored` is a git -pathspec with `:(glob)` magic, and git itself does the matching, through `git diff … -- -:(glob)

` and `git ls-files … -- :(glob)

`. #1950's `listKeepCandidates` already matches -the keep list this way. So `check worktree` and `afx cleanup --keep-ignored` agree by -construction, and no glob library is added. Node ≥ 20 has no stable `path.matchesGlob`, and -`minimatch` is only a transitive dependency here. +### Decisions made in this plan + +- **Roots come from git, not `findWorkspaceRoot()`.** Both `findWorkspaceRoot()` + implementations return a builder worktree's *own* root when run inside it (#407), and + `.builders/` does not exist there. `codev check` asks git for both roots, through the + runner: + - **`mainRoot`** is the first entry of `git worktree list --porcelain`. Git always lists the + main worktree first. + - **`checkoutRoot`** is `git rev-parse --show-toplevel`. + + Configuration loads from `mainRoot`, and builder ids resolve under + `/.builders/`. The command therefore behaves the same from the main checkout + and from any builder worktree. Every git command runs in `mainRoot`, where refs and the + object store are shared across worktrees. The exceptions are the per-worktree reads in + `check worktree`, which run with `-C `. No `origin` gives exit 2, and so does + running outside a git repository. +- **Every glob is a git pathspec with `:(glob)` magic, and git does the matching.** This + applies to `check.watch`, `check.flag`, `check.notForReading` and `cleanup.keepIgnored`. The + calls are `git diff … -- :(glob)

…` and `git ls-files … -- :(glob)

…`. #1950's + `listKeepCandidates` already matches the keep list this way, so `check worktree` and + `afx cleanup --keep-ignored` agree by construction, and no glob library is added. Node ≥ 20 + has no stable `path.matchesGlob`, and `minimatch` is only a transitive dependency here. + - **The empty-list trap.** A bare `--` with no pathspec matches *every* file. So an empty + *include* list (`check.watch`, `check.flag`, `cleanup.keepIgnored`) short-circuits to "no + matches" without running git. + - An *exclude* list (`check.notForReading`) is passed as `-- . ':(exclude,glob)

'…`. When + it is empty, the pathspec is omitted entirely, which correctly means all files. +- **The diff range for `watched`, `size`, `to-read` and `overlap` is merge-base → head**, which + is what the forge's diff view shows. `overlap` adds merge-base → base tip and intersects the + two. +- **The `forge` check is `ok` for `MERGEABLE` with `mergeStateStatus` `CLEAN` or `HAS_HOOKS`.** + `HAS_HOOKS` goes slightly beyond the spec's "its clean state". It means "clean, with + pre-receive hooks" on GitHub Enterprise, and treating it as attention would be pure noise. + `UNSTABLE`, meaning non-required checks failing, is attention here *and* in `checks`. That + double report is deliberate and documented. ## Phases (Machine Readable) @@ -44,7 +74,8 @@ construction, and no glob library is added. Node ≥ 20 has no stable `path.matc "phases": [ {"id": "forge_read_concepts", "title": "Forge read concepts for PR mechanics"}, {"id": "readonly_core", "title": "Read-only runner, configuration and report core"}, - {"id": "check_pr", "title": "codev check pr"}, + {"id": "check_pr_mechanics", "title": "codev check pr: merge mechanics"}, + {"id": "check_pr_forge", "title": "codev check pr: forge state and CI checks"}, {"id": "check_deploy", "title": "codev check deploy"}, {"id": "check_worktree", "title": "codev check worktree"}, {"id": "docs_guidance", "title": "Architect guidance and command documentation"} @@ -56,32 +87,35 @@ construction, and no glob library is added. Node ≥ 20 has no stable `path.matc ``` packages/codev/src/commands/check/ - allow-list.ts pure: git argv grammar + allowed forge concepts (Phase 2) - runner.ts the ONLY subprocess path: git(argv), forge(concept, env); timeouts (Phase 2) - validate.ts PR number, SHA, builder id, config-string validation (Phase 2) - settings.ts check.* (and cleanup.keepIgnored) load + validate, naming key and file (Phase 2/5) - report.ts schema-1 types, statuses, verdict, exit code, check.skip (Phase 2) - render.ts human summary, --json, error report (Phase 2) - git-facts.ts git version gate, live tip (ls-remote), ensureObjects (ref-neutral fetch), - merge-base, pathspec-filtered diffs, ancestry (Phase 2) - index.ts `codev check` commander group, --json, exit-code mapping (Phase 3; grows in 4, 5) - pr.ts, porch-only.ts, linked-issue.ts (Phase 3) - deploy.ts (Phase 4) - worktree.ts (Phase 5) - __tests__/helpers/git-fixture.ts real repos: bare "origin", clones, worktrees, state snapshot - __tests__/helpers/stub-bin.ts stub gh (fixtures) + stub git (recorder → real git) + allow-list.ts pure: closed git argv grammar + allowed forge concepts (Phase 2) + runner.ts the ONLY subprocess path: git(argv), forge(concept, env) (Phase 2) + validate.ts PR number, SHA, builder id, -C path, config-string checks (Phase 2) + roots.ts mainRoot / checkoutRoot from git, origin required (Phase 2) + settings.ts check.* (and, in Phase 6, cleanup.keepIgnored), naming key+file (Phase 2) + report.ts schema-1 types, statuses, verdict, exit code, check.skip, + summarizeRuns() → CommitRuns (shared by pr and deploy) (Phase 2) + render.ts human summary, --json, error report (Phase 2) + git-facts.ts git version gate, live tip, ensureCommits (ref-neutral fetch), + merge-base, ancestry, pathspec diffs/numstat (Phase 2) + index.ts `codev check` commander group, --json, exit-code mapping (Phase 3; grows 5, 6) + pr.ts (Phases 3, 4) + porch-only.ts, linked-issue.ts (Phase 4) + deploy.ts (Phase 5) + worktree.ts (Phase 6) + __tests__/helpers/git-fixture.ts real repos: bare "origin", clones, worktrees, state snapshot + __tests__/helpers/stub-bin.ts stub gh (fixtures) + stub git (recorder → real git) ``` `cli.ts` registers the group with `program.addCommand(buildCheckCommand())`. The group calls -`exitOverride()`, so a commander usage error exits **2**, not commander's default 1. When -`--json` is in argv, the error goes out as the `ErrorReport` object. Each command function -takes `{ cwd, workspaceRoot, timeoutMs }` and returns `{ report, exitCode }`. Tests call it in -process, and the CLI wrapper prints the result and exits. +`exitOverride()`, and the handler maps commander's errors to exit codes: -The workspace root comes from `findWorkspaceRoot()`, as the other `codev` commands do. From a -builder worktree that is still the main checkout, so config and `.builders/` resolve the same -way. `codev check` does not require a `codev/` directory. It does require a git repository -with an `origin` remote, and without one it exits 2. +- `commander.helpDisplayed` and `commander.version` exit **0**, so `codev check --help` and + `codev check pr --help` succeed. +- Every other `CommanderError` is a usage error and exits **2**, not commander's default 1. + When `--json` is in argv, the error goes out as the `ErrorReport` object. + +Each command function takes `{ cwd, timeoutMs }` and returns `{ report, exitCode }`. Tests call +it in process, and the CLI wrapper prints the result and exits explicitly. ## Phase Breakdown @@ -113,8 +147,8 @@ each new field or concept, or explicitly disabling it. Nothing is left silently - `packages/codev/src/lib/forge.ts`: - `KNOWN_CONCEPTS` += `commit-checks`, `workflow-runs`. - The gitlab and gitea presets pass both new concepts in their explicit disabled list. - Without that, `buildPresetFromScripts` would omit them and let them fall through to the - GitHub default. + Without that, `buildPresetFromScripts` would omit them and `getForgeCommand` would fall + through to the GitHub default, so a gitlab workspace would silently run `gh`. - `ForgeCommandOptions.timeoutMs?`, default `30_000`. The dispatcher's existing limit stays the default. - `ForgeCommandError.timedOut: boolean`, derived from the exec error's `killed`/`signal`. @@ -122,11 +156,9 @@ each new field or concept, or explicitly disabling it. Nothing is left silently - `packages/codev/scripts/forge/github/pr-view.sh`: add `headRefOid,isDraft,mergeable,mergeStateStatus,mergeCommit,mergedAt` to the `--json` list. - `packages/codev/scripts/forge/github/commit-checks.sh` (new). Input `CODEV_COMMIT_SHA`. - - Makes read-only `gh api` GET calls: - - `repos/{owner}/{repo}/commits/$SHA/check-runs` (paginated) - - `…/commits/$SHA/status` (legacy commit statuses) - - `…/actions/runs?head_sha=$SHA`, which supplies the workflow name of each check run - through its `check_suite_id` + - Makes two read-only `gh api` GET calls: + - `repos/{owner}/{repo}/commits/$SHA/check-runs?per_page=100` with `--paginate` + - `repos/{owner}/{repo}/commits/$SHA/status` (legacy commit statuses) - Normalizes everything to `CommitCheckItem[]`: - completed + success → `pass` - skipped → `skipped` @@ -134,20 +166,29 @@ each new field or concept, or explicitly disabling it. Nothing is left silently - failure, cancelled, timed_out, action_required, stale or startup_failure → `fail` - not completed → `pending` - status `success` → `pass`; `failure` or `error` → `fail`; `pending` → `pending` + - `workflow` is omitted. The contract makes it optional, and labeling it would cost a + third call per commit (`actions/runs?head_sha=`) against Scenario 29's time budget. - Uses the capture-then-`jq` shape with `# forge-executable: gh`, like `pr-list.sh`. - `packages/codev/scripts/forge/github/workflow-runs.sh` (new). Inputs `CODEV_WORKFLOW` and `CODEV_BRANCH`. Runs `exec gh run list --workflow "$CODEV_WORKFLOW" --branch "$CODEV_BRANCH" --limit 50 --json headSha,status,conclusion,url,createdAt`. -- `packages/codev/scripts/forge/gitlab/pr-view.sh`: add the new fields from glab's MR object, - marked UNVERIFIED like its siblings: - - `sha` → `headRefOid` - - `draft` → `isDraft` - - `merge_commit_sha // squash_commit_sha` → `mergeCommit.oid` - - `merged_at` → `mergedAt` - - `detailed_merge_status` → `mergeable`: `conflict` → `CONFLICTING`; `checking`, - `unchecked` or `preparing` → `UNKNOWN`; anything else → `MERGEABLE` - - `detailed_merge_status` → `mergeStateStatus`: `mergeable` → `CLEAN`; anything else - upper-cased +- `packages/codev/scripts/forge/gitlab/pr-view.sh`: rewritten into the safe shape. Today it is + a bare `glab … | jq` pipeline. + - **Capture before piping.** POSIX sh has no pipefail, so a failed `glab` would surface as + `jq`'s exit 0. That was the #1645 failure its github and gitea siblings were fixed for. + - **Declare `# forge-executable: glab`.** `extractExecutable` skips `out="$(…)"` lines, so + without the declaration doctor would report `printf`. That was #1455. + - Adds the new fields from glab's MR object, marked UNVERIFIED like its siblings: + - `sha` → `headRefOid` + - `draft` → `isDraft` + - `merge_commit_sha // squash_commit_sha` → `mergeCommit.oid` + - `merged_at` → `mergedAt` + - `detailed_merge_status` → `mergeable`: `conflict` → `CONFLICTING`; `checking`, + `unchecked` or `preparing` → `UNKNOWN`; anything else → `MERGEABLE` + - `detailed_merge_status` → `mergeStateStatus`: `mergeable` → `CLEAN`; anything else + upper-cased + - Existing fields pass through unchanged. The pipefail fix is an adjacent bug fixed in + place, and the PR body will name it. - `packages/codev/scripts/forge/gitea/pr-view.sh`: add the new fields from the REST pull object it already fetches: `head.sha`, `draft`, `mergeable` (bool → `MERGEABLE` or `CONFLICTING`), `merge_commit_sha`, `merged_at`. @@ -155,6 +196,9 @@ each new field or concept, or explicitly disabling it. Nothing is left silently `null`. They cannot be verified in this environment, which has no glab and no Gitea server. A disabled concept shows as `not run: … unavailable on `, which is honest. A project can supply its own override. +- Existing tests with concept counts: `src/__tests__/forge.test.ts` ("returns all 18 known + concept names", `toHaveLength(18)`) and `src/__tests__/doctor.test.ts` (the hard-coded + 18-concept mock list and its comment) go up to 20. - `codev/resources/commands/forge.md`: document the two new concepts (inputs, output contract, state normalization), the new optional `pr-view` fields, which presets provide what, and that `codev check` is their consumer. @@ -165,9 +209,10 @@ each new field or concept, or explicitly disabling it. Nothing is left silently - [ ] Contract types for the new fields and the two concepts - [ ] `commit-checks` and `workflow-runs` registered. The github scripts implement them; the gitlab and gitea presets disable them explicitly. -- [ ] `pr-view` returns the new fields on github, gitlab and gitea +- [ ] `pr-view` returns the new fields on github, gitlab and gitea. The gitlab script captures + before piping and declares `forge-executable: glab`. - [ ] `timeoutMs` option and `timedOut` error flag on the dispatcher -- [ ] `forge.md` updated +- [ ] Concept-count tests updated; `forge.md` updated - [ ] Tests for this phase #### Acceptance Criteria @@ -176,16 +221,18 @@ each new field or concept, or explicitly disabling it. Nothing is left silently them as `default` for github, linear and jira (they fall through to github), and as `disabled` for gitlab and gitea. So `codev doctor`, which lists `resolveAllConcepts`, shows them. +- [ ] `resolveAllConcepts({provider: 'gitlab'})` reports `pr-view`'s executable as `glab`, not + `printf`. - [ ] With a stub `gh` on `PATH`, the github `pr-view`, `commit-checks` and `workflow-runs` scripts emit JSON that matches the contract. Fixtures cover mixed conclusions, legacy - statuses, two pages of check runs and a run with no workflow match. The stub fails the - test on any `gh` call other than `pr view`, `run list`, or `api` with GET and no field - flags. -- [ ] The gitlab and gitea `pr-view` mappings are verified against a stub `glab` and `tea` - (skipped when `jq` is absent, as the existing preset tests are). + statuses and two pages of check runs. The stub fails the test on any `gh` call other + than `pr view`, `run list`, or `api` with GET and no field flags. +- [ ] The gitlab and gitea `pr-view` mappings are verified against a stub `glab` and `tea`. A + failing `glab` makes the gitlab script exit non-zero. These tests are skipped when `jq` + is absent, as the existing preset tests are. - [ ] A concept that sleeps past `timeoutMs` returns `error.timedOut === true`, in both the `exec gh` script shape and the capture-pattern shape. -- [ ] Existing forge and doctor tests still pass, with any concept-count expectations updated. +- [ ] Existing forge and doctor tests pass with the updated counts. #### Test Plan @@ -201,39 +248,51 @@ each new field or concept, or explicitly disabling it. Nothing is left silently #### Objective The read-only guarantee as code: one runner that refuses any non-allowed command before -spawning it, plus everything the three commands share. That shared part is validated -configuration and input, the schema-1 report with its verdict and exit codes, both renderers, -and the git plumbing that reads live tips and fetches objects without moving a ref. +spawning it, plus everything the commands share. That shared part is validated configuration +and input, the git-derived roots, the schema-1 report with its verdict and exit codes, both +renderers, the run summarizer, and the git plumbing that reads live tips and fetches objects +without moving a ref. #### Files to Create / Modify -- `packages/codev/src/commands/check/allow-list.ts` - - **Git grammar**: `git [--no-optional-locks] [-C

] [-c gc.auto=0] [-c maintenance.auto=false] …`. - No other global option is accepted. - - **Allowed subcommands**: the spec's list exactly. `version`, `rev-parse`, `rev-list`, - `merge-base`, `log`, `show`, `cat-file` and `for-each-ref` are allowed without - conditions. The others carry a rule: +- `packages/codev/src/commands/check/allow-list.ts`: a **closed** grammar. Every token must be + explicitly permitted. An unknown flag is refused, and so is a permitted flag in the wrong + position. + - **Global options**: only `--no-optional-locks`, `-C `, + `-c gc.auto=0` and `-c maintenance.auto=false`. `--exec-path`, `--git-dir`, `-c ` + and everything else are refused. + - **Per subcommand**, an explicit list of permitted flags (exact, or `--flag=`) + and of positional kinds (SHA, ref name, revision range, `--` followed by pathspecs). The + list is exactly what the commands use. A few rules worth naming: | Subcommand | Rule | |---|---| - | `diff`, `diff-tree` | `--output` is refused | - | `ls-files` | read flags only | - | `ls-remote` | the remote must be `origin`; `--symref` is allowed | - | `worktree` | `list` only | - | `config` | `--get` or `--get-regexp` only | - | `symbolic-ref` | read form only: one positional argument | + | `diff`, `log`, `show` | must carry `--no-ext-diff --no-textconv`, so no repository-configured diff program runs; `--output` is refused | + | `cat-file` | `-e`, `-t`, `-p` only; `--textconv` and `--filters` are refused | + | `ls-remote` | `origin` only; `--symref` is allowed; `--upload-pack` is refused | + | `fetch` | only `-c gc.auto=0 -c maintenance.auto=false fetch --no-write-fetch-head --refmap= origin …`, every `` validated; `--upload-pack` is refused | | `status` | only with the global `--no-optional-locks` | | `merge-tree` | must include `--write-tree` | - | `fetch` | only the exact ref-neutral form: `-c gc.auto=0 -c maintenance.auto=false fetch --no-write-fetch-head --refmap= origin …`, every `` validated | + | `symbolic-ref` | read form only | + | `config` | `--get` or `--get-regexp` only | + | `worktree` | `list --porcelain` only | + - **Environment**: the runner sets `GIT_TERMINAL_PROMPT=0`, so a credential prompt cannot + wait for input. - **Allowed forge concepts**: `pr-view`, `pr-search`, `commit-checks`, `workflow-runs`. +- **Stated trust boundary.** `merge-tree` may run a custom merge driver. A driver is defined + only in the *user's own* git config, never by the PR: `.gitattributes` can name a driver but + cannot define its command. It is trusted like a project's own concept override, and the docs + say so (Phase 7). - `packages/codev/src/commands/check/runner.ts` - `createRunner({ cwd, timeoutMs = 30_000, spawn? })`. Two methods: - `git(args, { network? })` → `{ stdout, stderr, exitCode }`. It uses argv `spawn`, never a shell, with `windowsHide`. - `forge(concept, env)` → `{ data } | { notRun: reason }`. Possible reasons are disabled, - failed (with stderr), timed out and invalid JSON. - - Allow-list violations throw `RunnerRefusal`, which the commands map to exit 2. + failed (with stderr), timed out, and invalid output. **Invalid output** is when + `executeForgeCommandDetailed` returns `data === null && error === null`, because a JSON + parse failure collapses to that. + - Allow-list violations throw `RunnerRefusal` and the commands map it to exit 2. - Networked git calls (`ls-remote`, `fetch`) and every forge call get `timeoutMs`. - The runner also races each call against its own deadline. A grandchild holding a stdio pipe therefore cannot keep a call alive past the bound. A late result is discarded, and @@ -242,34 +301,40 @@ and the git plumbing that reads live tips and fetches objects without moving a r - `packages/codev/src/commands/check/validate.ts` - A PR number must be a positive integer (`^[1-9]\d*$`). - A SHA must be 7–40 hex characters. - - A builder id must be `^[A-Za-z0-9][A-Za-z0-9._-]*$`, with no `..` and no path separator. - Registration in `git worktree list` is confirmed later. + - A builder id must be `^[A-Za-z0-9][A-Za-z0-9._-]*$`, with no `..`. + - A `-C` path must be absolute, with no control characters. - A config string passed to git or a concept may not begin with `-` and may not contain a control character. - A violation throws `InputError` naming the value, and for config, the key and file. +- `packages/codev/src/commands/check/roots.ts` + - Determines `checkoutRoot` (`rev-parse --show-toplevel`) and `mainRoot` (the first + `worktree list --porcelain` entry). + - `requireOrigin()` uses `config --get remote.origin.url`. + - Not in a repository, or no `origin` → exit 2. - `packages/codev/src/commands/check/settings.ts` - - `loadCheckSettings(workspaceRoot)` reads `check.attribution`, `watch`, `flag`, - `notForReading`, `deploy.branch`, `deploy.workflow` and `skip`, and applies the spec's - defaults. + - `loadCheckSettings(mainRoot)` reads `check.attribution`, `watch`, `flag`, `notForReading`, + `deploy.branch`, `deploy.workflow` and `skip`, and applies the spec's defaults. - Validation: - each type - `attribution` regexes compile, case-insensitive - `skip` entries are known check ids - `deploy.*` strings go through `validate.ts` - - Errors name the key and the file `findConfigSource()` reports. -- `packages/codev/src/lib/config.ts`: add `check?: { … }` to `CodevConfig`. Type only, since the - loader already merges arbitrary keys and arrays replace. + - Errors name the key and the file that `findConfigSource(mainRoot, …)` reports. +- `packages/codev/src/lib/config.ts`: add `check?: { … }` to `CodevConfig`. Type only, since + the loader already merges arbitrary keys and arrays replace. - `packages/codev/src/commands/check/report.ts` - The schema-1 types from the spec: `Check`, `PrReport`, `DeployReport`, `WorktreeReport`, - `ErrorReport`. + `ErrorReport`, `CommitRuns`. - `applySkips()`: a skipped check becomes `skip` with reason `check.skip`. - `verdictOf(checks)`: any `attention` or `not-run` → `attention`. - `exitCodeOf(report)`: 0 when clear, 1 when attention. + - `summarizeRuns(sha, items) → CommitRuns`, counting passed, failed and pending, with skipped + and neutral counted as passed. - `packages/codev/src/commands/check/render.ts` - The human form: - - The verdict line comes first, naming each check that needs attention. A qualifier is - added where it tells the architect what to do, e.g. `checks (running)` versus - `checks (failed)`, or `watched (flagged)`. + - The verdict line comes first, naming each check that needs attention, with a qualifier + where it tells the architect what to do (`checks (running)`, `checks (failed)`, + `watched (flagged)`). - Then the header lines, then one line per check with its status word (`ok`, `ATTN`, `info`, `not run`, `off`, `skip`). - Lists are truncated with `… +N`. @@ -278,15 +343,14 @@ and the git plumbing that reads live tips and fetches objects without moving a r - `gitVersion()` and `requireGit(major.minor)`. Below 2.38 the trial merge is `not run`; below 2.29 the ref-neutral fetch is unavailable, so checks that need a missing object are `not run`. - - `requireOrigin()`: no `origin` → exit 2. - `liveTip(branch)`, via `ls-remote origin refs/heads/`. - `remoteDefaultBranch()`, via `ls-remote --symref origin HEAD`. - `hasCommit(sha)`, via `cat-file -e ^{commit}`. - `ensureCommits(shas)`: fetches only the missing SHAs, in the ref-neutral form. On failure it returns a per-SHA `not available locally ()`. - - Also `mergeBase`, `isAncestor` (`merge-base --is-ancestor`), and - `changedFiles(from, to, { include?, exclude? })` and `numstat(…)`, which use - `-- :(glob)…` and `:(exclude,glob)…` pathspecs. + - Also `mergeBase`, `isAncestor` (`merge-base --is-ancestor`), and `changedFiles(from, to, + { include?, exclude? })` and `numstat(…)`, which use `:(glob)` and `:(exclude,glob)` + pathspecs. An empty include list short-circuits. - Test helpers: `__tests__/helpers/git-fixture.ts` and `__tests__/helpers/stub-bin.ts`. - `git-fixture.ts` builds a bare remote, clones and worktrees. Its `snapshotRepoState(repo)` captures `for-each-ref` output, `HEAD`, the index file's bytes, @@ -298,12 +362,17 @@ and the git plumbing that reads live tips and fetches objects without moving a r - `stub-bin.ts` also writes a `gh` stub that records argv, refuses anything that is not read-only, and answers from a fixtures file. It can sleep on demand, for the timeout cases. + - The stubs record **every** `git` and `gh` invocation the test process makes, from any + module. So a subprocess started outside the runner, perhaps by a transitively imported + helper, is caught too. - Tests (new): `__tests__/allow-list.test.ts`, `runner.test.ts`, `validate.test.ts`, - `settings.test.ts`, `report-render.test.ts`, `git-facts.test.ts`, `structure.test.ts`. + `roots.test.ts`, `settings.test.ts`, `report-render.test.ts`, `git-facts.test.ts`, + `imports.test.ts`. #### Deliverables -- [ ] Allow-list, runner, validation, settings, report, renderers, git facts +- [ ] Allow-list, runner, validation, roots, settings, report (with `summarizeRuns`), + renderers, git facts - [ ] Test helpers: fixture repos, state snapshot, stub `gh`/`git` - [ ] Tests for this phase @@ -312,27 +381,46 @@ and the git plumbing that reads live tips and fetches objects without moving a r - [ ] A table of refused argv is refused, with the spawn spy never called: - `update-ref` - `push` + - `branch -D` - `fetch origin main` - `fetch` without `--refmap=` - `merge-tree` without `--write-tree` - `status` without `--no-optional-locks` - - `diff --output=x` - `config --unset` - `symbolic-ref HEAD refs/heads/x` - `worktree remove` - - `branch -D` - `-c core.hooksPath=x log` -- [ ] Each allowed form of every subcommand passes. + - and, **for every allowed subcommand**, the file-writing and program-running flags: + `--output=x`, `--ext-diff`, `--textconv`, `--filters`, `--upload-pack=x`, + `--exec=x`, and an unknown `--frobnicate` +- [ ] Each allowed form of every subcommand passes. `diff`, `log` and `show` without + `--no-ext-diff --no-textconv` are refused. - [ ] The concept `pr-merge` is refused before dispatch. -- [ ] **Structural test.** Within `commands/check/`, only `runner.ts` imports - `node:child_process`, `child_process` or the forge dispatcher (`lib/forge.js`). The - runner is then the only subprocess path, as spec § Read-only enforcement 1 requires. +- [ ] **Audited imports.** Every import in `commands/check/*.ts` other than `runner.ts` is on + an explicit allow-list kept in the test: + - modules inside `commands/check/` + - `node:path` + - named read-only `node:fs` functions: `existsSync`, `readFileSync`, `realpathSync`, + `statSync`, `lstatSync` + - `lib/config.js`, for `loadConfig` and `findConfigSource`, which only read files + - in Phase 6, the pure scaffold and keep-list modules + + Only `runner.ts` may import `node:child_process` or `lib/forge.js`. Adding an import + means extending the test's list with a reason, which makes the "single subprocess path" + rule reviewable. The stub-`PATH` recorder catches anything that slips past at run time. - [ ] An `ls-remote` or forge call past `timeoutMs` yields `not run: timed out after Ns`. + A forge script that prints non-JSON yields `not run: returned invalid output`. - [ ] Settings: - A non-array `check.watch` exits 2 naming `check.watch` and the file. - So does an unparseable `check.attribution` regex. - So does an unknown `check.skip` id. - `check.notForReading` replaces the default list rather than adding to it. +- [ ] Empty lists: `changedFiles` with `include: []` returns `[]` without running git. With + `exclude: []` it returns every changed file. +- [ ] Each default glob (`CLAUDE.md`, `.codev/**`, `codev/roles/**`, `**/pnpm-lock.yaml` at the + root *and* nested, `codev/projects/**`) matches as documented against real git. +- [ ] Roots: run from a builder worktree made with `git worktree add` in a fixture, `mainRoot` + is the main checkout and `checkoutRoot` is the worktree. Config is read from `mainRoot`. - [ ] Input validation: `12a`, SHA `zz12` and `check.deploy.workflow: "--repo=x"` each exit 2 naming the value, with no subprocess started. - [ ] Real repository: `ensureCommits` fetches a missing SHA from the bare remote. `for-each-ref`, @@ -344,136 +432,191 @@ and the git plumbing that reads live tips and fetches objects without moving a r #### Test Plan - Unit: allow-list tables, runner with injected spawn, validation, settings with temp config - layers, renderers. -- Integration (real git, every platform): `git-facts.test.ts` against `git-fixture.ts` repos. + layers, renderers, `summarizeRuns`. +- Integration (real git, every platform): `git-facts.test.ts` and `roots.test.ts` against + `git-fixture.ts` repos. +- Static: `imports.test.ts` parses the import specifiers of the module's sources. -### Phase 3: `codev check pr` +### Phase 3: `codev check pr` — merge mechanics **Dependencies**: Phase 2 #### Objective -The headline path. An architect runs `codev check pr ` and, in one screen, sees everything -needed to recommend the merge, or the specific thing that blocks it. +The first half of the headline path. `codev check pr ` exists, anchors on the exact head +the forge reports and the live base tip, and reports the checks that are computed locally on +that head: the merge mechanics. It also detects the head or base moving during the run. #### Files to Create / Modify -- `packages/codev/src/commands/check/pr.ts`: the command. The flow: - 1. Validate N. Load the settings. Check the git version. Require `origin`. +- `packages/codev/src/commands/check/pr.ts`. The flow: + 1. Validate N. Find the roots and require `origin`. Load the settings. Check the git + version. 2. Anchor on `pr-view`. Exit 2 when the PR is not found, the call fails or times out, or `headRefOid` is missing. The message names the concept, the provider, and the override file when there is one. 3. Read `baseTip` with `ls-remote`, then `ensureCommits(head, baseTip)`. - 4. Compute the local checks on the exact head: + 4. Compute the local checks on the exact head. The diff range is merge-base → head + throughout. + - `head`: compares the local `refs/heads/` with the forge head: matches, + local ahead (unpushed, attention), behind, diverged, or absent. - `attribution`: the PR description, then each commit in `log baseTip..head`, matched - line by line. + line by line. Configured patterns are compiled once. - `trial-merge`: `merge-tree --write-tree --name-only --no-messages baseTip head`. Exit 1 means conflicts, and the output lists the files. - `watched`: files matching `check.watch`; matches of `check.flag` are flagged. - - `overlap`: files changed on both sides since the merge-base. - - `size` and `to-read`: numstat between the merge-base and head. `to-read` excludes - `check.notForReading` and is sorted largest first. - 5. Fill the forge checks from `pr-view`: - - `state`, from state and draft. Normalization: upper-case it; `OPENED` → `OPEN`; a - non-null `mergedAt` → `MERGED`. - - `forge` is `ok` only for `MERGEABLE` with a `mergeStateStatus` that is absent, `CLEAN` - or `HAS_HOOKS`. Anything else is attention, in the forge's own words. - - `linked-issue`. - 6. Fill `checks` from the porch-only walk (below). - 7. Re-read `pr-view` and `ls-remote`. + - `overlap`: the intersection of merge-base → head and merge-base → baseTip. + - `size` and `to-read`: numstat; `to-read` excludes `check.notForReading` and is sorted + largest first. + 5. Re-read `pr-view` and `ls-remote`. - If the head moved, the `head` check carries `movedTo` and is attention. - If the base moved, `trial-merge` carries `movedTo` and is attention. The spec designates no id for base movement; `trial-merge` is the base-anchored check, so this is an additive key in its `details`. - - An `UNKNOWN` mergeability takes the second read's value. That is the spec's "re-read - once". - 8. `head` also compares the local `refs/heads/` with the forge head: matches, - local ahead (unpushed, attention), behind, diverged, or absent. -- `packages/codev/src/commands/check/porch-only.ts`, mostly pure: - - A commit is porch-only when it is not a merge commit (one parent, from - `rev-list --parents`) and `diff-tree -r --name-only` against its first parent shows only - paths under `codev/projects/`. - - The walk follows the head's first-parent chain down to the merge-base, looking for the - last code commit C. It queries at most 10 commits. When C is not found within that bound, - the check is `not run: more than 10 porch-only commits`. - - `commit-checks` runs on head first, then on each commit below head down to C. It stops at - the first commit that has results. - - **The display carries the architect's standing order.** Right after a builder reaches the - `pr` gate, porch's status commit is head and its CI is still running. The checks line - must then let an architect tell "wait a few minutes" from "something failed". - - Head is C, or head is porch-only with all its runs complete: one line. - - Head is porch-only and its runs are absent or still pending: two lines. The newest - completed code runs at or below head show as `code : 8 passed`. The head line - reads `head : porch-only, 8 still running` or `head : no runs — 3 porch-state - commits above the code`. - - The verdict is the spec's: `ok` only when code runs exist and all passed (skipped and - neutral count as passed) and nothing on head failed or is pending. The attention - qualifier in the verdict line is `checks (running)` when the only problem is pending - runs, and `checks (failed)` or `checks (none)` otherwise. +- `packages/codev/src/commands/check/index.ts` (new): `buildCheckCommand()`, the `check` group + with `pr [--json]`, plus the exit mapping (help and version 0, usage 2). +- `packages/codev/src/cli.ts`: register the group. +- Tests (new): + - `__tests__/check-pr-mechanics.test.ts`: POSIX, with stub `gh` fixtures and the stub `git` + passing through to a real fixture repo. + - `__tests__/check-pr-readonly.test.ts`: every platform, real repos, the forge supplied + through config overrides. A `forge: { "pr-view": "/pr-view.sh" }` fixture works + on Windows too, because Git Bash runs a bare `.sh` path. + - `__tests__/check-cli.test.ts`: the commander wiring. + +#### Deliverables + +- [ ] `codev check pr [--json]`, listed in `codev --help` and `codev check --help` +- [ ] Checks `head`, `attribution`, `trial-merge`, `watched`, `overlap`, `size`, `to-read`; + head/base race detection +- [ ] Tests for this phase + +#### Acceptance Criteria + +- [ ] Spec Test Scenarios 2, 3, 4, 5, 6, 8, 9, 11 and 12 pass as automated tests. +- [ ] Real-repo snapshot identical before and after (Scenario 23), for a clean run, a + conflicting trial merge, a stale local `origin/main`, and a head that must be fetched. +- [ ] Scenario 22 for `check pr`: the stub `gh` and `git` see only read-only invocations, and + an injected `update-ref` or `gh pr merge` is refused by the runner. +- [ ] Scenario 25: a `pr-view` override with no `headRefOid` gives exit 2 naming the concept + and the field. Scenario 27: git older than 2.38 gives `trial-merge` + `not run: requires git 2.38+`. +- [ ] The anchoring `pr-view` hanging gives exit 2, part of Scenario 12b. +- [ ] `codev check --help` and `codev check pr --help` exit 0; a usage error exits 2; with + `--json` a usage error prints the `ErrorReport`. +- [ ] Run from a builder worktree, the command gives the same report as from the main checkout. + +#### Test Plan + +- Integration (POSIX): `check-pr-mechanics.test.ts`, scenario by scenario. +- Integration (every platform): `check-pr-readonly.test.ts`. +- Unit: `check-cli.test.ts`, run through `parseAsync` with an injected exit. + +### Phase 4: `codev check pr` — forge state and CI checks + +**Dependencies**: Phase 3 + +#### Objective + +Complete `check pr` with the checks that need the forge: PR state and draft, the forge's own +mergeability, CI on the right commit (including the porch-only-head case), and the linked +issue. After this phase the headline path is whole. + +#### Files to Create / Modify + +- `packages/codev/src/commands/check/pr.ts`: add four checks. + - `state`, from state and draft. Normalization: upper-case it; `OPENED` → `OPEN`; a + non-null `mergedAt` → `MERGED`. Anything other than an open non-draft PR is attention. + - `forge`: `ok` for `MERGEABLE` with `mergeStateStatus` absent, `CLEAN` or `HAS_HOOKS`. + Anything else is attention, in the forge's own words. An `UNKNOWN` mergeability takes the + end-of-run re-read's value, the spec's "re-read once". If it is still `UNKNOWN`, the + summary says "forge has not computed mergeability yet". + - `checks`, through `porch-only.ts`. + - `linked-issue`, through `linked-issue.ts`. +- `packages/codev/src/commands/check/porch-only.ts`. The selection is pure; the lookups go + through the runner. + - A commit is **porch-only** when it has exactly one parent (from `rev-list --parents`) and + `diff-tree -r --name-only` against that parent lists only paths under `codev/projects/`. + - **Finding C.** Walk the head's first-parent chain toward the merge-base, at most 11 + commits, and stop at the first commit that is not porch-only. That commit is C. When none + is found within the bound, the check is `not run: more than 10 porch-only commits`. + Reaching the merge-base before finding C is "no code commit": the check is attention. + - **Lookups.** At most 10 `commit-checks` calls per run. + 1. Look up head. Call its result `H`, and keep it. + 2. If head is C, the code runs are `H`. Stop. + 3. If `H` is non-empty and all passed, the code runs are `H`. Stop. + 4. Otherwise walk from `head^1` down to C, one lookup per commit. Take the first commit + whose runs are non-empty and all complete; those are the code runs. + 5. If the walk ends without one, take the first commit seen in the walk that had any runs + at all, even if some are still pending. + 6. If no commit had any runs, there are no code runs. + - **Display.** This carries the architect's standing order. Right after a builder reaches the + `pr` gate, porch's status commit is head and its CI is still running, and the line must let + an architect tell "wait a few minutes" from "something failed". + - **One line** when head is C, or when head is porch-only and `H` is all passed. + - **Two lines** otherwise: + - `code : 8 passed`, or `code : no runs` + - `head : porch-only, 8 still running`, or `head : porch-only, 1 failed (unit)`, + or `head : no runs — 3 porch-state commits above the code` + - **Verdict**, the spec's rule: `ok` only when the code runs exist and all passed (skipped and + neutral count as passed) and nothing in `H` failed or is pending. The qualifier in the + verdict line: + - `checks (running)` when the only problem is pending runs + - `checks (failed)` when any run failed + - `checks (none)` when there are no code runs + - The `details` follow the spec: `{ head, code?, lastCodeCommit, porchOnlyAbove }`. - `packages/codev/src/commands/check/linked-issue.ts` - The keyword regex: `\b(close[sd]?|fix(e[sd])?|resolve[sd]?)\b:?\s+#(\d+)`, case-insensitive. These are GitHub's documented closing keywords. - The branch id comes from `^builder/[a-z]+-(\d+)$`. - A keyword alone is `info`. No keyword is `info` with the close-by-hand note. A keyword naming a different issue than the branch's id is attention. -- `packages/codev/src/commands/check/index.ts` (new): `buildCheckCommand()`, the `check` group - with `pr [--json]`, plus the exit-2 mapping. -- `packages/codev/src/cli.ts`: register the group. - Tests (new): - - `__tests__/check-pr.test.ts`: POSIX, with stub `gh` fixtures and the stub `git` passing - through to a real fixture repo. - - `__tests__/check-pr-readonly.test.ts`: every platform, real repos, the forge supplied - through config overrides (`forge: { "pr-view": "", … }`), so no `gh` is - needed. - `__tests__/porch-only.test.ts`: pure selection and display tables. - - `__tests__/check-cli.test.ts`: the commander wiring, including usage errors → exit 2 and a - JSON error. + - `__tests__/check-pr-forge.test.ts`: POSIX stub suite. + - `__tests__/linked-issue.test.ts`. #### Deliverables -- [ ] `codev check pr [--json]`, listed in `codev --help` and `codev check --help` -- [ ] All eleven checks: `head`, `state`, `forge`, `attribution`, `trial-merge`, `checks`, - `watched`, `linked-issue`, `overlap`, `size`, `to-read` -- [ ] Porch-only walk and the two-line display -- [ ] Re-read race detection +- [ ] Checks `state`, `forge`, `checks` (with the porch-only walk and the two-line display) and + `linked-issue`; all eleven checks now present - [ ] Tests for this phase #### Acceptance Criteria -- [ ] Spec Test Scenarios 1–12b pass as automated tests, covering each functional case listed - there. -- [ ] Spec Test Scenarios 22–28a pass for `check pr`: - - the stub `gh` and `git` see only read-only invocations - - an injected `update-ref` or `gh pr merge` is refused by the runner - - the real-repo snapshot is identical before and after, including a conflicting trial - merge and a run that must fetch the head - - a `null` concept and a failing concept give `not run` - - a `pr-view` override with no `headRefOid` gives exit 2 - - git older than 2.38 gives `not run: requires git 2.38+` - - `--json` matches the schema -- [ ] Each `forge-dependent` check (`state`, `forge`, `checks`) shows `not run: …` and - exit 1 with its concept disabled or failing. It is never `ok`. -- [ ] The human summary for Scenario 1 fits in 25 lines (Scenario 30). -- [ ] **Live run.** `codev check pr` is run against at least one real open PR in this - repository, e.g. #1954, from both the main checkout and this worktree. The output is - recorded in the thread log. One run uses a temporary, gitignored - `.codev/config.local.json` with attribution patterns, to exercise an attribution hit; the - file is removed afterwards. `~/.codev/config.json` is never touched. The run on this - project's own PR, where porch-only commits sit on head at the `pr` gate, happens in the - Review phase and goes into the review. +- [ ] Spec Test Scenarios 1, 7, 10, 12a and 12b pass. The Scenario 7 cases are: + - runs only on the code commit + - runs only on head + - runs on a push tip between them + - no runs anywhere + - failure on head while the code commit is green + - **head pending while the code is green**: `code : N passed`, + `head : porch-only, N still running`, verdict `checks (running)` + - head pending while the code failed +- [ ] More than 10 porch-only commits gives `not run: more than 10 porch-only commits`. +- [ ] Scenario 24: with each of `pr-view`'s new fields absent, and with `commit-checks` disabled + or failing, the affected check (`state`, `forge`, `checks`) shows + `not run: …` and exit 1. It is never `ok`. +- [ ] Scenario 28: `--json` for every Phase 3 and 4 scenario parses and matches `PrReport`. +- [ ] Scenario 30: the human summary for Scenario 1 fits in 25 lines. +- [ ] **Live run** against at least one real open PR in this repository, e.g. #1954, from the + main checkout and from this worktree. The output is recorded in the thread log. + - The attribution-hit run is made from a **scratch clone** in the session scratchpad, + with `origin` set to the GitHub URL and its own `.codev/config.local.json` holding the + patterns. Neither the user's main checkout config nor `~/.codev/config.json` is + touched. + - The run on this project's own PR, where porch-only commits sit on head at the `pr` + gate, happens in the Review phase. #### Test Plan -- Integration (POSIX): `check-pr.test.ts`, scenario by scenario. The fixtures model the forge - responses; the git side is real. -- Integration (every platform): `check-pr-readonly.test.ts`, with snapshots taken around - clean, conflicting, stale-local-base and missing-head runs. -- Unit: porch-only selection, linked-issue parsing, state normalization, forge mergeability - mapping. +- Unit: porch-only selection tables (pure), linked-issue parsing, state normalization, forge + mergeability mapping. +- Integration (POSIX): `check-pr-forge.test.ts`, with `commit-checks` fixtures per commit. -### Phase 4: `codev check deploy` +### Phase 5: `codev check deploy` -**Dependencies**: Phase 3 (the `check` group in `index.ts`, the shared `CommitRuns` summary) +**Dependencies**: Phase 3 (the `check` group). It uses `summarizeRuns` from Phase 2. #### Objective @@ -489,15 +632,21 @@ commit. cannot be read is a per-PR `not run`. It does not exit 2. - `merged`: `ok` when the PR is merged and has a merge commit; otherwise attention. - `on-branch`: the branch is `check.deploy.branch`, or else the PR's base. `ls-remote` gives - its tip, `ensureCommits` fetches what is missing, and `merge-base --is-ancestor` decides. + its tip, `ensureCommits(mergeCommit, tip)` fetches what is missing, and + `merge-base --is-ancestor` decides. A failed fetch makes the check `not run`. - `deploy-run`, when `check.deploy.workflow` is set: - `workflow-runs(workflow, branch)` is read, and the newest run with `status=completed` - and `conclusion=success` is taken. Is the merge an ancestor of that run's `headSha`? + and `conclusion=success` is taken. + - That run's `headSha` is validated as a SHA. An invalid value is `not run: workflow-runs + returned invalid headSha`. + - `ensureCommits(headSha)` fetches it if missing. A failure, or a git too old for the + ref-neutral fetch, is `not run: not available locally ()`. + - Then: is the merge an ancestor of that `headSha`? - No green run among those returned is attention. - When `check.deploy.workflow` is unset, `deploy-run` is `off` with reason `check.deploy.workflow`. - `merge-checks`, shown only when no workflow is configured: `commit-checks` on the merge - commit, summarized with the Phase 3 `CommitRuns` logic. + commit, summarized with `summarizeRuns`. - The overall verdict is the worst across all PRs. - `packages/codev/src/commands/check/index.ts`: add `deploy [--json]`. - Tests (new): `__tests__/check-deploy.test.ts` (POSIX stubs) and @@ -514,10 +663,12 @@ commit. - [ ] Spec Test Scenarios 13, 14, 15 and 15a pass. 15a: `check deploy 1948 99999` reports #1948 in full, reports #99999 as `not run: PR not found`, and exits 1. -- [ ] `workflow-runs` disabled or failing makes `deploy-run` `not run` (exit 1), never `ok`. - The same holds for `commit-checks` and `merge-checks`. -- [ ] Real-repo snapshot identical before and after, including a run that must fetch the - deploy-branch tip. +- [ ] A green run whose `headSha` is not local is fetched ref-neutrally and judged. One that + cannot be fetched is `deploy-run` `not run`, never `ok`. +- [ ] `workflow-runs` or `commit-checks` disabled or failing makes the dependent check + `not run` (exit 1). +- [ ] Real-repo snapshot identical before and after, including runs that must fetch the + deploy-branch tip and a run's `headSha`. - [ ] `--json` matches `DeployReport`. Exit 2 is reserved for usage, repository and configuration failures. @@ -527,10 +678,10 @@ commit. missing the merge, and the latest green run before and after the merge. - Integration (every platform): the snapshot test. -### Phase 5: `codev check worktree` +### Phase 6: `codev check worktree` -**Dependencies**: Phase 2 (core). It also uses the `pr-search` and `pr-view` concepts, and the -#1950 keep-list definitions (see coordination). +**Dependencies**: Phase 3 (the `check` group in `index.ts`). It also uses the `pr-search` and +`pr-view` concepts, and the #1950 keep-list definitions (see coordination). #### Objective @@ -542,28 +693,31 @@ be lost. At the start of this phase, check whether PR #1954 has merged. -- **Merged**: merge `origin/main` into this branch. Reuse `DEFAULT_KEEP_IGNORED` and - `keepPatterns()` from `packages/codev/src/agent-farm/lib/keep-files.ts`. Export its - never-copy segment set (`NEVER_KEEP`, today module-private) along with a pure - `isNeverKeep(path)`. That is the only change to that file. Then add the spec's agreement - test: the files `check worktree` lists as keep equal the ignored subset of +- **Merged**: merge `origin/main` into this branch. Move the *pure* keep-list definitions out + of `packages/codev/src/agent-farm/lib/keep-files.ts`, which spawns git, into a new pure + module `packages/codev/src/agent-farm/lib/keep-list.ts`. The definitions are + `DEFAULT_KEEP_IGNORED`, `keepPatterns()` and the never-copy segment set, which is + module-private today and becomes an exported `isNeverKeep(path)`. `keep-files.ts` then + imports them from there. Behavior is unchanged, and #1954's own tests prove it. Add the + spec's agreement test: the files `check worktree` lists as keep equal the ignored subset of `listKeepCandidates()` for the same worktree. -- **Not merged**: tell the architect, then follow the spec's rule. This project defines - `DEFAULT_KEEP_IGNORED` (with #1950's defaults), the never-copy set and `keepPatterns()` in - one shared module, `packages/codev/src/lib/keep-ignored.ts`, for cleanup to import, and - #1950 adopts it. Whichever PR lands second adds the agreement test. +- **Not merged**: tell the architect, then follow the spec's rule. This project creates the + same pure module (`agent-farm/lib/keep-list.ts`, with #1950's defaults) for cleanup to + import, and #1954 adopts it. Whichever PR lands second adds the agreement test. #### Files to Create / Modify -- `packages/codev/src/agent-farm/lib/builder-scaffold.ts` (new). Exports the spawn scaffold - set: `.builder-*` plus `GUARD_SCRIPT_RELPATH` and `GUARD_SETTINGS_RELPATH` from +- `packages/codev/src/agent-farm/lib/builder-scaffold.ts` (new, pure). Exports the spawn + scaffold set: `.builder-*` plus `GUARD_SCRIPT_RELPATH` and `GUARD_SETTINGS_RELPATH` from `utils/worktree-write-guard.ts`, built from the constants spawn already writes so the two cannot drift. Also exports `isBuilderScaffold(path)`. +- `packages/codev/src/agent-farm/lib/keep-list.ts`: per the coordination above. - `packages/codev/src/commands/check/worktree.ts` - - **Resolving the target.** A builder id resolves to `/.builders/`; a - path is resolved to its real path. Either must appear in `git worktree list --porcelain` - and must not be the main worktree, or the command exits 2. The branch comes from the - porcelain entry. + - **Resolving the target.** A builder id resolves to `/.builders/`; a path is + resolved to its real path. Either must appear in `git worktree list --porcelain`, compared + by real path, and must not be the main worktree, or the command exits 2. The branch comes + from the porcelain entry. Because resolution is against `mainRoot`, it works the same from + inside any worktree. - **`pr`**: `pr-search` with `head:`, keeping exact `headRefName` matches and preferring OPEN, then the newest MERGED, then CLOSED. Then `pr-view` for `headRefOid`, which is `mergedHead`, and for the base. OPEN is attention ("builder not finished"). @@ -582,7 +736,7 @@ At the start of this phase, check whether PR #1954 has merged. both ways. Context only. - **`ignored`**: - The keep files come from `git -C ls-files --others --ignored --exclude-standard -z - -- :(glob)…`, minus never-keep paths. + -- :(glob)…`, minus never-keep paths. An empty keep list short-circuits. - The regenerable count is the remaining entries of `ls-files --others --ignored --exclude-standard --directory -z`, with directories collapsed. That keeps the command fast with a large `node_modules/`. @@ -593,6 +747,7 @@ At the start of this phase, check whether PR #1954 has merged. did not run. - `packages/codev/src/commands/check/settings.ts`: read `cleanup.keepIgnored` through the shared `keepPatterns()`. Errors name the key and the file. +- `__tests__/imports.test.ts`: add the two pure modules to the audited list. - `packages/codev/src/commands/check/index.ts`: add `worktree [--json]`. - Tests (new): - `__tests__/check-worktree.test.ts`: real worktrees made with `git worktree add` in a @@ -604,7 +759,7 @@ At the start of this phase, check whether PR #1954 has merged. - [ ] `codev check worktree [--json]`, with the checks `uncommitted`, `commits`, `remote`, `pr` and `ignored`, and the three verdict words -- [ ] Exported scaffold set; shared keep-list definitions (per the coordination rule) +- [ ] Pure scaffold and keep-list modules (per the coordination rule) - [ ] Tests for this phase #### Acceptance Criteria @@ -612,9 +767,12 @@ At the start of this phase, check whether PR #1954 has merged. - [ ] Spec Test Scenarios 16–21 pass, including 19 (squash-merged with tip equal to the merged head → `REMOVABLE`; one commit after it → `NOT REMOVABLE`) and 20a (clean, PR OPEN → `REMOVABLE`, `pr` attention, exit 1). +- [ ] `codev check worktree ` run from inside another builder worktree resolves the + target under `mainRoot`. - [ ] The real-repo snapshot is identical before and after, for the main checkout and for the inspected worktree. That covers refs, `HEAD`, both index files, `FETCH_HEAD` and `status`. +- [ ] `cleanup.keepIgnored: []` reports zero keep files. - [ ] Keep-list agreement test (see coordination), or a note in the thread and the PR body saying which PR will add it. - [ ] `pr-search` disabled (as on gitea) → `pr` is `not run`, and the data verdict still comes @@ -627,9 +785,9 @@ At the start of this phase, check whether PR #1954 has merged. next to `node_modules/`, and an unregistered path. - Integration (POSIX): the stub-`PATH` audit of every invocation. -### Phase 6: Architect guidance and command documentation +### Phase 7: Architect guidance and command documentation -**Dependencies**: Phases 3–5 (it documents shipped behavior). First merge `origin/main` +**Dependencies**: Phases 3–6 (it documents shipped behavior). First merge `origin/main` (standing order: #1953 and #1954 touch adjacent files and the skill hashes). #### Objective @@ -655,8 +813,9 @@ read the spec. - a `codev check` section with the three subcommands, sample output, statuses, exit codes and `--json` - every `check.*` key with its default, and `cleanup.keepIgnored` + - "globs are git `:(glob)` pathspecs" - the only writes the commands make: objects added to the store - - the trust boundary for project concept overrides + - the trust boundary for project concept overrides and the user's own merge drivers - `codev/resources/commands/overview.md` and `codev-skeleton/resources/commands/overview.md`: a quick-reference row for each subcommand. - The `codev` skill, in all four copies: `.claude/skills/codev/SKILL.md`, @@ -665,9 +824,9 @@ read the spec. exact syntax. Then regenerate `packages/codev/src/lib/shipped-skill-hashes.ts` with `pnpm --filter @cluesmith/codev generate-skill-hashes`. - `codev/resources/arch.md` (COLD tier): one entry under Core Components for - `commands/check/`, covering the read-only runner, its allow-list and the forge concepts it - uses. The HOT tier is unchanged; any routing decision is made at review time with the - update-arch-docs skill. + `commands/check/`, covering the read-only runner, its closed allow-list, the audited-imports + rule and the forge concepts it uses. The HOT tier is unchanged; any routing decision is made + at review time with the update-arch-docs skill. - `CLAUDE.md` and `AGENTS.md` are **not** changed. #### Deliverables @@ -700,21 +859,23 @@ project's PR to exist: - Run `codev check pr ` at the `pr` gate, where porch status commits sit on head (the porch-only case), and record its output in the review. Also record the attribution-hit - run from Phase 3. + run from Phase 4. - Spec Scenario 29: time a run on a 25-file PR with a 3-commit porch tail against GitHub, and record the time in the review. - Dispatch the on-demand Windows workflow on the branch and link the run in the PR body. The commands spawn processes. The command: - `gh workflow run windows.yml --ref builder/spir-1951 -f purpose='codev check runner, git plumbing and forge scripts' -f suites=true`. + `gh workflow run windows.yml --ref builder/spir-1951 -f purpose='codev check runner, git plumbing and forge scripts' -f suites=true -f filter=commands/check`. + The targeted job gives fast signal on the new module. ## Testing approach (all phases) - **Two kinds of test.** - - **Stub-`PATH` tests** (POSIX only): prove every `gh` and `git` invocation is read-only. The - stubs keep their own allow-list, separate from the runner's. + - **Stub-`PATH` tests** (POSIX only): prove every `gh` and `git` invocation is read-only, + whichever module made it. The stubs keep their own allow-list, separate from the + runner's. - **Real-repo tests** (every platform, including the Windows workflow): prove no state change. - They take the forge from `forge` config overrides, so they need neither `gh` nor a - network. + They take the forge from `forge` config overrides (absolute `.sh` paths, which Git Bash + runs on Windows), so they need neither `gh` nor a network. Runner unit tests inject `spawn` and run everywhere. The stub-`PATH` tests are POSIX-only because an `sh` stub on `PATH` cannot be run through argv `spawn` on Windows; existing preset @@ -728,24 +889,26 @@ project's PR to exist: | Risk | Probability | Impact | Mitigation | |------|-------------|--------|------------| -| A mutating git command reaches the code path | Low | High | One runner with the allow-list, refusing before spawn. A structural test that nothing else in `commands/check/` imports `child_process` or the dispatcher. Stub tests with an independent list. Real-repo snapshots. | -| A grandchild process holds a pipe, so the dispatcher's timeout does not bound a forge call | Medium | Medium | The runner races each call against its own deadline. A capture-pattern hang test in Phase 1/2. | -| Git pathspec `:(glob)` semantics differ from what users expect, e.g. whether `**/x` matches at the root | Medium | Low | One table test for each default glob in Phase 2, run against real git. The docs say "git pathspec glob". | -| The GitHub `check-runs` and `actions/runs` join is awkward in `jq` | Medium | Low | `workflow` is optional in the contract. If the join proves brittle, the script omits it, and the summary names the check run alone. | +| A mutating git command, or a flag that writes a file or runs a program, reaches the code path | Low | High | A closed per-subcommand grammar that refuses before spawn. Diff-family commands are forced to `--no-ext-diff --no-textconv`. Refusal tests for every subcommand. The audited-imports test. Stub-`PATH` recorders that see every invocation the process makes. Real-repo snapshots. | +| A grandchild process holds a pipe, so the dispatcher's timeout does not bound a forge call | Medium | Medium | The runner races each call against its own deadline. A capture-pattern hang test in Phases 1 and 2. | +| An empty glob list becomes a bare `--`, which matches everything | Medium | High | Empty include lists short-circuit without running git. Empty exclude lists omit the pathspec. Acceptance tests in Phases 2 and 6. | +| Git pathspec `:(glob)` semantics differ from what users expect, e.g. whether `**/x` matches at the root | Medium | Low | One test for each default glob against real git (Phase 2). The docs say "git pathspec glob". | +| The command behaves differently from a builder worktree than from the main checkout | Medium | Medium | Roots come from git (`worktree list` and `rev-parse`), not `findWorkspaceRoot()`. Config comes from `mainRoot`. Tests run from a worktree in Phases 2, 3 and 6. | +| The `commit-checks` call volume threatens Scenario 29's 30 s on a long porch tail | Low | Medium | Two GETs per commit, no workflow-name join. At most 10 lookups, and normally one to three, because the walk stops at the first complete result. | | gitlab and gitea `pr-view` mappings are unverified (no glab or Gitea server here) | High | Medium | Mapped from the documented API fields and marked UNVERIFIED like the sibling scripts. Stub-CLI tests pin the mapping. `commit-checks` and `workflow-runs` are explicitly disabled there, so nothing is guessed. | -| PR #1954 lands `cleanup.keepIgnored` in a different shape, or late | Medium | Medium | The Phase 5 coordination rule: reuse it if merged, otherwise define the shared module and notify. The agreement test is owned by whichever PR lands second. | +| PR #1954 lands `cleanup.keepIgnored` in a different shape, or late | Medium | Medium | The Phase 6 coordination rule: extract its pure definitions if merged, otherwise create the shared pure module and notify. The agreement test is owned by whichever PR lands second. | | `afx cleanup`'s scaffold regex (`^\?\? \.builder-`) is narrower than the exported scaffold set, which also has the write-guard files | Medium | Low | The spec says cleanup's behavior does not change, and #1954 is editing `cleanup.ts`, so cleanup is left alone here. The plan-approval message flags the discrepancy for the architect to decide: switch cleanup to `isBuilderScaffold()` in this PR, or not. | | Exit 1 becomes routine noise, e.g. `mergeable: UNKNOWN` just after a push, or CI still running at the `pr` gate | Medium | Medium | The end-of-run `pr-view` re-read replaces `UNKNOWN`. The verdict line says `checks (running)` rather than a bare `checks`. `check.skip` lets a project make exit 0 meaningful. | -| Merge conflicts with sibling PRs in `forge.ts`, `config.ts` or the skill hashes | Medium | Low | Merge `origin/main` before Phases 5 and 6. Edits to shared files stay small and additive. | +| Merge conflicts with sibling PRs in `forge.ts`, `config.ts` or the skill hashes | Medium | Low | Merge `origin/main` before Phases 6 and 7. Edits to shared files stay small and additive. | ## Documentation Updates - `codev/resources/commands/forge.md`: new concepts and `pr-view` fields (Phase 1). - `codev/roles/architect.md`, `codev/resources/risk-triage.md`, `codev/resources/commands/codev.md` and `codev/resources/commands/overview.md`, each mirrored - in `codev-skeleton/` (Phase 6). -- The `codev` skill, four copies, plus regenerated `shipped-skill-hashes.ts` (Phase 6). -- `codev/resources/arch.md`, cold tier: a `commands/check/` entry (Phase 6). Lessons are routed + in `codev-skeleton/` (Phase 7). +- The `codev` skill, four copies, plus regenerated `shipped-skill-hashes.ts` (Phase 7). +- `codev/resources/arch.md`, cold tier: a `commands/check/` entry (Phase 7). Lessons are routed at review time. - Not changed: `CLAUDE.md`/`AGENTS.md`, porch's `pr` gate text, and the builder role. These are the owner's decisions on Open Questions 3–4. From 97ceaa56f4e3505f92daa28dc7f661fc35c7f35f Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 13:41:08 -0800 Subject: [PATCH 13/94] chore(porch): 1951 plan-approval gate-requested --- codev/projects/1951-read-only-pr-check-for-archite/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 975227f32..761686b66 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -11,6 +11,7 @@ gates: approved_at: '2026-11-23T21:21:55.621Z' plan-approval: status: pending + requested_at: '2026-11-23T21:41:08.788Z' pr: status: pending verify-approval: @@ -19,7 +20,7 @@ iteration: 1 build_complete: true history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T21:31:53.045Z' +updated_at: '2026-11-23T21:41:08.788Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From f33a34cf73bc8c8c4de8007b8fc95d51cce2a88c Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 13:41:18 -0800 Subject: [PATCH 14/94] [Spec 1951] Thread log: plan review --- codev/state/spir-1951_thread.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 733dc34bf..729b8dced 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -41,3 +41,13 @@ All points accepted and folded in: architect rather than changed. - PR #1954 (#1950, keep-files.ts with DEFAULT_KEEP_IGNORED) still open; Phase 5 has a merged/not-merged rule. + +## 2026-11-23 — plan, CMAP iter 1 (codex REQUEST_CHANGES, claude COMMENT) +All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals.md). Notable: +- My plan wrongly assumed `findWorkspaceRoot()` returns the main checkout from a worktree — it returns + the worktree root (#407). Roots now come from git (`worktree list` first entry = mainRoot). +- Allow-list is now a closed per-subcommand grammar; diff/log/show forced `--no-ext-diff --no-textconv`; + `--upload-pack`/`--output`/`--textconv`/`--filters` refused everywhere. +- Empty include pathspec list would become a bare `--` (= every file) — short-circuit. +- Phase 3 split into merge-mechanics / forge-fed checks → 7 phases. Porch-only walk algorithm pinned. +- plan-approval gate reached; waiting for the owner. From c619dc211bde32077507a211c6479610c9cbdb77 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 14:10:01 -0800 Subject: [PATCH 15/94] chore(porch): 1951 plan-approval gate-approved --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 761686b66..b5709a527 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -10,8 +10,9 @@ gates: requested_at: '2026-11-23T19:11:38.967Z' approved_at: '2026-11-23T21:21:55.621Z' plan-approval: - status: pending + status: approved requested_at: '2026-11-23T21:41:08.788Z' + approved_at: '2026-11-23T22:10:01.002Z' pr: status: pending verify-approval: @@ -20,7 +21,7 @@ iteration: 1 build_complete: true history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T21:41:08.788Z' +updated_at: '2026-11-23T22:10:01.005Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From beb8f4f4e8455b12240eb844911cc5b134254131 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 14:10:25 -0800 Subject: [PATCH 16/94] [Spec 1951] Final approved plan (main-36: cleanup uses shared scaffold list) --- .../plans/1951-read-only-pr-check-for-archite.md | 16 +++++++++++++++- codev/state/spir-1951_thread.md | 8 ++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/codev/plans/1951-read-only-pr-check-for-archite.md b/codev/plans/1951-read-only-pr-check-for-archite.md index 44a564458..bea60db78 100644 --- a/codev/plans/1951-read-only-pr-check-for-archite.md +++ b/codev/plans/1951-read-only-pr-check-for-archite.md @@ -712,6 +712,16 @@ At the start of this phase, check whether PR #1954 has merged. `utils/worktree-write-guard.ts`, built from the constants spawn already writes so the two cannot drift. Also exports `isBuilderScaffold(path)`. - `packages/codev/src/agent-farm/lib/keep-list.ts`: per the coordination above. +- `packages/codev/src/agent-farm/commands/cleanup.ts`: **an owner-approved addition to the + spec's "cleanup is unchanged"** (decision main-36, 2026-11-23, "approve, fix cleanup"). + - Do this after merging `origin/main` with PR #1954 in it. + - `hasUncommittedChanges` replaces its `^\?\? \.builder-` regex with `isBuilderScaffold()`, + so one exported list serves cleanup and `check worktree`. + - The notice stays informational. Nothing else about cleanup changes. + - Evidence: on 2026-11-23 cleanup printed "Worktree has uncommitted changes: 1 uncommitted + file(s)" for two bugfix builders that had nothing uncommitted. + - Test: a worktree holding only spawn's scaffold files, write-guard files included, is + reported as not dirty. - `packages/codev/src/commands/check/worktree.ts` - **Resolving the target.** A builder id resolves to `/.builders/`; a path is resolved to its real path. Either must appear in `git worktree list --porcelain`, compared @@ -760,6 +770,7 @@ At the start of this phase, check whether PR #1954 has merged. - [ ] `codev check worktree [--json]`, with the checks `uncommitted`, `commits`, `remote`, `pr` and `ignored`, and the three verdict words - [ ] Pure scaffold and keep-list modules (per the coordination rule) +- [ ] `afx cleanup`'s `hasUncommittedChanges` uses `isBuilderScaffold()` (main-36) - [ ] Tests for this phase #### Acceptance Criteria @@ -773,6 +784,9 @@ At the start of this phase, check whether PR #1954 has merged. inspected worktree. That covers refs, `HEAD`, both index files, `FETCH_HEAD` and `status`. - [ ] `cleanup.keepIgnored: []` reports zero keep files. +- [ ] A worktree holding only spawn's scaffold files, `.builder-*` and both write-guard files, + is not dirty to `afx cleanup`. Cleanup's other behavior is unchanged, and its existing + tests pass. - [ ] Keep-list agreement test (see coordination), or a note in the thread and the PR body saying which PR will add it. - [ ] `pr-search` disabled (as on gitea) → `pr` is `not run`, and the data verdict still comes @@ -897,7 +911,7 @@ project's PR to exist: | The `commit-checks` call volume threatens Scenario 29's 30 s on a long porch tail | Low | Medium | Two GETs per commit, no workflow-name join. At most 10 lookups, and normally one to three, because the walk stops at the first complete result. | | gitlab and gitea `pr-view` mappings are unverified (no glab or Gitea server here) | High | Medium | Mapped from the documented API fields and marked UNVERIFIED like the sibling scripts. Stub-CLI tests pin the mapping. `commit-checks` and `workflow-runs` are explicitly disabled there, so nothing is guessed. | | PR #1954 lands `cleanup.keepIgnored` in a different shape, or late | Medium | Medium | The Phase 6 coordination rule: extract its pure definitions if merged, otherwise create the shared pure module and notify. The agreement test is owned by whichever PR lands second. | -| `afx cleanup`'s scaffold regex (`^\?\? \.builder-`) is narrower than the exported scaffold set, which also has the write-guard files | Medium | Low | The spec says cleanup's behavior does not change, and #1954 is editing `cleanup.ts`, so cleanup is left alone here. The plan-approval message flags the discrepancy for the architect to decide: switch cleanup to `isBuilderScaffold()` in this PR, or not. | +| `afx cleanup`'s scaffold regex (`^\?\? \.builder-`) is narrower than the exported scaffold set, which also has the write-guard files | Medium | Low | Owner ruling main-36: cleanup switches to `isBuilderScaffold()` in Phase 6, after #1954 is merged in. The change is scoped to `hasUncommittedChanges`. | | Exit 1 becomes routine noise, e.g. `mergeable: UNKNOWN` just after a push, or CI still running at the `pr` gate | Medium | Medium | The end-of-run `pr-view` re-read replaces `UNKNOWN`. The verdict line says `checks (running)` rather than a bare `checks`. `check.skip` lets a project make exit 0 meaningful. | | Merge conflicts with sibling PRs in `forge.ts`, `config.ts` or the skill hashes | Medium | Low | Merge `origin/main` before Phases 6 and 7. Edits to shared files stay small and additive. | diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 729b8dced..024b877dc 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -51,3 +51,11 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals - Empty include pathspec list would become a bare `--` (= every file) — short-circuit. - Phase 3 split into merge-mechanics / forge-fed checks → 7 phases. Porch-only walk algorithm pinned. - plan-approval gate reached; waiting for the owner. + +## 2026-11-23 — plan approved (main-36) +- Owner approved plan-approval on d213afdc3 ("approve, fix cleanup"); I ran porch approve. +- Owner-approved addition to the spec's "cleanup is unchanged": in Phase 6, after merging origin/main + with PR #1954, `hasUncommittedChanges` in cleanup.ts uses the shared `isBuilderScaffold()` list. + Scoped to that function; notice stays informational. Evidence: 2026-11-23 cleanup reported + "1 uncommitted file(s)" for two bugfix builders with nothing uncommitted. Record in the review. +- Standing ruling main-32 applies to all seven phases; pr gate is the owner's. From b6c4ba8bef1fd64ec44b6bf3f520c77d2e9acf0a Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 14:10:25 -0800 Subject: [PATCH 17/94] chore(porch): 1951 implement phase-transition --- .../status.yaml | 31 ++++++++++++++++--- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index b5709a527..d703ab702 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -1,9 +1,30 @@ id: '1951' title: read-only-pr-check-for-archite protocol: spir -phase: plan -plan_phases: [] -current_plan_phase: null +phase: implement +plan_phases: + - id: forge_read_concepts + title: Forge read concepts for PR mechanics + status: in_progress + - id: readonly_core + title: Read-only runner, configuration and report core + status: pending + - id: check_pr_mechanics + title: 'codev check pr: merge mechanics' + status: pending + - id: check_pr_forge + title: 'codev check pr: forge state and CI checks' + status: pending + - id: check_deploy + title: codev check deploy + status: pending + - id: check_worktree + title: codev check worktree + status: pending + - id: docs_guidance + title: Architect guidance and command documentation + status: pending +current_plan_phase: forge_read_concepts gates: spec-approval: status: approved @@ -18,10 +39,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T22:10:01.005Z' +updated_at: '2026-11-23T22:10:25.669Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From d119eaaebffd6520a1b91c374e0248ef0028a14a Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 14:13:34 -0800 Subject: [PATCH 18/94] [Spec 1951] Plan: forge verdict follows mergeable only; reviewDecision context (architect, 2026-11-23) --- .../1951-read-only-pr-check-for-archite.md | 35 +++++++++++++------ 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/codev/plans/1951-read-only-pr-check-for-archite.md b/codev/plans/1951-read-only-pr-check-for-archite.md index bea60db78..d9da1b00f 100644 --- a/codev/plans/1951-read-only-pr-check-for-archite.md +++ b/codev/plans/1951-read-only-pr-check-for-archite.md @@ -61,11 +61,21 @@ The work goes in dependency order: - **The diff range for `watched`, `size`, `to-read` and `overlap` is merge-base → head**, which is what the forge's diff view shows. `overlap` adds merge-base → base tip and intersects the two. -- **The `forge` check is `ok` for `MERGEABLE` with `mergeStateStatus` `CLEAN` or `HAS_HOOKS`.** - `HAS_HOOKS` goes slightly beyond the spec's "its clean state". It means "clean, with - pre-receive hooks" on GitHub Enterprise, and treating it as attention would be pure noise. - `UNSTABLE`, meaning non-required checks failing, is attention here *and* in `checks`. That - double report is deliberate and documented. +- **The `forge` check's verdict follows `mergeable` only.** This was decided by the architect on + 2026-11-23 and reported to the owner, who may overrule it. It narrows the spec's "forge + mergeability other than its clean state". + - `MERGEABLE` is `ok`. `CONFLICTING` and `UNKNOWN` are attention, and `UNKNOWN` keeps the + end-of-run re-read. + - `mergeStateStatus` is shown verbatim as context and never changes the verdict by itself. + - When the state is `BLOCKED` and the forge gives a `reviewDecision`, the line says why, e.g. + `ok forge MERGEABLE (state BLOCKED: review required)`. Without a `reviewDecision` it shows + the state alone. + - `--json` `details` carry `mergeable`, `mergeStateStatus` and `reviewDecision`. There is no + new config key. + - Why: on this repository every open PR reads `MERGEABLE`/`BLOCKED`, because PRs merge while + `REVIEW_REQUIRED`. A check that exits 1 on every PR would defeat the headline path. + Conflicts are covered by `trial-merge`, CI by `checks` and draft by `state`. And + `check.skip: ["forge"]` would throw away the `CONFLICTING` and `UNKNOWN` signals too. ## Phases (Machine Readable) @@ -140,6 +150,9 @@ each new field or concept, or explicitly disabling it. Nothing is left silently upper-cased. - `mergeCommit?: { oid: string } | null` - `mergedAt?: string | null` + - `reviewDecision?: string | null`, added by the architect's decision (see Decisions). + GitHub's words: `APPROVED`, `CHANGES_REQUESTED`, `REVIEW_REQUIRED`. The github preset + implements it; gitlab and gitea emit an explicit `null`. - New `CommitCheckItem` `{ name, state: 'pass'|'fail'|'pending'|'skipped'|'neutral', url?, workflow? }` and `CommitChecksResult`. - New `WorkflowRunItem` `{ headSha, status, conclusion, url, createdAt }` and @@ -154,7 +167,7 @@ each new field or concept, or explicitly disabling it. Nothing is left silently - `ForgeCommandError.timedOut: boolean`, derived from the exec error's `killed`/`signal`. - All of these are additive. Existing callers are unchanged. - `packages/codev/scripts/forge/github/pr-view.sh`: add - `headRefOid,isDraft,mergeable,mergeStateStatus,mergeCommit,mergedAt` to the `--json` list. + `headRefOid,isDraft,mergeable,mergeStateStatus,mergeCommit,mergedAt,reviewDecision` to the `--json` list. - `packages/codev/scripts/forge/github/commit-checks.sh` (new). Input `CODEV_COMMIT_SHA`. - Makes two read-only `gh api` GET calls: - `repos/{owner}/{repo}/commits/$SHA/check-runs?per_page=100` with `--paginate` @@ -527,10 +540,12 @@ issue. After this phase the headline path is whole. - `packages/codev/src/commands/check/pr.ts`: add four checks. - `state`, from state and draft. Normalization: upper-case it; `OPENED` → `OPEN`; a non-null `mergedAt` → `MERGED`. Anything other than an open non-draft PR is attention. - - `forge`: `ok` for `MERGEABLE` with `mergeStateStatus` absent, `CLEAN` or `HAS_HOOKS`. - Anything else is attention, in the forge's own words. An `UNKNOWN` mergeability takes the - end-of-run re-read's value, the spec's "re-read once". If it is still `UNKNOWN`, the - summary says "forge has not computed mergeability yet". + - `forge`, per the architect's decision: the verdict follows `mergeable` only. + - `MERGEABLE` is `ok`; `CONFLICTING` and `UNKNOWN` are attention. + - `mergeStateStatus` is context, with the reason taken from `reviewDecision` when the state + is `BLOCKED`, e.g. `MERGEABLE (state BLOCKED: review required)`. + - An `UNKNOWN` mergeability takes the end-of-run re-read's value, the spec's "re-read once". + If it is still `UNKNOWN`, the summary says "forge has not computed mergeability yet". - `checks`, through `porch-only.ts`. - `linked-issue`, through `linked-issue.ts`. - `packages/codev/src/commands/check/porch-only.ts`. The selection is pure; the lookups go From 01565e67be697bf176f261d65f78e1579e6b5f29 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 14:18:05 -0800 Subject: [PATCH 19/94] [Spec 1951][Phase: forge_read_concepts] feat: forge read concepts for PR mechanics - pr-view gains optional headRefOid, isDraft, mergeable, mergeStateStatus, mergeCommit, mergedAt, reviewDecision (github, gitlab, gitea) - new read concepts commit-checks and workflow-runs: github implements them, gitlab and gitea disable them explicitly (no silent fall-through to gh) - dispatcher: timeoutMs option and a timedOut flag on ForgeCommandError - gitlab pr-view now captures before piping (#1645) and declares forge-executable: glab (#1455); it also maps body/baseRefName/headRefName - forge.md documents the concepts and fields --- codev/resources/commands/forge.md | 46 ++- packages/codev/scripts/forge/gitea/pr-view.sh | 19 +- .../scripts/forge/github/commit-checks.sh | 38 ++ .../codev/scripts/forge/github/pr-view.sh | 5 +- .../scripts/forge/github/workflow-runs.sh | 7 + .../codev/scripts/forge/gitlab/pr-view.sh | 47 ++- packages/codev/src/__tests__/doctor.test.ts | 4 +- .../__tests__/forge-windows-launcher.test.ts | 2 +- packages/codev/src/__tests__/forge.test.ts | 12 +- .../spec-1951-forge-read-concepts.test.ts | 371 ++++++++++++++++++ packages/codev/src/lib/forge-contracts.ts | 69 ++++ packages/codev/src/lib/forge.ts | 26 +- 12 files changed, 621 insertions(+), 25 deletions(-) create mode 100755 packages/codev/scripts/forge/github/commit-checks.sh create mode 100755 packages/codev/scripts/forge/github/workflow-runs.sh create mode 100644 packages/codev/src/__tests__/spec-1951-forge-read-concepts.test.ts diff --git a/codev/resources/commands/forge.md b/codev/resources/commands/forge.md index 9c08bd079..30bf9d2f8 100644 --- a/codev/resources/commands/forge.md +++ b/codev/resources/commands/forge.md @@ -78,6 +78,48 @@ Set a concept to `null` to disable it. The feature that uses it will gracefully | `pr-view` | `CODEV_PR_NUMBER`, `CODEV_INCLUDE_COMMENTS` | JSON or text | View PR details | | `pr-diff` | `CODEV_PR_NUMBER`, `CODEV_DIFF_NAME_ONLY` | text | Get PR diff | +### Merge Mechanics (read-only, used by `codev check`) + +| Concept | Env Vars | Output | Description | +|---------|----------|--------|-------------| +| `commit-checks` | `CODEV_COMMIT_SHA` | JSON array `[{name, state, url?, workflow?}]` | Check results reported on one commit | +| `workflow-runs` | `CODEV_WORKFLOW`, `CODEV_BRANCH` | JSON array `[{headSha, status, conclusion, url, createdAt}]`, newest first | Runs of one workflow on one branch | + +`commit-checks` normalizes every result to one `state` word: `pass`, `fail`, `pending`, `skipped` +or `neutral`. Skipped and neutral count as passed. The github script reads the commit's check +runs (the latest attempt for each name) and its legacy commit statuses: + +- A check run that has not completed is `pending`. +- `success` is `pass`, `skipped` is `skipped`, and `neutral` is `neutral`. +- Every other conclusion is `fail`: `failure`, `cancelled`, `timed_out`, `action_required`, + `stale` and `startup_failure`. +- A status of `success` is `pass`, `pending` is `pending`, and `failure` or `error` is `fail`. + +An empty array means nothing reported on the commit. A failure exits non-zero; it is never +an empty array. + +`pr-view` also carries optional fields that `codev check` reads. Consumers that do not know +them are unaffected. + +| Field | Meaning | github | gitlab | gitea | +|---|---|---|---|---| +| `headRefOid` | full SHA of the PR head | `headRefOid` | `sha` | `head.sha` | +| `isDraft` | draft flag | `isDraft` | `draft` | `draft` | +| `mergeable` | `MERGEABLE` / `CONFLICTING` / `UNKNOWN` | `mergeable` | from `detailed_merge_status` | from `mergeable` | +| `mergeStateStatus` | merge state, GitHub's words (`CLEAN` = clean) | `mergeStateStatus` | `detailed_merge_status` (`mergeable` → `CLEAN`, others upper-cased) | — | +| `mergeCommit` | `{oid}` of the merge/squash commit, `null` until merged | `mergeCommit` | `merge_commit_sha` / `squash_commit_sha` | `merge_commit_sha` | +| `mergedAt` | merge time, `null` until merged | `mergedAt` | `merged_at` | `merged_at` | +| `reviewDecision` | `APPROVED` / `CHANGES_REQUESTED` / `REVIEW_REQUIRED` | `reviewDecision` | `null` | `null` | + +A preset that cannot supply a field omits it (or sends `null` where the table says so), and +`codev check` then reports the dependent check as `not run`. The gitlab mappings follow +GitLab's documented merge-request API but are unverified against a live `glab`. + +**Providers.** github implements both new concepts, and so do linear and jira, which use the +github default for every PR concept. gitlab and gitea disable both explicitly, so a +`codev check` there shows `not run: commit-checks unavailable on gitlab`, never a silent `gh` +call. Supply an override to enable them, e.g. `"commit-checks": "./scripts/my-ci-status.sh"`. + ### Analytics & Team | Concept | Env Vars | Output | Description | @@ -106,7 +148,7 @@ Set a concept to `null` to disable it. The feature that uses it will gracefully } ``` -This maps all concepts to `glab` equivalents. Concepts without a GitLab equivalent (`team-activity`, `on-it-timestamps`) are automatically disabled. +This maps all concepts to `glab` equivalents. Concepts without a GitLab equivalent (`team-activity`, `on-it-timestamps`) are automatically disabled, as are `commit-checks` and `workflow-runs`, which could not be verified against GitLab. To customize specific concepts: @@ -129,7 +171,7 @@ To customize specific concepts: } ``` -Some Gitea concepts (`pr-search`, `pr-diff`) are disabled by default since `tea` doesn't support them directly. You can provide custom scripts: +Some Gitea concepts (`pr-search`, `pr-diff`) are disabled by default since `tea` doesn't support them directly; `commit-checks` and `workflow-runs` are disabled because they could not be verified against a Gitea server. You can provide custom scripts: ```json { diff --git a/packages/codev/scripts/forge/gitea/pr-view.sh b/packages/codev/scripts/forge/gitea/pr-view.sh index d4ef6dcf4..9f8eb8e25 100755 --- a/packages/codev/scripts/forge/gitea/pr-view.sh +++ b/packages/codev/scripts/forge/gitea/pr-view.sh @@ -3,7 +3,8 @@ # forge-executable: tea # Input: CODEV_PR_NUMBER # Output: JSON {title, body, state, url, author{login}, baseRefName, headRefName, -# additions, deletions} (see PrViewResult in forge-contracts.ts) +# additions, deletions, headRefOid?, isDraft?, mergeable?, mergeCommit, +# mergedAt, reviewDecision: null} (see PrViewResult in forge-contracts.ts) # # `tea pulls view N --output json` returns a table header / empty list rather # than the PR object, so route through the raw REST passthrough. `tea api` @@ -63,5 +64,17 @@ printf '%s' "$PR" | jq ' # Type-checked, not just defaulted: the contract types these as numbers, and # a non-numeric value here would be passed straight through. additions: (if (.additions | type) == "number" then .additions else 0 end), - deletions: (if (.deletions | type) == "number" then .deletions else 0 end) -}' + deletions: (if (.deletions | type) == "number" then .deletions else 0 end), + # Spec 1951 (`codev check`): Gitea has no review-decision field, so it is an + # explicit null rather than absent. + reviewDecision: null, + mergeCommit: (if (.merge_commit_sha | type) == "string" and .merge_commit_sha != "" + then {oid: .merge_commit_sha} else null end), + mergedAt: (if (.merged_at | type) == "string" then .merged_at else null end) +} +# The optional fields Gitea may not supply are omitted rather than defaulted, so a +# consumer reports them as unavailable instead of trusting an invented value. ++ (if (.head.sha | type) == "string" then {headRefOid: .head.sha} else {} end) ++ (if (.draft | type) == "boolean" then {isDraft: .draft} else {} end) ++ (if (.mergeable | type) == "boolean" + then {mergeable: (if .mergeable then "MERGEABLE" else "CONFLICTING" end)} else {} end)' diff --git a/packages/codev/scripts/forge/github/commit-checks.sh b/packages/codev/scripts/forge/github/commit-checks.sh new file mode 100755 index 000000000..bc9f786b9 --- /dev/null +++ b/packages/codev/scripts/forge/github/commit-checks.sh @@ -0,0 +1,38 @@ +#!/bin/sh +# Forge concept: commit-checks (GitHub via gh CLI) — Spec 1951 +# Input: CODEV_COMMIT_SHA (full or abbreviated commit SHA) +# Output: JSON [{name, state, url?}] (CommitCheckItem[] in forge-contracts.ts) +# +# Two read-only GETs: the commit's check runs (GitHub Actions and other apps, latest +# attempt per name, paginated) and its legacy commit statuses. Both are normalized to +# one state vocabulary: pass | fail | pending | skipped | neutral. +# check run: not completed → pending; success → pass; skipped → skipped; +# neutral → neutral; any other conclusion (failure, cancelled, +# timed_out, action_required, stale, startup_failure) → fail +# status: success → pass; pending → pending; failure or error → fail +# `workflow` is not emitted: naming it costs a third call per commit, and the +# contract makes it optional. +# +# Not `gh … | jq`: POSIX sh has no pipefail, so a failed gh would look like a +# commit with no checks (#1645). Capture first, then normalize. +# forge-executable: gh +runs="$(gh api --paginate "repos/{owner}/{repo}/commits/${CODEV_COMMIT_SHA}/check-runs?per_page=100" \ + --jq '.check_runs[] | {kind: "run", name, status, conclusion, url: .html_url}')" || exit 1 +statuses="$(gh api "repos/{owner}/{repo}/commits/${CODEV_COMMIT_SHA}/status?per_page=100" \ + --jq '.statuses[] | {kind: "status", name: .context, state, url: .target_url}')" || exit 1 +printf '%s\n%s\n' "$runs" "$statuses" | jq -s ' + map( + (if .kind == "run" then + (if .status != "completed" then "pending" + elif .conclusion == "success" then "pass" + elif .conclusion == "skipped" then "skipped" + elif .conclusion == "neutral" then "neutral" + else "fail" end) + else + (if .state == "success" then "pass" + elif .state == "pending" then "pending" + else "fail" end) + end) as $state + | {name, state: $state} + + (if (.url | type) == "string" and .url != "" then {url} else {} end) + )' diff --git a/packages/codev/scripts/forge/github/pr-view.sh b/packages/codev/scripts/forge/github/pr-view.sh index 52fc02961..916e5ae0d 100755 --- a/packages/codev/scripts/forge/github/pr-view.sh +++ b/packages/codev/scripts/forge/github/pr-view.sh @@ -2,10 +2,13 @@ # Forge concept: pr-view (GitHub via gh CLI) # Input: CODEV_PR_NUMBER, CODEV_INCLUDE_COMMENTS (optional, "1" to include) # Output: JSON or text (with comments) +# +# headRefOid, isDraft, mergeable, mergeStateStatus, mergeCommit, mergedAt and reviewDecision are the +# optional PrViewResult fields `codev check` reads (Spec 1951). if [ "$CODEV_INCLUDE_COMMENTS" = "1" ]; then exec gh pr view "$CODEV_PR_NUMBER" --comments else exec gh pr view "$CODEV_PR_NUMBER" \ - --json title,body,state,url,author,baseRefName,headRefName,additions,deletions + --json title,body,state,url,author,baseRefName,headRefName,additions,deletions,headRefOid,isDraft,mergeable,mergeStateStatus,mergeCommit,mergedAt,reviewDecision fi diff --git a/packages/codev/scripts/forge/github/workflow-runs.sh b/packages/codev/scripts/forge/github/workflow-runs.sh new file mode 100755 index 000000000..9de5caa7e --- /dev/null +++ b/packages/codev/scripts/forge/github/workflow-runs.sh @@ -0,0 +1,7 @@ +#!/bin/sh +# Forge concept: workflow-runs (GitHub via gh CLI) — Spec 1951 +# Input: CODEV_WORKFLOW (workflow file name or name), CODEV_BRANCH +# Output: JSON [{headSha, status, conclusion, url, createdAt}], newest first +# (WorkflowRunItem[] in forge-contracts.ts) +exec gh run list --workflow "$CODEV_WORKFLOW" --branch "$CODEV_BRANCH" --limit 50 \ + --json headSha,status,conclusion,url,createdAt diff --git a/packages/codev/scripts/forge/gitlab/pr-view.sh b/packages/codev/scripts/forge/gitlab/pr-view.sh index 8aed3c14c..fbccbb198 100755 --- a/packages/codev/scripts/forge/gitlab/pr-view.sh +++ b/packages/codev/scripts/forge/gitlab/pr-view.sh @@ -1,6 +1,45 @@ #!/bin/sh # Forge concept: pr-view (GitLab via glab CLI) -# Adds a `url` field mapped from GitLab's `web_url` (the MR's browser page); -# all other fields glab emits are passed through unchanged. `. + {url: …}` is -# non-destructive — if `web_url` is absent, `url` is null (optional by contract). -glab mr view "$CODEV_PR_NUMBER" --output json | jq '. + {url: .web_url}' +# Input: CODEV_PR_NUMBER +# Output: glab's merge-request JSON, passed through, plus the PrViewResult fields +# (forge-contracts.ts) that GitLab names differently: +# web_url -> url (the MR's browser page) +# description -> body +# target_branch / source_branch -> baseRefName / headRefName +# sha -> headRefOid (Spec 1951) +# draft -> isDraft +# merge_commit_sha // squash_commit_sha -> mergeCommit {oid} +# merged_at -> mergedAt +# detailed_merge_status -> mergeable: conflict → CONFLICTING; +# checking/unchecked/preparing → UNKNOWN; +# anything else → MERGEABLE +# mergeStateStatus: mergeable → CLEAN; else upper-cased +# reviewDecision -> explicit null (GitLab has no single equivalent) +# A field glab does not supply is omitted, never invented. +# +# ⚠️ UNVERIFIED — `glab` is not available in the authoring environment; the field +# names follow GitLab's documented merge-request API. Smoke-test before relying on it. +# +# Not `glab … | jq`: POSIX sh has no pipefail, so a failed glab would surface as jq's +# exit 0 on empty input (#1645). The capture hides glab from extractExecutable's +# first-line heuristic, so the backend is declared explicitly (#1455). +# forge-executable: glab +out="$(glab mr view "$CODEV_PR_NUMBER" --output json)" || exit 1 +printf '%s' "$out" | jq ' + def str($v): ($v | type) == "string"; + . + {url: .web_url, reviewDecision: null} + + (if str(.description) then {body: .description} else {} end) + + (if str(.target_branch) then {baseRefName: .target_branch} else {} end) + + (if str(.source_branch) then {headRefName: .source_branch} else {} end) + + (if str(.sha) then {headRefOid: .sha} else {} end) + + (if (.draft | type) == "boolean" then {isDraft: .draft} else {} end) + + ((.merge_commit_sha // .squash_commit_sha) as $m + | {mergeCommit: (if str($m) then {oid: $m} else null end)}) + + {mergedAt: (if str(.merged_at) then .merged_at else null end)} + + (if str(.detailed_merge_status) then + .detailed_merge_status as $s + | {mergeable: (if $s == "conflict" then "CONFLICTING" + elif $s == "checking" or $s == "unchecked" or $s == "preparing" then "UNKNOWN" + else "MERGEABLE" end), + mergeStateStatus: (if $s == "mergeable" then "CLEAN" else ($s | ascii_upcase) end)} + else {} end)' diff --git a/packages/codev/src/__tests__/doctor.test.ts b/packages/codev/src/__tests__/doctor.test.ts index a6ccefd34..366609832 100644 --- a/packages/codev/src/__tests__/doctor.test.ts +++ b/packages/codev/src/__tests__/doctor.test.ts @@ -36,13 +36,13 @@ const executeForgeCommandSyncMock = vi.hoisted(() => vi.fn((concept: string) => const loadForgeConfigMock = vi.hoisted(() => vi.fn(() => null)); const validateForgeConfigMock = vi.hoisted(() => vi.fn(() => [])); const resolveAllConceptsMock = vi.hoisted(() => vi.fn(() => { - // All 18 concepts (KNOWN_CONCEPTS in lib/forge.ts) as default/gh-based, so the + // All 20 concepts (KNOWN_CONCEPTS in lib/forge.ts) as default/gh-based, so the // doctor report's rendering is exercised for every row it actually prints. const concepts = [ 'issue-view', 'pr-list', 'issue-list', 'issue-search', 'issue-comment', 'pr-exists', 'recently-closed', 'recently-merged', 'user-identity', 'team-activity', 'on-it-timestamps', 'pr-create', 'pr-merge', 'pr-search', 'pr-view', 'pr-diff', - 'auth-status', 'repo-archive', + 'auth-status', 'repo-archive', 'commit-checks', 'workflow-runs', ]; return concepts.map(c => ({ concept: c, command: `gh ${c}`, source: 'default', executable: 'gh' })); })); diff --git a/packages/codev/src/__tests__/forge-windows-launcher.test.ts b/packages/codev/src/__tests__/forge-windows-launcher.test.ts index c3126237c..6d00be26d 100644 --- a/packages/codev/src/__tests__/forge-windows-launcher.test.ts +++ b/packages/codev/src/__tests__/forge-windows-launcher.test.ts @@ -35,7 +35,7 @@ const CONCEPTS = [ 'issue-view', 'pr-list', 'issue-list', 'issue-search', 'issue-comment', 'pr-exists', 'recently-closed', 'recently-merged', 'user-identity', 'team-activity', 'on-it-timestamps', 'pr-create', 'pr-merge', 'pr-search', 'pr-view', 'pr-diff', - 'auth-status', 'repo-archive', + 'auth-status', 'repo-archive', 'commit-checks', 'workflow-runs', ]; const CWD = 'C:\\Users\\dev\\repo'; diff --git a/packages/codev/src/__tests__/forge.test.ts b/packages/codev/src/__tests__/forge.test.ts index 4b2fedd85..d6f5b3ee8 100644 --- a/packages/codev/src/__tests__/forge.test.ts +++ b/packages/codev/src/__tests__/forge.test.ts @@ -324,7 +324,7 @@ describe('executeForgeCommandSync', () => { // ============================================================================= describe('getKnownConcepts', () => { - it('returns all 18 known concept names', () => { + it('returns all 20 known concept names', () => { const concepts = getKnownConcepts(); expect(concepts).toContain('issue-view'); expect(concepts).toContain('pr-list'); @@ -344,7 +344,9 @@ describe('getKnownConcepts', () => { expect(concepts).toContain('pr-diff'); expect(concepts).toContain('auth-status'); expect(concepts).toContain('repo-archive'); - expect(concepts.length).toBe(18); + expect(concepts).toContain('commit-checks'); + expect(concepts).toContain('workflow-runs'); + expect(concepts.length).toBe(20); }); }); @@ -674,9 +676,9 @@ describe('graceful degradation when command not found', () => { // ============================================================================= describe('resolveAllConcepts', () => { - it('returns all 18 concepts with default source when no config', () => { + it('returns all 20 concepts with default source when no config', () => { const resolutions = resolveAllConcepts(); - expect(resolutions).toHaveLength(18); + expect(resolutions).toHaveLength(20); expect(resolutions.every(r => r.source === 'default')).toBe(true); expect(resolutions.every(r => r.executable !== null)).toBe(true); }); @@ -795,7 +797,7 @@ describe('executeForgeCommandDetailed (#1645)', () => { it('reports a disabled concept as an error without executing', async () => { const result = await executeForgeCommandDetailed('issue-view', {}, { forgeConfig: { 'issue-view': null } }); - expect(result).toEqual({ data: null, error: { message: expect.stringContaining('disabled'), stderr: '', exitCode: null } }); + expect(result).toEqual({ data: null, error: { message: expect.stringContaining('disabled'), stderr: '', exitCode: null, timedOut: false } }); }); it('reports a malformed .codev/config.json as an error instead of rejecting', async () => { diff --git a/packages/codev/src/__tests__/spec-1951-forge-read-concepts.test.ts b/packages/codev/src/__tests__/spec-1951-forge-read-concepts.test.ts new file mode 100644 index 000000000..0dcec3582 --- /dev/null +++ b/packages/codev/src/__tests__/spec-1951-forge-read-concepts.test.ts @@ -0,0 +1,371 @@ +/** + * Spec 1951 — forge read concepts for `codev check`. + * + * Pins: + * 1. `commit-checks` and `workflow-runs` are known concepts; github (and the hybrid + * providers, which fall through to it) implement them, gitlab and gitea disable them + * explicitly instead of silently falling through to `gh`. + * 2. The github scripts honour their contracts and make only read-only `gh` calls. + * 3. `pr-view` carries the new optional fields on github, gitlab and gitea. + * 4. The dispatcher's `timeoutMs` option and `timedOut` error flag. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { execFileSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { + executeForgeCommandDetailed, + getForgeCommand, + getKnownConcepts, + resolveAllConcepts, +} from '../lib/forge.js'; +import type { CommitChecksResult, PrViewResult, WorkflowRunsResult } from '../lib/forge-contracts.js'; + +const forgeScripts = path.resolve(import.meta.dirname, '..', '..', 'scripts', 'forge'); +const NEW_CONCEPTS = ['commit-checks', 'workflow-runs'] as const; +const SHA = 'a'.repeat(40); + +function hasJq(): boolean { + try { + execFileSync('sh', ['-c', 'command -v jq'], { stdio: 'ignore' }); + return true; + } catch { + return false; + } +} + +const posixWithJq = process.platform !== 'win32' && hasJq(); + +/** + * A fake `gh` implementing the read-only slice the github scripts use. Every call is + * appended to `gh-calls`; any call outside the read-only list is appended to `violations` + * and exits 97, so a script that tries to write fails loudly and the test sees it. + * + * pr view … → pr-view.json + * run list … → run-list.json + * api … check-runs … → each check-runs..json page through the --jq expression + * api … /status … → status.json through the --jq expression + * + * STUB_FAIL_API=1 makes `gh api` fail, to prove the capture-then-jq shape propagates it. + */ +const GH_STUB = `#!/bin/sh +dir="$(dirname "$0")" +printf '%s\\n' "$*" >> "$dir/gh-calls" +refuse() { printf '%s\\n' "$*" >> "$dir/violations"; exit 97; } +case "$1" in + pr) case "$2" in view|list) ;; *) refuse "$@" ;; esac ;; + run) [ "$2" = list ] || refuse "$@" ;; + api) + for a in "$@"; do + case "$a" in + -X|-X*|--method|--method=*|-f|-F|--field|--field=*|--raw-field|--raw-field=*|--input|--input=*) refuse "$@" ;; + esac + done ;; + *) refuse "$@" ;; +esac +if [ "$1" = pr ]; then cat "$dir/pr-view.json"; exit 0; fi +if [ "$1" = run ]; then cat "$dir/run-list.json"; exit 0; fi +[ "$STUB_FAIL_API" = 1 ] && { echo "HTTP 502" >&2; exit 1; } +expr=""; endpoint=""; prev="" +for a in "$@"; do + [ "$prev" = "--jq" ] && expr="$a" + case "$a" in repos/*) endpoint="$a" ;; esac + prev="$a" +done +case "$endpoint" in + */check-runs*) for page in "$dir"/check-runs.*.json; do jq -c "$expr" "$page"; done ;; + */status*) jq -c "$expr" "$dir/status.json" ;; + *) refuse "$@" ;; +esac +`; + +function writeStub(dir: string, name: string, body: string): void { + const file = path.join(dir, name); + fs.writeFileSync(file, body); + fs.chmodSync(file, 0o755); +} + +function withPath(dir: string): Record { + return { PATH: `${dir}${path.delimiter}${process.env.PATH ?? ''}` }; +} + +describe('Spec 1951 — new concepts are registered per provider', () => { + it('both concepts are known', () => { + for (const concept of NEW_CONCEPTS) expect(getKnownConcepts()).toContain(concept); + }); + + it.each(['github', 'linear', 'jira'])('%s runs the github scripts', (provider) => { + for (const concept of NEW_CONCEPTS) { + expect(getForgeCommand(concept, { provider })).toBe(path.join(forgeScripts, 'github', `${concept}.sh`)); + const resolution = resolveAllConcepts({ provider }).find((r) => r.concept === concept); + expect(resolution?.executable).toBe('gh'); + } + }); + + it.each(['gitlab', 'gitea'])('%s disables them explicitly — never a silent fall-through to gh', (provider) => { + for (const concept of NEW_CONCEPTS) { + expect(getForgeCommand(concept, { provider })).toBeNull(); + const resolution = resolveAllConcepts({ provider }).find((r) => r.concept === concept); + expect(resolution?.source).toBe('disabled'); + } + }); + + it('doctor names glab as the gitlab pr-view executable, not printf (#1455)', () => { + const resolution = resolveAllConcepts({ provider: 'gitlab' }).find((r) => r.concept === 'pr-view'); + expect(resolution?.executable).toBe('glab'); + }); + + it.skipIf(process.platform === 'win32').each(NEW_CONCEPTS)('the github %s script is executable', (concept) => { + expect(fs.statSync(path.join(forgeScripts, 'github', `${concept}.sh`)).mode & 0o111).not.toBe(0); + }); +}); + +describe.skipIf(!posixWithJq)('Spec 1951 — github scripts honour the contracts, read-only', () => { + let tmp: string; + + beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'spec-1951-forge-')); + writeStub(tmp, 'gh', GH_STUB); + }); + + afterEach(() => { + // Every test ends with the read-only audit: no refused gh call happened. + expect(fs.existsSync(path.join(tmp, 'violations')), 'a gh call outside the read-only list').toBe(false); + fs.rmSync(tmp, { recursive: true, force: true }); + }); + + const run = (concept: string, env: Record) => + executeForgeCommandDetailed(concept, { ...env, ...withPath(tmp) }, { forgeConfig: { provider: 'github' }, cwd: tmp }); + + it('pr-view asks gh for the new fields and passes them through', async () => { + const pr = { + title: 't', body: 'b', state: 'OPEN', url: 'u', author: { login: 'x' }, baseRefName: 'main', + headRefName: 'builder/spir-1', additions: 1, deletions: 2, headRefOid: SHA, isDraft: false, + mergeable: 'MERGEABLE', mergeStateStatus: 'BLOCKED', mergeCommit: null, mergedAt: null, + reviewDecision: 'REVIEW_REQUIRED', + }; + fs.writeFileSync(path.join(tmp, 'pr-view.json'), JSON.stringify(pr)); + const result = await run('pr-view', { CODEV_PR_NUMBER: '7' }); + expect(result.error).toBeNull(); + expect(result.data as PrViewResult).toEqual(pr); + const call = fs.readFileSync(path.join(tmp, 'gh-calls'), 'utf-8').trim(); + for (const field of ['headRefOid', 'isDraft', 'mergeable', 'mergeStateStatus', 'mergeCommit', 'mergedAt', 'reviewDecision']) { + expect(call).toContain(field); + } + }); + + it('commit-checks normalizes every check-run conclusion and commit status, across pages', async () => { + const checkRun = (name: string, status: string, conclusion: string | null) => + ({ name, status, conclusion, html_url: `https://ci.example/${name}` }); + fs.writeFileSync(path.join(tmp, 'check-runs.1.json'), JSON.stringify({ + check_runs: [ + checkRun('unit', 'completed', 'success'), + checkRun('lint', 'completed', 'failure'), + checkRun('docs', 'completed', 'skipped'), + checkRun('info', 'completed', 'neutral'), + checkRun('e2e', 'in_progress', null), + ], + })); + fs.writeFileSync(path.join(tmp, 'check-runs.2.json'), JSON.stringify({ + check_runs: [ + checkRun('cancelled', 'completed', 'cancelled'), + checkRun('slow', 'completed', 'timed_out'), + checkRun('queued', 'queued', null), + ], + })); + fs.writeFileSync(path.join(tmp, 'status.json'), JSON.stringify({ + statuses: [ + { context: 'legacy/ok', state: 'success', target_url: 'https://legacy/ok' }, + { context: 'legacy/bad', state: 'error', target_url: '' }, + { context: 'legacy/wait', state: 'pending', target_url: null }, + ], + })); + const result = await run('commit-checks', { CODEV_COMMIT_SHA: SHA }); + expect(result.error).toBeNull(); + expect(result.data as CommitChecksResult).toEqual([ + { name: 'unit', state: 'pass', url: 'https://ci.example/unit' }, + { name: 'lint', state: 'fail', url: 'https://ci.example/lint' }, + { name: 'docs', state: 'skipped', url: 'https://ci.example/docs' }, + { name: 'info', state: 'neutral', url: 'https://ci.example/info' }, + { name: 'e2e', state: 'pending', url: 'https://ci.example/e2e' }, + { name: 'cancelled', state: 'fail', url: 'https://ci.example/cancelled' }, + { name: 'slow', state: 'fail', url: 'https://ci.example/slow' }, + { name: 'queued', state: 'pending', url: 'https://ci.example/queued' }, + { name: 'legacy/ok', state: 'pass', url: 'https://legacy/ok' }, + { name: 'legacy/bad', state: 'fail' }, + { name: 'legacy/wait', state: 'pending' }, + ]); + const calls = fs.readFileSync(path.join(tmp, 'gh-calls'), 'utf-8'); + expect(calls).toContain(`repos/{owner}/{repo}/commits/${SHA}/check-runs`); + expect(calls).toContain('--paginate'); + expect(calls).toContain(`repos/{owner}/{repo}/commits/${SHA}/status`); + }); + + it('commit-checks reports a commit with nothing on it as an empty list', async () => { + fs.writeFileSync(path.join(tmp, 'check-runs.1.json'), JSON.stringify({ check_runs: [] })); + fs.writeFileSync(path.join(tmp, 'status.json'), JSON.stringify({ statuses: [] })); + const result = await run('commit-checks', { CODEV_COMMIT_SHA: SHA }); + expect(result).toEqual({ data: [], error: null }); + }); + + it('commit-checks fails when gh fails — never "no checks" (#1645)', async () => { + fs.writeFileSync(path.join(tmp, 'check-runs.1.json'), JSON.stringify({ check_runs: [] })); + fs.writeFileSync(path.join(tmp, 'status.json'), JSON.stringify({ statuses: [] })); + const result = await run('commit-checks', { CODEV_COMMIT_SHA: SHA, STUB_FAIL_API: '1' }); + expect(result.data).toBeNull(); + expect(result.error?.timedOut).toBe(false); + expect(result.error?.exitCode).not.toBe(0); + }); + + it('workflow-runs lists the runs of one workflow on one branch', async () => { + const runs: WorkflowRunsResult = [ + { headSha: SHA, status: 'completed', conclusion: 'success', url: 'https://ci/1', createdAt: '2026-11-22T18:04:00Z' }, + { headSha: 'b'.repeat(40), status: 'in_progress', conclusion: '', url: 'https://ci/2', createdAt: '2026-11-22T17:00:00Z' }, + ]; + fs.writeFileSync(path.join(tmp, 'run-list.json'), JSON.stringify(runs)); + const result = await run('workflow-runs', { CODEV_WORKFLOW: 'deploy.yml', CODEV_BRANCH: 'production' }); + expect(result).toEqual({ data: runs, error: null }); + const call = fs.readFileSync(path.join(tmp, 'gh-calls'), 'utf-8').trim(); + expect(call).toBe('run list --workflow deploy.yml --branch production --limit 50 --json headSha,status,conclusion,url,createdAt'); + }); +}); + +describe.skipIf(!posixWithJq)('Spec 1951 — gitlab and gitea pr-view carry the new fields', () => { + let tmp: string; + + beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'spec-1951-prview-')); + }); + + afterEach(() => { + fs.rmSync(tmp, { recursive: true, force: true }); + }); + + const glabMr = (overrides: Record) => JSON.stringify({ + iid: 7, title: 't', state: 'opened', description: 'body text', web_url: 'https://gl/mr/7', + target_branch: 'main', source_branch: 'builder/spir-7', sha: SHA, draft: false, + merge_commit_sha: null, squash_commit_sha: null, merged_at: null, detailed_merge_status: 'mergeable', + ...overrides, + }); + + const runGitlab = async (mr: string, exitCode = 0) => { + writeStub(tmp, 'glab', `#!/bin/sh\ncat <<'JSON'\n${mr}\nJSON\nexit ${exitCode}\n`); + return executeForgeCommandDetailed('pr-view', { CODEV_PR_NUMBER: '7', ...withPath(tmp) }, { forgeConfig: { provider: 'gitlab' }, cwd: tmp }); + }; + + it('gitlab maps an open, clean MR', async () => { + const result = await runGitlab(glabMr({})); + expect(result.data).toMatchObject({ + url: 'https://gl/mr/7', body: 'body text', baseRefName: 'main', headRefName: 'builder/spir-7', + headRefOid: SHA, isDraft: false, mergeCommit: null, mergedAt: null, + mergeable: 'MERGEABLE', mergeStateStatus: 'CLEAN', reviewDecision: null, + }); + }); + + it.each([ + ['conflict', 'CONFLICTING', 'CONFLICT'], + ['checking', 'UNKNOWN', 'CHECKING'], + ['unchecked', 'UNKNOWN', 'UNCHECKED'], + ['not_approved', 'MERGEABLE', 'NOT_APPROVED'], + ])('gitlab maps detailed_merge_status %s', async (status, mergeable, mergeStateStatus) => { + const result = await runGitlab(glabMr({ detailed_merge_status: status })); + expect(result.data).toMatchObject({ mergeable, mergeStateStatus }); + }); + + it('gitlab maps a squash-merged MR', async () => { + const result = await runGitlab(glabMr({ + state: 'merged', merge_commit_sha: null, squash_commit_sha: 'c'.repeat(40), merged_at: '2026-11-22T00:00:00Z', + })); + expect(result.data).toMatchObject({ mergeCommit: { oid: 'c'.repeat(40) }, mergedAt: '2026-11-22T00:00:00Z' }); + }); + + it('gitlab omits a field glab does not supply rather than inventing it', async () => { + const result = await runGitlab(glabMr({ sha: null, draft: undefined, detailed_merge_status: undefined })); + const data = result.data as Record; + expect('headRefOid' in data).toBe(false); + expect('isDraft' in data).toBe(false); + expect('mergeable' in data).toBe(false); + }); + + it('gitlab fails when glab fails, instead of reporting jq\'s exit 0 (#1645)', async () => { + const result = await runGitlab('', 1); + expect(result.data).toBeNull(); + expect(result.error).not.toBeNull(); + }); + + const runGitea = async (pull: Record) => { + const body = JSON.stringify({ + number: 7, title: 't', state: 'open', body: 'b', html_url: 'https://gt/pulls/7', + user: { login: 'x' }, base: { ref: 'main' }, head: { ref: 'builder/spir-7', sha: SHA }, + additions: 1, deletions: 2, draft: false, mergeable: true, merge_commit_sha: null, merged_at: null, + ...pull, + }); + writeStub(tmp, 'tea', `#!/bin/sh\ncat <<'JSON'\n${body}\nJSON\n`); + return executeForgeCommandDetailed('pr-view', { CODEV_PR_NUMBER: '7', CODEV_REPO: 'o/r', ...withPath(tmp) }, { forgeConfig: { provider: 'gitea' }, cwd: tmp }); + }; + + it('gitea maps an open, mergeable pull', async () => { + const result = await runGitea({}); + expect(result.data).toMatchObject({ + headRefOid: SHA, isDraft: false, mergeable: 'MERGEABLE', mergeCommit: null, mergedAt: null, reviewDecision: null, + }); + }); + + it('gitea maps a merged, unmergeable pull', async () => { + const result = await runGitea({ mergeable: false, merge_commit_sha: 'd'.repeat(40), merged_at: '2026-11-22T00:00:00Z' }); + expect(result.data).toMatchObject({ + mergeable: 'CONFLICTING', mergeCommit: { oid: 'd'.repeat(40) }, mergedAt: '2026-11-22T00:00:00Z', + }); + }); + + it('gitea omits headRefOid, isDraft and mergeable when the server does not send them', async () => { + const result = await runGitea({ head: { ref: 'b' }, draft: undefined, mergeable: undefined }); + const data = result.data as Record; + expect('headRefOid' in data).toBe(false); + expect('isDraft' in data).toBe(false); + expect('mergeable' in data).toBe(false); + }); +}); + +describe.skipIf(process.platform === 'win32')('Spec 1951 — the dispatcher reports a timeout as a timeout', () => { + let tmp: string; + + beforeEach(() => { + tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'spec-1951-timeout-')); + }); + + afterEach(() => { + fs.rmSync(tmp, { recursive: true, force: true }); + }); + + const script = (name: string, body: string): string => { + writeStub(tmp, name, `#!/bin/sh\n${body}\n`); + return path.join(tmp, name); + }; + + it('a concept that exec-s a hanging tool times out at timeoutMs', async () => { + const hang = script('hang.sh', 'exec sleep 5'); + const started = Date.now(); + const result = await executeForgeCommandDetailed('pr-view', {}, { forgeConfig: { 'pr-view': hang }, timeoutMs: 300 }); + expect(result.data).toBeNull(); + expect(result.error?.timedOut).toBe(true); + expect(Date.now() - started).toBeLessThan(3000); + }); + + it('a capture-pattern concept whose tool hangs is still flagged as timed out', async () => { + // The killed shell's grandchild keeps stderr open until it exits, so the promise + // settles late; `codev check`'s runner bounds that with its own deadline (Phase 2). + const hang = script('hang-capture.sh', 'out="$(sleep 1)"\nprintf "%s" "$out"'); + const result = await executeForgeCommandDetailed('pr-view', {}, { forgeConfig: { 'pr-view': hang }, timeoutMs: 200 }); + expect(result.data).toBeNull(); + expect(result.error?.timedOut).toBe(true); + }); + + it('an ordinary failure is not a timeout', async () => { + const fail = script('fail.sh', 'echo nope >&2\nexit 3'); + const result = await executeForgeCommandDetailed('pr-view', {}, { forgeConfig: { 'pr-view': fail } }); + expect(result.error).toMatchObject({ exitCode: 3, timedOut: false }); + }); +}); diff --git a/packages/codev/src/lib/forge-contracts.ts b/packages/codev/src/lib/forge-contracts.ts index b9422b3c8..ad35e4e1d 100644 --- a/packages/codev/src/lib/forge-contracts.ts +++ b/packages/codev/src/lib/forge-contracts.ts @@ -189,8 +189,77 @@ export interface PrViewResult { headRefName: string; additions: number; deletions: number; + /* + * The fields below are optional and additive (Spec 1951, consumed by `codev check`). + * A preset that cannot supply one omits it; the consumer then reports the dependent + * check as "not run", never as passing. + */ + /** Full SHA of the PR's head commit as the forge sees it: GitHub `headRefOid`, GitLab `sha`, Gitea `head.sha`. */ + headRefOid?: string; + /** Whether the PR is a draft. */ + isDraft?: boolean; + /** The forge's own mergeability, normalized to GitHub's three words. */ + mergeable?: 'MERGEABLE' | 'CONFLICTING' | 'UNKNOWN'; + /** + * The forge's merge-state word in GitHub's vocabulary, where `CLEAN` is the clean state. + * Other presets map their clean state to `CLEAN` and pass any other state through + * upper-cased. + */ + mergeStateStatus?: string; + /** The commit the merge produced (merge, squash or rebase tip); null while unmerged. */ + mergeCommit?: { oid: string } | null; + /** ISO 8601 merge time; null while unmerged. */ + mergedAt?: string | null; + /** + * The review state in GitHub's words (`APPROVED`, `CHANGES_REQUESTED`, `REVIEW_REQUIRED`), + * which explains a `BLOCKED` merge state. Explicitly `null` from presets whose forge has + * no equivalent (gitlab, gitea). + */ + reviewDecision?: string | null; +} + +// ============================================================================= +// Commit and workflow concepts (Spec 1951) +// ============================================================================= + +/** A check result's state, normalized across forges. Skipped and neutral count as passed. */ +export type CommitCheckState = 'pass' | 'fail' | 'pending' | 'skipped' | 'neutral'; + +/** + * Single item in `commit-checks` concept output: one check run or commit status + * reported for the commit named by `CODEV_COMMIT_SHA`. + */ +export interface CommitCheckItem { + name: string; + state: CommitCheckState; + /** Browser URL of the run's details, when the forge supplies one. */ + url?: string; + /** Workflow the run belongs to, when the forge supplies it cheaply. */ + workflow?: string; } +/** Output of the `commit-checks` concept command. Empty when nothing reported on the commit. */ +export type CommitChecksResult = CommitCheckItem[]; + +/** + * Single item in `workflow-runs` concept output: one run of the workflow named by + * `CODEV_WORKFLOW` on the branch named by `CODEV_BRANCH`. + */ +export interface WorkflowRunItem { + /** Full SHA the run was for. */ + headSha: string; + /** `completed` once finished; anything else means still running or queued. */ + status: string; + /** For a completed run, `success` means green. Empty or null while running. */ + conclusion: string | null; + url: string; + /** ISO 8601. */ + createdAt: string; +} + +/** Output of the `workflow-runs` concept command, newest first. */ +export type WorkflowRunsResult = WorkflowRunItem[]; + /** * Output of the `pr-create` concept command. * diff --git a/packages/codev/src/lib/forge.ts b/packages/codev/src/lib/forge.ts index 88e6a79b9..74c706fcb 100644 --- a/packages/codev/src/lib/forge.ts +++ b/packages/codev/src/lib/forge.ts @@ -34,6 +34,8 @@ function resolveScriptPath(provider: string, concept: string): string { /** Default maxBuffer for forge commands (10MB). Prevents truncation for large diffs. */ const DEFAULT_MAX_BUFFER = 10 * 1024 * 1024; +/** Default time limit for one concept command (ms). */ +const DEFAULT_TIMEOUT_MS = 30_000; // ============================================================================= // Types @@ -54,6 +56,8 @@ export interface ForgeCommandOptions { raw?: boolean; /** Maximum stdout buffer size in bytes. Defaults to 10MB. */ maxBuffer?: number; + /** Kill the command after this many milliseconds. Defaults to 30 000. */ + timeoutMs?: number; } // ============================================================================= @@ -64,7 +68,7 @@ const KNOWN_CONCEPTS = [ 'issue-view', 'pr-list', 'issue-list', 'issue-search', 'issue-comment', 'pr-exists', 'recently-closed', 'recently-merged', 'user-identity', 'team-activity', 'on-it-timestamps', 'pr-create', 'pr-merge', 'pr-search', 'pr-view', 'pr-diff', - 'auth-status', 'repo-archive', + 'auth-status', 'repo-archive', 'commit-checks', 'workflow-runs', ] as const; // ============================================================================= @@ -124,8 +128,12 @@ function getProviderPresets(): Record> { if (_providerPresets) return _providerPresets; _providerPresets = { github: getDefaultCommands(), - gitlab: buildPresetFromScripts('gitlab', ['team-activity', 'on-it-timestamps']), - gitea: buildPresetFromScripts('gitea', ['team-activity', 'on-it-timestamps', 'pr-search', 'pr-diff']), + // commit-checks / workflow-runs (Spec 1951) are disabled, not omitted: an omitted + // concept falls through to the github default and would run `gh` on a GitLab or + // Gitea workspace. Neither could be verified against a real glab or Gitea server, so + // `codev check` reports them as "not run" by name until a project supplies an override. + gitlab: buildPresetFromScripts('gitlab', ['team-activity', 'on-it-timestamps', 'commit-checks', 'workflow-runs']), + gitea: buildPresetFromScripts('gitea', ['team-activity', 'on-it-timestamps', 'pr-search', 'pr-diff', 'commit-checks', 'workflow-runs']), // Linear is a hybrid forge (spec 719): it owns *issues*, while every PR // concept — pr-create included — deliberately falls through to the github // default. Disabling pr-create here would leave Linear the one provider @@ -373,6 +381,8 @@ export interface ForgeCommandError { stderr: string; /** Process exit code; null when the command was disabled, timed out, or config failed to load. */ exitCode: number | null; + /** True when the command was killed for running past its time limit. */ + timedOut: boolean; } export interface ForgeCommandResult { @@ -396,7 +406,7 @@ export async function executeForgeCommandDetailed( const forgeConfig = resolveForgeConfig(options); const command = getForgeCommand(concept, forgeConfig); if (command === null) { - return { data: null, error: { message: `concept '${concept}' is disabled or unknown`, stderr: '', exitCode: null } }; + return { data: null, error: { message: `concept '${concept}' is disabled or unknown`, stderr: '', exitCode: null, timedOut: false } }; } const execEnv = { ...process.env, ...buildForgeEnv(forgeConfig), ...env }; @@ -404,7 +414,7 @@ export async function executeForgeCommandDetailed( const stdout = await commandLaunch().execShellString(command, { cwd: options?.cwd, env: execEnv, - timeout: 30_000, + timeout: options?.timeoutMs ?? DEFAULT_TIMEOUT_MS, maxBuffer, workspaceRoot: options?.workspaceRoot ?? options?.cwd, msysPathEnvKeys: PATH_INPUTS, @@ -412,13 +422,15 @@ export async function executeForgeCommandDetailed( return { data: parseOutput(stdout, options?.raw), error: null }; } catch (err: unknown) { logDebug(concept, err); - const e = err as { message?: string; stderr?: string; code?: unknown }; + const e = err as { message?: string; stderr?: string; code?: unknown; killed?: boolean }; return { data: null, error: { message: e?.message ?? String(err), stderr: typeof e?.stderr === 'string' ? e.stderr : '', exitCode: typeof e?.code === 'number' ? e.code : null, + // Node kills the child on timeout and on maxBuffer overflow; only the former is a timeout. + timedOut: e?.killed === true && e?.code !== 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER', }, }; } @@ -483,7 +495,7 @@ export function executeForgeCommandSync( const stdout = commandLaunch().execShellStringSync(command, { cwd: options?.cwd, env: execEnv, - timeout: 30_000, + timeout: DEFAULT_TIMEOUT_MS, maxBuffer, workspaceRoot: options?.workspaceRoot ?? options?.cwd, msysPathEnvKeys: PATH_INPUTS, From 1e135c6c415adc6dbe31880ecb088583d3964c6c Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 14:23:29 -0800 Subject: [PATCH 20/94] [Spec 1951][Phase: forge_read_concepts] test: gitea pr-view shape carries the new nullable fields --- .../codev/src/__tests__/bugfix-1137-gitea-tea-api.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/codev/src/__tests__/bugfix-1137-gitea-tea-api.test.ts b/packages/codev/src/__tests__/bugfix-1137-gitea-tea-api.test.ts index 67f261247..9a0cb48bc 100644 --- a/packages/codev/src/__tests__/bugfix-1137-gitea-tea-api.test.ts +++ b/packages/codev/src/__tests__/bugfix-1137-gitea-tea-api.test.ts @@ -384,6 +384,12 @@ describe.skipIf(!jqAvailable)('bugfix #1137: gitea preset routes reads through ` headRefName: 'feature/x', additions: 10, deletions: 3, + // Spec 1951: always present (null until merged / no gitea equivalent). The + // fixture has no head.sha, draft or mergeable, so headRefOid, isDraft and + // mergeable are omitted rather than invented. + reviewDecision: null, + mergeCommit: null, + mergedAt: null, }); }); From bb2ad2710c5d40e4bcd39adc70340537029b1fcb Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 14:27:00 -0800 Subject: [PATCH 21/94] [Spec 1951] Thread log: Phase 1 --- codev/state/spir-1951_thread.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 024b877dc..c4e41d958 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -59,3 +59,12 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals Scoped to that function; notice stays informational. Evidence: 2026-11-23 cleanup reported "1 uncommitted file(s)" for two bugfix builders with nothing uncommitted. Record in the review. - Standing ruling main-32 applies to all seven phases; pr gate is the owner's. + +## 2026-11-23 — implement: forge_read_concepts (Phase 1) +- Commits 01565e67b + 1e135c6c4. pr-view new optional fields (+ reviewDecision, architect ruling 2026-11-23: + forge verdict follows `mergeable` only; mergeStateStatus is context). commit-checks / workflow-runs on + github; gitlab/gitea explicitly null. Dispatcher timeoutMs + timedOut. gitlab pr-view pipefail fix. +- Surprise: worktree had no node_modules / built sdk — `pnpm install` + `npm run build` first. +- Full suite: run 1 failed on bugfix-1137 (mine: gitea pr-view shape, fixed) + 3 spawn-heavy tests that pass + alone (launch-loop, ide-command, agy-auth-cache). porch `tests` failed again at load ~30 (names not shown); + my next full run passed clean (8290/8290). Per main-32: stopped, opened draft PR #1958 for CI. From 233372f8d43c9f298aac56e95eddaddb935e29b7 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 14:44:06 -0800 Subject: [PATCH 22/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index d703ab702..004d3e513 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,10 +39,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T22:10:25.669Z' +updated_at: '2026-11-23T22:44:06.744Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From 0448553f0e5a3ec2edb2e97086e89d38b90c181b Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 14:50:03 -0800 Subject: [PATCH 23/94] =?UTF-8?q?[Spec=201951][Phase:=20forge=5Fread=5Fcon?= =?UTF-8?q?cepts]=20fix:=20review=20follow-ups=20=E2=80=94=20gitlab=20empt?= =?UTF-8?q?y-output=20guard=20and=20body=20default,=20paginate=20legacy=20?= =?UTF-8?q?statuses?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../scripts/forge/github/commit-checks.sh | 9 ++++---- .../codev/scripts/forge/gitlab/pr-view.sh | 10 +++++++-- .../spec-1951-forge-read-concepts.test.ts | 21 +++++++++++++++---- 3 files changed, 30 insertions(+), 10 deletions(-) diff --git a/packages/codev/scripts/forge/github/commit-checks.sh b/packages/codev/scripts/forge/github/commit-checks.sh index bc9f786b9..714ebf209 100755 --- a/packages/codev/scripts/forge/github/commit-checks.sh +++ b/packages/codev/scripts/forge/github/commit-checks.sh @@ -3,9 +3,10 @@ # Input: CODEV_COMMIT_SHA (full or abbreviated commit SHA) # Output: JSON [{name, state, url?}] (CommitCheckItem[] in forge-contracts.ts) # -# Two read-only GETs: the commit's check runs (GitHub Actions and other apps, latest -# attempt per name, paginated) and its legacy commit statuses. Both are normalized to -# one state vocabulary: pass | fail | pending | skipped | neutral. +# Two read-only GETs, both paginated (a truncated list could hide a failure): the +# commit's check runs (GitHub Actions and other apps, latest attempt per name) and its +# legacy commit statuses. Both are normalized to one state vocabulary: +# pass | fail | pending | skipped | neutral. # check run: not completed → pending; success → pass; skipped → skipped; # neutral → neutral; any other conclusion (failure, cancelled, # timed_out, action_required, stale, startup_failure) → fail @@ -18,7 +19,7 @@ # forge-executable: gh runs="$(gh api --paginate "repos/{owner}/{repo}/commits/${CODEV_COMMIT_SHA}/check-runs?per_page=100" \ --jq '.check_runs[] | {kind: "run", name, status, conclusion, url: .html_url}')" || exit 1 -statuses="$(gh api "repos/{owner}/{repo}/commits/${CODEV_COMMIT_SHA}/status?per_page=100" \ +statuses="$(gh api --paginate "repos/{owner}/{repo}/commits/${CODEV_COMMIT_SHA}/status?per_page=100" \ --jq '.statuses[] | {kind: "status", name: .context, state, url: .target_url}')" || exit 1 printf '%s\n%s\n' "$runs" "$statuses" | jq -s ' map( diff --git a/packages/codev/scripts/forge/gitlab/pr-view.sh b/packages/codev/scripts/forge/gitlab/pr-view.sh index fbccbb198..61a31018b 100755 --- a/packages/codev/scripts/forge/gitlab/pr-view.sh +++ b/packages/codev/scripts/forge/gitlab/pr-view.sh @@ -4,7 +4,7 @@ # Output: glab's merge-request JSON, passed through, plus the PrViewResult fields # (forge-contracts.ts) that GitLab names differently: # web_url -> url (the MR's browser page) -# description -> body +# description -> body ("" when GitLab sends null, as github/gitea do) # target_branch / source_branch -> baseRefName / headRefName # sha -> headRefOid (Spec 1951) # draft -> isDraft @@ -25,10 +25,16 @@ # first-line heuristic, so the backend is declared explicitly (#1455). # forge-executable: glab out="$(glab mr view "$CODEV_PR_NUMBER" --output json)" || exit 1 +# An empty body at exit 0 would give jq nothing to work on: it would print nothing and +# exit 0, an ambiguous "success" with no data. Fail loudly instead, as gitea's script does. +if [ -z "$out" ]; then + echo "gitlab forge: empty \`glab mr view\` response for merge request ${CODEV_PR_NUMBER}" >&2 + exit 1 +fi printf '%s' "$out" | jq ' def str($v): ($v | type) == "string"; . + {url: .web_url, reviewDecision: null} - + (if str(.description) then {body: .description} else {} end) + + {body: (if str(.description) then .description else "" end)} + (if str(.target_branch) then {baseRefName: .target_branch} else {} end) + (if str(.source_branch) then {headRefName: .source_branch} else {} end) + (if str(.sha) then {headRefOid: .sha} else {} end) diff --git a/packages/codev/src/__tests__/spec-1951-forge-read-concepts.test.ts b/packages/codev/src/__tests__/spec-1951-forge-read-concepts.test.ts index 0dcec3582..4392c2bde 100644 --- a/packages/codev/src/__tests__/spec-1951-forge-read-concepts.test.ts +++ b/packages/codev/src/__tests__/spec-1951-forge-read-concepts.test.ts @@ -197,10 +197,12 @@ describe.skipIf(!posixWithJq)('Spec 1951 — github scripts honour the contracts { name: 'legacy/bad', state: 'fail' }, { name: 'legacy/wait', state: 'pending' }, ]); - const calls = fs.readFileSync(path.join(tmp, 'gh-calls'), 'utf-8'); - expect(calls).toContain(`repos/{owner}/{repo}/commits/${SHA}/check-runs`); - expect(calls).toContain('--paginate'); - expect(calls).toContain(`repos/{owner}/{repo}/commits/${SHA}/status`); + // Both lists are paginated: a truncated list could hide a failure. + const calls = fs.readFileSync(path.join(tmp, 'gh-calls'), 'utf-8').trim().split('\n'); + expect(calls).toHaveLength(2); + expect(calls[0]).toContain(`repos/{owner}/{repo}/commits/${SHA}/check-runs`); + expect(calls[1]).toContain(`repos/{owner}/{repo}/commits/${SHA}/status`); + for (const call of calls) expect(call).toContain('--paginate'); }); it('commit-checks reports a commit with nothing on it as an empty list', async () => { @@ -289,12 +291,23 @@ describe.skipIf(!posixWithJq)('Spec 1951 — gitlab and gitea pr-view carry the expect('mergeable' in data).toBe(false); }); + it('gitlab reports a null description as an empty body, as github and gitea do', async () => { + const result = await runGitlab(glabMr({ description: null })); + expect(result.data).toMatchObject({ body: '' }); + }); + it('gitlab fails when glab fails, instead of reporting jq\'s exit 0 (#1645)', async () => { const result = await runGitlab('', 1); expect(result.data).toBeNull(); expect(result.error).not.toBeNull(); }); + it('gitlab fails loudly when glab exits 0 with no output', async () => { + const result = await runGitlab('', 0); + expect(result.data).toBeNull(); + expect(result.error?.stderr).toContain('empty `glab mr view` response'); + }); + const runGitea = async (pull: Record) => { const body = JSON.stringify({ number: 7, title: 't', state: 'open', body: 'b', html_url: 'https://gt/pulls/7', From 6bc4b187bb67ae9fc4b3a252b5429de7201f1905 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 14:50:05 -0800 Subject: [PATCH 24/94] =?UTF-8?q?chore(porch):=201951=20advance=20plan=20p?= =?UTF-8?q?hase=20=E2=86=92=20readonly=5Fcore?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1951-read-only-pr-check-for-archite/status.yaml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 004d3e513..3725f786d 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -5,10 +5,10 @@ phase: implement plan_phases: - id: forge_read_concepts title: Forge read concepts for PR mechanics - status: in_progress + status: complete - id: readonly_core title: Read-only runner, configuration and report core - status: pending + status: in_progress - id: check_pr_mechanics title: 'codev check pr: merge mechanics' status: pending @@ -24,7 +24,7 @@ plan_phases: - id: docs_guidance title: Architect guidance and command documentation status: pending -current_plan_phase: forge_read_concepts +current_plan_phase: readonly_core gates: spec-approval: status: approved @@ -39,11 +39,13 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T22:44:06.744Z' +updated_at: '2026-11-23T22:50:05.115Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' acknowledged_at: '2026-11-23T21:23:07.115Z' + - boundary: plan-phase:readonly_core + at: '2026-11-23T22:50:05.115Z' From 2a3c23d063ec811e0d2b096f1d30efa9e99817f4 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 14:50:10 -0800 Subject: [PATCH 25/94] chore(porch): 1951 acknowledge context refresh --- codev/projects/1951-read-only-pr-check-for-archite/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 3725f786d..d712617cf 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -42,10 +42,11 @@ iteration: 1 build_complete: false history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T22:50:05.115Z' +updated_at: '2026-11-23T22:50:10.516Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' acknowledged_at: '2026-11-23T21:23:07.115Z' - boundary: plan-phase:readonly_core at: '2026-11-23T22:50:05.115Z' + acknowledged_at: '2026-11-23T22:50:10.516Z' From 7f4dd48793f1da67a34909a73088cf7ce7eab151 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 14:50:20 -0800 Subject: [PATCH 26/94] [Spec 1951] Thread log: Phase 1 review --- codev/state/spir-1951_thread.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index c4e41d958..3d3b0e99e 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -68,3 +68,9 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals - Full suite: run 1 failed on bugfix-1137 (mine: gitea pr-view shape, fixed) + 3 spawn-heavy tests that pass alone (launch-loop, ide-command, agy-auth-cache). porch `tests` failed again at load ~30 (names not shown); my next full run passed clean (8290/8290). Per main-32: stopped, opened draft PR #1958 for CI. +- Phase 1 tests-check skipped once under main-32 (architect confirmed GitHub 8/8 green at bb2ad2710); + skip lived only in worktree .codev/config.local.json, removed in the same command; noted in PR #1958. +- CMAP Phase 1: codex APPROVE, claude APPROVE. Follow-ups applied in 0448553f0: gitlab empty-output guard + + body "" default; legacy /status paginated. Probe: `gh pr view --json mergeStateStatus,reviewDecision` works + without push access (cli/cli). Claude also noted: gitlab pr-view now maps body/baseRefName/headRefName + (name in PR body); add the 2 concepts to repo-local `forge` skill tables in Phase 7. From 66b6921c005c7339ee163ec1198ed29ba535daa2 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 15:05:24 -0800 Subject: [PATCH 27/94] [Spec 1951][Phase: readonly_core] feat: read-only runner, allow-list, settings, report core and git plumbing - allow-list.ts: closed per-subcommand git grammar; diff/log/show forced to --no-ext-diff --no-textconv; ref-neutral fetch only; four read forge concepts - runner.ts: the only subprocess path; argv spawn, GIT_TERMINAL_PROMPT=0, ls-remote/fetch and forge calls bounded, with its own deadline race - validate.ts, roots.ts (roots from git), settings.ts (check.* with key+file on error) - report.ts (schema 1, verdict, exit codes, check.skip, summarizeRuns), render.ts - git-facts.ts: live tips, ensureCommits, ancestry, :(top,glob) pathspec filters - test helpers: fixture repos with state snapshot, stub git/gh PATH recorders - audited-imports test keeps child_process and the forge dispatcher in runner.ts --- .../check/__tests__/allow-list.test.ts | 122 ++++++++ .../check/__tests__/git-facts.test.ts | 283 ++++++++++++++++++ .../check/__tests__/helpers/git-fixture.ts | 127 ++++++++ .../check/__tests__/helpers/stub-bin.ts | 126 ++++++++ .../commands/check/__tests__/imports.test.ts | 141 +++++++++ .../check/__tests__/report-render.test.ts | 163 ++++++++++ .../commands/check/__tests__/roots.test.ts | 84 ++++++ .../commands/check/__tests__/runner.test.ts | 166 ++++++++++ .../commands/check/__tests__/settings.test.ts | 129 ++++++++ .../commands/check/__tests__/validate.test.ts | 73 +++++ .../codev/src/commands/check/allow-list.ts | 267 +++++++++++++++++ .../codev/src/commands/check/git-facts.ts | 203 +++++++++++++ packages/codev/src/commands/check/render.ts | 110 +++++++ packages/codev/src/commands/check/report.ts | 187 ++++++++++++ packages/codev/src/commands/check/roots.ts | 70 +++++ packages/codev/src/commands/check/runner.ts | 165 ++++++++++ packages/codev/src/commands/check/settings.ts | 139 +++++++++ packages/codev/src/commands/check/validate.ts | 89 ++++++ packages/codev/src/lib/config.ts | 23 ++ 19 files changed, 2667 insertions(+) create mode 100644 packages/codev/src/commands/check/__tests__/allow-list.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/git-facts.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts create mode 100644 packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts create mode 100644 packages/codev/src/commands/check/__tests__/imports.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/report-render.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/roots.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/runner.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/settings.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/validate.test.ts create mode 100644 packages/codev/src/commands/check/allow-list.ts create mode 100644 packages/codev/src/commands/check/git-facts.ts create mode 100644 packages/codev/src/commands/check/render.ts create mode 100644 packages/codev/src/commands/check/report.ts create mode 100644 packages/codev/src/commands/check/roots.ts create mode 100644 packages/codev/src/commands/check/runner.ts create mode 100644 packages/codev/src/commands/check/settings.ts create mode 100644 packages/codev/src/commands/check/validate.ts diff --git a/packages/codev/src/commands/check/__tests__/allow-list.test.ts b/packages/codev/src/commands/check/__tests__/allow-list.test.ts new file mode 100644 index 000000000..c402ca245 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/allow-list.test.ts @@ -0,0 +1,122 @@ +/** + * Spec 1951 — the closed read-only grammar for `codev check`'s git calls. + */ + +import { describe, expect, it } from 'vitest'; +import { assertConceptAllowed, assertGitArgvAllowed, RunnerRefusal } from '../allow-list.js'; + +const SHA = 'a'.repeat(40); +const SHA2 = 'b'.repeat(40); +const ABS = process.platform === 'win32' ? 'C:\\repo' : '/repo'; + +interface Form { + globals: string[]; + sub: string; + rest: string[]; +} + +const form = (globals: string[], sub: string, ...rest: string[]): Form => ({ globals, sub, rest }); +const argv = (f: Form): string[] => [...f.globals, f.sub, ...f.rest]; + +/** Every form the commands use. Each must pass. */ +const ALLOWED: Form[] = [ + form([], 'version'), + form([], 'rev-parse', '--show-toplevel'), + form([], 'rev-parse', '--verify', '--quiet', `${SHA}^{commit}`), + form([], 'rev-list', '--first-parent', '--max-count=10', SHA), + form([], 'rev-list', '--count', `${SHA}..${SHA2}`), + form([], 'merge-base', SHA, SHA2), + form([], 'merge-base', '--is-ancestor', SHA, 'refs/remotes/origin/main'), + form([], 'log', '--no-ext-diff', '--no-textconv', '-z', '--format=%H%x00%B', `${SHA}..${SHA2}`), + form([], 'show', '--no-ext-diff', '--no-textconv', '-s', '--format=%B', SHA), + form([], 'diff', '--no-ext-diff', '--no-textconv', '--name-only', '-z', '--no-renames', SHA, SHA2, '--', ':(top)', ':(top,exclude,glob)**/x'), + form([], 'diff', '--no-ext-diff', '--no-textconv', '--numstat', '-z', SHA, SHA2), + form([], 'diff-tree', '--no-commit-id', '--name-only', '-r', '-z', SHA), + form([], 'cat-file', '-e', `${SHA}^{commit}`), + form([], 'cat-file', '-t', SHA), + form([], 'for-each-ref', '--format=%(refname)', 'refs/heads/main'), + form(['-C', ABS], 'ls-files', '--others', '--ignored', '--exclude-standard', '-z', '--', ':(top,glob)codev/**'), + form([], 'ls-remote', 'origin', 'refs/heads/main'), + form([], 'ls-remote', '--symref', 'origin', 'HEAD'), + form([], 'worktree', 'list', '--porcelain'), + form([], 'config', '--get', 'remote.origin.url'), + form([], 'symbolic-ref', '--short', '-q', 'HEAD'), + form(['-C', ABS, '--no-optional-locks'], 'status', '--porcelain=v1', '-z', '--untracked-files=all'), + form([], 'merge-tree', '--write-tree', '--name-only', '--no-messages', '-z', SHA, SHA2), + form(['-c', 'gc.auto=0', '-c', 'maintenance.auto=false'], 'fetch', '--no-write-fetch-head', '--refmap=', '--no-tags', '--quiet', 'origin', SHA, SHA2), +]; + +const FETCH_GLOBALS = ['-c', 'gc.auto=0', '-c', 'maintenance.auto=false']; + +/** Named refusals from the plan's acceptance table. */ +const REFUSED: Array<[string, string[]]> = [ + ['update-ref', ['update-ref', 'refs/heads/x', SHA]], + ['push', ['push', 'origin', 'main']], + ['branch -D', ['branch', '-D', 'x']], + ['fetch origin main', [...FETCH_GLOBALS, 'fetch', '--no-write-fetch-head', '--refmap=', 'origin', 'main']], + ['fetch without --refmap=', [...FETCH_GLOBALS, 'fetch', '--no-write-fetch-head', 'origin', SHA]], + ['fetch without --no-write-fetch-head', [...FETCH_GLOBALS, 'fetch', '--refmap=', 'origin', SHA]], + ['fetch without the housekeeping overrides', ['fetch', '--no-write-fetch-head', '--refmap=', 'origin', SHA]], + ['fetch from another remote', [...FETCH_GLOBALS, 'fetch', '--no-write-fetch-head', '--refmap=', 'upstream', SHA]], + ['fetch an abbreviated SHA', [...FETCH_GLOBALS, 'fetch', '--no-write-fetch-head', '--refmap=', 'origin', 'abc1234']], + ['merge-tree without --write-tree', ['merge-tree', SHA, SHA2]], + ['status without --no-optional-locks', ['status', '--porcelain=v1']], + ['config --unset', ['config', '--unset', 'x.y']], + ['config set', ['config', 'x.y', 'z']], + ['config read without --get', ['config', 'remote.origin.url']], + ['symbolic-ref HEAD refs/heads/x', ['symbolic-ref', 'HEAD', 'refs/heads/x']], + ['worktree remove', ['worktree', 'remove', '/x']], + ['worktree list without --porcelain', ['worktree', 'list']], + ['-c core.hooksPath=x log', ['-c', 'core.hooksPath=x', 'log', '--no-ext-diff', '--no-textconv', SHA]], + ['-c on a subcommand other than fetch', ['-c', 'gc.auto=0', 'log', '--no-ext-diff', '--no-textconv', SHA]], + ['--exec-path', ['--exec-path=/x', 'version']], + ['--git-dir', ['--git-dir=/x', 'version']], + ['-C with a relative path', ['-C', 'repo', 'version']], + ['a global option after the subcommand', ['status', '--no-optional-locks', '--porcelain=v1']], + ['ls-remote another remote', ['ls-remote', 'upstream', 'HEAD']], + ['a revision beginning with -', ['merge-base', '--', SHA]], + ['a revision with ~', ['cat-file', '-e', 'HEAD~1']], + ['a triple-dot range', ['log', '--no-ext-diff', '--no-textconv', `${SHA}...${SHA2}`]], + ['pathspecs where none are allowed', ['merge-tree', '--write-tree', SHA, SHA2, '--', 'x']], + ['an empty pathspec', ['diff', '--no-ext-diff', '--no-textconv', SHA, SHA2, '--', '']], + ['a control character', ['cat-file', '-e', `${SHA}\n`]], + ['no subcommand', []], + ['a subcommand that is an Object.prototype key', ['toString']], + ['diff without --no-ext-diff', ['diff', '--no-textconv', SHA, SHA2]], + ['diff without --no-textconv', ['diff', '--no-ext-diff', SHA, SHA2]], + ['log without --no-ext-diff --no-textconv', ['log', SHA]], + ['show without --no-ext-diff --no-textconv', ['show', '-s', SHA]], +]; + +const BAD_FLAGS = ['--output=x', '--ext-diff', '--textconv', '--filters', '--upload-pack=x', '--exec=x', '--frobnicate']; + +describe('Spec 1951 — read-only git allow-list', () => { + it.each(ALLOWED.map((f) => [argv(f).join(' '), f] as const))('allows %s', (_name, f) => { + expect(assertGitArgvAllowed(argv(f))).toBe(f.sub); + }); + + it.each(REFUSED)('refuses %s', (_name, args) => { + expect(() => assertGitArgvAllowed(args)).toThrow(RunnerRefusal); + }); + + describe('refuses the file-writing and program-running flags on every allowed subcommand', () => { + const cases = ALLOWED.flatMap((f) => BAD_FLAGS.map((flag) => [`${f.sub} ${flag}`, { ...f, rest: [flag, ...f.rest] }] as const)); + it.each(cases)('%s', (_name, f) => { + expect(() => assertGitArgvAllowed(argv(f))).toThrow(RunnerRefusal); + }); + }); + + it('names the refused command in the error', () => { + expect(() => assertGitArgvAllowed(['push', 'origin'])).toThrow(/refused to run git push origin: git push is not on the read-only list/); + }); +}); + +describe('Spec 1951 — read-only forge concepts', () => { + it.each(['pr-view', 'pr-search', 'commit-checks', 'workflow-runs'])('allows %s', (concept) => { + expect(() => assertConceptAllowed(concept)).not.toThrow(); + }); + + it.each(['pr-merge', 'pr-comment', 'pr-create', 'issue-comment', 'pr-diff'])('refuses %s', (concept) => { + expect(() => assertConceptAllowed(concept)).toThrow(RunnerRefusal); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/git-facts.test.ts b/packages/codev/src/commands/check/__tests__/git-facts.test.ts new file mode 100644 index 000000000..c74f58e16 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/git-facts.test.ts @@ -0,0 +1,283 @@ +/** + * Spec 1951 — git plumbing against real repositories: live tips, the ref-neutral fetch, + * ancestry, and `:(glob)` pathspec filters. + */ + +import { spawn as realSpawn, spawnSync, type ChildProcess } from 'node:child_process'; +import { EventEmitter } from 'node:events'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + atLeast, + changedFiles, + ensureCommits, + gitVersion, + hasCommit, + isAncestor, + liveTip, + mergeBase, + numstat, + parseGitVersion, + pathspecArgs, + remoteDefaultBranch, + resolveCommit, + type GitVersion, +} from '../git-facts.js'; +import { createRunner, type Runner, type SpawnFn } from '../runner.js'; +import { DEFAULT_NOT_FOR_READING, DEFAULT_WATCH } from '../settings.js'; +import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { createStubBin } from './helpers/stub-bin.js'; + +const isWindows = process.platform === 'win32'; + +let fx: Fixture; +let runner: Runner; +let version: GitVersion; + +function runnerIn(cwd: string, extraEnv: Record = {}): Runner { + return createRunner({ cwd, workspaceRoot: cwd, env: { ...fx.env, ...extraEnv }, timeoutMs: 20_000 }); +} + +/** Push a commit to `branch` on origin from a second clone; the main clone never sees it. */ +function pushFromElsewhere(branch: string, files: Record): string { + const other = fs.existsSync(path.join(fx.root, 'other')) ? path.join(fx.root, 'other') : fx.clone('other'); + fx.git(other, 'fetch', '-q', 'origin'); + fx.git(other, 'checkout', '-q', '-B', branch, 'origin/main'); + const sha = fx.commit(other, files, `on ${branch}`); + fx.git(other, 'push', '-q', '-f', 'origin', `${branch}`); + return sha; +} + +beforeEach(async () => { + fx = createFixture(); + runner = runnerIn(fx.main); + version = await gitVersion(runner); +}); + +afterEach(() => { + fx.cleanup(); +}); + +describe('Spec 1951 — git version', () => { + it('parses the installed version', () => { + expect(version.major).toBeGreaterThanOrEqual(2); + expect(parseGitVersion('git version 2.39.3 (Apple Git-146)')).toMatchObject({ major: 2, minor: 39, patch: 3 }); + expect(parseGitVersion('git version 2.45.windows.1')).toMatchObject({ major: 2, minor: 45, patch: 0 }); + expect(parseGitVersion('nonsense')).toBeNull(); + }); + + it('compares against a minimum', () => { + const v = (major: number, minor: number): GitVersion => ({ major, minor, patch: 0, text: '' }); + expect(atLeast(v(2, 38), { major: 2, minor: 38 })).toBe(true); + expect(atLeast(v(2, 37), { major: 2, minor: 38 })).toBe(false); + expect(atLeast(v(3, 0), { major: 2, minor: 38 })).toBe(true); + }); +}); + +describe('Spec 1951 — live tips', () => { + it('reads the live tip from origin without updating the remote-tracking ref', async () => { + const stale = fx.git(fx.main, 'rev-parse', 'refs/remotes/origin/main').trim(); + const live = pushFromElsewhere('main', { 'later.txt': 'later\n' }); + expect(await liveTip(runner, 'main')).toEqual({ ok: true, value: live }); + expect(fx.git(fx.main, 'rev-parse', 'refs/remotes/origin/main').trim()).toBe(stale); + }); + + it('reports a branch origin does not have as null', async () => { + expect(await liveTip(runner, 'no-such-branch')).toEqual({ ok: true, value: null }); + }); + + it('reports a failure by name', async () => { + fx.git(fx.main, 'remote', 'set-url', 'origin', path.join(fx.root, 'missing.git')); + const tip = await liveTip(runner, 'main'); + expect(tip.ok).toBe(false); + if (!tip.ok) expect(tip.reason).toMatch(/^ls-remote failed/); + }); + + it('reports an ls-remote past the time limit as timed out', async () => { + const hanging = (() => { + const child = new EventEmitter() as ChildProcess; + child.stdout = new EventEmitter() as ChildProcess['stdout']; + child.stderr = new EventEmitter() as ChildProcess['stderr']; + child.kill = (() => true) as ChildProcess['kill']; + return child; + }) as SpawnFn; + const slow = createRunner({ cwd: fx.main, workspaceRoot: fx.main, spawn: hanging, timeoutMs: 50 }); + expect(await liveTip(slow, 'main')).toEqual({ ok: false, reason: 'ls-remote timed out after 50ms' }); + }); + + it("reads origin's default branch", async () => { + expect(await remoteDefaultBranch(runner)).toEqual({ ok: true, value: 'main' }); + }); +}); + +describe('Spec 1951 — ensureCommits (the ref-neutral fetch)', () => { + it('fetches a missing commit and moves no ref, writes no FETCH_HEAD, leaves index and status alone', async () => { + const sha = pushFromElsewhere('feature', { 'feature.txt': 'feature\n' }); + expect(await hasCommit(runner, sha)).toBe(false); + const before = snapshotRepoState(fx, fx.main); + expect(before.fetchHead).toBeNull(); + + const result = await ensureCommits(runner, [sha], version); + + expect(result.get(sha)).toBeNull(); + expect(await hasCommit(runner, sha)).toBe(true); + expect(snapshotRepoState(fx, fx.main)).toEqual(before); + }); + + it('does not fetch a commit that is already present', async () => { + const head = fx.git(fx.main, 'rev-parse', 'HEAD').trim(); + const spawned: string[][] = []; + const recording = createRunner({ + cwd: fx.main, + workspaceRoot: fx.main, + env: fx.env, + spawn: ((command, args, options) => { + spawned.push([...args]); + return realSpawn(command, args, options); + }) as SpawnFn, + }); + expect((await ensureCommits(recording, [head], version)).get(head)).toBeNull(); + expect(spawned.some((args) => args.includes('fetch'))).toBe(false); + }); + + it('reports a commit origin cannot provide', async () => { + const ghost = 'f'.repeat(40); + const result = await ensureCommits(runner, [ghost], version); + expect(result.get(ghost)).toMatch(/^fffffff not available locally \(/); + }); + + it('does not fetch on a git too old for the ref-neutral form', async () => { + const ghost = 'e'.repeat(40); + const old: GitVersion = { major: 2, minor: 28, patch: 0, text: 'git version 2.28.0' }; + const result = await ensureCommits(runner, [ghost], old); + expect(result.get(ghost)).toBe('eeeeeee not available locally (git 2.28.0 cannot fetch without moving a ref; needs 2.29)'); + }); +}); + +describe('Spec 1951 — ancestry', () => { + it('finds the merge base and ancestry', async () => { + const base = fx.git(fx.main, 'rev-parse', 'HEAD').trim(); + fx.git(fx.main, 'checkout', '-q', '-b', 'topic'); + const topic = fx.commit(fx.main, { 'topic.txt': 'x\n' }, 'topic'); + fx.git(fx.main, 'checkout', '-q', 'main'); + const mainTip = fx.commit(fx.main, { 'main.txt': 'y\n' }, 'main'); + expect(await mergeBase(runner, topic, mainTip)).toBe(base); + expect(await isAncestor(runner, base, topic)).toBe(true); + expect(await isAncestor(runner, topic, mainTip)).toBe(false); + expect(await resolveCommit(runner, 'topic')).toBe(topic); + expect(await resolveCommit(runner, 'no-such-ref')).toBeNull(); + }); +}); + +describe('Spec 1951 — pathspec filters', () => { + let from: string; + let to: string; + + beforeEach(() => { + from = fx.git(fx.main, 'rev-parse', 'HEAD').trim(); + to = fx.commit( + fx.main, + { + 'CLAUDE.md': 'a\n', + 'sub/CLAUDE.md': 'b\n', + '.codev/config.json': '{}\n', + 'codev/roles/architect.md': 'r\n', + 'codev/projects/1-x/status.yaml': 's\n', + 'codev/state/x_thread.md': 't\n', + 'pnpm-lock.yaml': 'l\n', + 'packages/a/pnpm-lock.yaml': 'l\n', + 'src/app.ts': 'one\ntwo\n', + 'image.bin': '\u0000\u0001\u0002', + }, + 'many', + ); + }); + + it('an empty include list matches nothing and runs no git', async () => { + const spawn = vi.fn(); + const spied = createRunner({ cwd: fx.main, workspaceRoot: fx.main, spawn }); + expect(pathspecArgs({ include: [] })).toBeNull(); + expect(await changedFiles(spied, from, to, { include: [] })).toEqual([]); + expect(await numstat(spied, from, to, { include: [] })).toEqual([]); + expect(spawn).not.toHaveBeenCalled(); + }); + + it('an empty exclude list returns every changed file', async () => { + expect(pathspecArgs({ exclude: [] })).toEqual([]); + expect(await changedFiles(runner, from, to, { exclude: [] })).toHaveLength(10); + expect(await changedFiles(runner, from, to)).toHaveLength(10); + }); + + it('the default watch globs match as documented', async () => { + expect(await changedFiles(runner, from, to, { include: DEFAULT_WATCH })).toEqual([ + '.codev/config.json', + 'CLAUDE.md', + 'codev/roles/architect.md', + ]); + }); + + it('the default not-for-reading globs exclude porch state, thread logs and lockfiles, root and nested', async () => { + expect(await changedFiles(runner, from, to, { exclude: DEFAULT_NOT_FOR_READING })).toEqual([ + '.codev/config.json', + 'CLAUDE.md', + 'codev/roles/architect.md', + 'image.bin', + 'src/app.ts', + 'sub/CLAUDE.md', + ]); + }); + + it('anchors patterns at the repository root whatever directory git runs in', async () => { + const fromSub = runnerIn(path.join(fx.main, 'sub')); + expect(await changedFiles(fromSub, from, to, { include: ['CLAUDE.md'] })).toEqual(['CLAUDE.md']); + expect(await changedFiles(fromSub, from, to, { include: ['**/pnpm-lock.yaml'] })).toEqual(['packages/a/pnpm-lock.yaml', 'pnpm-lock.yaml']); + }); + + it('counts lines per file, and marks binary files', async () => { + const stats = await numstat(runner, from, to, { include: ['src/**', 'image.bin'] }); + expect(stats).toEqual([ + { path: 'image.bin', additions: 0, deletions: 0, binary: true }, + { path: 'src/app.ts', additions: 2, deletions: 0, binary: false }, + ]); + }); + + it('shows a rename as a delete plus an add, so a file moved away from a watched path is seen', async () => { + fx.git(fx.main, 'mv', 'CLAUDE.md', 'NOTES.md'); + fx.git(fx.main, 'commit', '-q', '-m', 'rename'); + const renamed = fx.git(fx.main, 'rev-parse', 'HEAD').trim(); + expect(await changedFiles(runner, to, renamed, { include: DEFAULT_WATCH })).toEqual(['CLAUDE.md']); + }); +}); + +describe.skipIf(isWindows)('Spec 1951 — every git call the plumbing makes is read-only (stub PATH recorder)', () => { + it('records the fetch and the reads, with no violation', async () => { + const stubs = createStubBin(path.join(fx.root, 'stub-bin')); + const sha = pushFromElsewhere('feature', { 'f.txt': 'f\n' }); + const restore = stubs.install(); + try { + const stubbed = runnerIn(fx.main); + expect((await ensureCommits(stubbed, [sha], version)).get(sha)).toBeNull(); + await liveTip(stubbed, 'main'); + await changedFiles(stubbed, 'HEAD', sha, { exclude: DEFAULT_NOT_FOR_READING }); + } finally { + restore(); + } + expect(stubs.violations()).toEqual([]); + const calls = stubs.gitCalls(); + expect(calls.some((c) => c.includes('fetch --no-write-fetch-head --refmap='))).toBe(true); + expect(calls.some((c) => c.startsWith('ls-remote origin refs/heads/main'))).toBe(true); + }); + + it('the stub catches a write made outside the runner', async () => { + const stubs = createStubBin(path.join(fx.root, 'stub-bin')); + const restore = stubs.install(); + try { + spawnSync('git', ['update-ref', 'refs/heads/x', 'HEAD'], { cwd: fx.main, env: { ...process.env, ...fx.env } }); + } finally { + restore(); + } + expect(stubs.violations()).toHaveLength(1); + expect(fx.git(fx.main, 'for-each-ref', 'refs/heads/x')).toBe(''); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts b/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts new file mode 100644 index 000000000..7d39f0a36 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts @@ -0,0 +1,127 @@ +/** + * Real git repositories for `codev check` tests (Spec 1951): a bare "origin", clones of it, + * and worktrees. Fixture setup runs git by ABSOLUTE path, so a stub `git` first on PATH + * records only what the code under test runs. + * + * Every git call here, and every runner a test builds with `fixtureEnv()`, ignores the + * user's global and system git config, so a signing key or hook path on the developer's + * machine cannot change the outcome. + */ + +import { execFileSync } from 'node:child_process'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; + +const EXE = process.platform === 'win32' ? '.exe' : ''; + +/** The absolute path of an executable on the current PATH. */ +export function resolveExecutable(name: string): string { + for (const dir of (process.env.PATH ?? '').split(path.delimiter)) { + if (!dir) continue; + const candidate = path.join(dir, name + EXE); + if (fs.existsSync(candidate)) return candidate; + } + throw new Error(`${name} not found on PATH`); +} + +export const REAL_GIT = resolveExecutable('git'); + +export interface Fixture { + /** Temp directory holding everything; remove with `cleanup()`. */ + root: string; + /** The bare repository every clone calls `origin`. */ + origin: string; + /** The main clone, on `main`, with one commit pushed. */ + main: string; + /** Environment that isolates git from the user's config; pass to runners. */ + env: Record; + git(cwd: string, ...args: string[]): string; + /** Write files (relative path → content; null deletes) and commit them. Returns the SHA. */ + commit(cwd: string, files: Record, message: string): string; + clone(name: string): string; + addWorktree(name: string, branch: string, base?: string): string; + cleanup(): void; +} + +export function createFixture(): Fixture { + const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codev-check-'))); + const emptyConfig = path.join(root, 'gitconfig'); + fs.writeFileSync(emptyConfig, '[user]\n\tname = Fixture\n\temail = fixture@example.invalid\n[init]\n\tdefaultBranch = main\n'); + const env: Record = { + GIT_CONFIG_GLOBAL: emptyConfig, + GIT_CONFIG_NOSYSTEM: '1', + GIT_AUTHOR_DATE: '2026-01-01T00:00:00Z', + GIT_COMMITTER_DATE: '2026-01-01T00:00:00Z', + }; + + const git = (cwd: string, ...args: string[]): string => + execFileSync(REAL_GIT, args, { cwd, env: { ...process.env, ...env }, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] }); + + const commit = (cwd: string, files: Record, message: string): string => { + for (const [rel, content] of Object.entries(files)) { + const file = path.join(cwd, rel); + if (content === null) { + git(cwd, 'rm', '-q', '--', rel); + continue; + } + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content); + git(cwd, 'add', '--', rel); + } + git(cwd, 'commit', '-q', '--allow-empty', '-m', message); + return git(cwd, 'rev-parse', 'HEAD').trim(); + }; + + const origin = path.join(root, 'origin.git'); + git(root, 'init', '-q', '--bare', '-b', 'main', origin); + const main = path.join(root, 'main'); + git(root, 'clone', '-q', origin, main); + commit(main, { 'README.md': 'fixture\n' }, 'initial'); + git(main, 'push', '-q', 'origin', 'main'); + + return { + root, + origin, + main, + env, + git, + commit, + clone(name) { + const dir = path.join(root, name); + git(root, 'clone', '-q', origin, dir); + return dir; + }, + addWorktree(name, branch, base = 'HEAD') { + const dir = path.join(main, '.builders', name); + git(main, 'worktree', 'add', '-q', '-b', branch, dir, base); + return dir; + }, + cleanup() { + fs.rmSync(root, { recursive: true, force: true }); + }, + }; +} + +export interface RepoState { + refs: string; + head: string; + index: string; + fetchHead: string | null; + status: string; +} + +/** Everything a read-only command must leave untouched, captured for comparison. */ +export function snapshotRepoState(fixture: Fixture, repo: string): RepoState { + const gitDir = path.resolve(repo, fixture.git(repo, 'rev-parse', '--git-dir').trim()); + const commonDir = path.resolve(repo, fixture.git(repo, 'rev-parse', '--git-common-dir').trim()); + const indexFile = path.join(gitDir, 'index'); + const fetchHead = path.join(commonDir, 'FETCH_HEAD'); + return { + refs: fixture.git(repo, 'for-each-ref', '--format=%(refname) %(objectname)'), + head: fs.readFileSync(path.join(gitDir, 'HEAD'), 'utf-8'), + index: fs.existsSync(indexFile) ? fs.readFileSync(indexFile).toString('base64') : '', + fetchHead: fs.existsSync(fetchHead) ? fs.readFileSync(fetchHead, 'utf-8') : null, + status: fixture.git(repo, '--no-optional-locks', 'status', '--porcelain=v1'), + }; +} diff --git a/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts b/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts new file mode 100644 index 000000000..df03ea6b5 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts @@ -0,0 +1,126 @@ +/** + * Stub `git` and `gh` for `codev check` tests (Spec 1951). POSIX only: the stubs are `sh` + * scripts found on PATH. + * + * Both record every invocation and check it against a read-only list THEY keep, separate + * from the runner's allow-list, so a runner bug cannot hide behind a matching stub. A call + * off the list is written to `violations` and fails with exit 99; `assertNoViolations()` + * turns it into a test failure. + * + * - `git` then execs the real git, whose absolute path was resolved before PATH changed. + * - `gh` answers from fixtures: `answer(args, stdout, { exit, sleepSeconds })` matches the + * exact argument list. An unanswered call exits 98. + * + * `install()` puts the stub directory first on the TEST PROCESS's PATH, so a subprocess + * started by any module — not only the runner — is recorded. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { REAL_GIT } from './git-fixture.js'; + +const GIT_STUB = `#!/bin/sh +# Stub git (Spec 1951 tests): record, check the read-only list, exec the real git. +printf '%s\\n' "$*" >> "$STUB_DIR/git-calls" +violation() { printf 'git %s :: %s\\n' "$*" "$REASON" >> "$STUB_DIR/violations"; echo "stub git refused: $REASON" >&2; exit 99; } +sub=""; skip=0; for a in "$@"; do + if [ "$skip" = 1 ]; then skip=0; continue; fi + case "$a" in + -C|-c) skip=1 ;; + --no-optional-locks) ;; + -*) REASON="global option $a"; violation "$@" ;; + *) sub="$a"; break ;; + esac +done +case "$sub" in + version|rev-parse|rev-list|merge-base|log|show|diff|diff-tree|cat-file|for-each-ref|ls-files|ls-remote|merge-tree) ;; + worktree) case "$*" in *"worktree list --porcelain"*) ;; *) REASON="worktree other than list"; violation "$@" ;; esac ;; + config) case "$*" in *"config --get"*) ;; *) REASON="config without --get"; violation "$@" ;; esac ;; + status) case "$*" in *--no-optional-locks*) ;; *) REASON="status without --no-optional-locks"; violation "$@" ;; esac ;; + symbolic-ref) [ "$#" -le 6 ] || { REASON="symbolic-ref write form"; violation "$@"; } ;; + fetch) case "$*" in *--no-write-fetch-head*--refmap=*) ;; *) REASON="fetch that may move a ref"; violation "$@" ;; esac ;; + *) REASON="subcommand $sub"; violation "$@" ;; +esac +for a in "$@"; do + case "$a" in + --output*|--ext-diff|--textconv|--filters|--upload-pack*|--exec*) REASON="flag $a"; violation "$@" ;; + esac +done +exec "$REAL_GIT" "$@" +`; + +const GH_STUB = `#!/bin/sh +# Stub gh (Spec 1951 tests): record, check the read-only list, answer from fixtures. +printf '%s\\n' "$*" >> "$STUB_DIR/gh-calls" +violation() { printf 'gh %s :: %s\\n' "$*" "$REASON" >> "$STUB_DIR/violations"; echo "stub gh refused: $REASON" >&2; exit 99; } +case "$1 $2" in + "pr view"|"pr list"|"run list"|"run view") ;; + api\\ *) for a in "$@"; do case "$a" in + -X|--method|-f|-F|--field|--raw-field|--input) REASON="api write flag $a"; violation "$@" ;; + esac; done ;; + *) REASON="$1 $2"; violation "$@" ;; +esac +for f in "$STUB_DIR"/answers/*.args; do + [ -e "$f" ] || break + if [ "$(cat "$f")" = "$*" ]; then + base="\${f%.args}" + [ -e "$base.sleep" ] && sleep "$(cat "$base.sleep")" + cat "$base.out" + exit "$(cat "$base.exit")" + fi +done +echo "stub gh: no answer for: $*" >&2 +exit 98 +`; + +export interface StubBin { + dir: string; + /** PATH with the stub directory first. */ + pathValue: string; + /** Environment for a runner: the stub PATH and the variables the stubs read. */ + env: Record; + answer(args: readonly string[], stdout: string, options?: { exit?: number; sleepSeconds?: number }): void; + gitCalls(): string[]; + ghCalls(): string[]; + violations(): string[]; + /** Put the stubs first on the test process's own PATH; returns the undo. */ + install(): () => void; +} + +export function createStubBin(dir: string): StubBin { + fs.mkdirSync(path.join(dir, 'answers'), { recursive: true }); + fs.writeFileSync(path.join(dir, 'git'), GIT_STUB, { mode: 0o755 }); + fs.writeFileSync(path.join(dir, 'gh'), GH_STUB, { mode: 0o755 }); + const pathValue = `${dir}${path.delimiter}${process.env.PATH ?? ''}`; + const env = { PATH: pathValue, STUB_DIR: dir, REAL_GIT }; + let answers = 0; + const lines = (file: string): string[] => { + const full = path.join(dir, file); + return fs.existsSync(full) ? fs.readFileSync(full, 'utf-8').split('\n').filter(Boolean) : []; + }; + return { + dir, + pathValue, + env, + answer(args, stdout, options = {}) { + const base = path.join(dir, 'answers', String(answers++)); + fs.writeFileSync(`${base}.args`, args.join(' ')); + fs.writeFileSync(`${base}.out`, stdout); + fs.writeFileSync(`${base}.exit`, String(options.exit ?? 0)); + if (options.sleepSeconds !== undefined) fs.writeFileSync(`${base}.sleep`, String(options.sleepSeconds)); + }, + gitCalls: () => lines('git-calls'), + ghCalls: () => lines('gh-calls'), + violations: () => lines('violations'), + install() { + const saved = { PATH: process.env.PATH, STUB_DIR: process.env.STUB_DIR, REAL_GIT: process.env.REAL_GIT }; + Object.assign(process.env, env); + return () => { + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }; + }, + }; +} diff --git a/packages/codev/src/commands/check/__tests__/imports.test.ts b/packages/codev/src/commands/check/__tests__/imports.test.ts new file mode 100644 index 000000000..8f3c66a4a --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/imports.test.ts @@ -0,0 +1,141 @@ +/** + * Spec 1951 — audited imports: `runner.ts` is the only path to a subprocess in + * `commands/check/`. + * + * Every import in the other source files must be on the list below. Adding one means + * adding it here WITH A REASON, which keeps the "single subprocess path" rule reviewable. + * Type-only imports (`import type …`) are erased at compile time and so are not audited. + * The stub-PATH recorder in git-facts.test.ts catches anything that slips past at run time. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { describe, expect, it } from 'vitest'; + +const CHECK_DIR = path.resolve(__dirname, '..'); + +interface ImportRule { + /** Named imports allowed; `'*'` allows any (only for modules inside commands/check/). */ + names: readonly string[] | '*'; + reason: string; +} + +/** Imports allowed in every source file other than runner.ts. */ +const ALLOWED: Record = { + 'node:path': { names: '*', reason: 'path arithmetic only; no I/O' }, + 'node:fs': { + names: ['existsSync', 'readFileSync', 'realpathSync', 'statSync', 'lstatSync'], + reason: 'read-only file system calls', + }, + '../../lib/config.js': { + names: ['loadConfig', 'findConfigSource'], + reason: 'reads configuration files; never writes or spawns', + }, +}; + +/** runner.ts alone may reach a subprocess. */ +const RUNNER_ALLOWED: Record = { + 'node:child_process': { names: ['spawn', 'ChildProcess', 'SpawnOptions'], reason: 'git is spawned from argv here, after the allow-list check' }, + '../../lib/forge.js': { + names: ['executeForgeCommandDetailed', 'getForgeCommand', 'loadForgeConfig', 'ForgeConfig'], + reason: 'the forge dispatcher, called only for the four read concepts', + }, +}; + +interface ParsedImport { + specifier: string; + names: string[] | '*'; + typeOnly: boolean; +} + +/** Static imports and re-exports, plus any dynamic import() or require(). */ +export function parseImports(source: string): { imports: ParsedImport[]; dynamic: string[] } { + const imports: ParsedImport[] = []; + const statement = /^\s*(import|export)\s+(type\s+)?([\s\S]*?)\s*from\s*['"]([^'"]+)['"]/gm; + for (const match of source.matchAll(statement)) { + const clause = match[3]; + const typeOnly = Boolean(match[2]); + let names: string[] | '*'; + if (/\*\s+as\s+\w+/.test(clause) || clause.trim() === '*') { + names = '*'; + } else { + const braces = /\{([\s\S]*)\}/.exec(clause); + names = braces + ? braces[1].split(',').map((n) => n.trim().replace(/^type\s+/, '').split(/\s+as\s+/)[0]).filter(Boolean) + : []; + const defaultName = clause.replace(/\{[\s\S]*\}/, '').replace(/,/g, '').trim(); + if (defaultName) names.push(`default:${defaultName}`); + } + imports.push({ specifier: match[4], names, typeOnly }); + } + for (const match of source.matchAll(/^\s*import\s+['"]([^'"]+)['"]/gm)) { + imports.push({ specifier: match[1], names: [], typeOnly: false }); + } + const dynamic = [...source.matchAll(/\b(import|require)\s*\(\s*['"]?([^'")]*)/g)].map((m) => `${m[1]}(${m[2]})`); + return { imports, dynamic }; +} + +const sources = fs + .readdirSync(CHECK_DIR) + .filter((file) => file.endsWith('.ts') && !file.endsWith('.d.ts')) + .sort(); + +describe('Spec 1951 — audited imports in commands/check/', () => { + it('audits every source file in the directory', () => { + expect(sources).toEqual( + expect.arrayContaining(['allow-list.ts', 'git-facts.ts', 'render.ts', 'report.ts', 'roots.ts', 'runner.ts', 'settings.ts', 'validate.ts']), + ); + }); + + it.each(sources)('%s imports only what the list allows', (file) => { + const { imports, dynamic } = parseImports(fs.readFileSync(path.join(CHECK_DIR, file), 'utf-8')); + expect(dynamic, `${file} uses a dynamic import or require`).toEqual([]); + const rules = file === 'runner.ts' ? { ...ALLOWED, ...RUNNER_ALLOWED } : ALLOWED; + for (const imp of imports) { + if (imp.typeOnly) continue; + if (imp.specifier.startsWith('./')) { + expect(fs.existsSync(path.join(CHECK_DIR, imp.specifier.replace(/\.js$/, '.ts'))), `${file}: ${imp.specifier}`).toBe(true); + continue; + } + const rule = rules[imp.specifier]; + expect(rule, `${file} imports ${imp.specifier}, which is not on the audited list`).toBeDefined(); + if (rule.names === '*') continue; + expect(imp.names, `${file} imports ${imp.specifier} as a namespace`).not.toBe('*'); + for (const name of imp.names as string[]) { + expect(rule.names, `${file} imports ${name} from ${imp.specifier}`).toContain(name); + } + } + }); + + it('only runner.ts imports child_process or the forge dispatcher', () => { + for (const file of sources.filter((f) => f !== 'runner.ts')) { + const { imports } = parseImports(fs.readFileSync(path.join(CHECK_DIR, file), 'utf-8')); + const specifiers = imports.filter((i) => !i.typeOnly).map((i) => i.specifier); + expect(specifiers.filter((s) => /child_process|lib\/forge\.js$/.test(s)), file).toEqual([]); + } + }); + + it('the parser sees every kind of import it audits', () => { + const parsed = parseImports( + [ + "import { a, type B, c as d } from 'x';", + "import * as ns from 'y';", + "import def, { e } from 'z';", + "import type { T } from 't';", + "export { f } from 'w';", + "import 'side-effect';", + "const m = await import('dyn');", + "const r = require('req');", + ].join('\n'), + ); + expect(parsed.imports).toEqual([ + { specifier: 'x', names: ['a', 'B', 'c'], typeOnly: false }, + { specifier: 'y', names: '*', typeOnly: false }, + { specifier: 'z', names: ['e', 'default:def'], typeOnly: false }, + { specifier: 't', names: ['T'], typeOnly: true }, + { specifier: 'w', names: ['f'], typeOnly: false }, + { specifier: 'side-effect', names: [], typeOnly: false }, + ]); + expect(parsed.dynamic).toEqual(['import(dyn)', 'require(req)']); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/report-render.test.ts b/packages/codev/src/commands/check/__tests__/report-render.test.ts new file mode 100644 index 000000000..6edcfb738 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/report-render.test.ts @@ -0,0 +1,163 @@ +/** + * Spec 1951 — the schema-1 report, verdict and exit codes, and both renderers. + */ + +import { describe, expect, it } from 'vitest'; +import { RunnerRefusal } from '../allow-list.js'; +import { + applySkips, + check, + CheckCommandError, + describeRuns, + errorReport, + exitCodeOf, + notRun, + off, + summarizeRuns, + truncateList, + verdictOf, + type PrReport, +} from '../report.js'; +import { attentionNames, renderChecks, renderErrorHuman, renderHuman, renderJson } from '../render.js'; +import { InputError } from '../validate.js'; + +const HEAD = 'a1b2c3d'.padEnd(40, '0'); +const BASE = '7c0f3ab'.padEnd(40, '0'); + +describe('Spec 1951 — verdict and exit code', () => { + it('is clear when nothing needs attention; info, off and skip never change it', () => { + const checks = [check('size', 'info', '+1 −0 in 1 file'), check('state', 'ok', 'OPEN'), off('deploy-run', 'no workflow'), check('overlap', 'skip', 'skipped')]; + expect(verdictOf(checks)).toBe('clear'); + expect(exitCodeOf(verdictOf(checks))).toBe(0); + }); + + it('is attention for an attention check', () => { + expect(verdictOf([check('state', 'ok', ''), check('attribution', 'attention', '1 line')])).toBe('attention'); + expect(exitCodeOf('attention')).toBe(1); + }); + + it('counts a check that could not run as attention, never as passing', () => { + const c = notRun('checks', 'commit-checks timed out after 30s'); + expect(c).toEqual({ id: 'checks', status: 'not-run', summary: 'commit-checks timed out after 30s', details: {}, reason: 'commit-checks timed out after 30s' }); + expect(verdictOf([c])).toBe('attention'); + }); + + it('replaces a skipped check, attention included, with a skip entry', () => { + const checks = applySkips([check('size', 'info', 'x'), check('attribution', 'attention', 'y', { hits: [1] })], new Set(['attribution'])); + expect(checks[1]).toEqual({ id: 'attribution', status: 'skip', summary: 'skipped (check.skip)', details: {}, reason: 'check.skip' }); + expect(verdictOf(checks)).toBe('clear'); + }); +}); + +describe('Spec 1951 — summarizeRuns', () => { + it('counts passed, failed and pending, with skipped and neutral as passed', () => { + const runs = summarizeRuns(HEAD, [ + { name: 'unit', state: 'fail' }, + { name: 'lint', state: 'pass' }, + { name: 'docs', state: 'skipped' }, + { name: 'info', state: 'neutral' }, + { name: 'e2e', state: 'pending' }, + ]); + expect(runs).toMatchObject({ sha: HEAD, passed: 3, failed: 1, pending: 1 }); + expect(runs.runs).toHaveLength(5); + expect(describeRuns(runs)).toBe('3 passed, 1 failed (unit), 1 still running'); + }); + + it('describes no runs, and truncates the failed names', () => { + expect(describeRuns(summarizeRuns(HEAD, []))).toBe('no runs'); + const many = summarizeRuns(HEAD, ['a', 'b', 'c', 'd', 'e'].map((name) => ({ name, state: 'fail' as const }))); + expect(describeRuns(many)).toBe('5 failed (a, b, c, … +2)'); + }); + + it('truncates a list with a count', () => { + expect(truncateList(['a', 'b'], 3)).toBe('a, b'); + expect(truncateList(['a', 'b', 'c', 'd'], 2)).toBe('a, b, … +2'); + }); +}); + +describe('Spec 1951 — human form', () => { + const checks = [ + check('attribution', 'attention', '2 lines: commit 9f8e7d6 "Co-Authored-By: Claude …"'), + check('trial-merge', 'ok', 'clean into main @ 7c0f3ab'), + check('checks', 'attention', 'code 57d2ec5: 7 passed, 1 failed (unit)\nhead a1b2c3d: no runs'), + notRun('forge', 'pr-view timed out after 30s'), + off('deploy-run', 'no deploy workflow configured (check.deploy.workflow)'), + check('size', 'skip', 'skipped (check.skip)'), + check('to-read', 'info', '14 files'), + ]; + + it('names what needs attention on the verdict line, with qualifiers', () => { + const names = attentionNames(checks, { qualifier: (c) => (c.id === 'checks' ? 'failed' : null) }); + expect(names).toEqual(['attribution', 'checks (failed)', 'forge (not run)']); + }); + + it('prints one line per check with its status word, continuation lines aligned', () => { + const lines = renderChecks(checks); + expect(lines).toEqual([ + ' ATTN attribution 2 lines: commit 9f8e7d6 "Co-Authored-By: Claude …"', + ' ok trial merge clean into main @ 7c0f3ab', + ' ATTN checks code 57d2ec5: 7 passed, 1 failed (unit)', + ' head a1b2c3d: no runs', + ' not run forge pr-view timed out after 30s', + ' off deploy run no deploy workflow configured (check.deploy.workflow)', + ' skip size skipped (check.skip)', + ' info to read 14 files', + ]); + }); + + it('puts the verdict first, then the header, then the checks', () => { + const text = renderHuman({ + verdictLine: 'ATTENTION PR #1957 — attribution', + header: ['PR #1957 Title OPEN builder/x → main'], + sections: [{ checks: [checks[0]] }], + }); + expect(text.split('\n')).toEqual([ + 'ATTENTION PR #1957 — attribution', + '', + 'PR #1957 Title OPEN builder/x → main', + ' ATTN attribution 2 lines: commit 9f8e7d6 "Co-Authored-By: Claude …"', + '', + ]); + }); + + it('prints a section title above its checks', () => { + const text = renderHuman({ verdictLine: 'CLEAR #1948', header: [], sections: [{ title: '#1948 merged', checks: [checks[1]] }] }); + expect(text).toBe('CLEAR #1948\n\n#1948 merged\n ok trial merge clean into main @ 7c0f3ab\n'); + }); +}); + +describe('Spec 1951 — --json', () => { + it('writes one object with the schema-1 shape for a report', () => { + const report: PrReport = { + schema: 1, + command: 'pr', + verdict: 'attention', + generatedAt: '2026-11-23T00:00:00.000Z', + pr: { number: 1957, title: 'T', state: 'OPEN', draft: false, headRef: 'builder/x', head: HEAD, baseRef: 'main', baseTip: BASE, localBranch: null }, + checks: [check('attribution', 'attention', '1 line', { patterns: ['x'], hits: [] })], + }; + const text = renderJson(report); + expect(text.endsWith('}\n')).toBe(true); + const parsed = JSON.parse(text); + expect(parsed).toEqual(report); + expect(Object.keys(parsed)).toEqual(['schema', 'command', 'verdict', 'generatedAt', 'pr', 'checks']); + expect(Object.keys(parsed.checks[0])).toEqual(['id', 'status', 'summary', 'details']); + }); + + it('writes the error report for a failure', () => { + const parsed = JSON.parse(renderJson(errorReport('pr', new CheckCommandError('PR #9 not found', 'gh: no pull requests found')))); + expect(parsed).toEqual({ schema: 1, command: 'pr', error: { message: 'PR #9 not found', cause: 'gh: no pull requests found' } }); + }); + + it('maps input errors, refusals and unexpected errors to an error report', () => { + expect(errorReport('deploy', new InputError('invalid PR number "12a"')).error).toEqual({ message: 'invalid PR number "12a"' }); + expect(errorReport('worktree', new RunnerRefusal(['git', 'push'], 'no')).error.message).toBe('refused to run git push: no'); + expect(errorReport('pr', new Error('boom')).error).toEqual({ message: 'unexpected failure: boom' }); + }); + + it('renders an error for stderr', () => { + expect(renderErrorHuman(errorReport('pr', new CheckCommandError('no origin', 'line 1\nline 2')))).toBe( + 'codev check pr: no origin\n line 1\n line 2\n', + ); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/roots.test.ts b/packages/codev/src/commands/check/__tests__/roots.test.ts new file mode 100644 index 000000000..274d12ef3 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/roots.test.ts @@ -0,0 +1,84 @@ +/** + * Spec 1951 — roots come from git, so `codev check` behaves the same from the main checkout + * and from inside a builder worktree. + */ + +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { CheckCommandError } from '../report.js'; +import { parseWorktreeList, resolveRoots } from '../roots.js'; +import { createRunner } from '../runner.js'; +import { loadCheckSettings } from '../settings.js'; +import { createFixture, type Fixture } from './helpers/git-fixture.js'; + +let fx: Fixture; + +const rootsFrom = (cwd: string) => resolveRoots(createRunner({ cwd, workspaceRoot: cwd, env: fx.env })); + +beforeEach(() => { + fx = createFixture(); +}); + +afterEach(() => { + fx.cleanup(); +}); + +describe('Spec 1951 — roots', () => { + it('from the main checkout, both roots are the main checkout', async () => { + expect(await rootsFrom(fx.main)).toEqual({ checkoutRoot: fx.main, mainRoot: fx.main }); + }); + + it('from a subdirectory, the checkout root is the top level', async () => { + const sub = path.join(fx.main, 'deep', 'er'); + fs.mkdirSync(sub, { recursive: true }); + expect(await rootsFrom(sub)).toEqual({ checkoutRoot: fx.main, mainRoot: fx.main }); + }); + + it('from a builder worktree, mainRoot is the main checkout and config is read from it', async () => { + const worktree = fx.addWorktree('spir-1', 'builder/spir-1'); + fs.mkdirSync(path.join(fx.main, '.codev'), { recursive: true }); + fs.writeFileSync(path.join(fx.main, '.codev', 'config.json'), JSON.stringify({ check: { watch: ['from-main/**'] } })); + fs.mkdirSync(path.join(worktree, '.codev'), { recursive: true }); + fs.writeFileSync(path.join(worktree, '.codev', 'config.json'), JSON.stringify({ check: { watch: ['from-worktree/**'] } })); + + const roots = await rootsFrom(path.join(worktree)); + expect(roots).toEqual({ checkoutRoot: worktree, mainRoot: fx.main }); + expect(loadCheckSettings(roots.mainRoot).watch).toEqual(['from-main/**']); + }); + + it('outside a git repository, fails', async () => { + const outside = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codev-check-norepo-'))); + try { + const error = await rootsFrom(outside).catch((err: unknown) => err); + expect(error).toBeInstanceOf(CheckCommandError); + expect((error as Error).message).toBe('not in a git repository'); + } finally { + fs.rmSync(outside, { recursive: true, force: true }); + } + }); + + it('without an origin remote, fails', async () => { + fx.git(fx.main, 'remote', 'remove', 'origin'); + await expect(rootsFrom(fx.main)).rejects.toThrow('this repository has no "origin" remote'); + }); +}); + +describe('Spec 1951 — parseWorktreeList', () => { + it('parses branches, detached heads and bare entries', () => { + const sep = path.sep; + const entries = parseWorktreeList( + [ + 'worktree /repo', 'HEAD ' + 'a'.repeat(40), 'branch refs/heads/main', '', + 'worktree /repo/.builders/x', 'HEAD ' + 'b'.repeat(40), 'detached', '', + 'worktree /bare.git', 'bare', '', + ].join('\n'), + ); + expect(entries.map((e) => ({ ...e, path: e.path.split(sep).filter(Boolean).pop() }))).toEqual([ + { path: 'repo', head: 'a'.repeat(40), branch: 'main', bare: false }, + { path: 'x', head: 'b'.repeat(40), branch: null, bare: false }, + { path: 'bare.git', head: null, branch: null, bare: true }, + ]); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/runner.test.ts b/packages/codev/src/commands/check/__tests__/runner.test.ts new file mode 100644 index 000000000..b1b9c22de --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/runner.test.ts @@ -0,0 +1,166 @@ +/** + * Spec 1951 — the runner: the only subprocess path in `codev check`. + */ + +import { EventEmitter } from 'node:events'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import type { ChildProcess } from 'node:child_process'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { RunnerRefusal } from '../allow-list.js'; +import { createRunner, formatDuration, type SpawnFn } from '../runner.js'; + +const isWindows = process.platform === 'win32'; + +/** A child that never exits on its own; records kill(). */ +function hangingChild(): ChildProcess & { killedWith: string[] } { + const child = new EventEmitter() as ChildProcess & { killedWith: string[] }; + child.stdout = new EventEmitter() as ChildProcess['stdout']; + child.stderr = new EventEmitter() as ChildProcess['stderr']; + child.killedWith = []; + child.kill = ((signal: string) => { + child.killedWith.push(signal); + return true; + }) as ChildProcess['kill']; + return child; +} + +let workspace: string; + +function writeForgeConfig(forge: Record): void { + fs.mkdirSync(path.join(workspace, '.codev'), { recursive: true }); + fs.writeFileSync(path.join(workspace, '.codev', 'config.json'), JSON.stringify({ forge })); +} + +beforeEach(() => { + workspace = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codev-check-runner-'))); +}); + +afterEach(() => { + fs.rmSync(workspace, { recursive: true, force: true }); +}); + +describe('Spec 1951 — runner: git', () => { + it('refuses a command off the allow-list before spawning it', async () => { + const spawn = vi.fn(); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace, spawn }); + for (const args of [['push', 'origin', 'main'], ['update-ref', 'refs/heads/x', 'a'.repeat(40)], ['branch', '-D', 'x'], ['status']]) { + await expect(runner.git(args)).rejects.toThrow(RunnerRefusal); + } + expect(spawn).not.toHaveBeenCalled(); + }); + + it('spawns git from argv, never a shell, with GIT_TERMINAL_PROMPT=0 and windowsHide', async () => { + const child = hangingChild(); + const spawn = vi.fn(() => child); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace, spawn, env: { EXTRA: '1' } }); + const pending = runner.git(['version']); + child.stdout!.emit('data', Buffer.from('git version 2.50.1\n')); + child.emit('close', 0); + await expect(pending).resolves.toEqual({ stdout: 'git version 2.50.1\n', stderr: '', exitCode: 0, timedOut: false }); + const [command, args, options] = spawn.mock.calls[0]; + expect(command).toBe('git'); + expect(args).toEqual(['version']); + expect(options.shell).toBeUndefined(); + expect(options.windowsHide).toBe(true); + expect(options.cwd).toBe(workspace); + expect(options.env).toMatchObject({ GIT_TERMINAL_PROMPT: '0', EXTRA: '1' }); + }); + + it('bounds ls-remote by timeoutMs and kills the child', async () => { + const child = hangingChild(); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace, spawn: () => child, timeoutMs: 50 }); + const result = await runner.git(['ls-remote', 'origin', 'refs/heads/main']); + expect(result).toEqual({ stdout: '', stderr: '', exitCode: null, timedOut: true }); + expect(child.killedWith).toEqual(['SIGKILL']); + }); + + it('bounds fetch by timeoutMs', async () => { + const child = hangingChild(); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace, spawn: () => child, timeoutMs: 50 }); + const result = await runner.git(['-c', 'gc.auto=0', '-c', 'maintenance.auto=false', 'fetch', '--no-write-fetch-head', '--refmap=', 'origin', 'a'.repeat(40)]); + expect(result.timedOut).toBe(true); + }); + + it('does not bound a local git call', async () => { + const child = hangingChild(); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace, spawn: () => child, timeoutMs: 20 }); + const pending = runner.git(['version']); + await new Promise((resolve) => setTimeout(resolve, 80)); + child.emit('close', 0); + await expect(pending).resolves.toMatchObject({ exitCode: 0, timedOut: false }); + expect(child.killedWith).toEqual([]); + }); + + it('runs the real git', async () => { + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace }); + const result = await runner.git(['version']); + expect(result.exitCode).toBe(0); + expect(result.stdout).toMatch(/^git version \d+\.\d+/); + }); + + it('formats durations for messages', () => { + expect(formatDuration(30_000)).toBe('30s'); + expect(formatDuration(250)).toBe('250ms'); + }); +}); + +describe('Spec 1951 — runner: forge', () => { + it('refuses a concept off the read-only list before dispatch', async () => { + writeForgeConfig({ 'pr-merge': 'echo merged > merged.txt' }); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace }); + await expect(runner.forge('pr-merge')).rejects.toThrow(RunnerRefusal); + expect(fs.existsSync(path.join(workspace, 'merged.txt'))).toBe(false); + }); + + it('reports a disabled concept', async () => { + writeForgeConfig({ provider: 'gitea' }); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace }); + await expect(runner.forge('pr-search')).resolves.toEqual({ ok: false, kind: 'disabled', reason: 'pr-search unavailable on gitea' }); + expect(runner.provider()).toBe('gitea'); + }); + + it.skipIf(isWindows)('returns parsed data', async () => { + writeForgeConfig({ 'pr-view': 'printf \'{"number":%s}\' "$CODEV_PR_NUMBER"' }); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace }); + await expect(runner.forge('pr-view', { CODEV_PR_NUMBER: '7' })).resolves.toEqual({ ok: true, data: { number: 7 } }); + }); + + it.skipIf(isWindows)('reports invalid output when the concept prints non-JSON', async () => { + writeForgeConfig({ 'pr-view': 'echo this is not json' }); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace }); + await expect(runner.forge('pr-view')).resolves.toEqual({ ok: false, kind: 'invalid', reason: 'pr-view returned invalid output' }); + }); + + it.skipIf(isWindows)('reports a failure with the first line of stderr', async () => { + writeForgeConfig({ 'pr-view': 'echo "no such PR" >&2; echo more >&2; exit 3' }); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace }); + await expect(runner.forge('pr-view')).resolves.toEqual({ ok: false, kind: 'failed', reason: 'pr-view failed: no such PR' }); + }); + + it.skipIf(isWindows)('reports a call past timeoutMs as timed out', async () => { + writeForgeConfig({ 'pr-view': 'sleep 5' }); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace, timeoutMs: 300 }); + const started = Date.now(); + await expect(runner.forge('pr-view')).resolves.toEqual({ ok: false, kind: 'timeout', reason: 'pr-view timed out after 300ms' }); + expect(Date.now() - started).toBeLessThan(4_000); + }); + + it.skipIf(isWindows)('does not wait for a grandchild that holds the output pipe open', async () => { + // The shell is killed at the time limit, but the background sleep keeps stdout open, + // so the dispatcher alone would wait the full 8 s. The runner's own deadline does not. + writeForgeConfig({ 'pr-view': 'sleep 8 & wait' }); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace, timeoutMs: 200 }); + const started = Date.now(); + const outcome = await runner.forge('pr-view'); + expect(outcome).toMatchObject({ ok: false, kind: 'timeout' }); + expect(Date.now() - started).toBeLessThan(4_000); + }, 10_000); + + it.skipIf(isWindows)('passes the runner environment to the concept', async () => { + writeForgeConfig({ 'pr-view': 'printf \'{"v":"%s"}\' "$CHECK_RUNNER_PROBE"' }); + const runner = createRunner({ cwd: workspace, workspaceRoot: workspace, env: { CHECK_RUNNER_PROBE: 'yes' } }); + await expect(runner.forge('pr-view')).resolves.toEqual({ ok: true, data: { v: 'yes' } }); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/settings.test.ts b/packages/codev/src/commands/check/__tests__/settings.test.ts new file mode 100644 index 000000000..8ae4aea9a --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/settings.test.ts @@ -0,0 +1,129 @@ +/** + * Spec 1951 — `check.*` configuration: defaults, validation, and the file named on error. + */ + +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { CheckCommandError } from '../report.js'; +import { DEFAULT_NOT_FOR_READING, DEFAULT_WATCH, loadCheckSettings, parseCheckSettings } from '../settings.js'; + +let root: string; +let projectFile: string; +let localFile: string; + +function writeProject(check: unknown): void { + fs.writeFileSync(projectFile, JSON.stringify({ check })); +} + +beforeEach(() => { + root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codev-check-settings-'))); + fs.mkdirSync(path.join(root, '.codev')); + projectFile = path.join(root, '.codev', 'config.json'); + localFile = path.join(root, '.codev', 'config.local.json'); +}); + +afterEach(() => { + fs.rmSync(root, { recursive: true, force: true }); +}); + +function loadError(): CheckCommandError { + try { + loadCheckSettings(root); + } catch (err) { + expect(err).toBeInstanceOf(CheckCommandError); + return err as CheckCommandError; + } + throw new Error('expected loadCheckSettings to fail'); +} + +describe('Spec 1951 — check settings', () => { + it('applies the defaults when nothing is configured', () => { + fs.writeFileSync(projectFile, '{}'); + const settings = loadCheckSettings(root); + expect(settings.attribution).toEqual([]); + expect(settings.watch).toEqual(DEFAULT_WATCH); + expect(settings.flag).toEqual([]); + expect(settings.notForReading).toEqual(DEFAULT_NOT_FOR_READING); + expect(settings.deploy).toEqual({ branch: null, workflow: null }); + expect([...settings.skip]).toEqual([]); + }); + + it('reads every key', () => { + writeProject({ + attribution: ['co-authored-by: claude'], + watch: ['CLAUDE.md'], + flag: ['CLAUDE.md'], + notForReading: ['docs/**'], + deploy: { branch: 'production', workflow: 'deploy.yml' }, + skip: ['size', 'overlap'], + }); + const settings = loadCheckSettings(root); + expect(settings.attribution.map((p) => p.source)).toEqual(['co-authored-by: claude']); + expect(settings.attribution[0].regex.test('Co-Authored-By: Claude Opus')).toBe(true); + expect(settings.watch).toEqual(['CLAUDE.md']); + expect(settings.flag).toEqual(['CLAUDE.md']); + expect(settings.deploy).toEqual({ branch: 'production', workflow: 'deploy.yml' }); + expect([...settings.skip]).toEqual(['size', 'overlap']); + }); + + it('replaces the notForReading default rather than adding to it', () => { + writeProject({ notForReading: ['docs/**'] }); + expect(loadCheckSettings(root).notForReading).toEqual(['docs/**']); + }); + + it('lets config.local.json replace an array set by config.json', () => { + writeProject({ watch: ['a/**', 'b/**'] }); + fs.writeFileSync(localFile, JSON.stringify({ check: { watch: ['c/**'] } })); + expect(loadCheckSettings(root).watch).toEqual(['c/**']); + }); + + it('refuses a non-array check.watch, naming the key and the file', () => { + writeProject({ watch: 'CLAUDE.md' }); + expect(loadError().message).toBe(`check.watch must be an array of glob strings (in ${projectFile})`); + }); + + it('names config.local.json when that is the file that set the bad value', () => { + writeProject({ watch: ['ok/**'] }); + fs.writeFileSync(localFile, JSON.stringify({ check: { watch: [''] } })); + expect(loadError().message).toContain(`(in ${localFile})`); + }); + + it('refuses an unparseable attribution regex, naming the key and the file', () => { + writeProject({ attribution: ['co-authored-by: (claude'] }); + const message = loadError().message; + expect(message).toContain('check.attribution pattern "co-authored-by: (claude" is not a valid regex'); + expect(message).toContain(`(in ${projectFile})`); + }); + + it('refuses an unknown check.skip id', () => { + writeProject({ skip: ['size', 'colour'] }); + expect(loadError().message).toBe(`check.skip names an unknown check id "colour" (in ${projectFile})`); + }); + + it('refuses a deploy workflow that reads as an option, naming the value', () => { + writeProject({ deploy: { workflow: '--repo=x' } }); + expect(loadError().message).toBe(`check.deploy.workflow "--repo=x" may not begin with '-' (in ${projectFile})`); + }); + + it('refuses a deploy branch that is not a valid branch name', () => { + writeProject({ deploy: { branch: 'a..b' } }); + expect(loadError().message).toContain('check.deploy.branch "a..b" is not a valid branch name'); + }); + + it('refuses an unknown key, so a typo is not silently ignored', () => { + writeProject({ wacth: ['x'] }); + expect(loadError().message).toContain('check.wacth is not a known key'); + writeProject({ deploy: { workflows: 'x' } }); + expect(loadError().message).toContain('check.deploy.workflows is not a known key'); + }); + + it('refuses a check section that is not an object', () => { + expect(() => parseCheckSettings(['x'], () => null)).toThrow('check must be an object'); + }); + + it('refuses a glob with a control character', () => { + expect(() => parseCheckSettings({ flag: ['a\nb'] }, () => null)).toThrow(/check\.flag must contain only non-empty glob strings/); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/validate.test.ts b/packages/codev/src/commands/check/__tests__/validate.test.ts new file mode 100644 index 000000000..8819d3b95 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/validate.test.ts @@ -0,0 +1,73 @@ +/** + * Spec 1951 — input validation for `codev check`. + */ + +import { describe, expect, it } from 'vitest'; +import { + InputError, + isRefName, + validateAbsolutePath, + validateBuilderId, + validateConfigString, + validatePrNumber, + validateSha, +} from '../validate.js'; + +const ABS = process.platform === 'win32' ? 'C:\\repo\\.builders\\x' : '/repo/.builders/x'; + +describe('Spec 1951 — validation', () => { + it('accepts a positive PR number', () => { + expect(validatePrNumber('1951')).toBe(1951); + }); + + it.each(['12a', '0', '012', '-1', '1.5', '', ' 12', '99999999999999999999'])('refuses PR number %j, naming it', (raw) => { + expect(() => validatePrNumber(raw)).toThrow(InputError); + expect(() => validatePrNumber(raw)).toThrow(JSON.stringify(raw)); + }); + + it.each(['abc1234', 'a'.repeat(40)])('accepts SHA %s', (sha) => { + expect(validateSha(sha)).toBe(sha); + }); + + it.each(['zz12', 'abc123', 'a'.repeat(41), 'ABC1234', '-abc1234'])('refuses SHA %j, naming it', (raw) => { + expect(() => validateSha(raw)).toThrow(`invalid commit SHA ${JSON.stringify(raw)}`); + }); + + it.each(['spir-1951', 'bugfix-42', 'a.b_c'])('accepts builder id %s', (id) => { + expect(validateBuilderId(id)).toBe(id); + }); + + it.each(['../x', 'a..b', '-x', '.x', 'a/b', 'a b', ''])('refuses builder id %j', (raw) => { + expect(() => validateBuilderId(raw)).toThrow(InputError); + }); + + it('accepts an absolute path and refuses a relative one or a control character', () => { + expect(validateAbsolutePath(ABS, 'worktree')).toBe(ABS); + expect(() => validateAbsolutePath('repo/x', 'worktree')).toThrow('invalid worktree "repo/x"'); + expect(() => validateAbsolutePath(`${ABS}\n`, 'worktree')).toThrow(InputError); + }); + + it('refuses a config string that reads as an option, naming the value, key and file', () => { + expect(() => validateConfigString('--repo=x', 'check.deploy.workflow', '/repo/.codev/config.json')).toThrow( + 'check.deploy.workflow "--repo=x" may not begin with \'-\' (in /repo/.codev/config.json)', + ); + }); + + it('refuses a config string with a control character, or an empty or non-string one', () => { + expect(() => validateConfigString('deploy\u0007.yml', 'k', null)).toThrow('may not contain control characters'); + expect(() => validateConfigString('', 'k', null)).toThrow('must be a non-empty string'); + expect(() => validateConfigString(3, 'k', null)).toThrow('must be a non-empty string'); + expect(validateConfigString('deploy.yml', 'k', null)).toBe('deploy.yml'); + }); + + it.each(['main', 'builder/spir-1951', 'refs/heads/main', 'HEAD', 'release-1.2'])('accepts ref name %s', (ref) => { + expect(isRefName(ref)).toBe(true); + }); + + it.each(['', '-x', '/x', 'x/', 'x.', 'x.lock', 'a..b', 'a@{1}', 'a b', 'a~1', 'a^', 'a:b', 'a?', 'a*', 'a[', 'a\\b', '.x', 'a/.b', 'a//b', '@'])( + 'refuses ref name %j', + (ref) => { + expect(isRefName(ref)).toBe(false); + }, + ); +}); diff --git a/packages/codev/src/commands/check/allow-list.ts b/packages/codev/src/commands/check/allow-list.ts new file mode 100644 index 000000000..adddbaea9 --- /dev/null +++ b/packages/codev/src/commands/check/allow-list.ts @@ -0,0 +1,267 @@ +/** + * The read-only allow-list for `codev check` (Spec 1951 § Read-only enforcement). + * + * A CLOSED grammar: every token of a git argv must be explicitly permitted, so an unknown + * flag is refused rather than passed through. It covers the git subcommands the commands + * run, and only the flags they use. Diff-family commands must carry + * `--no-ext-diff --no-textconv`, so no repository-configured diff program runs; flags that + * write files (`--output`) or run programs (`--upload-pack`, `--exec`, `--textconv`, + * `--filters`) are never permitted. `fetch` is allowed only in its ref-neutral form, which + * adds objects and moves no ref and writes no FETCH_HEAD. + * + * Forge concepts are allowed by name: only the four read concepts. + */ + +import { hasControlChars, isFullSha, isRefName, isSha } from './validate.js'; +import { isAbsolute } from 'node:path'; + +export class RunnerRefusal extends Error { + constructor(public readonly argv: readonly string[], reason: string) { + super(`refused to run ${argv.join(' ')}: ${reason}`); + this.name = 'RunnerRefusal'; + } +} + +export const ALLOWED_CONCEPTS: readonly string[] = ['pr-view', 'pr-search', 'commit-checks', 'workflow-runs']; + +export function assertConceptAllowed(concept: string): void { + if (!ALLOWED_CONCEPTS.includes(concept)) { + throw new RunnerRefusal([concept], `forge concept '${concept}' is not on the read-only list (${ALLOWED_CONCEPTS.join(', ')})`); + } +} + +/** `-c` settings the ref-neutral fetch needs; no other `-c` is accepted. */ +const ALLOWED_CONFIG_OVERRIDES = new Set(['gc.auto=0', 'maintenance.auto=false']); + +interface Globals { + noOptionalLocks: boolean; + configOverrides: Set; +} + +type PositionalCheck = (positionals: string[]) => string | null; + +interface SubcommandRule { + /** Exact flags permitted. */ + flags?: readonly string[]; + /** `--name=` prefixes permitted; the value may be anything without control characters. */ + valueFlags?: readonly string[]; + /** Flags that must be present. */ + required?: readonly string[]; + /** Exactly one of these flags must be present. */ + oneOf?: readonly string[]; + /** Whether `--` followed by pathspecs is permitted. */ + pathspecs?: boolean; + /** Validates the positional arguments; returns a reason to refuse, or null. */ + positionals: PositionalCheck; + /** Extra checks on the global options. */ + globals?: (globals: Globals) => string | null; +} + +/** A revision `codev check` may name: a SHA, a ref name, or either peeled with `^{commit}`. */ +export function isRevision(value: string): boolean { + const base = value.endsWith('^{commit}') ? value.slice(0, -'^{commit}'.length) : value; + return isSha(base) || isRefName(base); +} + +/** A revision, or `..`. */ +function isRevisionOrRange(value: string): boolean { + const parts = value.split('..'); + if (parts.length === 1) return isRevision(value); + return parts.length === 2 && parts.every(isRevision); +} + +const none: PositionalCheck = (p) => (p.length === 0 ? null : `unexpected argument ${p[0]}`); + +function exactly(n: number, check: (value: string) => boolean, what: string): PositionalCheck { + return (p) => { + if (p.length !== n) return `expected ${n} ${what}, got ${p.length}`; + const bad = p.find((value) => !check(value)); + return bad === undefined ? null : `${JSON.stringify(bad)} is not a valid ${what}`; + }; +} + +function between(min: number, max: number, check: (value: string) => boolean, what: string): PositionalCheck { + return (p) => { + if (p.length < min || p.length > max) return `expected ${min}–${max} ${what}, got ${p.length}`; + const bad = p.find((value) => !check(value)); + return bad === undefined ? null : `${JSON.stringify(bad)} is not a valid ${what}`; + }; +} + +const NO_EXT_DIFF = ['--no-ext-diff', '--no-textconv'] as const; + +const RULES: Record = { + version: { positionals: none }, + 'rev-parse': { + flags: ['--show-toplevel', '--verify', '--quiet', '-q', '--abbrev-ref'], + positionals: between(0, 1, isRevision, 'revision'), + }, + 'rev-list': { + flags: ['--first-parent', '--parents', '--count', '--not', '--reverse'], + valueFlags: ['--max-count='], + positionals: between(1, 8, isRevisionOrRange, 'revision'), + }, + 'merge-base': { + flags: ['--is-ancestor'], + positionals: exactly(2, isRevision, 'revision'), + }, + log: { + flags: [...NO_EXT_DIFF, '--first-parent', '--no-merges', '-z'], + valueFlags: ['--format=', '--max-count='], + required: NO_EXT_DIFF, + positionals: between(1, 4, isRevisionOrRange, 'revision'), + }, + show: { + flags: [...NO_EXT_DIFF, '-s', '--no-patch'], + valueFlags: ['--format='], + required: NO_EXT_DIFF, + positionals: exactly(1, isRevision, 'revision'), + }, + diff: { + flags: [...NO_EXT_DIFF, '--name-only', '--numstat', '-z', '--no-renames'], + required: NO_EXT_DIFF, + pathspecs: true, + positionals: exactly(2, isRevision, 'revision'), + }, + 'diff-tree': { + flags: ['--no-commit-id', '--name-only', '-r', '-z', '--no-renames'], + positionals: between(1, 2, isRevision, 'revision'), + }, + 'cat-file': { + flags: ['-e', '-t', '-p'], + positionals: exactly(1, isRevision, 'revision'), + }, + 'for-each-ref': { + valueFlags: ['--format='], + positionals: between(0, 4, (v) => v.startsWith('refs/') && isRefName(v), 'ref pattern'), + }, + 'ls-files': { + flags: ['--others', '--ignored', '--exclude-standard', '--directory', '-z'], + pathspecs: true, + positionals: none, + }, + 'ls-remote': { + flags: ['--symref'], + positionals: (p) => { + if (p[0] !== 'origin') return 'ls-remote may only query origin'; + const bad = p.slice(1).find((ref) => !(ref === 'HEAD' || (ref.startsWith('refs/') && isRefName(ref)))); + return bad === undefined ? null : `${JSON.stringify(bad)} is not a valid ref`; + }, + }, + worktree: { + flags: ['--porcelain', '-z'], + required: ['--porcelain'], + positionals: exactly(1, (v) => v === 'list', 'worktree subcommand (only "list")'), + }, + config: { + flags: ['--get', '--get-regexp'], + oneOf: ['--get', '--get-regexp'], + positionals: exactly(1, (v) => /^[A-Za-z0-9._-]+$/.test(v), 'config key'), + }, + 'symbolic-ref': { + flags: ['--short', '-q', '--quiet'], + positionals: exactly(1, isRefName, 'ref name'), + }, + status: { + flags: ['--porcelain=v1', '-z', '--untracked-files=all'], + positionals: none, + globals: (g) => (g.noOptionalLocks ? null : 'status needs the global --no-optional-locks (a plain status may rewrite the index)'), + }, + 'merge-tree': { + flags: ['--write-tree', '--name-only', '--no-messages', '-z'], + required: ['--write-tree'], + positionals: exactly(2, isRevision, 'revision'), + }, + fetch: { + flags: ['--no-write-fetch-head', '--refmap=', '--no-tags', '--no-recurse-submodules', '--quiet'], + required: ['--no-write-fetch-head', '--refmap='], + positionals: (p) => { + if (p[0] !== 'origin') return 'fetch may only fetch from origin'; + if (p.length < 2) return 'fetch needs at least one commit SHA'; + const bad = p.slice(1).find((sha) => !isFullSha(sha)); + return bad === undefined ? null : `fetch accepts only full commit SHAs, not ${JSON.stringify(bad)}`; + }, + globals: (g) => + ALLOWED_CONFIG_OVERRIDES.size === g.configOverrides.size + ? null + : 'fetch needs -c gc.auto=0 -c maintenance.auto=false (no housekeeping)', + }, +}; + +/** Subcommands that reach the network, and so are bounded by the runner's time limit. */ +export const NETWORK_SUBCOMMANDS: ReadonlySet = new Set(['ls-remote', 'fetch']); + +/** + * Throws `RunnerRefusal` unless `argv` (the arguments after `git`) is on the read-only + * list. Returns the subcommand. + */ +export function assertGitArgvAllowed(argv: readonly string[]): string { + function refuse(reason: string): never { + throw new RunnerRefusal(['git', ...argv], reason); + } + const bad = argv.find((token) => hasControlChars(token)); + if (bad !== undefined) refuse('an argument contains a control character'); + + const globals: Globals = { noOptionalLocks: false, configOverrides: new Set() }; + let i = 0; + for (; i < argv.length && argv[i].startsWith('-'); i++) { + const token = argv[i]; + if (token === '--no-optional-locks') { + globals.noOptionalLocks = true; + } else if (token === '-C') { + const dir = argv[++i]; + if (dir === undefined || !isAbsolute(dir)) refuse('-C needs an absolute directory'); + } else if (token === '-c') { + const setting = argv[++i]; + if (setting === undefined || !ALLOWED_CONFIG_OVERRIDES.has(setting)) refuse(`-c ${setting ?? ''} is not permitted`); + globals.configOverrides.add(setting); + } else { + refuse(`global option ${token} is not permitted`); + } + } + + const subcommand = argv[i]; + if (subcommand === undefined) refuse('no git subcommand'); + if (!Object.hasOwn(RULES, subcommand)) refuse(`git ${subcommand} is not on the read-only list`); + const rule = RULES[subcommand]; + if (globals.configOverrides.size > 0 && subcommand !== 'fetch') refuse(`-c is permitted only for fetch`); + + const flags = new Set(rule.flags ?? []); + const seen = new Set(); + const positionals: string[] = []; + const rest = argv.slice(i + 1); + for (let j = 0; j < rest.length; j++) { + const token = rest[j]; + if (token === '--') { + if (!rule.pathspecs) refuse(`git ${subcommand} takes no pathspecs`); + const specs = rest.slice(j + 1); + if (specs.some((spec) => spec === '')) refuse('empty pathspec'); + break; + } + if (token.startsWith('-')) { + if (flags.has(token)) { + seen.add(token); + continue; + } + const valueFlag = (rule.valueFlags ?? []).find((prefix) => token.startsWith(prefix) && token.length > prefix.length); + if (valueFlag) { + seen.add(valueFlag); + continue; + } + refuse(`git ${subcommand} ${token} is not permitted`); + } + positionals.push(token); + } + + for (const required of rule.required ?? []) { + if (!seen.has(required)) refuse(`git ${subcommand} must carry ${required}`); + } + if (rule.oneOf && rule.oneOf.filter((flag) => seen.has(flag)).length !== 1) { + refuse(`git ${subcommand} must carry exactly one of ${rule.oneOf.join(', ')}`); + } + const positionalProblem = rule.positionals(positionals); + if (positionalProblem) refuse(positionalProblem); + const globalProblem = rule.globals?.(globals); + if (globalProblem) refuse(globalProblem); + return subcommand; +} diff --git a/packages/codev/src/commands/check/git-facts.ts b/packages/codev/src/commands/check/git-facts.ts new file mode 100644 index 000000000..82590121c --- /dev/null +++ b/packages/codev/src/commands/check/git-facts.ts @@ -0,0 +1,203 @@ +/** + * Git plumbing shared by the `codev check` commands (Spec 1951), all through the runner. + * + * Live tips come from `ls-remote` (no remote-tracking ref is updated). Missing objects are + * fetched in the ref-neutral form, which adds objects to the store and moves no ref, writes + * no FETCH_HEAD and runs no housekeeping. Path filters are git pathspecs with `:(glob)` + * magic, so git does the matching; an empty include list never becomes a bare `--`. + */ + +import { CheckCommandError } from './report.js'; +import type { GitResult, Runner } from './runner.js'; +import { isFullSha } from './validate.js'; + +export interface GitVersion { + major: number; + minor: number; + patch: number; + text: string; +} + +/** `merge-tree --write-tree` (the trial merge). */ +export const TRIAL_MERGE_MIN = { major: 2, minor: 38 } as const; +/** `fetch --no-write-fetch-head` (the ref-neutral fetch). */ +export const REF_NEUTRAL_FETCH_MIN = { major: 2, minor: 29 } as const; + +export type Lookup = { ok: true; value: T } | { ok: false; reason: string }; + +function firstLine(text: string): string { + return text.trim().split('\n')[0] ?? ''; +} + +/** Why a git call failed, for a `not run` reason. */ +export function failureReason(call: string, result: GitResult, timeoutLabel: string): string { + if (result.timedOut) return `${call} timed out after ${timeoutLabel}`; + const detail = firstLine(result.stderr); + return detail ? `${call} failed: ${detail}` : `${call} failed (exit ${result.exitCode})`; +} + +export function parseGitVersion(output: string): GitVersion | null { + const match = /git version (\d+)\.(\d+)(?:\.(\d+))?/.exec(output); + if (!match) return null; + return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3] ?? 0), text: output.trim() }; +} + +export async function gitVersion(runner: Runner): Promise { + const result = await runner.git(['version']); + const version = result.exitCode === 0 ? parseGitVersion(result.stdout) : null; + if (!version) throw new CheckCommandError('could not determine the git version', result.stderr.trim() || result.stdout.trim()); + return version; +} + +export function atLeast(version: GitVersion, min: { major: number; minor: number }): boolean { + return version.major > min.major || (version.major === min.major && version.minor >= min.minor); +} + +export function versionLabel(version: GitVersion): string { + return `${version.major}.${version.minor}.${version.patch}`; +} + +/** The live tip of `origin/`, or null when the branch does not exist there. */ +export async function liveTip(runner: Runner, branch: string): Promise> { + const ref = `refs/heads/${branch}`; + const result = await runner.git(['ls-remote', 'origin', ref]); + if (result.exitCode !== 0) return { ok: false, reason: failureReason('ls-remote', result, runner.timeoutLabel) }; + for (const line of result.stdout.split('\n')) { + const [sha, name] = line.trim().split(/\s+/); + if (name === ref && sha && isFullSha(sha)) return { ok: true, value: sha }; + } + return { ok: true, value: null }; +} + +/** The branch `origin`'s HEAD points at, or null when the remote does not say. */ +export async function remoteDefaultBranch(runner: Runner): Promise> { + const result = await runner.git(['ls-remote', '--symref', 'origin', 'HEAD']); + if (result.exitCode !== 0) return { ok: false, reason: failureReason('ls-remote', result, runner.timeoutLabel) }; + const match = /^ref: refs\/heads\/(\S+)\s+HEAD$/m.exec(result.stdout); + return { ok: true, value: match ? match[1] : null }; +} + +export async function hasCommit(runner: Runner, sha: string): Promise { + const result = await runner.git(['cat-file', '-e', `${sha}^{commit}`]); + return result.exitCode === 0; +} + +/** + * Make each commit available locally, fetching only the missing ones, ref-neutrally. + * Returns, per SHA, null when it is available or the reason it is not. + */ +export async function ensureCommits(runner: Runner, shas: readonly string[], version: GitVersion): Promise> { + const result = new Map(); + const missing: string[] = []; + for (const sha of new Set(shas)) { + if (await hasCommit(runner, sha)) result.set(sha, null); + else missing.push(sha); + } + if (missing.length === 0) return result; + + const unavailable = (reason: string): void => { + for (const sha of missing) result.set(sha, `${sha.slice(0, 7)} not available locally (${reason})`); + }; + if (!atLeast(version, REF_NEUTRAL_FETCH_MIN)) { + unavailable(`git ${versionLabel(version)} cannot fetch without moving a ref; needs ${REF_NEUTRAL_FETCH_MIN.major}.${REF_NEUTRAL_FETCH_MIN.minor}`); + return result; + } + const notFull = missing.filter((sha) => !isFullSha(sha)); + if (notFull.length > 0) throw new CheckCommandError(`cannot fetch abbreviated SHA ${notFull[0]}; a full 40-hex SHA is needed`); + + const fetch = await runner.git([ + '-c', 'gc.auto=0', '-c', 'maintenance.auto=false', + 'fetch', '--no-write-fetch-head', '--refmap=', '--no-tags', '--no-recurse-submodules', '--quiet', 'origin', ...missing, + ]); + if (fetch.exitCode !== 0) { + unavailable(failureReason('fetch', fetch, runner.timeoutLabel)); + return result; + } + for (const sha of missing) { + result.set(sha, (await hasCommit(runner, sha)) ? null : `${sha.slice(0, 7)} not available locally (origin did not provide it)`); + } + return result; +} + +/** Resolve a revision to its full commit SHA, or null when it does not name a commit. */ +export async function resolveCommit(runner: Runner, revision: string): Promise { + const result = await runner.git(['rev-parse', '--verify', '--quiet', `${revision}^{commit}`]); + const sha = result.stdout.trim(); + return result.exitCode === 0 && isFullSha(sha) ? sha : null; +} + +export async function mergeBase(runner: Runner, a: string, b: string): Promise { + const result = await runner.git(['merge-base', a, b]); + if (result.exitCode === 1) return null; + if (result.exitCode !== 0) throw new CheckCommandError(`git merge-base ${a} ${b} failed`, result.stderr.trim()); + return result.stdout.trim(); +} + +/** Whether `ancestor` is reachable from `descendant` (a commit is its own ancestor). */ +export async function isAncestor(runner: Runner, ancestor: string, descendant: string): Promise { + const result = await runner.git(['merge-base', '--is-ancestor', ancestor, descendant]); + if (result.exitCode === 0) return true; + if (result.exitCode === 1) return false; + throw new CheckCommandError(`git merge-base --is-ancestor ${ancestor} ${descendant} failed`, result.stderr.trim()); +} + +// ============================================================================= +// Pathspecs +// ============================================================================= + +export interface PathFilter { + /** Globs a path must match one of. An empty list matches nothing. Absent: all paths. */ + include?: readonly string[]; + /** Globs that remove a path. */ + exclude?: readonly string[]; +} + +/** + * The pathspec arguments for a filter, or null when the filter matches nothing (an empty + * include list). `top` magic anchors every pattern at the repository root, whatever the + * directory git runs in. + */ +export function pathspecArgs(filter: PathFilter): string[] | null { + if (filter.include !== undefined && filter.include.length === 0) return null; + const include = filter.include?.map((p) => `:(top,glob)${p}`) ?? []; + const exclude = filter.exclude?.map((p) => `:(top,exclude,glob)${p}`) ?? []; + if (include.length === 0 && exclude.length === 0) return []; + return ['--', ...(include.length > 0 ? include : [':(top)']), ...exclude]; +} + +function splitNul(output: string): string[] { + return output.split('\0').filter((entry) => entry !== ''); +} + +/** Files that differ between two commits, sorted, renames shown as delete plus add. */ +export async function changedFiles(runner: Runner, from: string, to: string, filter: PathFilter = {}): Promise { + const pathspecs = pathspecArgs(filter); + if (pathspecs === null) return []; + const result = await runner.git(['diff', '--no-ext-diff', '--no-textconv', '--name-only', '-z', '--no-renames', from, to, ...pathspecs]); + if (result.exitCode !== 0) throw new CheckCommandError(`git diff ${from} ${to} failed`, result.stderr.trim()); + return splitNul(result.stdout).sort(); +} + +export interface FileStat { + path: string; + additions: number; + deletions: number; + /** Git reported the file as binary (no line counts). */ + binary: boolean; +} + +/** Line counts per changed file between two commits. */ +export async function numstat(runner: Runner, from: string, to: string, filter: PathFilter = {}): Promise { + const pathspecs = pathspecArgs(filter); + if (pathspecs === null) return []; + const result = await runner.git(['diff', '--no-ext-diff', '--no-textconv', '--numstat', '-z', '--no-renames', from, to, ...pathspecs]); + if (result.exitCode !== 0) throw new CheckCommandError(`git diff --numstat ${from} ${to} failed`, result.stderr.trim()); + const stats: FileStat[] = []; + for (const entry of splitNul(result.stdout)) { + const match = /^(\d+|-)\t(\d+|-)\t(.+)$/s.exec(entry); + if (!match) throw new CheckCommandError(`unexpected git diff --numstat output ${JSON.stringify(entry)}`); + const binary = match[1] === '-'; + stats.push({ path: match[3], additions: binary ? 0 : Number(match[1]), deletions: binary ? 0 : Number(match[2]), binary }); + } + return stats.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)); +} diff --git a/packages/codev/src/commands/check/render.ts b/packages/codev/src/commands/check/render.ts new file mode 100644 index 000000000..7faa4e4cd --- /dev/null +++ b/packages/codev/src/commands/check/render.ts @@ -0,0 +1,110 @@ +/** + * Rendering for `codev check` (Spec 1951 § Output and exit codes). + * + * The human form: the verdict line first, naming what needs attention; then the header; then + * one line per check with its status word. `--json` writes exactly one object to stdout. + * Each command supplies its own verdict text, header and labels; the layout lives here. + */ + +import type { Check, ErrorReport, Status } from './report.js'; +import { needsAttention } from './report.js'; + +export const STATUS_WORD: Record = { + ok: 'ok', + attention: 'ATTN', + info: 'info', + 'not-run': 'not run', + off: 'off', + skip: 'skip', +}; + +/** How a check id reads in the human form, where it differs from the id. */ +const DEFAULT_LABELS: Record = { + 'trial-merge': 'trial merge', + 'linked-issue': 'linked issue', + 'to-read': 'to read', + 'on-branch': 'on branch', + 'deploy-run': 'deploy run', + 'merge-checks': 'merge checks', +}; + +export function defaultLabel(id: string): string { + return DEFAULT_LABELS[id] ?? id; +} + +export interface RenderOptions { + /** The label printed for a check; defaults to `defaultLabel(check.id)`. */ + label?: (check: Check) => string; + /** + * A qualifier for a check named on the verdict line, e.g. `running` for + * `checks (running)`. A not-run check is qualified `not run` unless this says otherwise. + */ + qualifier?: (check: Check) => string | null; +} + +/** The names on the verdict line: each check needing attention, with its qualifier. */ +export function attentionNames(checks: readonly Check[], options: RenderOptions = {}): string[] { + const label = options.label ?? ((c: Check) => defaultLabel(c.id)); + return checks.filter(needsAttention).map((c) => { + const qualifier = options.qualifier?.(c) ?? (c.status === 'not-run' ? 'not run' : null); + return qualifier ? `${label(c)} (${qualifier})` : label(c); + }); +} + +const STATUS_WIDTH = Math.max(...Object.values(STATUS_WORD).map((w) => w.length)) + 1; + +/** + * One line per check: ` ATTN attribution 2 lines: …`. A summary's continuation + * lines (separated by `\n`) are indented to the summary column. + */ +export function renderChecks(checks: readonly Check[], options: RenderOptions = {}): string[] { + const label = options.label ?? ((c: Check) => defaultLabel(c.id)); + const labelWidth = Math.max(0, ...checks.map((c) => label(c).length)) + 3; + const indent = ' '.repeat(2 + STATUS_WIDTH + labelWidth); + const lines: string[] = []; + for (const c of checks) { + const [first, ...rest] = c.summary.split('\n'); + lines.push(` ${STATUS_WORD[c.status].padEnd(STATUS_WIDTH)}${label(c).padEnd(labelWidth)}${first}`.trimEnd()); + for (const line of rest) lines.push(`${indent}${line}`.trimEnd()); + } + return lines; +} + +export interface HumanSection { + /** A line printed above the section's checks (e.g. `#1948 merged … → main`). */ + title?: string; + checks: readonly Check[]; +} + +export interface HumanReport { + verdictLine: string; + header: readonly string[]; + sections: readonly HumanSection[]; +} + +export function renderHuman(report: HumanReport, options: RenderOptions = {}): string { + const lines: string[] = [report.verdictLine, '']; + if (report.header.length > 0) lines.push(...report.header); + for (const section of report.sections) { + if (section.title !== undefined) lines.push(section.title); + lines.push(...renderChecks(section.checks, options)); + } + return `${lines.join('\n')}\n`; +} + +/** `--json`: exactly one object. */ +export function renderJson(value: object): string { + return `${JSON.stringify(value, null, 2)}\n`; +} + +/** The human form of an exit-2 failure, for stderr. */ +export function renderErrorHuman(report: ErrorReport): string { + const lines = [`codev check ${report.command}: ${report.error.message}`]; + if (report.error.cause) lines.push(...report.error.cause.split('\n').map((l) => ` ${l}`)); + return `${lines.join('\n')}\n`; +} + +/** The short form of a SHA for the human output. */ +export function short(sha: string): string { + return sha.slice(0, 7); +} diff --git a/packages/codev/src/commands/check/report.ts b/packages/codev/src/commands/check/report.ts new file mode 100644 index 000000000..e11b1bb56 --- /dev/null +++ b/packages/codev/src/commands/check/report.ts @@ -0,0 +1,187 @@ +/** + * The `codev check` report model, schema 1 (Spec 1951 § JSON schema), with the verdict and + * exit-code rules (§ Output and exit codes). + */ + +import type { CommitCheckItem } from '../../lib/forge-contracts.js'; +import { InputError } from './validate.js'; +import { RunnerRefusal } from './allow-list.js'; + +export type Status = 'ok' | 'attention' | 'info' | 'not-run' | 'off' | 'skip'; +export type CommandName = 'pr' | 'deploy' | 'worktree'; +export type Verdict = 'clear' | 'attention'; + +export interface Check { + /** A check id from the lists below. */ + id: string; + status: Status; + /** The one-line text the human form prints (continuation lines separated by `\n`). */ + summary: string; + /** Per-id shape (spec § JSON schema); `{}` when there is nothing more. */ + details: Record; + /** For not-run / off / skip: why, naming the concept, key or git version. */ + reason?: string; +} + +export interface Report { + schema: 1; + command: CommandName; + verdict: Verdict; + generatedAt: string; +} + +export interface PrReport extends Report { + command: 'pr'; + pr: { + number: number; + title: string; + url?: string; + state: string; + draft: boolean | null; + headRef: string; + head: string; + baseRef: string; + baseTip: string; + localBranch: { name: string; sha: string } | null; + }; + checks: Check[]; +} + +export interface DeployReport extends Report { + command: 'deploy'; + deployBranch: string | null; + workflow: string | null; + prs: Array<{ + number: number; + mergedAt: string | null; + mergeCommit: string | null; + baseRef: string | null; + verdict: Verdict; + checks: Check[]; + }>; +} + +export type Removable = 'removable' | 'removable-after-keeping' | 'not-removable'; + +export interface WorktreeReport extends Report { + command: 'worktree'; + removable: Removable; + worktree: { path: string; builderId: string | null; branch: string; baseRef: string; baseTip: string }; + checks: Check[]; +} + +export interface ErrorReport { + schema: 1; + command: CommandName; + error: { message: string; cause?: string }; +} + +export const PR_CHECK_IDS = [ + 'head', 'state', 'forge', 'attribution', 'trial-merge', 'checks', 'watched', 'linked-issue', + 'overlap', 'size', 'to-read', +] as const; +export const DEPLOY_CHECK_IDS = ['merged', 'on-branch', 'deploy-run', 'merge-checks'] as const; +export const WORKTREE_CHECK_IDS = ['uncommitted', 'commits', 'remote', 'pr', 'ignored'] as const; +export const ALL_CHECK_IDS: ReadonlySet = new Set([...PR_CHECK_IDS, ...DEPLOY_CHECK_IDS, ...WORKTREE_CHECK_IDS]); + +/** The command failed and produced no report: exit 2. */ +export class CheckCommandError extends Error { + constructor(message: string, public readonly causeText?: string) { + super(message); + this.name = 'CheckCommandError'; + } +} + +export function check(id: string, status: Status, summary: string, details: Record = {}, reason?: string): Check { + return reason === undefined ? { id, status, summary, details } : { id, status, summary, details, reason }; +} + +/** + * A check that could not run. Always counts as attention. The human line reads + * `not run `, so the summary is the reason alone. + */ +export function notRun(id: string, reason: string, details: Record = {}): Check { + return check(id, 'not-run', reason, details, reason); +} + +/** A check with no configuration. Does not count as attention. */ +export function off(id: string, reason: string): Check { + return check(id, 'off', reason, {}, reason); +} + +/** Replace every check named in `check.skip` with a `skip` entry. */ +export function applySkips(checks: Check[], skip: ReadonlySet): Check[] { + return checks.map((c) => (skip.has(c.id) ? check(c.id, 'skip', 'skipped (check.skip)', {}, 'check.skip') : c)); +} + +export function needsAttention(c: Check): boolean { + return c.status === 'attention' || c.status === 'not-run'; +} + +export function verdictOf(checks: readonly Check[]): Verdict { + return checks.some(needsAttention) ? 'attention' : 'clear'; +} + +export function exitCodeOf(verdict: Verdict): 0 | 1 { + return verdict === 'clear' ? 0 : 1; +} + +// ============================================================================= +// Check runs on one commit +// ============================================================================= + +export interface CommitRuns { + sha: string; + runs: CommitCheckItem[]; + passed: number; + failed: number; + pending: number; +} + +/** Count a commit's check results. Skipped and neutral count as passed. */ +export function summarizeRuns(sha: string, runs: readonly CommitCheckItem[]): CommitRuns { + let passed = 0; + let failed = 0; + let pending = 0; + for (const run of runs) { + if (run.state === 'fail') failed++; + else if (run.state === 'pending') pending++; + else passed++; + } + return { sha, runs: [...runs], passed, failed, pending }; +} + +/** `8 passed`, `7 passed, 1 failed (unit)`, `5 passed, 3 still running`, or `no runs`. */ +export function describeRuns(runs: CommitRuns): string { + if (runs.runs.length === 0) return 'no runs'; + const parts: string[] = []; + if (runs.passed > 0) parts.push(`${runs.passed} passed`); + if (runs.failed > 0) { + const names = runs.runs.filter((r) => r.state === 'fail').map((r) => r.name); + parts.push(`${runs.failed} failed (${truncateList(names, 3)})`); + } + if (runs.pending > 0) parts.push(`${runs.pending} still running`); + return parts.join(', '); +} + +// ============================================================================= +// Errors → exit 2 +// ============================================================================= + +/** The `ErrorReport` for a failure that prevented any report. */ +export function errorReport(command: CommandName, err: unknown): ErrorReport { + if (err instanceof CheckCommandError) { + return { schema: 1, command, error: err.causeText ? { message: err.message, cause: err.causeText } : { message: err.message } }; + } + if (err instanceof InputError || err instanceof RunnerRefusal) { + return { schema: 1, command, error: { message: err.message } }; + } + const message = err instanceof Error ? err.message : String(err); + return { schema: 1, command, error: { message: `unexpected failure: ${message}` } }; +} + +/** `a, b, c, … +N` */ +export function truncateList(items: readonly string[], max: number): string { + if (items.length <= max) return items.join(', '); + return `${items.slice(0, max).join(', ')}, … +${items.length - max}`; +} diff --git a/packages/codev/src/commands/check/roots.ts b/packages/codev/src/commands/check/roots.ts new file mode 100644 index 000000000..e5c7a7cdd --- /dev/null +++ b/packages/codev/src/commands/check/roots.ts @@ -0,0 +1,70 @@ +/** + * Where `codev check` is running, asked of git (Spec 1951 plan § Decisions). + * + * `findWorkspaceRoot()` deliberately returns a builder worktree's OWN root (#407), and + * `.builders/` does not exist there. So the roots come from git: + * - `checkoutRoot` — `git rev-parse --show-toplevel`, the checkout the command runs in; + * - `mainRoot` — the first entry of `git worktree list --porcelain`, which git always + * lists as the main worktree. + * Configuration loads from `mainRoot` and builder ids resolve under it, so the commands + * behave the same from the main checkout and from any builder worktree. + */ + +import { resolve } from 'node:path'; +import { CheckCommandError } from './report.js'; +import type { Runner } from './runner.js'; + +export interface Roots { + checkoutRoot: string; + mainRoot: string; +} + +export interface WorktreeEntry { + path: string; + head: string | null; + /** `refs/heads/…` stripped; null for a detached HEAD. */ + branch: string | null; + bare: boolean; +} + +/** Parse `git worktree list --porcelain`. Paths are resolved to the platform's form. */ +export function parseWorktreeList(output: string): WorktreeEntry[] { + const entries: WorktreeEntry[] = []; + for (const block of output.split(/\n\s*\n/)) { + const lines = block.split('\n').map((l) => l.trim()).filter(Boolean); + const pathLine = lines.find((l) => l.startsWith('worktree ')); + if (!pathLine) continue; + const headLine = lines.find((l) => l.startsWith('HEAD ')); + const branchLine = lines.find((l) => l.startsWith('branch ')); + entries.push({ + path: resolve(pathLine.slice('worktree '.length)), + head: headLine ? headLine.slice('HEAD '.length) : null, + branch: branchLine ? branchLine.slice('branch '.length).replace(/^refs\/heads\//, '') : null, + bare: lines.includes('bare'), + }); + } + return entries; +} + +export async function listWorktrees(runner: Runner): Promise { + const result = await runner.git(['worktree', 'list', '--porcelain']); + if (result.exitCode !== 0) throw new CheckCommandError('could not list worktrees', result.stderr.trim()); + return parseWorktreeList(result.stdout); +} + +/** Find both roots, and require an `origin` remote. Fails with exit 2 otherwise. */ +export async function resolveRoots(runner: Runner): Promise { + const top = await runner.git(['rev-parse', '--show-toplevel']); + if (top.exitCode !== 0) throw new CheckCommandError('not in a git repository', top.stderr.trim()); + const checkoutRoot = resolve(top.stdout.trim()); + + const [main] = await listWorktrees(runner); + if (!main) throw new CheckCommandError('git worktree list returned no worktrees'); + if (main.bare) throw new CheckCommandError(`the main worktree ${main.path} is a bare repository; run codev check from a checkout`); + + const origin = await runner.git(['config', '--get', 'remote.origin.url']); + if (origin.exitCode !== 0 || origin.stdout.trim() === '') { + throw new CheckCommandError('this repository has no "origin" remote; codev check reads base and head from origin'); + } + return { checkoutRoot, mainRoot: main.path }; +} diff --git a/packages/codev/src/commands/check/runner.ts b/packages/codev/src/commands/check/runner.ts new file mode 100644 index 000000000..cc526ec1b --- /dev/null +++ b/packages/codev/src/commands/check/runner.ts @@ -0,0 +1,165 @@ +/** + * The ONLY path to a subprocess in `codev check` (Spec 1951 § Read-only enforcement 1). + * + * `git(argv)` checks the argv against the closed allow-list and refuses — before spawning — + * anything not on it. Git runs from argv, never through a shell. `forge(concept, env)` runs + * only the four read concepts through the existing dispatcher. + * + * Networked git calls (`ls-remote`, `fetch`) and every forge call are bounded by + * `timeoutMs`. The runner also races each bounded call against its own deadline, because a + * killed shell's grandchild can keep a stdio pipe open and delay the child's `close` well + * past the kill; a late result is discarded. `imports.test.ts` keeps every other module in + * this directory away from `child_process` and the forge dispatcher. + */ + +import { spawn as nodeSpawn, type ChildProcess, type SpawnOptions } from 'node:child_process'; +import { executeForgeCommandDetailed, getForgeCommand, loadForgeConfig, type ForgeConfig } from '../../lib/forge.js'; +import { assertConceptAllowed, assertGitArgvAllowed, NETWORK_SUBCOMMANDS } from './allow-list.js'; + +export const DEFAULT_TIMEOUT_MS = 30_000; + +/** Extra time the runner's own deadline allows the dispatcher to report its kill itself. */ +const DEADLINE_GRACE_MS = 1_000; + +export type SpawnFn = (command: string, args: readonly string[], options: SpawnOptions) => ChildProcess; + +export interface GitResult { + stdout: string; + stderr: string; + /** The process exit code; null when it timed out or was killed by a signal. */ + exitCode: number | null; + timedOut: boolean; +} + +export type ForgeOutcome = + | { ok: true; data: unknown } + | { ok: false; kind: 'disabled' | 'failed' | 'timeout' | 'invalid'; reason: string }; + +export interface RunnerOptions { + /** Directory git and the forge concepts run in. */ + cwd: string; + /** Workspace root whose `.codev/config.json` holds the forge configuration. */ + workspaceRoot: string; + timeoutMs?: number; + /** Extra environment for every subprocess (tests put stubs first on PATH). */ + env?: Record; + /** Injected for unit tests; defaults to `child_process.spawn`. */ + spawn?: SpawnFn; +} + +export interface Runner { + readonly cwd: string; + readonly timeoutMs: number; + /** Human form of the time limit, e.g. `30s`. */ + readonly timeoutLabel: string; + /** Run git. `ls-remote` and `fetch` are bounded by `timeoutMs`. */ + git(args: readonly string[]): Promise; + forge(concept: string, env?: Record): Promise; + /** The forge provider name for messages (`github` when none is configured). */ + provider(): string; +} + +export function formatDuration(ms: number): string { + return ms % 1000 === 0 ? `${ms / 1000}s` : `${ms}ms`; +} + +function firstLine(text: string): string { + return text.trim().split('\n')[0] ?? ''; +} + +export function createRunner(options: RunnerOptions): Runner { + const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const timeoutLabel = formatDuration(timeoutMs); + const spawnImpl: SpawnFn = options.spawn ?? ((command, args, spawnOptions) => nodeSpawn(command, args, spawnOptions)); + let forgeConfig: ForgeConfig | null | undefined; + + const loadForge = (): ForgeConfig | null => { + if (forgeConfig === undefined) forgeConfig = loadForgeConfig(options.workspaceRoot); + return forgeConfig; + }; + + const git = async (args: readonly string[]): Promise => { + const bounded = NETWORK_SUBCOMMANDS.has(assertGitArgvAllowed(args)); + return await new Promise((resolve, reject) => { + const child = spawnImpl('git', args, { + cwd: options.cwd, + env: { ...process.env, ...options.env, GIT_TERMINAL_PROMPT: '0' }, + stdio: ['ignore', 'pipe', 'pipe'], + windowsHide: true, + }); + const stdout: Buffer[] = []; + const stderr: Buffer[] = []; + let settled = false; + let timer: NodeJS.Timeout | undefined; + const settle = (result: GitResult | Error): void => { + if (settled) return; + settled = true; + if (timer) clearTimeout(timer); + if (result instanceof Error) reject(result); + else resolve(result); + }; + child.stdout?.on('data', (chunk: Buffer) => stdout.push(chunk)); + child.stderr?.on('data', (chunk: Buffer) => stderr.push(chunk)); + child.on('error', (err) => settle(new Error(`could not run git: ${err.message}`))); + child.on('close', (code) => { + settle({ + stdout: Buffer.concat(stdout).toString('utf-8'), + stderr: Buffer.concat(stderr).toString('utf-8'), + exitCode: code, + timedOut: false, + }); + }); + if (bounded) { + timer = setTimeout(() => { + child.kill('SIGKILL'); + settle({ stdout: '', stderr: '', exitCode: null, timedOut: true }); + }, timeoutMs); + } + }); + }; + + const forge = async (concept: string, env: Record = {}): Promise => { + assertConceptAllowed(concept); + const config = loadForge(); + if (getForgeCommand(concept, config) === null) { + return { ok: false, kind: 'disabled', reason: `${concept} unavailable on ${providerOf(config)}` }; + } + const timedOut: ForgeOutcome = { ok: false, kind: 'timeout', reason: `${concept} timed out after ${timeoutLabel}` }; + let timer: NodeJS.Timeout | undefined; + const deadline = new Promise((resolve) => { + timer = setTimeout(() => resolve(timedOut), timeoutMs + DEADLINE_GRACE_MS); + }); + const call = executeForgeCommandDetailed(concept, { ...options.env, ...env }, { + cwd: options.cwd, + workspaceRoot: options.workspaceRoot, + forgeConfig: config, + timeoutMs, + }).then((result): ForgeOutcome => { + if (result.error) { + if (result.error.timedOut) return timedOut; + const detail = firstLine(result.error.stderr) || firstLine(result.error.message); + return { ok: false, kind: 'failed', reason: `${concept} failed: ${detail}` }; + } + if (result.data === null) return { ok: false, kind: 'invalid', reason: `${concept} returned invalid output` }; + return { ok: true, data: result.data }; + }); + try { + return await Promise.race([call, deadline]); + } finally { + if (timer) clearTimeout(timer); + } + }; + + return { + cwd: options.cwd, + timeoutMs, + timeoutLabel, + git, + forge, + provider: () => providerOf(loadForge()), + }; +} + +function providerOf(config: ForgeConfig | null): string { + return config?.provider ?? 'github'; +} diff --git a/packages/codev/src/commands/check/settings.ts b/packages/codev/src/commands/check/settings.ts new file mode 100644 index 000000000..7b0c71f61 --- /dev/null +++ b/packages/codev/src/commands/check/settings.ts @@ -0,0 +1,139 @@ +/** + * `check.*` configuration (Spec 1951 § What is configurable). + * + * Read from the main workspace root through the usual five-layer loader (arrays replace, + * never concatenate). Every value is validated; a bad one is exit 2 naming the key and the + * file that set it. + */ + +import { findConfigSource, loadConfig } from '../../lib/config.js'; +import { ALL_CHECK_IDS, CheckCommandError } from './report.js'; +import { hasControlChars, isRefName, validateConfigString, InputError } from './validate.js'; + +/** The agent-instruction surface: always worth knowing when it moves. */ +export const DEFAULT_WATCH: readonly string[] = [ + 'CLAUDE.md', + 'AGENTS.md', + '.codev/**', + '.claude/**', + 'codev/roles/**', + 'codev/protocols/**', + 'codev/templates/**', + 'codev/resources/arch-critical.md', + 'codev/resources/lessons-critical.md', +]; + +/** Porch state and review artifacts, thread logs and architect state, and lockfiles. */ +export const DEFAULT_NOT_FOR_READING: readonly string[] = [ + 'codev/projects/**', + 'codev/state/**', + '**/pnpm-lock.yaml', + '**/package-lock.json', + '**/yarn.lock', + '**/Cargo.lock', + '**/poetry.lock', + '**/uv.lock', + '**/go.sum', + '**/Gemfile.lock', + '**/composer.lock', +]; + +export interface AttributionPattern { + source: string; + regex: RegExp; +} + +export interface CheckSettings { + attribution: AttributionPattern[]; + watch: readonly string[]; + flag: readonly string[]; + notForReading: readonly string[]; + deploy: { branch: string | null; workflow: string | null }; + skip: ReadonlySet; +} + +const KNOWN_KEYS = new Set(['attribution', 'watch', 'flag', 'notForReading', 'deploy', 'skip']); +const KNOWN_DEPLOY_KEYS = new Set(['branch', 'workflow']); + +export function loadCheckSettings(mainRoot: string): CheckSettings { + let raw: unknown; + try { + raw = loadConfig(mainRoot).check; + } catch (err) { + throw new CheckCommandError('could not load configuration', err instanceof Error ? err.message : String(err)); + } + return parseCheckSettings(raw, (keyPath) => findConfigSource(mainRoot, keyPath)); +} + +/** Pure validation; `sourceOf` names the file that set a key (for error messages). */ +export function parseCheckSettings(raw: unknown, sourceOf: (keyPath: string[]) => string | null): CheckSettings { + const fail = (keyPath: string[], problem: string): never => { + const source = sourceOf(keyPath); + throw new CheckCommandError(`${keyPath.join('.')} ${problem}${source ? ` (in ${source})` : ''}`); + }; + + if (raw === undefined) raw = {}; + if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) fail(['check'], 'must be an object'); + const section = raw as Record; + for (const key of Object.keys(section)) { + if (!KNOWN_KEYS.has(key)) fail(['check', key], `is not a known key (known: ${[...KNOWN_KEYS].join(', ')})`); + } + + const globs = (key: string, fallback: readonly string[]): readonly string[] => { + const value = section[key]; + if (value === undefined) return fallback; + if (!Array.isArray(value)) fail(['check', key], 'must be an array of glob strings'); + for (const item of value as unknown[]) { + if (typeof item !== 'string' || item.trim() === '' || hasControlChars(item)) { + fail(['check', key], `must contain only non-empty glob strings (got ${JSON.stringify(item)})`); + } + } + return value as string[]; + }; + + const attributionSources = globs('attribution', []); + const attribution = attributionSources.map((source): AttributionPattern => { + try { + return { source, regex: new RegExp(source, 'i') }; + } catch (err) { + return fail(['check', 'attribution'], `pattern ${JSON.stringify(source)} is not a valid regex: ${(err as Error).message}`); + } + }); + + const deploy = { branch: null as string | null, workflow: null as string | null }; + const rawDeploy = section.deploy; + if (rawDeploy !== undefined) { + if (typeof rawDeploy !== 'object' || rawDeploy === null || Array.isArray(rawDeploy)) fail(['check', 'deploy'], 'must be an object'); + const d = rawDeploy as Record; + for (const key of Object.keys(d)) { + if (!KNOWN_DEPLOY_KEYS.has(key)) fail(['check', 'deploy', key], 'is not a known key (known: branch, workflow)'); + } + for (const key of ['branch', 'workflow'] as const) { + if (d[key] === undefined) continue; + const keyPath = ['check', 'deploy', key]; + try { + deploy[key] = validateConfigString(d[key], keyPath.join('.'), sourceOf(keyPath)); + } catch (err) { + if (err instanceof InputError) throw new CheckCommandError(err.message); + throw err; + } + } + if (deploy.branch !== null && !isRefName(deploy.branch)) { + fail(['check', 'deploy', 'branch'], `${JSON.stringify(deploy.branch)} is not a valid branch name`); + } + } + + const skip = globs('skip', []); + for (const id of skip) { + if (!ALL_CHECK_IDS.has(id)) fail(['check', 'skip'], `names an unknown check id ${JSON.stringify(id)}`); + } + + return { + attribution, + watch: globs('watch', DEFAULT_WATCH), + flag: globs('flag', []), + notForReading: globs('notForReading', DEFAULT_NOT_FOR_READING), + deploy, + skip: new Set(skip), + }; +} diff --git a/packages/codev/src/commands/check/validate.ts b/packages/codev/src/commands/check/validate.ts new file mode 100644 index 000000000..b94141947 --- /dev/null +++ b/packages/codev/src/commands/check/validate.ts @@ -0,0 +1,89 @@ +/** + * Input validation for `codev check` (Spec 1951). + * + * Every value that reaches a git argv or a forge concept is validated here before any + * subprocess runs. A violation is an `InputError`, which the commands report as exit 2 + * naming the value (and, for configuration, the key and the file it came from). + */ + +import { isAbsolute } from 'node:path'; + +export class InputError extends Error { + constructor(message: string) { + super(message); + this.name = 'InputError'; + } +} + +const CONTROL_CHARS = /[\u0000-\u001f\u007f]/; +const SHA = /^[0-9a-f]{7,40}$/; +const FULL_SHA = /^[0-9a-f]{40}$/; +const PR_NUMBER = /^[1-9]\d*$/; +const BUILDER_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; + +export function hasControlChars(value: string): boolean { + return CONTROL_CHARS.test(value); +} + +export function isSha(value: string): boolean { + return SHA.test(value); +} + +export function isFullSha(value: string): boolean { + return FULL_SHA.test(value); +} + +/** + * A branch or ref name as git accepts it, restricted to what `codev check` ever passes: + * no leading `-`, no whitespace or control characters, none of `~ ^ : ? * [ \`, no `..`, + * no `@{`, no component beginning with `.`, and not ending in `/`, `.` or `.lock`. + */ +export function isRefName(value: string): boolean { + if (value === '' || value.startsWith('-') || value.startsWith('/')) return false; + if (/[\s~^:?*[\\\u0000-\u001f\u007f]/.test(value)) return false; + if (value.includes('..') || value.includes('@{') || value.includes('//') || value.includes('/.')) return false; + if (value.startsWith('.') || value === '@') return false; + if (value.endsWith('/') || value.endsWith('.') || value.endsWith('.lock')) return false; + return true; +} + +function quote(value: string): string { + return JSON.stringify(value); +} + +export function validatePrNumber(raw: string): number { + if (!PR_NUMBER.test(raw)) throw new InputError(`invalid PR number ${quote(raw)}: expected a positive integer`); + const value = Number(raw); + if (!Number.isSafeInteger(value)) throw new InputError(`invalid PR number ${quote(raw)}: too large`); + return value; +} + +export function validateSha(raw: string): string { + if (!isSha(raw)) throw new InputError(`invalid commit SHA ${quote(raw)}: expected 7–40 hex characters`); + return raw; +} + +export function validateBuilderId(raw: string): string { + if (!BUILDER_ID.test(raw) || raw.includes('..')) { + throw new InputError(`invalid builder id ${quote(raw)}: expected letters, digits, '.', '_' or '-'`); + } + return raw; +} + +/** A directory handed to git as `-C `: absolute, no control characters. */ +export function validateAbsolutePath(raw: string, what: string): string { + if (!isAbsolute(raw) || hasControlChars(raw)) throw new InputError(`invalid ${what} ${quote(raw)}: expected an absolute path`); + return raw; +} + +/** + * A configuration string that is passed to git or to a forge concept. It may not begin + * with `-` (it would read as an option) and may not contain a control character. + */ +export function validateConfigString(value: unknown, key: string, source: string | null): string { + const where = source ? ` (in ${source})` : ''; + if (typeof value !== 'string' || value.trim() === '') throw new InputError(`${key} must be a non-empty string${where}`); + if (value.startsWith('-')) throw new InputError(`${key} ${quote(value)} may not begin with '-'${where}`); + if (hasControlChars(value)) throw new InputError(`${key} ${quote(value)} may not contain control characters${where}`); + return value; +} diff --git a/packages/codev/src/lib/config.ts b/packages/codev/src/lib/config.ts index 41841fa8d..0061ad756 100644 --- a/packages/codev/src/lib/config.ts +++ b/packages/codev/src/lib/config.ts @@ -106,6 +106,29 @@ export interface CodevConfig { claudeAuth?: ClaudeAuthMode; }; forge?: Record & { provider?: string }; + /** + * `codev check` (Spec 1951). Every glob is a git pathspec with `:(glob)` magic; arrays + * replace the defaults. Validated, with the key and file named, by + * `commands/check/settings.ts`. + */ + check?: { + /** Regexes (JavaScript, case-insensitive, per line) for forbidden attribution. Default `[]` (off). */ + attribution?: string[]; + /** Files whose movement is always listed. */ + watch?: string[]; + /** The subset of watched files whose movement needs attention. */ + flag?: string[]; + /** Files excluded from "files a person still has to read". */ + notForReading?: string[]; + deploy?: { + /** Deploy branch for `codev check deploy`; default: each PR's base branch. */ + branch?: string; + /** Workflow whose latest green run on the deploy branch must contain the merge. */ + workflow?: string; + }; + /** Check ids to skip by declaration. */ + skip?: string[]; + }; templates?: { dir?: string; }; From 9081d43678b23fbf6b9d4a8d858a56ad5027c59d Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 15:05:35 -0800 Subject: [PATCH 28/94] [Spec 1951] Thread log: Phase 2 built --- codev/state/spir-1951_thread.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 3d3b0e99e..34e132489 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -74,3 +74,15 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals body "" default; legacy /status paginated. Probe: `gh pr view --json mergeStateStatus,reviewDecision` works without push access (cli/cli). Claude also noted: gitlab pr-view now maps body/baseRefName/headRefName (name in PR body); add the 2 concepts to repo-local `forge` skill tables in Phase 7. + +## Phase 2 — readonly_core (built 66b6921c0) +- Modules: allow-list, runner, validate, roots, settings, report, render, git-facts + helpers + (git-fixture with state snapshot, stub git/gh PATH recorders). 8 test files, 373 tests, all pass locally + (targeted run only; no local full suite per architect). Build passes. +- Choices: runner bounds ls-remote/fetch automatically by subcommand (no caller flag); notRun summary is the + reason alone (the human line already says "not run"); pathspecs use `:(top,glob)` so matching is anchored at + the repo root from any cwd; diff uses --no-renames so a file renamed away from a watched path still shows. +- Ref-neutral fetch by SHA works against a local bare origin (protocol v2); snapshot identical before/after. +- Porch's context-refresh task at the Phase 1→2 boundary was not run: its commands were not captured before the + next `porch next` replaced the task, and a context compaction happened at the same point. +- Waiting: architect's word on main-38 before `porch done` (GitHub run on the pushed head may come first). From 89fc6a2faca08421b0879b7fb5122d99e79fa891 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 15:20:08 -0800 Subject: [PATCH 29/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index d712617cf..01cfe969c 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,10 +39,10 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: [] started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T22:50:10.516Z' +updated_at: '2026-11-23T23:20:08.434Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From 91007fac99ba19b4217ca1847a5e4f56a374e587 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 15:20:20 -0800 Subject: [PATCH 30/94] [Spec 1951] Commit spec and plan iteration-1 rebuttals --- .../1951-plan-iter1-rebuttals.md | 78 +++++++++++++++++++ .../1951-specify-iter1-rebuttals.md | 60 ++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 codev/projects/1951-read-only-pr-check-for-archite/1951-plan-iter1-rebuttals.md create mode 100644 codev/projects/1951-read-only-pr-check-for-archite/1951-specify-iter1-rebuttals.md diff --git a/codev/projects/1951-read-only-pr-check-for-archite/1951-plan-iter1-rebuttals.md b/codev/projects/1951-read-only-pr-check-for-archite/1951-plan-iter1-rebuttals.md new file mode 100644 index 000000000..d0ebc5eea --- /dev/null +++ b/codev/projects/1951-read-only-pr-check-for-archite/1951-plan-iter1-rebuttals.md @@ -0,0 +1,78 @@ +# Plan 1951 — iteration 1 response + +I accepted every point from both reviewers. Each one was checked against the code before I +changed the plan. The revised plan is commit d213afdc3. + +## Codex (REQUEST_CHANGES) + +1. **The `findWorkspaceRoot()` assumption was wrong.** Confirmed: both implementations return a + builder worktree's own root (`lib/skeleton.ts:32`; `agent-farm/utils/config.ts`, #407). + Fix: a new `roots.ts` gets `mainRoot` (the first entry of `git worktree list --porcelain`) + and `checkoutRoot` (`rev-parse --show-toplevel`) from git, through the runner. + - Config loads from `mainRoot`, and builder ids resolve under `/.builders/`. + - New tests run each command from inside a builder worktree (Phases 2, 3 and 6). +2. **The allow-list was not read-only enough.** Fix: it is now a closed grammar per subcommand, + where every flag and positional must be permitted. + - `diff`, `log` and `show` must carry `--no-ext-diff --no-textconv`. + - `cat-file` drops `--textconv` and `--filters`. + - `ls-remote` and `fetch` refuse `--upload-pack`. + - `GIT_TERMINAL_PROMPT=0` is set for every call. + - Refusal tests cover `--output`, `--ext-diff`, `--textconv`, `--filters`, `--upload-pack`, + `--exec` and unknown flags for *every* allowed subcommand. + - The merge-driver trust boundary is stated: drivers come only from the user's own git + config, never from the PR. +3. **The porch-only algorithm was inconsistent.** Fix: Phase 4 now gives an exact algorithm. + 1. Head's result `H` is always kept. + 2. Stop there if head is C, or if head is porch-only and `H` all passed. + 3. Otherwise walk `head^1` down to C, taking the first commit whose runs are non-empty and + all complete. + 4. Failing that, take the first commit with any runs. + - The total is at most 10 lookups. + - The display rules and the `running` / `failed` / `none` qualifiers are tied to it. + - Pending head with green code and pending head with failed code are explicit tests. +4. **`check deploy` did not fetch the run's `headSha`.** Fix: the `headSha` is validated as a SHA, + then `ensureCommits(headSha)` runs. A failed fetch or an old git gives `deploy-run: not run`. + There are acceptance and snapshot tests for it. +5. **The structural test was too shallow.** A transitive scan cannot work as stated, because + `lib/config.ts` transitively imports `platform.js` and `harness.js`, and those modules import + process code even though `loadConfig` spawns nothing. Fix: an **audited-imports** test. + - Every import in `commands/check/` outside `runner.ts` must be on an explicit list kept in + the test: sibling modules, `node:path`, the named read-only `node:fs` functions, + `lib/config.js`, and the pure scaffold and keep-list modules. + - Adding an import means extending the list with a reason. + - At run time, the stub-`PATH` recorders see every `git` and `gh` invocation the process + makes, from any module. + - #1954's `keep-files.ts` spawns git, so its pure definitions move into a new + `keep-list.ts`, which is what `check worktree` imports. + +## Claude (COMMENT) + +1. **`findWorkspaceRoot()`.** Same as Codex 1. The attribution-hit live run now uses a scratch + clone with its own `.codev/config.local.json`. No config of the user's is touched. +2. **The empty-pathspec trap.** Empty include lists short-circuit without running git. An + empty exclude list omits the pathspec. Acceptance tests are in Phases 2 and 6. +3. **`exitOverride()` and `--help`.** `commander.helpDisplayed` and `commander.version` now exit + 0. Acceptance tests cover `codev check --help` and `codev check pr --help`. +4. **The gitlab `pr-view.sh` shape.** It is rewritten to capture before piping (#1645) and to + declare `# forge-executable: glab` (#1455). A test checks that doctor reports `glab`. +5. **Dependency labels.** `worktree` and `deploy` now depend on Phase 3 (`index.ts`). + `summarizeRuns()` moved into `report.ts` (Phase 2), so `deploy` does not import from + `porch-only.ts`. +6. **Phase 3 was too large.** Split as suggested: **Phase 3** holds the merge mechanics (CLI + wiring, `head`, `attribution`, `trial-merge`, `watched`, `overlap`, `size`, `to-read`, and + race detection). **Phase 4** holds the forge-fed checks (`state`, `forge`, `checks` with the + porch-only walk, and `linked-issue`). There are seven phases now. +7. **Concept-count touchpoints.** `forge.test.ts` and `doctor.test.ts` are now named in Phase 1. +8. **`commit-checks` call volume.** The `actions/runs` join is dropped. That leaves two GETs per + commit, and `workflow` is omitted since the contract makes it optional. `statusCheckRollup` + only covers head, while the walk needs earlier commits and the merge commit, so + `commit-checks` stays as one uniform path. +9. **Smaller notes.** + - `-C` paths are validated. + - "Invalid output" is derived from `data === null && error === null`. + - The `HAS_HOOKS` decision and the deliberate `UNSTABLE` double report are stated. + - The diff range is pinned to merge-base → head. + - The Windows dispatch adds `-f filter=commands/check`. + +The "REPOSITORY MOVED" note on both reviews came from my own commit (cbc82c02a, a thread-log +entry) made while the reviews ran. The plan file was unchanged by it. diff --git a/codev/projects/1951-read-only-pr-check-for-archite/1951-specify-iter1-rebuttals.md b/codev/projects/1951-read-only-pr-check-for-archite/1951-specify-iter1-rebuttals.md new file mode 100644 index 000000000..9baff5c75 --- /dev/null +++ b/codev/projects/1951-read-only-pr-check-for-archite/1951-specify-iter1-rebuttals.md @@ -0,0 +1,60 @@ +# Spec 1951 — iteration 1 rebuttal + +Both reviews were accepted in full; nothing was declined. Changes are in commit +`[Spec 1951] Specification with multi-agent review`. + +## Codex (REQUEST_CHANGES) + +1. **Live-base race** — Accepted. The base tip (`ls-remote`) is now re-read together with the + head SHA when every check has finished; either moving makes the verdict attention + ("base|head moved during check; re-run"). New § "The trial merge moves no ref" step 4, + success criterion "Exact head, live base, no race", test scenario 11, risk row. +2. **`check-attr` needs git 2.40 for `--source`** — Accepted (confirmed: `--source` landed in + git 2.40). Rather than raise the floor or re-implement attribute matching, the + "files to read" rule is now globs only (`check.notForReading`); the spec says why + `linguist-generated` is not honored. `check-attr` is removed from the git allow-list. +3. **Worktree verdict semantics inconsistent** — Accepted. The verdict now answers one + question, "would removal lose data?", with each category defined: uncommitted + (non-scaffold) files; unsafe commits (on neither the live base nor the live remote branch, + with the squash/rebase case decided exactly by local tip == merged PR head); keep-list + ignored files. Non-keep-list ignored files are declared regenerable (that is what the keep + list means) and their count is printed. Lifecycle (PR still OPEN, or PR state unavailable) + is a separate `pr` check: attention / not-run, exit 1, without changing the verdict word. +4. **JSON schema not documented** — Accepted. New § "JSON schema": typed report shapes for all + three commands and the exit-2 error object, plus a `details` table for every check id. +5. **Trust boundary overstated** — Accepted. New item 4 in § "Read-only enforcement" states it + precisely: runtime enforcement covers git argv and which concepts are invoked; concept + scripts run through the dispatcher's shell, so shipped scripts are secured by stub-`PATH` + tests and review, and project overrides are trusted. + +## Claude (COMMENT) + +1. **`check-attr --source` / git 2.40** — same as Codex 2; fixed the same way. +2. **"merge-tree is the only write" contradicts the fetch** — Accepted. Reworded: the only + writes are object-store additions (fetched packs and merge-tree's unreachable objects); no + ref, `HEAD`, index, working-tree file or `FETCH_HEAD` changes. +3. **No timeout behavior** — Accepted. Every forge call keeps the dispatcher's 30 s limit, and + `ls-remote`/`fetch` get the same; a timeout is a named `not run` (exit 2 only for the + anchoring `pr-view`). Success criterion, scenario 12b, risk row. +4. **Multi-PR `check deploy` error semantics** — Accepted as suggested: an unreadable PR is a + per-PR `not run` (exit 1) and the rest are still reported; exit 2 is reserved for + repository-, configuration- and usage-level failures. Scenario 15a. +5. **`cleanup.keepIgnored` criterion untickable if #1950 lands second** — Accepted. Assumptions + now state the landing-order rule: if #1950 has not merged, this project defines the key and + never-copy list (with #1950's defaults) in one shared place and #1950 adopts it; the + cross-check test lands with whichever PR is second. Not blocked on #1950. +6. **Missing pre-merge linked-issue check** — Accepted. New `linked-issue` check: closing + keyword present and matching the `builder/-` branch → info; absent → info + with "close # by hand after merge" (partial fixes legitimately lack one); naming a + different issue → attention. +7. **Input validation** — Accepted. New § "Input validation": PR numbers, SHAs, builder ids / + paths and the deploy config strings (no leading `-`, no control characters) are validated + before any subprocess; attribution regexes are trusted config, compiled once, applied per + line. Scenario 28a. +8. **Docs criterion omits `.codex` skill mirrors** — Accepted (verified all four copies exist). + The criterion names `.claude/skills/codev/`, `.codex/skills/codev/` and both skeleton + mirrors, plus hash regeneration. + +"Things I could not check" (the issue body): I diffed the spec against issue #1951's +"What the spec must decide", "What the helpers do" and "Constraints" item by item; every item +is answered in the spec. From 5dea9be3ee25bc64dbc858efb512bbf65ab7b777 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 15:30:10 -0800 Subject: [PATCH 31/94] =?UTF-8?q?[Spec=201951][Phase:=20readonly=5Fcore]?= =?UTF-8?q?=20fix:=20review=20iteration=201=20=E2=80=94=20closed=20stub-gi?= =?UTF-8?q?t=20grammar,=20fetch=20requires=20--no-tags,=20per-worktree=20F?= =?UTF-8?q?ETCH=5FHEAD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - stub git keeps its own closed grammar (symbolic-ref read form only; fetch from origin by full SHA with housekeeping overrides and all ref-neutral flags); new stub-bin self-test over every read form and 25 write forms - allow-list: fetch requires --no-tags --no-recurse-submodules; config --get only - isRefName rejects any component ending in .lock - snapshotRepoState reads FETCH_HEAD from the worktree git dir and the common dir; tag and linked-worktree cases added to the ref-neutral fetch tests - settings errors name what each array holds --- .../1951-readonly_core-iter1-rebuttals.md | 41 ++++++++++ .../check/__tests__/allow-list.test.ts | 66 ++-------------- .../check/__tests__/git-facts.test.ts | 19 ++++- .../check/__tests__/helpers/git-fixture.ts | 7 +- .../check/__tests__/helpers/git-forms.ts | 78 +++++++++++++++++++ .../check/__tests__/helpers/stub-bin.ts | 78 +++++++++++++------ .../commands/check/__tests__/runner.test.ts | 2 +- .../commands/check/__tests__/settings.test.ts | 12 +++ .../commands/check/__tests__/stub-bin.test.ts | 58 ++++++++++++++ .../commands/check/__tests__/validate.test.ts | 2 +- .../codev/src/commands/check/allow-list.ts | 15 ++-- packages/codev/src/commands/check/settings.ts | 12 +-- packages/codev/src/commands/check/validate.ts | 5 +- 13 files changed, 288 insertions(+), 107 deletions(-) create mode 100644 codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter1-rebuttals.md create mode 100644 packages/codev/src/commands/check/__tests__/helpers/git-forms.ts create mode 100644 packages/codev/src/commands/check/__tests__/stub-bin.test.ts diff --git a/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter1-rebuttals.md b/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter1-rebuttals.md new file mode 100644 index 000000000..dfc2ef186 --- /dev/null +++ b/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter1-rebuttals.md @@ -0,0 +1,41 @@ +# Phase 2 (readonly_core): iteration 1 response + +Both reviewers asked for changes. Every point is accepted except one minor point, which Phase 4 covers. All changes are in the commit after `91007fac9`. + +## Codex + +**1. The stub `git` does not keep a closed grammar of its own.** +Accepted. `helpers/stub-bin.ts` now parses the global options and the subcommand itself, independently of the runner's allow-list: +- `-c` accepts only `gc.auto=0` and `maintenance.auto=false`, and only on `fetch`. +- `symbolic-ref` accepts only its read form: one ref, plus `--short`, `-q` and `--quiet`. So `symbolic-ref HEAD refs/heads/x` is now refused. +- `fetch` requires both housekeeping overrides, plus `--no-write-fetch-head`, `--refmap=`, `--no-tags` and `--no-recurse-submodules`. It must fetch from `origin`, and every other positional must be a full 40-hex SHA. +- `config` accepts only `--get `. `worktree` accepts only `list --porcelain`. `merge-tree` must carry `--write-tree`. `status` needs `--no-optional-locks`. +- The file-writing and program-running flags are refused on every subcommand. + +New self-test, `__tests__/stub-bin.test.ts` (POSIX): +- Every read form the commands use passes through to the real git with no violation. +- Every write form, 25 of them, exits 99, is recorded, and leaves the repository snapshot unchanged. +- The `gh` stub answers reads from fixtures and refuses `pr merge`, `pr comment`, `api -X POST` and `api -f`. + +The read forms and the write forms now live in `helpers/git-forms.ts`. The allow-list test and the stub test share those cases, but the two grammars remain separate code. + +**2. `isRefName()` accepts a component ending in `.lock`, such as `foo.lock/bar`.** +Accepted. The check now applies to every path component. There are tests for `foo.lock/bar`, `a/b.lock/c`, and a `check.deploy.branch` of `release.lock/x` (exit 2, key and file named). + +## Claude + +**1. The fetch rule does not require `--no-tags`.** +Accepted. The allow-list now requires `--no-tags` and `--no-recurse-submodules` on `fetch`, and the stub does too. A probe with git 2.50 found that a SHA-only fetch with `--refmap=` does not auto-follow tags, because auto-follow needs a stored ref. So today the risk is theoretical. Requiring the flags makes the guarantee independent of that git behaviour. + +**2. No test exercises the tag case.** +Accepted, in two ways: +- The ref-neutral fetch test now pushes a lightweight tag and an annotated tag on origin, both pointing at the fetched commit. The snapshot must still be identical afterwards, so no `refs/tags/*` may appear. +- Because the runner refuses a fetch without `--no-tags`, deleting the flag from `ensureCommits` now fails that test. + +**3. `snapshotRepoState` reads `FETCH_HEAD` only under `--git-common-dir`.** +Accepted. The snapshot now reads `FETCH_HEAD` from both the worktree's git dir and the common dir. A new test runs `ensureCommits` from a linked worktree and requires that worktree's snapshot, both `FETCH_HEAD` locations included, to be identical before and after. + +**4. Minor points.** +- *The error wording "glob strings" is reused for `attribution` and `skip`.* Fixed. The messages now name what each array holds: `regex strings`, `check ids` or `glob strings`. There is a test. +- *`config --get-regexp` is permitted, but its positional pattern rejects regex metacharacters.* Fixed by removing `--get-regexp`. No command uses it, and the list is meant to be exactly what the commands use. `config` now requires `--get`. +- *`check.flag` is not validated against `check.watch`.* No change in this phase. The spec defines `flag` as "a subset of what you watch". Globs cannot be checked statically for containment, so Phase 4 applies the meaning instead: a flagged file is a watched file, one that `watch` matched, that also matches `flag`. A flag glob outside the watch list therefore has no effect. `CheckSettings.flag` now documents this, and Phase 4's tests will cover it. diff --git a/packages/codev/src/commands/check/__tests__/allow-list.test.ts b/packages/codev/src/commands/check/__tests__/allow-list.test.ts index c402ca245..e68fb9b3d 100644 --- a/packages/codev/src/commands/check/__tests__/allow-list.test.ts +++ b/packages/codev/src/commands/check/__tests__/allow-list.test.ts @@ -4,70 +4,16 @@ import { describe, expect, it } from 'vitest'; import { assertConceptAllowed, assertGitArgvAllowed, RunnerRefusal } from '../allow-list.js'; +import { allowedForms, argvOf as argv, FETCH_GLOBALS, SHA, SHA2, WRITE_FORMS } from './helpers/git-forms.js'; -const SHA = 'a'.repeat(40); -const SHA2 = 'b'.repeat(40); const ABS = process.platform === 'win32' ? 'C:\\repo' : '/repo'; +const ALLOWED = allowedForms(ABS); -interface Form { - globals: string[]; - sub: string; - rest: string[]; -} - -const form = (globals: string[], sub: string, ...rest: string[]): Form => ({ globals, sub, rest }); -const argv = (f: Form): string[] => [...f.globals, f.sub, ...f.rest]; - -/** Every form the commands use. Each must pass. */ -const ALLOWED: Form[] = [ - form([], 'version'), - form([], 'rev-parse', '--show-toplevel'), - form([], 'rev-parse', '--verify', '--quiet', `${SHA}^{commit}`), - form([], 'rev-list', '--first-parent', '--max-count=10', SHA), - form([], 'rev-list', '--count', `${SHA}..${SHA2}`), - form([], 'merge-base', SHA, SHA2), - form([], 'merge-base', '--is-ancestor', SHA, 'refs/remotes/origin/main'), - form([], 'log', '--no-ext-diff', '--no-textconv', '-z', '--format=%H%x00%B', `${SHA}..${SHA2}`), - form([], 'show', '--no-ext-diff', '--no-textconv', '-s', '--format=%B', SHA), - form([], 'diff', '--no-ext-diff', '--no-textconv', '--name-only', '-z', '--no-renames', SHA, SHA2, '--', ':(top)', ':(top,exclude,glob)**/x'), - form([], 'diff', '--no-ext-diff', '--no-textconv', '--numstat', '-z', SHA, SHA2), - form([], 'diff-tree', '--no-commit-id', '--name-only', '-r', '-z', SHA), - form([], 'cat-file', '-e', `${SHA}^{commit}`), - form([], 'cat-file', '-t', SHA), - form([], 'for-each-ref', '--format=%(refname)', 'refs/heads/main'), - form(['-C', ABS], 'ls-files', '--others', '--ignored', '--exclude-standard', '-z', '--', ':(top,glob)codev/**'), - form([], 'ls-remote', 'origin', 'refs/heads/main'), - form([], 'ls-remote', '--symref', 'origin', 'HEAD'), - form([], 'worktree', 'list', '--porcelain'), - form([], 'config', '--get', 'remote.origin.url'), - form([], 'symbolic-ref', '--short', '-q', 'HEAD'), - form(['-C', ABS, '--no-optional-locks'], 'status', '--porcelain=v1', '-z', '--untracked-files=all'), - form([], 'merge-tree', '--write-tree', '--name-only', '--no-messages', '-z', SHA, SHA2), - form(['-c', 'gc.auto=0', '-c', 'maintenance.auto=false'], 'fetch', '--no-write-fetch-head', '--refmap=', '--no-tags', '--quiet', 'origin', SHA, SHA2), -]; - -const FETCH_GLOBALS = ['-c', 'gc.auto=0', '-c', 'maintenance.auto=false']; - -/** Named refusals from the plan's acceptance table. */ +/** Refusals beyond the shared write forms: grammar edges. */ const REFUSED: Array<[string, string[]]> = [ - ['update-ref', ['update-ref', 'refs/heads/x', SHA]], - ['push', ['push', 'origin', 'main']], - ['branch -D', ['branch', '-D', 'x']], - ['fetch origin main', [...FETCH_GLOBALS, 'fetch', '--no-write-fetch-head', '--refmap=', 'origin', 'main']], - ['fetch without --refmap=', [...FETCH_GLOBALS, 'fetch', '--no-write-fetch-head', 'origin', SHA]], - ['fetch without --no-write-fetch-head', [...FETCH_GLOBALS, 'fetch', '--refmap=', 'origin', SHA]], - ['fetch without the housekeeping overrides', ['fetch', '--no-write-fetch-head', '--refmap=', 'origin', SHA]], - ['fetch from another remote', [...FETCH_GLOBALS, 'fetch', '--no-write-fetch-head', '--refmap=', 'upstream', SHA]], - ['fetch an abbreviated SHA', [...FETCH_GLOBALS, 'fetch', '--no-write-fetch-head', '--refmap=', 'origin', 'abc1234']], - ['merge-tree without --write-tree', ['merge-tree', SHA, SHA2]], - ['status without --no-optional-locks', ['status', '--porcelain=v1']], - ['config --unset', ['config', '--unset', 'x.y']], - ['config set', ['config', 'x.y', 'z']], - ['config read without --get', ['config', 'remote.origin.url']], - ['symbolic-ref HEAD refs/heads/x', ['symbolic-ref', 'HEAD', 'refs/heads/x']], - ['worktree remove', ['worktree', 'remove', '/x']], - ['worktree list without --porcelain', ['worktree', 'list']], - ['-c core.hooksPath=x log', ['-c', 'core.hooksPath=x', 'log', '--no-ext-diff', '--no-textconv', SHA]], + ...WRITE_FORMS, + ['fetch without --no-recurse-submodules', [...FETCH_GLOBALS, 'fetch', '--no-write-fetch-head', '--refmap=', '--no-tags', 'origin', SHA]], + ['config --get-regexp', ['config', '--get-regexp', 'remote']], ['-c on a subcommand other than fetch', ['-c', 'gc.auto=0', 'log', '--no-ext-diff', '--no-textconv', SHA]], ['--exec-path', ['--exec-path=/x', 'version']], ['--git-dir', ['--git-dir=/x', 'version']], diff --git a/packages/codev/src/commands/check/__tests__/git-facts.test.ts b/packages/codev/src/commands/check/__tests__/git-facts.test.ts index c74f58e16..abc9c09af 100644 --- a/packages/codev/src/commands/check/__tests__/git-facts.test.ts +++ b/packages/codev/src/commands/check/__tests__/git-facts.test.ts @@ -112,11 +112,15 @@ describe('Spec 1951 — live tips', () => { }); describe('Spec 1951 — ensureCommits (the ref-neutral fetch)', () => { - it('fetches a missing commit and moves no ref, writes no FETCH_HEAD, leaves index and status alone', async () => { + it('fetches a missing commit and moves no ref or tag, writes no FETCH_HEAD, leaves index and status alone', async () => { const sha = pushFromElsewhere('feature', { 'feature.txt': 'feature\n' }); + const other = path.join(fx.root, 'other'); + fx.git(other, 'tag', 'v1', sha); + fx.git(other, 'tag', '-a', 'v1-annotated', '-m', 'annotated', sha); + fx.git(other, 'push', '-q', 'origin', 'v1', 'v1-annotated'); expect(await hasCommit(runner, sha)).toBe(false); const before = snapshotRepoState(fx, fx.main); - expect(before.fetchHead).toBeNull(); + expect(before.fetchHead).toEqual({ worktree: null, common: null }); const result = await ensureCommits(runner, [sha], version); @@ -155,6 +159,17 @@ describe('Spec 1951 — ensureCommits (the ref-neutral fetch)', () => { }); }); +describe('Spec 1951 — ensureCommits from a linked worktree', () => { + it('writes no FETCH_HEAD in the worktree or the common directory', async () => { + const worktree = fx.addWorktree('spir-1', 'builder/spir-1'); + const sha = pushFromElsewhere('feature', { 'w.txt': 'w\n' }); + const before = snapshotRepoState(fx, worktree); + const inWorktree = runnerIn(worktree); + expect((await ensureCommits(inWorktree, [sha], version)).get(sha)).toBeNull(); + expect(snapshotRepoState(fx, worktree)).toEqual(before); + }); +}); + describe('Spec 1951 — ancestry', () => { it('finds the merge base and ancestry', async () => { const base = fx.git(fx.main, 'rev-parse', 'HEAD').trim(); diff --git a/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts b/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts index 7d39f0a36..a02d3c970 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts @@ -107,7 +107,8 @@ export interface RepoState { refs: string; head: string; index: string; - fetchHead: string | null; + /** FETCH_HEAD is per-worktree; both locations are read, so a linked worktree is covered. */ + fetchHead: { worktree: string | null; common: string | null }; status: string; } @@ -116,12 +117,12 @@ export function snapshotRepoState(fixture: Fixture, repo: string): RepoState { const gitDir = path.resolve(repo, fixture.git(repo, 'rev-parse', '--git-dir').trim()); const commonDir = path.resolve(repo, fixture.git(repo, 'rev-parse', '--git-common-dir').trim()); const indexFile = path.join(gitDir, 'index'); - const fetchHead = path.join(commonDir, 'FETCH_HEAD'); + const read = (file: string): string | null => (fs.existsSync(file) ? fs.readFileSync(file, 'utf-8') : null); return { refs: fixture.git(repo, 'for-each-ref', '--format=%(refname) %(objectname)'), head: fs.readFileSync(path.join(gitDir, 'HEAD'), 'utf-8'), index: fs.existsSync(indexFile) ? fs.readFileSync(indexFile).toString('base64') : '', - fetchHead: fs.existsSync(fetchHead) ? fs.readFileSync(fetchHead, 'utf-8') : null, + fetchHead: { worktree: read(path.join(gitDir, 'FETCH_HEAD')), common: read(path.join(commonDir, 'FETCH_HEAD')) }, status: fixture.git(repo, '--no-optional-locks', 'status', '--porcelain=v1'), }; } diff --git a/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts b/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts new file mode 100644 index 000000000..c3191d90b --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts @@ -0,0 +1,78 @@ +/** + * Git invocations shared by the allow-list test and the stub-git self-test (Spec 1951): + * every read form `codev check` uses, and the write forms both layers must refuse. + */ + +export const SHA = 'a'.repeat(40); +export const SHA2 = 'b'.repeat(40); + +export interface GitForm { + globals: string[]; + sub: string; + rest: string[]; +} + +export const form = (globals: string[], sub: string, ...rest: string[]): GitForm => ({ globals, sub, rest }); +export const argvOf = (f: GitForm): string[] => [...f.globals, f.sub, ...f.rest]; + +export const FETCH_GLOBALS = ['-c', 'gc.auto=0', '-c', 'maintenance.auto=false']; +const FETCH_FLAGS = ['--no-write-fetch-head', '--refmap=', '--no-tags', '--no-recurse-submodules']; + +/** Every read form the commands use; `dir` is an absolute directory for `-C`. */ +export function allowedForms(dir: string): GitForm[] { + return [ + form([], 'version'), + form([], 'rev-parse', '--show-toplevel'), + form([], 'rev-parse', '--verify', '--quiet', `${SHA}^{commit}`), + form([], 'rev-list', '--first-parent', '--max-count=10', SHA), + form([], 'rev-list', '--count', `${SHA}..${SHA2}`), + form([], 'merge-base', SHA, SHA2), + form([], 'merge-base', '--is-ancestor', SHA, 'refs/remotes/origin/main'), + form([], 'log', '--no-ext-diff', '--no-textconv', '-z', '--format=%H%x00%B', `${SHA}..${SHA2}`), + form([], 'show', '--no-ext-diff', '--no-textconv', '-s', '--format=%B', SHA), + form([], 'diff', '--no-ext-diff', '--no-textconv', '--name-only', '-z', '--no-renames', SHA, SHA2, '--', ':(top)', ':(top,exclude,glob)**/x'), + form([], 'diff', '--no-ext-diff', '--no-textconv', '--numstat', '-z', SHA, SHA2), + form([], 'diff-tree', '--no-commit-id', '--name-only', '-r', '-z', SHA), + form([], 'cat-file', '-e', `${SHA}^{commit}`), + form([], 'cat-file', '-t', SHA), + form([], 'for-each-ref', '--format=%(refname)', 'refs/heads/main'), + form(['-C', dir], 'ls-files', '--others', '--ignored', '--exclude-standard', '-z', '--', ':(top,glob)codev/**'), + form([], 'ls-remote', 'origin', 'refs/heads/main'), + form([], 'ls-remote', '--symref', 'origin', 'HEAD'), + form([], 'worktree', 'list', '--porcelain'), + form([], 'config', '--get', 'remote.origin.url'), + form([], 'symbolic-ref', '--short', '-q', 'HEAD'), + form(['-C', dir, '--no-optional-locks'], 'status', '--porcelain=v1', '-z', '--untracked-files=all'), + form([], 'merge-tree', '--write-tree', '--name-only', '--no-messages', '-z', SHA, SHA2), + form(FETCH_GLOBALS, 'fetch', ...FETCH_FLAGS, '--quiet', 'origin', SHA, SHA2), + ]; +} + +/** Invocations that write a ref, the index, the work tree, config or FETCH_HEAD, or run a program. */ +export const WRITE_FORMS: Array<[string, string[]]> = [ + ['update-ref', ['update-ref', 'refs/heads/x', SHA]], + ['push', ['push', 'origin', 'main']], + ['branch -D', ['branch', '-D', 'x']], + ['tag', ['tag', 'x']], + ['reset --hard', ['reset', '--hard']], + ['checkout', ['checkout', '--', '.']], + ['gc', ['gc']], + ['fetch origin main', [...FETCH_GLOBALS, 'fetch', ...FETCH_FLAGS, 'origin', 'main']], + ['fetch without --refmap=', [...FETCH_GLOBALS, 'fetch', '--no-write-fetch-head', '--no-tags', '--no-recurse-submodules', 'origin', SHA]], + ['fetch without --no-write-fetch-head', [...FETCH_GLOBALS, 'fetch', '--refmap=', '--no-tags', '--no-recurse-submodules', 'origin', SHA]], + ['fetch without --no-tags', [...FETCH_GLOBALS, 'fetch', '--no-write-fetch-head', '--refmap=', '--no-recurse-submodules', 'origin', SHA]], + ['fetch without the housekeeping overrides', ['fetch', ...FETCH_FLAGS, 'origin', SHA]], + ['fetch from another remote', [...FETCH_GLOBALS, 'fetch', ...FETCH_FLAGS, 'upstream', SHA]], + ['fetch an abbreviated SHA', [...FETCH_GLOBALS, 'fetch', ...FETCH_FLAGS, 'origin', 'abc1234']], + ['merge-tree without --write-tree', ['merge-tree', SHA, SHA2]], + ['status without --no-optional-locks', ['status', '--porcelain=v1']], + ['config --unset', ['config', '--unset', 'x.y']], + ['config set', ['config', 'x.y', 'z']], + ['config read without --get', ['config', 'remote.origin.url']], + ['symbolic-ref HEAD refs/heads/x', ['symbolic-ref', 'HEAD', 'refs/heads/x']], + ['worktree remove', ['worktree', 'remove', '/x']], + ['worktree list without --porcelain', ['worktree', 'list']], + ['-c core.hooksPath=x log', ['-c', 'core.hooksPath=x', 'log', '--no-ext-diff', '--no-textconv', SHA]], + ['log --output=x', ['log', '--no-ext-diff', '--no-textconv', '--output=x', SHA]], + ['ls-remote --upload-pack=x', ['ls-remote', '--upload-pack=x', 'origin']], +]; diff --git a/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts b/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts index df03ea6b5..8bfb94581 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts @@ -20,32 +20,62 @@ import * as path from 'node:path'; import { REAL_GIT } from './git-fixture.js'; const GIT_STUB = `#!/bin/sh -# Stub git (Spec 1951 tests): record, check the read-only list, exec the real git. +# Stub git (Spec 1951 tests): record, check a read-only grammar of its own, exec the real git. printf '%s\\n' "$*" >> "$STUB_DIR/git-calls" -violation() { printf 'git %s :: %s\\n' "$*" "$REASON" >> "$STUB_DIR/violations"; echo "stub git refused: $REASON" >&2; exit 99; } -sub=""; skip=0; for a in "$@"; do - if [ "$skip" = 1 ]; then skip=0; continue; fi - case "$a" in - -C|-c) skip=1 ;; - --no-optional-locks) ;; - -*) REASON="global option $a"; violation "$@" ;; - *) sub="$a"; break ;; +ALL="$*" +violation() { printf 'git %s :: %s\\n' "$ALL" "$1" >> "$STUB_DIR/violations"; echo "stub git refused: $1" >&2; exit 99; } +has() { want="$1"; shift; for a in "$@"; do [ "$a" = "$want" ] && return 0; done; return 1; } +is_sha40() { case "$1" in ''|*[!0-9a-f]*) return 1 ;; esac; [ "\${#1}" -eq 40 ]; } +check() { + gcauto=0; maint=0; locks=0 + while [ $# -gt 0 ]; do + case "$1" in + -C) case "$2" in /*) ;; *) violation "-C needs an absolute path" ;; esac; shift 2 ;; + -c) case "$2" in gc.auto=0) gcauto=1 ;; maintenance.auto=false) maint=1 ;; *) violation "-c $2" ;; esac; shift 2 ;; + --no-optional-locks) locks=1; shift ;; + -*) violation "global option $1" ;; + *) break ;; + esac + done + sub="$1"; [ $# -gt 0 ] && shift + for a in "$@"; do + case "$a" in + --) break ;; + --output*|--ext-diff|--textconv|--filters|--upload-pack*|--exec*) violation "flag $a" ;; + esac + done + if [ "$sub" != fetch ] && [ $((gcauto + maint)) -gt 0 ]; then violation "-c outside fetch"; fi + case "$sub" in + version|rev-parse|rev-list|merge-base|log|show|diff|diff-tree|cat-file|for-each-ref|ls-files|ls-remote) ;; + merge-tree) has --write-tree "$@" || violation "merge-tree without --write-tree" ;; + status) [ "$locks" = 1 ] || violation "status without --no-optional-locks" ;; + worktree) [ "$*" = "list --porcelain" ] || [ "$*" = "list --porcelain -z" ] || violation "worktree $*" ;; + config) { [ $# -eq 2 ] && [ "$1" = --get ]; } || violation "config other than --get " ;; + symbolic-ref) + refs=0 + for a in "$@"; do + case "$a" in --short|-q|--quiet) ;; -*) violation "symbolic-ref $a" ;; *) refs=$((refs + 1)) ;; esac + done + [ "$refs" -eq 1 ] || violation "symbolic-ref write form" ;; + fetch) + [ "$gcauto" = 1 ] && [ "$maint" = 1 ] || violation "fetch without the housekeeping overrides" + for flag in --no-write-fetch-head --refmap= --no-tags --no-recurse-submodules; do + has "$flag" "$@" || violation "fetch without $flag" + done + remote=""; shas=0 + for a in "$@"; do + case "$a" in + --no-write-fetch-head|--refmap=|--no-tags|--no-recurse-submodules|--quiet) ;; + -*) violation "fetch $a" ;; + *) if [ -z "$remote" ]; then remote="$a"; elif is_sha40 "$a"; then shas=$((shas + 1)); else violation "fetch of $a, not a full SHA"; fi ;; + esac + done + [ "$remote" = origin ] || violation "fetch from $remote, not origin" + [ "$shas" -gt 0 ] || violation "fetch with no SHA" ;; + *) violation "subcommand $sub" ;; esac -done -case "$sub" in - version|rev-parse|rev-list|merge-base|log|show|diff|diff-tree|cat-file|for-each-ref|ls-files|ls-remote|merge-tree) ;; - worktree) case "$*" in *"worktree list --porcelain"*) ;; *) REASON="worktree other than list"; violation "$@" ;; esac ;; - config) case "$*" in *"config --get"*) ;; *) REASON="config without --get"; violation "$@" ;; esac ;; - status) case "$*" in *--no-optional-locks*) ;; *) REASON="status without --no-optional-locks"; violation "$@" ;; esac ;; - symbolic-ref) [ "$#" -le 6 ] || { REASON="symbolic-ref write form"; violation "$@"; } ;; - fetch) case "$*" in *--no-write-fetch-head*--refmap=*) ;; *) REASON="fetch that may move a ref"; violation "$@" ;; esac ;; - *) REASON="subcommand $sub"; violation "$@" ;; -esac -for a in "$@"; do - case "$a" in - --output*|--ext-diff|--textconv|--filters|--upload-pack*|--exec*) REASON="flag $a"; violation "$@" ;; - esac -done +} +check "$@" exec "$REAL_GIT" "$@" `; diff --git a/packages/codev/src/commands/check/__tests__/runner.test.ts b/packages/codev/src/commands/check/__tests__/runner.test.ts index b1b9c22de..3cea2f658 100644 --- a/packages/codev/src/commands/check/__tests__/runner.test.ts +++ b/packages/codev/src/commands/check/__tests__/runner.test.ts @@ -79,7 +79,7 @@ describe('Spec 1951 — runner: git', () => { it('bounds fetch by timeoutMs', async () => { const child = hangingChild(); const runner = createRunner({ cwd: workspace, workspaceRoot: workspace, spawn: () => child, timeoutMs: 50 }); - const result = await runner.git(['-c', 'gc.auto=0', '-c', 'maintenance.auto=false', 'fetch', '--no-write-fetch-head', '--refmap=', 'origin', 'a'.repeat(40)]); + const result = await runner.git(['-c', 'gc.auto=0', '-c', 'maintenance.auto=false', 'fetch', '--no-write-fetch-head', '--refmap=', '--no-tags', '--no-recurse-submodules', 'origin', 'a'.repeat(40)]); expect(result.timedOut).toBe(true); }); diff --git a/packages/codev/src/commands/check/__tests__/settings.test.ts b/packages/codev/src/commands/check/__tests__/settings.test.ts index 8ae4aea9a..652a9935f 100644 --- a/packages/codev/src/commands/check/__tests__/settings.test.ts +++ b/packages/codev/src/commands/check/__tests__/settings.test.ts @@ -97,6 +97,18 @@ describe('Spec 1951 — check settings', () => { expect(message).toContain(`(in ${projectFile})`); }); + it('names what each array must hold', () => { + writeProject({ attribution: 'claude' }); + expect(loadError().message).toBe(`check.attribution must be an array of regex strings (in ${projectFile})`); + writeProject({ skip: [3] }); + expect(loadError().message).toBe(`check.skip must contain only non-empty check ids (got 3) (in ${projectFile})`); + }); + + it('refuses a deploy branch with a component ending in .lock', () => { + writeProject({ deploy: { branch: 'release.lock/x' } }); + expect(loadError().message).toContain('check.deploy.branch "release.lock/x" is not a valid branch name'); + }); + it('refuses an unknown check.skip id', () => { writeProject({ skip: ['size', 'colour'] }); expect(loadError().message).toBe(`check.skip names an unknown check id "colour" (in ${projectFile})`); diff --git a/packages/codev/src/commands/check/__tests__/stub-bin.test.ts b/packages/codev/src/commands/check/__tests__/stub-bin.test.ts new file mode 100644 index 000000000..42d99f433 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/stub-bin.test.ts @@ -0,0 +1,58 @@ +/** + * Spec 1951 — the stub `git` and `gh` are an independent second layer: they must let every + * read form through to the real program and refuse every write form, recording it. + */ + +import { spawnSync } from 'node:child_process'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { allowedForms, argvOf, WRITE_FORMS } from './helpers/git-forms.js'; +import { createStubBin, type StubBin } from './helpers/stub-bin.js'; + +let fx: Fixture; +let stubs: StubBin; + +function run(command: 'git' | 'gh', args: readonly string[]): number | null { + const result = spawnSync(path.join(stubs.dir, command), args, { cwd: fx.main, env: { ...process.env, ...fx.env, ...stubs.env } }); + return result.status; +} + +beforeEach(() => { + fx = createFixture(); + stubs = createStubBin(path.join(fx.root, 'stub-bin')); +}); + +afterEach(() => { + fx.cleanup(); +}); + +describe.skipIf(process.platform === 'win32')('Spec 1951 — stub git and gh', () => { + it('passes every read form through to the real git, recording each', () => { + const forms = allowedForms(fx.main); + for (const f of forms) expect(run('git', argvOf(f)), argvOf(f).join(' ')).not.toBe(99); + expect(stubs.violations()).toEqual([]); + expect(stubs.gitCalls()).toHaveLength(forms.length); + }); + + it.each(WRITE_FORMS)('refuses %s, records it, and leaves the repository untouched', (_name, args) => { + const before = snapshotRepoState(fx, fx.main); + expect(run('git', args)).toBe(99); + expect(stubs.violations()).toHaveLength(1); + expect(snapshotRepoState(fx, fx.main)).toEqual(before); + }); + + it('answers gh read calls from fixtures and refuses writes', () => { + stubs.answer(['pr', 'view', '7', '--json', 'title'], '{"title":"t"}\n'); + const view = spawnSync(path.join(stubs.dir, 'gh'), ['pr', 'view', '7', '--json', 'title'], { env: { ...process.env, ...stubs.env }, encoding: 'utf-8' }); + expect(view.status).toBe(0); + expect(view.stdout).toBe('{"title":"t"}\n'); + expect(run('gh', ['pr', 'view', '8'])).toBe(98); + expect(stubs.violations()).toEqual([]); + + for (const args of [['pr', 'merge', '7'], ['pr', 'comment', '7', '-b', 'x'], ['api', '-X', 'POST', 'repos/o/r/issues'], ['api', 'repos/o/r/issues', '-f', 'title=x']]) { + expect(run('gh', args), args.join(' ')).toBe(99); + } + expect(stubs.violations()).toHaveLength(4); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/validate.test.ts b/packages/codev/src/commands/check/__tests__/validate.test.ts index 8819d3b95..98d6cf057 100644 --- a/packages/codev/src/commands/check/__tests__/validate.test.ts +++ b/packages/codev/src/commands/check/__tests__/validate.test.ts @@ -64,7 +64,7 @@ describe('Spec 1951 — validation', () => { expect(isRefName(ref)).toBe(true); }); - it.each(['', '-x', '/x', 'x/', 'x.', 'x.lock', 'a..b', 'a@{1}', 'a b', 'a~1', 'a^', 'a:b', 'a?', 'a*', 'a[', 'a\\b', '.x', 'a/.b', 'a//b', '@'])( + it.each(['', '-x', '/x', 'x/', 'x.', 'x.lock', 'a..b', 'a@{1}', 'a b', 'a~1', 'a^', 'a:b', 'a?', 'a*', 'a[', 'a\\b', '.x', 'a/.b', 'a//b', '@', 'foo.lock/bar', 'a/b.lock/c'])( 'refuses ref name %j', (ref) => { expect(isRefName(ref)).toBe(false); diff --git a/packages/codev/src/commands/check/allow-list.ts b/packages/codev/src/commands/check/allow-list.ts index adddbaea9..ceecb3e68 100644 --- a/packages/codev/src/commands/check/allow-list.ts +++ b/packages/codev/src/commands/check/allow-list.ts @@ -7,7 +7,7 @@ * `--no-ext-diff --no-textconv`, so no repository-configured diff program runs; flags that * write files (`--output`) or run programs (`--upload-pack`, `--exec`, `--textconv`, * `--filters`) are never permitted. `fetch` is allowed only in its ref-neutral form, which - * adds objects and moves no ref and writes no FETCH_HEAD. + * adds objects and moves no ref (no tags, no submodules) and writes no FETCH_HEAD. * * Forge concepts are allowed by name: only the four read concepts. */ @@ -47,8 +47,6 @@ interface SubcommandRule { valueFlags?: readonly string[]; /** Flags that must be present. */ required?: readonly string[]; - /** Exactly one of these flags must be present. */ - oneOf?: readonly string[]; /** Whether `--` followed by pathspecs is permitted. */ pathspecs?: boolean; /** Validates the positional arguments; returns a reason to refuse, or null. */ @@ -154,8 +152,8 @@ const RULES: Record = { positionals: exactly(1, (v) => v === 'list', 'worktree subcommand (only "list")'), }, config: { - flags: ['--get', '--get-regexp'], - oneOf: ['--get', '--get-regexp'], + flags: ['--get'], + required: ['--get'], positionals: exactly(1, (v) => /^[A-Za-z0-9._-]+$/.test(v), 'config key'), }, 'symbolic-ref': { @@ -174,7 +172,9 @@ const RULES: Record = { }, fetch: { flags: ['--no-write-fetch-head', '--refmap=', '--no-tags', '--no-recurse-submodules', '--quiet'], - required: ['--no-write-fetch-head', '--refmap='], + // --refmap= stores no remote-tracking ref, but tag auto-following is separate: without + // --no-tags a fetch can still create refs/tags/*. + required: ['--no-write-fetch-head', '--refmap=', '--no-tags', '--no-recurse-submodules'], positionals: (p) => { if (p[0] !== 'origin') return 'fetch may only fetch from origin'; if (p.length < 2) return 'fetch needs at least one commit SHA'; @@ -256,9 +256,6 @@ export function assertGitArgvAllowed(argv: readonly string[]): string { for (const required of rule.required ?? []) { if (!seen.has(required)) refuse(`git ${subcommand} must carry ${required}`); } - if (rule.oneOf && rule.oneOf.filter((flag) => seen.has(flag)).length !== 1) { - refuse(`git ${subcommand} must carry exactly one of ${rule.oneOf.join(', ')}`); - } const positionalProblem = rule.positionals(positionals); if (positionalProblem) refuse(positionalProblem); const globalProblem = rule.globals?.(globals); diff --git a/packages/codev/src/commands/check/settings.ts b/packages/codev/src/commands/check/settings.ts index 7b0c71f61..7b8685afd 100644 --- a/packages/codev/src/commands/check/settings.ts +++ b/packages/codev/src/commands/check/settings.ts @@ -46,6 +46,7 @@ export interface AttributionPattern { export interface CheckSettings { attribution: AttributionPattern[]; watch: readonly string[]; + /** Applies only to files `watch` matched: a flag glob outside the watch list has no effect. */ flag: readonly string[]; notForReading: readonly string[]; deploy: { branch: string | null; workflow: string | null }; @@ -79,19 +80,20 @@ export function parseCheckSettings(raw: unknown, sourceOf: (keyPath: string[]) = if (!KNOWN_KEYS.has(key)) fail(['check', key], `is not a known key (known: ${[...KNOWN_KEYS].join(', ')})`); } - const globs = (key: string, fallback: readonly string[]): readonly string[] => { + const strings = (key: string, kind: string, fallback: readonly string[]): readonly string[] => { const value = section[key]; if (value === undefined) return fallback; - if (!Array.isArray(value)) fail(['check', key], 'must be an array of glob strings'); + if (!Array.isArray(value)) fail(['check', key], `must be an array of ${kind}`); for (const item of value as unknown[]) { if (typeof item !== 'string' || item.trim() === '' || hasControlChars(item)) { - fail(['check', key], `must contain only non-empty glob strings (got ${JSON.stringify(item)})`); + fail(['check', key], `must contain only non-empty ${kind} (got ${JSON.stringify(item)})`); } } return value as string[]; }; + const globs = (key: string, fallback: readonly string[]) => strings(key, 'glob strings', fallback); - const attributionSources = globs('attribution', []); + const attributionSources = strings('attribution', 'regex strings', []); const attribution = attributionSources.map((source): AttributionPattern => { try { return { source, regex: new RegExp(source, 'i') }; @@ -123,7 +125,7 @@ export function parseCheckSettings(raw: unknown, sourceOf: (keyPath: string[]) = } } - const skip = globs('skip', []); + const skip = strings('skip', 'check ids', []); for (const id of skip) { if (!ALL_CHECK_IDS.has(id)) fail(['check', 'skip'], `names an unknown check id ${JSON.stringify(id)}`); } diff --git a/packages/codev/src/commands/check/validate.ts b/packages/codev/src/commands/check/validate.ts index b94141947..885befe1c 100644 --- a/packages/codev/src/commands/check/validate.ts +++ b/packages/codev/src/commands/check/validate.ts @@ -36,14 +36,15 @@ export function isFullSha(value: string): boolean { /** * A branch or ref name as git accepts it, restricted to what `codev check` ever passes: * no leading `-`, no whitespace or control characters, none of `~ ^ : ? * [ \`, no `..`, - * no `@{`, no component beginning with `.`, and not ending in `/`, `.` or `.lock`. + * no `@{`, no component beginning with `.` or ending in `.lock`, and not ending in `/` or `.`. */ export function isRefName(value: string): boolean { if (value === '' || value.startsWith('-') || value.startsWith('/')) return false; if (/[\s~^:?*[\\\u0000-\u001f\u007f]/.test(value)) return false; if (value.includes('..') || value.includes('@{') || value.includes('//') || value.includes('/.')) return false; if (value.startsWith('.') || value === '@') return false; - if (value.endsWith('/') || value.endsWith('.') || value.endsWith('.lock')) return false; + if (value.endsWith('/') || value.endsWith('.')) return false; + if (value.split('/').some((component) => component.endsWith('.lock'))) return false; return true; } From 08fd44979e6ae4b3aeff138c8d71c0a4e8acdd28 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 15:37:40 -0800 Subject: [PATCH 32/94] chore(porch): 1951 implement re-iter (iter 2) --- .../status.yaml | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 01cfe969c..7b12c1c55 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -38,11 +38,23 @@ gates: status: pending verify-approval: status: pending -iteration: 1 -build_complete: true -history: [] +iteration: 2 +build_complete: false +history: + - iteration: 1 + plan_phase: readonly_core + build_output: '' + reviews: + - model: codex + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter1-codex.txt + - model: claude + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T23:20:08.434Z' +updated_at: '2026-11-23T23:37:40.784Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From 9983468c5e344eba4452e64b774fd8633ae9271d Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 15:38:13 -0800 Subject: [PATCH 33/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 7b12c1c55..c95f58c69 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 2 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: readonly_core @@ -54,7 +54,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T23:37:40.784Z' +updated_at: '2026-11-23T23:38:13.247Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From 93a87a41e34b31d43d94e46c2d39d26441f5f1ed Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 15:47:13 -0800 Subject: [PATCH 34/94] =?UTF-8?q?[Spec=201951][Phase:=20readonly=5Fcore]?= =?UTF-8?q?=20fix:=20review=20iteration=202=20=E2=80=94=20closed=20per-sub?= =?UTF-8?q?command=20stub=20grammar,=20gh=20joined=20write=20flags,=20fake?= =?UTF-8?q?=20home?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - stub git: closed flag list per subcommand; diff-family commands must carry --no-ext-diff --no-textconv; shared OFF_GRAMMAR_FORMS refused by both layers - stub gh: refuses joined and clustered method/body flags (-XPOST, --field=, -iX) - diff-tree requires --no-ext-diff --no-textconv in the allow-list too - remoteDefaultBranch rejects an invalid branch name from origin - settings, roots and runner tests pin HOME/USERPROFILE to an empty fake home --- .../1951-readonly_core-iter2-rebuttals.md | 34 ++++++++ .../check/__tests__/allow-list.test.ts | 4 +- .../check/__tests__/git-facts.test.ts | 16 ++++ .../check/__tests__/helpers/fake-home.ts | 33 ++++++++ .../check/__tests__/helpers/git-forms.ts | 19 ++++- .../check/__tests__/helpers/stub-bin.ts | 79 ++++++++++++++----- .../commands/check/__tests__/roots.test.ts | 4 + .../commands/check/__tests__/runner.test.ts | 4 + .../commands/check/__tests__/settings.test.ts | 14 ++++ .../commands/check/__tests__/stub-bin.test.ts | 33 ++++++-- .../codev/src/commands/check/allow-list.ts | 7 +- .../codev/src/commands/check/git-facts.ts | 6 +- 12 files changed, 220 insertions(+), 33 deletions(-) create mode 100644 codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter2-rebuttals.md create mode 100644 packages/codev/src/commands/check/__tests__/helpers/fake-home.ts diff --git a/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter2-rebuttals.md b/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter2-rebuttals.md new file mode 100644 index 000000000..e44361c91 --- /dev/null +++ b/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter2-rebuttals.md @@ -0,0 +1,34 @@ +# Phase 2 (readonly_core): iteration 2 response + +Both reviewers asked for changes, and every point is accepted. The changes are in the commit after `08fd44979`. + +## Codex + +**1. The stub `git` accepts valid forms outside the allow-list, such as `git log ` or `git diff ` without the mandatory guards.** +Accepted. The stub's grammar is now closed for each subcommand. Each one has its own list of permitted flags, and every option before `--` must be on that list. `log`, `show`, `diff` and `diff-tree` must carry both `--no-ext-diff` and `--no-textconv`, and `version` takes no arguments. Globbing is off in the stub (`set -f`), so its flag lists are never expanded against files. + +The grammar is still separate code from the runner's allow-list, written in `sh`. + +A new shared list, `OFF_GRAMMAR_FORMS` in `helpers/git-forms.ts`, holds invocations that are read-only in themselves but fall outside the grammar: +- the four diff-family commands without their guards; +- `rev-list --all`, `cat-file --batch`, `ls-files --stage`, `rev-parse --git-path` and `version --build-options`. + +Both the allow-list test and the stub self-test now require each of these to be refused. So a regression that drops a guard is caught by either layer. + +**2. The stub `gh` misses joined write-flag forms.** +Accepted. `gh api` now refuses any argument that begins with `--method`, `--field`, `--raw-field` or `--input`. It also refuses any single-dash argument containing `X`, `f` or `F`. That covers `-XPOST`, `-ftitle=x`, `-Fbody=@f` and short clusters such as `-iX POST`. + +The self-test covers all twelve write forms: `pr merge`, `pr comment`, `-X POST`, `-f`, `--method=POST`, `-XPOST`, `-iX POST`, `--field=…`, `-f…`, `-F…`, `--raw-field=…` and `--input=…`. It also checks that the read-only `api --paginate … --jq …` form the forge scripts use still gets through. + +## Claude + +**1. `settings.test.ts` and `roots.test.ts` read the developer's real `~/.codev/config.json`.** +Accepted. A new helper, `helpers/fake-home.ts`, points both `HOME` and `USERPROFILE` at an empty temp directory for each test, as `src/__tests__/config.test.ts` does. The settings, roots and runner tests use it. The runner test is included because it also loads forge configuration through the same layers. + +A new settings test writes `check.*` into the fake `~/.codev/config.json`. It confirms that the file is read as a layer, and that a bad value there is reported naming that file. + +**2. `diff-tree` is exempt from the forced `--no-ext-diff --no-textconv` (minor).** +Accepted. `diff-tree` now requires both flags in the allow-list and in the stub, like `diff`, `log` and `show`. The shared read form carries them, and the unguarded form is refused by both layers. + +**3. `remoteDefaultBranch` returns an unvalidated branch name supplied by the remote (minor).** +Accepted. A name that fails `isRefName` now returns `{ ok: false, reason: "origin's HEAD names an invalid branch \"…\"" }`, instead of failing later as a runner refusal. A test injects such a reply. diff --git a/packages/codev/src/commands/check/__tests__/allow-list.test.ts b/packages/codev/src/commands/check/__tests__/allow-list.test.ts index e68fb9b3d..4ff112ac5 100644 --- a/packages/codev/src/commands/check/__tests__/allow-list.test.ts +++ b/packages/codev/src/commands/check/__tests__/allow-list.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest'; import { assertConceptAllowed, assertGitArgvAllowed, RunnerRefusal } from '../allow-list.js'; -import { allowedForms, argvOf as argv, FETCH_GLOBALS, SHA, SHA2, WRITE_FORMS } from './helpers/git-forms.js'; +import { allowedForms, argvOf as argv, FETCH_GLOBALS, OFF_GRAMMAR_FORMS, SHA, SHA2, WRITE_FORMS } from './helpers/git-forms.js'; const ABS = process.platform === 'win32' ? 'C:\\repo' : '/repo'; const ALLOWED = allowedForms(ABS); @@ -12,6 +12,7 @@ const ALLOWED = allowedForms(ABS); /** Refusals beyond the shared write forms: grammar edges. */ const REFUSED: Array<[string, string[]]> = [ ...WRITE_FORMS, + ...OFF_GRAMMAR_FORMS, ['fetch without --no-recurse-submodules', [...FETCH_GLOBALS, 'fetch', '--no-write-fetch-head', '--refmap=', '--no-tags', 'origin', SHA]], ['config --get-regexp', ['config', '--get-regexp', 'remote']], ['-c on a subcommand other than fetch', ['-c', 'gc.auto=0', 'log', '--no-ext-diff', '--no-textconv', SHA]], @@ -32,6 +33,7 @@ const REFUSED: Array<[string, string[]]> = [ ['diff without --no-textconv', ['diff', '--no-ext-diff', SHA, SHA2]], ['log without --no-ext-diff --no-textconv', ['log', SHA]], ['show without --no-ext-diff --no-textconv', ['show', '-s', SHA]], + ['diff-tree without --no-ext-diff --no-textconv', ['diff-tree', '--name-only', '-r', SHA]], ]; const BAD_FLAGS = ['--output=x', '--ext-diff', '--textconv', '--filters', '--upload-pack=x', '--exec=x', '--frobnicate']; diff --git a/packages/codev/src/commands/check/__tests__/git-facts.test.ts b/packages/codev/src/commands/check/__tests__/git-facts.test.ts index abc9c09af..ec9a867e8 100644 --- a/packages/codev/src/commands/check/__tests__/git-facts.test.ts +++ b/packages/codev/src/commands/check/__tests__/git-facts.test.ts @@ -106,6 +106,22 @@ describe('Spec 1951 — live tips', () => { expect(await liveTip(slow, 'main')).toEqual({ ok: false, reason: 'ls-remote timed out after 50ms' }); }); + it("refuses an invalid branch name in origin's HEAD", async () => { + const answering = (() => { + const child = new EventEmitter() as ChildProcess; + child.stdout = new EventEmitter() as ChildProcess['stdout']; + child.stderr = new EventEmitter() as ChildProcess['stderr']; + child.kill = (() => true) as ChildProcess['kill']; + setImmediate(() => { + child.stdout!.emit('data', Buffer.from(`ref: refs/heads/a..b\tHEAD\n${'c'.repeat(40)}\tHEAD\n`)); + child.emit('close', 0); + }); + return child; + }) as SpawnFn; + const odd = createRunner({ cwd: fx.main, workspaceRoot: fx.main, spawn: answering }); + expect(await remoteDefaultBranch(odd)).toEqual({ ok: false, reason: 'origin\'s HEAD names an invalid branch "a..b"' }); + }); + it("reads origin's default branch", async () => { expect(await remoteDefaultBranch(runner)).toEqual({ ok: true, value: 'main' }); }); diff --git a/packages/codev/src/commands/check/__tests__/helpers/fake-home.ts b/packages/codev/src/commands/check/__tests__/helpers/fake-home.ts new file mode 100644 index 000000000..726704443 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/helpers/fake-home.ts @@ -0,0 +1,33 @@ +/** + * Point `os.homedir()` at an empty temp directory for the current test file (Spec 1951). + * + * The config loader reads `~/.codev/config.json` as a layer, and the spec recommends that an + * owner put `check.*` there. A test that loads configuration must not see the developer's own + * file. `os.homedir()` reads HOME on POSIX and USERPROFILE on Windows, so both are set, as + * `src/__tests__/config.test.ts` does. + */ + +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterEach, beforeEach } from 'vitest'; + +export function useFakeHome(): { readonly dir: () => string } { + let home = ''; + const saved: Record = {}; + beforeEach(() => { + home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codev-check-home-'))); + for (const key of ['HOME', 'USERPROFILE']) { + saved[key] = process.env[key]; + process.env[key] = home; + } + }); + afterEach(() => { + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + fs.rmSync(home, { recursive: true, force: true }); + }); + return { dir: () => home }; +} diff --git a/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts b/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts index c3191d90b..a581fa8c0 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts @@ -32,7 +32,7 @@ export function allowedForms(dir: string): GitForm[] { form([], 'show', '--no-ext-diff', '--no-textconv', '-s', '--format=%B', SHA), form([], 'diff', '--no-ext-diff', '--no-textconv', '--name-only', '-z', '--no-renames', SHA, SHA2, '--', ':(top)', ':(top,exclude,glob)**/x'), form([], 'diff', '--no-ext-diff', '--no-textconv', '--numstat', '-z', SHA, SHA2), - form([], 'diff-tree', '--no-commit-id', '--name-only', '-r', '-z', SHA), + form([], 'diff-tree', '--no-ext-diff', '--no-textconv', '--no-commit-id', '--name-only', '-r', '-z', SHA), form([], 'cat-file', '-e', `${SHA}^{commit}`), form([], 'cat-file', '-t', SHA), form([], 'for-each-ref', '--format=%(refname)', 'refs/heads/main'), @@ -76,3 +76,20 @@ export const WRITE_FORMS: Array<[string, string[]]> = [ ['log --output=x', ['log', '--no-ext-diff', '--no-textconv', '--output=x', SHA]], ['ls-remote --upload-pack=x', ['ls-remote', '--upload-pack=x', 'origin']], ]; + +/** + * Read-only in themselves, but outside the grammar: a diff-family command without its + * guards, or a flag no command uses. Both layers must refuse them, so a regression that + * drops a guard is caught by either. + */ +export const OFF_GRAMMAR_FORMS: Array<[string, string[]]> = [ + ['log without its guards', ['log', SHA]], + ['diff without its guards', ['diff', SHA, SHA2]], + ['show without its guards', ['show', '-s', SHA]], + ['diff-tree without its guards', ['diff-tree', '--name-only', '-r', SHA]], + ['rev-list --all', ['rev-list', '--all']], + ['cat-file --batch', ['cat-file', '--batch']], + ['ls-files --stage', ['ls-files', '--stage']], + ['rev-parse --git-path', ['rev-parse', '--git-path', 'x']], + ['version --build-options', ['version', '--build-options']], +]; diff --git a/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts b/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts index 8bfb94581..5395b6e3c 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts @@ -4,8 +4,8 @@ * * Both record every invocation and check it against a read-only list THEY keep, separate * from the runner's allow-list, so a runner bug cannot hide behind a matching stub. A call - * off the list is written to `violations` and fails with exit 99; `assertNoViolations()` - * turns it into a test failure. + * off the list is written to `violations` and fails with exit 99; tests assert that + * `violations()` is empty. * * - `git` then execs the real git, whose absolute path was resolved before PATH changed. * - `gh` answers from fixtures: `answer(args, stdout, { exit, sleepSeconds })` matches the @@ -20,12 +20,34 @@ import * as path from 'node:path'; import { REAL_GIT } from './git-fixture.js'; const GIT_STUB = `#!/bin/sh -# Stub git (Spec 1951 tests): record, check a read-only grammar of its own, exec the real git. +# Stub git (Spec 1951 tests): record, check a CLOSED read-only grammar of its own, exec the +# real git. Globbing is off so the flag lists below are never expanded against files. +set -f printf '%s\\n' "$*" >> "$STUB_DIR/git-calls" ALL="$*" violation() { printf 'git %s :: %s\\n' "$ALL" "$1" >> "$STUB_DIR/violations"; echo "stub git refused: $1" >&2; exit 99; } -has() { want="$1"; shift; for a in "$@"; do [ "$a" = "$want" ] && return 0; done; return 1; } +has() { want="$1"; shift; for a in "$@"; do [ "$a" = "--" ] && return 1; [ "$a" = "$want" ] && return 0; done; return 1; } is_sha40() { case "$1" in ''|*[!0-9a-f]*) return 1 ;; esac; [ "\${#1}" -eq 40 ]; } +# flags_only "" args…: every option before "--" must be on the allowed list. +# An entry ending in "=*" is a prefix that needs a value; any other entry is exact. +flags_only() { + allowed="$1"; shift + for a in "$@"; do + [ "$a" = "--" ] && return 0 + case "$a" in + -*) + ok=0 + for p in $allowed; do + case "$p" in + *'=*') case "$a" in "\${p%\\*}"?*) ok=1 ;; esac ;; + *) [ "$a" = "$p" ] && ok=1 ;; + esac + done + [ "$ok" = 1 ] || violation "$sub $a" ;; + esac + done +} +no_ext_diff() { { has --no-ext-diff "$@" && has --no-textconv "$@"; } || violation "$sub without --no-ext-diff --no-textconv"; } check() { gcauto=0; maint=0; locks=0 while [ $# -gt 0 ]; do @@ -38,35 +60,43 @@ check() { esac done sub="$1"; [ $# -gt 0 ] && shift - for a in "$@"; do - case "$a" in - --) break ;; - --output*|--ext-diff|--textconv|--filters|--upload-pack*|--exec*) violation "flag $a" ;; - esac - done if [ "$sub" != fetch ] && [ $((gcauto + maint)) -gt 0 ]; then violation "-c outside fetch"; fi case "$sub" in - version|rev-parse|rev-list|merge-base|log|show|diff|diff-tree|cat-file|for-each-ref|ls-files|ls-remote) ;; - merge-tree) has --write-tree "$@" || violation "merge-tree without --write-tree" ;; - status) [ "$locks" = 1 ] || violation "status without --no-optional-locks" ;; + version) [ $# -eq 0 ] || violation "version $*" ;; + rev-parse) flags_only "--show-toplevel --verify --quiet -q --abbrev-ref" "$@" ;; + rev-list) flags_only "--first-parent --parents --count --not --reverse --max-count=*" "$@" ;; + merge-base) flags_only "--is-ancestor" "$@" ;; + log) flags_only "--no-ext-diff --no-textconv --first-parent --no-merges -z --format=* --max-count=*" "$@"; no_ext_diff "$@" ;; + show) flags_only "--no-ext-diff --no-textconv -s --no-patch --format=*" "$@"; no_ext_diff "$@" ;; + diff) flags_only "--no-ext-diff --no-textconv --name-only --numstat -z --no-renames" "$@"; no_ext_diff "$@" ;; + diff-tree) flags_only "--no-ext-diff --no-textconv --no-commit-id --name-only -r -z --no-renames" "$@"; no_ext_diff "$@" ;; + cat-file) flags_only "-e -t -p" "$@" ;; + for-each-ref) flags_only "--format=*" "$@" ;; + ls-files) flags_only "--others --ignored --exclude-standard --directory -z" "$@" ;; + ls-remote) flags_only "--symref" "$@" ;; + merge-tree) + flags_only "--write-tree --name-only --no-messages -z" "$@" + has --write-tree "$@" || violation "merge-tree without --write-tree" ;; + status) + flags_only "--porcelain=v1 -z --untracked-files=all" "$@" + [ "$locks" = 1 ] || violation "status without --no-optional-locks" ;; worktree) [ "$*" = "list --porcelain" ] || [ "$*" = "list --porcelain -z" ] || violation "worktree $*" ;; config) { [ $# -eq 2 ] && [ "$1" = --get ]; } || violation "config other than --get " ;; symbolic-ref) + flags_only "--short -q --quiet" "$@" refs=0 - for a in "$@"; do - case "$a" in --short|-q|--quiet) ;; -*) violation "symbolic-ref $a" ;; *) refs=$((refs + 1)) ;; esac - done + for a in "$@"; do case "$a" in -*) ;; *) refs=$((refs + 1)) ;; esac; done [ "$refs" -eq 1 ] || violation "symbolic-ref write form" ;; fetch) [ "$gcauto" = 1 ] && [ "$maint" = 1 ] || violation "fetch without the housekeeping overrides" + flags_only "--no-write-fetch-head --refmap= --no-tags --no-recurse-submodules --quiet" "$@" for flag in --no-write-fetch-head --refmap= --no-tags --no-recurse-submodules; do has "$flag" "$@" || violation "fetch without $flag" done remote=""; shas=0 for a in "$@"; do case "$a" in - --no-write-fetch-head|--refmap=|--no-tags|--no-recurse-submodules|--quiet) ;; - -*) violation "fetch $a" ;; + -*) ;; *) if [ -z "$remote" ]; then remote="$a"; elif is_sha40 "$a"; then shas=$((shas + 1)); else violation "fetch of $a, not a full SHA"; fi ;; esac done @@ -85,9 +115,16 @@ printf '%s\\n' "$*" >> "$STUB_DIR/gh-calls" violation() { printf 'gh %s :: %s\\n' "$*" "$REASON" >> "$STUB_DIR/violations"; echo "stub gh refused: $REASON" >&2; exit 99; } case "$1 $2" in "pr view"|"pr list"|"run list"|"run view") ;; - api\\ *) for a in "$@"; do case "$a" in - -X|--method|-f|-F|--field|--raw-field|--input) REASON="api write flag $a"; violation "$@" ;; - esac; done ;; + api\\ *) + # Refuse every method and body flag, joined forms (--method=POST, -XPOST, -fx) and short + # clusters (-iX POST) included. + for a in "$@"; do + case "$a" in + --method*|--field*|--raw-field*|--input*) REASON="api write flag $a"; violation "$@" ;; + --*) ;; + -*X*|-*f*|-*F*) REASON="api write flag $a"; violation "$@" ;; + esac + done ;; *) REASON="$1 $2"; violation "$@" ;; esac for f in "$STUB_DIR"/answers/*.args; do diff --git a/packages/codev/src/commands/check/__tests__/roots.test.ts b/packages/codev/src/commands/check/__tests__/roots.test.ts index 274d12ef3..abdf041f8 100644 --- a/packages/codev/src/commands/check/__tests__/roots.test.ts +++ b/packages/codev/src/commands/check/__tests__/roots.test.ts @@ -12,11 +12,15 @@ import { parseWorktreeList, resolveRoots } from '../roots.js'; import { createRunner } from '../runner.js'; import { loadCheckSettings } from '../settings.js'; import { createFixture, type Fixture } from './helpers/git-fixture.js'; +import { useFakeHome } from './helpers/fake-home.js'; let fx: Fixture; const rootsFrom = (cwd: string) => resolveRoots(createRunner({ cwd, workspaceRoot: cwd, env: fx.env })); +/** Never read the developer's own ~/.codev/config.json. */ +useFakeHome(); + beforeEach(() => { fx = createFixture(); }); diff --git a/packages/codev/src/commands/check/__tests__/runner.test.ts b/packages/codev/src/commands/check/__tests__/runner.test.ts index 3cea2f658..73a242d1b 100644 --- a/packages/codev/src/commands/check/__tests__/runner.test.ts +++ b/packages/codev/src/commands/check/__tests__/runner.test.ts @@ -10,6 +10,7 @@ import type { ChildProcess } from 'node:child_process'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { RunnerRefusal } from '../allow-list.js'; import { createRunner, formatDuration, type SpawnFn } from '../runner.js'; +import { useFakeHome } from './helpers/fake-home.js'; const isWindows = process.platform === 'win32'; @@ -33,6 +34,9 @@ function writeForgeConfig(forge: Record): void { fs.writeFileSync(path.join(workspace, '.codev', 'config.json'), JSON.stringify({ forge })); } +/** Never read the developer's own ~/.codev/config.json. */ +useFakeHome(); + beforeEach(() => { workspace = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codev-check-runner-'))); }); diff --git a/packages/codev/src/commands/check/__tests__/settings.test.ts b/packages/codev/src/commands/check/__tests__/settings.test.ts index 652a9935f..ecd2abf6d 100644 --- a/packages/codev/src/commands/check/__tests__/settings.test.ts +++ b/packages/codev/src/commands/check/__tests__/settings.test.ts @@ -8,6 +8,7 @@ import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { CheckCommandError } from '../report.js'; import { DEFAULT_NOT_FOR_READING, DEFAULT_WATCH, loadCheckSettings, parseCheckSettings } from '../settings.js'; +import { useFakeHome } from './helpers/fake-home.js'; let root: string; let projectFile: string; @@ -17,6 +18,9 @@ function writeProject(check: unknown): void { fs.writeFileSync(projectFile, JSON.stringify({ check })); } +/** Never read the developer's own ~/.codev/config.json. */ +const home = useFakeHome(); + beforeEach(() => { root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codev-check-settings-'))); fs.mkdirSync(path.join(root, '.codev')); @@ -68,6 +72,16 @@ describe('Spec 1951 — check settings', () => { expect([...settings.skip]).toEqual(['size', 'overlap']); }); + it('reads ~/.codev/config.json as a layer, and names it on error', () => { + const homeFile = path.join(home.dir(), '.codev', 'config.json'); + fs.mkdirSync(path.dirname(homeFile), { recursive: true }); + fs.writeFileSync(homeFile, JSON.stringify({ check: { attribution: ['co-authored-by'] } })); + fs.writeFileSync(projectFile, '{}'); + expect(loadCheckSettings(root).attribution.map((p) => p.source)).toEqual(['co-authored-by']); + fs.writeFileSync(homeFile, JSON.stringify({ check: { skip: ['colour'] } })); + expect(loadError().message).toBe(`check.skip names an unknown check id "colour" (in ${homeFile})`); + }); + it('replaces the notForReading default rather than adding to it', () => { writeProject({ notForReading: ['docs/**'] }); expect(loadCheckSettings(root).notForReading).toEqual(['docs/**']); diff --git a/packages/codev/src/commands/check/__tests__/stub-bin.test.ts b/packages/codev/src/commands/check/__tests__/stub-bin.test.ts index 42d99f433..dfa46f0b3 100644 --- a/packages/codev/src/commands/check/__tests__/stub-bin.test.ts +++ b/packages/codev/src/commands/check/__tests__/stub-bin.test.ts @@ -7,7 +7,7 @@ import { spawnSync } from 'node:child_process'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; -import { allowedForms, argvOf, WRITE_FORMS } from './helpers/git-forms.js'; +import { allowedForms, argvOf, OFF_GRAMMAR_FORMS, WRITE_FORMS } from './helpers/git-forms.js'; import { createStubBin, type StubBin } from './helpers/stub-bin.js'; let fx: Fixture; @@ -42,6 +42,11 @@ describe.skipIf(process.platform === 'win32')('Spec 1951 — stub git and gh', ( expect(snapshotRepoState(fx, fx.main)).toEqual(before); }); + it.each(OFF_GRAMMAR_FORMS)('refuses %s, so a dropped guard is caught', (_name, args) => { + expect(run('git', args)).toBe(99); + expect(stubs.violations()).toHaveLength(1); + }); + it('answers gh read calls from fixtures and refuses writes', () => { stubs.answer(['pr', 'view', '7', '--json', 'title'], '{"title":"t"}\n'); const view = spawnSync(path.join(stubs.dir, 'gh'), ['pr', 'view', '7', '--json', 'title'], { env: { ...process.env, ...stubs.env }, encoding: 'utf-8' }); @@ -50,9 +55,27 @@ describe.skipIf(process.platform === 'win32')('Spec 1951 — stub git and gh', ( expect(run('gh', ['pr', 'view', '8'])).toBe(98); expect(stubs.violations()).toEqual([]); - for (const args of [['pr', 'merge', '7'], ['pr', 'comment', '7', '-b', 'x'], ['api', '-X', 'POST', 'repos/o/r/issues'], ['api', 'repos/o/r/issues', '-f', 'title=x']]) { - expect(run('gh', args), args.join(' ')).toBe(99); - } - expect(stubs.violations()).toHaveLength(4); + const writes = [ + ['pr', 'merge', '7'], + ['pr', 'comment', '7', '-b', 'x'], + ['api', '-X', 'POST', 'repos/o/r/issues'], + ['api', 'repos/o/r/issues', '-f', 'title=x'], + ['api', '--method=POST', 'repos/o/r/issues'], + ['api', '-XPOST', 'repos/o/r/issues'], + ['api', '-iX', 'POST', 'repos/o/r/issues'], + ['api', 'repos/o/r/issues', '--field=title=x'], + ['api', 'repos/o/r/issues', '-ftitle=x'], + ['api', 'repos/o/r/issues', '-Fbody=@f'], + ['api', 'repos/o/r/issues', '--raw-field=title=x'], + ['api', 'repos/o/r/issues', '--input=body.json'], + ]; + for (const args of writes) expect(run('gh', args), args.join(' ')).toBe(99); + expect(stubs.violations()).toHaveLength(writes.length); + }); + + it('lets the read-only gh api forms the forge scripts use through', () => { + const args = ['api', '--paginate', 'repos/{owner}/{repo}/commits/abc/check-runs?per_page=100', '--jq', '.check_runs[] | {name}']; + expect(run('gh', args)).toBe(98); + expect(stubs.violations()).toEqual([]); }); }); diff --git a/packages/codev/src/commands/check/allow-list.ts b/packages/codev/src/commands/check/allow-list.ts index ceecb3e68..24739ae0f 100644 --- a/packages/codev/src/commands/check/allow-list.ts +++ b/packages/codev/src/commands/check/allow-list.ts @@ -3,8 +3,8 @@ * * A CLOSED grammar: every token of a git argv must be explicitly permitted, so an unknown * flag is refused rather than passed through. It covers the git subcommands the commands - * run, and only the flags they use. Diff-family commands must carry - * `--no-ext-diff --no-textconv`, so no repository-configured diff program runs; flags that + * run, and only the flags they use. Diff-family commands (`diff`, `diff-tree`, `log`, + * `show`) must carry `--no-ext-diff --no-textconv`, so no repository-configured diff program runs; flags that * write files (`--output`) or run programs (`--upload-pack`, `--exec`, `--textconv`, * `--filters`) are never permitted. `fetch` is allowed only in its ref-neutral form, which * adds objects and moves no ref (no tags, no submodules) and writes no FETCH_HEAD. @@ -122,7 +122,8 @@ const RULES: Record = { positionals: exactly(2, isRevision, 'revision'), }, 'diff-tree': { - flags: ['--no-commit-id', '--name-only', '-r', '-z', '--no-renames'], + flags: [...NO_EXT_DIFF, '--no-commit-id', '--name-only', '-r', '-z', '--no-renames'], + required: NO_EXT_DIFF, positionals: between(1, 2, isRevision, 'revision'), }, 'cat-file': { diff --git a/packages/codev/src/commands/check/git-facts.ts b/packages/codev/src/commands/check/git-facts.ts index 82590121c..2de5b5168 100644 --- a/packages/codev/src/commands/check/git-facts.ts +++ b/packages/codev/src/commands/check/git-facts.ts @@ -9,7 +9,7 @@ import { CheckCommandError } from './report.js'; import type { GitResult, Runner } from './runner.js'; -import { isFullSha } from './validate.js'; +import { isFullSha, isRefName } from './validate.js'; export interface GitVersion { major: number; @@ -74,7 +74,9 @@ export async function remoteDefaultBranch(runner: Runner): Promise { From e21d4bb41accf30c64d4cc7bde354ee93f82a0fa Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 16:02:44 -0800 Subject: [PATCH 35/94] chore(porch): 1951 implement re-iter (iter 3) --- .../status.yaml | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index c95f58c69..0639ad4e7 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -38,8 +38,8 @@ gates: status: pending verify-approval: status: pending -iteration: 2 -build_complete: true +iteration: 3 +build_complete: false history: - iteration: 1 plan_phase: readonly_core @@ -53,8 +53,20 @@ history: verdict: REQUEST_CHANGES file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter1-claude.txt + - iteration: 2 + plan_phase: readonly_core + build_output: '' + reviews: + - model: codex + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter2-codex.txt + - model: claude + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter2-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-23T23:38:13.247Z' +updated_at: '2026-11-24T00:02:43.994Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From dcabaafc4e84f95e3095700821b35bcee14cc3b2 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 16:03:04 -0800 Subject: [PATCH 36/94] [Spec 1951] Thread log: Phase 2 review rounds --- codev/state/spir-1951_thread.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 34e132489..53f942630 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -86,3 +86,16 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals - Porch's context-refresh task at the Phase 1→2 boundary was not run: its commands were not captured before the next `porch next` replaced the task, and a context compaction happened at the same point. - Waiting: architect's word on main-38 before `porch done` (GitHub run on the pushed head may come first). +- Phase 2 tests check: one local porch run failed on 4 unrelated spawn-heavy files (names found in vitest's + results cache; porch's output truncation is #1853, another builder's). All 4 pass alone. One-time skip used + under main-32, then for each later porch done on GitHub-green heads 5dea9be3e and 93a87a41e (architect + confirmed each). +- CMAP Phase 2 iter 1 (both REQUEST_CHANGES): stub git grammar not closed (symbolic-ref write form, fetch by + non-SHA); isRefName missed `.lock` components; fetch rule lacked --no-tags; snapshot read FETCH_HEAD only + from the common dir. Fixed in 5dea9be3e. +- CMAP Phase 2 iter 2 (both REQUEST_CHANGES): stub git flags not closed per subcommand (log/diff without the + guards passed); stub gh missed joined write flags (-XPOST, --field=); tests read the real ~/.codev config; + diff-tree lacked the guards; origin HEAD branch not validated. Fixed in 93a87a41e. +- ARCHITECT ORDER (2026-11-24): the review must list what each round found in the allow-list and the stubs, + so the owner can see at the pr gate how the read-only claim was tightened. If round 3 asks for changes, + tell the architect what it found BEFORE fixing. From da7f7f11aa6b0ed0685069698bc18b868e60a367 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 16:04:04 -0800 Subject: [PATCH 37/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 0639ad4e7..d151ca0dc 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 3 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: readonly_core @@ -66,7 +66,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter2-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T00:02:43.994Z' +updated_at: '2026-11-24T00:04:04.559Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From aa7e34f58268ca4fe089a2879d5e64e43a54f4bd Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 16:13:07 -0800 Subject: [PATCH 38/94] =?UTF-8?q?[Spec=201951][Phase:=20readonly=5Fcore]?= =?UTF-8?q?=20fix:=20review=20iteration=203=20=E2=80=94=20stub=20checks=20?= =?UTF-8?q?arguments,=20not=20only=20flags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - stub ls-remote: origin only, then HEAD or refs/… names (no ::, no ..) - stub revision-taking subcommands refuse path and URL arguments, closing the implicit --no-index diff of files outside the repository - stub ls-files/status take no arguments before --; for-each-ref refs/ only - shared refusal cases for all of the above, refused by both layers - liveTip rejects an invalid branch name without running git --- .../1951-readonly_core-iter3-rebuttals.md | 40 +++++++++++ .../check/__tests__/git-facts.test.ts | 7 ++ .../check/__tests__/helpers/git-forms.ts | 11 +++ .../check/__tests__/helpers/stub-bin.ts | 67 +++++++++++++++---- .../codev/src/commands/check/git-facts.ts | 1 + 5 files changed, 114 insertions(+), 12 deletions(-) create mode 100644 codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-rebuttals.md diff --git a/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-rebuttals.md b/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-rebuttals.md new file mode 100644 index 000000000..f82cb965e --- /dev/null +++ b/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-rebuttals.md @@ -0,0 +1,40 @@ +# Phase 2 (readonly_core): iteration 3 response + +Claude approved. Codex asked for one change, which is accepted. The architect approved the fix before it was made, and asked for an audit of every similar form in the stub. Everything here is in the test helpers, except a one-line guard in `git-facts.ts`. + +## Codex + +**The stub `git` checks `ls-remote`'s flags but not its remote or ref arguments.** +Accepted. The stub's `ls-remote` now requires `origin` as its first argument. Every argument after it must be `HEAD` or a `refs/…` name containing neither `::` nor `..`. Four shared cases were added to `OFF_GRAMMAR_FORMS`: +- another remote; +- an `ext::sh -c …` transport; +- a path to another repository; +- `origin` with an `ext::` ref. + +Both layers refuse all four: `allow-list.test.ts` includes the list, and so does `stub-bin.test.ts`. The `ext::` case's probe file is never created, because the stub refuses the call before git starts. + +## Audit requested by the architect: other forms with checked flags but unchecked arguments + +Every subcommand the stub accepts was read for arguments that name a repository, a URL or a file system path: + +| Form | Before | Now | +|---|---|---| +| `ls-remote` | remote and refs unchecked | `origin` only, then `HEAD` or `refs/…` names (above) | +| `fetch` | already checked: remote must be `origin`, every other argument a full 40-hex SHA | unchanged | +| global `-C ` | already checked: absolute path, in both layers. It selects a local checkout that `codev check` itself named, such as a builder worktree; it is not a remote. | unchanged | +| `diff`, `log`, `show`, `diff-tree`, `merge-tree`, `merge-base`, `rev-list`, `rev-parse`, `cat-file` | **same gap: revision arguments were unchecked.** `git diff --no-ext-diff --no-textconv /etc/hosts /etc/passwd`, or `../a ../b`, runs as an implicit `--no-index` diff of files outside the repository. That is a read, but of arbitrary paths, and the runner already refuses it. | Each argument before `--` must look like a revision. Absolute paths, `../` paths, `:` (and so `::`) and backslashes are refused. Both cases were added to the shared refusals. | +| `ls-files`, `status` | positional pathspecs before `--` were unchecked (they are confined to the repository) | no arguments before `--`, as in the runner; shared refusal cases added | +| `for-each-ref` | patterns unchecked | `refs/…` patterns only, as in the runner; shared refusal case added | +| `config` | already exactly `--get `, with no file option | unchanged | +| `worktree`, `symbolic-ref`, `version` | already exact forms | unchanged | + +Pathspecs after `--` stay unchecked by design. git confines them to the repository, and `:(top,glob)` magic is how the commands use them. + +## Claude (APPROVE, non-blocking notes) + +- **`liveTip`'s branch argument is not pre-validated.** Taken, as the architect asked: one line. An invalid name now returns `{ ok: false, reason: 'invalid branch name "…"' }` without running git. A test uses a spawn spy. +- **Empty versus invalid forge output.** Left for Phase 6, as the note says. +- **Strictness about unknown `check.*` keys, the set-size test in the fetch globals rule, and optional askpass hardening.** Left as they are. None names a defect in this phase. + - Refusing unknown keys is deliberate: a typo such as `wacth` exits 2 rather than silently doing nothing. + - The fetch rule compares set sizes, but the set can only ever contain the two permitted overrides, so equal size means both are present. + - `GIT_TERMINAL_PROMPT=0` already keeps a prompt from waiting for input. diff --git a/packages/codev/src/commands/check/__tests__/git-facts.test.ts b/packages/codev/src/commands/check/__tests__/git-facts.test.ts index ec9a867e8..fa2c12bd0 100644 --- a/packages/codev/src/commands/check/__tests__/git-facts.test.ts +++ b/packages/codev/src/commands/check/__tests__/git-facts.test.ts @@ -83,6 +83,13 @@ describe('Spec 1951 — live tips', () => { expect(fx.git(fx.main, 'rev-parse', 'refs/remotes/origin/main').trim()).toBe(stale); }); + it('reports an invalid branch name without running git', async () => { + const spawn = vi.fn(); + const spied = createRunner({ cwd: fx.main, workspaceRoot: fx.main, spawn }); + expect(await liveTip(spied, 'a..b')).toEqual({ ok: false, reason: 'invalid branch name "a..b"' }); + expect(spawn).not.toHaveBeenCalled(); + }); + it('reports a branch origin does not have as null', async () => { expect(await liveTip(runner, 'no-such-branch')).toEqual({ ok: true, value: null }); }); diff --git a/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts b/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts index a581fa8c0..f3381d2f8 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts @@ -92,4 +92,15 @@ export const OFF_GRAMMAR_FORMS: Array<[string, string[]]> = [ ['ls-files --stage', ['ls-files', '--stage']], ['rev-parse --git-path', ['rev-parse', '--git-path', 'x']], ['version --build-options', ['version', '--build-options']], + // Arguments, not flags: another repository, a transport that runs a program, a file + // system path. The second layer must not rely on the first having checked them. + ['ls-remote another remote', ['ls-remote', 'upstream', 'HEAD']], + ['ls-remote an ext:: transport', ['ls-remote', 'ext::sh -c touch% /tmp/codev-check-ext', 'HEAD']], + ['ls-remote a path to another repository', ['ls-remote', '/other/repo.git']], + ['ls-remote origin with an ext:: ref', ['ls-remote', 'origin', 'ext::x']], + ['diff of absolute paths (an implicit --no-index diff)', ['diff', '--no-ext-diff', '--no-textconv', '/etc/hosts', '/etc/passwd']], + ['diff of paths outside the work tree', ['diff', '--no-ext-diff', '--no-textconv', '../a', '../b']], + ['ls-files with a path argument', ['ls-files', 'README.md']], + ['status with a path argument', ['--no-optional-locks', 'status', '--porcelain=v1', 'README.md']], + ['for-each-ref outside refs/', ['for-each-ref', 'heads/']], ]; diff --git a/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts b/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts index 5395b6e3c..a2d10f49c 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/stub-bin.ts @@ -48,6 +48,25 @@ flags_only() { done } no_ext_diff() { { has --no-ext-diff "$@" && has --no-textconv "$@"; } || violation "$sub without --no-ext-diff --no-textconv"; } +# revisions_only args…: every argument before "--" that is not an option must look like a +# revision, never a file system path (which can turn \`diff\` into a --no-index diff of files +# outside the repository) or a transport URL. +revisions_only() { + for a in "$@"; do + [ "$a" = "--" ] && return 0 + case "$a" in + -*) ;; + /*|../*|*/../*|..|*::*|*:*|*\\\\*) violation "$sub argument $a is not a revision" ;; + esac + done +} +# no_positionals args…: nothing but options before "--". +no_positionals() { + for a in "$@"; do + [ "$a" = "--" ] && return 0 + case "$a" in -*) ;; *) violation "$sub takes no argument $a" ;; esac + done +} check() { gcauto=0; maint=0; locks=0 while [ $# -gt 0 ]; do @@ -63,22 +82,46 @@ check() { if [ "$sub" != fetch ] && [ $((gcauto + maint)) -gt 0 ]; then violation "-c outside fetch"; fi case "$sub" in version) [ $# -eq 0 ] || violation "version $*" ;; - rev-parse) flags_only "--show-toplevel --verify --quiet -q --abbrev-ref" "$@" ;; - rev-list) flags_only "--first-parent --parents --count --not --reverse --max-count=*" "$@" ;; - merge-base) flags_only "--is-ancestor" "$@" ;; - log) flags_only "--no-ext-diff --no-textconv --first-parent --no-merges -z --format=* --max-count=*" "$@"; no_ext_diff "$@" ;; - show) flags_only "--no-ext-diff --no-textconv -s --no-patch --format=*" "$@"; no_ext_diff "$@" ;; - diff) flags_only "--no-ext-diff --no-textconv --name-only --numstat -z --no-renames" "$@"; no_ext_diff "$@" ;; - diff-tree) flags_only "--no-ext-diff --no-textconv --no-commit-id --name-only -r -z --no-renames" "$@"; no_ext_diff "$@" ;; - cat-file) flags_only "-e -t -p" "$@" ;; - for-each-ref) flags_only "--format=*" "$@" ;; - ls-files) flags_only "--others --ignored --exclude-standard --directory -z" "$@" ;; - ls-remote) flags_only "--symref" "$@" ;; + rev-parse) flags_only "--show-toplevel --verify --quiet -q --abbrev-ref" "$@"; revisions_only "$@" ;; + rev-list) flags_only "--first-parent --parents --count --not --reverse --max-count=*" "$@"; revisions_only "$@" ;; + merge-base) flags_only "--is-ancestor" "$@"; revisions_only "$@" ;; + log) flags_only "--no-ext-diff --no-textconv --first-parent --no-merges -z --format=* --max-count=*" "$@"; no_ext_diff "$@"; revisions_only "$@" ;; + show) flags_only "--no-ext-diff --no-textconv -s --no-patch --format=*" "$@"; no_ext_diff "$@"; revisions_only "$@" ;; + diff) flags_only "--no-ext-diff --no-textconv --name-only --numstat -z --no-renames" "$@"; no_ext_diff "$@"; revisions_only "$@" ;; + diff-tree) flags_only "--no-ext-diff --no-textconv --no-commit-id --name-only -r -z --no-renames" "$@"; no_ext_diff "$@"; revisions_only "$@" ;; + cat-file) flags_only "-e -t -p" "$@"; revisions_only "$@" ;; + for-each-ref) + flags_only "--format=*" "$@" + for a in "$@"; do case "$a" in -*|refs/*) ;; *) violation "for-each-ref pattern $a outside refs/" ;; esac; done ;; + ls-files) flags_only "--others --ignored --exclude-standard --directory -z" "$@"; no_positionals "$@" ;; + ls-remote) + # A remote, URL or path here can reach another repository or run a transport + # program (ext::); only origin, then HEAD or refs/… names. + flags_only "--symref" "$@" + seen_remote=0 + for a in "$@"; do + case "$a" in + -*) ;; + *) if [ "$seen_remote" = 0 ]; then + [ "$a" = origin ] || violation "ls-remote of $a, not origin"; seen_remote=1 + else + case "$a" in + HEAD) ;; + *::*|*..*) violation "ls-remote ref $a" ;; + refs/*) ;; + *) violation "ls-remote ref $a" ;; + esac + fi ;; + esac + done + [ "$seen_remote" = 1 ] || violation "ls-remote without origin" ;; merge-tree) flags_only "--write-tree --name-only --no-messages -z" "$@" - has --write-tree "$@" || violation "merge-tree without --write-tree" ;; + has --write-tree "$@" || violation "merge-tree without --write-tree" + revisions_only "$@" ;; status) flags_only "--porcelain=v1 -z --untracked-files=all" "$@" + no_positionals "$@" [ "$locks" = 1 ] || violation "status without --no-optional-locks" ;; worktree) [ "$*" = "list --porcelain" ] || [ "$*" = "list --porcelain -z" ] || violation "worktree $*" ;; config) { [ $# -eq 2 ] && [ "$1" = --get ]; } || violation "config other than --get " ;; diff --git a/packages/codev/src/commands/check/git-facts.ts b/packages/codev/src/commands/check/git-facts.ts index 2de5b5168..df26c3cee 100644 --- a/packages/codev/src/commands/check/git-facts.ts +++ b/packages/codev/src/commands/check/git-facts.ts @@ -59,6 +59,7 @@ export function versionLabel(version: GitVersion): string { /** The live tip of `origin/`, or null when the branch does not exist there. */ export async function liveTip(runner: Runner, branch: string): Promise> { + if (!isRefName(branch)) return { ok: false, reason: `invalid branch name ${JSON.stringify(branch)}` }; const ref = `refs/heads/${branch}`; const result = await runner.git(['ls-remote', 'origin', ref]); if (result.exitCode !== 0) return { ok: false, reason: failureReason('ls-remote', result, runner.timeoutLabel) }; From c42251ec5504bd44acbd59ee671ed823661c9663 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 16:18:56 -0800 Subject: [PATCH 39/94] [Spec 1951][Phase: readonly_core] fix: ext:: refusal case uses no /tmp path (tmp-residue check) --- .../1951-readonly_core-iter3-rebuttals.md | 2 +- .../codev/src/commands/check/__tests__/helpers/git-forms.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-rebuttals.md b/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-rebuttals.md index f82cb965e..354b4745d 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-rebuttals.md +++ b/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-rebuttals.md @@ -11,7 +11,7 @@ Accepted. The stub's `ls-remote` now requires `origin` as its first argument. Ev - a path to another repository; - `origin` with an `ext::` ref. -Both layers refuse all four: `allow-list.test.ts` includes the list, and so does `stub-bin.test.ts`. The `ext::` case's probe file is never created, because the stub refuses the call before git starts. +Both layers refuse all four: `allow-list.test.ts` includes the list, and so does `stub-bin.test.ts`. The `ext::` case uses `sh -c true`, because the repository's `/tmp` residue check (`scripts/tmp-residue-check.mjs`) refuses a literal `/tmp` path in a test file. ## Audit requested by the architect: other forms with checked flags but unchecked arguments diff --git a/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts b/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts index f3381d2f8..a8f3e8c09 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts @@ -95,7 +95,7 @@ export const OFF_GRAMMAR_FORMS: Array<[string, string[]]> = [ // Arguments, not flags: another repository, a transport that runs a program, a file // system path. The second layer must not rely on the first having checked them. ['ls-remote another remote', ['ls-remote', 'upstream', 'HEAD']], - ['ls-remote an ext:: transport', ['ls-remote', 'ext::sh -c touch% /tmp/codev-check-ext', 'HEAD']], + ['ls-remote an ext:: transport', ['ls-remote', 'ext::sh -c true', 'HEAD']], ['ls-remote a path to another repository', ['ls-remote', '/other/repo.git']], ['ls-remote origin with an ext:: ref', ['ls-remote', 'origin', 'ext::x']], ['diff of absolute paths (an implicit --no-index diff)', ['diff', '--no-ext-diff', '--no-textconv', '/etc/hosts', '/etc/passwd']], From 8c9715a4bdb57ba0919daa4310b5969254d55942 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 16:24:36 -0800 Subject: [PATCH 40/94] chore(porch): 1951 implement force-advance (safety ceiling reached at iter 3) --- .../status.yaml | 20 ++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index d151ca0dc..7a2160b9c 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -65,8 +65,20 @@ history: verdict: REQUEST_CHANGES file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter2-claude.txt + - iteration: 3 + plan_phase: readonly_core + build_output: '' + reviews: + - model: codex + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-codex.txt + - model: claude + verdict: APPROVE + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T00:04:04.559Z' +updated_at: '2026-11-24T00:24:36.768Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -74,3 +86,9 @@ context_refreshes: - boundary: plan-phase:readonly_core at: '2026-11-23T22:50:05.115Z' acknowledged_at: '2026-11-23T22:50:10.516Z' +force_advanced: + phase: readonly_core + iteration: 3 + max_iterations: 3 + rebuttal_file: 1951-readonly_core-iter3-rebuttals.md + at: '2026-11-24T00:24:36.768Z' From 360d0eb9b73bc2ce0594ae7f1482a46067a1a0bf Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 16:24:38 -0800 Subject: [PATCH 41/94] =?UTF-8?q?chore(porch):=201951=20advance=20plan=20p?= =?UTF-8?q?hase=20=E2=86=92=20check=5Fpr=5Fmechanics?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../status.yaml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 7a2160b9c..5d622a4f8 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -8,10 +8,10 @@ plan_phases: status: complete - id: readonly_core title: Read-only runner, configuration and report core - status: in_progress + status: complete - id: check_pr_mechanics title: 'codev check pr: merge mechanics' - status: pending + status: in_progress - id: check_pr_forge title: 'codev check pr: forge state and CI checks' status: pending @@ -24,7 +24,7 @@ plan_phases: - id: docs_guidance title: Architect guidance and command documentation status: pending -current_plan_phase: readonly_core +current_plan_phase: check_pr_mechanics gates: spec-approval: status: approved @@ -38,8 +38,8 @@ gates: status: pending verify-approval: status: pending -iteration: 3 -build_complete: true +iteration: 1 +build_complete: false history: - iteration: 1 plan_phase: readonly_core @@ -78,7 +78,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T00:24:36.768Z' +updated_at: '2026-11-24T00:24:38.902Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -86,6 +86,8 @@ context_refreshes: - boundary: plan-phase:readonly_core at: '2026-11-23T22:50:05.115Z' acknowledged_at: '2026-11-23T22:50:10.516Z' + - boundary: plan-phase:check_pr_mechanics + at: '2026-11-24T00:24:38.902Z' force_advanced: phase: readonly_core iteration: 3 From 6a0330096ce2e430c147489ef29a60fbdb9f4114 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 16:25:18 -0800 Subject: [PATCH 42/94] [Spec 1951] Thread log: Phase 2 round 3 and force-advance --- codev/state/spir-1951_thread.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 53f942630..55cb8da43 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -99,3 +99,15 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals - ARCHITECT ORDER (2026-11-24): the review must list what each round found in the allow-list and the stubs, so the owner can see at the pr gate how the read-only claim was tightened. If round 3 asks for changes, tell the architect what it found BEFORE fixing. +- CMAP Phase 2 iter 3: claude APPROVE; codex REQUEST_CHANGES (stub ls-remote args unchecked: another remote + or ext:: transport). Architect approved the fix + an audit of all path/URL-taking stub forms. Audit found the + stub left revision args of diff-family/etc. unchecked (implicit --no-index diff of files outside the repo); + also mirrored the runner for ls-files/status (no args) and for-each-ref (refs/ only). liveTip guard added. + Fixed in aa7e34f58 + c42251ec5 (ext:: case had a /tmp path → repo tmp-residue check failed CI once). +- Phase 2 was FORCE-ADVANCED by porch at the 3-iteration ceiling (8c9715a4b): the round-3 fix was not re-reviewed + by CMAP. Told the architect. +- REVIEW TABLE (architect order): per round, what was found in the allow-list and the stubs — + iter1: stub symbolic-ref write form + fetch by non-SHA; isRefName `.lock` components; fetch lacked --no-tags; + snapshot FETCH_HEAD per-worktree. iter2: stub flags not closed per subcommand (log/diff without guards); + stub gh joined write flags; diff-tree guards; origin HEAD branch validation; tests read real ~/.codev. + iter3: stub ls-remote args; (audit) stub revision args / implicit --no-index; ls-files/status/for-each-ref. From ea0996755f4f519339fffae1131eae2ed2fa1ac7 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 16:26:09 -0800 Subject: [PATCH 43/94] [Spec 1951] Thread log: unreviewed-commits order --- codev/state/spir-1951_thread.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 55cb8da43..0fb1825b8 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -111,3 +111,6 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals snapshot FETCH_HEAD per-worktree. iter2: stub flags not closed per subcommand (log/diff without guards); stub gh joined write flags; diff-tree guards; origin HEAD branch validation; tests read real ~/.codev. iter3: stub ls-remote args; (audit) stub revision args / implicit --no-index; ls-files/status/for-each-ref. +- ARCHITECT ORDER (2026-11-24 00:25): no extra consultation. The PR body (done) and the REVIEW file must list the + commits no reviewer saw (aa7e34f58 and c42251ec5: the stub ls-remote rule, the revision-argument audit, and the + liveTip guard) under a heading of their own, for the pr-phase reviewers. From 7eeec98b80163463148ac00aed2ab68397439341 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 16:31:23 -0800 Subject: [PATCH 44/94] chore(porch): 1951 acknowledge context refresh --- codev/projects/1951-read-only-pr-check-for-archite/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 5d622a4f8..b52683ffe 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -78,7 +78,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T00:24:38.902Z' +updated_at: '2026-11-24T00:31:23.829Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -88,6 +88,7 @@ context_refreshes: acknowledged_at: '2026-11-23T22:50:10.516Z' - boundary: plan-phase:check_pr_mechanics at: '2026-11-24T00:24:38.902Z' + acknowledged_at: '2026-11-24T00:31:23.829Z' force_advanced: phase: readonly_core iteration: 3 From 5bef2f503d8d7a25f461b08d01ac61d7010ca0b3 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 16:53:04 -0800 Subject: [PATCH 45/94] =?UTF-8?q?[Spec=201951][Phase:=20check=5Fpr=5Fmecha?= =?UTF-8?q?nics]=20feat:=20codev=20check=20pr=20=E2=80=94=20merge=20mechan?= =?UTF-8?q?ics?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - `codev check pr [--json]`: anchors on the forge's head SHA and the live base tip (ls-remote), fetching missing objects ref-neutrally - checks head (local branch vs PR head; compared only when origin's branch is the PR head, so a fork's PR is not misread), attribution, trial-merge (merge-tree --write-tree), watched/flagged, overlap, size, to-read - re-reads pr-view and ls-remote at the end; a head or base that moved needs attention, even on a skipped check - `codev check` group: help exits 0, usage errors exit 2, a --json usage error prints the ErrorReport - tests: stub gh/git scenarios (POSIX), real-repo snapshots and races (all platforms), CLI wiring, parsers; fixes a type error in allow-list.test.ts --- codev/state/spir-1951_thread.md | 23 + packages/codev/src/cli.ts | 4 + .../check/__tests__/allow-list.test.ts | 4 +- .../check/__tests__/check-cli.test.ts | 164 ++++++ .../__tests__/check-pr-mechanics.test.ts | 379 ++++++++++++++ .../check/__tests__/check-pr-readonly.test.ts | 278 +++++++++++ .../check/__tests__/helpers/pr-fixture.ts | 130 +++++ .../commands/check/__tests__/imports.test.ts | 8 +- .../check/__tests__/pr-parsers.test.ts | 90 ++++ packages/codev/src/commands/check/index.ts | 95 ++++ packages/codev/src/commands/check/pr.ts | 470 ++++++++++++++++++ packages/codev/src/commands/check/report.ts | 37 +- 12 files changed, 1678 insertions(+), 4 deletions(-) create mode 100644 packages/codev/src/commands/check/__tests__/check-cli.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/check-pr-mechanics.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/helpers/pr-fixture.ts create mode 100644 packages/codev/src/commands/check/__tests__/pr-parsers.test.ts create mode 100644 packages/codev/src/commands/check/index.ts create mode 100644 packages/codev/src/commands/check/pr.ts diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 0fb1825b8..0c62e79cf 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -114,3 +114,26 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals - ARCHITECT ORDER (2026-11-24 00:25): no extra consultation. The PR body (done) and the REVIEW file must list the commits no reviewer saw (aa7e34f58 and c42251ec5: the stub ls-remote rule, the revision-argument audit, and the liveTip guard) under a heading of their own, for the pr-phase reviewers. + +## Phase 3 — check_pr_mechanics +- Owner ruling main-38 'ci-first' (2026-11-24 00:33): no local full suite at all until #1956; per phase run targeted + tests + build + type-check, push, wait for GitHub green on that head, tell the architect, skip on their word. +- Built: `codev check pr [--json]` (pr.ts, index.ts, registered in cli.ts). Checks: head, attribution, trial-merge, + watched, overlap, size, to-read; end-of-run re-read of pr-view then ls-remote (head/base movement). +- Live run on PR #1958 from this worktree: CLEAR, exit 0, ~5 s; overlap found 2 files main also changed + (doctor.test.ts, lib/config.ts). +- Choices / deviations to note in the review: + - `pr.baseTip` is `string | null` (null when ls-remote failed or origin lacks the base); the spec typed it `string`. + null follows the spec's own convention (`draft`, `localBranch`) instead of a sentinel. + - `head` compares the local branch only when origin's branch of that name IS the PR head. Otherwise info + "origin's main is at X, not the PR head (a fork's PR, or the branch moved)": a fork PR from its own `main` would otherwise read as + "local main diverged (N not pushed)". Additive details: `relation`, `behindPr`, `originBranchSha`. + - Behind the PR head is ok; ahead or diverged is attention ("not pushed"). An ok head prints in the header + (as the spec sample does); a head needing attention gets its own line. + - A base or head that moves (or cannot be re-read) also overrides a `check.skip` of its carrier check, so a + CLEAR always describes live tips. + - Lists on a check line are cut by width (72 chars, `fitList`), not by count. + - Usage errors: JSON ErrorReport only for errors on a subcommand (`pr`); group-level ones (unknown subcommand) + have no command name, so they stay human-only on stderr. The CLI deps take argv explicitly (commander's + rawArgs is untyped/internal). + - Fixed in place: a type error in Phase 2's allow-list.test.ts (readonly tuple), found type-checking the tests. diff --git a/packages/codev/src/cli.ts b/packages/codev/src/cli.ts index e02841212..a17a510d8 100644 --- a/packages/codev/src/cli.ts +++ b/packages/codev/src/cli.ts @@ -19,6 +19,7 @@ import { handleStats } from './commands/consult/stats.js'; import { cli as porchCli } from './commands/porch/index.js'; import { importCommand } from './commands/import.js'; import { generateImage } from './commands/generate-image.js'; +import { buildCheckCommand } from './commands/check/index.js'; import { version } from './version.js'; import { isCodevEntrypoint } from './lib/cli-entry.js'; import { findWorkspaceRoot } from './agent-farm/utils/index.js'; @@ -62,6 +63,9 @@ program } }); +// Check command group: read-only merge, deploy and worktree checks (Spec 1951) +program.addCommand(buildCheckCommand()); + // Init command program .command('init [project-name]') diff --git a/packages/codev/src/commands/check/__tests__/allow-list.test.ts b/packages/codev/src/commands/check/__tests__/allow-list.test.ts index 4ff112ac5..bc4a75f69 100644 --- a/packages/codev/src/commands/check/__tests__/allow-list.test.ts +++ b/packages/codev/src/commands/check/__tests__/allow-list.test.ts @@ -4,7 +4,7 @@ import { describe, expect, it } from 'vitest'; import { assertConceptAllowed, assertGitArgvAllowed, RunnerRefusal } from '../allow-list.js'; -import { allowedForms, argvOf as argv, FETCH_GLOBALS, OFF_GRAMMAR_FORMS, SHA, SHA2, WRITE_FORMS } from './helpers/git-forms.js'; +import { allowedForms, argvOf as argv, FETCH_GLOBALS, OFF_GRAMMAR_FORMS, SHA, SHA2, WRITE_FORMS, type GitForm } from './helpers/git-forms.js'; const ABS = process.platform === 'win32' ? 'C:\\repo' : '/repo'; const ALLOWED = allowedForms(ABS); @@ -48,7 +48,7 @@ describe('Spec 1951 — read-only git allow-list', () => { }); describe('refuses the file-writing and program-running flags on every allowed subcommand', () => { - const cases = ALLOWED.flatMap((f) => BAD_FLAGS.map((flag) => [`${f.sub} ${flag}`, { ...f, rest: [flag, ...f.rest] }] as const)); + const cases = ALLOWED.flatMap((f) => BAD_FLAGS.map((flag): [string, GitForm] => [`${f.sub} ${flag}`, { ...f, rest: [flag, ...f.rest] }])); it.each(cases)('%s', (_name, f) => { expect(() => assertGitArgvAllowed(argv(f))).toThrow(RunnerRefusal); }); diff --git a/packages/codev/src/commands/check/__tests__/check-cli.test.ts b/packages/codev/src/commands/check/__tests__/check-cli.test.ts new file mode 100644 index 000000000..717334b5c --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/check-cli.test.ts @@ -0,0 +1,164 @@ +/** + * Spec 1951 — the `codev check` command group: commander wiring and exit codes. + * + * Help exits 0, every usage error exits 2 (not commander's 1), and with `--json` a usage + * error on a subcommand prints its `ErrorReport` on stdout. Parsed through `parseAsync` + * with an injected exit, so nothing here ends the test process. + */ + +import { CommanderError } from 'commander'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { buildCheckCommand, exitCodeForCommander } from '../index.js'; +import { useFakeHome } from './helpers/fake-home.js'; +import { createFixture, type Fixture } from './helpers/git-fixture.js'; +import { prView, prViewOverride, pushBranch, writeConfig } from './helpers/pr-fixture.js'; + +class Exited extends Error { + constructor(public readonly code: number) { + super(`exit ${code}`); + } +} + +interface Outcome { + code: number | undefined; + stdout: string; + stderr: string; +} + +async function runCli(args: string[], options: { cwd?: string; env?: Record } = {}): Promise { + const out: string[] = []; + const err: string[] = []; + let code: number | undefined; + const group = buildCheckCommand({ + exit: (c) => { + code = c; + throw new Exited(c); + }, + stdout: (s) => void out.push(s), + stderr: (s) => void err.push(s), + cwd: () => options.cwd ?? process.cwd(), + argv: () => args, + env: options.env, + timeoutMs: 20_000, + }); + try { + await group.parseAsync(args, { from: 'user' }); + } catch (e) { + // The exit callback rethrows commander's own error after recording the code. + if (!(e instanceof Exited) && !(e instanceof CommanderError)) throw e; + } + return { code, stdout: out.join(''), stderr: err.join('') }; +} + +useFakeHome(); + +describe('Spec 1951 — codev check: commander wiring', () => { + it('maps commander exits: help and version 0, usage errors 2', () => { + const e = (exitCode: number, code: string) => new CommanderError(exitCode, code, ''); + expect(exitCodeForCommander(e(0, 'commander.helpDisplayed'))).toBe(0); + expect(exitCodeForCommander(e(0, 'commander.version'))).toBe(0); + expect(exitCodeForCommander(e(0, 'commander.help'))).toBe(0); + expect(exitCodeForCommander(e(1, 'commander.help'))).toBe(2); + expect(exitCodeForCommander(e(1, 'commander.unknownOption'))).toBe(2); + expect(exitCodeForCommander(e(1, 'commander.missingArgument'))).toBe(2); + }); + + it.each([[['--help']], [['pr', '--help']], [['help', 'pr']]])('%j exits 0 and prints help on stdout', async (args) => { + const outcome = await runCli(args); + expect(outcome.code).toBe(0); + expect(outcome.stdout).toMatch(/Usage: check/); + }); + + it('lists pr with its argument and --json', async () => { + expect((await runCli(['--help'])).stdout).toMatch(/pr \[options\] /); + expect((await runCli(['pr', '--help'])).stdout).toMatch(/--json/); + }); + + it.each([ + ['no subcommand', []], + ['an unknown subcommand', ['merge', '7']], + ['a missing PR number', ['pr']], + ['an extra argument', ['pr', '7', '8']], + ['an unknown option', ['pr', '7', '--jsn']], + ])('%s is a usage error: exit 2', async (_name, args) => { + const outcome = await runCli(args); + expect(outcome.code).toBe(2); + expect(outcome.stdout).toBe(''); + expect(outcome.stderr).not.toBe(''); + }); + + it('with --json, a usage error prints the ErrorReport on stdout', async () => { + const outcome = await runCli(['pr', '7', '--jsn', '--json']); + expect(outcome.code).toBe(2); + expect(JSON.parse(outcome.stdout)).toEqual({ schema: 1, command: 'pr', error: { message: expect.stringMatching(/^unknown option '--jsn'/) } }); + }); + + it('an invalid PR number is exit 2: on stderr, or as the ErrorReport with --json', async () => { + const human = await runCli(['pr', '12a']); + expect(human).toMatchObject({ code: 2, stdout: '' }); + expect(human.stderr).toBe('codev check pr: invalid PR number "12a": expected a positive integer\n'); + + const json = await runCli(['pr', '12a', '--json']); + expect(json.code).toBe(2); + expect(JSON.parse(json.stdout)).toEqual({ + schema: 1, + command: 'pr', + error: { message: 'invalid PR number "12a": expected a positive integer' }, + }); + }); +}); + +describe('Spec 1951 — codev check pr through the CLI', { timeout: 30_000 }, () => { + let fx: Fixture; + + beforeEach(() => { + fx = createFixture(); + const forge = prViewOverride(fx); + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + writeConfig(fx, { forge: { 'pr-view': forge.script } }); + }); + + afterEach(() => { + fx.cleanup(); + }); + + it('prints the summary and exits with the verdict', async () => { + const outcome = await runCli(['pr', '7'], { cwd: fx.main, env: fx.env }); + expect(outcome.code).toBe(0); + expect(outcome.stdout.split('\n')[0]).toBe('CLEAR PR #7 — ready to recommend'); + expect(outcome.stderr).toBe(''); + }); + + it('--json prints exactly one PrReport object', async () => { + const outcome = await runCli(['pr', '7', '--json'], { cwd: fx.main, env: fx.env }); + expect(outcome.code).toBe(0); + const report = JSON.parse(outcome.stdout); + expect(report).toMatchObject({ schema: 1, command: 'pr', verdict: 'clear', pr: { number: 7 } }); + expect(report.checks.map((c: { id: string }) => c.id)).toEqual(['head', 'attribution', 'trial-merge', 'watched', 'overlap', 'size', 'to-read']); + }); +}); + +describe('Spec 1951 — codev --help lists check', () => { + let exit: ReturnType; + let write: ReturnType; + + beforeEach(() => { + exit = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => { + throw new Exited(code ?? 0); + }) as typeof process.exit); + write = vi.spyOn(process.stdout, 'write').mockImplementation(() => true); + }); + + afterEach(() => { + exit.mockRestore(); + write.mockRestore(); + }); + + it('registers the group on the codev program', async () => { + const { run } = await import('../../../cli.js'); + await expect(run(['--help'])).rejects.toThrow(Exited); + const printed = write.mock.calls.map((call: unknown[]) => String(call[0])).join(''); + expect(printed).toMatch(/\n {2}check +Read-only checks/); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/check-pr-mechanics.test.ts b/packages/codev/src/commands/check/__tests__/check-pr-mechanics.test.ts new file mode 100644 index 000000000..74b762030 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/check-pr-mechanics.test.ts @@ -0,0 +1,379 @@ +/** + * Spec 1951 — `codev check pr`: merge mechanics, scenario by scenario (POSIX). + * + * The shipped github `pr-view` script runs against a stub `gh` that answers from fixtures; + * a stub `git` first on PATH records every git call and passes it to the real git, so each + * test also proves that nothing off the read-only list ran. Every scenario runs on a real + * repository with a bare origin, and the repository state is compared before and after. + */ + +import { spawn as realSpawn } from 'node:child_process'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { RunnerRefusal } from '../allow-list.js'; +import { checkPr, renderPrHuman } from '../pr.js'; +import type { Check, CommandOptions, ErrorReport, PrReport } from '../report.js'; +import { createRunner, type SpawnFn } from '../runner.js'; +import { useFakeHome } from './helpers/fake-home.js'; +import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { otherClone, PR_BRANCH, PR_NUMBER, PR_VIEW_FIELDS, prView, pushBranch, pushFromElsewhere, writeConfig } from './helpers/pr-fixture.js'; +import { createStubBin, type StubBin } from './helpers/stub-bin.js'; + +const isWindows = process.platform === 'win32'; + +useFakeHome(); + +let fx: Fixture; +let stub: StubBin; +let uninstall: () => void; + +beforeEach(() => { + fx = createFixture(); + stub = createStubBin(path.join(fx.root, 'bin')); + uninstall = stub.install(); +}); + +afterEach(() => { + uninstall(); + fx.cleanup(); +}); + +function answerPrView(view: Record, number = PR_NUMBER): void { + stub.answer(['pr', 'view', String(number), '--json', PR_VIEW_FIELDS], JSON.stringify(view)); +} + +async function run(extra: Partial = {}, number = String(PR_NUMBER)) { + return checkPr(number, { cwd: fx.main, env: { ...fx.env, ...stub.env }, timeoutMs: 20_000, ...extra }); +} + +async function runReport(extra: Partial = {}): Promise<{ report: PrReport; exitCode: number }> { + const result = await run(extra); + if ('error' in result.report) throw new Error(`unexpected exit 2: ${result.report.error.message}`); + return { report: result.report, exitCode: result.exitCode }; +} + +function byId(report: PrReport, id: string): Check { + const found = report.checks.find((c) => c.id === id); + if (!found) throw new Error(`no ${id} check`); + return found; +} + +function statuses(report: PrReport): Record { + return Object.fromEntries(report.checks.map((c) => [c.id, c.status])); +} + +/** Run, and assert the repository is untouched and every subprocess stayed on the read-only list. */ +async function runReadOnly(extra: Partial = {}) { + const before = snapshotRepoState(fx, fx.main); + const result = await runReport(extra); + expect(snapshotRepoState(fx, fx.main)).toEqual(before); + expect(stub.violations()).toEqual([]); + return result; +} + +// Each case builds real repositories and runs the command once or twice. +describe.skipIf(isWindows)('Spec 1951 — check pr: merge mechanics (stub gh and git)', { timeout: 30_000 }, () => { + it('reports a clean PR: exact head, live base, every mechanics check', async () => { + const { head } = pushBranch(fx, [{ files: { 'src/a.ts': 'export const a = 1;\n' }, message: 'add a' }]); + answerPrView(prView(head)); + const base = fx.git(fx.main, 'rev-parse', 'main').trim(); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(0); + expect(report.verdict).toBe('clear'); + expect(statuses(report)).toEqual({ + head: 'ok', + attribution: 'off', + 'trial-merge': 'ok', + watched: 'ok', + overlap: 'info', + size: 'info', + 'to-read': 'info', + }); + expect(report.pr).toMatchObject({ number: 7, head, baseRef: 'main', baseTip: base, headRef: PR_BRANCH, draft: false, state: 'OPEN' }); + expect(report.pr.localBranch).toEqual({ name: PR_BRANCH, sha: head }); + expect(byId(report, 'trial-merge').details).toEqual({ baseTip: base, head, conflicts: 0, files: [] }); + expect(byId(report, 'size').details).toEqual({ additions: 1, deletions: 0, files: 1 }); + // The anchoring read and the end-of-run re-read. + expect(stub.ghCalls()).toEqual([`pr view 7 --json ${PR_VIEW_FIELDS}`, `pr view 7 --json ${PR_VIEW_FIELDS}`]); + expect(stub.gitCalls().some((call) => call.startsWith('merge-tree --write-tree'))).toBe(true); + + const human = renderPrHuman(report); + expect(human.split('\n')[0]).toBe('CLEAR PR #7 — ready to recommend'); + expect(human).toContain(`head ${head.slice(0, 7)} (local ${PR_BRANCH} matches)`); + expect(human).toContain(`base main @ ${base.slice(0, 7)} (origin, live)`); + }); + + it('Scenario 2: a conflicting trial merge lists the files and their count; nothing moves', async () => { + const { head } = pushBranch(fx, [{ files: { 'README.md': 'ours\n', 'src/x.ts': 'x\n' }, message: 'change readme' }]); + fx.commit(fx.main, { 'README.md': 'theirs\n' }, 'main changes readme'); + fx.git(fx.main, 'push', '-q', 'origin', 'main'); + answerPrView(prView(head)); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(1); + const merge = byId(report, 'trial-merge'); + expect(merge.status).toBe('attention'); + expect(merge.details).toMatchObject({ conflicts: 1, files: ['README.md'] }); + expect(merge.summary).toMatch(/^1 conflicting file merging into main @ [0-9a-f]{7}: README\.md$/); + expect(renderPrHuman(report).split('\n')[0]).toBe('ATTENTION PR #7 — trial merge (conflicts)'); + // The base also changed README.md since the branch point. + expect(byId(report, 'overlap').details).toEqual({ files: ['README.md'] }); + }); + + it('Scenario 3: a stale local origin/main is not used; the live tip conflicts', async () => { + const { head } = pushBranch(fx, [{ files: { 'README.md': 'ours\n' }, message: 'change readme' }]); + const stale = fx.git(fx.main, 'rev-parse', 'refs/remotes/origin/main').trim(); + const live = pushFromElsewhere(fx, 'main', { 'README.md': 'theirs\n' }); + answerPrView(prView(head)); + + const { report } = await runReadOnly(); + + expect(report.pr.baseTip).toBe(live); + expect(byId(report, 'trial-merge')).toMatchObject({ status: 'attention', details: { baseTip: live, conflicts: 1 } }); + expect(fx.git(fx.main, 'rev-parse', 'refs/remotes/origin/main').trim()).toBe(stale); + }); + + it('Scenario 4: a head that is not local is fetched ref-neutrally, then checked', async () => { + const head = pushFromElsewhere(fx, PR_BRANCH, { 'src/remote.ts': 'r\n' }); + expect(() => fx.git(fx.main, 'cat-file', '-e', `${head}^{commit}`)).toThrow(); + answerPrView(prView(head)); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(0); + expect(byId(report, 'head')).toMatchObject({ status: 'ok', details: { relation: 'absent' } }); + expect(byId(report, 'trial-merge').status).toBe('ok'); + expect(fx.git(fx.main, 'cat-file', '-t', head).trim()).toBe('commit'); + expect(stub.gitCalls().filter((c) => c.includes(' fetch '))).toEqual([ + `-c gc.auto=0 -c maintenance.auto=false fetch --no-write-fetch-head --refmap= --no-tags --no-recurse-submodules --quiet origin ${head}`, + ]); + }); + + it('Scenario 5: a head that cannot be fetched leaves the head checks not run (exit 1)', async () => { + const missing = 'e'.repeat(40); + answerPrView(prView(missing, { headRefName: 'builder/spir-8' })); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(1); + for (const id of ['trial-merge', 'watched', 'overlap', 'size', 'to-read']) { + expect(byId(report, id), id).toMatchObject({ status: 'not-run', reason: expect.stringMatching(/^eeeeeee not available locally \(fetch failed/) }); + } + expect(report.checks.some((c) => c.status === 'ok' && c.id !== 'head')).toBe(false); + }); + + it('a base branch origin does not have leaves the base checks not run', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + answerPrView(prView(head, { baseRefName: 'release' })); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(1); + expect(report.pr.baseTip).toBeNull(); + expect(byId(report, 'trial-merge')).toMatchObject({ status: 'not-run', reason: 'origin has no branch release' }); + expect(renderPrHuman(report)).toContain('base release (live tip not read)'); + }); + + it('Scenario 6: attribution in a commit and in the description is reported by place; base commits are not scanned', async () => { + writeConfig(fx, { check: { attribution: ['^\\s*Co-Authored-By:'] } }); + fx.commit(fx.main, { 'old.txt': 'old\n' }, 'already on main\n\nCo-Authored-By: Someone '); + fx.git(fx.main, 'push', '-q', 'origin', 'main'); + const { head } = pushBranch(fx, [ + { files: { 'a.txt': 'a\n' }, message: 'clean commit' }, + { files: { 'b.txt': 'b\n' }, message: 'add b\n\nCo-Authored-By: Claude ' }, + ]); + answerPrView(prView(head, { body: 'Summary\n\nco-authored-by: a bot\nFixes #7' })); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(1); + const attribution = byId(report, 'attribution'); + expect(attribution.status).toBe('attention'); + expect(attribution.details).toEqual({ + patterns: ['^\\s*Co-Authored-By:'], + hits: [ + { where: 'description', line: 3, text: 'co-authored-by: a bot' }, + { where: 'commit', sha: head, line: 3, text: 'Co-Authored-By: Claude ' }, + ], + commitsScanned: 2, + }); + expect(attribution.summary).toBe(`2 lines: description line 3, commit ${head.slice(0, 7)} "Co-Authored-By: Claude { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'clean' }]); + answerPrView(prView(head)); + expect(byId((await runReadOnly()).report, 'attribution')).toMatchObject({ + status: 'off', + summary: 'no patterns configured (check.attribution)', + }); + + writeConfig(fx, { check: { attribution: ['Generated with \\[Claude Code\\]'] } }); + expect(byId((await runReadOnly()).report, 'attribution')).toMatchObject({ status: 'ok', summary: 'none in the description or 1 commit' }); + }); + + it('Scenario 8: a flagged watched file needs attention; an unflagged one is info', async () => { + writeConfig(fx, { check: { flag: ['CLAUDE.md'] } }); + const { head } = pushBranch(fx, [ + { files: { 'CLAUDE.md': 'rules\n', 'codev/roles/architect.md': 'role\n', 'src/a.ts': 'a\n' }, message: 'instructions' }, + ]); + answerPrView(prView(head)); + + const { report } = await runReadOnly(); + + const watched = byId(report, 'watched'); + expect(watched).toMatchObject({ + status: 'attention', + summary: 'CLAUDE.md (flagged), codev/roles/architect.md', + details: { files: [{ path: 'CLAUDE.md', flagged: true }, { path: 'codev/roles/architect.md', flagged: false }] }, + }); + expect(renderPrHuman(report).split('\n')[0]).toBe('ATTENTION PR #7 — watched (flagged)'); + + writeConfig(fx, { check: { flag: ['src/**'] } }); + // check.flag applies only to watched files: src/a.ts is flagged but not watched. + expect(byId((await runReadOnly()).report, 'watched')).toMatchObject({ status: 'info' }); + }); + + it('Scenario 9: porch state and lockfiles are not for reading; check.notForReading replaces the default', async () => { + const big = Array.from({ length: 30 }, (_, i) => `line ${i}`).join('\n'); + const { head } = pushBranch(fx, [ + { + files: { + 'src/big.ts': `${big}\n`, + 'src/small.ts': 'small\n', + 'pnpm-lock.yaml': 'lock\n', + 'packages/x/package-lock.json': '{}\n', + 'codev/projects/7-feature/status.yaml': 'phase: review\n', + 'codev/state/spir-7_thread.md': 'log\n', + }, + message: 'work', + }, + ]); + answerPrView(prView(head)); + + const first = byId((await runReadOnly()).report, 'to-read'); + expect(first.details).toEqual({ + files: [ + { path: 'src/big.ts', additions: 30, deletions: 0 }, + { path: 'src/small.ts', additions: 1, deletions: 0 }, + ], + excluded: ['codev/projects/7-feature/status.yaml', 'codev/state/spir-7_thread.md', 'packages/x/package-lock.json', 'pnpm-lock.yaml'], + }); + expect(first.summary).toBe('2 files (4 not for reading): src/big.ts, src/small.ts'); + + writeConfig(fx, { check: { notForReading: ['src/small.ts'] } }); + const replaced = byId((await runReadOnly()).report, 'to-read'); + expect((replaced.details.files as Array<{ path: string }>).map((f) => f.path)).toEqual([ + 'src/big.ts', + 'codev/projects/7-feature/status.yaml', + 'codev/state/spir-7_thread.md', + 'packages/x/package-lock.json', + 'pnpm-lock.yaml', + ]); + expect(replaced.details.excluded).toEqual(['src/small.ts']); + }); + + it('Scenario 12: a local branch ahead of the PR head needs attention (not pushed)', async () => { + const { dir, head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'pushed' }]); + const local = fx.commit(dir, { 'b.txt': 'b\n' }, 'not pushed'); + answerPrView(prView(head)); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(1); + expect(byId(report, 'head')).toMatchObject({ + status: 'attention', + summary: `local ${PR_BRANCH} is 1 commit ahead of the PR head (not pushed)`, + details: { forgeHead: head, localBranchSha: local, aheadOfPr: 1, relation: 'ahead' }, + }); + expect(report.pr.localBranch).toEqual({ name: PR_BRANCH, sha: local }); + const human = renderPrHuman(report); + expect(human.split('\n')[0]).toBe('ATTENTION PR #7 — head (not pushed)'); + expect(human).toMatch(/\n {2}ATTN +head +local builder\/spir-7 is 1 commit ahead/); + }); + + it('a local branch behind the PR head is fine; a diverged one needs attention', async () => { + const { dir, head: first } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'first' }]); + const head = fx.commit(dir, { 'b.txt': 'b\n' }, 'second'); + fx.git(dir, 'push', '-q', 'origin', PR_BRANCH); + fx.git(dir, 'reset', '-q', '--hard', first); + answerPrView(prView(head)); + expect(byId((await runReadOnly()).report, 'head')).toMatchObject({ status: 'ok', details: { relation: 'behind', behindPr: 1 } }); + + fx.commit(dir, { 'c.txt': 'c\n' }, 'local only'); + expect(byId((await runReadOnly()).report, 'head')).toMatchObject({ status: 'attention', details: { relation: 'diverged', aheadOfPr: 1, behindPr: 1 } }); + }); + + it("a fork's PR is not compared with an unrelated local branch of the same name", async () => { + // A fork's PR from its own `main`: the head is reachable on origin only through + // refs/pull/7/head, as GitHub keeps it, and our local main has moved on since. + const other = otherClone(fx); + fx.git(other, 'fetch', '-q', 'origin'); + fx.git(other, 'checkout', '-q', '-B', 'fork-main', 'origin/main'); + const head = fx.commit(other, { 'src/fork.ts': 'f\n' }, 'fork work'); + fx.git(other, 'push', '-q', 'origin', 'HEAD:refs/pull/7/head'); + fx.commit(fx.main, { 'later.txt': 'later\n' }, 'main moves on'); + fx.git(fx.main, 'push', '-q', 'origin', 'main'); + const originMain = fx.git(fx.main, 'rev-parse', 'main').trim(); + answerPrView(prView(head, { headRefName: 'main' })); + + const { report } = await runReadOnly(); + + expect(byId(report, 'head')).toMatchObject({ + status: 'info', + summary: `origin's main is at ${originMain.slice(0, 7)}, not the PR head (a fork's PR, or the branch moved): local main not compared`, + details: { relation: 'not-origin-branch', originBranchSha: originMain }, + }); + expect(byId(report, 'trial-merge').status).toBe('ok'); + expect(report.verdict).toBe('clear'); + }); + + it('Scenario 25: pr-view without headRefOid is exit 2 naming the concept and the field', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + const view = prView(head); + delete view.headRefOid; + answerPrView(view); + + const result = await run(); + + expect(result.exitCode).toBe(2); + expect((result.report as ErrorReport).error.message).toBe('could not read PR #7: pr-view did not return headRefOid (provider github)'); + }); + + it('a PR the forge cannot read is exit 2 naming the concept', async () => { + const result = await run({}, '8'); + expect(result.exitCode).toBe(2); + expect((result.report as ErrorReport).error.message).toMatch(/^could not read PR #8: pr-view failed: stub gh: no answer for: pr view 8 /); + }); + + it('Scenario 27: git older than 2.38 leaves the trial merge not run, naming the version', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + answerPrView(prView(head)); + const oldGit: SpawnFn = (command, args, options) => + args.length === 1 && args[0] === 'version' + ? realSpawn(process.execPath, ['-e', 'process.stdout.write("git version 2.37.1\\n")'], options) + : realSpawn(command, args, options); + + const { report, exitCode } = await runReadOnly({ spawn: oldGit }); + + expect(exitCode).toBe(1); + expect(byId(report, 'trial-merge')).toMatchObject({ status: 'not-run', reason: 'requires git 2.38+ (found 2.37.1)' }); + expect(stub.gitCalls().some((c) => c.startsWith('merge-tree'))).toBe(false); + }); + + it('Scenario 22: a write is refused by the runner, and a write in a concept is caught by the stub', async () => { + const runner = createRunner({ cwd: fx.main, workspaceRoot: fx.main, env: { ...fx.env, ...stub.env } }); + await expect(runner.git(['update-ref', 'refs/heads/x', 'a'.repeat(40)])).rejects.toThrow(RunnerRefusal); + await expect(runner.forge('pr-merge')).rejects.toThrow(RunnerRefusal); + expect(stub.gitCalls().some((c) => c.startsWith('update-ref'))).toBe(false); + + // A project override is trusted by the runner; in tests the stub still sees what it runs. + writeConfig(fx, { forge: { 'pr-view': 'gh pr merge "$CODEV_PR_NUMBER"; gh api -X POST repos/o/r/merges' } }); + const result = await run(); + expect(result.exitCode).toBe(2); + expect(stub.violations()).toEqual(['gh pr merge 7 :: pr merge', 'gh api -X POST repos/o/r/merges :: api write flag -X']); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts b/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts new file mode 100644 index 000000000..829f1dfff --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts @@ -0,0 +1,278 @@ +/** + * Spec 1951 — `codev check pr` against real repositories, on every platform. + * + * The forge comes from a `pr-view` concept override (a `.sh` script Git Bash runs on + * Windows), so neither `gh` nor a network is needed. These tests prove that no ref, `HEAD`, + * index byte, `FETCH_HEAD` or status line changes (Scenario 23), that a head or base moving + * during the run is caught (Scenario 11), that a hanging anchor read is exit 2 (Scenario + * 12b), and that the command reports the same from a builder worktree as from the main + * checkout. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { checkPr } from '../pr.js'; +import type { Check, CommandOptions, ErrorReport, PrReport } from '../report.js'; +import type { SpawnFn } from '../runner.js'; +import { useFakeHome } from './helpers/fake-home.js'; +import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { + otherClone, + PR_BRANCH, + prView, + prViewOverride, + pushBranch, + pushFromElsewhere, + shPath, + writeConfig, + type PrViewOverride, +} from './helpers/pr-fixture.js'; + +useFakeHome(); + +let fx: Fixture; +let forge: PrViewOverride; + +beforeEach(() => { + fx = createFixture(); + forge = prViewOverride(fx); +}); + +afterEach(() => { + fx.cleanup(); +}); + +function configure(check: Record = {}): string { + return writeConfig(fx, { forge: { 'pr-view': forge.script }, check }); +} + +async function run(extra: Partial = {}, number = '7') { + return checkPr(number, { cwd: fx.main, env: fx.env, timeoutMs: 20_000, ...extra }); +} + +async function runReport(extra: Partial = {}): Promise { + const result = await run(extra); + if ('error' in result.report) throw new Error(`unexpected exit 2: ${result.report.error.message}`); + return result.report; +} + +function byId(report: PrReport, id: string): Check { + const found = report.checks.find((c) => c.id === id); + if (!found) throw new Error(`no ${id} check`); + return found; +} + +function withoutTime(report: PrReport): Omit { + const { generatedAt: _ignored, ...rest } = report; + return rest; +} + +interface SnapshotCase { + name: string; + /** Build the PR; returns its head. */ + setup: () => string; + trialMerge: 'ok' | 'attention'; +} + +const SNAPSHOT_CASES: SnapshotCase[] = [ + { + name: 'a clean run', + setup: () => pushBranch(fx, [{ files: { 'src/a.ts': 'a\n' }, message: 'a' }]).head, + trialMerge: 'ok', + }, + { + name: 'a conflicting trial merge', + setup: () => { + const { head } = pushBranch(fx, [{ files: { 'README.md': 'ours\n' }, message: 'ours' }]); + fx.commit(fx.main, { 'README.md': 'theirs\n' }, 'theirs'); + fx.git(fx.main, 'push', '-q', 'origin', 'main'); + return head; + }, + trialMerge: 'attention', + }, + { + name: 'a stale local origin/main', + setup: () => { + const { head } = pushBranch(fx, [{ files: { 'README.md': 'ours\n' }, message: 'ours' }]); + pushFromElsewhere(fx, 'main', { 'README.md': 'theirs\n' }); + return head; + }, + trialMerge: 'attention', + }, + { + name: 'a head that must be fetched', + setup: () => pushFromElsewhere(fx, PR_BRANCH, { 'src/remote.ts': 'r\n' }), + trialMerge: 'ok', + }, +]; + +// Each case builds real repositories and runs the command at least once. +describe('Spec 1951 — check pr on real repositories', { timeout: 30_000 }, () => { + it.each(SNAPSHOT_CASES)('Scenario 23: $name leaves refs, HEAD, index, FETCH_HEAD and status unchanged', async (c) => { + const head = c.setup(); + forge.answer(prView(head)); + configure(); + const before = snapshotRepoState(fx, fx.main); + + const report = await runReport(); + + expect(snapshotRepoState(fx, fx.main)).toEqual(before); + expect(report.pr.head).toBe(head); + expect(byId(report, 'trial-merge').status).toBe(c.trialMerge); + expect(fx.git(fx.main, 'cat-file', '-t', head).trim()).toBe('commit'); + }); + + it('a linked worktree is left unchanged too', async () => { + const { dir, head } = pushBranch(fx, [{ files: { 'README.md': 'ours\n' }, message: 'ours' }]); + pushFromElsewhere(fx, 'main', { 'README.md': 'theirs\n' }); + forge.answer(prView(head)); + configure(); + const before = snapshotRepoState(fx, dir); + + await runReport({ cwd: dir }); + + expect(snapshotRepoState(fx, dir)).toEqual(before); + }); + + it('reports the same from a builder worktree as from the main checkout, with the main checkout’s config', async () => { + const { dir, head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a\n\nCo-Authored-By: Bot ' }]); + forge.answer(prView(head)); + configure({ attribution: ['^Co-Authored-By:'] }); + + const fromMain = await runReport(); + const fromWorktree = await runReport({ cwd: dir }); + const fromSubdirectory = await runReport({ cwd: path.join(fx.main, '.codev') }); + + expect(byId(fromMain, 'attribution').status).toBe('attention'); + expect(withoutTime(fromWorktree)).toEqual(withoutTime(fromMain)); + expect(withoutTime(fromSubdirectory)).toEqual(withoutTime(fromMain)); + }); + + it('Scenario 11: a head that moves during the run needs attention, naming both SHAs', async () => { + const { dir, head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + const next = fx.commit(dir, { 'b.txt': 'b\n' }, 'b'); + forge.answer(prView(head)); + forge.answerOn(2, prView(next)); + configure(); + + const report = await runReport(); + + expect(forge.calls()).toBe(2); + expect(report.verdict).toBe('attention'); + const headCheck = byId(report, 'head'); + expect(headCheck.status).toBe('attention'); + expect(headCheck.details.movedTo).toBe(next); + expect(headCheck.summary.split('\n')).toContain(`head moved during check (${head.slice(0, 7)} → ${next.slice(0, 7)}); re-run`); + }); + + it('Scenario 11: a base that moves during the run needs attention on the trial merge', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + const before = fx.git(fx.main, 'rev-parse', 'main').trim(); + const other = otherClone(fx); + fx.git(other, 'checkout', '-q', '-B', 'main', 'origin/main'); + const later = fx.commit(other, { 'later.txt': 'later\n' }, 'later on main'); + forge.answer(prView(head)); + // The re-read of pr-view comes before the re-read of the base, so a push here moves it. + forge.runOn(2, `git -C '${shPath(other)}' push -q origin main`); + configure(); + + const report = await runReport(); + + const merge = byId(report, 'trial-merge'); + expect(merge.status).toBe('attention'); + expect(merge.details).toMatchObject({ baseTip: before, movedTo: later }); + expect(merge.summary.split('\n')).toEqual([ + `clean into main @ ${before.slice(0, 7)}`, + `base moved during check (${before.slice(0, 7)} → ${later.slice(0, 7)}); re-run`, + ]); + }); + + it('a head that cannot be re-read at the end is not reported as confirmed', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + forge.answerOn(2, 'not json'); + configure(); + + const report = await runReport(); + + expect(byId(report, 'head')).toMatchObject({ status: 'attention', details: { recheck: 'pr-view returned invalid output' } }); + expect(report.verdict).toBe('attention'); + }); + + it('Scenario 12b: a hanging anchoring pr-view is exit 2 within the time limit', async () => { + const hang = path.join(fx.root, 'forge', 'hang.sh'); + fs.writeFileSync(hang, '#!/bin/sh\nexec sleep 10\n', { mode: 0o755 }); + writeConfig(fx, { forge: { 'pr-view': hang } }); + const started = Date.now(); + + const result = await run({ timeoutMs: 500 }); + + expect(result.exitCode).toBe(2); + expect((result.report as ErrorReport).error.message).toMatch(/^could not read PR #7: pr-view timed out after 500ms \(provider github, override in /); + expect(Date.now() - started).toBeLessThan(8_000); + }); + + it('Scenario 25: an override without headRefOid is exit 2 naming the concept, the field and the file', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + const view = prView(head); + delete view.headRefOid; + forge.answer(view); + const file = configure(); + + const result = await run(); + + expect(result).toEqual({ + exitCode: 2, + report: { + schema: 1, + command: 'pr', + error: { message: `could not read PR #7: pr-view did not return headRefOid (provider github, override in ${file})` }, + }, + }); + }); + + it('a headRefOid that is not a full SHA is exit 2', async () => { + forge.answer(prView('abc1234')); + configure(); + const result = await run(); + expect(result.exitCode).toBe(2); + expect((result.report as ErrorReport).error.message).toContain('pr-view returned headRefOid "abc1234", not a full commit SHA'); + }); + + it('check.skip replaces a check by name; a base that moves still shows on a skipped trial merge', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + const other = otherClone(fx); + fx.git(other, 'checkout', '-q', '-B', 'main', 'origin/main'); + fx.commit(other, { 'later.txt': 'later\n' }, 'later'); + forge.answer(prView(head)); + configure({ skip: ['size', 'trial-merge'] }); + + const quiet = await runReport(); + expect(byId(quiet, 'size')).toMatchObject({ status: 'skip', summary: 'skipped (check.skip)' }); + expect(byId(quiet, 'trial-merge').status).toBe('skip'); + expect(quiet.verdict).toBe('clear'); + + forge.runOn(forge.calls() + 2, `git -C '${shPath(other)}' push -q origin main`); + const moved = await runReport(); + expect(byId(moved, 'trial-merge')).toMatchObject({ status: 'attention', summary: expect.stringMatching(/^base moved during check/) }); + }); + + it('Scenario 28a: an invalid PR number is exit 2 before any subprocess starts', async () => { + const spawn = vi.fn(); + for (const bad of ['12a', '0', '-1', '7.5', '']) { + const result = await checkPr(bad, { cwd: fx.main, spawn }); + expect(result.exitCode, bad).toBe(2); + expect((result.report as ErrorReport).error.message, bad).toMatch(/^invalid PR number/); + } + expect(spawn).not.toHaveBeenCalled(); + }); + + it('outside a git repository is exit 2', async () => { + const plain = path.join(fx.root, 'plain'); + fs.mkdirSync(plain); + const result = await checkPr('7', { cwd: plain, env: { ...fx.env, GIT_CEILING_DIRECTORIES: fx.root } }); + expect(result.exitCode).toBe(2); + expect((result.report as ErrorReport).error.message).toBe('not in a git repository'); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/helpers/pr-fixture.ts b/packages/codev/src/commands/check/__tests__/helpers/pr-fixture.ts new file mode 100644 index 000000000..9b3af2311 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/helpers/pr-fixture.ts @@ -0,0 +1,130 @@ +/** + * Pull-request fixtures for the `codev check pr` tests (Spec 1951): a builder branch pushed + * to the fixture's origin, the `pr-view` JSON the forge would return for it, project + * configuration, and a `pr-view` concept override that runs on every platform. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { Fixture } from './git-fixture.js'; + +/** The `--json` field list the shipped github `pr-view` script asks `gh` for. */ +export const PR_VIEW_FIELDS = + 'title,body,state,url,author,baseRefName,headRefName,additions,deletions,headRefOid,isDraft,mergeable,mergeStateStatus,mergeCommit,mergedAt,reviewDecision'; + +export const PR_NUMBER = 7; +export const PR_BRANCH = 'builder/spir-7'; + +/** What `gh pr view` returns for an open PR on `PR_BRANCH` → main with the given head. */ +export function prView(head: string, overrides: Record = {}): Record { + return { + title: 'Feature 7', + body: 'Does the thing.\n\nFixes #7', + state: 'OPEN', + url: 'https://example.invalid/pr/7', + author: { login: 'builder' }, + baseRefName: 'main', + headRefName: PR_BRANCH, + additions: 1, + deletions: 0, + headRefOid: head, + isDraft: false, + mergeable: 'MERGEABLE', + mergeStateStatus: 'CLEAN', + mergeCommit: null, + mergedAt: null, + reviewDecision: null, + ...overrides, + }; +} + +export type Commits = Array<{ files: Record; message: string }>; + +/** + * Create `branch` from `base` in a worktree under the main clone, commit, and push it to + * origin. The local branch then matches the PR head. + */ +export function pushBranch(fx: Fixture, commits: Commits, branch = PR_BRANCH, base = 'main'): { dir: string; head: string } { + const dir = fx.addWorktree(branch.replace(/\//g, '-'), branch, base); + let head = fx.git(dir, 'rev-parse', 'HEAD').trim(); + for (const c of commits) head = fx.commit(dir, c.files, c.message); + fx.git(dir, 'push', '-q', 'origin', branch); + return { dir, head }; +} + +/** Push a commit to `branch` on origin from a second clone; the main clone never sees it. */ +export function pushFromElsewhere(fx: Fixture, branch: string, files: Record, message = `on ${branch}`): string { + const other = otherClone(fx); + fx.git(other, 'fetch', '-q', 'origin'); + const exists = fx.git(other, 'ls-remote', 'origin', `refs/heads/${branch}`).trim() !== ''; + fx.git(other, 'checkout', '-q', '-B', branch, exists ? `origin/${branch}` : 'origin/main'); + const sha = fx.commit(other, files, message); + fx.git(other, 'push', '-q', 'origin', branch); + return sha; +} + +export function otherClone(fx: Fixture): string { + const dir = path.join(fx.root, 'other'); + return fs.existsSync(dir) ? dir : fx.clone('other'); +} + +/** Write the main clone's `.codev/config.json`. Returns its path. */ +export function writeConfig(fx: Fixture, config: Record): string { + const file = path.join(fx.main, '.codev', 'config.json'); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, JSON.stringify(config, null, 2)); + return file; +} + +/** Forward slashes, which both sh and Git Bash read in an absolute path. */ +export function shPath(p: string): string { + return p.replace(/\\/g, '/'); +} + +export interface PrViewOverride { + /** The absolute script path, to put in `forge["pr-view"]`. */ + script: string; + /** The answer for every call, unless `answerOn` set one for that call. */ + answer(view: Record | string): void; + /** The answer for call `n` (1-based): the anchoring read is 1, the end-of-run re-read 2. */ + answerOn(n: number, view: Record | string): void; + /** A shell snippet run before answering call `n`. */ + runOn(n: number, snippet: string): void; + calls(): number; +} + +/** + * A `pr-view` override: a `.sh` script outside the repository that answers from files and + * counts its calls. Git Bash runs a bare `.sh` path on Windows, so it works everywhere. + */ +export function prViewOverride(fx: Fixture): PrViewOverride { + const dir = path.join(fx.root, 'forge'); + fs.mkdirSync(dir, { recursive: true }); + const script = path.join(dir, 'pr-view.sh'); + const d = shPath(dir); + fs.writeFileSync( + script, + [ + '#!/bin/sh', + `dir='${d}'`, + 'n=$(cat "$dir/count" 2>/dev/null || echo 0)', + 'n=$((n + 1))', + 'echo "$n" > "$dir/count"', + '[ -f "$dir/run.$n.sh" ] && . "$dir/run.$n.sh"', + 'if [ -f "$dir/answer.$n.json" ]; then cat "$dir/answer.$n.json"; else cat "$dir/answer.json"; fi', + '', + ].join('\n'), + { mode: 0o755 }, + ); + const text = (view: Record | string): string => (typeof view === 'string' ? view : JSON.stringify(view)); + return { + script, + answer: (view) => fs.writeFileSync(path.join(dir, 'answer.json'), text(view)), + answerOn: (n, view) => fs.writeFileSync(path.join(dir, `answer.${n}.json`), text(view)), + runOn: (n, snippet) => fs.writeFileSync(path.join(dir, `run.${n}.sh`), `${snippet}\n`), + calls: () => { + const file = path.join(dir, 'count'); + return fs.existsSync(file) ? Number(fs.readFileSync(file, 'utf-8').trim()) : 0; + }, + }; +} diff --git a/packages/codev/src/commands/check/__tests__/imports.test.ts b/packages/codev/src/commands/check/__tests__/imports.test.ts index 8f3c66a4a..fbe947962 100644 --- a/packages/codev/src/commands/check/__tests__/imports.test.ts +++ b/packages/codev/src/commands/check/__tests__/imports.test.ts @@ -31,6 +31,10 @@ const ALLOWED: Record = { names: ['loadConfig', 'findConfigSource'], reason: 'reads configuration files; never writes or spawns', }, + commander: { + names: ['Command', 'CommanderError'], + reason: 'argument parsing for the check group (index.ts); only action-handler subcommands, never the executable form that spawns', + }, }; /** runner.ts alone may reach a subprocess. */ @@ -83,7 +87,9 @@ const sources = fs describe('Spec 1951 — audited imports in commands/check/', () => { it('audits every source file in the directory', () => { expect(sources).toEqual( - expect.arrayContaining(['allow-list.ts', 'git-facts.ts', 'render.ts', 'report.ts', 'roots.ts', 'runner.ts', 'settings.ts', 'validate.ts']), + expect.arrayContaining([ + 'allow-list.ts', 'git-facts.ts', 'index.ts', 'pr.ts', 'render.ts', 'report.ts', 'roots.ts', 'runner.ts', 'settings.ts', 'validate.ts', + ]), ); }); diff --git a/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts b/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts new file mode 100644 index 000000000..418e81b75 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts @@ -0,0 +1,90 @@ +/** + * Spec 1951 — the pure parsers behind `codev check pr`: the `pr-view` contract fields it + * relies on, `git log -z` and `git merge-tree -z` output, per-line attribution matching, + * and width-bounded lists. + */ + +import { describe, expect, it } from 'vitest'; +import { matchLines, parseLogMessages, parseMergeTree, parsePrView } from '../pr.js'; +import { CheckCommandError, fitList } from '../report.js'; + +const SHA = 'a'.repeat(40); +const SHA2 = 'b'.repeat(40); + +describe('Spec 1951 — parsePrView', () => { + const view = { title: 'T', body: 'B', state: 'OPEN', url: 'u', isDraft: true, headRefName: 'builder/spir-7', baseRefName: 'main', headRefOid: SHA }; + + it('reads the fields the command needs', () => { + expect(parsePrView(view)).toEqual({ + ok: true, + value: { title: 'T', body: 'B', state: 'OPEN', url: 'u', draft: true, headRef: 'builder/spir-7', baseRef: 'main', head: SHA }, + }); + }); + + it('keeps optional fields it does not get as null, never a guess', () => { + const result = parsePrView({ headRefName: 'b', baseRefName: 'main', headRefOid: SHA }); + expect(result).toEqual({ ok: true, value: { title: null, body: null, state: null, url: null, draft: null, headRef: 'b', baseRef: 'main', head: SHA } }); + }); + + it.each([ + [{ ...view, headRefOid: undefined }, 'pr-view did not return headRefOid'], + [{ ...view, headRefOid: '' }, 'pr-view did not return headRefOid'], + [{ ...view, headRefOid: 'abc1234' }, 'pr-view returned headRefOid "abc1234", not a full commit SHA'], + [{ ...view, headRefOid: 42 }, 'pr-view returned headRefOid 42, not a full commit SHA'], + [{ ...view, baseRefName: undefined }, 'pr-view did not return baseRefName'], + [{ ...view, headRefName: '--upload-pack=x' }, 'pr-view returned headRefName "--upload-pack=x", not a valid branch name'], + [{ ...view, baseRefName: 'a..b' }, 'pr-view returned baseRefName "a..b", not a valid branch name'], + [[], 'pr-view returned something other than a JSON object'], + ['text', 'pr-view returned something other than a JSON object'], + ])('refuses %j', (data, reason) => { + expect(parsePrView(data)).toEqual({ ok: false, reason }); + }); +}); + +describe('Spec 1951 — git output parsers', () => { + it('parses git log -z --format=%H%x00%B, empty messages included', () => { + expect(parseLogMessages(`${SHA}\0second\n\0${SHA2}\0first\n\nTrailer: x\n\0`)).toEqual([ + { sha: SHA, message: 'second\n' }, + { sha: SHA2, message: 'first\n\nTrailer: x\n' }, + ]); + expect(parseLogMessages(`${SHA}\0\0`)).toEqual([{ sha: SHA, message: '' }]); + expect(parseLogMessages('')).toEqual([]); + }); + + it('fails loudly on log output it does not understand', () => { + expect(() => parseLogMessages(`${SHA}\0msg\0extra`)).toThrow(CheckCommandError); + expect(() => parseLogMessages('nothex\0msg\0')).toThrow(/not a commit SHA/); + }); + + it('parses merge-tree -z: the tree, then the conflicted files', () => { + expect(parseMergeTree(`${SHA}\0`)).toEqual({ tree: SHA, files: [] }); + expect(parseMergeTree(`${SHA}\n`)).toEqual({ tree: SHA, files: [] }); + expect(parseMergeTree(`${SHA}\0a b.txt\0dir/c\0`)).toEqual({ tree: SHA, files: ['a b.txt', 'dir/c'] }); + expect(() => parseMergeTree('fatal: bad\0')).toThrow(CheckCommandError); + }); +}); + +describe('Spec 1951 — attribution matching', () => { + const patterns = [{ source: '^\\s*Co-Authored-By:', regex: /^\s*Co-Authored-By:/i }]; + + it('reports 1-based line numbers per matching line', () => { + expect(matchLines('title\r\n\r\n co-authored-by: X\nCo-Authored-By: Y', patterns)).toEqual([ + { line: 3, text: ' co-authored-by: X' }, + { line: 4, text: 'Co-Authored-By: Y' }, + ]); + }); + + it('matches each line on its own, so an anchor cannot match mid-message', () => { + expect(matchLines('mentions Co-Authored-By: in prose', patterns)).toEqual([]); + }); +}); + +describe('Spec 1951 — fitList', () => { + it('shows what fits, at least one item, then the count of the rest', () => { + expect(fitList([], 10)).toBe(''); + expect(fitList(['a', 'b', 'c'], 10)).toBe('a, b, c'); + expect(fitList(['aaaa', 'bbbb', 'cccc'], 10)).toBe('aaaa, bbbb, … +1'); + expect(fitList(['a-very-long-path'], 5)).toBe('a-very-long-path'); + expect(fitList(['a-very-long-path', 'b'], 5)).toBe('a-very-long-path, … +1'); + }); +}); diff --git a/packages/codev/src/commands/check/index.ts b/packages/codev/src/commands/check/index.ts new file mode 100644 index 000000000..5fb006337 --- /dev/null +++ b/packages/codev/src/commands/check/index.ts @@ -0,0 +1,95 @@ +/** + * The `codev check` command group (Spec 1951): read-only checks an architect runs before a + * merge, after it, and before cleanup. + * + * Exit codes: 0 clear, 1 needs attention, 2 the command failed. Commander's own exits are + * mapped to the same scheme: `--help` exits 0, and every usage error (unknown option, + * missing or extra argument, unknown subcommand) exits 2, not commander's default 1. With + * `--json`, a usage error on a subcommand prints that subcommand's `ErrorReport` on stdout. + * + * Subcommands are action handlers only. Commander's executable-subcommand form, which + * spawns a program, is never used, so the runner stays the only subprocess path. + */ + +import { Command, CommanderError } from 'commander'; +import { checkPr, renderPrHuman } from './pr.js'; +import { renderErrorHuman, renderJson } from './render.js'; +import type { CommandName, CommandResult, ErrorReport, Report } from './report.js'; + +export interface CheckCliDeps { + /** End the process with this code. Production never returns; tests record the code and throw. */ + exit: (code: number) => void; + /** Write to stdout; resolves once the text is flushed, so a large `--json` survives the exit. */ + stdout: (text: string) => void | Promise; + stderr: (text: string) => void | Promise; + cwd: () => string; + /** The arguments being parsed, to see whether a usage error should be reported as JSON. */ + argv: () => readonly string[]; + /** Extra environment for every subprocess (tests only). */ + env?: Record; + timeoutMs?: number; +} + +function flushed(stream: NodeJS.WriteStream): (text: string) => Promise { + return (text) => new Promise((resolve) => stream.write(text, () => resolve())); +} + +const PROCESS_DEPS: CheckCliDeps = { + exit: (code) => process.exit(code), + stdout: flushed(process.stdout), + stderr: flushed(process.stderr), + cwd: () => process.cwd(), + argv: () => process.argv, +}; + +/** Commander's exit, mapped: help and version 0, anything else a usage error, 2. */ +export function exitCodeForCommander(err: CommanderError): 0 | 2 { + if (err.code === 'commander.helpDisplayed' || err.code === 'commander.version') return 0; + if (err.code === 'commander.help') return err.exitCode === 0 ? 0 : 2; + return 2; +} + +export function buildCheckCommand(deps: CheckCliDeps = PROCESS_DEPS): Command { + /** + * The exit callback commander calls instead of `process.exit`. It must not return: + * commander exits with its own code if it does, so it rethrows after `deps.exit`. + */ + const onCommanderExit = (command: CommandName | null) => (err: CommanderError): never => { + const code = exitCodeForCommander(err); + if (code === 2 && command !== null && deps.argv().includes('--json')) { + const report: ErrorReport = { schema: 1, command, error: { message: err.message.replace(/^error: /, '') } }; + void deps.stdout(renderJson(report)); + } + deps.exit(code); + throw err; + }; + + const finish = async (result: CommandResult, json: boolean, human: (report: R) => string): Promise => { + const { report } = result; + if ('error' in report) { + if (json) await deps.stdout(renderJson(report)); + else await deps.stderr(renderErrorHuman(report)); + } else { + await deps.stdout(json ? renderJson(report) : human(report)); + } + deps.exit(result.exitCode); + }; + + const group = new Command('check') + .description('Read-only checks: merge readiness of a PR (never merges, pushes, comments or deletes)') + .configureOutput({ writeOut: (s) => void deps.stdout(s), writeErr: (s) => void deps.stderr(s) }); + group.exitOverride(onCommanderExit(null)); + + const pr = group + .command('pr ') + .description('Merge mechanics of PR : exact head, live base, trial merge, attribution, watched files, size, files to read') + .option('--json', 'print one JSON object (schema 1) instead of the summary') + .allowExcessArguments(false) + .action(async (number: string, options: { json?: boolean }) => { + const result = await checkPr(number, { cwd: deps.cwd(), env: deps.env, timeoutMs: deps.timeoutMs }); + await finish(result, options.json === true, renderPrHuman); + }); + pr.exitOverride(onCommanderExit('pr')); + + return group; +} diff --git a/packages/codev/src/commands/check/pr.ts b/packages/codev/src/commands/check/pr.ts new file mode 100644 index 000000000..449b18b0d --- /dev/null +++ b/packages/codev/src/commands/check/pr.ts @@ -0,0 +1,470 @@ +/** + * `codev check pr ` (Spec 1951): what an architect reads before recommending a merge. + * + * The run anchors on the head SHA the forge reports (`pr-view`) and on the base tip + * `ls-remote` reports. The local `origin/` is never used. Missing objects are fetched + * ref-neutrally. Every check below is computed on those exact commits, with the diff range + * merge-base → head (what the forge's diff view shows): + * + * head the local branch against the forge head (local ahead = not pushed) + * attribution configured patterns, per line, in the description and each commit not on base + * trial-merge `merge-tree --write-tree` in the object store: no ref, index or file moves + * watched files matching `check.watch`; those also matching `check.flag` need attention + * overlap files the base has also changed since the branch point + * size lines and files changed + * to-read the changed files minus `check.notForReading`, largest first + * + * When the checks finish, `pr-view` and `ls-remote` are read again. If the head or the base + * moved, the check anchored on it (`head`, `trial-merge`) needs attention, so a CLEAR always + * describes the tips that were live at the end of the run. + */ + +import { findConfigSource } from '../../lib/config.js'; +import { + atLeast, + changedFiles, + ensureCommits, + failureReason, + gitVersion, + liveTip, + mergeBase, + numstat, + resolveCommit, + TRIAL_MERGE_MIN, + versionLabel, + type FileStat, + type GitVersion, + type Lookup, +} from './git-facts.js'; +import { attentionNames, renderHuman, short, type RenderOptions } from './render.js'; +import { + applySkips, + check, + CheckCommandError, + errorReport, + exitCodeOf, + fitList, + notRun, + off, + verdictOf, + type Check, + type CommandOptions, + type CommandResult, + type PrReport, +} from './report.js'; +import { resolveRoots } from './roots.js'; +import { createRunner, type Runner } from './runner.js'; +import { loadCheckSettings, type AttributionPattern, type CheckSettings } from './settings.js'; +import { isFullSha, isRefName, validatePrNumber } from './validate.js'; + +/** The `pr-view` fields this command reads, validated. */ +interface PrView { + title: string | null; + body: string | null; + state: string | null; + url: string | null; + draft: boolean | null; + headRef: string; + baseRef: string; + head: string; +} + +/** Validate a `pr-view` result. A failure reason names the field. */ +export function parsePrView(data: unknown): Lookup { + if (typeof data !== 'object' || data === null || Array.isArray(data)) { + return { ok: false, reason: 'pr-view returned something other than a JSON object' }; + } + const raw = data as Record; + if (raw.headRefOid === undefined || raw.headRefOid === null || raw.headRefOid === '') { + return { ok: false, reason: 'pr-view did not return headRefOid' }; + } + if (typeof raw.headRefOid !== 'string' || !isFullSha(raw.headRefOid)) { + return { ok: false, reason: `pr-view returned headRefOid ${JSON.stringify(raw.headRefOid)}, not a full commit SHA` }; + } + for (const field of ['headRefName', 'baseRefName'] as const) { + const value = raw[field]; + if (value === undefined || value === null || value === '') return { ok: false, reason: `pr-view did not return ${field}` }; + if (typeof value !== 'string' || !isRefName(value)) { + return { ok: false, reason: `pr-view returned ${field} ${JSON.stringify(value)}, not a valid branch name` }; + } + } + const text = (value: unknown): string | null => (typeof value === 'string' ? value : null); + return { + ok: true, + value: { + title: text(raw.title), + body: text(raw.body), + state: text(raw.state), + url: text(raw.url), + draft: typeof raw.isDraft === 'boolean' ? raw.isDraft : null, + headRef: raw.headRefName as string, + baseRef: raw.baseRefName as string, + head: raw.headRefOid, + }, + }; +} + +async function readPrView(runner: Runner, number: number): Promise> { + const outcome = await runner.forge('pr-view', { CODEV_PR_NUMBER: String(number) }); + if (!outcome.ok) return { ok: false, reason: outcome.reason }; + return parsePrView(outcome.data); +} + +/** `provider github`, or `provider github, override in ` when a project overrides the concept. */ +function forgeSource(runner: Runner, mainRoot: string): string { + const override = findConfigSource(mainRoot, ['forge', 'pr-view']); + return override ? `provider ${runner.provider()}, override in ${override}` : `provider ${runner.provider()}`; +} + +/** Characters a file list may take on a check's line before it is cut to `… +N`. */ +const LIST_WIDTH = 72; + +function plural(n: number, word: string): string { + return `${n.toLocaleString('en-US')} ${word}${n === 1 ? '' : 's'}`; +} + +/** At most `max` characters of a line, for the human summary. */ +function clip(text: string, max = 30): string { + const trimmed = text.trim(); + return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max - 1)}…`; +} + +async function countRange(runner: Runner, from: string, to: string): Promise { + const result = await runner.git(['rev-list', '--count', `${from}..${to}`]); + const count = Number(result.stdout.trim()); + if (result.exitCode !== 0 || !Number.isInteger(count)) { + throw new CheckCommandError(`git rev-list --count ${from}..${to} failed`, result.stderr.trim()); + } + return count; +} + +// ============================================================================= +// The checks +// ============================================================================= + +/** The commits the base-dependent and head-dependent checks need, or why they are missing. */ +interface Anchors { + head: string; + headProblem: string | null; + baseTip: string | null; + baseProblem: string | null; + mergeBase: string | null; + rangeProblem: string | null; +} + +async function checkHead(runner: Runner, pr: PrView, local: string | null, anchors: Anchors): Promise { + const name = pr.headRef; + if (local === null) return check('head', 'ok', `no local branch ${name}`, { forgeHead: pr.head, relation: 'absent' }); + const details: Record = { forgeHead: pr.head, localBranchSha: local }; + if (local === pr.head) return check('head', 'ok', `local ${name} matches`, { ...details, relation: 'matches', aheadOfPr: 0 }); + // The local branch is compared only when origin's branch of that name is the PR head. A + // fork's PR names a branch in another repository, often `main`; a local branch of the same + // name is unrelated to it and must not be reported as unpushed work. + const onOrigin = await liveTip(runner, name); + if (!onOrigin.ok) return notRun('head', onOrigin.reason, details); + if (onOrigin.value !== pr.head) { + const where = + onOrigin.value === null + ? `origin has no branch ${name} (a fork's PR, or the branch was deleted)` + : `origin's ${name} is at ${short(onOrigin.value)}, not the PR head (a fork's PR, or the branch moved)`; + return check('head', 'info', `${where}: local ${name} not compared`, { + forgeHead: pr.head, + relation: 'not-origin-branch', + originBranchSha: onOrigin.value, + }); + } + if (anchors.headProblem) return notRun('head', anchors.headProblem, details); + const ahead = await countRange(runner, pr.head, local); + const behind = await countRange(runner, local, pr.head); + const counted = { ...details, aheadOfPr: ahead, behindPr: behind }; + if (ahead > 0 && behind > 0) { + return check('head', 'attention', `local ${name} has diverged from the PR head (${ahead} not pushed, ${behind} not local)`, { + ...counted, + relation: 'diverged', + }); + } + if (ahead > 0) { + return check('head', 'attention', `local ${name} is ${plural(ahead, 'commit')} ahead of the PR head (not pushed)`, { + ...counted, + relation: 'ahead', + }); + } + return check('head', 'ok', `local ${name} is ${plural(behind, 'commit')} behind the PR head`, { ...counted, relation: 'behind' }); +} + +interface AttributionHit { + where: 'description' | 'commit'; + sha?: string; + line: number; + text: string; +} + +/** Lines (1-based) of `text` that match any pattern. Patterns carry no `g` flag, so `test` keeps no state. */ +export function matchLines(text: string, patterns: readonly AttributionPattern[]): Array<{ line: number; text: string }> { + const hits: Array<{ line: number; text: string }> = []; + text.split(/\r?\n/).forEach((line, index) => { + if (patterns.some((p) => p.regex.test(line))) hits.push({ line: index + 1, text: line }); + }); + return hits; +} + +/** Parse `git log -z --format=%H%x00%B`: SHA and message, alternating, NUL-separated. */ +export function parseLogMessages(output: string): Array<{ sha: string; message: string }> { + const tokens = output.split('\0'); + if (tokens.length > 0 && tokens[tokens.length - 1] === '') tokens.pop(); + if (tokens.length % 2 !== 0) throw new CheckCommandError('unexpected git log output (an odd number of fields)'); + const commits: Array<{ sha: string; message: string }> = []; + for (let i = 0; i < tokens.length; i += 2) { + const sha = tokens[i].trim(); + if (!isFullSha(sha)) throw new CheckCommandError(`unexpected git log output: ${JSON.stringify(sha)} is not a commit SHA`); + commits.push({ sha, message: tokens[i + 1] }); + } + return commits; +} + +async function checkAttribution(runner: Runner, pr: PrView, settings: CheckSettings, anchors: Anchors): Promise { + if (settings.attribution.length === 0) return off('attribution', 'no patterns configured (check.attribution)'); + if (pr.body === null) return notRun('attribution', 'pr-view did not return body (the description)'); + const blocked = anchors.headProblem ?? anchors.baseProblem; + if (blocked) return notRun('attribution', blocked); + + const log = await runner.git(['log', '--no-ext-diff', '--no-textconv', '-z', '--format=%H%x00%B', `${anchors.baseTip}..${anchors.head}`]); + if (log.exitCode !== 0) return notRun('attribution', failureReason('git log', log, runner.timeoutLabel)); + const commits = parseLogMessages(log.stdout); + + const hits: AttributionHit[] = matchLines(pr.body, settings.attribution).map((h) => ({ where: 'description', ...h })); + for (const commit of commits) { + for (const h of matchLines(commit.message, settings.attribution)) hits.push({ where: 'commit', sha: commit.sha, ...h }); + } + const details = { patterns: settings.attribution.map((p) => p.source), hits, commitsScanned: commits.length }; + if (hits.length === 0) { + return check('attribution', 'ok', `none in the description or ${plural(commits.length, 'commit')}`, details); + } + const places = hits.map((h) => (h.where === 'description' ? `description line ${h.line}` : `commit ${short(h.sha!)} "${clip(h.text)}"`)); + return check('attribution', 'attention', `${plural(hits.length, 'line')}: ${fitList(places, LIST_WIDTH)}`, details); +} + +/** Parse `merge-tree --write-tree --name-only --no-messages -z`: the tree, then conflicted files. */ +export function parseMergeTree(output: string): { tree: string; files: string[] } { + const [tree, ...rest] = output.split('\0'); + const treeOid = (tree ?? '').trim(); + if (!isFullSha(treeOid)) throw new CheckCommandError(`unexpected git merge-tree output ${JSON.stringify(output.slice(0, 80))}`); + return { tree: treeOid, files: rest.filter((f) => f !== '') }; +} + +async function checkTrialMerge(runner: Runner, pr: PrView, version: GitVersion, anchors: Anchors): Promise { + if (!atLeast(version, TRIAL_MERGE_MIN)) { + return notRun('trial-merge', `requires git ${TRIAL_MERGE_MIN.major}.${TRIAL_MERGE_MIN.minor}+ (found ${versionLabel(version)})`); + } + const blocked = anchors.headProblem ?? anchors.baseProblem; + if (blocked) return notRun('trial-merge', blocked); + const baseTip = anchors.baseTip!; + const result = await runner.git(['merge-tree', '--write-tree', '--name-only', '--no-messages', '-z', baseTip, anchors.head]); + if (result.exitCode !== 0 && result.exitCode !== 1) return notRun('trial-merge', failureReason('git merge-tree', result, runner.timeoutLabel)); + const { files } = parseMergeTree(result.stdout); + const details = { baseTip, head: anchors.head, conflicts: files.length, files }; + const target = `${pr.baseRef} @ ${short(baseTip)}`; + if (result.exitCode === 0) return check('trial-merge', 'ok', `clean into ${target}`, details); + return check('trial-merge', 'attention', `${plural(files.length, 'conflicting file')} merging into ${target}: ${fitList(files, LIST_WIDTH)}`, details); +} + +async function checkWatched(runner: Runner, settings: CheckSettings, anchors: Anchors): Promise { + if (settings.watch.length === 0) return off('watched', 'no watched paths configured (check.watch)'); + const blocked = anchors.headProblem ?? anchors.baseProblem ?? anchors.rangeProblem; + if (blocked) return notRun('watched', blocked); + const mb = anchors.mergeBase!; + const watched = await changedFiles(runner, mb, anchors.head, { include: settings.watch }); + // check.flag applies only to files check.watch matched. + const flagged = new Set(await changedFiles(runner, mb, anchors.head, { include: settings.flag })); + const files = watched + .map((path) => ({ path, flagged: flagged.has(path) })) + .sort((a, b) => Number(b.flagged) - Number(a.flagged)); + if (files.length === 0) return check('watched', 'ok', 'no watched file changed', { files }); + const names = files.map((f) => (f.flagged ? `${f.path} (flagged)` : f.path)); + return check('watched', files.some((f) => f.flagged) ? 'attention' : 'info', fitList(names, LIST_WIDTH), { files }); +} + +async function checkOverlap(runner: Runner, pr: PrView, changed: readonly FileStat[], anchors: Anchors): Promise { + const onBase = new Set(await changedFiles(runner, anchors.mergeBase!, anchors.baseTip!)); + const files = changed.map((s) => s.path).filter((p) => onBase.has(p)); + const where = `on ${pr.baseRef} since the branch point`; + if (files.length === 0) return check('overlap', 'info', `no file also changed ${where}`, { files }); + return check('overlap', 'info', `${plural(files.length, 'file')} also changed ${where}: ${fitList(files, LIST_WIDTH)}`, { files }); +} + +function checkSize(changed: readonly FileStat[]): Check { + const additions = changed.reduce((n, s) => n + s.additions, 0); + const deletions = changed.reduce((n, s) => n + s.deletions, 0); + const summary = `+${additions.toLocaleString('en-US')} −${deletions.toLocaleString('en-US')} in ${plural(changed.length, 'file')}`; + return check('size', 'info', summary, { additions, deletions, files: changed.length }); +} + +async function checkToRead(runner: Runner, settings: CheckSettings, changed: readonly FileStat[], anchors: Anchors): Promise { + const toRead = await numstat(runner, anchors.mergeBase!, anchors.head, { exclude: settings.notForReading }); + const kept = new Set(toRead.map((s) => s.path)); + const excluded = changed.map((s) => s.path).filter((p) => !kept.has(p)); + const largestFirst = [...toRead].sort((a, b) => b.additions + b.deletions - (a.additions + a.deletions) || (a.path < b.path ? -1 : 1)); + const details = { + files: largestFirst.map(({ path, additions, deletions }) => ({ path, additions, deletions })), + excluded, + }; + const notForReading = `${excluded.length.toLocaleString('en-US')} not for reading`; + if (largestFirst.length === 0) return check('to-read', 'info', `nothing to read (${notForReading})`, details); + const paths = largestFirst.map((s) => s.path); + return check('to-read', 'info', `${plural(paths.length, 'file')} (${notForReading}): ${fitList(paths, LIST_WIDTH)}`, details); +} + +/** The range checks (`overlap`, `size`, `to-read`) share one numstat; all are not run when the range is not available. */ +async function rangeChecks(runner: Runner, pr: PrView, settings: CheckSettings, anchors: Anchors): Promise { + const blocked = anchors.headProblem ?? anchors.baseProblem ?? anchors.rangeProblem; + if (blocked) return [notRun('overlap', blocked), notRun('size', blocked), notRun('to-read', blocked)]; + const changed = await numstat(runner, anchors.mergeBase!, anchors.head); + return [await checkOverlap(runner, pr, changed, anchors), checkSize(changed), await checkToRead(runner, settings, changed, anchors)]; +} + +// ============================================================================= +// Movement during the run +// ============================================================================= + +/** + * Add a note to the check anchored on a tip that moved (or could not be re-read). The check + * needs attention; one the project skipped is replaced, because a CLEAR must describe the + * live tips. + */ +function flagCheck(checks: Check[], id: string, note: string, extra: Record): Check[] { + return checks.map((c) => { + if (c.id !== id) return c; + if (c.status === 'skip') return check(id, 'attention', note, extra); + const status = c.status === 'not-run' ? 'not-run' : 'attention'; + return { ...c, status, summary: `${c.summary}\n${note}`, details: { ...c.details, ...extra } }; + }); +} + +function moved(from: string | null, to: string | null): string { + return `${from ? short(from) : 'none'} → ${to ? short(to) : 'none'}`; +} + +// ============================================================================= +// The command +// ============================================================================= + +async function buildPrReport(number: number, options: CommandOptions): Promise { + const runnerOptions = { timeoutMs: options.timeoutMs, env: options.env, spawn: options.spawn }; + const roots = await resolveRoots(createRunner({ cwd: options.cwd, workspaceRoot: options.cwd, ...runnerOptions })); + const runner = createRunner({ cwd: roots.mainRoot, workspaceRoot: roots.mainRoot, ...runnerOptions }); + const settings = loadCheckSettings(roots.mainRoot); + const version = await gitVersion(runner); + + const anchor = await readPrView(runner, number); + if (!anchor.ok) throw new CheckCommandError(`could not read PR #${number}: ${anchor.reason} (${forgeSource(runner, roots.mainRoot)})`); + const pr = anchor.value; + + const base = await liveTip(runner, pr.baseRef); + const anchors: Anchors = { head: pr.head, headProblem: null, baseTip: null, baseProblem: null, mergeBase: null, rangeProblem: null }; + if (!base.ok) anchors.baseProblem = base.reason; + else if (base.value === null) anchors.baseProblem = `origin has no branch ${pr.baseRef}`; + else anchors.baseTip = base.value; + + const available = await ensureCommits(runner, anchors.baseTip ? [pr.head, anchors.baseTip] : [pr.head], version); + anchors.headProblem = available.get(pr.head) ?? null; + if (anchors.baseTip && !anchors.baseProblem) anchors.baseProblem = available.get(anchors.baseTip) ?? null; + if (!anchors.headProblem && !anchors.baseProblem) { + anchors.mergeBase = await mergeBase(runner, anchors.baseTip!, pr.head); + if (anchors.mergeBase === null) anchors.rangeProblem = `the head and ${pr.baseRef} @ ${short(anchors.baseTip!)} share no history`; + } + + const localSha = await resolveCommit(runner, `refs/heads/${pr.headRef}`); + let checks: Check[] = [ + await checkHead(runner, pr, localSha, anchors), + await checkAttribution(runner, pr, settings, anchors), + await checkTrialMerge(runner, pr, version, anchors), + await checkWatched(runner, settings, anchors), + ...(await rangeChecks(runner, pr, settings, anchors)), + ]; + checks = applySkips(checks, settings.skip); + + // Read both tips again: pr-view first, then ls-remote. + const reread = await readPrView(runner, number); + if (!reread.ok) { + checks = flagCheck(checks, 'head', `could not confirm the head at the end of the run (${reread.reason}); re-run`, { recheck: reread.reason }); + } else if (reread.value.head !== pr.head) { + checks = flagCheck(checks, 'head', `head moved during check (${moved(pr.head, reread.value.head)}); re-run`, { movedTo: reread.value.head }); + } + if (base.ok) { + const rebase = await liveTip(runner, pr.baseRef); + if (!rebase.ok) { + checks = flagCheck(checks, 'trial-merge', `could not confirm the base at the end of the run (${rebase.reason}); re-run`, { recheck: rebase.reason }); + } else if (rebase.value !== base.value) { + checks = flagCheck(checks, 'trial-merge', `base moved during check (${moved(base.value, rebase.value)}); re-run`, { movedTo: rebase.value }); + } + } + + return { + schema: 1, + command: 'pr', + verdict: verdictOf(checks), + generatedAt: new Date().toISOString(), + pr: { + number, + title: pr.title ?? '', + ...(pr.url ? { url: pr.url } : {}), + state: pr.state ?? '', + draft: pr.draft, + headRef: pr.headRef, + head: pr.head, + baseRef: pr.baseRef, + baseTip: anchors.baseTip, + localBranch: localSha ? { name: pr.headRef, sha: localSha } : null, + }, + checks, + }; +} + +/** `codev check pr `. Never throws: a failure that prevents a report is exit 2 with an `ErrorReport`. */ +export async function checkPr(rawNumber: string, options: CommandOptions): Promise> { + try { + const number = validatePrNumber(rawNumber); + const report = await buildPrReport(number, options); + return { report, exitCode: exitCodeOf(report.verdict) }; + } catch (err) { + return { report: errorReport('pr', err), exitCode: 2 }; + } +} + +// ============================================================================= +// Human form +// ============================================================================= + +const PR_RENDER: RenderOptions = { + qualifier: (c) => { + if (c.status === 'not-run') return 'not run'; + if ('movedTo' in c.details) return c.id === 'head' ? 'moved' : 'base moved'; + if (c.id === 'head' && (c.details.relation === 'ahead' || c.details.relation === 'diverged')) return 'not pushed'; + if (c.id === 'trial-merge' && c.status === 'attention' && 'conflicts' in c.details) return 'conflicts'; + if (c.id === 'watched' && c.status === 'attention') return 'flagged'; + return null; + }, +}; + +export function renderPrHuman(report: PrReport): string { + const { pr } = report; + // A head that is fine reads in the header; one that needs attention gets its own line. + const headCheck = report.checks.find((c) => c.id === 'head' && c.status === 'ok'); + const headInHeader = headCheck !== undefined; + const verdictLine = + report.verdict === 'clear' + ? `CLEAR PR #${pr.number} — ready to recommend` + : `ATTENTION PR #${pr.number} — ${attentionNames(report.checks, PR_RENDER).join(', ')}`; + const state = `${pr.state || 'state unknown'}${pr.draft ? ' (draft)' : ''}`; + const title = pr.title ? ` ${pr.title}` : ''; + const headPart = `head ${short(pr.head)}${headCheck ? ` (${headCheck.summary.split('\n')[0]})` : ''}`; + const basePart = pr.baseTip ? `base ${pr.baseRef} @ ${short(pr.baseTip)} (origin, live)` : `base ${pr.baseRef} (live tip not read)`; + return renderHuman( + { + verdictLine, + header: [`PR #${pr.number}${title} ${state} ${pr.headRef} → ${pr.baseRef}`, `${headPart} ${basePart}`, ''], + sections: [{ checks: report.checks.filter((c) => !(c.id === 'head' && headInHeader)) }], + }, + PR_RENDER, + ); +} diff --git a/packages/codev/src/commands/check/report.ts b/packages/codev/src/commands/check/report.ts index e11b1bb56..f3813c264 100644 --- a/packages/codev/src/commands/check/report.ts +++ b/packages/codev/src/commands/check/report.ts @@ -4,9 +4,28 @@ */ import type { CommitCheckItem } from '../../lib/forge-contracts.js'; +import type { SpawnFn } from './runner.js'; import { InputError } from './validate.js'; import { RunnerRefusal } from './allow-list.js'; +/** What every command function takes. Tests call the functions in process with these. */ +export interface CommandOptions { + /** Directory the command was run from. */ + cwd: string; + /** Limit for each forge call and networked git call; default 30 s. */ + timeoutMs?: number; + /** Extra environment for every subprocess (tests isolate git config and put stubs on PATH). */ + env?: Record; + /** Injected for tests; defaults to `child_process.spawn` inside the runner. */ + spawn?: SpawnFn; +} + +/** A command's outcome: the report (or the exit-2 error report) and the exit code. */ +export interface CommandResult { + report: R | ErrorReport; + exitCode: 0 | 1 | 2; +} + export type Status = 'ok' | 'attention' | 'info' | 'not-run' | 'off' | 'skip'; export type CommandName = 'pr' | 'deploy' | 'worktree'; export type Verdict = 'clear' | 'attention'; @@ -41,7 +60,8 @@ export interface PrReport extends Report { headRef: string; head: string; baseRef: string; - baseTip: string; + /** The live tip `ls-remote` reported; null when it could not be read (the base checks are then not run). */ + baseTip: string | null; localBranch: { name: string; sha: string } | null; }; checks: Check[]; @@ -180,6 +200,21 @@ export function errorReport(command: CommandName, err: unknown): ErrorReport { return { schema: 1, command, error: { message: `unexpected failure: ${message}` } }; } +/** + * As many items as fit in `width` characters (always at least one), then `… +N` for the + * rest. Keeps a check's line on one screen line however long the paths are. + */ +export function fitList(items: readonly string[], width: number): string { + if (items.length === 0) return ''; + let shown = 1; + let length = items[0].length; + while (shown < items.length && length + 2 + items[shown].length <= width) { + length += 2 + items[shown].length; + shown++; + } + return shown === items.length ? items.join(', ') : `${items.slice(0, shown).join(', ')}, … +${items.length - shown}`; +} + /** `a, b, c, … +N` */ export function truncateList(items: readonly string[], max: number): string { if (items.length <= max) return items.join(', '); From 786206972003deee64683db6f1770b76171b9158 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:01:39 -0800 Subject: [PATCH 46/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index b52683ffe..6df7aec9b 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: readonly_core @@ -78,7 +78,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T00:31:23.829Z' +updated_at: '2026-11-24T01:01:39.053Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From a1bd59df99411320649c3df02b65cf202738a0bb Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:07:01 -0800 Subject: [PATCH 47/94] =?UTF-8?q?chore(porch):=201951=20advance=20plan=20p?= =?UTF-8?q?hase=20=E2=86=92=20check=5Fpr=5Fforge?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1951-read-only-pr-check-for-archite/status.yaml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 6df7aec9b..ffc7faada 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -11,10 +11,10 @@ plan_phases: status: complete - id: check_pr_mechanics title: 'codev check pr: merge mechanics' - status: in_progress + status: complete - id: check_pr_forge title: 'codev check pr: forge state and CI checks' - status: pending + status: in_progress - id: check_deploy title: codev check deploy status: pending @@ -24,7 +24,7 @@ plan_phases: - id: docs_guidance title: Architect guidance and command documentation status: pending -current_plan_phase: check_pr_mechanics +current_plan_phase: check_pr_forge gates: spec-approval: status: approved @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: - iteration: 1 plan_phase: readonly_core @@ -78,7 +78,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T01:01:39.053Z' +updated_at: '2026-11-24T01:07:01.800Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -89,6 +89,8 @@ context_refreshes: - boundary: plan-phase:check_pr_mechanics at: '2026-11-24T00:24:38.902Z' acknowledged_at: '2026-11-24T00:31:23.829Z' + - boundary: plan-phase:check_pr_forge + at: '2026-11-24T01:07:01.800Z' force_advanced: phase: readonly_core iteration: 3 From ac72f4a054cf4227e323b20e790abcc057f2606f Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:07:38 -0800 Subject: [PATCH 48/94] [Spec 1951] Thread log: architect's Phase 3 verification on PR #1957 --- codev/state/spir-1951_thread.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 0c62e79cf..e7e98cec8 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -137,3 +137,7 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals have no command name, so they stay human-only on stderr. The CLI deps take argv explicitly (commander's rawArgs is untyped/internal). - Fixed in place: a type error in Phase 2's allow-list.test.ts (readonly tuple), found type-checking the tests. +- Architect verified Phase 3 on PR #1957 (draft, other project): CLEAR 4.5 s, +11,320 −464 in 69 files matching + GitHub, --json schema 1, exit 2 for missing PR / bad number, refs/status/FETCH_HEAD unchanged. Accepted both + deviations (fork-PR head rule; baseTip string|null) as deliberate. Open for Phase 4: a draft must not read CLEAR + (the `state` check), with a test; the architect reruns check pr 1957 then. From 899e8e960408d1733290a536364602e5c0b28e92 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:08:51 -0800 Subject: [PATCH 49/94] chore(porch): 1951 acknowledge context refresh --- codev/projects/1951-read-only-pr-check-for-archite/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index ffc7faada..77fdc7f5d 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -78,7 +78,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T01:07:01.800Z' +updated_at: '2026-11-24T01:08:51.119Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -91,6 +91,7 @@ context_refreshes: acknowledged_at: '2026-11-24T00:31:23.829Z' - boundary: plan-phase:check_pr_forge at: '2026-11-24T01:07:01.800Z' + acknowledged_at: '2026-11-24T01:08:51.118Z' force_advanced: phase: readonly_core iteration: 3 From 410d5ec1479c711910ba0357646b65723ba2e76e Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:27:49 -0800 Subject: [PATCH 50/94] =?UTF-8?q?[Spec=201951][Phase:=20check=5Fpr=5Fforge?= =?UTF-8?q?]=20feat:=20codev=20check=20pr=20=E2=80=94=20state,=20forge,=20?= =?UTF-8?q?CI=20on=20the=20code,=20linked=20issue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit All eleven checks of `codev check pr` are now present: - state: an open PR that is not a draft (OPENED → OPEN, a merge time → MERGED); a draft can never read CLEAR. - forge: the verdict follows `mergeable` alone; the merge state and review decision are context; an UNKNOWN takes the end-of-run re-read once. - checks (porch-only.ts): find the last code commit past porch-only commits (at most 10), choose the code runs with at most 10 commit-checks lookups, and show code and head on two lines so "still running" reads apart from "failed". - linked-issue (linked-issue.ts): GitHub's closing keywords against the builder branch's issue. Phase 3 review fold-ins: commander exits throw CheckExit carrying their writes, and cli.ts flushes them before exiting; `head` is attention when origin's branch is past the forge head (a push the forge has not indexed); localBranchSha in the not-origin-branch details; commander may be imported by index.ts only. --- codev/state/spir-1951_thread.md | 36 ++ packages/codev/src/cli.ts | 9 +- .../check/__tests__/check-cli.test.ts | 55 ++- .../check/__tests__/check-pr-forge.test.ts | 457 ++++++++++++++++++ .../__tests__/check-pr-mechanics.test.ts | 78 ++- .../check/__tests__/check-pr-readonly.test.ts | 12 +- .../check/__tests__/helpers/pr-fixture.ts | 62 +++ .../check/__tests__/helpers/report-shape.ts | 57 +++ .../commands/check/__tests__/imports.test.ts | 24 +- .../check/__tests__/linked-issue.test.ts | 95 ++++ .../check/__tests__/porch-only.test.ts | 189 ++++++++ .../check/__tests__/pr-parsers.test.ts | 85 +++- packages/codev/src/commands/check/index.ts | 44 +- .../codev/src/commands/check/linked-issue.ts | 60 +++ .../codev/src/commands/check/porch-only.ts | 257 ++++++++++ packages/codev/src/commands/check/pr.ts | 158 +++++- packages/codev/src/commands/check/report.ts | 7 +- 17 files changed, 1624 insertions(+), 61 deletions(-) create mode 100644 packages/codev/src/commands/check/__tests__/check-pr-forge.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/helpers/report-shape.ts create mode 100644 packages/codev/src/commands/check/__tests__/linked-issue.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/porch-only.test.ts create mode 100644 packages/codev/src/commands/check/linked-issue.ts create mode 100644 packages/codev/src/commands/check/porch-only.ts diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index e7e98cec8..f74c4d3a1 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -141,3 +141,39 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals GitHub, --json schema 1, exit 2 for missing PR / bad number, refs/status/FETCH_HEAD unchanged. Accepted both deviations (fork-PR head rule; baseTip string|null) as deliberate. Open for Phase 4: a draft must not read CLEAR (the `state` check), with a test; the architect reruns check pr 1957 then. + +## Phase 4 — check_pr_forge +- Built: `state`, `forge`, `checks` (porch-only.ts) and `linked-issue` (linked-issue.ts); all eleven checks now + present, in PR_CHECK_IDS order. Plus the three Phase 3 review fold-ins: commander exits throw `CheckExit` + carrying their pending writes and cli.ts awaits them before exiting; `head` is attention when origin's branch is + a descendant of the forge head (a push the forge has not indexed), decided only when the origin tip is local; + `localBranchSha` in the not-origin-branch details; the commander import allowance is now index.ts only. +- Choices to note in the review: + - Bounds: finding C reads at most 11 commits (more than 10 porch-only → not run). The lookups stay at 10: with + exactly ten porch-only commits above C the walk skips the oldest of them, keeping C (the plan's two bounds + differ by one at that edge). + - Verdict-line qualifier precedence for `checks`: failed, then running, then none. "No code runs, head still + running" reads `checks (running)`: wait and re-run, not "nothing ran". + - `forge` summary: `MERGEABLE, CLEAN` (spec sample); `MERGEABLE, BLOCKED (review required)` (the plan's + example worded as `MERGEABLE (state BLOCKED: review required)`). REVIEW_REQUIRED and CHANGES_REQUESTED give a + reason; APPROVED gives none. + - `linked-issue`: several keywords, one of them the branch's issue → info naming the others. Attention only when + none names the branch's issue. details add `references` (every keyword found). + - An ok `state` reads in the header (`OPEN`), like an ok `head`; one needing attention gets its own line. + - `pr.state` in the report is the normalized word (OPENED → OPEN, merged → MERGED). + - A `check.skip` of `checks` makes no commit-checks call. +- Targeted 644/644 (17 files), build, tsc on src and on the check tests, tmp-residue check OK. +- LIVE RUNS (worktree build, 2026-11-23): + - PR #1965 from the main checkout, 6.5 s, exit 1: `ATTENTION — checks (running)`; + `code 31d3edf: 4 passed, 4 still running` / `head 0513558: porch-only, 8 still running`; forge + `MERGEABLE, BLOCKED (review required)`; linked issue `"Fixes #1956" — matches builder/bugfix-1956`. + Main's refs and FETCH_HEAD (md5) unchanged. From this worktree: `--json` identical except generatedAt. + - PR #1957 (draft): `ATTENTION — state (draft), checks (running)`; `head f3ed3d4: 8 still running`; linked + issue `no closing keyword — close #1940 by hand after merge`. + - PR #1958 (draft, this project): `ATTENTION — state (draft), checks (running)`; + `code ac72f4a: no runs` / `head 899e8e9: porch-only, 7 passed, 1 still running` — the porch-only head case. + - Attribution hit from a scratch clone (session scratchpad; origin = git@github.com:cluesmith/codev.git; its + own .codev/config.local.json with `^\s*Co-Authored-By:` and `Generated with \[Claude Code\]`) on PR #1657: + `5 lines: description line 118, commit 23de988 "Co-Authored-By: Claude Opus 5…", … +3`; forge + `CONFLICTING, DIRTY` agreeing with `trial merge 5 conflicting files`; `checks head 1fe1037: porch-only, 7 + passed`. Clone refs unchanged, no FETCH_HEAD written. Main's config and ~/.codev untouched. diff --git a/packages/codev/src/cli.ts b/packages/codev/src/cli.ts index a17a510d8..60df6db9c 100644 --- a/packages/codev/src/cli.ts +++ b/packages/codev/src/cli.ts @@ -19,7 +19,7 @@ import { handleStats } from './commands/consult/stats.js'; import { cli as porchCli } from './commands/porch/index.js'; import { importCommand } from './commands/import.js'; import { generateImage } from './commands/generate-image.js'; -import { buildCheckCommand } from './commands/check/index.js'; +import { buildCheckCommand, CheckExit } from './commands/check/index.js'; import { version } from './version.js'; import { isCodevEntrypoint } from './lib/cli-entry.js'; import { findWorkspaceRoot } from './agent-farm/utils/index.js'; @@ -397,7 +397,12 @@ if (isMainModule) { process.stderr.write(`\`codev ${args[0]}\` is no longer supported. Use \`${hint}\` directly.\n`); process.exit(1); } - program.parseAsync(process.argv).catch((error) => { + program.parseAsync(process.argv).catch(async (error) => { + // `codev check` help and usage errors (Spec 1951): flush what was written, then exit with its code. + if (error instanceof CheckExit) { + await error.flush(); + process.exit(error.code); + } console.error(error instanceof Error ? error.message : String(error)); process.exit(1); }); diff --git a/packages/codev/src/commands/check/__tests__/check-cli.test.ts b/packages/codev/src/commands/check/__tests__/check-cli.test.ts index 717334b5c..865b3196a 100644 --- a/packages/codev/src/commands/check/__tests__/check-cli.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-cli.test.ts @@ -8,10 +8,10 @@ import { CommanderError } from 'commander'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { buildCheckCommand, exitCodeForCommander } from '../index.js'; +import { buildCheckCommand, CheckExit, exitCodeForCommander } from '../index.js'; import { useFakeHome } from './helpers/fake-home.js'; import { createFixture, type Fixture } from './helpers/git-fixture.js'; -import { prView, prViewOverride, pushBranch, writeConfig } from './helpers/pr-fixture.js'; +import { commitChecksOverride, passing, prView, prViewOverride, pushBranch, writeConfig } from './helpers/pr-fixture.js'; class Exited extends Error { constructor(public readonly code: number) { @@ -25,7 +25,16 @@ interface Outcome { stderr: string; } -async function runCli(args: string[], options: { cwd?: string; env?: Record } = {}): Promise { +type Write = (text: string, sink: string[]) => void | Promise; + +const immediate: Write = (text, sink) => void sink.push(text); + +/** + * Parse as cli.ts does: a command's exit goes through `deps.exit`; commander's own (help, + * usage errors) throw `CheckExit`, whose writes are awaited before the code counts. + */ +async function runCli(args: string[], options: { cwd?: string; env?: Record; write?: Write } = {}): Promise { + const write = options.write ?? immediate; const out: string[] = []; const err: string[] = []; let code: number | undefined; @@ -34,8 +43,8 @@ async function runCli(args: string[], options: { cwd?: string; env?: Record void out.push(s), - stderr: (s) => void err.push(s), + stdout: (s) => write(s, out), + stderr: (s) => write(s, err), cwd: () => options.cwd ?? process.cwd(), argv: () => args, env: options.env, @@ -44,8 +53,12 @@ async function runCli(args: string[], options: { cwd?: string; env?: Record { expect(JSON.parse(outcome.stdout)).toEqual({ schema: 1, command: 'pr', error: { message: expect.stringMatching(/^unknown option '--jsn'/) } }); }); + it('commander exits carry their writes: a slow stdout is flushed before the exit code is taken', async () => { + const slow: Write = (text, sink) => new Promise((resolve) => setTimeout(() => resolve(void sink.push(text)), 20)); + const usage = await runCli(['pr', '7', '--jsn', '--json'], { write: slow }); + expect(usage.code).toBe(2); + expect(JSON.parse(usage.stdout)).toMatchObject({ schema: 1, command: 'pr' }); + + const help = await runCli(['pr', '--help'], { write: slow }); + expect(help.code).toBe(0); + expect(help.stdout).toMatch(/Usage: check pr/); + }); + + it('CheckExit carries commander\'s error and code', async () => { + const group = buildCheckCommand({ exit: () => undefined, stdout: () => undefined, stderr: () => undefined, cwd: () => '.', argv: () => ['pr'] }); + const thrown = await group.parseAsync(['pr'], { from: 'user' }).catch((e: unknown) => e); + expect(thrown).toBeInstanceOf(CheckExit); + expect((thrown as CheckExit).code).toBe(2); + expect((thrown as CheckExit).commanderError).toBeInstanceOf(CommanderError); + expect((thrown as CheckExit).commanderError.code).toBe('commander.missingArgument'); + }); + it('an invalid PR number is exit 2: on stderr, or as the ErrorReport with --json', async () => { const human = await runCli(['pr', '12a']); expect(human).toMatchObject({ code: 2, stdout: '' }); @@ -114,9 +147,11 @@ describe('Spec 1951 — codev check pr through the CLI', { timeout: 30_000 }, () beforeEach(() => { fx = createFixture(); const forge = prViewOverride(fx); + const ci = commitChecksOverride(fx); + ci.answerAll(passing(2)); const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); forge.answer(prView(head)); - writeConfig(fx, { forge: { 'pr-view': forge.script } }); + writeConfig(fx, { forge: { 'pr-view': forge.script, 'commit-checks': ci.script } }); }); afterEach(() => { @@ -135,7 +170,9 @@ describe('Spec 1951 — codev check pr through the CLI', { timeout: 30_000 }, () expect(outcome.code).toBe(0); const report = JSON.parse(outcome.stdout); expect(report).toMatchObject({ schema: 1, command: 'pr', verdict: 'clear', pr: { number: 7 } }); - expect(report.checks.map((c: { id: string }) => c.id)).toEqual(['head', 'attribution', 'trial-merge', 'watched', 'overlap', 'size', 'to-read']); + expect(report.checks.map((c: { id: string }) => c.id)).toEqual([ + 'head', 'state', 'forge', 'attribution', 'trial-merge', 'checks', 'watched', 'linked-issue', 'overlap', 'size', 'to-read', + ]); }); }); diff --git a/packages/codev/src/commands/check/__tests__/check-pr-forge.test.ts b/packages/codev/src/commands/check/__tests__/check-pr-forge.test.ts new file mode 100644 index 000000000..adfc41933 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/check-pr-forge.test.ts @@ -0,0 +1,457 @@ +/** + * Spec 1951 — `codev check pr`: the checks that need the forge (POSIX). + * + * `state`, `forge`, `checks` (with the porch-only walk on real commits) and `linked-issue`. + * `pr-view` and `commit-checks` come from overrides that answer per call and per commit; a + * stub `git` first on PATH records every git call, so each case also proves nothing off the + * read-only list ran, and the repository state is compared before and after. + */ + +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { checkPr, renderPrHuman } from '../pr.js'; +import type { Check, CommandOptions, PrReport } from '../report.js'; +import { useFakeHome } from './helpers/fake-home.js'; +import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { + commitChecksOverride, + passing, + PR_BRANCH, + prView, + prViewOverride, + pushBranch, + writeConfig, + type CommitChecksOverride, + type PrViewOverride, + type Run, +} from './helpers/pr-fixture.js'; +import { expectPrReportShape } from './helpers/report-shape.js'; +import { createStubBin, type StubBin } from './helpers/stub-bin.js'; + +const isWindows = process.platform === 'win32'; + +useFakeHome(); + +let fx: Fixture; +let stub: StubBin; +let forge: PrViewOverride; +let ci: CommitChecksOverride; +let uninstall: () => void; + +function configure(extra: { forge?: Record; check?: Record } = {}): void { + writeConfig(fx, { forge: { 'pr-view': forge.script, 'commit-checks': ci.script, ...extra.forge }, ...(extra.check ? { check: extra.check } : {}) }); +} + +beforeEach(() => { + fx = createFixture(); + stub = createStubBin(path.join(fx.root, 'bin')); + uninstall = stub.install(); + forge = prViewOverride(fx); + ci = commitChecksOverride(fx); + configure(); +}); + +afterEach(() => { + uninstall(); + fx.cleanup(); +}); + +async function runReadOnly(extra: Partial = {}): Promise<{ report: PrReport; exitCode: number }> { + const before = snapshotRepoState(fx, fx.main); + const result = await checkPr('7', { cwd: fx.main, env: { ...fx.env, ...stub.env }, timeoutMs: 20_000, ...extra }); + if ('error' in result.report) throw new Error(`unexpected exit 2: ${result.report.error.message}`); + expect(snapshotRepoState(fx, fx.main)).toEqual(before); + expect(stub.violations()).toEqual([]); + expectPrReportShape(result.report); + return { report: result.report, exitCode: result.exitCode }; +} + +function byId(report: PrReport, id: string): Check { + const found = report.checks.find((c) => c.id === id); + if (!found) throw new Error(`no ${id} check`); + return found; +} + +function verdictLine(report: PrReport): string { + return renderPrHuman(report).split('\n')[0]; +} + +const PORCH_FILE = 'codev/projects/7-feature/status.yaml'; + +/** A code commit, then `porch` porch-only commits, pushed. `tail` is newest first. */ +function prWithPorchTail(porch: number): { dir: string; code: string; tail: string[]; head: string } { + const { dir, head: code } = pushBranch(fx, [{ files: { 'src/a.ts': 'export const a = 1;\n' }, message: 'the code' }]); + const tail: string[] = []; + for (let i = 0; i < porch; i++) tail.unshift(fx.commit(dir, { [PORCH_FILE]: `step: ${i}\n` }, `chore(porch): 7 step ${i}`)); + if (porch > 0) fx.git(dir, 'push', '-q', 'origin', PR_BRANCH); + return { dir, code, tail, head: tail[0] ?? code }; +} + +const running = (n: number): Run[] => Array.from({ length: n }, (_, i) => ({ name: `ci-${i + 1}`, state: 'pending' as const })); + +describe.skipIf(isWindows)('Spec 1951 — check pr: forge state and CI (stub git)', { timeout: 30_000 }, () => { + it('Scenario 1: a clean PR, all runs green on head, is CLEAR in under 25 lines', async () => { + const { head } = pushBranch(fx, [{ files: { 'src/a.ts': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + ci.answer(head, passing(8)); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(0); + expect(report.verdict).toBe('clear'); + for (const c of report.checks) expect(['ok', 'info', 'off'], c.id).toContain(c.status); + expect(byId(report, 'state')).toMatchObject({ status: 'ok', details: { state: 'OPEN', draft: false } }); + expect(byId(report, 'forge')).toMatchObject({ status: 'ok', summary: 'MERGEABLE, CLEAN', details: { mergeable: 'MERGEABLE', mergeStateStatus: 'CLEAN' } }); + expect(byId(report, 'checks')).toMatchObject({ + status: 'ok', + summary: `head ${head.slice(0, 7)}: 8 passed`, + details: { lastCodeCommit: head, porchOnlyAbove: 0, head: { sha: head, passed: 8 }, code: { sha: head } }, + }); + expect(byId(report, 'linked-issue')).toMatchObject({ status: 'info', summary: `"Fixes #7" — matches ${PR_BRANCH}` }); + expect(ci.calls()).toEqual([head]); + + const human = renderPrHuman(report); + expect(human.split('\n')[0]).toBe('CLEAR PR #7 — ready to recommend'); + expect(human.trimEnd().split('\n').length).toBeLessThanOrEqual(25); + // An ok head and state read in the header, not as lines of their own. + expect(human).toContain('OPEN builder/spir-7 → main'); + expect(human).not.toMatch(/\n {2}ok +state /); + expect(human).toMatch(/\n {2}ok +checks +head [0-9a-f]{7}: 8 passed\n/); + }); + + describe('Scenario 7: porch-only commits above the code', () => { + it('runs only on the code commit: the walk finds it past the porch commits', async () => { + const { code, tail, head } = prWithPorchTail(2); + forge.answer(prView(head)); + ci.answer(code, passing(8)); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(0); + expect(byId(report, 'checks')).toMatchObject({ + status: 'ok', + summary: `code ${code.slice(0, 7)}: 8 passed\nhead ${head.slice(0, 7)}: no runs — 2 porch-state commits above the code`, + details: { lastCodeCommit: code, porchOnlyAbove: 2 }, + }); + expect(ci.calls()).toEqual([...tail, code]); + expect(renderPrHuman(report)).toContain(`checks code ${code.slice(0, 7)}: 8 passed\n`); + }); + + it('runs only on head, all passed: one line, head alone looked up', async () => { + const { head } = prWithPorchTail(1); + forge.answer(prView(head)); + ci.answer(head, passing(8)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'checks')).toMatchObject({ status: 'ok', summary: `head ${head.slice(0, 7)}: porch-only, 8 passed` }); + expect(ci.calls()).toEqual([head]); + }); + + it('runs on a push tip between them', async () => { + const { code, tail, head } = prWithPorchTail(3); + forge.answer(prView(head)); + ci.answer(tail[1], passing(8)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'checks')).toMatchObject({ + status: 'ok', + summary: `code ${tail[1].slice(0, 7)}: 8 passed\nhead ${head.slice(0, 7)}: no runs — 3 porch-state commits above the code`, + details: { code: { sha: tail[1] }, lastCodeCommit: code }, + }); + expect(ci.calls()).toEqual([head, tail[1]]); + }); + + it('no runs anywhere is attention: checks (none)', async () => { + const { code, head } = prWithPorchTail(1); + forge.answer(prView(head)); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(1); + expect(byId(report, 'checks')).toMatchObject({ + status: 'attention', + summary: `code ${code.slice(0, 7)}: no runs\nhead ${head.slice(0, 7)}: no runs — 1 porch-state commit above the code`, + }); + expect(verdictLine(report)).toBe('ATTENTION PR #7 — checks (none)'); + }); + + it('a failure on head while the code commit is green: checks (failed)', async () => { + const { code, head } = prWithPorchTail(1); + forge.answer(prView(head)); + ci.answer(head, [...passing(7), { name: 'unit', state: 'fail' }]); + ci.answer(code, passing(8)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'checks').summary).toBe(`code ${code.slice(0, 7)}: 8 passed\nhead ${head.slice(0, 7)}: porch-only, 7 passed, 1 failed (unit)`); + expect(verdictLine(report)).toBe('ATTENTION PR #7 — checks (failed)'); + }); + + it('head pending while the code is green: "still running" on head, checks (running)', async () => { + const { code, head } = prWithPorchTail(1); + forge.answer(prView(head)); + ci.answer(head, running(8)); + ci.answer(code, passing(8)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'checks')).toMatchObject({ + status: 'attention', + summary: `code ${code.slice(0, 7)}: 8 passed\nhead ${head.slice(0, 7)}: porch-only, 8 still running`, + }); + expect(verdictLine(report)).toBe('ATTENTION PR #7 — checks (running)'); + }); + + it('head pending while the code failed: checks (failed)', async () => { + const { code, head } = prWithPorchTail(1); + forge.answer(prView(head)); + ci.answer(head, running(8)); + ci.answer(code, [...passing(7), { name: 'unit', state: 'fail' }]); + + const { report } = await runReadOnly(); + + expect(byId(report, 'checks').summary).toBe(`code ${code.slice(0, 7)}: 7 passed, 1 failed (unit)\nhead ${head.slice(0, 7)}: porch-only, 8 still running`); + expect(verdictLine(report)).toBe('ATTENTION PR #7 — checks (failed)'); + }); + + it('a commit touching anything outside codev/projects/ is code, a thread log included', async () => { + const { dir, head: porch } = prWithPorchTail(1); + const thread = fx.commit(dir, { 'codev/state/spir-7_thread.md': 'log\n' }, 'thread log'); + fx.git(dir, 'push', '-q', 'origin', PR_BRANCH); + forge.answer(prView(thread)); + ci.answer(thread, passing(2)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'checks').details).toMatchObject({ lastCodeCommit: thread, porchOnlyAbove: 0 }); + expect(porch).not.toBe(thread); + }); + + it('a merge commit at head is never porch-only', async () => { + const { dir } = prWithPorchTail(1); + fx.commit(fx.main, { 'later.txt': 'later\n' }, 'main moves on'); + fx.git(fx.main, 'push', '-q', 'origin', 'main'); + fx.git(dir, 'merge', '-q', '--no-ff', '-m', 'merge main', 'origin/main'); + const merge = fx.git(dir, 'rev-parse', 'HEAD').trim(); + fx.git(dir, 'push', '-q', 'origin', PR_BRANCH); + forge.answer(prView(merge)); + ci.answer(merge, passing(2)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'checks')).toMatchObject({ status: 'ok', details: { lastCodeCommit: merge, porchOnlyAbove: 0 } }); + }); + + it('more than 10 porch-only commits: not run, nothing looked up', async () => { + const { head } = prWithPorchTail(11); + forge.answer(prView(head)); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(1); + expect(byId(report, 'checks')).toMatchObject({ status: 'not-run', reason: 'more than 10 porch-only commits' }); + expect(ci.calls()).toEqual([]); + }); + + it('exactly 10 porch-only commits: at most 10 lookups, the code commit among them', async () => { + const { code, head } = prWithPorchTail(10); + forge.answer(prView(head)); + ci.answer(code, passing(3)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'checks')).toMatchObject({ status: 'ok', details: { lastCodeCommit: code, porchOnlyAbove: 10 } }); + expect(ci.calls()).toHaveLength(10); + expect(ci.calls().at(-1)).toBe(code); + }); + + it('a branch of porch-only commits has no code commit: attention', async () => { + const { dir } = pushBranch(fx, [{ files: { [PORCH_FILE]: 'step: 0\n' }, message: 'chore(porch): 7 init' }]); + const head = fx.commit(dir, { [PORCH_FILE]: 'step: 1\n' }, 'chore(porch): 7 next'); + fx.git(dir, 'push', '-q', 'origin', PR_BRANCH); + forge.answer(prView(head)); + ci.answer(head, passing(2)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'checks')).toMatchObject({ + status: 'attention', + summary: `head ${head.slice(0, 7)}: 2 passed — no code commit: all 2 commits since the branch point are porch-only`, + details: { lastCodeCommit: null, porchOnlyAbove: 2 }, + }); + }); + }); + + describe('Scenario 10: state', () => { + it.each([ + ['a draft', { isDraft: true }, 'OPEN but a draft: it must be marked ready for review first', 'state (draft)'], + ['a closed PR', { state: 'CLOSED' }, 'CLOSED: only an open PR can be recommended', 'state (closed)'], + ['a merged PR', { state: 'MERGED', mergedAt: '2026-11-20T10:00:00Z' }, 'MERGED: only an open PR can be recommended', 'state (merged)'], + ['a merged PR a forge calls closed', { state: 'closed', mergedAt: '2026-11-20T10:00:00Z' }, 'MERGED: only an open PR can be recommended', 'state (merged)'], + ])('%s needs attention and can never read CLEAR', async (_name, fields, summary, named) => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head, fields)); + ci.answer(head, passing(2)); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(1); + expect(byId(report, 'state')).toMatchObject({ status: 'attention', summary }); + expect(verdictLine(report)).toBe(`ATTENTION PR #7 — ${named}`); + expect(renderPrHuman(report)).toMatch(/\n {2}ATTN +state +/); + }); + + it("GitLab's lower-case 'opened' is OPEN", async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head, { state: 'opened' })); + ci.answer(head, passing(2)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'state')).toMatchObject({ status: 'ok', details: { state: 'OPEN' } }); + expect(report.pr.state).toBe('OPEN'); + expect(report.verdict).toBe('clear'); + }); + }); + + describe('forge mergeability', () => { + it('CONFLICTING needs attention', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head, { mergeable: 'CONFLICTING', mergeStateStatus: 'DIRTY' })); + ci.answer(head, passing(2)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'forge')).toMatchObject({ status: 'attention', summary: 'CONFLICTING, DIRTY' }); + expect(verdictLine(report)).toBe('ATTENTION PR #7 — forge (conflicts)'); + }); + + it('BLOCKED by a required review is still MERGEABLE: ok, with the reason', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head, { mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED' })); + ci.answer(head, passing(2)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'forge')).toMatchObject({ + status: 'ok', + summary: 'MERGEABLE, BLOCKED (review required)', + details: { mergeable: 'MERGEABLE', mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED' }, + }); + expect(report.verdict).toBe('clear'); + }); + + it('UNKNOWN at the first read takes the re-read', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + forge.answerOn(1, prView(head, { mergeable: 'UNKNOWN', mergeStateStatus: 'UNKNOWN' })); + ci.answer(head, passing(2)); + + const { report } = await runReadOnly(); + + expect(forge.calls()).toBe(2); + expect(byId(report, 'forge')).toMatchObject({ status: 'ok', summary: 'MERGEABLE, CLEAN' }); + }); + + it('UNKNOWN twice: the forge has not computed it yet', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head, { mergeable: 'UNKNOWN', mergeStateStatus: 'UNKNOWN' })); + ci.answer(head, passing(2)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'forge')).toMatchObject({ status: 'attention', summary: 'forge has not computed mergeability yet; re-run shortly' }); + expect(verdictLine(report)).toBe('ATTENTION PR #7 — forge (not computed)'); + }); + }); + + it('Scenario 12a: a closing keyword for another issue needs attention', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head, { body: 'Fixes #8' })); + ci.answer(head, passing(2)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'linked-issue')).toMatchObject({ status: 'attention', summary: `"Fixes #8", but ${PR_BRANCH} is for #7` }); + expect(verdictLine(report)).toBe('ATTENTION PR #7 — linked issue (wrong issue)'); + }); + + describe('Scenario 24: a field or concept the forge cannot provide is not run, never ok', () => { + it.each([ + ['state', 'state', 'pr-view did not return state'], + ['isDraft', 'state', 'pr-view did not return isDraft'], + ['mergeable', 'forge', 'pr-view did not return mergeable'], + ])('pr-view without %s', async (field, id, reason) => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + const view = prView(head); + delete view[field]; + forge.answer(view); + ci.answer(head, passing(2)); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(1); + expect(byId(report, id)).toMatchObject({ status: 'not-run', reason }); + expect(verdictLine(report)).toContain(`${id} (not run)`); + }); + + it('commit-checks disabled', async () => { + configure({ forge: { 'commit-checks': null } }); + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(1); + expect(byId(report, 'checks')).toMatchObject({ status: 'not-run', reason: 'commit-checks unavailable on github' }); + }); + + it('commit-checks failing', async () => { + ci.fail(); + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(1); + expect(byId(report, 'checks')).toMatchObject({ status: 'not-run', reason: 'commit-checks failed: commit-checks stub: forge unreachable' }); + }); + + it('commit-checks returning something off the contract', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + ci.answer(head, '[{"name": "unit", "state": "success"}]'); + + const { report } = await runReadOnly(); + + expect(byId(report, 'checks')).toMatchObject({ status: 'not-run', reason: expect.stringMatching(/^commit-checks item 1 \(unit\) has state "success"/) }); + }); + }); + + it('Scenario 12b: a commit-checks that never answers leaves checks not run within the time limit', async () => { + ci.hang(); + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + const started = Date.now(); + + const { report, exitCode } = await runReadOnly({ timeoutMs: 1_000 }); + + expect(exitCode).toBe(1); + expect(byId(report, 'checks')).toMatchObject({ status: 'not-run', reason: 'commit-checks timed out after 1s' }); + expect(Date.now() - started).toBeLessThan(15_000); + }); + + it('check.skip ["checks"] skips it by name without asking the forge', async () => { + configure({ check: { skip: ['checks'] } }); + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'checks')).toMatchObject({ status: 'skip', reason: 'check.skip' }); + expect(ci.calls()).toEqual([]); + expect(report.verdict).toBe('clear'); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/check-pr-mechanics.test.ts b/packages/codev/src/commands/check/__tests__/check-pr-mechanics.test.ts index 74b762030..db051f122 100644 --- a/packages/codev/src/commands/check/__tests__/check-pr-mechanics.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-pr-mechanics.test.ts @@ -5,6 +5,8 @@ * a stub `git` first on PATH records every git call and passes it to the real git, so each * test also proves that nothing off the read-only list ran. Every scenario runs on a real * repository with a bare origin, and the repository state is compared before and after. + * `commit-checks` comes from an override that reports three passing runs on every commit; + * the CI selection itself is tested in check-pr-forge.test.ts. */ import { spawn as realSpawn } from 'node:child_process'; @@ -16,7 +18,20 @@ import type { Check, CommandOptions, ErrorReport, PrReport } from '../report.js' import { createRunner, type SpawnFn } from '../runner.js'; import { useFakeHome } from './helpers/fake-home.js'; import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; -import { otherClone, PR_BRANCH, PR_NUMBER, PR_VIEW_FIELDS, prView, pushBranch, pushFromElsewhere, writeConfig } from './helpers/pr-fixture.js'; +import { + commitChecksOverride, + otherClone, + passing, + PR_BRANCH, + PR_NUMBER, + PR_VIEW_FIELDS, + prView, + pushBranch, + pushFromElsewhere, + writeConfig, + type CommitChecksOverride, +} from './helpers/pr-fixture.js'; +import { expectPrReportShape } from './helpers/report-shape.js'; import { createStubBin, type StubBin } from './helpers/stub-bin.js'; const isWindows = process.platform === 'win32'; @@ -25,12 +40,21 @@ useFakeHome(); let fx: Fixture; let stub: StubBin; +let ci: CommitChecksOverride; let uninstall: () => void; +/** The project configuration: `check` settings, with `commit-checks` from the override. */ +function configure(check?: Record): void { + writeConfig(fx, { forge: { 'commit-checks': ci.script }, ...(check ? { check } : {}) }); +} + beforeEach(() => { fx = createFixture(); stub = createStubBin(path.join(fx.root, 'bin')); uninstall = stub.install(); + ci = commitChecksOverride(fx); + ci.answerAll(passing(3)); + configure(); }); afterEach(() => { @@ -68,6 +92,7 @@ async function runReadOnly(extra: Partial = {}) { const result = await runReport(extra); expect(snapshotRepoState(fx, fx.main)).toEqual(before); expect(stub.violations()).toEqual([]); + expectPrReportShape(result.report); return result; } @@ -84,9 +109,13 @@ describe.skipIf(isWindows)('Spec 1951 — check pr: merge mechanics (stub gh and expect(report.verdict).toBe('clear'); expect(statuses(report)).toEqual({ head: 'ok', + state: 'ok', + forge: 'ok', attribution: 'off', 'trial-merge': 'ok', + checks: 'ok', watched: 'ok', + 'linked-issue': 'info', overlap: 'info', size: 'info', 'to-read': 'info', @@ -159,10 +188,12 @@ describe.skipIf(isWindows)('Spec 1951 — check pr: merge mechanics (stub gh and const { report, exitCode } = await runReadOnly(); expect(exitCode).toBe(1); - for (const id of ['trial-merge', 'watched', 'overlap', 'size', 'to-read']) { + for (const id of ['trial-merge', 'checks', 'watched', 'overlap', 'size', 'to-read']) { expect(byId(report, id), id).toMatchObject({ status: 'not-run', reason: expect.stringMatching(/^eeeeeee not available locally \(fetch failed/) }); } - expect(report.checks.some((c) => c.status === 'ok' && c.id !== 'head')).toBe(false); + // Only what the forge itself reports can be ok without the head's objects. + expect(report.checks.filter((c) => c.status === 'ok').map((c) => c.id)).toEqual(['head', 'state', 'forge']); + expect(ci.calls()).toEqual([]); }); it('a base branch origin does not have leaves the base checks not run', async () => { @@ -178,7 +209,7 @@ describe.skipIf(isWindows)('Spec 1951 — check pr: merge mechanics (stub gh and }); it('Scenario 6: attribution in a commit and in the description is reported by place; base commits are not scanned', async () => { - writeConfig(fx, { check: { attribution: ['^\\s*Co-Authored-By:'] } }); + configure({ attribution: ['^\\s*Co-Authored-By:'] }); fx.commit(fx.main, { 'old.txt': 'old\n' }, 'already on main\n\nCo-Authored-By: Someone '); fx.git(fx.main, 'push', '-q', 'origin', 'main'); const { head } = pushBranch(fx, [ @@ -211,12 +242,12 @@ describe.skipIf(isWindows)('Spec 1951 — check pr: merge mechanics (stub gh and summary: 'no patterns configured (check.attribution)', }); - writeConfig(fx, { check: { attribution: ['Generated with \\[Claude Code\\]'] } }); + configure({ attribution: ['Generated with \\[Claude Code\\]'] }); expect(byId((await runReadOnly()).report, 'attribution')).toMatchObject({ status: 'ok', summary: 'none in the description or 1 commit' }); }); it('Scenario 8: a flagged watched file needs attention; an unflagged one is info', async () => { - writeConfig(fx, { check: { flag: ['CLAUDE.md'] } }); + configure({ flag: ['CLAUDE.md'] }); const { head } = pushBranch(fx, [ { files: { 'CLAUDE.md': 'rules\n', 'codev/roles/architect.md': 'role\n', 'src/a.ts': 'a\n' }, message: 'instructions' }, ]); @@ -232,7 +263,7 @@ describe.skipIf(isWindows)('Spec 1951 — check pr: merge mechanics (stub gh and }); expect(renderPrHuman(report).split('\n')[0]).toBe('ATTENTION PR #7 — watched (flagged)'); - writeConfig(fx, { check: { flag: ['src/**'] } }); + configure({ flag: ['src/**'] }); // check.flag applies only to watched files: src/a.ts is flagged but not watched. expect(byId((await runReadOnly()).report, 'watched')).toMatchObject({ status: 'info' }); }); @@ -264,7 +295,7 @@ describe.skipIf(isWindows)('Spec 1951 — check pr: merge mechanics (stub gh and }); expect(first.summary).toBe('2 files (4 not for reading): src/big.ts, src/small.ts'); - writeConfig(fx, { check: { notForReading: ['src/small.ts'] } }); + configure({ notForReading: ['src/small.ts'] }); const replaced = byId((await runReadOnly()).report, 'to-read'); expect((replaced.details.files as Array<{ path: string }>).map((f) => f.path)).toEqual([ 'src/big.ts', @@ -325,12 +356,41 @@ describe.skipIf(isWindows)('Spec 1951 — check pr: merge mechanics (stub gh and expect(byId(report, 'head')).toMatchObject({ status: 'info', summary: `origin's main is at ${originMain.slice(0, 7)}, not the PR head (a fork's PR, or the branch moved): local main not compared`, - details: { relation: 'not-origin-branch', originBranchSha: originMain }, + details: { relation: 'not-origin-branch', originBranchSha: originMain, localBranchSha: originMain, forgeHead: head }, }); expect(byId(report, 'trial-merge').status).toBe('ok'); expect(report.verdict).toBe('clear'); }); + it("origin's branch past the forge head is a push the forge has not indexed: attention, not the fork note", async () => { + const { dir, head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'indexed' }]); + const pushed = fx.commit(dir, { 'b.txt': 'b\n' }, 'pushed, not indexed yet'); + fx.git(dir, 'push', '-q', 'origin', PR_BRANCH); + answerPrView(prView(head)); + + const { report, exitCode } = await runReadOnly(); + + expect(exitCode).toBe(1); + expect(byId(report, 'head')).toMatchObject({ + status: 'attention', + summary: `origin's ${PR_BRANCH} is 1 commit past the PR head (a push the forge has not indexed yet); re-run`, + details: { relation: 'origin-ahead', forgeHead: head, originBranchSha: pushed, localBranchSha: pushed, originAheadOfPr: 1 }, + }); + expect(renderPrHuman(report).split('\n')[0]).toBe('ATTENTION PR #7 — head (forge behind)'); + }); + + it("an origin tip that is not local is not compared: the fork note, nothing fetched for it", async () => { + const { dir, head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'indexed' }]); + fx.commit(dir, { 'mine.txt': 'm\n' }, 'local only'); + const elsewhere = pushFromElsewhere(fx, PR_BRANCH, { 'theirs.txt': 't\n' }); + answerPrView(prView(head)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'head')).toMatchObject({ status: 'info', details: { relation: 'not-origin-branch', originBranchSha: elsewhere } }); + expect(stub.gitCalls().filter((c) => c.includes(' fetch '))).toEqual([]); + }); + it('Scenario 25: pr-view without headRefOid is exit 2 naming the concept and the field', async () => { const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); const view = prView(head); diff --git a/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts b/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts index 829f1dfff..217d3208f 100644 --- a/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts @@ -1,8 +1,8 @@ /** * Spec 1951 — `codev check pr` against real repositories, on every platform. * - * The forge comes from a `pr-view` concept override (a `.sh` script Git Bash runs on - * Windows), so neither `gh` nor a network is needed. These tests prove that no ref, `HEAD`, + * The forge comes from `pr-view` and `commit-checks` concept overrides (`.sh` scripts Git + * Bash runs on Windows), so neither `gh` nor a network is needed. These tests prove that no ref, `HEAD`, * index byte, `FETCH_HEAD` or status line changes (Scenario 23), that a head or base moving * during the run is caught (Scenario 11), that a hanging anchor read is exit 2 (Scenario * 12b), and that the command reports the same from a builder worktree as from the main @@ -18,7 +18,9 @@ import type { SpawnFn } from '../runner.js'; import { useFakeHome } from './helpers/fake-home.js'; import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; import { + commitChecksOverride, otherClone, + passing, PR_BRANCH, prView, prViewOverride, @@ -26,6 +28,7 @@ import { pushFromElsewhere, shPath, writeConfig, + type CommitChecksOverride, type PrViewOverride, } from './helpers/pr-fixture.js'; @@ -33,10 +36,13 @@ useFakeHome(); let fx: Fixture; let forge: PrViewOverride; +let ci: CommitChecksOverride; beforeEach(() => { fx = createFixture(); forge = prViewOverride(fx); + ci = commitChecksOverride(fx); + ci.answerAll(passing(3)); }); afterEach(() => { @@ -44,7 +50,7 @@ afterEach(() => { }); function configure(check: Record = {}): string { - return writeConfig(fx, { forge: { 'pr-view': forge.script }, check }); + return writeConfig(fx, { forge: { 'pr-view': forge.script, 'commit-checks': ci.script }, check }); } async function run(extra: Partial = {}, number = '7') { diff --git a/packages/codev/src/commands/check/__tests__/helpers/pr-fixture.ts b/packages/codev/src/commands/check/__tests__/helpers/pr-fixture.ts index 9b3af2311..2eabf7390 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/pr-fixture.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/pr-fixture.ts @@ -128,3 +128,65 @@ export function prViewOverride(fx: Fixture): PrViewOverride { }, }; } + +export interface Run { + name: string; + state: 'pass' | 'fail' | 'pending' | 'skipped' | 'neutral'; + url?: string; + workflow?: string; +} + +/** `n` passing runs named `ci-1` … `ci-n`. */ +export function passing(n: number): Run[] { + return Array.from({ length: n }, (_, i) => ({ name: `ci-${i + 1}`, state: 'pass' as const })); +} + +export interface CommitChecksOverride { + /** The absolute script path, to put in `forge["commit-checks"]`. */ + script: string; + /** The runs on `sha` (or raw output). A commit with no answer gets the default. */ + answer(sha: string, runs: Run[] | string): void; + /** The answer for every commit without one of its own; `[]` (no runs) until set. */ + answerAll(runs: Run[] | string): void; + /** Make every call fail with exit 1. */ + fail(): void; + /** Make every call hang, for the time limit. */ + hang(): void; + /** The SHAs asked for, in order. */ + calls(): string[]; +} + +/** A `commit-checks` override answering per commit from files, like `prViewOverride`. */ +export function commitChecksOverride(fx: Fixture): CommitChecksOverride { + const dir = path.join(fx.root, 'forge-checks'); + fs.mkdirSync(dir, { recursive: true }); + const script = path.join(dir, 'commit-checks.sh'); + const d = shPath(dir); + fs.writeFileSync( + script, + [ + '#!/bin/sh', + `dir='${d}'`, + 'printf \'%s\\n\' "$CODEV_COMMIT_SHA" >> "$dir/calls"', + '[ -f "$dir/hang" ] && exec sleep 60', + 'if [ -f "$dir/fail" ]; then echo "commit-checks stub: forge unreachable" >&2; exit 1; fi', + 'if [ -f "$dir/$CODEV_COMMIT_SHA.json" ]; then cat "$dir/$CODEV_COMMIT_SHA.json"', + 'elif [ -f "$dir/default.json" ]; then cat "$dir/default.json"', + "else echo '[]'; fi", + '', + ].join('\n'), + { mode: 0o755 }, + ); + const text = (runs: Run[] | string): string => (typeof runs === 'string' ? runs : JSON.stringify(runs)); + return { + script, + answer: (sha, runs) => fs.writeFileSync(path.join(dir, `${sha}.json`), text(runs)), + answerAll: (runs) => fs.writeFileSync(path.join(dir, 'default.json'), text(runs)), + fail: () => fs.writeFileSync(path.join(dir, 'fail'), ''), + hang: () => fs.writeFileSync(path.join(dir, 'hang'), ''), + calls: () => { + const file = path.join(dir, 'calls'); + return fs.existsSync(file) ? fs.readFileSync(file, 'utf-8').split('\n').filter(Boolean) : []; + }, + }; +} diff --git a/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts b/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts new file mode 100644 index 000000000..6472aec4b --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts @@ -0,0 +1,57 @@ +/** + * Scenario 28 (Spec 1951 § JSON schema): a `PrReport` survives JSON and has the schema-1 + * shape, with every check id present in order and the verdict following the statuses. + */ + +import { expect } from 'vitest'; +import { PR_CHECK_IDS, type PrReport } from '../../report.js'; + +const STATUSES = ['ok', 'attention', 'info', 'not-run', 'off', 'skip']; +const WITH_REASON = new Set(['not-run', 'off', 'skip']); +const SHA = /^[0-9a-f]{40}$/; + +function expectCommitRuns(value: unknown, where: string): void { + expect(value, where).toMatchObject({ + sha: expect.stringMatching(SHA), + runs: expect.any(Array), + passed: expect.any(Number), + failed: expect.any(Number), + pending: expect.any(Number), + }); + const runs = (value as { runs: unknown[] }).runs; + for (const run of runs) { + expect(run, where).toMatchObject({ name: expect.any(String), state: expect.stringMatching(/^(pass|fail|pending|skipped|neutral)$/) }); + } +} + +export function expectPrReportShape(report: PrReport): void { + const parsed = JSON.parse(JSON.stringify(report)) as PrReport; + expect(parsed).toMatchObject({ schema: 1, command: 'pr', verdict: expect.stringMatching(/^(clear|attention)$/), generatedAt: expect.any(String) }); + expect(Number.isNaN(Date.parse(parsed.generatedAt))).toBe(false); + + const { pr } = parsed; + expect(pr).toMatchObject({ number: expect.any(Number), title: expect.any(String), state: expect.any(String), headRef: expect.any(String), baseRef: expect.any(String) }); + expect(pr.head).toMatch(SHA); + expect(pr.baseTip === null || SHA.test(pr.baseTip)).toBe(true); + expect(pr.draft === null || typeof pr.draft === 'boolean').toBe(true); + if (pr.localBranch !== null) expect(pr.localBranch).toEqual({ name: expect.any(String), sha: expect.stringMatching(SHA) }); + + expect(parsed.checks.map((c) => c.id)).toEqual([...PR_CHECK_IDS]); + for (const c of parsed.checks) { + expect(STATUSES, c.id).toContain(c.status); + expect(typeof c.summary, c.id).toBe('string'); + expect(typeof c.details === 'object' && c.details !== null && !Array.isArray(c.details), c.id).toBe(true); + expect(typeof c.reason === 'string', `${c.id} reason`).toBe(WITH_REASON.has(c.status)); + if (c.status === 'not-run' || c.status === 'off' || c.status === 'skip') continue; + if (c.id === 'state') expect(c.details).toEqual({ state: expect.any(String), draft: expect.any(Boolean) }); + if (c.id === 'forge') expect(c.details).toHaveProperty('mergeable'); + if (c.id === 'checks') { + expectCommitRuns(c.details.head, 'checks.head'); + if ('code' in c.details) expectCommitRuns(c.details.code, 'checks.code'); + expect(c.details.lastCodeCommit === null || SHA.test(String(c.details.lastCodeCommit))).toBe(true); + expect(typeof c.details.porchOnlyAbove).toBe('number'); + } + } + const attention = parsed.checks.some((c) => c.status === 'attention' || c.status === 'not-run'); + expect(parsed.verdict).toBe(attention ? 'attention' : 'clear'); +} diff --git a/packages/codev/src/commands/check/__tests__/imports.test.ts b/packages/codev/src/commands/check/__tests__/imports.test.ts index fbe947962..afab7aad7 100644 --- a/packages/codev/src/commands/check/__tests__/imports.test.ts +++ b/packages/codev/src/commands/check/__tests__/imports.test.ts @@ -31,9 +31,13 @@ const ALLOWED: Record = { names: ['loadConfig', 'findConfigSource'], reason: 'reads configuration files; never writes or spawns', }, +}; + +/** index.ts alone parses arguments. */ +const INDEX_ALLOWED: Record = { commander: { names: ['Command', 'CommanderError'], - reason: 'argument parsing for the check group (index.ts); only action-handler subcommands, never the executable form that spawns', + reason: 'argument parsing for the check group; only action-handler subcommands, never the executable form that spawns', }, }; @@ -46,6 +50,12 @@ const RUNNER_ALLOWED: Record = { }, }; +/** The extra imports each file may have, beyond ALLOWED. */ +const PER_FILE: Record> = { + 'runner.ts': RUNNER_ALLOWED, + 'index.ts': INDEX_ALLOWED, +}; + interface ParsedImport { specifier: string; names: string[] | '*'; @@ -88,7 +98,8 @@ describe('Spec 1951 — audited imports in commands/check/', () => { it('audits every source file in the directory', () => { expect(sources).toEqual( expect.arrayContaining([ - 'allow-list.ts', 'git-facts.ts', 'index.ts', 'pr.ts', 'render.ts', 'report.ts', 'roots.ts', 'runner.ts', 'settings.ts', 'validate.ts', + 'allow-list.ts', 'git-facts.ts', 'index.ts', 'linked-issue.ts', 'porch-only.ts', 'pr.ts', 'render.ts', 'report.ts', 'roots.ts', + 'runner.ts', 'settings.ts', 'validate.ts', ]), ); }); @@ -96,7 +107,7 @@ describe('Spec 1951 — audited imports in commands/check/', () => { it.each(sources)('%s imports only what the list allows', (file) => { const { imports, dynamic } = parseImports(fs.readFileSync(path.join(CHECK_DIR, file), 'utf-8')); expect(dynamic, `${file} uses a dynamic import or require`).toEqual([]); - const rules = file === 'runner.ts' ? { ...ALLOWED, ...RUNNER_ALLOWED } : ALLOWED; + const rules = { ...ALLOWED, ...PER_FILE[file] }; for (const imp of imports) { if (imp.typeOnly) continue; if (imp.specifier.startsWith('./')) { @@ -113,6 +124,13 @@ describe('Spec 1951 — audited imports in commands/check/', () => { } }); + it('only index.ts imports commander', () => { + for (const file of sources.filter((f) => f !== 'index.ts')) { + const { imports } = parseImports(fs.readFileSync(path.join(CHECK_DIR, file), 'utf-8')); + expect(imports.filter((i) => !i.typeOnly && i.specifier === 'commander').map((i) => i.specifier), file).toEqual([]); + } + }); + it('only runner.ts imports child_process or the forge dispatcher', () => { for (const file of sources.filter((f) => f !== 'runner.ts')) { const { imports } = parseImports(fs.readFileSync(path.join(CHECK_DIR, file), 'utf-8')); diff --git a/packages/codev/src/commands/check/__tests__/linked-issue.test.ts b/packages/codev/src/commands/check/__tests__/linked-issue.test.ts new file mode 100644 index 000000000..e4c2e624f --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/linked-issue.test.ts @@ -0,0 +1,95 @@ +/** + * Spec 1951 — the `linked-issue` check: closing keywords in the description against the + * builder branch's issue (Scenario 12a). + */ + +import { describe, expect, it } from 'vitest'; +import { branchIssue, checkLinkedIssue, closingReferences } from '../linked-issue.js'; + +describe('Spec 1951 — closing keywords', () => { + it.each([ + ['close #1', 'close'], + ['closes #1', 'closes'], + ['Closed #1', 'Closed'], + ['fix #1', 'fix'], + ['Fixes #1', 'Fixes'], + ['FIXED #1', 'FIXED'], + ['resolve #1', 'resolve'], + ['Resolves: #1', 'Resolves'], + ['resolved #1', 'resolved'], + ])('%j is a closing keyword', (text, keyword) => { + expect(closingReferences(text)).toEqual([{ keyword, issue: 1 }]); + }); + + it.each([ + ['a word that only ends in one', 'prefixes #1'], + ['a keyword run into the number', 'Fixes#1'], + ['another repository', 'Fixes owner/repo#1'], + ['a mention without a keyword', 'See #1'], + ['an inflection GitHub does not take', 'Fixing #1'], + ])('%s is not one: %j', (_name, text) => { + expect(closingReferences(text)).toEqual([]); + }); + + it('finds every reference, in order', () => { + expect(closingReferences('Fixes #12\n\nAlso closes #13 and resolves #12.')).toEqual([ + { keyword: 'Fixes', issue: 12 }, + { keyword: 'closes', issue: 13 }, + { keyword: 'resolves', issue: 12 }, + ]); + }); + + it('reads the issue from a builder/- branch only', () => { + expect(branchIssue('builder/spir-1951')).toBe(1951); + expect(branchIssue('builder/bugfix-42')).toBe(42); + expect(branchIssue('feature/1951')).toBeNull(); + expect(branchIssue('builder/spir-1951-extra')).toBeNull(); + expect(branchIssue('main')).toBeNull(); + }); +}); + +describe('Spec 1951 — Scenario 12a: the linked-issue check', () => { + it('a keyword naming the branch issue is info', () => { + expect(checkLinkedIssue('Summary\n\nFixes #1951', 'builder/spir-1951')).toEqual({ + id: 'linked-issue', + status: 'info', + summary: '"Fixes #1951" — matches builder/spir-1951', + details: { references: [{ keyword: 'Fixes', issue: 1951 }], branchIssue: 1951, keyword: 'Fixes', issue: 1951 }, + }); + }); + + it('no keyword is info with the close-by-hand note', () => { + expect(checkLinkedIssue('Part of #1951', 'builder/spir-1951')).toMatchObject({ + status: 'info', + summary: 'no closing keyword — close #1951 by hand after merge', + details: { references: [], branchIssue: 1951 }, + }); + }); + + it('a keyword naming a different issue needs attention', () => { + expect(checkLinkedIssue('Fixes #1950', 'builder/spir-1951')).toMatchObject({ + status: 'attention', + summary: '"Fixes #1950", but builder/spir-1951 is for #1951', + details: { keyword: 'Fixes', issue: 1950, branchIssue: 1951 }, + }); + }); + + it('the branch issue among several is info, naming the others', () => { + expect(checkLinkedIssue('Closes #1950\nFixes #1951', 'builder/spir-1951')).toMatchObject({ + status: 'info', + summary: '"Fixes #1951" — matches builder/spir-1951; also #1950', + }); + }); + + it('on a branch that names no issue, a keyword is info and none is the plain note', () => { + expect(checkLinkedIssue('Fixes #12', 'feature/x')).toMatchObject({ status: 'info', summary: '"Fixes #12"' }); + expect(checkLinkedIssue('nothing', 'feature/x')).toMatchObject({ status: 'info', summary: 'no closing keyword', details: { references: [] } }); + }); + + it('no description is not run, naming the concept', () => { + expect(checkLinkedIssue(null, 'builder/spir-1951')).toMatchObject({ + status: 'not-run', + reason: 'pr-view did not return body (the description)', + }); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/porch-only.test.ts b/packages/codev/src/commands/check/__tests__/porch-only.test.ts new file mode 100644 index 000000000..f676700b7 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/porch-only.test.ts @@ -0,0 +1,189 @@ +/** + * Spec 1951 — the porch-only rule and the choice of the code runs (§ Porch-only heads), + * as pure tables: the lookups come from a map, so each case names exactly which commits + * were asked for, what the `checks` line reads, and the verdict. + */ + +import { describe, expect, it } from 'vitest'; +import type { CommitCheckItem } from '../../../lib/forge-contracts.js'; +import { + checksProblem, + checksResult, + isPorchOnly, + MAX_LOOKUPS, + parseCommitChecks, + parseParents, + selectCodeRuns, + type RunsLookup, + type Selection, +} from '../porch-only.js'; +import { summarizeRuns, type CommitRuns } from '../report.js'; + +const sha = (c: string): string => c.repeat(40); +const H = sha('a'); +const T = sha('b'); +const C = sha('c'); + +const pass = (name: string): CommitCheckItem => ({ name, state: 'pass' }); +const fail = (name: string): CommitCheckItem => ({ name, state: 'fail' }); +const pending = (name: string): CommitCheckItem => ({ name, state: 'pending' }); +const green = [pass('build'), pass('unit'), pass('lint')]; + +function table(runs: Record): { lookup: RunsLookup } { + return { lookup: async (s) => ({ ok: true, value: summarizeRuns(s, runs[s] ?? []) }) }; +} + +async function select(range: string[], runs: Record): Promise { + const result = await selectCodeRuns(range, table(runs).lookup); + if (!result.ok) throw new Error(result.reason); + return result.value; +} + +describe('Spec 1951 — what is porch-only', () => { + it('one parent and only codev/projects/ paths', () => { + expect(isPorchOnly(1, ['codev/projects/1951-x/status.yaml'])).toBe(true); + expect(isPorchOnly(1, ['codev/projects/1951-x/status.yaml', 'codev/projects/1951-x/1951-review-iter1.md'])).toBe(true); + // An empty commit changes no code either. + expect(isPorchOnly(1, [])).toBe(true); + }); + + it('anything outside codev/projects/, a merge, or a root commit is code', () => { + expect(isPorchOnly(1, ['codev/projects/1951-x/status.yaml', 'src/a.ts'])).toBe(false); + expect(isPorchOnly(1, ['codev/state/spir-1951_thread.md'])).toBe(false); + expect(isPorchOnly(1, ['codev/projects.md'])).toBe(false); + expect(isPorchOnly(2, ['codev/projects/1951-x/status.yaml'])).toBe(false); + expect(isPorchOnly(0, [])).toBe(false); + }); + + it('parses rev-list --parents, refusing anything but SHAs', () => { + expect(parseParents(`${H} ${T}\n${T} ${C} ${sha('d')}\n${C}\n`)).toEqual([ + { sha: H, parents: [T] }, + { sha: T, parents: [C, sha('d')] }, + { sha: C, parents: [] }, + ]); + expect(() => parseParents('not-a-sha\n')).toThrow(/not a commit SHA/); + }); +}); + +describe('Spec 1951 — commit-checks output', () => { + it('accepts the contract, url and workflow optional', () => { + const items = [{ name: 'unit', state: 'pass', url: 'https://x.invalid/1', workflow: 'test.yml' }, { name: 'lint', state: 'neutral' }]; + expect(parseCommitChecks(items)).toEqual({ ok: true, value: items }); + expect(parseCommitChecks([])).toEqual({ ok: true, value: [] }); + }); + + it.each([ + ['an object', { name: 'unit' }, 'commit-checks returned something other than a JSON array'], + ['an item without a name', [{ state: 'pass' }], 'commit-checks item 1 has no name'], + ['an unknown state', [{ name: 'unit', state: 'success' }], 'commit-checks item 1 (unit) has state "success", not one of pass/fail/pending/skipped/neutral'], + ['a url that is not text', [{ name: 'unit', state: 'pass', url: 3 }], 'commit-checks item 1 (unit) has a url that is not a string'], + ['a non-object item', ['unit'], 'commit-checks item 1 is not an object'], + ])('refuses %s, naming the concept', (_name, data, reason) => { + expect(parseCommitChecks(data)).toEqual({ ok: false, reason }); + }); +}); + +describe('Spec 1951 — Scenario 7: choosing the code runs', () => { + it('runs only on the code commit: two lines, ok', async () => { + const range = [H, T, C]; + const selection = await select(range, { [C]: green }); + expect(selection.queried).toEqual([H, T, C]); + expect(checksResult(range, selection)).toMatchObject({ + status: 'ok', + summary: 'code ccccccc: 3 passed\nhead aaaaaaa: no runs — 2 porch-state commits above the code', + details: { lastCodeCommit: C, porchOnlyAbove: 2, code: { sha: C, passed: 3 }, head: { sha: H, runs: [] } }, + }); + }); + + it('runs only on head, all passed: one line, ok, nothing else looked up', async () => { + const range = [H, C]; + const selection = await select(range, { [H]: green }); + expect(selection.queried).toEqual([H]); + expect(checksResult(range, selection)).toMatchObject({ status: 'ok', summary: 'head aaaaaaa: porch-only, 3 passed' }); + }); + + it('runs on a push tip between them: the tip carries the code runs', async () => { + const range = [H, T, C]; + const selection = await select(range, { [T]: green }); + expect(selection.queried).toEqual([H, T]); + expect(checksResult(range, selection)).toMatchObject({ + status: 'ok', + summary: 'code bbbbbbb: 3 passed\nhead aaaaaaa: no runs — 2 porch-state commits above the code', + details: { code: { sha: T }, lastCodeCommit: C }, + }); + }); + + it('no runs anywhere: attention (none), no code runs in the details', async () => { + const range = [H, C]; + const result = checksResult(range, await select(range, {})); + expect(result).toMatchObject({ status: 'attention', summary: 'code ccccccc: no runs\nhead aaaaaaa: no runs — 1 porch-state commit above the code' }); + expect(result.details).not.toHaveProperty('code'); + expect(checksProblem(result.details.head as CommitRuns, null)).toBe('none'); + }); + + it('a failure on head while the code commit is green: attention (failed)', async () => { + const range = [H, C]; + const selection = await select(range, { [H]: [pass('build'), fail('unit')], [C]: green }); + expect(checksResult(range, selection)).toMatchObject({ + status: 'attention', + summary: 'code ccccccc: 3 passed\nhead aaaaaaa: porch-only, 1 passed, 1 failed (unit)', + }); + expect(checksProblem(selection.head, selection.code)).toBe('failed'); + }); + + it('head pending while the code is green: "still running" on head, attention (running)', async () => { + const range = [H, T, C]; + const selection = await select(range, { [H]: [pending('build'), pending('unit'), pending('lint')], [C]: green }); + expect(checksResult(range, selection)).toMatchObject({ + status: 'attention', + summary: 'code ccccccc: 3 passed\nhead aaaaaaa: porch-only, 3 still running', + }); + expect(checksProblem(selection.head, selection.code)).toBe('running'); + }); + + it('head pending while the code failed: attention (failed)', async () => { + const range = [H, C]; + const selection = await select(range, { [H]: [pending('unit')], [C]: [pass('build'), fail('unit')] }); + expect(checksResult(range, selection).summary).toBe('code ccccccc: 1 passed, 1 failed (unit)\nhead aaaaaaa: porch-only, 1 still running'); + expect(checksProblem(selection.head, selection.code)).toBe('failed'); + }); + + it('a complete older run wins over a pending newer one; failing that, the first with any runs', async () => { + const range = [H, T, C]; + const complete = await select(range, { [T]: [pending('unit')], [C]: [pass('unit')] }); + expect(complete.code?.sha).toBe(C); + + const onlyPending = await select(range, { [T]: [pending('unit')], [C]: [] }); + expect(onlyPending.code?.sha).toBe(T); + expect(checksProblem(onlyPending.head, onlyPending.code)).toBe('running'); + }); + + it('head is the code commit: one line, its own runs decide', async () => { + expect(checksResult([H], await select([H], { [H]: green }))).toMatchObject({ status: 'ok', summary: 'head aaaaaaa: 3 passed' }); + const none = checksResult([H], await select([H], {})); + expect(none).toMatchObject({ status: 'attention', summary: 'head aaaaaaa: no runs', details: { porchOnlyAbove: 0 } }); + const running = await select([H], { [H]: [pass('a'), pending('b')] }); + expect(checksResult([H], running)).toMatchObject({ status: 'attention', summary: 'head aaaaaaa: 1 passed, 1 still running' }); + expect(checksProblem(running.head, running.code)).toBe('running'); + }); + + it('skipped and neutral count as passed', async () => { + const runs: CommitCheckItem[] = [pass('build'), { name: 'docs', state: 'skipped' }, { name: 'bot', state: 'neutral' }]; + expect(checksResult([H], await select([H], { [H]: runs }))).toMatchObject({ status: 'ok', summary: 'head aaaaaaa: 3 passed' }); + }); + + it(`looks up at most ${MAX_LOOKUPS} commits, C always among them`, async () => { + const porch = Array.from({ length: 10 }, (_, i) => `${i}`.repeat(40)); + const range = [...porch, C]; + const selection = await select(range, {}); + expect(selection.queried).toHaveLength(MAX_LOOKUPS); + expect(selection.queried[0]).toBe(porch[0]); + expect(selection.queried[selection.queried.length - 1]).toBe(C); + expect(selection.queried).not.toContain(porch[9]); + }); + + it('a lookup that fails stops the selection with its reason', async () => { + const lookup: RunsLookup = async (s) => (s === T ? { ok: false, reason: 'commit-checks failed: HTTP 502' } : { ok: true, value: summarizeRuns(s, []) }); + expect(await selectCodeRuns([H, T, C], lookup)).toEqual({ ok: false, reason: 'commit-checks failed: HTTP 502' }); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts b/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts index 418e81b75..22b80ecdc 100644 --- a/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts +++ b/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts @@ -1,29 +1,51 @@ /** * Spec 1951 — the pure parsers behind `codev check pr`: the `pr-view` contract fields it * relies on, `git log -z` and `git merge-tree -z` output, per-line attribution matching, - * and width-bounded lists. + * width-bounded lists, state normalization and the forge mergeability mapping. */ import { describe, expect, it } from 'vitest'; -import { matchLines, parseLogMessages, parseMergeTree, parsePrView } from '../pr.js'; +import { checkForge, checkState, matchLines, normalizeState, parseLogMessages, parseMergeTree, parsePrView } from '../pr.js'; import { CheckCommandError, fitList } from '../report.js'; const SHA = 'a'.repeat(40); const SHA2 = 'b'.repeat(40); describe('Spec 1951 — parsePrView', () => { - const view = { title: 'T', body: 'B', state: 'OPEN', url: 'u', isDraft: true, headRefName: 'builder/spir-7', baseRefName: 'main', headRefOid: SHA }; + const view = { + title: 'T', + body: 'B', + state: 'OPEN', + url: 'u', + isDraft: true, + headRefName: 'builder/spir-7', + baseRefName: 'main', + headRefOid: SHA, + mergeable: 'MERGEABLE', + mergeStateStatus: 'BLOCKED', + reviewDecision: 'REVIEW_REQUIRED', + mergedAt: null, + }; it('reads the fields the command needs', () => { expect(parsePrView(view)).toEqual({ ok: true, - value: { title: 'T', body: 'B', state: 'OPEN', url: 'u', draft: true, headRef: 'builder/spir-7', baseRef: 'main', head: SHA }, + value: { + title: 'T', body: 'B', state: 'OPEN', url: 'u', draft: true, headRef: 'builder/spir-7', baseRef: 'main', head: SHA, + mergeable: 'MERGEABLE', mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED', mergedAt: null, + }, }); }); it('keeps optional fields it does not get as null, never a guess', () => { const result = parsePrView({ headRefName: 'b', baseRefName: 'main', headRefOid: SHA }); - expect(result).toEqual({ ok: true, value: { title: null, body: null, state: null, url: null, draft: null, headRef: 'b', baseRef: 'main', head: SHA } }); + expect(result).toEqual({ + ok: true, + value: { + title: null, body: null, state: null, url: null, draft: null, headRef: 'b', baseRef: 'main', head: SHA, + mergeable: null, mergeStateStatus: null, reviewDecision: null, mergedAt: null, + }, + }); }); it.each([ @@ -88,3 +110,56 @@ describe('Spec 1951 — fitList', () => { expect(fitList(['a-very-long-path', 'b'], 5)).toBe('a-very-long-path, … +1'); }); }); + +describe('Spec 1951 — state and forge from pr-view', () => { + const base = { headRefName: 'builder/spir-7', baseRefName: 'main', headRefOid: SHA, state: 'OPEN', isDraft: false, mergeable: 'MERGEABLE', mergeStateStatus: 'CLEAN' }; + const pr = (fields: Record = {}) => { + const parsed = parsePrView({ ...base, ...fields }); + if (!parsed.ok) throw new Error(parsed.reason); + return parsed.value; + }; + + it('normalizes the state word: upper-cased, OPENED is OPEN, a merge time means MERGED', () => { + expect(normalizeState('open', null)).toBe('OPEN'); + expect(normalizeState('opened', null)).toBe('OPEN'); + expect(normalizeState('OPEN', null)).toBe('OPEN'); + expect(normalizeState('closed', '2026-11-20T10:00:00Z')).toBe('MERGED'); + expect(normalizeState('closed', null)).toBe('CLOSED'); + }); + + it('only an open PR that is not a draft is ok', () => { + expect(checkState(pr())).toMatchObject({ status: 'ok', details: { state: 'OPEN', draft: false } }); + expect(checkState(pr({ isDraft: true }))).toMatchObject({ status: 'attention', details: { state: 'OPEN', draft: true } }); + expect(checkState(pr({ state: 'CLOSED', isDraft: true }))).toMatchObject({ status: 'attention', details: { state: 'CLOSED' } }); + expect(checkState(pr({ state: undefined }))).toMatchObject({ status: 'not-run', reason: 'pr-view did not return state' }); + expect(checkState(pr({ isDraft: 'no' }))).toMatchObject({ status: 'not-run', reason: 'pr-view did not return isDraft' }); + }); + + it.each([ + [{}, 'ok', 'MERGEABLE, CLEAN'], + [{ mergeStateStatus: undefined }, 'ok', 'MERGEABLE'], + [{ mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED' }, 'ok', 'MERGEABLE, BLOCKED (review required)'], + [{ mergeStateStatus: 'BLOCKED', reviewDecision: 'CHANGES_REQUESTED' }, 'ok', 'MERGEABLE, BLOCKED (changes requested)'], + [{ mergeStateStatus: 'BLOCKED', reviewDecision: 'APPROVED' }, 'ok', 'MERGEABLE, BLOCKED'], + [{ mergeStateStatus: 'UNSTABLE' }, 'ok', 'MERGEABLE, UNSTABLE'], + [{ mergeable: 'CONFLICTING', mergeStateStatus: 'DIRTY' }, 'attention', 'CONFLICTING, DIRTY'], + [{ mergeable: 'UNKNOWN' }, 'attention', 'forge has not computed mergeability yet; re-run shortly'], + ])('the verdict follows mergeable alone: %j', (fields, status, summary) => { + expect(checkForge(pr(fields), null)).toMatchObject({ status, summary }); + }); + + it('an UNKNOWN takes the re-read once; a re-read without the field keeps UNKNOWN', () => { + expect(checkForge(pr({ mergeable: 'UNKNOWN' }), pr())).toMatchObject({ status: 'ok', summary: 'MERGEABLE, CLEAN' }); + expect(checkForge(pr({ mergeable: 'UNKNOWN' }), pr({ mergeable: undefined }))).toMatchObject({ status: 'attention' }); + // A known first answer is not replaced. + expect(checkForge(pr({ mergeable: 'CONFLICTING' }), pr())).toMatchObject({ status: 'attention', summary: 'CONFLICTING, CLEAN' }); + }); + + it('a missing or off-contract mergeable is not run, naming the concept', () => { + expect(checkForge(pr({ mergeable: undefined }), null)).toMatchObject({ status: 'not-run', reason: 'pr-view did not return mergeable' }); + expect(checkForge(pr({ mergeable: 'YES' }), null)).toMatchObject({ + status: 'not-run', + reason: 'pr-view returned mergeable "YES", not MERGEABLE, CONFLICTING, UNKNOWN', + }); + }); +}); diff --git a/packages/codev/src/commands/check/index.ts b/packages/codev/src/commands/check/index.ts index 5fb006337..19f0003bb 100644 --- a/packages/codev/src/commands/check/index.ts +++ b/packages/codev/src/commands/check/index.ts @@ -6,6 +6,8 @@ * mapped to the same scheme: `--help` exits 0, and every usage error (unknown option, * missing or extra argument, unknown subcommand) exits 2, not commander's default 1. With * `--json`, a usage error on a subcommand prints that subcommand's `ErrorReport` on stdout. + * Commander's exits do not end the process here: they throw `CheckExit`, which carries the + * writes still in flight, and the caller (cli.ts) awaits them before exiting. * * Subcommands are action handlers only. Commander's executable-subcommand form, which * spawns a program, is never used, so the runner stays the only subprocess path. @@ -17,7 +19,10 @@ import { renderErrorHuman, renderJson } from './render.js'; import type { CommandName, CommandResult, ErrorReport, Report } from './report.js'; export interface CheckCliDeps { - /** End the process with this code. Production never returns; tests record the code and throw. */ + /** + * End the process with this code once a command has run. Production never returns; tests + * record the code and throw. Commander's own exits (help, usage errors) throw `CheckExit`. + */ exit: (code: number) => void; /** Write to stdout; resolves once the text is flushed, so a large `--json` survives the exit. */ stdout: (text: string) => void | Promise; @@ -42,6 +47,26 @@ const PROCESS_DEPS: CheckCliDeps = { argv: () => process.argv, }; +/** + * Thrown in place of commander's exit (help, version, usage errors): the exit code, and the + * writes still in flight, which must be flushed before the process exits. + */ +export class CheckExit extends Error { + constructor( + public readonly code: 0 | 2, + private readonly writes: ReadonlyArray>, + public readonly commanderError: CommanderError, + ) { + super(commanderError.message); + this.name = 'CheckExit'; + } + + /** Resolves once everything commander and the `--json` report wrote is flushed. */ + async flush(): Promise { + await Promise.all(this.writes); + } +} + /** Commander's exit, mapped: help and version 0, anything else a usage error, 2. */ export function exitCodeForCommander(err: CommanderError): 0 | 2 { if (err.code === 'commander.helpDisplayed' || err.code === 'commander.version') return 0; @@ -50,18 +75,23 @@ export function exitCodeForCommander(err: CommanderError): 0 | 2 { } export function buildCheckCommand(deps: CheckCliDeps = PROCESS_DEPS): Command { + /** Writes commander made (help, usage errors), for `CheckExit` to flush. */ + const inFlight: Array> = []; + const track = (write: void | Promise): void => { + inFlight.push(Promise.resolve(write)); + }; + /** * The exit callback commander calls instead of `process.exit`. It must not return: - * commander exits with its own code if it does, so it rethrows after `deps.exit`. + * commander exits with its own code if it does, so it throws `CheckExit`. */ const onCommanderExit = (command: CommandName | null) => (err: CommanderError): never => { const code = exitCodeForCommander(err); if (code === 2 && command !== null && deps.argv().includes('--json')) { const report: ErrorReport = { schema: 1, command, error: { message: err.message.replace(/^error: /, '') } }; - void deps.stdout(renderJson(report)); + track(deps.stdout(renderJson(report))); } - deps.exit(code); - throw err; + throw new CheckExit(code, [...inFlight], err); }; const finish = async (result: CommandResult, json: boolean, human: (report: R) => string): Promise => { @@ -77,12 +107,12 @@ export function buildCheckCommand(deps: CheckCliDeps = PROCESS_DEPS): Command { const group = new Command('check') .description('Read-only checks: merge readiness of a PR (never merges, pushes, comments or deletes)') - .configureOutput({ writeOut: (s) => void deps.stdout(s), writeErr: (s) => void deps.stderr(s) }); + .configureOutput({ writeOut: (s) => track(deps.stdout(s)), writeErr: (s) => track(deps.stderr(s)) }); group.exitOverride(onCommanderExit(null)); const pr = group .command('pr ') - .description('Merge mechanics of PR : exact head, live base, trial merge, attribution, watched files, size, files to read') + .description('Merge readiness of PR : exact head, state, forge mergeability, trial merge, CI on the code, attribution, watched files, linked issue, size, files to read') .option('--json', 'print one JSON object (schema 1) instead of the summary') .allowExcessArguments(false) .action(async (number: string, options: { json?: boolean }) => { diff --git a/packages/codev/src/commands/check/linked-issue.ts b/packages/codev/src/commands/check/linked-issue.ts new file mode 100644 index 000000000..c7b62060a --- /dev/null +++ b/packages/codev/src/commands/check/linked-issue.ts @@ -0,0 +1,60 @@ +/** + * The `linked-issue` check of `codev check pr` (Spec 1951 § Linked issue). + * + * The architect role requires that the issue closes when the PR merges. The description is + * read for GitHub's documented closing keywords (`close`, `closes`, `closed`, `fix`, `fixes`, + * `fixed`, `resolve`, `resolves`, `resolved`, optionally followed by a colon) before + * `#`. A `builder/-` branch names the issue it is for. + * + * - a keyword naming the branch's issue, or any keyword on another branch: `info` + * - no keyword: `info`, with the close-by-hand note (a partial fix legitimately has none) + * - keywords, none of them naming the branch's issue: attention + */ + +import { check, notRun, type Check } from './report.js'; + +const CLOSING_KEYWORD = /\b(close[sd]?|fix(?:e[sd])?|resolve[sd]?)\b:?\s+#(\d+)/gi; +const BUILDER_BRANCH = /^builder\/[a-z]+-(\d+)$/; + +export interface ClosingReference { + /** The keyword as written, e.g. `Fixes`. */ + keyword: string; + issue: number; +} + +/** Every closing keyword in `text`, in order. */ +export function closingReferences(text: string): ClosingReference[] { + return [...text.matchAll(CLOSING_KEYWORD)].map((m) => ({ keyword: m[1], issue: Number(m[2]) })); +} + +/** The issue a `builder/-` branch is for, or null for any other branch. */ +export function branchIssue(branch: string): number | null { + const match = BUILDER_BRANCH.exec(branch); + return match ? Number(match[1]) : null; +} + +function quote(ref: ClosingReference): string { + return `"${ref.keyword} #${ref.issue}"`; +} + +export function checkLinkedIssue(body: string | null, headRef: string): Check { + if (body === null) return notRun('linked-issue', 'pr-view did not return body (the description)'); + const refs = closingReferences(body); + const forBranch = branchIssue(headRef); + const details: Record = { references: refs }; + if (forBranch !== null) details.branchIssue = forBranch; + + if (refs.length === 0) { + const note = forBranch === null ? 'no closing keyword' : `no closing keyword — close #${forBranch} by hand after merge`; + return check('linked-issue', 'info', note, details); + } + const matching = forBranch === null ? undefined : refs.find((r) => r.issue === forBranch); + const chosen = matching ?? refs[0]; + Object.assign(details, { keyword: chosen.keyword, issue: chosen.issue }); + const others = refs.filter((r) => r !== chosen).map((r) => `#${r.issue}`); + const also = others.length > 0 ? `; also ${[...new Set(others)].join(', ')}` : ''; + + if (forBranch === null) return check('linked-issue', 'info', `${quote(chosen)}${also}`, details); + if (matching) return check('linked-issue', 'info', `${quote(chosen)} — matches ${headRef}${also}`, details); + return check('linked-issue', 'attention', `${quote(chosen)}${also}, but ${headRef} is for #${forBranch}`, details); +} diff --git a/packages/codev/src/commands/check/porch-only.ts b/packages/codev/src/commands/check/porch-only.ts new file mode 100644 index 000000000..375416253 --- /dev/null +++ b/packages/codev/src/commands/check/porch-only.ts @@ -0,0 +1,257 @@ +/** + * The `checks` check of `codev check pr` (Spec 1951 § Porch-only heads): CI on the commit + * that carries the code. + * + * A builder's last commits are usually porch bookkeeping. A commit is **porch-only** when it + * has exactly one parent and changes nothing outside `codev/projects/`. The **last code + * commit** C is the first commit that is not porch-only on the head's first-parent chain, + * walking toward the merge-base. Every commit from C to head has the same code, so the + * **code runs** are the newest complete runs in that range. + * + * Finding C reads at most 11 commits; more than 10 porch-only commits and the check is not + * run. The selection of the code runs is pure: it takes the lookup as a function, and asks + * for at most 10 commits, newest first, C always among them. + */ + +import type { CommitCheckItem, CommitCheckState } from '../../lib/forge-contracts.js'; +import type { Lookup } from './git-facts.js'; +import { short } from './render.js'; +import { check, CheckCommandError, describeRuns, notRun, summarizeRuns, type Check, type CommitRuns } from './report.js'; +import type { Runner } from './runner.js'; +import { isFullSha } from './validate.js'; + +/** Porch state lives here; a commit that changes only paths under it is porch-only. */ +export const PORCH_STATE_DIR = 'codev/projects/'; +/** More porch-only commits than this above the code, and the check is not run. */ +export const MAX_PORCH_ONLY = 10; +/** At most this many `commit-checks` lookups per run. */ +export const MAX_LOOKUPS = 10; + +// ============================================================================= +// Finding the last code commit +// ============================================================================= + +export interface ChainCommit { + sha: string; + parents: string[]; +} + +/** Parse `rev-list --parents`: each line a commit, then its parents. */ +export function parseParents(output: string): ChainCommit[] { + return output + .split('\n') + .map((line) => line.trim()) + .filter((line) => line !== '') + .map((line) => { + const [sha, ...parents] = line.split(' '); + const bad = [sha, ...parents].find((s) => !isFullSha(s)); + if (bad !== undefined) throw new CheckCommandError(`unexpected git rev-list output: ${JSON.stringify(bad)} is not a commit SHA`); + return { sha, parents }; + }); +} + +/** Porch-only: exactly one parent, and every changed path under `codev/projects/`. */ +export function isPorchOnly(parentCount: number, changed: readonly string[]): boolean { + return parentCount === 1 && changed.every((path) => path.startsWith(PORCH_STATE_DIR)); +} + +export type CodeCommit = + /** `above`: the porch-only commits from head down to C, newest first (empty when head is C). */ + | { kind: 'found'; sha: string; above: string[] } + /** The walk reached the merge-base: every commit on the branch is porch-only. */ + | { kind: 'none'; porchOnly: string[] } + | { kind: 'too-many' }; + +/** Walk the head's first-parent chain toward the merge-base and find C. */ +export async function findCodeCommit(runner: Runner, head: string, mergeBase: string): Promise { + const walk = await runner.git(['rev-list', '--first-parent', '--parents', `--max-count=${MAX_PORCH_ONLY + 1}`, head, '--not', mergeBase]); + if (walk.exitCode !== 0) throw new CheckCommandError(`git rev-list ${head} --not ${mergeBase} failed`, walk.stderr.trim()); + const chain = parseParents(walk.stdout); + const above: string[] = []; + for (const commit of chain) { + if (commit.parents.length === 1 && isPorchOnly(commit.parents.length, await changedInCommit(runner, commit.parents[0], commit.sha))) { + above.push(commit.sha); + continue; + } + return { kind: 'found', sha: commit.sha, above }; + } + return chain.length > MAX_PORCH_ONLY ? { kind: 'too-many' } : { kind: 'none', porchOnly: above }; +} + +async function changedInCommit(runner: Runner, parent: string, sha: string): Promise { + const result = await runner.git(['diff-tree', '--no-ext-diff', '--no-textconv', '--no-commit-id', '--name-only', '-r', '-z', '--no-renames', parent, sha]); + if (result.exitCode !== 0) throw new CheckCommandError(`git diff-tree ${parent} ${sha} failed`, result.stderr.trim()); + return result.stdout.split('\0').filter((path) => path !== ''); +} + +// ============================================================================= +// Lookups +// ============================================================================= + +const STATES: ReadonlySet = new Set(['pass', 'fail', 'pending', 'skipped', 'neutral']); + +/** Validate `commit-checks` output. A failure reason names the concept. */ +export function parseCommitChecks(data: unknown): Lookup { + if (!Array.isArray(data)) return { ok: false, reason: 'commit-checks returned something other than a JSON array' }; + const items: CommitCheckItem[] = []; + for (const [index, raw] of data.entries()) { + const where = `commit-checks item ${index + 1}`; + if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return { ok: false, reason: `${where} is not an object` }; + const { name, state, url, workflow } = raw as Record; + if (typeof name !== 'string' || name === '') return { ok: false, reason: `${where} has no name` }; + if (typeof state !== 'string' || !STATES.has(state as CommitCheckState)) { + return { ok: false, reason: `${where} (${name}) has state ${JSON.stringify(state)}, not one of ${[...STATES].join('/')}` }; + } + const item: CommitCheckItem = { name, state: state as CommitCheckState }; + if (url !== undefined) { + if (typeof url !== 'string') return { ok: false, reason: `${where} (${name}) has a url that is not a string` }; + item.url = url; + } + if (workflow !== undefined) { + if (typeof workflow !== 'string') return { ok: false, reason: `${where} (${name}) has a workflow that is not a string` }; + item.workflow = workflow; + } + items.push(item); + } + return { ok: true, value: items }; +} + +/** The runs on one commit, through the runner's `commit-checks`. */ +export async function lookupRuns(runner: Runner, sha: string): Promise> { + const outcome = await runner.forge('commit-checks', { CODEV_COMMIT_SHA: sha }); + if (!outcome.ok) return { ok: false, reason: outcome.reason }; + const parsed = parseCommitChecks(outcome.data); + return parsed.ok ? { ok: true, value: summarizeRuns(sha, parsed.value) } : parsed; +} + +export type RunsLookup = (sha: string) => Promise>; + +export interface Selection { + head: CommitRuns; + /** The code runs, or null when no commit from C to head has any. */ + code: CommitRuns | null; + /** Every commit looked up, in order. */ + queried: string[]; +} + +function allPassed(runs: CommitRuns): boolean { + return runs.runs.length > 0 && runs.failed === 0 && runs.pending === 0; +} + +/** + * Choose the code runs. `range` is C..head, newest first: head is `range[0]`, C the last. + * + * 1. Look up head (H). + * 2. Head is C: the code runs are H. + * 3. H is non-empty and all passed: the code runs are H. + * 4. Otherwise walk from head^1 down to C; the first commit whose runs are non-empty and + * all complete has the code runs. + * 5. Failing that, the first commit in the walk with any runs, even pending ones. + * 6. Failing that, there are no code runs. + * + * The walk is cut so the lookups stay within MAX_LOOKUPS, keeping C: with exactly ten + * porch-only commits above C, the oldest of them is not looked up. + */ +export async function selectCodeRuns(range: readonly string[], lookup: RunsLookup): Promise> { + if (range.length === 0) throw new Error('selectCodeRuns needs at least the head'); + const queried: string[] = []; + const get = async (sha: string): Promise> => { + queried.push(sha); + return lookup(sha); + }; + + const h = await get(range[0]); + if (!h.ok) return h; + const head = h.value; + if (range.length === 1) return { ok: true, value: { head, code: head.runs.length > 0 ? head : null, queried } }; + if (allPassed(head)) return { ok: true, value: { head, code: head, queried } }; + + const codeCommit = range[range.length - 1]; + let walk = range.slice(1); + if (walk.length > MAX_LOOKUPS - 1) walk = [...walk.slice(0, MAX_LOOKUPS - 2), codeCommit]; + let firstWithRuns: CommitRuns | null = null; + for (const sha of walk) { + const r = await get(sha); + if (!r.ok) return r; + if (r.value.runs.length === 0) continue; + if (r.value.pending === 0) return { ok: true, value: { head, code: r.value, queried } }; + firstWithRuns ??= r.value; + } + return { ok: true, value: { head, code: firstWithRuns, queried } }; +} + +// ============================================================================= +// The check +// ============================================================================= + +export type ChecksProblem = 'failed' | 'running' | 'none'; + +/** + * What keeps the check from `ok`, or null when nothing does. A failure anywhere comes first; + * then a pending run anywhere (wait and re-run); then no code runs at all. + */ +export function checksProblem(head: CommitRuns, code: CommitRuns | null): ChecksProblem | null { + if (head.failed > 0 || (code?.failed ?? 0) > 0) return 'failed'; + if (head.pending > 0 || (code?.pending ?? 0) > 0) return 'running'; + if (code === null || code.runs.length === 0) return 'none'; + return null; +} + +function plural(n: number, word: string): string { + return `${n} ${word}${n === 1 ? '' : 's'}`; +} + +/** + * The `checks` line. One line when head carries the code runs; otherwise the code runs, then + * head, so a run still going reads differently than one that failed. + */ +function describeSelection(range: readonly string[], selection: Selection): string { + const { head, code } = selection; + const codeCommit = range[range.length - 1]; + const porchOnlyAbove = range.length - 1; + const headLine = porchOnlyAbove === 0 ? `head ${short(head.sha)}: ${describeRuns(head)}` : `head ${short(head.sha)}: porch-only, ${describeRuns(head)}`; + if (porchOnlyAbove === 0 || code === head) return headLine; + const codeLine = code ? `code ${short(code.sha)}: ${describeRuns(code)}` : `code ${short(codeCommit)}: no runs`; + const tail = + head.runs.length === 0 ? `head ${short(head.sha)}: no runs — ${plural(porchOnlyAbove, 'porch-state commit')} above the code` : headLine; + return `${codeLine}\n${tail}`; +} + +/** + * The check for a selection over `range` (C..head, newest first). `ok` only when the code + * runs exist and all passed (skipped and neutral count as passed) and nothing on head + * failed or is pending. + */ +export function checksResult(range: readonly string[], selection: Selection): Check { + const details: Record = { + head: selection.head, + ...(selection.code ? { code: selection.code } : {}), + lastCodeCommit: range[range.length - 1], + porchOnlyAbove: range.length - 1, + }; + const problem = checksProblem(selection.head, selection.code); + return check('checks', problem === null ? 'ok' : 'attention', describeSelection(range, selection), details); +} + +/** The checks the project's CI reported on the PR's code. A failing local git call throws (exit 2). */ +export async function checkChecks(runner: Runner, head: string, mergeBase: string): Promise { + const lookup: RunsLookup = (sha) => lookupRuns(runner, sha); + const found = await findCodeCommit(runner, head, mergeBase); + if (found.kind === 'too-many') return notRun('checks', `more than ${MAX_PORCH_ONLY} porch-only commits`); + + if (found.kind === 'none') { + const h = await lookup(head); + if (!h.ok) return notRun('checks', h.reason); + const count = found.porchOnly.length; + return check( + 'checks', + 'attention', + `head ${short(head)}: ${describeRuns(h.value)} — no code commit: ${count === 1 ? 'the one commit' : `all ${count} commits`} since the branch point ${count === 1 ? 'is' : 'are'} porch-only`, + { head: h.value, lastCodeCommit: null, porchOnlyAbove: count }, + ); + } + + const range = [...found.above, found.sha]; + const selected = await selectCodeRuns(range, lookup); + return selected.ok ? checksResult(range, selected.value) : notRun('checks', selected.reason); +} diff --git a/packages/codev/src/commands/check/pr.ts b/packages/codev/src/commands/check/pr.ts index 449b18b0d..1c65da23a 100644 --- a/packages/codev/src/commands/check/pr.ts +++ b/packages/codev/src/commands/check/pr.ts @@ -6,17 +6,22 @@ * ref-neutrally. Every check below is computed on those exact commits, with the diff range * merge-base → head (what the forge's diff view shows): * - * head the local branch against the forge head (local ahead = not pushed) - * attribution configured patterns, per line, in the description and each commit not on base - * trial-merge `merge-tree --write-tree` in the object store: no ref, index or file moves - * watched files matching `check.watch`; those also matching `check.flag` need attention - * overlap files the base has also changed since the branch point - * size lines and files changed - * to-read the changed files minus `check.notForReading`, largest first + * head the local branch against the forge head (local ahead = not pushed) + * state an open PR that is not a draft + * forge the forge's own mergeability (`MERGEABLE` is ok) + * attribution configured patterns, per line, in the description and each commit not on base + * trial-merge `merge-tree --write-tree` in the object store: no ref, index or file moves + * checks CI on the code, past porch-only commits at the head (porch-only.ts) + * watched files matching `check.watch`; those also matching `check.flag` need attention + * linked-issue a closing keyword for the branch's issue (linked-issue.ts) + * overlap files the base has also changed since the branch point + * size lines and files changed + * to-read the changed files minus `check.notForReading`, largest first * * When the checks finish, `pr-view` and `ls-remote` are read again. If the head or the base * moved, the check anchored on it (`head`, `trial-merge`) needs attention, so a CLEAR always - * describes the tips that were live at the end of the run. + * describes the tips that were live at the end of the run. A mergeability the forge had not + * computed at the first read takes the second read's value. */ import { findConfigSource } from '../../lib/config.js'; @@ -26,6 +31,8 @@ import { ensureCommits, failureReason, gitVersion, + hasCommit, + isAncestor, liveTip, mergeBase, numstat, @@ -36,6 +43,8 @@ import { type GitVersion, type Lookup, } from './git-facts.js'; +import { checkLinkedIssue } from './linked-issue.js'; +import { checkChecks, checksProblem } from './porch-only.js'; import { attentionNames, renderHuman, short, type RenderOptions } from './render.js'; import { applySkips, @@ -46,10 +55,13 @@ import { fitList, notRun, off, + PR_CHECK_IDS, + skipped, verdictOf, type Check, type CommandOptions, type CommandResult, + type CommitRuns, type PrReport, } from './report.js'; import { resolveRoots } from './roots.js'; @@ -67,6 +79,11 @@ interface PrView { headRef: string; baseRef: string; head: string; + /** The optional fields below are null when `pr-view` did not return them as strings. */ + mergeable: string | null; + mergeStateStatus: string | null; + reviewDecision: string | null; + mergedAt: string | null; } /** Validate a `pr-view` result. A failure reason names the field. */ @@ -100,6 +117,10 @@ export function parsePrView(data: unknown): Lookup { headRef: raw.headRefName as string, baseRef: raw.baseRefName as string, head: raw.headRefOid, + mergeable: text(raw.mergeable), + mergeStateStatus: text(raw.mergeStateStatus), + reviewDecision: text(raw.reviewDecision), + mergedAt: text(raw.mergedAt), }, }; } @@ -162,15 +183,27 @@ async function checkHead(runner: Runner, pr: PrView, local: string | null, ancho // name is unrelated to it and must not be reported as unpushed work. const onOrigin = await liveTip(runner, name); if (!onOrigin.ok) return notRun('head', onOrigin.reason, details); - if (onOrigin.value !== pr.head) { + const originTip = onOrigin.value; + if (originTip !== pr.head) { + // origin's branch past the forge head is a push the forge has not indexed yet, so every + // forge answer describes an older head. Decided only when the origin tip is local. + if (originTip !== null && !anchors.headProblem && (await hasCommit(runner, originTip)) && (await isAncestor(runner, pr.head, originTip))) { + const past = await countRange(runner, pr.head, originTip); + return check( + 'head', + 'attention', + `origin's ${name} is ${plural(past, 'commit')} past the PR head (a push the forge has not indexed yet); re-run`, + { ...details, relation: 'origin-ahead', originBranchSha: originTip, originAheadOfPr: past }, + ); + } const where = - onOrigin.value === null + originTip === null ? `origin has no branch ${name} (a fork's PR, or the branch was deleted)` - : `origin's ${name} is at ${short(onOrigin.value)}, not the PR head (a fork's PR, or the branch moved)`; + : `origin's ${name} is at ${short(originTip)}, not the PR head (a fork's PR, or the branch moved)`; return check('head', 'info', `${where}: local ${name} not compared`, { - forgeHead: pr.head, + ...details, relation: 'not-origin-branch', - originBranchSha: onOrigin.value, + originBranchSha: originTip, }); } if (anchors.headProblem) return notRun('head', anchors.headProblem, details); @@ -192,6 +225,55 @@ async function checkHead(runner: Runner, pr: PrView, local: string | null, ancho return check('head', 'ok', `local ${name} is ${plural(behind, 'commit')} behind the PR head`, { ...counted, relation: 'behind' }); } +/** The forge's state word, normalized: upper-cased, `OPENED` → `OPEN`, and `MERGED` once merged. */ +export function normalizeState(state: string, mergedAt: string | null): string { + if (mergedAt) return 'MERGED'; + const upper = state.toUpperCase(); + return upper === 'OPENED' ? 'OPEN' : upper; +} + +export function checkState(pr: PrView): Check { + if (pr.state === null || pr.state === '') return notRun('state', 'pr-view did not return state'); + if (pr.draft === null) return notRun('state', 'pr-view did not return isDraft'); + const state = normalizeState(pr.state, pr.mergedAt); + const details = { state, draft: pr.draft }; + if (state !== 'OPEN') return check('state', 'attention', `${state}: only an open PR can be recommended`, details); + if (pr.draft) return check('state', 'attention', 'OPEN but a draft: it must be marked ready for review first', details); + return check('state', 'ok', 'OPEN, ready for review', details); +} + +const MERGEABILITY = ['MERGEABLE', 'CONFLICTING', 'UNKNOWN']; + +/** Why a `BLOCKED` merge state is blocked, from the review decision. */ +const BLOCKED_BY: Record = { + REVIEW_REQUIRED: 'review required', + CHANGES_REQUESTED: 'changes requested', +}; + +function mergeWords(view: PrView): string { + const state = view.mergeStateStatus; + if (!state) return view.mergeable!; + const why = state === 'BLOCKED' && view.reviewDecision ? BLOCKED_BY[view.reviewDecision] : undefined; + return why ? `${view.mergeable}, BLOCKED (${why})` : `${view.mergeable}, ${state}`; +} + +/** + * The forge's own mergeability. The verdict follows `mergeable` alone; the merge state and + * review decision are context. An `UNKNOWN` at the first read takes the re-read's value. + */ +export function checkForge(first: PrView, reread: PrView | null): Check { + const view = first.mergeable === 'UNKNOWN' && reread?.mergeable ? reread : first; + const mergeable = view.mergeable; + if (mergeable === null) return notRun('forge', 'pr-view did not return mergeable'); + if (!MERGEABILITY.includes(mergeable)) { + return notRun('forge', `pr-view returned mergeable ${JSON.stringify(mergeable)}, not ${MERGEABILITY.join(', ')}`); + } + const details = { mergeable, mergeStateStatus: view.mergeStateStatus, reviewDecision: view.reviewDecision }; + if (mergeable === 'MERGEABLE') return check('forge', 'ok', mergeWords(view), details); + if (mergeable === 'CONFLICTING') return check('forge', 'attention', mergeWords(view), details); + return check('forge', 'attention', 'forge has not computed mergeability yet; re-run shortly', details); +} + interface AttributionHit { where: 'description' | 'commit'; sha?: string; @@ -322,6 +404,19 @@ async function rangeChecks(runner: Runner, pr: PrView, settings: CheckSettings, return [await checkOverlap(runner, pr, changed, anchors), checkSize(changed), await checkToRead(runner, settings, changed, anchors)]; } +async function checkCi(runner: Runner, settings: CheckSettings, anchors: Anchors): Promise { + if (settings.skip.has('checks')) return skipped('checks'); + const blocked = anchors.headProblem ?? anchors.baseProblem ?? anchors.rangeProblem; + if (blocked) return notRun('checks', blocked); + return checkChecks(runner, anchors.head, anchors.mergeBase!); +} + +/** The checks in the order of PR_CHECK_IDS. */ +function inOrder(checks: readonly Check[]): Check[] { + const order: readonly string[] = PR_CHECK_IDS; + return [...checks].sort((a, b) => order.indexOf(a.id) - order.indexOf(b.id)); +} + // ============================================================================= // Movement during the run // ============================================================================= @@ -376,15 +471,18 @@ async function buildPrReport(number: number, options: CommandOptions): Promise

{ if (c.status === 'not-run') return 'not run'; if ('movedTo' in c.details) return c.id === 'head' ? 'moved' : 'base moved'; - if (c.id === 'head' && (c.details.relation === 'ahead' || c.details.relation === 'diverged')) return 'not pushed'; - if (c.id === 'trial-merge' && c.status === 'attention' && 'conflicts' in c.details) return 'conflicts'; - if (c.id === 'watched' && c.status === 'attention') return 'flagged'; - return null; + if (c.status !== 'attention') return null; + switch (c.id) { + case 'head': + if (c.details.relation === 'ahead' || c.details.relation === 'diverged') return 'not pushed'; + return c.details.relation === 'origin-ahead' ? 'forge behind' : null; + case 'state': + return c.details.state === 'OPEN' ? 'draft' : String(c.details.state).toLowerCase(); + case 'forge': + return c.details.mergeable === 'CONFLICTING' ? 'conflicts' : 'not computed'; + case 'trial-merge': + return 'conflicts' in c.details ? 'conflicts' : null; + case 'checks': + return checksProblem(c.details.head as CommitRuns, (c.details.code as CommitRuns | undefined) ?? null); + case 'watched': + return 'flagged'; + case 'linked-issue': + return 'wrong issue'; + default: + return null; + } }, }; export function renderPrHuman(report: PrReport): string { const { pr } = report; - // A head that is fine reads in the header; one that needs attention gets its own line. + // A head and a state that are fine read in the header; one that needs attention gets its own line. const headCheck = report.checks.find((c) => c.id === 'head' && c.status === 'ok'); - const headInHeader = headCheck !== undefined; + const inHeader = (c: Check): boolean => (c.id === 'head' && c === headCheck) || (c.id === 'state' && c.status === 'ok'); const verdictLine = report.verdict === 'clear' ? `CLEAR PR #${pr.number} — ready to recommend` @@ -463,7 +577,7 @@ export function renderPrHuman(report: PrReport): string { { verdictLine, header: [`PR #${pr.number}${title} ${state} ${pr.headRef} → ${pr.baseRef}`, `${headPart} ${basePart}`, ''], - sections: [{ checks: report.checks.filter((c) => !(c.id === 'head' && headInHeader)) }], + sections: [{ checks: report.checks.filter((c) => !inHeader(c)) }], }, PR_RENDER, ); diff --git a/packages/codev/src/commands/check/report.ts b/packages/codev/src/commands/check/report.ts index f3813c264..8f76be7d8 100644 --- a/packages/codev/src/commands/check/report.ts +++ b/packages/codev/src/commands/check/report.ts @@ -129,9 +129,14 @@ export function off(id: string, reason: string): Check { return check(id, 'off', reason, {}, reason); } +/** A check the project declared skipped in `check.skip`. Does not count as attention. */ +export function skipped(id: string): Check { + return check(id, 'skip', 'skipped (check.skip)', {}, 'check.skip'); +} + /** Replace every check named in `check.skip` with a `skip` entry. */ export function applySkips(checks: Check[], skip: ReadonlySet): Check[] { - return checks.map((c) => (skip.has(c.id) ? check(c.id, 'skip', 'skipped (check.skip)', {}, 'check.skip') : c)); + return checks.map((c) => (skip.has(c.id) ? skipped(c.id) : c)); } export function needsAttention(c: Check): boolean { From 8bf2a0226afd9a1edaa41436d6c76ce95bbf6110 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:38:26 -0800 Subject: [PATCH 51/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 77fdc7f5d..66d5ab43f 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: readonly_core @@ -78,7 +78,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T01:08:51.119Z' +updated_at: '2026-11-24T01:38:26.255Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From e1cece6f63c2e36ec8fd37bbea3c82e0700d93bc Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:47:17 -0800 Subject: [PATCH 52/94] =?UTF-8?q?[Spec=201951][Phase:=20check=5Fpr=5Fforge?= =?UTF-8?q?]=20fix:=20review=20iteration=201=20=E2=80=94=20name=20what=20t?= =?UTF-8?q?he=20walk=20and=20the=20forge=20did=20not=20provide?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - forge: a merge state the forge did not report is said on the line, `MERGEABLE (merge state not reported)`; the verdict still follows `mergeable` alone. - checks: a git call in the porch-only walk that fails leaves the check `not run` by name, and the other checks are still reported (was exit 2). - The one-line form is chosen by SHA, not object identity. - The walk's rev-list and two-revision diff-tree forms are in the shared form table. - Tests: a pr-view without mergeStateStatus, a failing diff-tree, and main merged into a porch-only branch (C is the merge; main's commit is never looked up). --- .../1951-check_pr_forge-iter1-rebuttals.md | 56 +++++++++++++++++++ codev/state/spir-1951_thread.md | 16 ++++++ .../check/__tests__/check-pr-forge.test.ts | 52 +++++++++++++++++ .../check/__tests__/helpers/git-forms.ts | 2 + .../check/__tests__/pr-parsers.test.ts | 3 +- .../codev/src/commands/check/porch-only.ts | 29 +++++----- packages/codev/src/commands/check/pr.ts | 9 ++- 7 files changed, 149 insertions(+), 18 deletions(-) create mode 100644 codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-rebuttals.md diff --git a/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-rebuttals.md b/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-rebuttals.md new file mode 100644 index 000000000..9033d7bc1 --- /dev/null +++ b/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-rebuttals.md @@ -0,0 +1,56 @@ +# Phase check_pr_forge — iteration 1 rebuttal + +Reviews: codex REQUEST_CHANGES (one key issue), claude APPROVE (six non-blocking comments). + +## codex — "an omitted `mergeStateStatus` is reported as ok" + +**Disagree with the requested change; changed the output so the gap is visible.** + +The request is to make `forge` `not run` whenever `mergeStateStatus` is absent. That would reverse a +decision the plan records as the architect's: "`forge`, per the architect's decision: the verdict +follows `mergeable` only … `mergeStateStatus` is context." The `forge` check's verdict depends on +`mergeable` alone; when `mergeable` is absent the check is `not run` +(`pr-view did not return mergeable`), as Scenario 24 requires and the tests show. `mergeStateStatus` +only colours the line. + +It would also break a forge the project supports. The gitea preset (Phase 1, approved) returns +`mergeable` from Gitea's boolean and has no merge-state field to return, so it omits +`mergeStateStatus` (forge-contracts.ts documents both fields as optional). Requiring it would leave +`forge` `not run` on every Gitea PR, for a field the verdict does not use. + +What was wrong is that the absence was silent: the line read just `MERGEABLE`. It now reads +`MERGEABLE (merge state not reported)` (and `CONFLICTING (merge state not reported)`), and +`details.mergeStateStatus` is `null`. Tests: two cases in `pr-parsers.test.ts`, and a Scenario 24 +integration case in `check-pr-forge.test.ts` (pr-view without `mergeStateStatus`, as the gitea preset). + +The architect has been told of this point. + +## claude (APPROVE) — the comments + +1. **A local git failure inside `checks` was exit 2.** Changed. `findCodeCommit` now returns a + `failed` result with `failureReason(...)`, and `checks` is `not run: git diff-tree failed: …` (or + `git rev-list failed: …`) while the other ten checks are still reported, as `attribution` and + `trial-merge` do. Test: a spawn that fails `diff-tree` gives exit 1, `checks` not run by name, + `trial-merge` ok, no lookups. `countRange` inside `head` (Phase 3 code, on commits already known + to be local) is left as it is: a failing `rev-list --count` there means a broken repository. +2. **`code === head` by object identity.** Changed to `code?.sha === head.sha`. +3. **The new argv forms were not in the shared form table.** Added + `rev-list --first-parent --parents --max-count=11 --not ` and the two-revision + `diff-tree … --no-renames ` to `git-forms.ts`, so both the runner's allow-list and + the stub accept them in `allow-list.test.ts` / `stub-bin.test.ts`. +4. **A walk past the branch point.** Settled with the fixture the reviewer proposed: a porch-only + branch with main merged in, then a porch commit, and a green run on main's new commit. C is the + merge commit (merges are never porch-only), the lookups are `[head, merge]`, and main's commit + is never asked for. The walk is `rev-list --not `, which excludes everything + reachable from the merge-base. +5. **An origin tip that is not local drops to `info`.** Unchanged: the fold-in, as the architect + scoped it, decides "origin past the forge head" only when the origin tip object is local, and + `check pr` fetches nothing it does not need. Recorded for the review. +6. **Extra `details` keys** (`references`, `relation`, …): additive, documented. No change. + +## Not changed, recorded for the review (architect) + +- An ok `state` line is not printed; the header shows `OPEN` and the JSON has the check (the same + rule as an ok `head`, matching the spec's own sample). +- The ten-commit edge: the walk allows 10 porch-only commits; the lookups stay at 10, with C always + among them. diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index f74c4d3a1..ceea1c046 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -177,3 +177,19 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals `5 lines: description line 118, commit 23de988 "Co-Authored-By: Claude Opus 5…", … +3`; forge `CONFLICTING, DIRTY` agreeing with `trial merge 5 conflicting files`; `checks head 1fe1037: porch-only, 7 passed`. Clone refs unchanged, no FETCH_HEAD written. Main's config and ~/.codev untouched. +- Architect verified Phase 4 (2026-11-24 01:37) from the main checkout: #1957 'ATTENTION — state (draft), checks + (running)', exit 1; #1965 at its pr gate CLEAR with 'checks: head 0513558: porch-only, 8 passed', in 5.4 s; two + controlled runs changed no ref, FETCH_HEAD byte-identical. Skip applied once under main-38 after GitHub 8/8 green + at 410d5ec14 (porch build-complete); noted in the PR body. +- For the REVIEW (architect): (1) the human form leaves out the `state` line when it is ok — the header shows OPEN + and the JSON has the check — which differs from the spec's "one line per check": record as deliberate (same rule + as an ok `head`). (2) Record the ten-commit edge decision (lookups ≤ 10, C always queried). +- Later: once PR #1965 (3-worker cap) merges, merging main gives a local suite that passes here; the owner may + retire ci-first. The architect will say. +- Review iter1: claude APPROVE (non-blocking), codex REQUEST_CHANGES: "`forge` ok with mergeStateStatus absent". + Rebutted (the architect's decision: verdict follows `mergeable` alone; gitea's preset has no merge state, so + requiring it would leave `forge` not run on every Gitea PR) — but the absence is now said on the line: + `MERGEABLE (merge state not reported)`. Took claude's cheap ones: a git failure in the walk is `checks not run: + git diff-tree failed: …` instead of exit 2; one-line form by SHA, not object identity; the two new argv forms in + git-forms.ts; a main-merged-into-porch-only-branch fixture (C = the merge; main's commit never asked for). + Not taken: `countRange` in head (broken repo → exit 2); origin tip not local stays info (fold-in's scope). diff --git a/packages/codev/src/commands/check/__tests__/check-pr-forge.test.ts b/packages/codev/src/commands/check/__tests__/check-pr-forge.test.ts index adfc41933..40c51e837 100644 --- a/packages/codev/src/commands/check/__tests__/check-pr-forge.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-pr-forge.test.ts @@ -7,10 +7,12 @@ * read-only list ran, and the repository state is compared before and after. */ +import { spawn as realSpawn } from 'node:child_process'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { checkPr, renderPrHuman } from '../pr.js'; import type { Check, CommandOptions, PrReport } from '../report.js'; +import type { SpawnFn } from '../runner.js'; import { useFakeHome } from './helpers/fake-home.js'; import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; import { @@ -244,6 +246,40 @@ describe.skipIf(isWindows)('Spec 1951 — check pr: forge state and CI (stub git expect(byId(report, 'checks')).toMatchObject({ status: 'ok', details: { lastCodeCommit: merge, porchOnlyAbove: 0 } }); }); + it('main merged into a porch-only branch: the merge is the code commit, never a commit of main', async () => { + const { dir } = pushBranch(fx, [{ files: { [PORCH_FILE]: 'step: 0\n' }, message: 'chore(porch): 7 init' }]); + const onMain = fx.commit(fx.main, { 'later.txt': 'later\n' }, 'main moves on'); + fx.git(fx.main, 'push', '-q', 'origin', 'main'); + fx.git(dir, 'merge', '-q', '--no-ff', '-m', 'merge main', 'origin/main'); + const merge = fx.git(dir, 'rev-parse', 'HEAD').trim(); + const head = fx.commit(dir, { [PORCH_FILE]: 'step: 1\n' }, 'chore(porch): 7 next'); + fx.git(dir, 'push', '-q', 'origin', PR_BRANCH); + forge.answer(prView(head)); + ci.answer(onMain, passing(5)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'checks')).toMatchObject({ status: 'attention', details: { lastCodeCommit: merge, porchOnlyAbove: 1 } }); + expect(ci.calls()).toEqual([head, merge]); + }); + + it('a git call in the walk that fails leaves checks not run by name; the other checks are still reported', async () => { + const { head } = prWithPorchTail(1); + forge.answer(prView(head)); + ci.answer(head, passing(2)); + const failingDiffTree: SpawnFn = (command, args, options) => + args[0] === 'diff-tree' + ? realSpawn(process.execPath, ['-e', 'process.stderr.write("fatal: simulated failure\\n"); process.exit(128)'], options) + : realSpawn(command, args, options); + + const { report, exitCode } = await runReadOnly({ spawn: failingDiffTree }); + + expect(exitCode).toBe(1); + expect(byId(report, 'checks')).toMatchObject({ status: 'not-run', reason: 'git diff-tree failed: fatal: simulated failure' }); + expect(byId(report, 'trial-merge').status).toBe('ok'); + expect(ci.calls()).toEqual([]); + }); + it('more than 10 porch-only commits: not run, nothing looked up', async () => { const { head } = prWithPorchTail(11); forge.answer(prView(head)); @@ -397,6 +433,22 @@ describe.skipIf(isWindows)('Spec 1951 — check pr: forge state and CI (stub git expect(verdictLine(report)).toContain(`${id} (not run)`); }); + it('pr-view without mergeStateStatus (as the gitea preset): the verdict follows mergeable, and the line says so', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + const view = prView(head); + delete view.mergeStateStatus; + forge.answer(view); + ci.answer(head, passing(2)); + + const { report } = await runReadOnly(); + + expect(byId(report, 'forge')).toMatchObject({ + status: 'ok', + summary: 'MERGEABLE (merge state not reported)', + details: { mergeable: 'MERGEABLE', mergeStateStatus: null }, + }); + }); + it('commit-checks disabled', async () => { configure({ forge: { 'commit-checks': null } }); const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); diff --git a/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts b/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts index a8f3e8c09..0d2ae5715 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts @@ -26,6 +26,7 @@ export function allowedForms(dir: string): GitForm[] { form([], 'rev-parse', '--verify', '--quiet', `${SHA}^{commit}`), form([], 'rev-list', '--first-parent', '--max-count=10', SHA), form([], 'rev-list', '--count', `${SHA}..${SHA2}`), + form([], 'rev-list', '--first-parent', '--parents', '--max-count=11', SHA, '--not', SHA2), form([], 'merge-base', SHA, SHA2), form([], 'merge-base', '--is-ancestor', SHA, 'refs/remotes/origin/main'), form([], 'log', '--no-ext-diff', '--no-textconv', '-z', '--format=%H%x00%B', `${SHA}..${SHA2}`), @@ -33,6 +34,7 @@ export function allowedForms(dir: string): GitForm[] { form([], 'diff', '--no-ext-diff', '--no-textconv', '--name-only', '-z', '--no-renames', SHA, SHA2, '--', ':(top)', ':(top,exclude,glob)**/x'), form([], 'diff', '--no-ext-diff', '--no-textconv', '--numstat', '-z', SHA, SHA2), form([], 'diff-tree', '--no-ext-diff', '--no-textconv', '--no-commit-id', '--name-only', '-r', '-z', SHA), + form([], 'diff-tree', '--no-ext-diff', '--no-textconv', '--no-commit-id', '--name-only', '-r', '-z', '--no-renames', SHA, SHA2), form([], 'cat-file', '-e', `${SHA}^{commit}`), form([], 'cat-file', '-t', SHA), form([], 'for-each-ref', '--format=%(refname)', 'refs/heads/main'), diff --git a/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts b/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts index 22b80ecdc..77c537445 100644 --- a/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts +++ b/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts @@ -137,7 +137,8 @@ describe('Spec 1951 — state and forge from pr-view', () => { it.each([ [{}, 'ok', 'MERGEABLE, CLEAN'], - [{ mergeStateStatus: undefined }, 'ok', 'MERGEABLE'], + [{ mergeStateStatus: undefined }, 'ok', 'MERGEABLE (merge state not reported)'], + [{ mergeable: 'CONFLICTING', mergeStateStatus: undefined }, 'attention', 'CONFLICTING (merge state not reported)'], [{ mergeStateStatus: 'BLOCKED', reviewDecision: 'REVIEW_REQUIRED' }, 'ok', 'MERGEABLE, BLOCKED (review required)'], [{ mergeStateStatus: 'BLOCKED', reviewDecision: 'CHANGES_REQUESTED' }, 'ok', 'MERGEABLE, BLOCKED (changes requested)'], [{ mergeStateStatus: 'BLOCKED', reviewDecision: 'APPROVED' }, 'ok', 'MERGEABLE, BLOCKED'], diff --git a/packages/codev/src/commands/check/porch-only.ts b/packages/codev/src/commands/check/porch-only.ts index 375416253..ab5f4d4de 100644 --- a/packages/codev/src/commands/check/porch-only.ts +++ b/packages/codev/src/commands/check/porch-only.ts @@ -14,7 +14,7 @@ */ import type { CommitCheckItem, CommitCheckState } from '../../lib/forge-contracts.js'; -import type { Lookup } from './git-facts.js'; +import { failureReason, type Lookup } from './git-facts.js'; import { short } from './render.js'; import { check, CheckCommandError, describeRuns, notRun, summarizeRuns, type Check, type CommitRuns } from './report.js'; import type { Runner } from './runner.js'; @@ -60,30 +60,30 @@ export type CodeCommit = | { kind: 'found'; sha: string; above: string[] } /** The walk reached the merge-base: every commit on the branch is porch-only. */ | { kind: 'none'; porchOnly: string[] } - | { kind: 'too-many' }; + | { kind: 'too-many' } + /** A git call in the walk failed: the check is not run, naming the call. */ + | { kind: 'failed'; reason: string }; /** Walk the head's first-parent chain toward the merge-base and find C. */ export async function findCodeCommit(runner: Runner, head: string, mergeBase: string): Promise { const walk = await runner.git(['rev-list', '--first-parent', '--parents', `--max-count=${MAX_PORCH_ONLY + 1}`, head, '--not', mergeBase]); - if (walk.exitCode !== 0) throw new CheckCommandError(`git rev-list ${head} --not ${mergeBase} failed`, walk.stderr.trim()); + if (walk.exitCode !== 0) return { kind: 'failed', reason: failureReason('git rev-list', walk, runner.timeoutLabel) }; const chain = parseParents(walk.stdout); const above: string[] = []; for (const commit of chain) { - if (commit.parents.length === 1 && isPorchOnly(commit.parents.length, await changedInCommit(runner, commit.parents[0], commit.sha))) { - above.push(commit.sha); - continue; + if (commit.parents.length === 1) { + const changed = await runner.git(['diff-tree', '--no-ext-diff', '--no-textconv', '--no-commit-id', '--name-only', '-r', '-z', '--no-renames', commit.parents[0], commit.sha]); + if (changed.exitCode !== 0) return { kind: 'failed', reason: failureReason('git diff-tree', changed, runner.timeoutLabel) }; + if (isPorchOnly(1, changed.stdout.split('\0').filter((path) => path !== ''))) { + above.push(commit.sha); + continue; + } } return { kind: 'found', sha: commit.sha, above }; } return chain.length > MAX_PORCH_ONLY ? { kind: 'too-many' } : { kind: 'none', porchOnly: above }; } -async function changedInCommit(runner: Runner, parent: string, sha: string): Promise { - const result = await runner.git(['diff-tree', '--no-ext-diff', '--no-textconv', '--no-commit-id', '--name-only', '-r', '-z', '--no-renames', parent, sha]); - if (result.exitCode !== 0) throw new CheckCommandError(`git diff-tree ${parent} ${sha} failed`, result.stderr.trim()); - return result.stdout.split('\0').filter((path) => path !== ''); -} - // ============================================================================= // Lookups // ============================================================================= @@ -210,7 +210,7 @@ function describeSelection(range: readonly string[], selection: Selection): stri const codeCommit = range[range.length - 1]; const porchOnlyAbove = range.length - 1; const headLine = porchOnlyAbove === 0 ? `head ${short(head.sha)}: ${describeRuns(head)}` : `head ${short(head.sha)}: porch-only, ${describeRuns(head)}`; - if (porchOnlyAbove === 0 || code === head) return headLine; + if (porchOnlyAbove === 0 || code?.sha === head.sha) return headLine; const codeLine = code ? `code ${short(code.sha)}: ${describeRuns(code)}` : `code ${short(codeCommit)}: no runs`; const tail = head.runs.length === 0 ? `head ${short(head.sha)}: no runs — ${plural(porchOnlyAbove, 'porch-state commit')} above the code` : headLine; @@ -233,10 +233,11 @@ export function checksResult(range: readonly string[], selection: Selection): Ch return check('checks', problem === null ? 'ok' : 'attention', describeSelection(range, selection), details); } -/** The checks the project's CI reported on the PR's code. A failing local git call throws (exit 2). */ +/** The checks the project's CI reported on the PR's code. A git call that fails leaves the check not run, by name. */ export async function checkChecks(runner: Runner, head: string, mergeBase: string): Promise { const lookup: RunsLookup = (sha) => lookupRuns(runner, sha); const found = await findCodeCommit(runner, head, mergeBase); + if (found.kind === 'failed') return notRun('checks', found.reason); if (found.kind === 'too-many') return notRun('checks', `more than ${MAX_PORCH_ONLY} porch-only commits`); if (found.kind === 'none') { diff --git a/packages/codev/src/commands/check/pr.ts b/packages/codev/src/commands/check/pr.ts index 1c65da23a..1fdead992 100644 --- a/packages/codev/src/commands/check/pr.ts +++ b/packages/codev/src/commands/check/pr.ts @@ -250,16 +250,19 @@ const BLOCKED_BY: Record = { CHANGES_REQUESTED: 'changes requested', }; +/** `MERGEABLE, CLEAN`; a merge state the forge did not report is said, not left out. */ function mergeWords(view: PrView): string { const state = view.mergeStateStatus; - if (!state) return view.mergeable!; + if (!state) return `${view.mergeable} (merge state not reported)`; const why = state === 'BLOCKED' && view.reviewDecision ? BLOCKED_BY[view.reviewDecision] : undefined; return why ? `${view.mergeable}, BLOCKED (${why})` : `${view.mergeable}, ${state}`; } /** - * The forge's own mergeability. The verdict follows `mergeable` alone; the merge state and - * review decision are context. An `UNKNOWN` at the first read takes the re-read's value. + * The forge's own mergeability. The verdict follows `mergeable` alone (the architect's + * decision in the plan); the merge state and review decision are context, so a forge that + * reports no merge state (the gitea preset) still gets a verdict, and the line says the + * state was not reported. An `UNKNOWN` at the first read takes the re-read's value. */ export function checkForge(first: PrView, reread: PrView | null): Check { const view = first.mergeable === 'UNKNOWN' && reread?.mergeable ? reread : first; From 1e29917e99db50c63907bff1fbdf909dfc878dbe Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:55:33 -0800 Subject: [PATCH 53/94] chore(porch): 1951 implement re-iter (iter 2) --- .../status.yaml | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 66d5ab43f..dc442127d 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -38,8 +38,8 @@ gates: status: pending verify-approval: status: pending -iteration: 1 -build_complete: true +iteration: 2 +build_complete: false history: - iteration: 1 plan_phase: readonly_core @@ -77,8 +77,20 @@ history: verdict: APPROVE file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-readonly_core-iter3-claude.txt + - iteration: 1 + plan_phase: check_pr_forge + build_output: '' + reviews: + - model: codex + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-codex.txt + - model: claude + verdict: APPROVE + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T01:38:26.255Z' +updated_at: '2026-11-24T01:55:32.937Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From 82190efa415df1ecfbc57e0b05985d9572a0c3c7 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:55:50 -0800 Subject: [PATCH 54/94] [Spec 1951] Thread log: architect keeps the mergeable-only forge verdict --- codev/state/spir-1951_thread.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index ceea1c046..cd852a9bb 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -193,3 +193,5 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals git diff-tree failed: …` instead of exit 2; one-line form by SHA, not object identity; the two new argv forms in git-forms.ts; a main-merged-into-porch-only-branch fixture (C = the merge; main's commit never asked for). Not taken: `countRange` in head (broken repo → exit 2); origin tip not local stays info (fold-in's scope). +- Architect (2026-11-24 01:47): keep the mergeable-only verdict, do not switch to codex's rule; "merge state not + reported" on the line is the right correction. Claude's notes well taken (named `not run` for a walk failure). From 45e4af3923c8c893a9b758aebbeafd3852027c0b Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:56:39 -0800 Subject: [PATCH 55/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index dc442127d..2de03093a 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 2 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: readonly_core @@ -90,7 +90,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T01:55:32.937Z' +updated_at: '2026-11-24T01:56:38.913Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From b357fe263c55c067bac61211aed968cc5db19c8f Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 17:59:51 -0800 Subject: [PATCH 56/94] =?UTF-8?q?chore(porch):=201951=20advance=20plan=20p?= =?UTF-8?q?hase=20=E2=86=92=20check=5Fdeploy?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../status.yaml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 2de03093a..2ed2ea780 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -14,17 +14,17 @@ plan_phases: status: complete - id: check_pr_forge title: 'codev check pr: forge state and CI checks' - status: in_progress + status: complete - id: check_deploy title: codev check deploy - status: pending + status: in_progress - id: check_worktree title: codev check worktree status: pending - id: docs_guidance title: Architect guidance and command documentation status: pending -current_plan_phase: check_pr_forge +current_plan_phase: check_deploy gates: spec-approval: status: approved @@ -38,8 +38,8 @@ gates: status: pending verify-approval: status: pending -iteration: 2 -build_complete: true +iteration: 1 +build_complete: false history: - iteration: 1 plan_phase: readonly_core @@ -90,7 +90,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T01:56:38.913Z' +updated_at: '2026-11-24T01:59:50.988Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -104,6 +104,8 @@ context_refreshes: - boundary: plan-phase:check_pr_forge at: '2026-11-24T01:07:01.800Z' acknowledged_at: '2026-11-24T01:08:51.118Z' + - boundary: plan-phase:check_deploy + at: '2026-11-24T01:59:50.988Z' force_advanced: phase: readonly_core iteration: 3 From 2b59076e032e6af6762a9727f1855d6e89f256a8 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 18:00:01 -0800 Subject: [PATCH 57/94] [Spec 1951] Thread log: Phase 4 review round 2, both approve --- codev/state/spir-1951_thread.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index cd852a9bb..8b6db5c01 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -195,3 +195,10 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals Not taken: `countRange` in head (broken repo → exit 2); origin tip not local stays info (fold-in's scope). - Architect (2026-11-24 01:47): keep the mergeable-only verdict, do not switch to codex's rule; "merge state not reported" on the line is the right correction. Claude's notes well taken (named `not run` for a walk failure). +- Review iter2: codex APPROVE (no issues), claude APPROVE. Porch advanced → check_deploy (b357fe263). + Non-blocking notes for the REVIEW file: (1) the ten-lookup edge drops the oldest porch commit — if it alone + carried runs and C had none, "no runs" would show for tested code (documented trade-off); (2) `checks` is + computed before the head re-read, so after a head move the line describes the old head (the verdict is + attention via `head` anyway); (3) ok `state` in the header (deliberate); (4) `lastCodeCommit: null` widens the + spec's details type for the all-porch-only branch; (5) `checkCi` tests `check.skip` itself (so a skip makes no + forge call) and `applySkips` repeats it — worth a one-line comment when next touching pr.ts. From 86a23ccbaf82b9435f5a79708404c7a713b744ce Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 18:01:11 -0800 Subject: [PATCH 58/94] chore(porch): 1951 acknowledge context refresh --- codev/projects/1951-read-only-pr-check-for-archite/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 2ed2ea780..b3214bdf9 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -90,7 +90,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T01:59:50.988Z' +updated_at: '2026-11-24T02:01:11.770Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -106,6 +106,7 @@ context_refreshes: acknowledged_at: '2026-11-24T01:08:51.118Z' - boundary: plan-phase:check_deploy at: '2026-11-24T01:59:50.988Z' + acknowledged_at: '2026-11-24T02:01:11.770Z' force_advanced: phase: readonly_core iteration: 3 From 073790df5ac4dfc9d40ce58cad7b7d05fc8520e3 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 18:19:02 -0800 Subject: [PATCH 59/94] =?UTF-8?q?[Spec=201951][Phase:=20check=5Fdeploy]=20?= =?UTF-8?q?feat:=20codev=20check=20deploy=20=E2=80=94=20merged,=20on-branc?= =?UTF-8?q?h,=20deploy-run,=20merge-checks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Per PR from pr-view: merged with a merge commit; the merge an ancestor of the live tip of check.deploy.branch (else the PR's base); with check.deploy.workflow, inside the newest green run of that workflow on the branch (workflow-runs), its head fetched ref-neutrally when missing; without one, CI on the merge commit. A PR that cannot be read is a per-PR not run; the verdict is the worst. --- .../check/__tests__/check-cli.test.ts | 55 +- .../__tests__/check-deploy-readonly.test.ts | 204 +++++++ .../check/__tests__/check-deploy.test.ts | 509 ++++++++++++++++++ .../check/__tests__/helpers/deploy-fixture.ts | 110 ++++ .../check/__tests__/helpers/pr-fixture.ts | 10 +- .../check/__tests__/helpers/report-shape.ts | 44 +- .../commands/check/__tests__/imports.test.ts | 2 +- packages/codev/src/commands/check/deploy.ts | 399 ++++++++++++++ packages/codev/src/commands/check/index.ts | 13 +- 9 files changed, 1338 insertions(+), 8 deletions(-) create mode 100644 packages/codev/src/commands/check/__tests__/check-deploy-readonly.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/check-deploy.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/helpers/deploy-fixture.ts create mode 100644 packages/codev/src/commands/check/deploy.ts diff --git a/packages/codev/src/commands/check/__tests__/check-cli.test.ts b/packages/codev/src/commands/check/__tests__/check-cli.test.ts index 865b3196a..4c9a292ff 100644 --- a/packages/codev/src/commands/check/__tests__/check-cli.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-cli.test.ts @@ -11,6 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { buildCheckCommand, CheckExit, exitCodeForCommander } from '../index.js'; import { useFakeHome } from './helpers/fake-home.js'; import { createFixture, type Fixture } from './helpers/git-fixture.js'; +import { mergedView, mergePr } from './helpers/deploy-fixture.js'; import { commitChecksOverride, passing, prView, prViewOverride, pushBranch, writeConfig } from './helpers/pr-fixture.js'; class Exited extends Error { @@ -76,15 +77,18 @@ describe('Spec 1951 — codev check: commander wiring', () => { expect(exitCodeForCommander(e(1, 'commander.missingArgument'))).toBe(2); }); - it.each([[['--help']], [['pr', '--help']], [['help', 'pr']]])('%j exits 0 and prints help on stdout', async (args) => { + it.each([[['--help']], [['pr', '--help']], [['help', 'pr']], [['deploy', '--help']]])('%j exits 0 and prints help on stdout', async (args) => { const outcome = await runCli(args); expect(outcome.code).toBe(0); expect(outcome.stdout).toMatch(/Usage: check/); }); - it('lists pr with its argument and --json', async () => { - expect((await runCli(['--help'])).stdout).toMatch(/pr \[options\] /); + it('lists pr and deploy with their arguments and --json', async () => { + const help = (await runCli(['--help'])).stdout; + expect(help).toMatch(/pr \[options\] /); + expect(help).toMatch(/deploy \[options\] /); expect((await runCli(['pr', '--help'])).stdout).toMatch(/--json/); + expect((await runCli(['deploy', '--help'])).stdout).toMatch(/--json/); }); it.each([ @@ -93,6 +97,8 @@ describe('Spec 1951 — codev check: commander wiring', () => { ['a missing PR number', ['pr']], ['an extra argument', ['pr', '7', '8']], ['an unknown option', ['pr', '7', '--jsn']], + ['deploy without a PR number', ['deploy']], + ['an unknown deploy option', ['deploy', '7', '--jsn']], ])('%s is a usage error: exit 2', async (_name, args) => { const outcome = await runCli(args); expect(outcome.code).toBe(2); @@ -104,6 +110,10 @@ describe('Spec 1951 — codev check: commander wiring', () => { const outcome = await runCli(['pr', '7', '--jsn', '--json']); expect(outcome.code).toBe(2); expect(JSON.parse(outcome.stdout)).toEqual({ schema: 1, command: 'pr', error: { message: expect.stringMatching(/^unknown option '--jsn'/) } }); + + const deploy = await runCli(['deploy', '--json']); + expect(deploy.code).toBe(2); + expect(JSON.parse(deploy.stdout)).toEqual({ schema: 1, command: 'deploy', error: { message: expect.stringMatching(/^missing required argument 'numbers'/) } }); }); it('commander exits carry their writes: a slow stdout is flushed before the exit code is taken', async () => { @@ -176,6 +186,45 @@ describe('Spec 1951 — codev check pr through the CLI', { timeout: 30_000 }, () }); }); +describe('Spec 1951 — codev check deploy through the CLI', { timeout: 30_000 }, () => { + let fx: Fixture; + + beforeEach(() => { + fx = createFixture(); + const forge = prViewOverride(fx); + const ci = commitChecksOverride(fx); + const pr = mergePr(fx, 8); + forge.answerFor(8, mergedView(pr)); + ci.answer(pr.merge, passing(2)); + writeConfig(fx, { forge: { 'pr-view': forge.script, 'commit-checks': ci.script } }); + }); + + afterEach(() => { + fx.cleanup(); + }); + + it('prints the summary and exits with the verdict', async () => { + const outcome = await runCli(['deploy', '8'], { cwd: fx.main, env: fx.env }); + expect(outcome.code).toBe(0); + expect(outcome.stdout.split('\n')[0]).toBe('CLEAR #8 on main; checks on the merge commit passed'); + expect(outcome.stderr).toBe(''); + }); + + it('--json prints exactly one DeployReport object', async () => { + const outcome = await runCli(['deploy', '8', '--json'], { cwd: fx.main, env: fx.env }); + expect(outcome.code).toBe(0); + const report = JSON.parse(outcome.stdout); + expect(report).toMatchObject({ schema: 1, command: 'deploy', verdict: 'clear', deployBranch: null, workflow: null, prs: [{ number: 8 }] }); + expect(report.prs[0].checks.map((c: { id: string }) => c.id)).toEqual(['merged', 'on-branch', 'deploy-run', 'merge-checks']); + }); + + it('an invalid PR number is exit 2 naming it', async () => { + const outcome = await runCli(['deploy', '8', '12a'], { cwd: fx.main, env: fx.env }); + expect(outcome).toMatchObject({ code: 2, stdout: '' }); + expect(outcome.stderr).toBe('codev check deploy: invalid PR number "12a": expected a positive integer\n'); + }); +}); + describe('Spec 1951 — codev --help lists check', () => { let exit: ReturnType; let write: ReturnType; diff --git a/packages/codev/src/commands/check/__tests__/check-deploy-readonly.test.ts b/packages/codev/src/commands/check/__tests__/check-deploy-readonly.test.ts new file mode 100644 index 000000000..653a188b1 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/check-deploy-readonly.test.ts @@ -0,0 +1,204 @@ +/** + * Spec 1951 — `codev check deploy` against real repositories, on every platform. + * + * The forge comes from `pr-view`, `workflow-runs` and `commit-checks` concept overrides + * (`.sh` scripts Git Bash runs on Windows), so neither `gh` nor a network is needed. These + * tests prove that no ref, `HEAD`, index byte, `FETCH_HEAD` or status line changes + * (Scenario 23), including runs that must fetch the deploy-branch tip and a run's head; that + * the command reports the same from a builder worktree; and the exit-2 paths. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { checkDeploy } from '../deploy.js'; +import type { Check, CommandOptions, DeployReport, ErrorReport } from '../report.js'; +import type { SpawnFn } from '../runner.js'; +import { green, mergedView, mergePr, setRemoteBranch, workflowRunsOverride, type MergedPr, type WorkflowRunsOverride } from './helpers/deploy-fixture.js'; +import { useFakeHome } from './helpers/fake-home.js'; +import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { + commitChecksOverride, + passing, + prViewOverride, + pushFromElsewhere, + writeConfig, + type CommitChecksOverride, + type PrViewOverride, +} from './helpers/pr-fixture.js'; + +useFakeHome(); + +const DEPLOYED = { deploy: { branch: 'production', workflow: 'deploy.yml' } }; + +let fx: Fixture; +let forge: PrViewOverride; +let runs: WorkflowRunsOverride; +let ci: CommitChecksOverride; + +beforeEach(() => { + fx = createFixture(); + forge = prViewOverride(fx); + runs = workflowRunsOverride(fx); + ci = commitChecksOverride(fx); + ci.answerAll(passing(3)); +}); + +afterEach(() => { + fx.cleanup(); +}); + +function configure(check: Record = {}): string { + return writeConfig(fx, { forge: { 'pr-view': forge.script, 'workflow-runs': runs.script, 'commit-checks': ci.script }, check }); +} + +async function runReport(numbers: string[] = ['8'], extra: Partial = {}): Promise { + const result = await checkDeploy(numbers, { cwd: fx.main, env: fx.env, timeoutMs: 20_000, ...extra }); + if ('error' in result.report) throw new Error(`unexpected exit 2: ${result.report.error.message}`); + return result.report; +} + +function byId(report: DeployReport, id: string, number = 8): Check { + const found = report.prs.find((p) => p.number === number)?.checks.find((c) => c.id === id); + if (!found) throw new Error(`no ${id} check for #${number}`); + return found; +} + +function withoutTime(report: DeployReport): Omit { + const { generatedAt: _ignored, ...rest } = report; + return rest; +} + +interface SnapshotCase { + name: string; + check: Record; + /** Merge the PR and arrange the remote; returns the commits the run must fetch. */ + setup: (pr: MergedPr) => string[]; + expected: Record; +} + +const SNAPSHOT_CASES: SnapshotCase[] = [ + { + name: 'a deploy branch and green run already local', + check: DEPLOYED, + setup: (pr) => { + setRemoteBranch(fx, 'production', pr.merge); + runs.answer([green(pr.merge)]); + return []; + }, + expected: { 'on-branch': 'ok', 'deploy-run': 'ok' }, + }, + { + name: 'a deploy-branch tip that must be fetched', + check: DEPLOYED, + setup: (pr) => { + setRemoteBranch(fx, 'production', pr.merge); + const tip = pushFromElsewhere(fx, 'production', { 'deployed.txt': 'x\n' }); + runs.answer([green(pr.merge)]); + return [tip]; + }, + expected: { 'on-branch': 'ok', 'deploy-run': 'ok' }, + }, + { + name: 'a green run whose head must be fetched', + check: DEPLOYED, + setup: (pr) => { + setRemoteBranch(fx, 'production', pr.before); + const runHead = pushFromElsewhere(fx, 'deploy-candidate', { 'candidate.txt': 'x\n' }); + runs.answer([green(runHead)]); + return [runHead]; + }, + expected: { 'on-branch': 'attention', 'deploy-run': 'ok' }, + }, + { + name: 'nothing configured, with main moved on since the merge', + check: {}, + setup: () => [pushFromElsewhere(fx, 'main', { 'later.txt': 'later\n' })], + expected: { 'on-branch': 'ok', 'deploy-run': 'off', 'merge-checks': 'ok' }, + }, +]; + +// Each case builds real repositories and runs the command at least once. +describe('Spec 1951 — check deploy on real repositories', { timeout: 30_000 }, () => { + it.each(SNAPSHOT_CASES)('Scenario 23: $name leaves refs, HEAD, index, FETCH_HEAD and status unchanged', async (c) => { + const pr = mergePr(fx, 8); + const fetched = c.setup(pr); + forge.answerFor(8, mergedView(pr)); + configure(c.check); + for (const sha of fetched) expect(() => fx.git(fx.main, 'cat-file', '-e', sha)).toThrow(); + const before = snapshotRepoState(fx, fx.main); + + const report = await runReport(); + + expect(snapshotRepoState(fx, fx.main)).toEqual(before); + for (const [id, status] of Object.entries(c.expected)) expect(byId(report, id).status, id).toBe(status); + for (const sha of fetched) expect(fx.git(fx.main, 'cat-file', '-t', sha).trim()).toBe('commit'); + }); + + it('a linked worktree is left unchanged, and the report is the same from it as from the main checkout', async () => { + const pr = mergePr(fx, 8); + const worktree = path.join(fx.main, '.builders', 'builder-spir-8'); + setRemoteBranch(fx, 'production', pr.merge); + pushFromElsewhere(fx, 'production', { 'deployed.txt': 'x\n' }); + forge.answerFor(8, mergedView(pr)); + runs.answer([green(pr.merge)]); + configure(DEPLOYED); + const before = snapshotRepoState(fx, worktree); + + const fromWorktree = await runReport(['8'], { cwd: worktree }); + const fromMain = await runReport(); + + expect(snapshotRepoState(fx, worktree)).toEqual(before); + expect(withoutTime(fromWorktree)).toEqual(withoutTime(fromMain)); + expect(fromMain.verdict).toBe('clear'); + }); + + it('Scenario 15a: check deploy 8 99999 reports #8 in full, #99999 not run, and exits 1', async () => { + const pr = mergePr(fx, 8); + forge.answerFor(8, mergedView(pr)); + forge.failFor(99999, 'GraphQL: Could not resolve to a PullRequest with the number of 99999.'); + configure(); + + const result = await checkDeploy(['8', '99999'], { cwd: fx.main, env: fx.env, timeoutMs: 20_000 }); + + expect(result.exitCode).toBe(1); + const report = result.report as DeployReport; + expect(report.prs.map((p) => [p.number, p.verdict])).toEqual([[8, 'clear'], [99999, 'attention']]); + expect(byId(report, 'merged', 99999)).toMatchObject({ + status: 'not-run', + reason: 'pr-view failed: GraphQL: Could not resolve to a PullRequest with the number of 99999.', + }); + }); + + it('Scenario 28a: an invalid PR number among several is exit 2 before any subprocess starts', async () => { + const spawn = vi.fn(); + for (const numbers of [['8', '12a'], ['0'], []]) { + const result = await checkDeploy(numbers, { cwd: fx.main, spawn }); + expect(result.exitCode, numbers.join(' ')).toBe(2); + expect((result.report as ErrorReport).command).toBe('deploy'); + } + const result = await checkDeploy(['8', '12a'], { cwd: fx.main, spawn }); + expect((result.report as ErrorReport).error.message).toBe('invalid PR number "12a": expected a positive integer'); + expect(spawn).not.toHaveBeenCalled(); + }); + + it('Scenario 28a: check.deploy.workflow "--repo=x" is exit 2 naming the value and the file, before any forge call', async () => { + const file = configure({ deploy: { workflow: '--repo=x' } }); + + const result = await checkDeploy(['8'], { cwd: fx.main, env: fx.env }); + + expect(result).toEqual({ + exitCode: 2, + report: { schema: 1, command: 'deploy', error: { message: `check.deploy.workflow "--repo=x" may not begin with '-' (in ${file})` } }, + }); + expect(forge.calls()).toBe(0); + }); + + it('outside a git repository is exit 2', async () => { + const plain = path.join(fx.root, 'plain'); + fs.mkdirSync(plain); + const result = await checkDeploy(['8'], { cwd: plain, env: { ...fx.env, GIT_CEILING_DIRECTORIES: fx.root } }); + expect(result.exitCode).toBe(2); + expect((result.report as ErrorReport).error.message).toBe('not in a git repository'); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/check-deploy.test.ts b/packages/codev/src/commands/check/__tests__/check-deploy.test.ts new file mode 100644 index 000000000..2897b47b9 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/check-deploy.test.ts @@ -0,0 +1,509 @@ +/** + * Spec 1951 — `codev check deploy` (Scenarios 13, 14, 15; POSIX). + * + * PRs are merged into the fixture's origin for real. `pr-view`, `workflow-runs` and + * `commit-checks` come from overrides; a stub `git` first on PATH records every git call, so + * each case also proves nothing off the read-only list ran, and the repository state is + * compared before and after. The parsers are tested on every platform. + */ + +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { checkDeploy, parseDeployView, parseWorkflowRuns, renderDeployHuman, runsProblem } from '../deploy.js'; +import { summarizeRuns, type Check, type CommandOptions, type DeployReport } from '../report.js'; +import { useFakeHome } from './helpers/fake-home.js'; +import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { green, mergedView, mergePr, run, setRemoteBranch, workflowRunsOverride, type WorkflowRunsOverride } from './helpers/deploy-fixture.js'; +import { + commitChecksOverride, + passing, + prView, + prViewOverride, + pushBranch, + pushFromElsewhere, + writeConfig, + type CommitChecksOverride, + type PrViewOverride, +} from './helpers/pr-fixture.js'; +import { expectDeployReportShape } from './helpers/report-shape.js'; +import { createStubBin, type StubBin } from './helpers/stub-bin.js'; + +const isWindows = process.platform === 'win32'; +const SHA = 'a'.repeat(40); +const DEPLOYED = { branch: 'production', workflow: 'deploy.yml' }; + +describe('Spec 1951 — check deploy: parsers', () => { + it('parseDeployView: a merged PR carries its merge commit and base', () => { + const parsed = parseDeployView({ state: 'MERGED', mergedAt: '2026-11-22T17:30:00Z', mergeCommit: { oid: SHA }, baseRefName: 'main' }); + expect(parsed).toEqual({ + ok: true, + value: { state: 'MERGED', mergedAt: '2026-11-22T17:30:00Z', base: { ok: true, value: 'main' }, merge: { ok: true, value: SHA } }, + }); + }); + + it.each([ + ['an open PR', { state: 'OPEN', mergeCommit: null }, 'the PR is not merged (OPEN)'], + ['a closed PR', { state: 'closed', mergeCommit: null }, 'the PR is not merged (CLOSED)'], + ['no state', { mergeCommit: { oid: SHA } }, 'pr-view did not return state'], + ['a preset without mergeCommit', { state: 'MERGED' }, 'pr-view did not return mergeCommit'], + ['a merged PR with a null merge commit', { state: 'MERGED', mergeCommit: null }, 'pr-view returned no merge commit for a merged PR'], + ['an abbreviated merge commit', { state: 'MERGED', mergeCommit: { oid: 'abc1234' } }, 'pr-view returned mergeCommit {"oid":"abc1234"}, not { oid: }'], + ['a bare-string merge commit', { state: 'MERGED', mergeCommit: SHA }, `pr-view returned mergeCommit "${SHA}", not { oid: }`], + ])('parseDeployView: %s has no merge commit to look for', (_name, raw, reason) => { + const parsed = parseDeployView({ baseRefName: 'main', ...raw }); + expect(parsed.ok && parsed.value.merge).toEqual({ ok: false, reason }); + }); + + it('parseDeployView: a merge time makes the state MERGED, as gitlab reports it', () => { + const parsed = parseDeployView({ state: 'merged', mergedAt: '2026-11-22T17:30:00Z', mergeCommit: { oid: SHA }, baseRefName: 'main' }); + expect(parsed.ok && parsed.value.merge).toEqual({ ok: true, value: SHA }); + }); + + it('parseDeployView: a missing or invalid base, and a non-object', () => { + const missing = parseDeployView({ state: 'MERGED', mergeCommit: { oid: SHA } }); + expect(missing.ok && missing.value.base).toEqual({ ok: false, reason: 'pr-view did not return baseRefName' }); + const invalid = parseDeployView({ state: 'MERGED', mergeCommit: { oid: SHA }, baseRefName: '--main' }); + expect(invalid.ok && invalid.value.base).toEqual({ ok: false, reason: 'pr-view returned baseRefName "--main", not a valid branch name' }); + expect(parseDeployView([])).toEqual({ ok: false, reason: 'pr-view returned something other than a JSON object' }); + }); + + it('parseWorkflowRuns: the contract, and what is off it', () => { + expect(parseWorkflowRuns([run(SHA, 'success'), run(SHA, null, undefined, 'in_progress')])).toEqual({ + ok: true, + value: [run(SHA, 'success'), run(SHA, null, undefined, 'in_progress')], + }); + expect(parseWorkflowRuns({})).toEqual({ ok: false, reason: 'workflow-runs returned something other than a JSON array' }); + expect(parseWorkflowRuns([1])).toEqual({ ok: false, reason: 'workflow-runs item 1 is not an object' }); + expect(parseWorkflowRuns([{ headSha: SHA }])).toEqual({ ok: false, reason: 'workflow-runs item 1 has no status' }); + expect(parseWorkflowRuns([{ headSha: SHA, status: 'completed', conclusion: 1 }])).toEqual({ + ok: false, + reason: 'workflow-runs item 1 has a conclusion that is not a string', + }); + }); + + it('runsProblem: failed first, then running, then no runs', () => { + expect(runsProblem(summarizeRuns(SHA, [{ name: 'a', state: 'pass' }, { name: 'b', state: 'skipped' }]))).toBeNull(); + expect(runsProblem(summarizeRuns(SHA, [{ name: 'a', state: 'pending' }, { name: 'b', state: 'fail' }]))).toBe('failed'); + expect(runsProblem(summarizeRuns(SHA, [{ name: 'a', state: 'pending' }]))).toBe('running'); + expect(runsProblem(summarizeRuns(SHA, []))).toBe('no runs'); + }); +}); + +useFakeHome(); + +let fx: Fixture; +let stub: StubBin; +let forge: PrViewOverride; +let runs: WorkflowRunsOverride; +let ci: CommitChecksOverride; +let uninstall: () => void; + +function configure(extra: { forge?: Record; check?: Record } = {}): void { + writeConfig(fx, { + forge: { 'pr-view': forge.script, 'workflow-runs': runs.script, 'commit-checks': ci.script, ...extra.forge }, + ...(extra.check ? { check: extra.check } : {}), + }); +} + +async function runReadOnly(numbers: string[], extra: Partial = {}): Promise<{ report: DeployReport; exitCode: number }> { + const before = snapshotRepoState(fx, fx.main); + const result = await checkDeploy(numbers, { cwd: fx.main, env: { ...fx.env, ...stub.env }, timeoutMs: 20_000, ...extra }); + if ('error' in result.report) throw new Error(`unexpected exit 2: ${result.report.error.message}`); + expect(snapshotRepoState(fx, fx.main)).toEqual(before); + expect(stub.violations()).toEqual([]); + expectDeployReportShape(result.report); + return { report: result.report, exitCode: result.exitCode }; +} + +function byId(report: DeployReport, number: number, id: string): Check { + const found = report.prs.find((p) => p.number === number)?.checks.find((c) => c.id === id); + if (!found) throw new Error(`no ${id} check for #${number}`); + return found; +} + +const s = (sha: string): string => sha.slice(0, 7); + +describe.skipIf(isWindows)('Spec 1951 — check deploy (stub git)', { timeout: 30_000 }, () => { + beforeEach(() => { + fx = createFixture(); + stub = createStubBin(path.join(fx.root, 'bin')); + uninstall = stub.install(); + forge = prViewOverride(fx); + runs = workflowRunsOverride(fx); + ci = commitChecksOverride(fx); + }); + + afterEach(() => { + uninstall(); + fx.cleanup(); + }); + + describe('Scenario 13: a deploy branch and workflow', () => { + beforeEach(() => configure({ check: { deploy: DEPLOYED } })); + + it('merged, on the deploy branch and inside the latest green run: CLEAR, laid out as the spec sample', async () => { + const pr = mergePr(fx, 8); + setRemoteBranch(fx, 'production', pr.merge); + forge.answerFor(8, mergedView(pr)); + runs.answer([run(SHA, null, '2026-11-23T09:00:00Z', 'in_progress'), run(SHA, 'failure', '2026-11-23T08:00:00Z'), green(pr.merge)]); + + const { report, exitCode } = await runReadOnly(['8']); + + expect(exitCode).toBe(0); + expect(report).toMatchObject({ verdict: 'clear', deployBranch: 'production', workflow: 'deploy.yml' }); + expect(report.prs[0]).toMatchObject({ number: 8, mergedAt: '2026-11-22T17:30:00Z', mergeCommit: pr.merge, baseRef: 'main', verdict: 'clear' }); + expect(byId(report, 8, 'merged')).toMatchObject({ status: 'ok', details: { state: 'MERGED', mergedAt: '2026-11-22T17:30:00Z', mergeCommit: pr.merge } }); + expect(byId(report, 8, 'on-branch')).toMatchObject({ status: 'ok', details: { branch: 'production', tip: pr.merge, contains: true } }); + expect(byId(report, 8, 'deploy-run')).toMatchObject({ + status: 'ok', + details: { workflow: 'deploy.yml', contains: true, run: { headSha: pr.merge, url: `https://example.invalid/runs/${s(pr.merge)}`, createdAt: '2026-11-22T18:04:00Z' } }, + }); + expect(runs.calls()).toEqual(['deploy.yml production']); + expect(ci.calls()).toEqual([]); + + expect(renderDeployHuman(report)).toBe( + [ + 'CLEAR #8 on production; in the latest green deploy.yml run', + '', + `#8 merged 2026-11-22 → main merge ${s(pr.merge)}`, + ` ok on production origin/production @ ${s(pr.merge)} contains ${s(pr.merge)}`, + ` ok deploy run latest green deploy.yml run (2026-11-22 18:04, ${s(pr.merge)}) contains ${s(pr.merge)}`, + '', + ].join('\n'), + ); + }); + + it('not on the deploy branch, and not in its latest green run: attention, "not deployed"', async () => { + const pr = mergePr(fx, 8); + setRemoteBranch(fx, 'production', pr.before); + forge.answerFor(8, mergedView(pr)); + runs.answer([green(pr.before)]); + + const { report, exitCode } = await runReadOnly(['8']); + + expect(exitCode).toBe(1); + expect(byId(report, 8, 'on-branch')).toMatchObject({ + status: 'attention', + summary: `origin/production @ ${s(pr.before)} does not contain ${s(pr.merge)}`, + details: { contains: false }, + }); + expect(byId(report, 8, 'deploy-run')).toMatchObject({ + status: 'attention', + summary: `latest green deploy.yml run (2026-11-22 18:04, ${s(pr.before)}) does not contain ${s(pr.merge)}`, + details: { contains: false }, + }); + expect(renderDeployHuman(report).split('\n')[0]).toBe('ATTENTION #8 not deployed'); + }); + + it('on the deploy branch but newer than the latest green run: deploy-run attention only', async () => { + const pr = mergePr(fx, 8); + setRemoteBranch(fx, 'production', pr.merge); + forge.answerFor(8, mergedView(pr)); + runs.answer([run(pr.merge, null, '2026-11-23T09:00:00Z', 'in_progress'), green(pr.before)]); + + const { report } = await runReadOnly(['8']); + + expect(byId(report, 8, 'on-branch').status).toBe('ok'); + expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'attention', details: { run: { headSha: pr.before }, contains: false } }); + expect(renderDeployHuman(report).split('\n')[0]).toBe('ATTENTION #8 not deployed'); + }); + + it('on the deploy branch with no green run: "not deployed", naming how many runs came back', async () => { + const pr = mergePr(fx, 8); + setRemoteBranch(fx, 'production', pr.merge); + forge.answerFor(8, mergedView(pr)); + runs.answer([run(pr.merge, 'failure'), run(pr.before, 'cancelled')]); + + const { report } = await runReadOnly(['8']); + expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'attention', summary: 'no green deploy.yml run on production among the 2 returned' }); + + runs.answer([]); + const { report: none } = await runReadOnly(['8']); + expect(byId(none, 8, 'deploy-run')).toMatchObject({ status: 'attention', summary: 'no deploy.yml run on production' }); + }); + + it('a deploy branch and a green run whose commits are not local are fetched ref-neutrally and judged', async () => { + const pr = mergePr(fx, 8); + setRemoteBranch(fx, 'production', pr.merge); + const later = pushFromElsewhere(fx, 'production', { 'deployed.txt': 'x\n' }); + forge.answerFor(8, mergedView(pr)); + runs.answer([green(later)]); + expect(() => fx.git(fx.main, 'cat-file', '-e', later)).toThrow(); + + const { report, exitCode } = await runReadOnly(['8']); + + expect(exitCode).toBe(0); + expect(byId(report, 8, 'on-branch')).toMatchObject({ status: 'ok', details: { tip: later } }); + expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'ok', details: { run: { headSha: later }, contains: true } }); + expect(stub.gitCalls().filter((c) => c.includes('fetch'))).toHaveLength(1); + expect(fx.git(fx.main, 'cat-file', '-t', later).trim()).toBe('commit'); + }); + + it('a green run whose head cannot be fetched is not run, never ok', async () => { + const pr = mergePr(fx, 8); + setRemoteBranch(fx, 'production', pr.merge); + forge.answerFor(8, mergedView(pr)); + runs.answer([green('f'.repeat(40))]); + + const { report, exitCode } = await runReadOnly(['8']); + + expect(exitCode).toBe(1); + expect(byId(report, 8, 'deploy-run')).toMatchObject({ + status: 'not-run', + reason: expect.stringMatching(/^fffffff not available locally \(fetch failed/), + details: { workflow: 'deploy.yml', run: { headSha: 'f'.repeat(40) } }, + }); + expect(renderDeployHuman(report).split('\n')[0]).toBe('ATTENTION #8 deploy run not run'); + }); + + it('a green run whose headSha is not a SHA is not run', async () => { + const pr = mergePr(fx, 8); + setRemoteBranch(fx, 'production', pr.merge); + forge.answerFor(8, mergedView(pr)); + runs.answer([green('abc1234')]); + + const { report } = await runReadOnly(['8']); + + expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'not-run', reason: 'workflow-runs returned invalid headSha "abc1234"' }); + }); + + it.each([ + ['disabled', () => configure({ forge: { 'workflow-runs': null }, check: { deploy: DEPLOYED } }), 'workflow-runs unavailable on github'], + ['failing', () => runs.fail(), 'workflow-runs failed: workflow-runs stub: forge unreachable'], + ['off the contract', () => runs.answer('{"runs": []}'), 'workflow-runs returned something other than a JSON array'], + ])('workflow-runs %s: deploy-run not run, exit 1', async (_name, arrange, reason) => { + const pr = mergePr(fx, 8); + setRemoteBranch(fx, 'production', pr.merge); + forge.answerFor(8, mergedView(pr)); + arrange(); + + const { report, exitCode } = await runReadOnly(['8']); + + expect(exitCode).toBe(1); + expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'not-run', reason }); + expect(byId(report, 8, 'on-branch').status).toBe('ok'); + }); + + it('a workflow-runs that never answers leaves deploy-run not run within the time limit', async () => { + const pr = mergePr(fx, 8); + setRemoteBranch(fx, 'production', pr.merge); + forge.answerFor(8, mergedView(pr)); + runs.hang(); + const started = Date.now(); + + const { report } = await runReadOnly(['8'], { timeoutMs: 1_000 }); + + expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'not-run', reason: 'workflow-runs timed out after 1s' }); + expect(Date.now() - started).toBeLessThan(15_000); + }); + + it('a deploy branch origin does not have: on-branch not run', async () => { + const pr = mergePr(fx, 8); + forge.answerFor(8, mergedView(pr)); + runs.answer([green(pr.merge)]); + + const { report } = await runReadOnly(['8']); + + expect(byId(report, 8, 'on-branch')).toMatchObject({ status: 'not-run', reason: 'origin has no branch production', details: { branch: 'production' } }); + }); + + it('several PRs: the deploy branch and its runs are read once, and the verdict is the worst', async () => { + const first = mergePr(fx, 8); + setRemoteBranch(fx, 'production', first.merge); + const second = mergePr(fx, 9); + forge.answerFor(8, mergedView(first)); + forge.answerFor(9, mergedView(second)); + runs.answer([green(first.merge)]); + + const { report, exitCode } = await runReadOnly(['8', '9', '8']); + + expect(exitCode).toBe(1); + expect(report.prs.map((p) => [p.number, p.verdict])).toEqual([[8, 'clear'], [9, 'attention']]); + expect(runs.calls()).toEqual(['deploy.yml production']); + expect(stub.gitCalls().filter((c) => c.startsWith('ls-remote'))).toHaveLength(1); + const human = renderDeployHuman(report); + expect(human.split('\n')[0]).toBe('ATTENTION #9 not deployed'); + expect(human).toContain(`#9 merged 2026-11-22 → main merge ${s(second.merge)}\n ATTN on production`); + }); + + it('check.skip ["deploy-run"] skips it by name without asking the forge', async () => { + configure({ check: { deploy: DEPLOYED, skip: ['deploy-run'] } }); + const pr = mergePr(fx, 8); + setRemoteBranch(fx, 'production', pr.merge); + forge.answerFor(8, mergedView(pr)); + + const { report } = await runReadOnly(['8']); + + expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'skip', reason: 'check.skip' }); + expect(runs.calls()).toEqual([]); + expect(renderDeployHuman(report).split('\n')[0]).toBe('CLEAR #8 on production'); + }); + }); + + describe('Scenario 14: nothing configured', () => { + beforeEach(() => configure()); + + it('the base branch is used, merge checks are reported and deploy-run is off: the spec sample', async () => { + const pr = mergePr(fx, 8); + forge.answerFor(8, mergedView(pr)); + ci.answer(pr.merge, passing(8)); + + const { report, exitCode } = await runReadOnly(['8']); + + expect(exitCode).toBe(0); + expect(report).toMatchObject({ verdict: 'clear', deployBranch: null, workflow: null }); + expect(byId(report, 8, 'on-branch')).toMatchObject({ status: 'ok', details: { branch: 'main', tip: pr.merge, contains: true } }); + expect(byId(report, 8, 'merge-checks')).toMatchObject({ status: 'ok', details: { sha: pr.merge, passed: 8, failed: 0, pending: 0 } }); + expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'off', reason: 'no deploy workflow configured (check.deploy.workflow)' }); + expect(runs.calls()).toEqual([]); + expect(ci.calls()).toEqual([pr.merge]); + + expect(renderDeployHuman(report)).toBe( + [ + 'CLEAR #8 on main; checks on the merge commit passed', + '', + `#8 merged 2026-11-22 → main merge ${s(pr.merge)}`, + ` ok on main origin/main @ ${s(pr.merge)} contains ${s(pr.merge)}`, + ` ok merge checks ${s(pr.merge)}: 8 passed`, + ' off deploy run no deploy workflow configured (check.deploy.workflow)', + '', + ].join('\n'), + ); + }); + + it('a merge commit since overtaken on main is still on it', async () => { + const pr = mergePr(fx, 8); + const later = pushFromElsewhere(fx, 'main', { 'later.txt': 'later\n' }); + forge.answerFor(8, mergedView(pr)); + ci.answer(pr.merge, passing(2)); + + const { report } = await runReadOnly(['8']); + + expect(byId(report, 8, 'on-branch')).toMatchObject({ status: 'ok', details: { tip: later, contains: true } }); + }); + + it('a squash merge (a merge commit with one parent) is judged the same way', async () => { + const { head } = pushBranch(fx, [{ files: { 'src/s.ts': 's\n' }, message: 's' }], 'builder/spir-8'); + const squash = fx.commit(fx.main, { 'src/s.ts': 's\n' }, 'Feature 8 (#8)'); + fx.git(fx.main, 'push', '-q', 'origin', 'main'); + forge.answerFor(8, mergedView({ number: 8, branch: 'builder/spir-8', head, merge: squash, before: '' })); + ci.answer(squash, passing(1)); + + const { report, exitCode } = await runReadOnly(['8']); + + expect(exitCode).toBe(0); + expect(byId(report, 8, 'on-branch')).toMatchObject({ status: 'ok', details: { contains: true } }); + }); + + it.each([ + ['failing', [{ name: 'unit', state: 'fail' as const }, ...passing(3)], 'merge checks failed', '3 passed, 1 failed (unit)'], + ['still running', [{ name: 'e2e', state: 'pending' as const }], 'merge checks running', '1 still running'], + ['absent', [], 'merge checks no runs', 'no runs'], + ])('merge checks %s: attention', async (_name, answer, words, summary) => { + const pr = mergePr(fx, 8); + forge.answerFor(8, mergedView(pr)); + ci.answer(pr.merge, answer); + + const { report, exitCode } = await runReadOnly(['8']); + + expect(exitCode).toBe(1); + expect(byId(report, 8, 'merge-checks')).toMatchObject({ status: 'attention', summary: `${s(pr.merge)}: ${summary}` }); + expect(renderDeployHuman(report).split('\n')[0]).toBe(`ATTENTION #8 ${words}`); + }); + + it.each([ + ['disabled', () => configure({ forge: { 'commit-checks': null } }), 'commit-checks unavailable on github'], + ['failing', () => ci.fail(), 'commit-checks failed: commit-checks stub: forge unreachable'], + ])('commit-checks %s: merge-checks not run, exit 1', async (_name, arrange, reason) => { + const pr = mergePr(fx, 8); + forge.answerFor(8, mergedView(pr)); + arrange(); + + const { report, exitCode } = await runReadOnly(['8']); + + expect(exitCode).toBe(1); + expect(byId(report, 8, 'merge-checks')).toMatchObject({ status: 'not-run', reason }); + }); + + it('check.deploy.branch alone: that branch is used, and merge checks are still reported', async () => { + configure({ check: { deploy: { branch: 'production' } } }); + const pr = mergePr(fx, 8); + setRemoteBranch(fx, 'production', pr.before); + forge.answerFor(8, mergedView(pr)); + ci.answer(pr.merge, passing(2)); + + const { report } = await runReadOnly(['8']); + + expect(report.deployBranch).toBe('production'); + expect(byId(report, 8, 'on-branch')).toMatchObject({ status: 'attention', details: { branch: 'production', contains: false } }); + expect(byId(report, 8, 'merge-checks').status).toBe('ok'); + expect(renderDeployHuman(report).split('\n')[0]).toBe('ATTENTION #8 not on production'); + }); + + it('check.skip ["merge-checks"] skips it without asking the forge', async () => { + configure({ check: { skip: ['merge-checks'] } }); + const pr = mergePr(fx, 8); + forge.answerFor(8, mergedView(pr)); + + const { report } = await runReadOnly(['8']); + + expect(byId(report, 8, 'merge-checks').status).toBe('skip'); + expect(ci.calls()).toEqual([]); + expect(renderDeployHuman(report).split('\n')[0]).toBe('CLEAR #8 on main'); + }); + }); + + describe('Scenario 15: unmerged and unreadable PRs', () => { + beforeEach(() => configure({ check: { deploy: DEPLOYED } })); + + it('a PR not merged: merged attention, the checks that need the merge commit not run', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }], 'builder/spir-8'); + forge.answerFor(8, prView(head, { headRefName: 'builder/spir-8' })); + + const { report, exitCode } = await runReadOnly(['8']); + + expect(exitCode).toBe(1); + expect(report.prs[0]).toMatchObject({ mergeCommit: null, mergedAt: null, baseRef: 'main', verdict: 'attention' }); + expect(byId(report, 8, 'merged')).toMatchObject({ status: 'attention', summary: 'OPEN: not merged', details: { state: 'OPEN', mergeCommit: null } }); + expect(byId(report, 8, 'on-branch')).toMatchObject({ status: 'not-run', reason: 'the PR is not merged (OPEN)', details: { branch: 'production' } }); + expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'not-run', reason: 'the PR is not merged (OPEN)' }); + expect(runs.calls()).toEqual([]); + const human = renderDeployHuman(report); + expect(human.split('\n')[0]).toBe('ATTENTION #8 not merged'); + expect(human).toContain('#8 OPEN → main\n ATTN merged OPEN: not merged\n not run on production'); + }); + + it('a preset that does not return mergeCommit: merged not run, naming the field', async () => { + const pr = mergePr(fx, 8); + const view = mergedView(pr); + delete view.mergeCommit; + forge.answerFor(8, view); + + const { report } = await runReadOnly(['8']); + + expect(byId(report, 8, 'merged')).toMatchObject({ status: 'not-run', reason: 'pr-view did not return mergeCommit' }); + expect(byId(report, 8, 'on-branch')).toMatchObject({ status: 'not-run', reason: 'pr-view did not return mergeCommit' }); + expect(renderDeployHuman(report).split('\n')[0]).toBe('ATTENTION #8 merge not read'); + }); + + it('Scenario 15a: one PR that cannot be read is a per-PR not run; the others are reported in full', async () => { + const pr = mergePr(fx, 8); + setRemoteBranch(fx, 'production', pr.merge); + forge.answerFor(8, mergedView(pr)); + forge.failFor(99999, 'GraphQL: Could not resolve to a PullRequest with the number of 99999. (repository.pullRequest)'); + runs.answer([green(pr.merge)]); + + const { report, exitCode } = await runReadOnly(['8', '99999']); + + expect(exitCode).toBe(1); + expect(report.prs[0]).toMatchObject({ number: 8, verdict: 'clear' }); + const reason = 'pr-view failed: GraphQL: Could not resolve to a PullRequest with the number of 99999. (repository.pullRequest)'; + expect(report.prs[1]).toMatchObject({ number: 99999, verdict: 'attention', mergeCommit: null, mergedAt: null, baseRef: null }); + expect(byId(report, 99999, 'merged')).toMatchObject({ status: 'not-run', reason }); + for (const id of ['on-branch', 'deploy-run']) expect(byId(report, 99999, id)).toMatchObject({ status: 'not-run', reason: 'the PR could not be read' }); + const human = renderDeployHuman(report); + expect(human.split('\n')[0]).toBe('ATTENTION #99999 not read'); + expect(human).toContain(`\n#99999\n not run merged ${reason}\n`); + }); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/helpers/deploy-fixture.ts b/packages/codev/src/commands/check/__tests__/helpers/deploy-fixture.ts new file mode 100644 index 000000000..f2b94dad7 --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/helpers/deploy-fixture.ts @@ -0,0 +1,110 @@ +/** + * Fixtures for the `codev check deploy` tests (Spec 1951): PRs merged into the fixture's + * origin, the `pr-view` JSON the forge returns for a merged PR, a deploy branch, and a + * `workflow-runs` concept override that runs on every platform. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { Fixture } from './git-fixture.js'; +import { prView, pushBranch, shPath } from './pr-fixture.js'; + +export const MERGED_AT = '2026-11-22T17:30:00Z'; + +export interface MergedPr { + number: number; + branch: string; + head: string; + /** The merge commit on main, pushed to origin. */ + merge: string; + /** main's tip before the merge. */ + before: string; +} + +/** + * Push a one-commit branch for PR `number`, merge it into main with a merge commit, and push + * main. The main clone has every commit; `pushFromElsewhere` makes ones it lacks. + */ +export function mergePr(fx: Fixture, number: number, file = `src/pr-${number}.ts`): MergedPr { + const branch = `builder/spir-${number}`; + const before = fx.git(fx.main, 'rev-parse', 'HEAD').trim(); + const { head } = pushBranch(fx, [{ files: { [file]: `export const n = ${number};\n` }, message: `PR ${number}` }], branch); + fx.git(fx.main, 'merge', '-q', '--no-ff', '-m', `Merge PR #${number}`, branch); + fx.git(fx.main, 'push', '-q', 'origin', 'main'); + return { number, branch, head, merge: fx.git(fx.main, 'rev-parse', 'HEAD').trim(), before }; +} + +/** What `gh pr view` returns for a merged PR. */ +export function mergedView(pr: MergedPr, overrides: Record = {}): Record { + return prView(pr.head, { + title: `Feature ${pr.number}`, + body: `Fixes #${pr.number}`, + state: 'MERGED', + headRefName: pr.branch, + mergeable: 'UNKNOWN', + mergeStateStatus: 'UNKNOWN', + mergeCommit: { oid: pr.merge }, + mergedAt: MERGED_AT, + ...overrides, + }); +} + +/** Point `branch` on origin at `sha` (pushed from the main clone, which already has it). */ +export function setRemoteBranch(fx: Fixture, branch: string, sha: string): void { + fx.git(fx.main, 'push', '-q', '--force', 'origin', `${sha}:refs/heads/${branch}`); +} + +export interface WorkflowRun { + headSha: string; + status: string; + conclusion: string | null; + url: string; + createdAt: string; +} + +export function run(headSha: string, conclusion: string | null, createdAt = '2026-11-22T18:04:00Z', status = 'completed'): WorkflowRun { + return { headSha, status, conclusion, url: `https://example.invalid/runs/${headSha.slice(0, 7)}`, createdAt }; +} + +export const green = (headSha: string, createdAt?: string): WorkflowRun => run(headSha, 'success', createdAt); + +export interface WorkflowRunsOverride { + /** The absolute script path, to put in `forge["workflow-runs"]`. */ + script: string; + /** The runs every call returns (or raw output); `[]` until set. */ + answer(runs: WorkflowRun[] | string): void; + fail(): void; + hang(): void; + /** ` ` for each call, in order. */ + calls(): string[]; +} + +/** A `workflow-runs` override answering from a file and recording what it was asked for. */ +export function workflowRunsOverride(fx: Fixture): WorkflowRunsOverride { + const dir = path.join(fx.root, 'forge-runs'); + fs.mkdirSync(dir, { recursive: true }); + const script = path.join(dir, 'workflow-runs.sh'); + fs.writeFileSync( + script, + [ + '#!/bin/sh', + `dir='${shPath(dir)}'`, + 'printf \'%s %s\\n\' "$CODEV_WORKFLOW" "$CODEV_BRANCH" >> "$dir/calls"', + '[ -f "$dir/hang" ] && exec sleep 60', + 'if [ -f "$dir/fail" ]; then echo "workflow-runs stub: forge unreachable" >&2; exit 1; fi', + "if [ -f \"$dir/runs.json\" ]; then cat \"$dir/runs.json\"; else echo '[]'; fi", + '', + ].join('\n'), + { mode: 0o755 }, + ); + return { + script, + answer: (runs) => fs.writeFileSync(path.join(dir, 'runs.json'), typeof runs === 'string' ? runs : JSON.stringify(runs)), + fail: () => fs.writeFileSync(path.join(dir, 'fail'), ''), + hang: () => fs.writeFileSync(path.join(dir, 'hang'), ''), + calls: () => { + const file = path.join(dir, 'calls'); + return fs.existsSync(file) ? fs.readFileSync(file, 'utf-8').split('\n').filter(Boolean) : []; + }, + }; +} diff --git a/packages/codev/src/commands/check/__tests__/helpers/pr-fixture.ts b/packages/codev/src/commands/check/__tests__/helpers/pr-fixture.ts index 2eabf7390..fd1281330 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/pr-fixture.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/pr-fixture.ts @@ -90,6 +90,10 @@ export interface PrViewOverride { answerOn(n: number, view: Record | string): void; /** A shell snippet run before answering call `n`. */ runOn(n: number, snippet: string): void; + /** The answer for PR `number` (`CODEV_PR_NUMBER`), ahead of the per-call answers. */ + answerFor(number: number, view: Record | string): void; + /** Make the call for PR `number` fail with exit 1, printing `stderr`. */ + failFor(number: number, stderr: string): void; calls(): number; } @@ -111,7 +115,9 @@ export function prViewOverride(fx: Fixture): PrViewOverride { 'n=$((n + 1))', 'echo "$n" > "$dir/count"', '[ -f "$dir/run.$n.sh" ] && . "$dir/run.$n.sh"', - 'if [ -f "$dir/answer.$n.json" ]; then cat "$dir/answer.$n.json"; else cat "$dir/answer.json"; fi', + 'if [ -f "$dir/fail.$CODEV_PR_NUMBER" ]; then cat "$dir/fail.$CODEV_PR_NUMBER" >&2; exit 1; fi', + 'if [ -f "$dir/pr.$CODEV_PR_NUMBER.json" ]; then cat "$dir/pr.$CODEV_PR_NUMBER.json"', + 'elif [ -f "$dir/answer.$n.json" ]; then cat "$dir/answer.$n.json"; else cat "$dir/answer.json"; fi', '', ].join('\n'), { mode: 0o755 }, @@ -122,6 +128,8 @@ export function prViewOverride(fx: Fixture): PrViewOverride { answer: (view) => fs.writeFileSync(path.join(dir, 'answer.json'), text(view)), answerOn: (n, view) => fs.writeFileSync(path.join(dir, `answer.${n}.json`), text(view)), runOn: (n, snippet) => fs.writeFileSync(path.join(dir, `run.${n}.sh`), `${snippet}\n`), + answerFor: (number, view) => fs.writeFileSync(path.join(dir, `pr.${number}.json`), text(view)), + failFor: (number, stderr) => fs.writeFileSync(path.join(dir, `fail.${number}`), `${stderr}\n`), calls: () => { const file = path.join(dir, 'count'); return fs.existsSync(file) ? Number(fs.readFileSync(file, 'utf-8').trim()) : 0; diff --git a/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts b/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts index 6472aec4b..517203f30 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts @@ -1,10 +1,10 @@ /** - * Scenario 28 (Spec 1951 § JSON schema): a `PrReport` survives JSON and has the schema-1 + * Scenario 28 (Spec 1951 § JSON schema): a `PrReport` or `DeployReport` survives JSON and has the schema-1 * shape, with every check id present in order and the verdict following the statuses. */ import { expect } from 'vitest'; -import { PR_CHECK_IDS, type PrReport } from '../../report.js'; +import { PR_CHECK_IDS, type DeployReport, type PrReport } from '../../report.js'; const STATUSES = ['ok', 'attention', 'info', 'not-run', 'off', 'skip']; const WITH_REASON = new Set(['not-run', 'off', 'skip']); @@ -55,3 +55,43 @@ export function expectPrReportShape(report: PrReport): void { const attention = parsed.checks.some((c) => c.status === 'attention' || c.status === 'not-run'); expect(parsed.verdict).toBe(attention ? 'attention' : 'clear'); } + +/** A `DeployReport` survives JSON and has the schema-1 shape; each PR's verdict follows its checks. */ +export function expectDeployReportShape(report: DeployReport): void { + const parsed = JSON.parse(JSON.stringify(report)) as DeployReport; + expect(parsed).toMatchObject({ schema: 1, command: 'deploy', verdict: expect.stringMatching(/^(clear|attention)$/), generatedAt: expect.any(String) }); + expect(Number.isNaN(Date.parse(parsed.generatedAt))).toBe(false); + expect(parsed.deployBranch === null || typeof parsed.deployBranch === 'string').toBe(true); + expect(parsed.workflow === null || typeof parsed.workflow === 'string').toBe(true); + expect(parsed.prs.length).toBeGreaterThan(0); + + const ids = ['merged', 'on-branch', 'deploy-run', ...(parsed.workflow === null ? ['merge-checks'] : [])]; + for (const pr of parsed.prs) { + const where = `#${pr.number}`; + expect(typeof pr.number, where).toBe('number'); + expect(pr.mergedAt === null || typeof pr.mergedAt === 'string', where).toBe(true); + expect(pr.mergeCommit === null || SHA.test(pr.mergeCommit), where).toBe(true); + expect(pr.baseRef === null || typeof pr.baseRef === 'string', where).toBe(true); + expect(pr.checks.map((c) => c.id), where).toEqual(ids); + for (const c of pr.checks) { + expect(STATUSES, `${where} ${c.id}`).toContain(c.status); + expect(typeof c.summary, `${where} ${c.id}`).toBe('string'); + expect(typeof c.details === 'object' && c.details !== null && !Array.isArray(c.details), `${where} ${c.id}`).toBe(true); + expect(typeof c.reason === 'string', `${where} ${c.id} reason`).toBe(WITH_REASON.has(c.status)); + if (c.status === 'not-run' || c.status === 'off' || c.status === 'skip') continue; + if (c.id === 'merged') expect(c.details).toEqual({ state: expect.any(String), mergedAt: pr.mergedAt, mergeCommit: pr.mergeCommit }); + if (c.id === 'on-branch') { + expect(c.details).toEqual({ branch: expect.any(String), tip: expect.stringMatching(SHA), contains: expect.any(Boolean) }); + } + if (c.id === 'deploy-run') { + expect(c.details).toMatchObject({ workflow: parsed.workflow }); + if ('run' in c.details) expect(c.details.run).toMatchObject({ headSha: expect.stringMatching(SHA), url: expect.any(String), createdAt: expect.any(String) }); + if ('contains' in c.details) expect(typeof c.details.contains).toBe('boolean'); + } + if (c.id === 'merge-checks') expectCommitRuns(c.details, `${where} merge-checks`); + } + const attention = pr.checks.some((c) => c.status === 'attention' || c.status === 'not-run'); + expect(pr.verdict, where).toBe(attention ? 'attention' : 'clear'); + } + expect(parsed.verdict).toBe(parsed.prs.some((p) => p.verdict === 'attention') ? 'attention' : 'clear'); +} diff --git a/packages/codev/src/commands/check/__tests__/imports.test.ts b/packages/codev/src/commands/check/__tests__/imports.test.ts index afab7aad7..85ea417d6 100644 --- a/packages/codev/src/commands/check/__tests__/imports.test.ts +++ b/packages/codev/src/commands/check/__tests__/imports.test.ts @@ -98,7 +98,7 @@ describe('Spec 1951 — audited imports in commands/check/', () => { it('audits every source file in the directory', () => { expect(sources).toEqual( expect.arrayContaining([ - 'allow-list.ts', 'git-facts.ts', 'index.ts', 'linked-issue.ts', 'porch-only.ts', 'pr.ts', 'render.ts', 'report.ts', 'roots.ts', + 'allow-list.ts', 'deploy.ts', 'git-facts.ts', 'index.ts', 'linked-issue.ts', 'porch-only.ts', 'pr.ts', 'render.ts', 'report.ts', 'roots.ts', 'runner.ts', 'settings.ts', 'validate.ts', ]), ); diff --git a/packages/codev/src/commands/check/deploy.ts b/packages/codev/src/commands/check/deploy.ts new file mode 100644 index 000000000..f3d6ab2e3 --- /dev/null +++ b/packages/codev/src/commands/check/deploy.ts @@ -0,0 +1,399 @@ +/** + * `codev check deploy …` (Spec 1951): whether each merged PR reached the deploy branch + * and, where a deploy workflow is configured, the latest green deploy run. + * + * Per PR, from `pr-view`: + * + * merged the PR is merged and the forge names its merge commit + * on-branch the merge commit is an ancestor of the live tip of `check.deploy.branch`, + * or of the PR's base when that is unset (`ls-remote`, never `origin/`) + * deploy-run with `check.deploy.workflow`: the merge commit is an ancestor of the head of + * the newest green run of that workflow on the branch (`workflow-runs`); + * without it, `off` + * merge-checks only without a deploy workflow: CI on the merge commit (`commit-checks`) + * + * A PR that cannot be read is a per-PR `not run`, and the other PRs are still reported. + * Missing commits are fetched ref-neutrally, as in `check pr`. The verdict is the worst + * across all PRs. + */ + +import type { WorkflowRunItem } from '../../lib/forge-contracts.js'; +import { ensureCommits, gitVersion, isAncestor, liveTip, type GitVersion, type Lookup } from './git-facts.js'; +import { lookupRuns } from './porch-only.js'; +import { normalizeState } from './pr.js'; +import { defaultLabel, renderHuman, short, type RenderOptions } from './render.js'; +import { + check, + describeRuns, + errorReport, + exitCodeOf, + needsAttention, + notRun, + off, + skipped, + verdictOf, + type Check, + type CommandOptions, + type CommandResult, + type CommitRuns, + type DeployReport, +} from './report.js'; +import { resolveRoots } from './roots.js'; +import { createRunner, type Runner } from './runner.js'; +import { loadCheckSettings, type CheckSettings } from './settings.js'; +import { InputError, isFullSha, isRefName, validatePrNumber } from './validate.js'; + +type DeployPr = DeployReport['prs'][number]; + +/** The `pr-view` fields this command reads. Each is null when the forge did not return it usably. */ +interface DeployView { + state: string | null; + mergedAt: string | null; + /** The validated base branch, or why there is none. */ + base: Lookup; + /** The validated merge commit, or why there is none to look for. */ + merge: Lookup; +} + +/** Validate a `pr-view` result for `check deploy`. Only a non-object is a failure; a missing field fails the check that needs it. */ +export function parseDeployView(data: unknown): Lookup { + if (typeof data !== 'object' || data === null || Array.isArray(data)) { + return { ok: false, reason: 'pr-view returned something other than a JSON object' }; + } + const raw = data as Record; + const text = (value: unknown): string | null => (typeof value === 'string' && value !== '' ? value : null); + const state = text(raw.state); + const mergedAt = text(raw.mergedAt); + const base: Lookup = + raw.baseRefName === undefined || raw.baseRefName === null || raw.baseRefName === '' + ? { ok: false, reason: 'pr-view did not return baseRefName' } + : typeof raw.baseRefName === 'string' && isRefName(raw.baseRefName) + ? { ok: true, value: raw.baseRefName } + : { ok: false, reason: `pr-view returned baseRefName ${JSON.stringify(raw.baseRefName)}, not a valid branch name` }; + + let merge: Lookup; + if (state === null) merge = { ok: false, reason: 'pr-view did not return state' }; + else if (normalizeState(state, mergedAt) !== 'MERGED') merge = { ok: false, reason: `the PR is not merged (${normalizeState(state, mergedAt)})` }; + else if (raw.mergeCommit === undefined) merge = { ok: false, reason: 'pr-view did not return mergeCommit' }; + else if (raw.mergeCommit === null) merge = { ok: false, reason: 'pr-view returned no merge commit for a merged PR' }; + else { + const oid = typeof raw.mergeCommit === 'object' ? (raw.mergeCommit as Record).oid : undefined; + merge = + typeof oid === 'string' && isFullSha(oid) + ? { ok: true, value: oid } + : { ok: false, reason: `pr-view returned mergeCommit ${JSON.stringify(raw.mergeCommit)}, not { oid: }` }; + } + return { ok: true, value: { state, mergedAt, base, merge } }; +} + +/** The runs `workflow-runs` returned, newest first. A failure reason names the concept and the item. */ +export function parseWorkflowRuns(data: unknown): Lookup { + if (!Array.isArray(data)) return { ok: false, reason: 'workflow-runs returned something other than a JSON array' }; + const runs: WorkflowRunItem[] = []; + for (const [index, raw] of data.entries()) { + const where = `workflow-runs item ${index + 1}`; + if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return { ok: false, reason: `${where} is not an object` }; + const { headSha, status, conclusion, url, createdAt } = raw as Record; + if (typeof status !== 'string') return { ok: false, reason: `${where} has no status` }; + if (conclusion !== null && conclusion !== undefined && typeof conclusion !== 'string') { + return { ok: false, reason: `${where} has a conclusion that is not a string` }; + } + runs.push({ + headSha: typeof headSha === 'string' ? headSha : '', + status, + conclusion: typeof conclusion === 'string' ? conclusion : null, + url: typeof url === 'string' ? url : '', + createdAt: typeof createdAt === 'string' ? createdAt : '', + }); + } + return { ok: true, value: runs }; +} + +/** `2026-11-22 18:04` (UTC) for an ISO 8601 time, or null when it does not parse. */ +function minutes(iso: string): string | null { + const time = Date.parse(iso); + return Number.isNaN(time) ? null : new Date(time).toISOString().slice(0, 16).replace('T', ' '); +} + +// ============================================================================= +// The checks +// ============================================================================= + +/** What every PR's checks share: the runner, the settings, and the reads made once per branch. */ +interface Context { + runner: Runner; + settings: CheckSettings; + version: GitVersion; + tips: Map>>; + runs: Map>>; +} + +function tipOf(ctx: Context, branch: string): Promise> { + let tip = ctx.tips.get(branch); + if (!tip) ctx.tips.set(branch, (tip = liveTip(ctx.runner, branch))); + return tip; +} + +function runsOf(ctx: Context, workflow: string, branch: string): Promise> { + let runs = ctx.runs.get(branch); + if (!runs) { + runs = ctx.runner + .forge('workflow-runs', { CODEV_WORKFLOW: workflow, CODEV_BRANCH: branch }) + .then((outcome) => (outcome.ok ? parseWorkflowRuns(outcome.data) : { ok: false, reason: outcome.reason })); + ctx.runs.set(branch, runs); + } + return runs; +} + +function checkMerged(view: DeployView): Check { + const details = { + state: view.state === null ? null : normalizeState(view.state, view.mergedAt), + mergedAt: view.mergedAt, + mergeCommit: view.merge.ok ? view.merge.value : null, + }; + if (view.merge.ok) { + const when = view.mergedAt ? ` ${view.mergedAt.slice(0, 10)}` : ''; + return check('merged', 'ok', `merged${when} as ${short(view.merge.value)}`, details); + } + if (details.state !== null && details.state !== 'MERGED') return check('merged', 'attention', `${details.state}: not merged`, details); + return notRun('merged', view.merge.reason, details); +} + +/** The merge commit and the branch it should reach. */ +interface Target { + merge: string; + branch: string; +} + +/** `check.deploy.branch`, else the PR's base. */ +function branchFor(ctx: Context, view: DeployView): Lookup { + const { branch } = ctx.settings.deploy; + return branch === null ? view.base : { ok: true, value: branch }; +} + +async function checkOnBranch(ctx: Context, { merge, branch }: Target): Promise { + const tip = await tipOf(ctx, branch); + if (!tip.ok) return notRun('on-branch', tip.reason, { branch }); + if (tip.value === null) return notRun('on-branch', `origin has no branch ${branch}`, { branch }); + const problems = await ensureCommits(ctx.runner, [merge, tip.value], ctx.version); + const problem = problems.get(merge) ?? problems.get(tip.value); + if (problem) return notRun('on-branch', problem, { branch, tip: tip.value }); + const contains = await isAncestor(ctx.runner, merge, tip.value); + const words = `origin/${branch} @ ${short(tip.value)} ${contains ? 'contains' : 'does not contain'} ${short(merge)}`; + return check('on-branch', contains ? 'ok' : 'attention', words, { branch, tip: tip.value, contains }); +} + +async function checkDeployRun(ctx: Context, { merge, branch }: Target, workflow: string): Promise { + const runs = await runsOf(ctx, workflow, branch); + if (!runs.ok) return notRun('deploy-run', runs.reason, { workflow }); + const green = runs.value.find((r) => r.status === 'completed' && r.conclusion === 'success'); + if (!green) { + const among = runs.value.length === 0 ? `no ${workflow} run on ${branch}` : `no green ${workflow} run on ${branch} among the ${runs.value.length} returned`; + return check('deploy-run', 'attention', among, { workflow }); + } + if (!isFullSha(green.headSha)) { + return notRun('deploy-run', `workflow-runs returned invalid headSha ${JSON.stringify(green.headSha)}`, { workflow }); + } + const run = { headSha: green.headSha, url: green.url, createdAt: green.createdAt }; + const problems = await ensureCommits(ctx.runner, [merge, green.headSha], ctx.version); + const problem = problems.get(green.headSha) ?? problems.get(merge); + if (problem) return notRun('deploy-run', problem, { workflow, run }); + const contains = await isAncestor(ctx.runner, merge, green.headSha); + const when = minutes(green.createdAt); + const which = `latest green ${workflow} run (${when ? `${when}, ` : ''}${short(green.headSha)})`; + return check('deploy-run', contains ? 'ok' : 'attention', `${which} ${contains ? 'contains' : 'does not contain'} ${short(merge)}`, { + workflow, + run, + contains, + }); +} + +/** What keeps a commit's runs from `ok`, or null when they all passed. */ +export function runsProblem(runs: CommitRuns): 'failed' | 'running' | 'no runs' | null { + if (runs.failed > 0) return 'failed'; + if (runs.pending > 0) return 'running'; + return runs.runs.length === 0 ? 'no runs' : null; +} + +async function checkMergeChecks(ctx: Context, merge: string): Promise { + const runs = await lookupRuns(ctx.runner, merge); + if (!runs.ok) return notRun('merge-checks', runs.reason); + const status = runsProblem(runs.value) === null ? 'ok' : 'attention'; + return check('merge-checks', status, `${short(merge)}: ${describeRuns(runs.value)}`, { ...runs.value }); +} + +/** + * A check, or its `skip` entry when `check.skip` names it. Tested before the check runs, so a + * skipped check asks neither git nor the forge anything. + */ +async function unlessSkipped(ctx: Context, id: string, run: () => Check | Promise): Promise { + return ctx.settings.skip.has(id) ? skipped(id) : run(); +} + +const NO_WORKFLOW = 'no deploy workflow configured (check.deploy.workflow)'; + +async function deployChecks(ctx: Context, view: DeployView): Promise { + const { workflow } = ctx.settings.deploy; + const branch = branchFor(ctx, view); + // The merge commit and its branch, or why the checks that need them cannot run. + const target: Lookup = !view.merge.ok + ? view.merge + : !branch.ok + ? branch + : { ok: true, value: { merge: view.merge.value, branch: branch.value } }; + const where = branch.ok ? { branch: branch.value } : {}; + + const checks = [ + await unlessSkipped(ctx, 'merged', () => checkMerged(view)), + await unlessSkipped(ctx, 'on-branch', () => (target.ok ? checkOnBranch(ctx, target.value) : notRun('on-branch', target.reason, where))), + await unlessSkipped(ctx, 'deploy-run', () => { + if (workflow === null) return off('deploy-run', NO_WORKFLOW); + return target.ok ? checkDeployRun(ctx, target.value, workflow) : notRun('deploy-run', target.reason, { workflow }); + }), + ]; + if (workflow === null) { + const merge = view.merge; + checks.push(await unlessSkipped(ctx, 'merge-checks', () => (merge.ok ? checkMergeChecks(ctx, merge.value) : notRun('merge-checks', merge.reason)))); + } + return checks; +} + +/** A PR that could not be read: `merged` says why, and every check that needs the PR is not run. */ +function unreadChecks(ctx: Context, reason: string): Check[] { + const { workflow, branch } = ctx.settings.deploy; + const unread = 'the PR could not be read'; + const checks = [ + notRun('merged', reason), + notRun('on-branch', unread, branch === null ? {} : { branch }), + workflow === null ? off('deploy-run', NO_WORKFLOW) : notRun('deploy-run', unread, { workflow }), + ]; + if (workflow === null) checks.push(notRun('merge-checks', unread)); + return checks.map((c) => (ctx.settings.skip.has(c.id) ? skipped(c.id) : c)); +} + +async function deployPr(ctx: Context, number: number): Promise { + const outcome = await ctx.runner.forge('pr-view', { CODEV_PR_NUMBER: String(number) }); + const read: Lookup = outcome.ok ? parseDeployView(outcome.data) : { ok: false, reason: outcome.reason }; + if (!read.ok) { + const checks = unreadChecks(ctx, read.reason); + return { number, mergedAt: null, mergeCommit: null, baseRef: null, verdict: verdictOf(checks), checks }; + } + const view = read.value; + const checks = await deployChecks(ctx, view); + return { + number, + mergedAt: view.mergedAt, + mergeCommit: view.merge.ok ? view.merge.value : null, + baseRef: view.base.ok ? view.base.value : null, + verdict: verdictOf(checks), + checks, + }; +} + +// ============================================================================= +// The command +// ============================================================================= + +async function buildDeployReport(numbers: readonly number[], options: CommandOptions): Promise { + const runnerOptions = { timeoutMs: options.timeoutMs, env: options.env, spawn: options.spawn }; + const roots = await resolveRoots(createRunner({ cwd: options.cwd, workspaceRoot: options.cwd, ...runnerOptions })); + const runner = createRunner({ cwd: roots.mainRoot, workspaceRoot: roots.mainRoot, ...runnerOptions }); + const settings = loadCheckSettings(roots.mainRoot); + const ctx: Context = { runner, settings, version: await gitVersion(runner), tips: new Map(), runs: new Map() }; + + const prs: DeployPr[] = []; + for (const number of numbers) prs.push(await deployPr(ctx, number)); + return { + schema: 1, + command: 'deploy', + verdict: prs.some((p) => p.verdict === 'attention') ? 'attention' : 'clear', + generatedAt: new Date().toISOString(), + deployBranch: settings.deploy.branch, + workflow: settings.deploy.workflow, + prs, + }; +} + +/** `codev check deploy …`. Never throws: a failure that prevents a report is exit 2 with an `ErrorReport`. */ +export async function checkDeploy(rawNumbers: readonly string[], options: CommandOptions): Promise> { + try { + if (rawNumbers.length === 0) throw new InputError('no PR number given'); + const numbers = [...new Set(rawNumbers.map(validatePrNumber))]; + const report = await buildDeployReport(numbers, options); + return { report, exitCode: exitCodeOf(report.verdict) }; + } catch (err) { + return { report: errorReport('deploy', err), exitCode: 2 }; + } +} + +// ============================================================================= +// Human form +// ============================================================================= + +/** The branch a PR's `on-branch` check looked at, when it got that far. */ +function branchOf(pr: DeployPr): string | null { + const onBranch = pr.checks.find((c) => c.id === 'on-branch'); + return typeof onBranch?.details.branch === 'string' ? onBranch.details.branch : null; +} + +const DEPLOY_RENDER: RenderOptions = { + label: (c) => (c.id === 'on-branch' && typeof c.details.branch === 'string' ? `on ${c.details.branch}` : defaultLabel(c.id)), +}; + +/** What a PR needing attention lacks, in a few words: `not deployed`, `not merged`, `merge checks failed`. */ +function problemWords(pr: DeployPr): string[] { + const merged = pr.checks.find((c) => c.id === 'merged'); + if (merged?.status === 'attention') return ['not merged']; + // An unread PR's `merged` carries no state at all. + if (merged?.status === 'not-run') return ['state' in merged.details ? 'merge not read' : 'not read']; + const words: string[] = []; + for (const c of pr.checks.filter(needsAttention)) { + const label = DEPLOY_RENDER.label!(c); + if (c.status === 'not-run') words.push(`${label} not run`); + else if (c.id === 'on-branch') words.push(`not ${label}`); + else if (c.id === 'deploy-run') words.push('not deployed'); + else if (c.id === 'merge-checks') words.push(`merge checks ${runsProblem(c.details as unknown as CommitRuns) ?? 'failed'}`); + } + // `not deployed` says what `not on ` would. + return words.includes('not deployed') ? words.filter((w) => !w.startsWith('not on ')) : words; +} + +/** `#1948 on main; checks on the merge commit passed`: what every PR passed, by check. */ +function clearWords(report: DeployReport): string { + const all = (id: string) => report.prs.every((p) => p.checks.some((c) => c.id === id && c.status === 'ok')); + const parts: string[] = []; + if (all('on-branch')) parts.push(`on ${[...new Set(report.prs.map(branchOf))].join(', ')}`); + if (all('deploy-run')) parts.push(`in the latest green ${report.workflow} run`); + if (all('merge-checks')) parts.push(`checks on the merge commit${report.prs.length === 1 ? '' : 's'} passed`); + const numbers = report.prs.map((p) => `#${p.number}`).join(', '); + return parts.length === 0 ? `${numbers} merged` : `${numbers} ${parts.join('; ')}`; +} + +function sectionTitle(pr: DeployPr): string { + const merged = pr.checks.find((c) => c.id === 'merged'); + const base = pr.baseRef ? ` → ${pr.baseRef}` : ''; + if (pr.mergeCommit) return `#${pr.number} merged${pr.mergedAt ? ` ${pr.mergedAt.slice(0, 10)}` : ''}${base} merge ${short(pr.mergeCommit)}`; + const state = typeof merged?.details.state === 'string' ? ` ${merged.details.state}` : ''; + return `#${pr.number}${state}${state ? base : ''}`; +} + +/** The order of the human lines: what was found first, a check with no configuration last. */ +const HUMAN_ORDER: readonly string[] = ['merged', 'on-branch', 'merge-checks', 'deploy-run']; + +export function renderDeployHuman(report: DeployReport): string { + const verdictLine = + report.verdict === 'clear' + ? `CLEAR ${clearWords(report)}` + : `ATTENTION ${report.prs + .filter((p) => p.verdict === 'attention') + .map((p) => `#${p.number} ${problemWords(p).join(', ')}`) + .join('; ')}`; + const sections = report.prs.map((pr) => ({ + title: sectionTitle(pr), + // An ok merge reads in the title; one needing attention gets its own line. + checks: pr.checks + .filter((c) => !(c.id === 'merged' && c.status === 'ok')) + .sort((a, b) => HUMAN_ORDER.indexOf(a.id) - HUMAN_ORDER.indexOf(b.id)), + })); + return renderHuman({ verdictLine, header: [], sections }, DEPLOY_RENDER); +} diff --git a/packages/codev/src/commands/check/index.ts b/packages/codev/src/commands/check/index.ts index 19f0003bb..c1d921476 100644 --- a/packages/codev/src/commands/check/index.ts +++ b/packages/codev/src/commands/check/index.ts @@ -14,6 +14,7 @@ */ import { Command, CommanderError } from 'commander'; +import { checkDeploy, renderDeployHuman } from './deploy.js'; import { checkPr, renderPrHuman } from './pr.js'; import { renderErrorHuman, renderJson } from './render.js'; import type { CommandName, CommandResult, ErrorReport, Report } from './report.js'; @@ -106,7 +107,7 @@ export function buildCheckCommand(deps: CheckCliDeps = PROCESS_DEPS): Command { }; const group = new Command('check') - .description('Read-only checks: merge readiness of a PR (never merges, pushes, comments or deletes)') + .description('Read-only checks: merge readiness of a PR, and whether merged PRs reached the deploy branch (never merges, pushes, comments or deletes)') .configureOutput({ writeOut: (s) => track(deps.stdout(s)), writeErr: (s) => track(deps.stderr(s)) }); group.exitOverride(onCommanderExit(null)); @@ -121,5 +122,15 @@ export function buildCheckCommand(deps: CheckCliDeps = PROCESS_DEPS): Command { }); pr.exitOverride(onCommanderExit('pr')); + const deploy = group + .command('deploy ') + .description('Whether each merged PR reached the deploy branch (check.deploy.branch, else its base) and, with check.deploy.workflow, the latest green deploy run; without one, CI on the merge commit') + .option('--json', 'print one JSON object (schema 1) instead of the summary') + .action(async (numbers: string[], options: { json?: boolean }) => { + const result = await checkDeploy(numbers, { cwd: deps.cwd(), env: deps.env, timeoutMs: deps.timeoutMs }); + await finish(result, options.json === true, renderDeployHuman); + }); + deploy.exitOverride(onCommanderExit('deploy')); + return group; } From 53f7e65229b3f42e572210d49d6d682b7ca1fe1c Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 18:19:02 -0800 Subject: [PATCH 60/94] [Spec 1951] Thread log: Phase 5 check_deploy built, live runs --- codev/state/spir-1951_thread.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 8b6db5c01..97c0a175b 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -202,3 +202,36 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals attention via `head` anyway); (3) ok `state` in the header (deliberate); (4) `lastCodeCommit: null` widens the spec's details type for the all-porch-only branch; (5) `checkCi` tests `check.skip` itself (so a skip makes no forge call) and `applySkips` repeats it — worth a one-line comment when next touching pr.ts. + +## Phase 5 — check_deploy +- Built: `codev check deploy … [--json]` (deploy.ts) with `merged`, `on-branch`, `deploy-run`, `merge-checks`; + registered in index.ts. Tests: check-deploy.test.ts (stub git, POSIX; the parsers run everywhere), + check-deploy-readonly.test.ts (real repos, every platform), CLI cases in check-cli.test.ts. Helpers: + prViewOverride gained `answerFor`/`failFor` (per PR number); new helpers/deploy-fixture.ts (merged PRs, a + `workflow-runs` override); expectDeployReportShape. +- Choices to note in the review: + - 15a: the unread PR's `merged` reason is the forge's own words (`pr-view failed: GraphQL: Could not resolve to + a PullRequest with the number of 99999. …`), not a literal "PR not found": telling not-found from any other + failure would mean parsing provider-specific stderr. The verdict line says `#99999 not read`; the checks that + need the PR say `the PR could not be read`. + - Unmerged PR: `merged` attention (`OPEN: not merged`); the checks that need the merge commit are not run + (`the PR is not merged (OPEN)`). A preset without `mergeCommit` → `merged` not run, naming the field. + - JSON order follows DEPLOY_CHECK_IDS; the human lines follow the spec sample (on branch, merge checks, then + deploy run, so an `off` line comes last). An ok `merged` reads in the PR's title line, like an ok head/state. + - `deploy run` lines carry the run's date on attention too (the sample shows it only on the ok line). + - ls-remote and workflow-runs run once per branch per command, however many PRs. Repeated PR numbers are + reported once. + - `check.skip` is tested before each check runs, so a skipped check asks neither git nor the forge. + - No end-of-run re-read (the spec asks for none in deploy; a deploy branch moving during the run only moves + forward). `workflow-runs` order is trusted as the contract says (newest first), not re-sorted. + - `merge checks` with no runs is attention, as `checks` is in pr; a project without CI on its base declares + `check.skip: ["merge-checks"]`. +- LIVE RUNS (worktree build, 2026-11-24): + - From the main checkout, nothing configured: `check deploy 1959 1955` → `CLEAR #1959, #1955 on main; checks + on the merge commits passed` (both `merge checks 8 passed`), 4 s, exit 0. `check deploy 1959 99999 1965` → + `ATTENTION #99999 not read; #1965 not merged`, exit 1. Main's refs (md5 of for-each-ref) and FETCH_HEAD (md5) + identical before and after. + - Scratch clone (session scratchpad, origin = git@github.com:cluesmith/codev.git, its own + .codev/config.local.json `check.deploy: {branch: main, workflow: test.yml}`): `check deploy 1959 1955 1954 + 99999` → three `ok on main` + `ok deploy run latest green test.yml run (2026-11-24 00:54, 77e2d82) contains …`, + #99999 not read, exit 1, 7 s; `--json` matches DeployReport. Clone refs unchanged, no FETCH_HEAD written. From 9745b635c0791f6b6ce4a9257dbe99b6b4315939 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 18:28:16 -0800 Subject: [PATCH 61/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index b3214bdf9..1a687b7bf 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: readonly_core @@ -90,7 +90,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T02:01:11.770Z' +updated_at: '2026-11-24T02:28:16.386Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From de04c7295df3fe203499eb4bf1f4eba08c34f922 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 18:32:56 -0800 Subject: [PATCH 62/94] =?UTF-8?q?chore(porch):=201951=20advance=20plan=20p?= =?UTF-8?q?hase=20=E2=86=92=20check=5Fworktree?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1951-read-only-pr-check-for-archite/status.yaml | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 1a687b7bf..2e1a393a9 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -17,14 +17,14 @@ plan_phases: status: complete - id: check_deploy title: codev check deploy - status: in_progress + status: complete - id: check_worktree title: codev check worktree - status: pending + status: in_progress - id: docs_guidance title: Architect guidance and command documentation status: pending -current_plan_phase: check_deploy +current_plan_phase: check_worktree gates: spec-approval: status: approved @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: true +build_complete: false history: - iteration: 1 plan_phase: readonly_core @@ -90,7 +90,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T02:28:16.386Z' +updated_at: '2026-11-24T02:32:56.934Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -107,6 +107,8 @@ context_refreshes: - boundary: plan-phase:check_deploy at: '2026-11-24T01:59:50.988Z' acknowledged_at: '2026-11-24T02:01:11.770Z' + - boundary: plan-phase:check_worktree + at: '2026-11-24T02:32:56.934Z' force_advanced: phase: readonly_core iteration: 3 From a9766d474fc21bfac52d3496de600bd1eb15759e Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 18:33:07 -0800 Subject: [PATCH 63/94] [Spec 1951] Thread log: Phase 5 review, both approve --- codev/state/spir-1951_thread.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 97c0a175b..a5748aa1b 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -235,3 +235,16 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals .codev/config.local.json `check.deploy: {branch: main, workflow: test.yml}`): `check deploy 1959 1955 1954 99999` → three `ok on main` + `ok deploy run latest green test.yml run (2026-11-24 00:54, 77e2d82) contains …`, #99999 not read, exit 1, 7 s; `--json` matches DeployReport. Clone refs unchanged, no FETCH_HEAD written. +- Architect (2026-11-24 02:27): confirmed 8/8 green at 53f7e6522 and the ci-first skip; re-ran `check deploy 1954 + 1939 1965` from the main checkout themselves (two merged `on main`, 8 merge checks passed; the open one `OPEN: + not merged`; 5.6 s; no ref changed). The 15a deviation is accepted: "the forge's own words for a PR it cannot + read, not a parsed 'not found'; record it" (for the REVIEW). Skip applied once (build-complete), noted in the PR + body. Next after review: Phase 6, merging origin/main first (PR #1954 is on main). +- Review iter1: codex APPROVE (no issues), claude APPROVE (none blocking). Porch advanced → check_worktree + (de04c7295). Claude's non-blocking notes: (1) `runsOf` caches by branch only — key it by workflow+branch; + (2) "newest first" from workflow-runs is trusted, not enforced (deliberate; record in the REVIEW); (3) a git + failure in `isAncestor` mid-PR escalates to exit 2 and drops the other PRs' reports — should be that PR's check + not run; (4) `merge not read` also when `state` itself is missing — "state not read" truer; (5) test gaps: two + PRs on different bases with no deploy branch (per-branch cache, `on main, release`), and `check.skip` of + `merged`/`on-branch`. Plan: fold (1), (3), (4), (5) into the first Phase 6 commit as Phase 5 review fold-ins + (as Phase 3's were folded into Phase 4), listed in the PR body; (2) goes to the REVIEW. From 5daa17f65c54c6e1a5474be294d3fc48adf0e232 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 18:33:21 -0800 Subject: [PATCH 64/94] chore(porch): 1951 acknowledge context refresh --- codev/projects/1951-read-only-pr-check-for-archite/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 2e1a393a9..8fe1165a1 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -90,7 +90,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T02:32:56.934Z' +updated_at: '2026-11-24T02:33:21.252Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -109,6 +109,7 @@ context_refreshes: acknowledged_at: '2026-11-24T02:01:11.770Z' - boundary: plan-phase:check_worktree at: '2026-11-24T02:32:56.934Z' + acknowledged_at: '2026-11-24T02:33:21.252Z' force_advanced: phase: readonly_core iteration: 3 From ef9502a1359e11777d151ac5e52b3e4072de375e Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 18:37:29 -0800 Subject: [PATCH 65/94] [Spec 1951][Phase: check_worktree] fix: Phase 5 review fold-ins in check deploy - workflow-runs cache keyed by workflow and branch, not branch alone - a git failure judging ancestry makes that PR's on-branch/deploy-run not run (new ancestry() Lookup in git-facts) instead of failing the whole command - a pr-view without state reads 'state not read', not 'merge not read' - tests: two PRs on different bases with no deploy branch, check.skip of merged and on-branch, the per-PR ancestry failure, the missing state --- .../check/__tests__/check-deploy.test.ts | 73 +++++++++++++++++++ packages/codev/src/commands/check/deploy.ts | 24 ++++-- .../codev/src/commands/check/git-facts.ts | 20 +++-- 3 files changed, 105 insertions(+), 12 deletions(-) diff --git a/packages/codev/src/commands/check/__tests__/check-deploy.test.ts b/packages/codev/src/commands/check/__tests__/check-deploy.test.ts index 2897b47b9..1c766b82e 100644 --- a/packages/codev/src/commands/check/__tests__/check-deploy.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-deploy.test.ts @@ -7,10 +7,12 @@ * compared before and after. The parsers are tested on every platform. */ +import { spawn as realSpawn } from 'node:child_process'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { checkDeploy, parseDeployView, parseWorkflowRuns, renderDeployHuman, runsProblem } from '../deploy.js'; import { summarizeRuns, type Check, type CommandOptions, type DeployReport } from '../report.js'; +import type { SpawnFn } from '../runner.js'; import { useFakeHome } from './helpers/fake-home.js'; import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; import { green, mergedView, mergePr, run, setRemoteBranch, workflowRunsOverride, type WorkflowRunsOverride } from './helpers/deploy-fixture.js'; @@ -326,6 +328,45 @@ describe.skipIf(isWindows)('Spec 1951 — check deploy (stub git)', { timeout: 3 expect(human).toContain(`#9 merged 2026-11-22 → main merge ${s(second.merge)}\n ATTN on production`); }); + it('check.skip ["merged", "on-branch"]: both skip by name, the deploy branch is never read, deploy-run still runs', async () => { + configure({ check: { deploy: DEPLOYED, skip: ['merged', 'on-branch'] } }); + const pr = mergePr(fx, 8); + forge.answerFor(8, mergedView(pr)); + runs.answer([green(pr.merge)]); + + const { report, exitCode } = await runReadOnly(['8']); + + expect(exitCode).toBe(0); + expect(byId(report, 8, 'merged')).toMatchObject({ status: 'skip', reason: 'check.skip' }); + expect(byId(report, 8, 'on-branch')).toMatchObject({ status: 'skip', reason: 'check.skip' }); + expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'ok', details: { contains: true } }); + expect(stub.gitCalls().filter((c) => c.startsWith('ls-remote'))).toEqual([]); + expect(renderDeployHuman(report).split('\n')[0]).toBe('CLEAR #8 in the latest green deploy.yml run'); + }); + + it('a git failure judging ancestry is that PR\'s check not run; every PR is still reported', async () => { + const first = mergePr(fx, 8); + const second = mergePr(fx, 9); + setRemoteBranch(fx, 'production', second.merge); + forge.answerFor(8, mergedView(first)); + forge.answerFor(9, mergedView(second)); + runs.answer([green(second.merge)]); + // Only PR 8's merge commit makes `merge-base --is-ancestor` fail. + const failingFor8: SpawnFn = (command, args, options) => + args.includes('--is-ancestor') && args.includes(first.merge) + ? realSpawn(process.execPath, ['-e', 'process.stderr.write("fatal: simulated failure\\n"); process.exit(128)'], options) + : realSpawn(command, args, options); + + const { report, exitCode } = await runReadOnly(['8', '9'], { spawn: failingFor8 }); + + expect(exitCode).toBe(1); + const reason = 'merge-base --is-ancestor failed: fatal: simulated failure'; + expect(byId(report, 8, 'on-branch')).toMatchObject({ status: 'not-run', reason, details: { branch: 'production', tip: second.merge } }); + expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'not-run', reason, details: { workflow: 'deploy.yml', run: { headSha: second.merge } } }); + expect(report.prs[1]).toMatchObject({ number: 9, verdict: 'clear' }); + expect(renderDeployHuman(report).split('\n')[0]).toBe('ATTENTION #8 on production not run, deploy run not run'); + }); + it('check.skip ["deploy-run"] skips it by name without asking the forge', async () => { configure({ check: { deploy: DEPLOYED, skip: ['deploy-run'] } }); const pr = mergePr(fx, 8); @@ -371,6 +412,26 @@ describe.skipIf(isWindows)('Spec 1951 — check deploy (stub git)', { timeout: 3 ); }); + it('two PRs on different bases: each is judged on its own base, each base read once', async () => { + const first = mergePr(fx, 8); + const second = mergePr(fx, 9); + setRemoteBranch(fx, 'release', second.merge); + forge.answerFor(8, mergedView(first)); + forge.answerFor(9, mergedView(second, { baseRefName: 'release' })); + ci.answer(first.merge, passing(2)); + ci.answer(second.merge, passing(2)); + + const { report, exitCode } = await runReadOnly(['8', '9']); + + expect(exitCode).toBe(0); + expect(byId(report, 8, 'on-branch')).toMatchObject({ status: 'ok', details: { branch: 'main', contains: true } }); + expect(byId(report, 9, 'on-branch')).toMatchObject({ status: 'ok', details: { branch: 'release', tip: second.merge, contains: true } }); + expect(stub.gitCalls().filter((c) => c.startsWith('ls-remote'))).toEqual(['ls-remote origin refs/heads/main', 'ls-remote origin refs/heads/release']); + const human = renderDeployHuman(report); + expect(human.split('\n')[0]).toBe('CLEAR #8, #9 on main, release; checks on the merge commits passed'); + expect(human).toContain(`#9 merged 2026-11-22 → release merge ${s(second.merge)}\n ok on release`); + }); + it('a merge commit since overtaken on main is still on it', async () => { const pr = mergePr(fx, 8); const later = pushFromElsewhere(fx, 'main', { 'later.txt': 'later\n' }); @@ -486,6 +547,18 @@ describe.skipIf(isWindows)('Spec 1951 — check deploy (stub git)', { timeout: 3 expect(renderDeployHuman(report).split('\n')[0]).toBe('ATTENTION #8 merge not read'); }); + it('a pr-view without state: merged not run, read as "state not read"', async () => { + const pr = mergePr(fx, 8); + const view = mergedView(pr); + delete view.state; + forge.answerFor(8, view); + + const { report } = await runReadOnly(['8']); + + expect(byId(report, 8, 'merged')).toMatchObject({ status: 'not-run', reason: 'pr-view did not return state', details: { state: null } }); + expect(renderDeployHuman(report).split('\n')[0]).toBe('ATTENTION #8 state not read'); + }); + it('Scenario 15a: one PR that cannot be read is a per-PR not run; the others are reported in full', async () => { const pr = mergePr(fx, 8); setRemoteBranch(fx, 'production', pr.merge); diff --git a/packages/codev/src/commands/check/deploy.ts b/packages/codev/src/commands/check/deploy.ts index f3d6ab2e3..b3bbcb3ea 100644 --- a/packages/codev/src/commands/check/deploy.ts +++ b/packages/codev/src/commands/check/deploy.ts @@ -18,7 +18,7 @@ */ import type { WorkflowRunItem } from '../../lib/forge-contracts.js'; -import { ensureCommits, gitVersion, isAncestor, liveTip, type GitVersion, type Lookup } from './git-facts.js'; +import { ancestry, ensureCommits, gitVersion, liveTip, type GitVersion, type Lookup } from './git-facts.js'; import { lookupRuns } from './porch-only.js'; import { normalizeState } from './pr.js'; import { defaultLabel, renderHuman, short, type RenderOptions } from './render.js'; @@ -124,7 +124,9 @@ interface Context { runner: Runner; settings: CheckSettings; version: GitVersion; + /** By branch. */ tips: Map>>; + /** By workflow and branch. */ runs: Map>>; } @@ -135,12 +137,13 @@ function tipOf(ctx: Context, branch: string): Promise> { } function runsOf(ctx: Context, workflow: string, branch: string): Promise> { - let runs = ctx.runs.get(branch); + const key = JSON.stringify([workflow, branch]); + let runs = ctx.runs.get(key); if (!runs) { runs = ctx.runner .forge('workflow-runs', { CODEV_WORKFLOW: workflow, CODEV_BRANCH: branch }) .then((outcome) => (outcome.ok ? parseWorkflowRuns(outcome.data) : { ok: false, reason: outcome.reason })); - ctx.runs.set(branch, runs); + ctx.runs.set(key, runs); } return runs; } @@ -178,7 +181,9 @@ async function checkOnBranch(ctx: Context, { merge, branch }: Target): Promise c.id === 'merged'); if (merged?.status === 'attention') return ['not merged']; - // An unread PR's `merged` carries no state at all. - if (merged?.status === 'not-run') return ['state' in merged.details ? 'merge not read' : 'not read']; + // An unread PR's `merged` carries no state at all; a read one may lack only its state. + if (merged?.status === 'not-run') { + if (!('state' in merged.details)) return ['not read']; + return [merged.details.state === null ? 'state not read' : 'merge not read']; + } const words: string[] = []; for (const c of pr.checks.filter(needsAttention)) { const label = DEPLOY_RENDER.label!(c); diff --git a/packages/codev/src/commands/check/git-facts.ts b/packages/codev/src/commands/check/git-facts.ts index df26c3cee..5def55fdb 100644 --- a/packages/codev/src/commands/check/git-facts.ts +++ b/packages/codev/src/commands/check/git-facts.ts @@ -136,12 +136,22 @@ export async function mergeBase(runner: Runner, a: string, b: string): Promise { +/** + * Whether `ancestor` is reachable from `descendant` (a commit is its own ancestor), or why git + * could not say, for a check that reports the failure as its own `not run`. + */ +export async function ancestry(runner: Runner, ancestor: string, descendant: string): Promise> { const result = await runner.git(['merge-base', '--is-ancestor', ancestor, descendant]); - if (result.exitCode === 0) return true; - if (result.exitCode === 1) return false; - throw new CheckCommandError(`git merge-base --is-ancestor ${ancestor} ${descendant} failed`, result.stderr.trim()); + if (result.exitCode === 0) return { ok: true, value: true }; + if (result.exitCode === 1) return { ok: true, value: false }; + return { ok: false, reason: failureReason('merge-base --is-ancestor', result, runner.timeoutLabel) }; +} + +/** `ancestry`, where a git failure fails the whole command. */ +export async function isAncestor(runner: Runner, ancestor: string, descendant: string): Promise { + const answer = await ancestry(runner, ancestor, descendant); + if (!answer.ok) throw new CheckCommandError(`git merge-base --is-ancestor ${ancestor} ${descendant} failed`, answer.reason); + return answer.value; } // ============================================================================= From b6f7d4d74b77408c818bb9c98cf8d1f6a62f11ca Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 18:55:06 -0800 Subject: [PATCH 66/94] [Spec 1951][Phase: check_worktree] feat: codev check worktree `codev check worktree [--json]`: whether removing a builder's worktree and its local branch would lose data (REMOVABLE / REMOVABLE AFTER KEEPING N FILES / NOT REMOVABLE), with the checks uncommitted, commits, remote, pr and ignored. An open PR is attention (exit 1) without changing the verdict. The target resolves against the main checkout, so it reads the same from any worktree; read-only through the runner (status --no-optional-locks, ls-files, rev-list, ls-remote, ref-neutral fetch; pr-search and pr-view). - agent-farm/lib/keep-list.ts: #1950's keep list as pure definitions (DEFAULT_KEEP_IGNORED, keepPatterns, isNeverKeep); keep-files.ts uses it. Agreement test: check worktree's keep files are the ignored part of what listKeepCandidates() keeps. - agent-farm/lib/builder-scaffold.ts: spawn's scaffold (root .builder-*, the write guard's two files, opencode.json) as one list; a test ties it to every built-in harness's worktree files. - afx cleanup (owner decision main-36): hasUncommittedChanges uses isBuilderScaffold() and lists untracked files one by one, so a worktree with only scaffold files, the write guard included, is no longer reported dirty. - settings: cleanup.keepIgnored through the shared keepPatterns(), errors naming the key and the file. - Tests: Scenarios 16-21 and 20a on real worktrees on every platform, the stub-PATH audit on POSIX, parsers, CLI, settings, imports audit. --- codev/state/spir-1951_thread.md | 42 ++ .../spec-1951-builder-scaffold.test.ts | 100 ++++ .../codev/src/agent-farm/commands/cleanup.ts | 16 +- .../src/agent-farm/lib/builder-scaffold.ts | 28 + .../codev/src/agent-farm/lib/keep-files.ts | 29 +- .../codev/src/agent-farm/lib/keep-list.ts | 36 ++ .../codev/src/agent-farm/utils/harness.ts | 3 +- .../check/__tests__/check-cli.test.ts | 54 +- .../__tests__/check-worktree-stubs.test.ts | 165 ++++++ .../check/__tests__/check-worktree.test.ts | 557 ++++++++++++++++++ .../check/__tests__/helpers/report-shape.ts | 45 +- .../__tests__/helpers/worktree-fixture.ts | 138 +++++ .../commands/check/__tests__/imports.test.ts | 29 +- .../commands/check/__tests__/settings.test.ts | 20 +- packages/codev/src/commands/check/index.ts | 14 +- packages/codev/src/commands/check/report.ts | 11 +- packages/codev/src/commands/check/settings.ts | 33 +- packages/codev/src/commands/check/worktree.ts | 540 +++++++++++++++++ 18 files changed, 1812 insertions(+), 48 deletions(-) create mode 100644 packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts create mode 100644 packages/codev/src/agent-farm/lib/builder-scaffold.ts create mode 100644 packages/codev/src/agent-farm/lib/keep-list.ts create mode 100644 packages/codev/src/commands/check/__tests__/check-worktree-stubs.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/check-worktree.test.ts create mode 100644 packages/codev/src/commands/check/__tests__/helpers/worktree-fixture.ts create mode 100644 packages/codev/src/commands/check/worktree.ts diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index a5748aa1b..eb796f51b 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -248,3 +248,45 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals PRs on different bases with no deploy branch (per-branch cache, `on main, release`), and `check.skip` of `merged`/`on-branch`. Plan: fold (1), (3), (4), (5) into the first Phase 6 commit as Phase 5 review fold-ins (as Phase 3's were folded into Phase 4), listed in the PR body; (2) goes to the REVIEW. + +## Phase 6 — check_worktree (2026-11-24) + +- Merged origin/main (112 commits, PR #1954 `afx cleanup --keep-ignored` among them) as b4ae91855: no conflicts. + The merge brought sdk changes (`connectionRefused`) whose stale local dist failed `tsc`; rebuilt types+sdk dist + locally, nothing to commit. +- Phase 5 fold-ins, own commit ef9502a13: runsOf keyed workflow+branch; new `ancestry()` Lookup in git-facts so an + is-ancestor failure is that PR's on-branch/deploy-run `not run` (isAncestor now wraps it); `state not read`; + tests for two bases (`on main, release`, two ls-remotes), skip of merged+on-branch (no ls-remote), the per-PR + ancestry failure, the missing state. +- #1950 coordination: PR #1954 merged → `agent-farm/lib/keep-list.ts` (pure: DEFAULT_KEEP_IGNORED, keepPatterns, + exported `isNeverKeep`); keep-files.ts imports it and re-exports the first two, so #1954's tests run unchanged. + Agreement test lands here (this PR is second): check worktree's keep files == the ignored part of + `listKeepCandidates()` (with the default list minus with `[]`). +- `agent-farm/lib/builder-scaffold.ts` (pure): root-level `.builder-*`, the guard's two files, and opencode.json + (`OPENCODE_CONFIG_RELPATH`, now the constant harness.ts writes). A test asserts SCAFFOLD_PATHS equals what every + BUILTIN_HARNESSES `getWorktreeFiles` writes. Only an untracked file is ever scaffold. +- cleanup.ts (main-36): `hasUncommittedChanges` uses `isBuilderScaffold()` AND `git status --porcelain + --untracked-files=all`. The second is needed for the fix to work: without -uall the guard shows as the directory + `?? .claude/hooks/`, which was the "1 uncommitted file(s)" the evidence saw. Exported for its test. Nothing else + in cleanup changed; its existing tests pass. +- Decisions inside the spec's latitude (for the REVIEW): + - `commits` details: `{ total, notOnBase, unsafe }` — total/notOnBase are the commits not on the live base tip; + `unsafe` (added) is the subset on no remote branch and not covered by the squash rule. The spec's `total` can't + mean "commits on the branch": after a merge-commit merge there is no fork point to count from. + - `pr`: MERGED ok, CLOSED ok ("CLOSED without merging" — finished, data judged by git), OPEN attention, no PR + found attention (can't say finished), any other state attention. PR choice: exact headRefName, OPEN, newest + MERGED, newest CLOSED, then blank state; "newest" = highest number (pr-search has no dates). + - `remote`: matches ok; absent/ahead/behind/diverged `info` (context only); a failed read `not run`. + - Base: the PR's baseRefName; with no PR, PR unavailable or `pr` skipped, origin's HEAD via ls-remote --symref. + `worktree.baseRef`/`baseTip` may be null in the JSON (Phase 7 schema docs, like pr's baseTip). + - A data check that cannot run is conservative: uncommitted or ignored not run → NOT REMOVABLE; commits not run + → NOT REMOVABLE unless the local tip is on the live remote branch (spec rule). + - `check.skip`: a skipped check runs nothing of its own; `remote` skipped still reads the branch tip for + `commits`; `pr` skipped means no forge call and no squash rule. `ignored`'s ls-files nested-repo `dir/` + entries are reported as the entry (keep-files expands them) — agreement holds for files. + - Verdict line omits keep-list files (the verdict word or the data already says it), as the spec sample does. + - A target is a path when it contains a separator or is `.`/`..`; otherwise a builder id. Detached HEAD → exit 2. +- LIVE RUNS (worktree build, before committing Phase 6): `codev check worktree spir-1951` → NOT REMOVABLE (20 + uncommitted = this phase's uncommitted work, 2 unpushed = the merge + fold-in commits, PR #1958 OPEN); + `air-1938` → REMOVABLE, exit 0 (#1939 MERGED, 1 commit after the merge on its remote branch); `bugfix-1956` → + REMOVABLE AFTER KEEPING 2 FILES (two porch review .txt), PR #1965 OPEN, exit 1. diff --git a/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts new file mode 100644 index 000000000..52de7700a --- /dev/null +++ b/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts @@ -0,0 +1,100 @@ +/** + * Spec 1951 — spawn's scaffold files as one list, shared by `afx cleanup` and + * `codev check worktree`, and the cleanup fix it carries (owner decision main-36): a worktree + * holding only scaffold files, the write guard's included, is not dirty to cleanup. + * + * Evidence for the fix: cleanup reported "1 uncommitted file(s)" for two bugfix builders that + * had nothing uncommitted. The one file was the write guard's `.claude/hooks/` directory, + * which `git status --porcelain` lists as a directory and the old `.builder-` regex missed. + */ + +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { hasUncommittedChanges } from '../commands/cleanup.js'; +import { isBuilderScaffold, OPENCODE_CONFIG_RELPATH, SCAFFOLD_PATHS } from '../lib/builder-scaffold.js'; +import { DEFAULT_KEEP_IGNORED, isNeverKeep, keepPatterns } from '../lib/keep-list.js'; +import * as keepFiles from '../lib/keep-files.js'; +import { BUILTIN_HARNESSES } from '../utils/harness.js'; +import { GUARD_SCRIPT_RELPATH, GUARD_SETTINGS_RELPATH } from '../utils/worktree-write-guard.js'; + +describe('Spec 1951 — isBuilderScaffold', () => { + it('matches root-level .builder-* files and the fixed scaffold paths', () => { + for (const p of ['.builder-prompt.txt', '.builder-role.md', '.builder-start.sh', '.builder-session-id', '.builder-state.md', '.builder-reorient.md']) { + expect(isBuilderScaffold(p), p).toBe(true); + } + for (const p of [GUARD_SCRIPT_RELPATH, GUARD_SETTINGS_RELPATH, OPENCODE_CONFIG_RELPATH]) expect(isBuilderScaffold(p), p).toBe(true); + }); + + it('matches nothing else: nested .builder-* names, other hook files, look-alikes', () => { + for (const p of ['src/.builder-x', '.claude/hooks/other.cjs', '.claude/settings.json', '.builder', 'builder-x', 'codev/state/x_thread.md', '.claude/hooks/']) { + expect(isBuilderScaffold(p), p).toBe(false); + } + }); + + it('names every file a built-in harness writes into a worktree, so the two cannot drift', () => { + const written = Object.values(BUILTIN_HARNESSES).flatMap((h) => h.getWorktreeFiles?.('role', '/w/.builder-role.md', '/w') ?? []); + expect([...new Set(written.map((f) => f.relativePath))].sort()).toEqual([...SCAFFOLD_PATHS].sort()); + }); +}); + +describe('Spec 1951 — keep-list.ts is the one definition keep-files.ts uses', () => { + it('keep-files re-exports the same objects', () => { + expect(keepFiles.DEFAULT_KEEP_IGNORED).toBe(DEFAULT_KEEP_IGNORED); + expect(keepFiles.keepPatterns).toBe(keepPatterns); + }); + + it('isNeverKeep: any dependency or build-output segment', () => { + expect(isNeverKeep('node_modules/x/index.js')).toBe(true); + expect(isNeverKeep('codev/projects/8/node_modules/a.js')).toBe(true); + expect(isNeverKeep('packages/x/dist/out.js')).toBe(true); + expect(isNeverKeep('codev/projects/8/review.txt')).toBe(false); + expect(isNeverKeep('distribution/notes.md')).toBe(false); + }); +}); + +describe('Spec 1951 — afx cleanup: hasUncommittedChanges and the scaffold (main-36)', () => { + let worktree: string; + const git = (...args: string[]) => + execFileSync('git', ['-c', 'user.email=t@t', '-c', 'user.name=t', ...args], { cwd: worktree, stdio: 'pipe' }); + const write = (rel: string, content = `${rel}\n`): void => { + mkdirSync(dirname(join(worktree, rel)), { recursive: true }); + writeFileSync(join(worktree, rel), content); + }; + + beforeEach(() => { + worktree = realpathSync(mkdtempSync(join(tmpdir(), 'spec-1951-scaffold-'))); + git('init', '-q'); + write('src/tracked.ts'); + git('add', '.'); + git('commit', '-qm', 'init'); + for (const rel of ['.builder-prompt.txt', '.builder-role.md', '.builder-start.sh', GUARD_SCRIPT_RELPATH, GUARD_SETTINGS_RELPATH]) write(rel); + }); + + afterEach(() => { + rmSync(worktree, { recursive: true, force: true }); + }); + + it('only scaffold files, the write guard included: not dirty', async () => { + expect(await hasUncommittedChanges(worktree)).toEqual({ dirty: false, scaffoldOnly: true, details: '' }); + }); + + it('a clean worktree: not dirty, not scaffold-only', async () => { + rmSync(join(worktree, '.claude'), { recursive: true }); + for (const rel of ['.builder-prompt.txt', '.builder-role.md', '.builder-start.sh']) rmSync(join(worktree, rel)); + expect(await hasUncommittedChanges(worktree)).toEqual({ dirty: false, scaffoldOnly: false, details: '' }); + }); + + it('another file next to the write guard is dirty, counted by itself', async () => { + write('.claude/hooks/mine.cjs'); + expect(await hasUncommittedChanges(worktree)).toEqual({ dirty: true, scaffoldOnly: false, details: '1 uncommitted file(s)' }); + }); + + it('a modified tracked file is dirty, whatever the scaffold', async () => { + write('src/tracked.ts', 'changed\n'); + write('notes.md'); + expect(await hasUncommittedChanges(worktree)).toEqual({ dirty: true, scaffoldOnly: false, details: '2 uncommitted file(s)' }); + }); +}); diff --git a/packages/codev/src/agent-farm/commands/cleanup.ts b/packages/codev/src/agent-farm/commands/cleanup.ts index fe28f499d..4956e570d 100644 --- a/packages/codev/src/agent-farm/commands/cleanup.ts +++ b/packages/codev/src/agent-farm/commands/cleanup.ts @@ -29,6 +29,7 @@ import { sameWindowsPath } from '../../lib/platform/windows/host-paths.js'; import { unquoteWindowsCommandLine } from '../../lib/platform/windows/command-line.js'; import { loadConfig } from '../../lib/config.js'; import { AGENT_FARM_DIR } from '../lib/tower-client.js'; +import { isBuilderScaffold } from '../lib/builder-scaffold.js'; import { keepFiles, keepPatterns, keptDirFor, listKeepCandidates } from '../lib/keep-files.js'; /** @@ -186,22 +187,23 @@ export interface CleanupOptions { /** * Check if a worktree has uncommitted changes - * Returns: dirty (has real changes), scaffoldOnly (only has .builder-* files) + * Returns: dirty (has real changes), scaffoldOnly (only has spawn's scaffold files, + * `isBuilderScaffold()`: `.builder-*` and the write guard's files) */ -async function hasUncommittedChanges(worktreePath: string): Promise<{ dirty: boolean; scaffoldOnly: boolean; details: string }> { +export async function hasUncommittedChanges(worktreePath: string): Promise<{ dirty: boolean; scaffoldOnly: boolean; details: string }> { if (!existsSync(worktreePath)) { return { dirty: false, scaffoldOnly: false, details: '' }; } try { - // Check for uncommitted changes (staged and unstaged) - const result = await run('git status --porcelain', { cwd: worktreePath }); + // Check for uncommitted changes (staged and unstaged). Untracked files are listed one by + // one, so the write guard's `.claude/hooks/` is judged by its file, not as a directory. + const result = await run('git status --porcelain --untracked-files=all', { cwd: worktreePath }); if (result.stdout.trim()) { - // Count changed files, excluding builder scaffold files - const scaffoldPattern = /^\?\? \.builder-/; + // Count changed files, excluding builder scaffold files (only ever untracked) const allLines = result.stdout.trim().split('\n').filter(Boolean); - const nonScaffoldLines = allLines.filter((line) => !scaffoldPattern.test(line)); + const nonScaffoldLines = allLines.filter((line) => !(line.startsWith('?? ') && isBuilderScaffold(line.slice(3)))); if (nonScaffoldLines.length > 0) { return { diff --git a/packages/codev/src/agent-farm/lib/builder-scaffold.ts b/packages/codev/src/agent-farm/lib/builder-scaffold.ts new file mode 100644 index 000000000..d609d83d5 --- /dev/null +++ b/packages/codev/src/agent-farm/lib/builder-scaffold.ts @@ -0,0 +1,28 @@ +/** + * The files `afx spawn` writes into a builder worktree that are not the builder's work + * (Spec 1951). Pure, so `afx cleanup` and `codev check worktree` share one list and agree on + * what is scaffold: + * + * - any root-level `.builder-*` file (the prompt, role, start script, session id, and the + * refresh state files, whose names keep that prefix so they classify as scaffold); + * - the write guard's hook script and settings (`worktree-write-guard.ts`); + * - OpenCode's `opencode.json`, which points the harness at `.builder-role.md`. + * + * Only an untracked file is ever scaffold: a change to a tracked file is a real change, + * whatever its path. + */ + +import { GUARD_SCRIPT_RELPATH, GUARD_SETTINGS_RELPATH } from '../utils/worktree-write-guard.js'; + +/** Worktree-relative path of the OpenCode harness's role-injection file. */ +export const OPENCODE_CONFIG_RELPATH = 'opencode.json'; + +const BUILDER_PREFIX = '.builder-'; + +/** The scaffold files with fixed paths; `.builder-*` is matched by prefix. */ +export const SCAFFOLD_PATHS: readonly string[] = [GUARD_SCRIPT_RELPATH, GUARD_SETTINGS_RELPATH, OPENCODE_CONFIG_RELPATH]; + +/** Whether a worktree-relative, `/`-separated path of an untracked file is spawn's scaffold. */ +export function isBuilderScaffold(path: string): boolean { + return (path.startsWith(BUILDER_PREFIX) && !path.includes('/')) || SCAFFOLD_PATHS.includes(path); +} diff --git a/packages/codev/src/agent-farm/lib/keep-files.ts b/packages/codev/src/agent-farm/lib/keep-files.ts index b0cef21b1..9531bf551 100644 --- a/packages/codev/src/agent-farm/lib/keep-files.ts +++ b/packages/codev/src/agent-farm/lib/keep-files.ts @@ -3,7 +3,8 @@ * * Kept: every untracked file that is not ignored, and the ignored files matching the keep list * (`cleanup.keepIgnored` in `.codev/config.json`). Never kept: dependency and build output, - * whatever the list says, and symlinks (a worktree's links point back into the workspace, and + * whatever the list says (both defined in `keep-list.ts`, which `codev check worktree` shares), + * and symlinks (a worktree's links point back into the workspace, and * following one could copy a secret such as `.env`). Every copy is checked by SHA-256; any * failure removes the partial kept folder and throws, so the caller stops before removing * anything. @@ -14,34 +15,14 @@ import { createHash } from 'node:crypto'; import { createReadStream, existsSync, lstatSync, mkdirSync, readdirSync, rmSync } from 'node:fs'; import { copyFile } from 'node:fs/promises'; import { basename, dirname, join } from 'node:path'; +import { isNeverKeep } from './keep-list.js'; -export const DEFAULT_KEEP_IGNORED: readonly string[] = [ - 'codev/projects/**', - 'codev/state/**', - '.builder-*', - 'tmp/**', - 'scratch/**', -]; - -/** Path segments that mark dependency or build output. */ -const NEVER_KEEP = new Set([ - 'node_modules', 'bower_components', 'dist', 'build', 'target', '.next', '.nuxt', '.turbo', - '.parcel-cache', '.gradle', '.venv', 'venv', '__pycache__', '.pytest_cache', '.mypy_cache', '.tox', -]); +export { DEFAULT_KEEP_IGNORED, keepPatterns } from './keep-list.js'; export function keptDirFor(agentFarmDir: string, workspaceRoot: string, builderId: string): string { return join(agentFarmDir, 'kept', basename(workspaceRoot), builderId); } -/** Validate a `cleanup.keepIgnored` value from config; undefined means the default list. */ -export function keepPatterns(configured: unknown): readonly string[] { - if (configured === undefined) return DEFAULT_KEEP_IGNORED; - if (!Array.isArray(configured) || configured.some((p) => typeof p !== 'string' || p.trim() === '')) { - throw new Error('cleanup.keepIgnored in .codev/config.json must be an array of non-empty glob strings'); - } - return configured; -} - function gitList(worktree: string, args: string[]): string[] { const out = execFileSync('git', ['-C', worktree, 'ls-files', '--others', '-z', ...args], { encoding: 'utf-8', @@ -77,7 +58,7 @@ export function listKeepCandidates(worktree: string, patterns: readonly string[] ? gitList(worktree, ['--ignored', '--exclude-standard', '--', ...patterns.map((p) => `:(glob)${p}`)]) : []; const all = [...new Set([...untracked, ...ignored])].flatMap((rel) => expand(worktree, rel)); - const files = all.filter((rel) => !rel.split('/').some((segment) => NEVER_KEEP.has(segment))).sort(); + const files = all.filter((rel) => !isNeverKeep(rel)).sort(); return { files, excluded: all.length - files.length }; } diff --git a/packages/codev/src/agent-farm/lib/keep-list.ts b/packages/codev/src/agent-farm/lib/keep-list.ts new file mode 100644 index 000000000..0f27fced6 --- /dev/null +++ b/packages/codev/src/agent-farm/lib/keep-list.ts @@ -0,0 +1,36 @@ +/** + * The keep list (#1950) as pure definitions, shared by `afx cleanup --keep-ignored` + * (`keep-files.ts`, which does the copying) and `codev check worktree` (Spec 1951, which only + * reports). One source of truth, so the two agree on what is kept. + * + * Kept: ignored files matching `cleanup.keepIgnored` (default below). Never kept, whatever the + * list says: any path with a dependency- or build-output segment. + */ + +export const DEFAULT_KEEP_IGNORED: readonly string[] = [ + 'codev/projects/**', + 'codev/state/**', + '.builder-*', + 'tmp/**', + 'scratch/**', +]; + +/** Path segments that mark dependency or build output. */ +const NEVER_KEEP = new Set([ + 'node_modules', 'bower_components', 'dist', 'build', 'target', '.next', '.nuxt', '.turbo', + '.parcel-cache', '.gradle', '.venv', 'venv', '__pycache__', '.pytest_cache', '.mypy_cache', '.tox', +]); + +/** Whether a worktree-relative, `/`-separated path is dependency or build output, and so never kept. */ +export function isNeverKeep(path: string): boolean { + return path.split('/').some((segment) => NEVER_KEEP.has(segment)); +} + +/** Validate a `cleanup.keepIgnored` value from config; undefined means the default list. */ +export function keepPatterns(configured: unknown): readonly string[] { + if (configured === undefined) return DEFAULT_KEEP_IGNORED; + if (!Array.isArray(configured) || configured.some((p) => typeof p !== 'string' || p.trim() === '')) { + throw new Error('cleanup.keepIgnored in .codev/config.json must be an array of non-empty glob strings'); + } + return configured; +} diff --git a/packages/codev/src/agent-farm/utils/harness.ts b/packages/codev/src/agent-farm/utils/harness.ts index 7edf19678..768fc8321 100644 --- a/packages/codev/src/agent-farm/utils/harness.ts +++ b/packages/codev/src/agent-farm/utils/harness.ts @@ -20,6 +20,7 @@ import { shellEscapeSingleQuote } from '../../lib/shell-quote.js'; import { findLatestSessionId, verifySessionOwnership } from './claude-session-discovery.js'; import { buildWorktreeGuardFiles } from './worktree-write-guard.js'; +import { OPENCODE_CONFIG_RELPATH } from '../lib/builder-scaffold.js'; // ============================================================================= // Types @@ -339,7 +340,7 @@ export const OPENCODE_HARNESS: HarnessProvider = { }, buildScriptRoleInjection: () => ({ fragment: '', env: {} }), getWorktreeFiles: () => ([{ - relativePath: 'opencode.json', + relativePath: OPENCODE_CONFIG_RELPATH, content: JSON.stringify({ instructions: ['.builder-role.md'] }, null, 2) + '\n', }]), }; diff --git a/packages/codev/src/commands/check/__tests__/check-cli.test.ts b/packages/codev/src/commands/check/__tests__/check-cli.test.ts index 4c9a292ff..46c0db1e5 100644 --- a/packages/codev/src/commands/check/__tests__/check-cli.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-cli.test.ts @@ -13,6 +13,7 @@ import { useFakeHome } from './helpers/fake-home.js'; import { createFixture, type Fixture } from './helpers/git-fixture.js'; import { mergedView, mergePr } from './helpers/deploy-fixture.js'; import { commitChecksOverride, passing, prView, prViewOverride, pushBranch, writeConfig } from './helpers/pr-fixture.js'; +import { addBuilder, builderView, prSearchOverride } from './helpers/worktree-fixture.js'; class Exited extends Error { constructor(public readonly code: number) { @@ -77,18 +78,18 @@ describe('Spec 1951 — codev check: commander wiring', () => { expect(exitCodeForCommander(e(1, 'commander.missingArgument'))).toBe(2); }); - it.each([[['--help']], [['pr', '--help']], [['help', 'pr']], [['deploy', '--help']]])('%j exits 0 and prints help on stdout', async (args) => { + it.each([[['--help']], [['pr', '--help']], [['help', 'pr']], [['deploy', '--help']], [['worktree', '--help']]])('%j exits 0 and prints help on stdout', async (args) => { const outcome = await runCli(args); expect(outcome.code).toBe(0); expect(outcome.stdout).toMatch(/Usage: check/); }); - it('lists pr and deploy with their arguments and --json', async () => { + it('lists pr, deploy and worktree with their arguments and --json', async () => { const help = (await runCli(['--help'])).stdout; expect(help).toMatch(/pr \[options\] /); expect(help).toMatch(/deploy \[options\] /); - expect((await runCli(['pr', '--help'])).stdout).toMatch(/--json/); - expect((await runCli(['deploy', '--help'])).stdout).toMatch(/--json/); + expect(help).toMatch(/worktree \[options\] /); + for (const command of ['pr', 'deploy', 'worktree']) expect((await runCli([command, '--help'])).stdout, command).toMatch(/--json/); }); it.each([ @@ -99,6 +100,8 @@ describe('Spec 1951 — codev check: commander wiring', () => { ['an unknown option', ['pr', '7', '--jsn']], ['deploy without a PR number', ['deploy']], ['an unknown deploy option', ['deploy', '7', '--jsn']], + ['worktree without a target', ['worktree']], + ['worktree with two targets', ['worktree', 'spir-1', 'spir-2']], ])('%s is a usage error: exit 2', async (_name, args) => { const outcome = await runCli(args); expect(outcome.code).toBe(2); @@ -225,6 +228,49 @@ describe('Spec 1951 — codev check deploy through the CLI', { timeout: 30_000 } }); }); +describe('Spec 1951 — codev check worktree through the CLI', { timeout: 30_000 }, () => { + let fx: Fixture; + + beforeEach(() => { + fx = createFixture(); + const forge = prViewOverride(fx); + const search = prSearchOverride(fx); + const b = addBuilder(fx, 'spir-8'); + search.answer([{ number: 8, headRefName: b.branch, state: 'OPEN' }]); + forge.answerFor(8, builderView(b, 'OPEN')); + writeConfig(fx, { forge: { 'pr-view': forge.script, 'pr-search': search.script } }); + }); + + afterEach(() => { + fx.cleanup(); + }); + + it('prints the summary and exits 1 for an open PR', async () => { + const outcome = await runCli(['worktree', 'spir-8'], { cwd: fx.main, env: fx.env }); + expect(outcome.code).toBe(1); + expect(outcome.stdout.split('\n')[0]).toBe('REMOVABLE spir-8 — PR #8 open: builder not finished'); + expect(outcome.stderr).toBe(''); + }); + + it('--json prints exactly one WorktreeReport object', async () => { + const outcome = await runCli(['worktree', 'spir-8', '--json'], { cwd: fx.main, env: fx.env }); + expect(outcome.code).toBe(1); + const report = JSON.parse(outcome.stdout); + expect(report).toMatchObject({ schema: 1, command: 'worktree', verdict: 'attention', removable: 'removable', worktree: { builderId: 'spir-8' } }); + expect(report.checks.map((c: { id: string }) => c.id)).toEqual(['uncommitted', 'commits', 'remote', 'pr', 'ignored']); + }); + + it('a builder that does not exist is exit 2 naming it, on stderr or as an ErrorReport', async () => { + const outcome = await runCli(['worktree', 'spir-99'], { cwd: fx.main, env: fx.env }); + expect(outcome).toMatchObject({ code: 2, stdout: '' }); + expect(outcome.stderr).toMatch(/^codev check worktree: builder spir-99 not found: there is no worktree at /); + + const json = await runCli(['worktree', 'spir-99', '--json'], { cwd: fx.main, env: fx.env }); + expect(json.code).toBe(2); + expect(JSON.parse(json.stdout)).toMatchObject({ schema: 1, command: 'worktree', error: { message: expect.stringMatching(/^builder spir-99 not found/) } }); + }); +}); + describe('Spec 1951 — codev --help lists check', () => { let exit: ReturnType; let write: ReturnType; diff --git a/packages/codev/src/commands/check/__tests__/check-worktree-stubs.test.ts b/packages/codev/src/commands/check/__tests__/check-worktree-stubs.test.ts new file mode 100644 index 000000000..794d03a6a --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/check-worktree-stubs.test.ts @@ -0,0 +1,165 @@ +/** + * Spec 1951 — `codev check worktree` under the stub-PATH audit (Scenario 22; POSIX). + * + * A stub `git` first on PATH records every call and refuses anything off its own read-only + * list, then runs the real git. Each case runs the command on a real worktree, then proves + * that nothing off the list ran, that the per-worktree reads named the worktree with `-C` and + * `status` carried `--no-optional-locks`, and that the main checkout and the inspected + * worktree are unchanged. + */ + +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { Removable } from '../report.js'; +import { checkWorktree } from '../worktree.js'; +import { useFakeHome } from './helpers/fake-home.js'; +import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { prViewOverride, writeConfig, type PrViewOverride } from './helpers/pr-fixture.js'; +import { expectWorktreeReportShape } from './helpers/report-shape.js'; +import { createStubBin, type StubBin } from './helpers/stub-bin.js'; +import { + addBuilder, + builderView, + deleteRemoteBranch, + mergeBuilder, + prSearchOverride, + squashBuilder, + writeFiles, + type Builder, + type PrSearchOverride, +} from './helpers/worktree-fixture.js'; + +const isWindows = process.platform === 'win32'; + +useFakeHome(); + +let fx: Fixture; +let stub: StubBin; +let view: PrViewOverride; +let search: PrSearchOverride; +let uninstall: () => void; + +function prIs(b: Builder, state: 'OPEN' | 'MERGED'): void { + search.answer([{ number: 8, headRefName: b.branch, state }]); + view.answerFor(8, builderView(b, state)); +} + +interface Case { + name: string; + arrange: () => Builder; + removable: Removable; + exitCode: number; +} + +const CASES: Case[] = [ + { + name: 'Scenario 16: merged, remote branch deleted', + arrange: () => { + const b = addBuilder(fx, 'spir-8'); + mergeBuilder(fx, b); + deleteRemoteBranch(fx, b.branch); + prIs(b, 'MERGED'); + return b; + }, + removable: 'removable', + exitCode: 0, + }, + { + name: 'Scenario 17: a modified tracked file', + arrange: () => { + const b = addBuilder(fx, 'spir-8'); + writeFiles(b.dir, { 'codev/state/spir-8_thread.md': 'changed\n' }); + prIs(b, 'OPEN'); + return b; + }, + removable: 'not-removable', + exitCode: 1, + }, + { + name: 'Scenario 18: an unpushed commit', + arrange: () => { + const b = addBuilder(fx, 'spir-8'); + fx.commit(b.dir, { 'late.ts': 'late\n' }, 'late'); + prIs(b, 'OPEN'); + return b; + }, + removable: 'not-removable', + exitCode: 1, + }, + { + name: 'Scenario 19: squash-merged at the merged head', + arrange: () => { + const b = addBuilder(fx, 'spir-8'); + squashBuilder(fx, b); + deleteRemoteBranch(fx, b.branch); + prIs(b, 'MERGED'); + return b; + }, + removable: 'removable', + exitCode: 0, + }, + { + name: 'Scenario 20: keep-list ignored files next to node_modules/', + arrange: () => { + fx.commit(fx.main, { '.gitignore': 'node_modules/\ntmp/\n' }, 'ignore'); + fx.git(fx.main, 'push', '-q', 'origin', 'main'); + const b = addBuilder(fx, 'spir-8'); + writeFiles(b.dir, { 'tmp/notes.md': 'n\n', 'node_modules/x/index.js': 'x\n' }); + mergeBuilder(fx, b); + prIs(b, 'MERGED'); + return b; + }, + removable: 'removable-after-keeping', + exitCode: 1, + }, + { + name: 'Scenario 20a: clean and pushed, PR open', + arrange: () => { + const b = addBuilder(fx, 'spir-8'); + prIs(b, 'OPEN'); + return b; + }, + removable: 'removable', + exitCode: 1, + }, +]; + +describe.skipIf(isWindows)('Spec 1951 — check worktree (stub git)', { timeout: 30_000 }, () => { + beforeEach(() => { + fx = createFixture(); + stub = createStubBin(path.join(fx.root, 'bin')); + uninstall = stub.install(); + view = prViewOverride(fx); + search = prSearchOverride(fx); + writeConfig(fx, { forge: { 'pr-view': view.script, 'pr-search': search.script } }); + }); + + afterEach(() => { + uninstall(); + fx.cleanup(); + }); + + it.each(CASES)('$name: every git call is on the read-only list, and nothing changes', async (c) => { + const b = c.arrange(); + const before = [snapshotRepoState(fx, fx.main), snapshotRepoState(fx, b.dir)]; + const callsBefore = stub.gitCalls().length; + + const result = await checkWorktree('spir-8', { cwd: fx.main, env: { ...fx.env, ...stub.env }, timeoutMs: 20_000 }); + + if ('error' in result.report) throw new Error(`unexpected exit 2: ${result.report.error.message}`); + expectWorktreeReportShape(result.report); + expect(result.report.removable).toBe(c.removable); + expect(result.exitCode).toBe(c.exitCode); + expect(stub.violations()).toEqual([]); + expect([snapshotRepoState(fx, fx.main), snapshotRepoState(fx, b.dir)]).toEqual(before); + + const calls = stub.gitCalls().slice(callsBefore); + const inWorktree = calls.filter((call) => call.startsWith(`-C ${b.dir} `)); + expect(inWorktree.map((call) => call.split(' ').slice(2, 4).join(' ')).sort()).toEqual([ + '--no-optional-locks status', + 'ls-files --others', + 'ls-files --others', + ]); + expect(calls.filter((call) => /(^| )status( |$)/.test(call)).every((call) => call.includes('--no-optional-locks'))).toBe(true); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/check-worktree.test.ts b/packages/codev/src/commands/check/__tests__/check-worktree.test.ts new file mode 100644 index 000000000..5af55430a --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/check-worktree.test.ts @@ -0,0 +1,557 @@ +/** + * Spec 1951 — `codev check worktree` (Scenarios 16–21, 20a) against real worktrees made with + * `git worktree add`, on every platform. + * + * The forge comes from `pr-search` and `pr-view` concept overrides (`.sh` scripts Git Bash + * runs on Windows). Every run compares the main checkout and the inspected worktree before + * and after: refs, HEAD, both index files, FETCH_HEAD and status (Scenario 23). The + * stub-PATH audit of every git call is in check-worktree-stubs.test.ts (POSIX). + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { listKeepCandidates } from '../../../agent-farm/lib/keep-files.js'; +import { DEFAULT_KEEP_IGNORED } from '../../../agent-farm/lib/keep-list.js'; +import type { Check, CommandOptions, ErrorReport, Status, WorktreeReport } from '../report.js'; +import type { SpawnFn } from '../runner.js'; +import { checkWorktree, parseStatus, pickPr, removability, renderWorktreeHuman } from '../worktree.js'; +import { useFakeHome } from './helpers/fake-home.js'; +import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { prViewOverride, writeConfig, type PrViewOverride } from './helpers/pr-fixture.js'; +import { expectWorktreeReportShape } from './helpers/report-shape.js'; +import { + addBuilder, + builderView, + deleteRemoteBranch, + mergeBuilder, + prSearchOverride, + SCAFFOLD_FILES, + squashBuilder, + writeFiles, + type Builder, + type PrSearchOverride, +} from './helpers/worktree-fixture.js'; + +const s = (sha: string): string => sha.slice(0, 7); + +describe('Spec 1951 — check worktree: parsers and the verdict rule', () => { + it('parseStatus: change words, a rename with its source, and conflicts', () => { + const output = [' M a.txt', '?? b.txt', 'R new.txt', 'old.txt', 'UU c.txt', 'A d.txt', ' D e.txt', ''].join('\0'); + expect(parseStatus(output)).toEqual([ + { path: 'a.txt', change: 'modified' }, + { path: 'b.txt', change: 'untracked' }, + { path: 'new.txt', change: 'renamed' }, + { path: 'c.txt', change: 'conflicted' }, + { path: 'd.txt', change: 'added' }, + { path: 'e.txt', change: 'deleted' }, + ]); + expect(parseStatus('')).toEqual([]); + expect(() => parseStatus('garbage\0')).toThrow('unexpected git status output'); + }); + + it('pickPr: exact head branch only; OPEN, then the newest MERGED, then CLOSED, then a blank state', () => { + const branch = 'builder/spir-8'; + const item = (number: number, state?: string, headRefName = branch) => ({ number, headRefName, ...(state === undefined ? {} : { state }) }); + expect(pickPr([item(3, 'MERGED'), item(9, 'OPEN'), item(5, 'CLOSED')], branch)).toEqual({ ok: true, value: 9 }); + expect(pickPr([item(3, 'MERGED'), item(7, 'MERGED'), item(9, 'CLOSED')], branch)).toEqual({ ok: true, value: 7 }); + expect(pickPr([item(9), item(4, 'closed')], branch)).toEqual({ ok: true, value: 4 }); + expect(pickPr([item(80, 'OPEN', 'builder/spir-80')], branch)).toEqual({ ok: true, value: null }); + expect(pickPr([], branch)).toEqual({ ok: true, value: null }); + expect(pickPr({}, branch)).toEqual({ ok: false, reason: 'pr-search returned something other than a JSON array' }); + expect(pickPr([{ number: '8', headRefName: branch }], branch)).toEqual({ ok: false, reason: 'pr-search item 1 has no valid number' }); + }); + + it('removability: data only; a data check that could not run is conservative', () => { + const c = (id: string, status: Status): Check => ({ id, status, summary: '', details: {} }); + const all = (u: Status, k: Status, i: Status, p: Status = 'ok') => [c('uncommitted', u), c('commits', k), c('remote', 'info'), c('pr', p), c('ignored', i)]; + expect(removability(all('ok', 'ok', 'ok', 'attention'), false)).toBe('removable'); + expect(removability(all('ok', 'ok', 'attention'), false)).toBe('removable-after-keeping'); + expect(removability(all('attention', 'ok', 'attention'), false)).toBe('not-removable'); + expect(removability(all('not-run', 'ok', 'ok'), false)).toBe('not-removable'); + expect(removability(all('ok', 'attention', 'ok'), true)).toBe('not-removable'); + expect(removability(all('ok', 'not-run', 'ok'), false)).toBe('not-removable'); + expect(removability(all('ok', 'not-run', 'ok'), true)).toBe('removable'); + expect(removability(all('ok', 'ok', 'not-run'), false)).toBe('not-removable'); + expect(removability(all('skip', 'skip', 'skip'), false)).toBe('removable'); + }); +}); + +useFakeHome(); + +let fx: Fixture; +let view: PrViewOverride; +let search: PrSearchOverride; + +beforeEach(() => { + fx = createFixture(); + view = prViewOverride(fx); + search = prSearchOverride(fx); +}); + +afterEach(() => { + fx.cleanup(); +}); + +function configure(extra: { forge?: Record; check?: Record; cleanup?: Record } = {}): string { + return writeConfig(fx, { + forge: { 'pr-view': view.script, 'pr-search': search.script, ...extra.forge }, + ...(extra.check ? { check: extra.check } : {}), + ...(extra.cleanup ? { cleanup: extra.cleanup } : {}), + }); +} + +/** The builder's PR as the forge reports it: found by `pr-search`, read by `pr-view`. */ +function prIs(builder: Builder, number: number, state: 'OPEN' | 'MERGED' | 'CLOSED', head = builder.head, overrides: Record = {}): void { + search.answer([{ number, headRefName: builder.branch, baseRefName: 'main', state }]); + view.answerFor(number, builderView(builder, state, head, overrides)); +} + +async function runReport(target: string, extra: Partial & { inspected?: string } = {}): Promise<{ report: WorktreeReport; exitCode: number }> { + const { inspected, ...options } = extra; + const watched = [fx.main, ...(inspected ? [inspected] : [])]; + const before = watched.map((dir) => snapshotRepoState(fx, dir)); + const result = await checkWorktree(target, { cwd: fx.main, env: fx.env, timeoutMs: 20_000, ...options }); + if ('error' in result.report) throw new Error(`unexpected exit 2: ${result.report.error.message}`); + expect(watched.map((dir) => snapshotRepoState(fx, dir))).toEqual(before); + expectWorktreeReportShape(result.report); + return { report: result.report, exitCode: result.exitCode }; +} + +function byId(report: WorktreeReport, id: string): Check { + const found = report.checks.find((c) => c.id === id); + if (!found) throw new Error(`no ${id} check`); + return found; +} + +function withoutTime(report: WorktreeReport): Omit { + const { generatedAt: _ignored, ...rest } = report; + return rest; +} + +const SCAFFOLD_SORTED = [...SCAFFOLD_FILES].sort(); + +// Each case builds real repositories and worktrees. +describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, () => { + it('Scenario 16: clean, merged with a merge commit, remote branch deleted: REMOVABLE, exit 0, laid out as the spec sample', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + mergeBuilder(fx, b); + deleteRemoteBranch(fx, b.branch); + prIs(b, 8, 'MERGED'); + const main = fx.git(fx.main, 'rev-parse', 'HEAD').trim(); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(0); + expect(report).toMatchObject({ + verdict: 'clear', + removable: 'removable', + worktree: { path: fs.realpathSync(b.dir), builderId: 'spir-8', branch: b.branch, baseRef: 'main', baseTip: main }, + }); + expect(byId(report, 'uncommitted')).toMatchObject({ status: 'ok', details: { files: [], scaffold: SCAFFOLD_SORTED } }); + expect(byId(report, 'commits')).toMatchObject({ status: 'ok', details: { total: 0, notOnBase: [], unsafe: [] } }); + expect(byId(report, 'remote')).toMatchObject({ status: 'info', details: { remoteSha: null, relation: 'absent' } }); + expect(byId(report, 'pr')).toMatchObject({ status: 'ok', details: { number: 8, state: 'MERGED', mergedHead: b.head } }); + expect(byId(report, 'ignored')).toMatchObject({ status: 'ok', details: { keep: [], regenerable: 0 } }); + expect(search.calls()).toEqual([`head:${b.branch}`]); + + expect(renderWorktreeHuman(report)).toBe( + [ + 'REMOVABLE spir-8', + '', + `worktree .builders/spir-8 branch builder/spir-8 base main @ ${s(main)} (origin, live)`, + ' ok uncommitted nothing uncommitted [5 scaffold files not counted]', + ' ok commits every commit is on origin/main', + ' info remote origin has no branch builder/spir-8', + ' ok pr #8 MERGED', + ' ok ignored no keep-list files; no other ignored files', + '', + ].join('\n'), + ); + }); + + it('Scenario 17: a modified thread file is NOT REMOVABLE; scaffold files are counted apart', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + prIs(b, 8, 'OPEN'); + fs.appendFileSync(path.join(b.dir, 'codev/state/spir-8_thread.md'), 'more\n'); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(1); + expect(report.removable).toBe('not-removable'); + expect(byId(report, 'uncommitted')).toMatchObject({ + status: 'attention', + summary: '1 file: codev/state/spir-8_thread.md (modified) [5 scaffold files not counted]', + details: { files: [{ path: 'codev/state/spir-8_thread.md', change: 'modified' }], scaffold: SCAFFOLD_SORTED }, + }); + expect(renderWorktreeHuman(report).split('\n')[0]).toBe('NOT REMOVABLE spir-8 — 1 uncommitted file, PR #8 open: builder not finished'); + }); + + it('Scenario 17: only scaffold files untracked, write guard included: nothing uncommitted', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + prIs(b, 8, 'OPEN'); + + const { report } = await runReport('spir-8', { inspected: b.dir }); + + expect(byId(report, 'uncommitted')).toMatchObject({ status: 'ok', details: { files: [], scaffold: SCAFFOLD_SORTED } }); + expect(report.removable).toBe('removable'); + }); + + it('Scenario 17: a staged file and an untracked one outside the scaffold are data', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + prIs(b, 8, 'OPEN'); + writeFiles(b.dir, { 'src/new.ts': 'x\n', 'notes.md': 'n\n', '.claude/other.json': '{}\n' }); + fx.git(b.dir, 'add', 'src/new.ts'); + + const { report } = await runReport('spir-8', { inspected: b.dir }); + + expect(byId(report, 'uncommitted').details.files).toEqual([ + { path: '.claude/other.json', change: 'untracked' }, + { path: 'notes.md', change: 'untracked' }, + { path: 'src/new.ts', change: 'added' }, + ]); + expect(report.removable).toBe('not-removable'); + }); + + it('Scenario 18: an unpushed commit not on the base is NOT REMOVABLE', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + prIs(b, 8, 'OPEN'); + const unpushed = fx.commit(b.dir, { 'src/late.ts': 'late\n' }, 'late work'); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(1); + expect(report.removable).toBe('not-removable'); + expect(byId(report, 'commits')).toMatchObject({ + status: 'attention', + summary: `1 commit on no remote branch: ${s(unpushed)}`, + details: { total: 2, notOnBase: [unpushed, b.head], unsafe: [unpushed] }, + }); + expect(byId(report, 'remote')).toMatchObject({ + status: 'info', + summary: `local ${s(unpushed)} is ahead of origin/builder/spir-8 @ ${s(b.head)} (not pushed)`, + details: { remoteSha: b.head, relation: 'ahead' }, + }); + expect(renderWorktreeHuman(report).split('\n')[0]).toBe('NOT REMOVABLE spir-8 — 1 unpushed commit, PR #8 open: builder not finished'); + }); + + it('pushed commits not yet on the base are safe: they are on the remote branch', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + prIs(b, 8, 'OPEN'); + + const { report } = await runReport('spir-8', { inspected: b.dir }); + + expect(byId(report, 'commits')).toMatchObject({ + status: 'ok', + summary: '1 commit not on origin/main, all on origin/builder/spir-8', + details: { total: 1, notOnBase: [b.head], unsafe: [] }, + }); + expect(byId(report, 'remote')).toMatchObject({ status: 'ok', summary: `origin/builder/spir-8 matches local (${s(b.head)})` }); + }); + + it('Scenario 19: squash-merged, local tip equal to the merged head: REMOVABLE', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + squashBuilder(fx, b); + deleteRemoteBranch(fx, b.branch); + prIs(b, 8, 'MERGED'); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(0); + expect(report.removable).toBe('removable'); + expect(byId(report, 'commits')).toMatchObject({ + status: 'ok', + summary: "1 commit not on origin/main; the local tip is PR #8's merged head (squash or rebase merge)", + details: { total: 1, notOnBase: [b.head], unsafe: [] }, + }); + }); + + it('Scenario 19: squash-merged, then one more local commit: NOT REMOVABLE', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + squashBuilder(fx, b); + deleteRemoteBranch(fx, b.branch); + prIs(b, 8, 'MERGED'); + const after = fx.commit(b.dir, { 'src/after.ts': 'after\n' }, 'after the merge'); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(1); + expect(report.removable).toBe('not-removable'); + expect(byId(report, 'commits')).toMatchObject({ status: 'attention', details: { total: 2, unsafe: [after, b.head] } }); + }); + + describe('Scenario 20: ignored files', () => { + beforeEach(() => { + fx.commit( + fx.main, + { '.gitignore': 'node_modules/\n*.log\ntmp/\ncodev/projects/**/*.txt\n', 'codev/projects/8-x/status.yaml': 'phase: x\n' }, + 'ignore build output and porch transcripts', + ); + fx.git(fx.main, 'push', '-q', 'origin', 'main'); + }); + + function withIgnored(): Builder { + const b = addBuilder(fx, 'spir-8'); + writeFiles(b.dir, { + 'codev/projects/8-x/8-specify-iter1-codex.txt': 'review\n', + 'tmp/notes.md': 'notes\n', + 'node_modules/pkg/index.js': 'module\n', + 'codev/projects/8-x/node_modules/dep.js': 'dep\n', + 'debug.log': 'log\n', + }); + mergeBuilder(fx, b); + deleteRemoteBranch(fx, b.branch); + prIs(b, 8, 'MERGED'); + return b; + } + + it('keep-list files make it REMOVABLE AFTER KEEPING N FILES; never-copy paths count as regenerable', async () => { + configure(); + const b = withIgnored(); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(1); + expect(report.removable).toBe('removable-after-keeping'); + expect(byId(report, 'ignored')).toMatchObject({ + status: 'attention', + details: { keep: ['codev/projects/8-x/8-specify-iter1-codex.txt', 'tmp/notes.md'], regenerable: 3 }, + }); + const human = renderWorktreeHuman(report); + expect(human.split('\n')[0]).toBe('REMOVABLE AFTER KEEPING 2 FILES spir-8'); + expect(human).toContain( + [ + ' ATTN ignored 2 keep-list files would be lost: codev/projects/8-x/8-specify-iter1-codex.txt, tmp/notes.md', + ' (3 other ignored paths treated as regenerable: codev/projects/8-x/node_modules/, … +2)', + ' → copy them out first, or use `afx cleanup --keep-ignored`', + ].join('\n'), + ); + }); + + it('agrees with afx cleanup --keep-ignored: the keep files are the ignored part of what it would keep', async () => { + configure(); + const b = withIgnored(); + const saved = { ...process.env }; + Object.assign(process.env, fx.env); + let cleanupKeeps: string[]; + try { + const kept = listKeepCandidates(b.dir, DEFAULT_KEEP_IGNORED).files; + const untracked = listKeepCandidates(b.dir, []).files; + cleanupKeeps = kept.filter((f) => !untracked.includes(f)); + } finally { + for (const key of Object.keys(fx.env)) { + if (saved[key] === undefined) delete process.env[key]; + else process.env[key] = saved[key]; + } + } + + const { report } = await runReport('spir-8', { inspected: b.dir }); + + expect(byId(report, 'ignored').details.keep).toEqual(cleanupKeeps); + expect(cleanupKeeps).toEqual(['codev/projects/8-x/8-specify-iter1-codex.txt', 'tmp/notes.md']); + }); + + it('cleanup.keepIgnored [] reports no keep files: REMOVABLE', async () => { + configure({ cleanup: { keepIgnored: [] } }); + const b = withIgnored(); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(0); + expect(report.removable).toBe('removable'); + expect(byId(report, 'ignored')).toMatchObject({ + status: 'ok', + summary: 'no keep list (cleanup.keepIgnored is empty); 5 ignored paths treated as regenerable: codev/projects/8-x/8-specify-iter1-codex.txt, … +4', + details: { keep: [], regenerable: 5 }, + }); + }); + + it('a configured keep list replaces the default', async () => { + configure({ cleanup: { keepIgnored: ['*.log'] } }); + const b = withIgnored(); + + const { report } = await runReport('spir-8', { inspected: b.dir }); + + expect(byId(report, 'ignored').details).toEqual({ keep: ['debug.log'], regenerable: 4 }); + }); + }); + + it('Scenario 20a: clean and fully pushed, PR still OPEN: REMOVABLE, pr attention, exit 1', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + prIs(b, 8, 'OPEN'); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(1); + expect(report).toMatchObject({ verdict: 'attention', removable: 'removable' }); + expect(byId(report, 'pr')).toMatchObject({ status: 'attention', summary: '#8 OPEN: builder not finished', details: { number: 8, state: 'OPEN' } }); + expect(renderWorktreeHuman(report).split('\n')[0]).toBe('REMOVABLE spir-8 — PR #8 open: builder not finished'); + }); + + it('a PR closed without merging is finished; its pushed commits are on the remote branch', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + prIs(b, 8, 'CLOSED'); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(0); + expect(byId(report, 'pr')).toMatchObject({ status: 'ok', summary: '#8 CLOSED without merging' }); + }); + + it('no PR for the branch: pr attention, base from origin\'s default branch', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + search.answer([{ number: 80, headRefName: 'builder/spir-80', state: 'OPEN' }]); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(1); + expect(byId(report, 'pr')).toMatchObject({ status: 'attention', summary: 'no PR found for builder/spir-8', details: {} }); + expect(report.worktree.baseRef).toBe('main'); + expect(view.calls()).toBe(0); + }); + + it.each([ + ['disabled', () => configure({ forge: { 'pr-search': null } }), 'PR state not available: pr-search unavailable on github'], + ['failing', () => (configure(), search.fail()), 'PR state not available: pr-search failed: pr-search stub: forge unreachable'], + ])('pr-search %s: pr not run, and the data verdict still comes from git', async (_name, arrange, reason) => { + arrange(); + const b = addBuilder(fx, 'spir-8'); + mergeBuilder(fx, b); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(1); + expect(report.removable).toBe('removable'); + expect(byId(report, 'pr')).toMatchObject({ status: 'not-run', reason }); + expect(byId(report, 'commits').status).toBe('ok'); + expect(report.worktree.baseRef).toBe('main'); + }); + + it('pr-view failing for the PR found: pr not run, naming the PR', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + search.answer([{ number: 8, headRefName: b.branch, state: 'OPEN' }]); + view.failFor(8, 'HTTP 502'); + + const { report } = await runReport('spir-8', { inspected: b.dir }); + + expect(byId(report, 'pr')).toMatchObject({ status: 'not-run', reason: 'PR state not available: pr-view failed: HTTP 502', details: { number: 8 } }); + }); + + it('a base origin does not have: commits not run; removable only because the local tip is on the remote branch', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + prIs(b, 8, 'OPEN', b.head, { baseRefName: 'release' }); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(1); + expect(byId(report, 'commits')).toMatchObject({ status: 'not-run', reason: 'base not read: origin has no branch release' }); + expect(report.removable).toBe('removable'); + expect(report.worktree).toMatchObject({ baseRef: 'release', baseTip: null }); + expect(renderWorktreeHuman(report)).toContain('base release (live tip not read)'); + + fx.commit(b.dir, { 'src/late.ts': 'late\n' }, 'late'); + const { report: later } = await runReport('spir-8', { inspected: b.dir }); + expect(later.removable).toBe('not-removable'); + }); + + it('check.skip ["pr", "ignored"]: both skip by name, the forge is never asked, the base is origin\'s default', async () => { + configure({ check: { skip: ['pr', 'ignored'] } }); + const b = addBuilder(fx, 'spir-8'); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(0); + expect(byId(report, 'pr')).toMatchObject({ status: 'skip', reason: 'check.skip' }); + expect(byId(report, 'ignored')).toMatchObject({ status: 'skip', reason: 'check.skip' }); + expect(search.calls()).toEqual([]); + expect(view.calls()).toBe(0); + expect(report.worktree.baseRef).toBe('main'); + }); + + it('run from inside another builder worktree, or given as a path, it resolves the same target', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + const other = addBuilder(fx, 'spir-9'); + prIs(b, 8, 'OPEN'); + + const fromMain = await runReport('spir-8', { inspected: b.dir }); + const fromOther = await runReport('spir-8', { cwd: other.dir, inspected: b.dir }); + const byRelative = await runReport(path.join('.builders', 'spir-8'), { inspected: b.dir }); + const byAbsolute = await runReport(b.dir, { cwd: other.dir, inspected: b.dir }); + const fromItself = await runReport('.', { cwd: b.dir, inspected: b.dir }); + + for (const r of [fromOther, byRelative, byAbsolute, fromItself]) expect(withoutTime(r.report)).toEqual(withoutTime(fromMain.report)); + }); + + it('a worktree outside .builders/ is reported by its path, with no builder id', async () => { + configure(); + const dir = path.join(fx.root, 'elsewhere'); + fx.git(fx.main, 'worktree', 'add', '-q', '-b', 'feature/x', dir, 'main'); + fx.git(dir, 'push', '-q', 'origin', 'feature/x'); + + const { report } = await runReport(dir, { inspected: dir }); + + expect(report.worktree).toMatchObject({ path: fs.realpathSync(dir), builderId: null, branch: 'feature/x' }); + expect(renderWorktreeHuman(report)).toContain(`worktree ${fs.realpathSync(dir)} branch feature/x`); + }); + + describe('Scenario 21: exit 2', () => { + async function failure(target: string, extra: Partial = {}): Promise { + const result = await checkWorktree(target, { cwd: fx.main, env: fx.env, ...extra }); + expect(result.exitCode, target).toBe(2); + const report = result.report as ErrorReport; + expect(report.command).toBe('worktree'); + return report.error.message; + } + + it('a builder id with no worktree', async () => { + configure(); + expect(await failure('spir-99')).toBe(`builder spir-99 not found: there is no worktree at ${path.join(fx.main, '.builders', 'spir-99')}`); + }); + + it('a path that is not a registered worktree, and one that does not exist', async () => { + configure(); + const plain = path.join(fx.main, '.builders', 'not-a-worktree'); + fs.mkdirSync(plain, { recursive: true }); + expect(await failure('not-a-worktree')).toMatch(/not-a-worktree is not a registered worktree of /); + expect(await failure(path.join(fx.root, 'nowhere'))).toBe(`worktree not found: ${path.join(fx.root, 'nowhere')} does not exist`); + }); + + it('the main worktree', async () => { + configure(); + expect(await failure('.')).toMatch(/is the main worktree, not a builder's$/); + }); + + it('a detached HEAD', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + fx.git(b.dir, 'checkout', '-q', '--detach'); + expect(await failure('spir-8')).toMatch(/has a detached HEAD/); + }); + + it('an invalid builder id, before any subprocess starts', async () => { + const spawn = vi.fn(); + for (const target of ['-rf', 'a b', '']) expect(await failure(target, { spawn }), JSON.stringify(target)).not.toBe(''); + expect(spawn).not.toHaveBeenCalled(); + }); + + it('an invalid cleanup.keepIgnored names the key and the file', async () => { + const file = configure({ cleanup: { keepIgnored: 'tmp/**' } }); + addBuilder(fx, 'spir-8'); + expect(await failure('spir-8')).toBe(`cleanup.keepIgnored must be an array of non-empty glob strings (in ${file})`); + }); + }); +}); diff --git a/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts b/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts index 517203f30..425e7e99d 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts @@ -1,10 +1,10 @@ /** - * Scenario 28 (Spec 1951 § JSON schema): a `PrReport` or `DeployReport` survives JSON and has the schema-1 - * shape, with every check id present in order and the verdict following the statuses. + * Scenario 28 (Spec 1951 § JSON schema): a `PrReport`, `DeployReport` or `WorktreeReport` survives JSON + * and has the schema-1 shape, with every check id present in order and the verdict following the statuses. */ import { expect } from 'vitest'; -import { PR_CHECK_IDS, type DeployReport, type PrReport } from '../../report.js'; +import { PR_CHECK_IDS, WORKTREE_CHECK_IDS, type DeployReport, type PrReport, type WorktreeReport } from '../../report.js'; const STATUSES = ['ok', 'attention', 'info', 'not-run', 'off', 'skip']; const WITH_REASON = new Set(['not-run', 'off', 'skip']); @@ -95,3 +95,42 @@ export function expectDeployReportShape(report: DeployReport): void { } expect(parsed.verdict).toBe(parsed.prs.some((p) => p.verdict === 'attention') ? 'attention' : 'clear'); } + +/** A `WorktreeReport` survives JSON and has the schema-1 shape, its details as the spec's table says. */ +export function expectWorktreeReportShape(report: WorktreeReport): void { + const parsed = JSON.parse(JSON.stringify(report)) as WorktreeReport; + expect(parsed).toMatchObject({ schema: 1, command: 'worktree', verdict: expect.stringMatching(/^(clear|attention)$/), generatedAt: expect.any(String) }); + expect(Number.isNaN(Date.parse(parsed.generatedAt))).toBe(false); + expect(['removable', 'removable-after-keeping', 'not-removable']).toContain(parsed.removable); + const { worktree } = parsed; + expect(typeof worktree.path).toBe('string'); + expect(worktree.builderId === null || typeof worktree.builderId === 'string').toBe(true); + expect(typeof worktree.branch).toBe('string'); + expect(worktree.baseRef === null || typeof worktree.baseRef === 'string').toBe(true); + expect(worktree.baseTip === null || SHA.test(worktree.baseTip)).toBe(true); + + expect(parsed.checks.map((c) => c.id)).toEqual([...WORKTREE_CHECK_IDS]); + for (const c of parsed.checks) { + expect(STATUSES, c.id).toContain(c.status); + expect(typeof c.summary, c.id).toBe('string'); + expect(typeof c.details === 'object' && c.details !== null && !Array.isArray(c.details), c.id).toBe(true); + expect(typeof c.reason === 'string', `${c.id} reason`).toBe(WITH_REASON.has(c.status)); + if (c.status === 'not-run' || c.status === 'off' || c.status === 'skip') continue; + if (c.id === 'uncommitted') { + expect(c.details).toEqual({ files: expect.any(Array), scaffold: expect.any(Array) }); + for (const f of c.details.files as unknown[]) expect(f).toEqual({ path: expect.any(String), change: expect.any(String) }); + } + if (c.id === 'commits') { + expect(c.details).toEqual({ total: expect.any(Number), notOnBase: expect.any(Array), unsafe: expect.any(Array) }); + for (const sha of [...(c.details.notOnBase as string[]), ...(c.details.unsafe as string[])]) expect(sha).toMatch(SHA); + } + if (c.id === 'remote') { + expect(c.details.remoteSha === null || SHA.test(String(c.details.remoteSha))).toBe(true); + expect(['matches', 'ahead', 'behind', 'diverged', 'absent']).toContain(c.details.relation); + } + if (c.id === 'pr' && 'mergedHead' in c.details) expect(c.details.mergedHead).toMatch(SHA); + if (c.id === 'ignored') expect(c.details).toEqual({ keep: expect.any(Array), regenerable: expect.any(Number) }); + } + const attention = parsed.checks.some((c) => c.status === 'attention' || c.status === 'not-run'); + expect(parsed.verdict).toBe(attention ? 'attention' : 'clear'); +} diff --git a/packages/codev/src/commands/check/__tests__/helpers/worktree-fixture.ts b/packages/codev/src/commands/check/__tests__/helpers/worktree-fixture.ts new file mode 100644 index 000000000..0744c7adb --- /dev/null +++ b/packages/codev/src/commands/check/__tests__/helpers/worktree-fixture.ts @@ -0,0 +1,138 @@ +/** + * Fixtures for the `codev check worktree` tests (Spec 1951): builder worktrees made with + * `git worktree add` under the fixture's main clone, spawn's scaffold files, PRs merged into + * origin by merge commit or squash, and a `pr-search` concept override that runs on every + * platform. + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { GUARD_SCRIPT_RELPATH, GUARD_SETTINGS_RELPATH } from '../../../../agent-farm/utils/worktree-write-guard.js'; +import type { Fixture } from './git-fixture.js'; +import { prView, shPath } from './pr-fixture.js'; + +export const MERGED_AT = '2026-11-22T17:30:00Z'; + +/** The scaffold files spawn writes into a Claude builder's worktree. */ +export const SCAFFOLD_FILES: readonly string[] = [ + '.builder-prompt.txt', + '.builder-role.md', + '.builder-start.sh', + GUARD_SCRIPT_RELPATH, + GUARD_SETTINGS_RELPATH, +]; + +export interface Builder { + id: string; + branch: string; + dir: string; + /** The local branch tip. */ + head: string; +} + +/** + * A builder worktree at `

/.builders/` on `builder/`, with one commit (a thread + * file), spawn's scaffold files, and the branch pushed to origin unless `push` is false. + */ +export function addBuilder(fx: Fixture, id: string, options: { push?: boolean; files?: Record } = {}): Builder { + const branch = `builder/${id}`; + const dir = path.join(fx.main, '.builders', id); + fx.git(fx.main, 'worktree', 'add', '-q', '-b', branch, dir, 'main'); + const head = fx.commit(dir, options.files ?? { [`codev/state/${id}_thread.md`]: `# ${id}\n` }, `[${id}] work`); + writeScaffold(dir); + if (options.push !== false) fx.git(dir, 'push', '-q', 'origin', branch); + return { id, branch, dir, head }; +} + +export function writeScaffold(dir: string): void { + for (const rel of SCAFFOLD_FILES) { + const file = path.join(dir, rel); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, `scaffold ${rel}\n`); + } +} + +/** Write untracked (or ignored) files into a worktree without committing them. */ +export function writeFiles(dir: string, files: Record): void { + for (const [rel, content] of Object.entries(files)) { + const file = path.join(dir, rel); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content); + } +} + +/** Merge the builder's branch into main with a merge commit and push main. Returns the merge commit. */ +export function mergeBuilder(fx: Fixture, builder: Builder): string { + fx.git(fx.main, 'merge', '-q', '--no-ff', '-m', `Merge ${builder.branch}`, builder.branch); + fx.git(fx.main, 'push', '-q', 'origin', 'main'); + return fx.git(fx.main, 'rev-parse', 'HEAD').trim(); +} + +/** Squash the builder's changes onto main as one new commit and push main. Returns it. */ +export function squashBuilder(fx: Fixture, builder: Builder): string { + fx.git(fx.main, 'merge', '-q', '--squash', builder.branch); + fx.git(fx.main, 'commit', '-q', '-m', `${builder.id} (squashed)`); + fx.git(fx.main, 'push', '-q', 'origin', 'main'); + return fx.git(fx.main, 'rev-parse', 'HEAD').trim(); +} + +export function deleteRemoteBranch(fx: Fixture, branch: string): void { + fx.git(fx.main, 'push', '-q', 'origin', '--delete', branch); +} + +/** What `gh pr view` returns for the builder's PR in `state`, its head the forge's `head`. */ +export function builderView(builder: Builder, state: 'OPEN' | 'MERGED' | 'CLOSED', head = builder.head, overrides: Record = {}): Record { + return prView(head, { + title: `Builder ${builder.id}`, + state, + headRefName: builder.branch, + mergedAt: state === 'MERGED' ? MERGED_AT : null, + mergeCommit: null, + ...overrides, + }); +} + +export interface SearchItem { + number: number; + headRefName: string; + baseRefName?: string; + state?: string; +} + +export interface PrSearchOverride { + /** The absolute script path, to put in `forge["pr-search"]`. */ + script: string; + /** The items every call returns (or raw output); `[]` until set. */ + answer(items: SearchItem[] | string): void; + fail(): void; + /** `CODEV_SEARCH_QUERY` for each call, in order. */ + calls(): string[]; +} + +/** A `pr-search` override answering from a file and recording each query. */ +export function prSearchOverride(fx: Fixture): PrSearchOverride { + const dir = path.join(fx.root, 'forge-search'); + fs.mkdirSync(dir, { recursive: true }); + const script = path.join(dir, 'pr-search.sh'); + fs.writeFileSync( + script, + [ + '#!/bin/sh', + `dir='${shPath(dir)}'`, + 'printf \'%s\\n\' "$CODEV_SEARCH_QUERY" >> "$dir/calls"', + 'if [ -f "$dir/fail" ]; then echo "pr-search stub: forge unreachable" >&2; exit 1; fi', + "if [ -f \"$dir/items.json\" ]; then cat \"$dir/items.json\"; else echo '[]'; fi", + '', + ].join('\n'), + { mode: 0o755 }, + ); + return { + script, + answer: (items) => fs.writeFileSync(path.join(dir, 'items.json'), typeof items === 'string' ? items : JSON.stringify(items)), + fail: () => fs.writeFileSync(path.join(dir, 'fail'), ''), + calls: () => { + const file = path.join(dir, 'calls'); + return fs.existsSync(file) ? fs.readFileSync(file, 'utf-8').split('\n').filter(Boolean) : []; + }, + }; +} diff --git a/packages/codev/src/commands/check/__tests__/imports.test.ts b/packages/codev/src/commands/check/__tests__/imports.test.ts index 85ea417d6..4fb1eb3a7 100644 --- a/packages/codev/src/commands/check/__tests__/imports.test.ts +++ b/packages/codev/src/commands/check/__tests__/imports.test.ts @@ -11,6 +11,7 @@ import * as fs from 'node:fs'; import * as path from 'node:path'; import { describe, expect, it } from 'vitest'; +import { WORKTREE_WRITE_GUARD_SCRIPT } from '../../../agent-farm/utils/worktree-write-guard.js'; const CHECK_DIR = path.resolve(__dirname, '..'); @@ -31,6 +32,25 @@ const ALLOWED: Record = { names: ['loadConfig', 'findConfigSource'], reason: 'reads configuration files; never writes or spawns', }, + '../../agent-farm/lib/keep-list.js': { + names: ['keepPatterns', 'isNeverKeep'], + reason: "#1950's keep list as pure definitions, shared with afx cleanup --keep-ignored (audited below)", + }, + '../../agent-farm/lib/builder-scaffold.js': { + names: ['isBuilderScaffold'], + reason: "spawn's scaffold file list, pure, shared with afx cleanup (audited below)", + }, +}; + +/** + * The modules outside this directory that the check commands import, and everything each may + * import in turn: none of them spawns or does I/O. `scriptText` is a script a module only + * emits as text; a `require` that appears in it is not the module's own. + */ +const PURE_MODULES: Record = { + '../../agent-farm/lib/keep-list.ts': { imports: [] }, + '../../agent-farm/lib/builder-scaffold.ts': { imports: ['../utils/worktree-write-guard.js'] }, + '../../agent-farm/utils/worktree-write-guard.ts': { imports: ['node:path'], scriptText: WORKTREE_WRITE_GUARD_SCRIPT }, }; /** index.ts alone parses arguments. */ @@ -99,7 +119,7 @@ describe('Spec 1951 — audited imports in commands/check/', () => { expect(sources).toEqual( expect.arrayContaining([ 'allow-list.ts', 'deploy.ts', 'git-facts.ts', 'index.ts', 'linked-issue.ts', 'porch-only.ts', 'pr.ts', 'render.ts', 'report.ts', 'roots.ts', - 'runner.ts', 'settings.ts', 'validate.ts', + 'runner.ts', 'settings.ts', 'validate.ts', 'worktree.ts', ]), ); }); @@ -124,6 +144,13 @@ describe('Spec 1951 — audited imports in commands/check/', () => { } }); + it.each(Object.entries(PURE_MODULES))('%s, imported from outside this directory, imports only what it lists', (file, rule) => { + const { imports, dynamic } = parseImports(fs.readFileSync(path.resolve(CHECK_DIR, file), 'utf-8')); + const own = dynamic.filter((d) => !rule.scriptText?.includes(d.replace(/^(\w+)\((.*)\)$/, "$1('$2')"))); + expect(own, file).toEqual([]); + expect(imports.filter((i) => !i.typeOnly).map((i) => i.specifier)).toEqual(rule.imports); + }); + it('only index.ts imports commander', () => { for (const file of sources.filter((f) => f !== 'index.ts')) { const { imports } = parseImports(fs.readFileSync(path.join(CHECK_DIR, file), 'utf-8')); diff --git a/packages/codev/src/commands/check/__tests__/settings.test.ts b/packages/codev/src/commands/check/__tests__/settings.test.ts index ecd2abf6d..4e1e026dc 100644 --- a/packages/codev/src/commands/check/__tests__/settings.test.ts +++ b/packages/codev/src/commands/check/__tests__/settings.test.ts @@ -7,7 +7,8 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { CheckCommandError } from '../report.js'; -import { DEFAULT_NOT_FOR_READING, DEFAULT_WATCH, loadCheckSettings, parseCheckSettings } from '../settings.js'; +import { DEFAULT_KEEP_IGNORED } from '../../../agent-farm/lib/keep-list.js'; +import { DEFAULT_NOT_FOR_READING, DEFAULT_WATCH, loadCheckSettings, loadKeepIgnored, parseCheckSettings, parseKeepIgnored } from '../settings.js'; import { useFakeHome } from './helpers/fake-home.js'; let root: string; @@ -153,3 +154,20 @@ describe('Spec 1951 — check settings', () => { expect(() => parseCheckSettings({ flag: ['a\nb'] }, () => null)).toThrow(/check\.flag must contain only non-empty glob strings/); }); }); + +describe('Spec 1951 — cleanup.keepIgnored for check worktree', () => { + it("is #1950's default list when unset, and a configured list replaces it", () => { + expect(loadKeepIgnored(root)).toBe(DEFAULT_KEEP_IGNORED); + fs.writeFileSync(projectFile, JSON.stringify({ cleanup: { keepIgnored: ['notes/**'] } })); + expect(loadKeepIgnored(root)).toEqual(['notes/**']); + fs.writeFileSync(projectFile, JSON.stringify({ cleanup: { keepIgnored: [] } })); + expect(loadKeepIgnored(root)).toEqual([]); + }); + + it('refuses a bad value, naming the key and the file', () => { + fs.writeFileSync(projectFile, JSON.stringify({ cleanup: { keepIgnored: 'tmp/**' } })); + expect(() => loadKeepIgnored(root)).toThrow(`cleanup.keepIgnored must be an array of non-empty glob strings (in ${projectFile})`); + expect(() => parseKeepIgnored(['ok', ''], null)).toThrow('cleanup.keepIgnored must be an array of non-empty glob strings'); + expect(() => parseKeepIgnored(['a\u0007b'], 'x.json')).toThrow('cleanup.keepIgnored pattern "a\\u0007b" contains a control character (in x.json)'); + }); +}); diff --git a/packages/codev/src/commands/check/index.ts b/packages/codev/src/commands/check/index.ts index c1d921476..0b5dbdbae 100644 --- a/packages/codev/src/commands/check/index.ts +++ b/packages/codev/src/commands/check/index.ts @@ -18,6 +18,7 @@ import { checkDeploy, renderDeployHuman } from './deploy.js'; import { checkPr, renderPrHuman } from './pr.js'; import { renderErrorHuman, renderJson } from './render.js'; import type { CommandName, CommandResult, ErrorReport, Report } from './report.js'; +import { checkWorktree, renderWorktreeHuman } from './worktree.js'; export interface CheckCliDeps { /** @@ -107,7 +108,7 @@ export function buildCheckCommand(deps: CheckCliDeps = PROCESS_DEPS): Command { }; const group = new Command('check') - .description('Read-only checks: merge readiness of a PR, and whether merged PRs reached the deploy branch (never merges, pushes, comments or deletes)') + .description('Read-only checks: merge readiness of a PR, whether merged PRs reached the deploy branch, and whether a builder worktree can be removed (never merges, pushes, comments or deletes)') .configureOutput({ writeOut: (s) => track(deps.stdout(s)), writeErr: (s) => track(deps.stderr(s)) }); group.exitOverride(onCommanderExit(null)); @@ -132,5 +133,16 @@ export function buildCheckCommand(deps: CheckCliDeps = PROCESS_DEPS): Command { }); deploy.exitOverride(onCommanderExit('deploy')); + const worktree = group + .command('worktree ') + .description('Whether removing a builder worktree (builder id or path) and its local branch would lose data: uncommitted files, unpushed commits, keep-list ignored files; and whether its PR is finished') + .option('--json', 'print one JSON object (schema 1) instead of the summary') + .allowExcessArguments(false) + .action(async (target: string, options: { json?: boolean }) => { + const result = await checkWorktree(target, { cwd: deps.cwd(), env: deps.env, timeoutMs: deps.timeoutMs }); + await finish(result, options.json === true, renderWorktreeHuman); + }); + worktree.exitOverride(onCommanderExit('worktree')); + return group; } diff --git a/packages/codev/src/commands/check/report.ts b/packages/codev/src/commands/check/report.ts index 8f76be7d8..4e0b6a200 100644 --- a/packages/codev/src/commands/check/report.ts +++ b/packages/codev/src/commands/check/report.ts @@ -86,7 +86,16 @@ export type Removable = 'removable' | 'removable-after-keeping' | 'not-removable export interface WorktreeReport extends Report { command: 'worktree'; removable: Removable; - worktree: { path: string; builderId: string | null; branch: string; baseRef: string; baseTip: string }; + worktree: { + /** The worktree's real path. */ + path: string; + builderId: string | null; + branch: string; + /** The PR's base, else origin's default branch; null when neither could be read. */ + baseRef: string | null; + /** The live tip `ls-remote` reported; null when it could not be read (`commits` is then not run). */ + baseTip: string | null; + }; checks: Check[]; } diff --git a/packages/codev/src/commands/check/settings.ts b/packages/codev/src/commands/check/settings.ts index 7b8685afd..6543352f4 100644 --- a/packages/codev/src/commands/check/settings.ts +++ b/packages/codev/src/commands/check/settings.ts @@ -1,11 +1,13 @@ /** - * `check.*` configuration (Spec 1951 § What is configurable). + * `check.*` configuration (Spec 1951 § What is configurable), and `cleanup.keepIgnored` + * (#1950) for `check worktree`. * * Read from the main workspace root through the usual five-layer loader (arrays replace, * never concatenate). Every value is validated; a bad one is exit 2 naming the key and the * file that set it. */ +import { keepPatterns } from '../../agent-farm/lib/keep-list.js'; import { findConfigSource, loadConfig } from '../../lib/config.js'; import { ALL_CHECK_IDS, CheckCommandError } from './report.js'; import { hasControlChars, isRefName, validateConfigString, InputError } from './validate.js'; @@ -56,14 +58,35 @@ export interface CheckSettings { const KNOWN_KEYS = new Set(['attribution', 'watch', 'flag', 'notForReading', 'deploy', 'skip']); const KNOWN_DEPLOY_KEYS = new Set(['branch', 'workflow']); -export function loadCheckSettings(mainRoot: string): CheckSettings { - let raw: unknown; +function readConfig(mainRoot: string): ReturnType { try { - raw = loadConfig(mainRoot).check; + return loadConfig(mainRoot); } catch (err) { throw new CheckCommandError('could not load configuration', err instanceof Error ? err.message : String(err)); } - return parseCheckSettings(raw, (keyPath) => findConfigSource(mainRoot, keyPath)); +} + +export function loadCheckSettings(mainRoot: string): CheckSettings { + return parseCheckSettings(readConfig(mainRoot).check, (keyPath) => findConfigSource(mainRoot, keyPath)); +} + +/** `cleanup.keepIgnored`, read through the same `keepPatterns()` `afx cleanup --keep-ignored` uses. */ +export function loadKeepIgnored(mainRoot: string): readonly string[] { + return parseKeepIgnored(readConfig(mainRoot).cleanup?.keepIgnored, findConfigSource(mainRoot, ['cleanup', 'keepIgnored'])); +} + +/** Pure validation of `cleanup.keepIgnored`; `source` names the file that set it. Undefined is the default list. */ +export function parseKeepIgnored(raw: unknown, source: string | null): readonly string[] { + const where = source ? ` (in ${source})` : ''; + let patterns: readonly string[]; + try { + patterns = keepPatterns(raw); + } catch { + throw new CheckCommandError(`cleanup.keepIgnored must be an array of non-empty glob strings${where}`); + } + const bad = patterns.find((p) => hasControlChars(p)); + if (bad !== undefined) throw new CheckCommandError(`cleanup.keepIgnored pattern ${JSON.stringify(bad)} contains a control character${where}`); + return patterns; } /** Pure validation; `sourceOf` names the file that set a key (for error messages). */ diff --git a/packages/codev/src/commands/check/worktree.ts b/packages/codev/src/commands/check/worktree.ts new file mode 100644 index 000000000..c55d0118b --- /dev/null +++ b/packages/codev/src/commands/check/worktree.ts @@ -0,0 +1,540 @@ +/** + * `codev check worktree ` (Spec 1951): would removing a builder's worktree + * and its local branch lose data, and, separately, is the builder finished. + * + * uncommitted staged, unstaged and untracked-not-ignored files (`status`, without optional + * locks); spawn's scaffold (`isBuilderScaffold`) is counted apart and is not data + * commits local commits on neither the live base tip nor the live remote branch tip, + * unless the PR is merged and the local tip is its merged head (squash or rebase) + * remote the local tip against `origin/`: context only + * pr the branch's PR: OPEN is attention ("builder not finished") + * ignored ignored files matching `cleanup.keepIgnored` that are not dependency or build + * output: the definitions `afx cleanup --keep-ignored` uses (`keep-list.ts`) + * + * The verdict word describes data only. The exit code also counts the lifecycle and anything + * that could not run, so "removable" never silently means "finished". The target is + * resolved against the main checkout, so the command reads the same from any worktree. + */ + +import { realpathSync } from 'node:fs'; +import { basename, dirname, isAbsolute, join, resolve } from 'node:path'; +import { isBuilderScaffold } from '../../agent-farm/lib/builder-scaffold.js'; +import { isNeverKeep } from '../../agent-farm/lib/keep-list.js'; +import { + ancestry, + ensureCommits, + failureReason, + gitVersion, + liveTip, + pathspecArgs, + remoteDefaultBranch, + type GitVersion, + type Lookup, +} from './git-facts.js'; +import { normalizeState, parsePrView } from './pr.js'; +import { defaultLabel, renderHuman, short } from './render.js'; +import { + check, + errorReport, + exitCodeOf, + fitList, + needsAttention, + notRun, + skipped, + verdictOf, + CheckCommandError, + type Check, + type CommandOptions, + type CommandResult, + type Removable, + type WorktreeReport, +} from './report.js'; +import { listWorktrees, resolveRoots, type Roots } from './roots.js'; +import { createRunner, type GitResult, type Runner } from './runner.js'; +import { loadCheckSettings, loadKeepIgnored } from './settings.js'; +import { hasControlChars, InputError, isFullSha, isRefName, validateBuilderId } from './validate.js'; + +/** Characters a file list may take on a check's line before it is cut to `… +N`. */ +const LIST_WIDTH = 72; + +function plural(n: number, word: string): string { + return `${n.toLocaleString('en-US')} ${word}${n === 1 ? '' : 's'}`; +} + +function splitNul(output: string): string[] { + return output.split('\0').filter((entry) => entry !== ''); +} + +// ============================================================================= +// The target +// ============================================================================= + +interface Target { + /** Real path. */ + path: string; + builderId: string | null; + branch: string; + /** The worktree's HEAD, which is its branch's tip. */ + tip: string; +} + +/** A real path for comparison (long names, on-disk case on Windows), or null when it does not exist. */ +function realPath(p: string): string | null { + try { + const real = realpathSync.native(p); + return process.platform === 'win32' ? real.toLowerCase() : real; + } catch { + return null; + } +} + +/** A builder id is a bare name; anything with a separator, or `.`/`..`, is a path. */ +function isPathArgument(raw: string): boolean { + return raw === '.' || raw === '..' || raw.includes('/') || raw.includes('\\') || isAbsolute(raw); +} + +/** The argument, validated before any subprocess runs. */ +type TargetArgument = { kind: 'id'; id: string } | { kind: 'path'; path: string }; + +export function parseTargetArgument(raw: string, cwd: string): TargetArgument { + if (raw.trim() === '') throw new InputError('no builder id or worktree path given'); + if (!isPathArgument(raw)) return { kind: 'id', id: validateBuilderId(raw) }; + if (hasControlChars(raw)) throw new InputError(`invalid worktree path ${JSON.stringify(raw)}: contains a control character`); + return { kind: 'path', path: resolve(cwd, raw) }; +} + +/** + * Resolve a builder id (`/.builders/`) or a path to a registered worktree that + * is not the main one. Anything else is exit 2. + */ +async function resolveTarget(runner: Runner, roots: Roots, argument: TargetArgument): Promise { + let builderId: string | null = null; + let wanted: string | null; + if (argument.kind === 'path') { + wanted = realPath(argument.path); + if (wanted === null) throw new CheckCommandError(`worktree not found: ${argument.path} does not exist`); + } else { + builderId = argument.id; + const dir = join(roots.mainRoot, '.builders', builderId); + wanted = realPath(dir); + if (wanted === null) throw new CheckCommandError(`builder ${builderId} not found: there is no worktree at ${dir}`); + } + + const [main, ...others] = await listWorktrees(runner); + if (wanted === realPath(main.path)) throw new CheckCommandError(`${main.path} is the main worktree, not a builder's`); + const entry = others.find((e) => realPath(e.path) === wanted); + if (!entry) throw new CheckCommandError(`${wanted} is not a registered worktree of ${roots.mainRoot} (git worktree list)`); + if (entry.branch === null) throw new CheckCommandError(`${entry.path} has a detached HEAD; check worktree judges a builder's branch`); + if (!isRefName(entry.branch)) throw new CheckCommandError(`${entry.path} is on branch ${JSON.stringify(entry.branch)}, which codev check cannot pass to git`); + if (entry.head === null || !isFullSha(entry.head)) throw new CheckCommandError(`git worktree list gave no commit for ${entry.path}`); + + if (builderId === null && dirname(entry.path) === join(main.path, '.builders')) builderId = basename(entry.path); + return { path: entry.path, builderId, branch: entry.branch, tip: entry.head }; +} + +// ============================================================================= +// Parsers +// ============================================================================= + +export interface StatusEntry { + path: string; + /** `modified`, `added`, `deleted`, `renamed`, `copied`, `type changed`, `conflicted` or `untracked`. */ + change: string; +} + +const CHANGE_WORDS: Record = { + M: 'modified', + A: 'added', + D: 'deleted', + R: 'renamed', + C: 'copied', + T: 'type changed', +}; + +function changeWord(xy: string): string { + if (xy === '??') return 'untracked'; + if (xy.includes('U') || xy === 'AA' || xy === 'DD') return 'conflicted'; + const letter = [...xy].find((c) => c !== ' ' && c !== '.'); + return (letter && CHANGE_WORDS[letter]) ?? 'changed'; +} + +/** Parse `status --porcelain=v1 -z`. A rename or copy carries its source as the next entry, which is dropped. */ +export function parseStatus(output: string): StatusEntry[] { + const tokens = splitNul(output); + const entries: StatusEntry[] = []; + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]; + if (token.length < 4 || token[2] !== ' ') throw new CheckCommandError(`unexpected git status output ${JSON.stringify(token.slice(0, 80))}`); + const xy = token.slice(0, 2); + entries.push({ path: token.slice(3), change: changeWord(xy) }); + if (xy.includes('R') || xy.includes('C')) i++; + } + return entries; +} + +/** + * The PR to judge the branch by, from `pr-search`: only exact head-branch matches, OPEN first, + * then the newest MERGED, then the newest CLOSED, then any whose state the search left blank. + * Null when there is none. + */ +export function pickPr(data: unknown, branch: string): Lookup { + if (!Array.isArray(data)) return { ok: false, reason: 'pr-search returned something other than a JSON array' }; + const rank: Record = { OPEN: 0, MERGED: 1, CLOSED: 2 }; + const candidates: Array<{ number: number; rank: number }> = []; + for (const [index, raw] of data.entries()) { + const where = `pr-search item ${index + 1}`; + if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return { ok: false, reason: `${where} is not an object` }; + const { number, headRefName, state } = raw as Record; + if (headRefName !== branch) continue; + if (typeof number !== 'number' || !Number.isSafeInteger(number) || number <= 0) return { ok: false, reason: `${where} has no valid number` }; + candidates.push({ number, rank: rank[typeof state === 'string' ? state.toUpperCase() : ''] ?? 3 }); + } + candidates.sort((a, b) => a.rank - b.rank || b.number - a.number); + return { ok: true, value: candidates[0]?.number ?? null }; +} + +// ============================================================================= +// What the checks share +// ============================================================================= + +interface BranchPr { + number: number; + state: string; + baseRef: string; + /** The forge's head SHA for the PR: the merged head when it is merged. */ + head: string; +} + +/** The PR found for the branch, none, or why its state is not available. */ +type PrLookup = { kind: 'found'; pr: BranchPr } | { kind: 'none' } | { kind: 'unavailable'; reason: string; number?: number }; + +async function lookupPr(runner: Runner, branch: string): Promise { + const search = await runner.forge('pr-search', { CODEV_SEARCH_QUERY: `head:${branch}` }); + if (!search.ok) return { kind: 'unavailable', reason: search.reason }; + const picked = pickPr(search.data, branch); + if (!picked.ok) return { kind: 'unavailable', reason: picked.reason }; + if (picked.value === null) return { kind: 'none' }; + const number = picked.value; + const outcome = await runner.forge('pr-view', { CODEV_PR_NUMBER: String(number) }); + const view = outcome.ok ? parsePrView(outcome.data) : { ok: false as const, reason: outcome.reason }; + if (!view.ok) return { kind: 'unavailable', reason: view.reason, number }; + if (view.value.state === null || view.value.state === '') return { kind: 'unavailable', reason: 'pr-view did not return state', number }; + const state = normalizeState(view.value.state, view.value.mergedAt); + return { kind: 'found', pr: { number, state, baseRef: view.value.baseRef, head: view.value.head } }; +} + +/** A tip read with `ls-remote` and made available locally, or why it is not. */ +type Tip = Lookup; + +interface Facts { + runner: Runner; + target: Target; + pr: PrLookup | null; + /** The base branch, or why there is none. */ + base: Lookup; + /** The live base tip; null when origin has no such branch. */ + baseTip: Tip; + /** The live `origin/` tip; null when origin has no such branch. */ + remoteTip: Tip; +} + +/** Each tip found is made available locally; one that cannot be is a failed lookup. */ +async function available(runner: Runner, tips: Tip[], version: GitVersion): Promise { + const shas = tips.flatMap((t) => (t.ok && t.value !== null ? [t.value] : [])); + const problems = shas.length > 0 ? await ensureCommits(runner, shas, version) : new Map(); + return tips.map((t) => { + if (!t.ok || t.value === null) return t; + const problem = problems.get(t.value); + return problem ? { ok: false, reason: problem } : t; + }); +} + +async function revList(runner: Runner, args: string[]): Promise> { + const result = await runner.git(['rev-list', ...args]); + if (result.exitCode !== 0) return { ok: false, reason: failureReason('rev-list', result, runner.timeoutLabel) }; + const shas = result.stdout.split('\n').map((l) => l.trim()).filter(Boolean); + const bad = shas.find((sha) => !isFullSha(sha)); + if (bad !== undefined) return { ok: false, reason: `unexpected git rev-list output: ${JSON.stringify(bad)} is not a commit SHA` }; + return { ok: true, value: shas }; +} + +/** Git in the inspected worktree, for the reads that are per worktree. */ +function gitIn(facts: Facts, args: string[]): Promise { + return facts.runner.git(['-C', facts.target.path, ...args]); +} + +// ============================================================================= +// The checks +// ============================================================================= + +async function checkUncommitted(facts: Facts): Promise { + const result = await gitIn(facts, ['--no-optional-locks', 'status', '--porcelain=v1', '-z', '--untracked-files=all']); + if (result.exitCode !== 0) return notRun('uncommitted', failureReason('status', result, facts.runner.timeoutLabel)); + const entries = parseStatus(result.stdout); + const isScaffold = (e: StatusEntry): boolean => e.change === 'untracked' && isBuilderScaffold(e.path); + const scaffold = entries.filter(isScaffold).map((e) => e.path).sort(); + const files = entries.filter((e) => !isScaffold(e)).sort((x, y) => (x.path < y.path ? -1 : x.path > y.path ? 1 : 0)); + const note = scaffold.length > 0 ? ` [${plural(scaffold.length, 'scaffold file')} not counted]` : ''; + const details = { files, scaffold }; + if (files.length === 0) return check('uncommitted', 'ok', `nothing uncommitted${note}`, details); + const list = fitList(files.map((f) => `${f.path} (${f.change})`), LIST_WIDTH); + return check('uncommitted', 'attention', `${plural(files.length, 'file')}: ${list}${note}`, details); +} + +/** Why the base cannot be judged against, or null when it can. */ +function baseProblem(facts: Facts): string | null { + if (!facts.base.ok) return facts.base.reason; + if (!facts.baseTip.ok) return facts.baseTip.reason; + return facts.baseTip.value === null ? `origin has no branch ${facts.base.value}` : null; +} + +async function checkCommits(facts: Facts): Promise { + const problem = baseProblem(facts); + if (problem !== null) return notRun('commits', `base not read: ${problem}`); + const base = facts.base.ok ? facts.base.value : ''; + const baseTip = facts.baseTip.ok ? (facts.baseTip.value as string) : ''; + const { tip, branch } = facts.target; + + const notOnBase = await revList(facts.runner, [tip, '--not', baseTip]); + if (!notOnBase.ok) return notRun('commits', notOnBase.reason); + const total = notOnBase.value.length; + if (total === 0) return check('commits', 'ok', `every commit is on origin/${base}`, { total, notOnBase: [], unsafe: [] }); + + const remote = facts.remoteTip; + const merged = facts.pr?.kind === 'found' && facts.pr.pr.state === 'MERGED' ? facts.pr.pr : null; + let unsafe = notOnBase.value; + if (remote.ok && remote.value !== null) { + const off = await revList(facts.runner, [tip, '--not', baseTip, remote.value]); + if (!off.ok) return notRun('commits', off.reason); + unsafe = off.value; + } + const details = { total, notOnBase: notOnBase.value, unsafe }; + const commits = plural(total, 'commit'); + if (unsafe.length > 0 && merged !== null && merged.head === tip) { + return check('commits', 'ok', `${commits} not on origin/${base}; the local tip is PR #${merged.number}'s merged head (squash or rebase merge)`, { + ...details, + unsafe: [], + }); + } + if (unsafe.length === 0) return check('commits', 'ok', `${commits} not on origin/${base}, all on origin/${branch}`, details); + const remoteNote = remote.ok ? '' : ` (origin/${branch} not read: ${remote.reason})`; + const listed = fitList(unsafe.map(short), LIST_WIDTH); + return check('commits', 'attention', `${plural(unsafe.length, 'commit')} on no remote branch: ${listed}${remoteNote}`, details); +} + +async function checkRemote(facts: Facts): Promise { + const { branch, tip } = facts.target; + const remote = facts.remoteTip; + if (!remote.ok) return notRun('remote', remote.reason); + if (remote.value === null) return check('remote', 'info', `origin has no branch ${branch}`, { remoteSha: null, relation: 'absent' }); + const remoteSha = remote.value; + if (remoteSha === tip) return check('remote', 'ok', `origin/${branch} matches local (${short(tip)})`, { remoteSha, relation: 'matches' }); + const remoteInLocal = await ancestry(facts.runner, remoteSha, tip); + if (!remoteInLocal.ok) return notRun('remote', remoteInLocal.reason, { remoteSha }); + const localInRemote = await ancestry(facts.runner, tip, remoteSha); + if (!localInRemote.ok) return notRun('remote', localInRemote.reason, { remoteSha }); + const relation = remoteInLocal.value ? 'ahead' : localInRemote.value ? 'behind' : 'diverged'; + const words = { + ahead: `local ${short(tip)} is ahead of origin/${branch} @ ${short(remoteSha)} (not pushed)`, + behind: `local ${short(tip)} is behind origin/${branch} @ ${short(remoteSha)}`, + diverged: `local ${short(tip)} and origin/${branch} @ ${short(remoteSha)} have diverged`, + }[relation]; + return check('remote', 'info', words, { remoteSha, relation }); +} + +function checkPrState(lookup: PrLookup, branch: string): Check { + if (lookup.kind === 'unavailable') { + return notRun('pr', `PR state not available: ${lookup.reason}`, lookup.number === undefined ? {} : { number: lookup.number }); + } + if (lookup.kind === 'none') return check('pr', 'attention', `no PR found for ${branch}`, {}); + const { number, state, head } = lookup.pr; + if (state === 'MERGED') return check('pr', 'ok', `#${number} MERGED`, { number, state, mergedHead: head }); + if (state === 'CLOSED') return check('pr', 'ok', `#${number} CLOSED without merging`, { number, state }); + if (state === 'OPEN') return check('pr', 'attention', `#${number} OPEN: builder not finished`, { number, state }); + return check('pr', 'attention', `#${number} ${state}`, { number, state }); +} + +async function checkIgnored(facts: Facts, patterns: readonly string[]): Promise { + let keep: string[] = []; + const pathspecs = pathspecArgs({ include: patterns }); + if (pathspecs !== null) { + const result = await gitIn(facts, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z', ...pathspecs]); + if (result.exitCode !== 0) return notRun('ignored', failureReason('ls-files', result, facts.runner.timeoutLabel)); + keep = splitNul(result.stdout).filter((p) => !isNeverKeep(p)).sort(); + } + const all = await gitIn(facts, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z']); + if (all.exitCode !== 0) return notRun('ignored', failureReason('ls-files', all, facts.runner.timeoutLabel)); + // Every other ignored path, directories collapsed, is treated as regenerable. + const holdsKept = (entry: string): boolean => keep.some((k) => k === entry || (entry.endsWith('/') && k.startsWith(entry))); + const others = splitNul(all.stdout).filter((entry) => !holdsKept(entry)).sort(); + const details = { keep, regenerable: others.length }; + const examples = others.length > 0 ? `: ${fitList(others, 40)}` : ''; + + if (keep.length === 0) { + const none = patterns.length === 0 ? 'no keep list (cleanup.keepIgnored is empty)' : 'no keep-list files'; + const rest = others.length === 0 ? 'no other ignored files' : `${plural(others.length, 'ignored path')} treated as regenerable${examples}`; + return check('ignored', 'ok', `${none}; ${rest}`, details); + } + const lines = [`${plural(keep.length, 'keep-list file')} would be lost: ${fitList(keep, LIST_WIDTH)}`]; + if (others.length > 0) lines.push(`(${plural(others.length, 'other ignored path')} treated as regenerable${examples})`); + lines.push('→ copy them out first, or use `afx cleanup --keep-ignored`'); + return check('ignored', 'attention', lines.join('\n'), details); +} + +// ============================================================================= +// The verdict +// ============================================================================= + +/** + * Data only. A data check that could not run makes the verdict conservative: NOT REMOVABLE, + * except `commits` when the local tip is on the live remote branch, which keeps every commit. + */ +export function removability(checks: readonly Check[], localOnRemote: boolean): Removable { + const status = (id: string): Check['status'] | undefined => checks.find((c) => c.id === id)?.status; + const uncommitted = status('uncommitted'); + const commits = status('commits'); + if (uncommitted === 'attention' || uncommitted === 'not-run' || status('ignored') === 'not-run') return 'not-removable'; + if (commits === 'attention' || (commits === 'not-run' && !localOnRemote)) return 'not-removable'; + return status('ignored') === 'attention' ? 'removable-after-keeping' : 'removable'; +} + +/** Whether the local tip is reachable from the live remote branch tip. */ +async function onRemote(facts: Facts): Promise { + const remote = facts.remoteTip; + if (!remote.ok || remote.value === null) return false; + const answer = await ancestry(facts.runner, facts.target.tip, remote.value); + return answer.ok && answer.value; +} + +// ============================================================================= +// The command +// ============================================================================= + +async function buildWorktreeReport(argument: TargetArgument, options: CommandOptions): Promise { + const runnerOptions = { timeoutMs: options.timeoutMs, env: options.env, spawn: options.spawn }; + const roots = await resolveRoots(createRunner({ cwd: options.cwd, workspaceRoot: options.cwd, ...runnerOptions })); + const runner = createRunner({ cwd: roots.mainRoot, workspaceRoot: roots.mainRoot, ...runnerOptions }); + const settings = loadCheckSettings(roots.mainRoot); + const patterns = loadKeepIgnored(roots.mainRoot); + const target = await resolveTarget(runner, roots, argument); + const skip = (id: string): boolean => settings.skip.has(id); + + // The PR decides the base; without one (or with `pr` skipped), origin's default branch does. + const pr = skip('pr') ? null : await lookupPr(runner, target.branch); + let base: Lookup; + if (pr?.kind === 'found') { + base = { ok: true, value: pr.pr.baseRef }; + } else { + const fallback = await remoteDefaultBranch(runner); + if (!fallback.ok) base = fallback; + else if (fallback.value === null) base = { ok: false, reason: 'no PR names a base, and origin does not name a default branch' }; + else base = { ok: true, value: fallback.value }; + } + + const needBase = !skip('commits'); + const needRemote = !skip('commits') || !skip('remote'); + const version = await gitVersion(runner); + const [baseTip, remoteTip] = await available( + runner, + [ + needBase && base.ok ? await liveTip(runner, base.value) : { ok: true, value: null }, + needRemote ? await liveTip(runner, target.branch) : { ok: true, value: null }, + ], + version, + ); + const facts: Facts = { runner, target, pr, base, baseTip, remoteTip }; + + const run = async (id: string, fn: () => Check | Promise): Promise => (skip(id) ? skipped(id) : fn()); + const checks = [ + await run('uncommitted', () => checkUncommitted(facts)), + await run('commits', () => checkCommits(facts)), + await run('remote', () => checkRemote(facts)), + await run('pr', () => checkPrState(pr as PrLookup, target.branch)), + await run('ignored', () => checkIgnored(facts, patterns)), + ]; + const commitsNotRun = checks.some((c) => c.id === 'commits' && c.status === 'not-run'); + const removable = removability(checks, commitsNotRun ? await onRemote(facts) : false); + + return { + schema: 1, + command: 'worktree', + verdict: verdictOf(checks), + generatedAt: new Date().toISOString(), + removable, + worktree: { + path: target.path, + builderId: target.builderId, + branch: target.branch, + baseRef: base.ok ? base.value : null, + baseTip: needBase && baseTip.ok ? baseTip.value : null, + }, + checks, + }; +} + +/** `codev check worktree `. Never throws: a failure that prevents a report is exit 2 with an `ErrorReport`. */ +export async function checkWorktree(raw: string, options: CommandOptions): Promise> { + try { + const report = await buildWorktreeReport(parseTargetArgument(raw, options.cwd), options); + return { report, exitCode: exitCodeOf(report.verdict) }; + } catch (err) { + return { report: errorReport('worktree', err), exitCode: 2 }; + } +} + +// ============================================================================= +// Human form +// ============================================================================= + +const VERDICT_WORDS: Record string> = { + removable: () => 'REMOVABLE', + 'removable-after-keeping': (keep) => `REMOVABLE AFTER KEEPING ${plural(keep, 'file').toUpperCase()}`, + 'not-removable': () => 'NOT REMOVABLE', +}; + +/** + * What a check needing attention means, in a few words for the verdict line. Keep-list files + * are left out: the verdict word, or the data that blocks removal anyway, already says it. + */ +function reasonWords(c: Check): string | null { + if (c.status === 'not-run') return `${defaultLabel(c.id)} not run`; + const d = c.details; + switch (c.id) { + case 'uncommitted': + return `${plural((d.files as unknown[]).length, 'uncommitted file')}`; + case 'commits': + return `${plural((d.unsafe as unknown[]).length, 'unpushed commit')}`; + case 'ignored': + return null; + case 'pr': + if (d.number === undefined) return 'no PR found'; + return d.state === 'OPEN' ? `PR #${String(d.number)} open: builder not finished` : `PR #${String(d.number)} ${String(d.state)}`; + default: + return defaultLabel(c.id); + } +} + +export function renderWorktreeHuman(report: WorktreeReport): string { + const { worktree } = report; + // A builder's worktree reads by its place under the main checkout; any other by its path. + const where = worktree.builderId === null ? worktree.path : `.builders/${worktree.builderId}`; + const name = worktree.builderId ?? worktree.path; + const keep = report.checks.find((c) => c.id === 'ignored'); + const keepCount = Array.isArray(keep?.details.keep) ? keep.details.keep.length : 0; + const reasons = report.checks + .filter(needsAttention) + .map(reasonWords) + .filter((r): r is string => r !== null); + const verdictLine = `${VERDICT_WORDS[report.removable](keepCount)} ${name}${reasons.length > 0 ? ` — ${reasons.join(', ')}` : ''}`; + const base = + worktree.baseRef === null + ? 'base not read' + : worktree.baseTip === null + ? `base ${worktree.baseRef} (live tip not read)` + : `base ${worktree.baseRef} @ ${short(worktree.baseTip)} (origin, live)`; + return renderHuman({ + verdictLine, + header: [`worktree ${where} branch ${worktree.branch} ${base}`], + sections: [{ checks: report.checks }], + }); +} From 7f583ac358b14dac01298c9e154bc043fb0e0ee7 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 19:03:45 -0800 Subject: [PATCH 67/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 8fe1165a1..2f78a7810 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: readonly_core @@ -90,7 +90,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T02:33:21.252Z' +updated_at: '2026-11-24T03:03:45.217Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From dd21e15ce59c489dcc496e22eb5c2d213104ac35 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 19:13:13 -0800 Subject: [PATCH 68/94] [Spec 1951][Phase: check_worktree] fix: review iteration 1 - ignored: a keep-list match that is a symbolic link is listed apart (details.links), not as a keep file: afx cleanup --keep-ignored never copies a link, and a link holds no file data of its own. A failed lstat makes the check not run. - commits: when origin/ cannot be read and commits are off the base, the check is not run, rather than calling them unpushed. - A skipped `ignored` no longer reads cleanup.keepIgnored; with `commits` skipped the header names the base without a tip remark; no cast for the skipped `pr` check. - Tests for each (symlink cases POSIX only), and the rebuttal. --- .../1951-check_worktree-iter1-rebuttals.md | 57 +++++++++++++ codev/state/spir-1951_thread.md | 16 ++++ .../check/__tests__/check-worktree.test.ts | 85 ++++++++++++++++++- .../check/__tests__/helpers/report-shape.ts | 2 +- packages/codev/src/commands/check/worktree.ts | 60 +++++++++---- 5 files changed, 202 insertions(+), 18 deletions(-) create mode 100644 codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter1-rebuttals.md diff --git a/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter1-rebuttals.md b/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter1-rebuttals.md new file mode 100644 index 000000000..389b302dd --- /dev/null +++ b/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter1-rebuttals.md @@ -0,0 +1,57 @@ +# Phase 6 (`check_worktree`) — iteration 1 rebuttal + +Codex: REQUEST_CHANGES. Claude: APPROVE with six non-blocking notes. + +## Codex — keep-list symlinks (accepted, fixed) + +> `worktree.ts` includes ignored symlinks in `details.keep` and advises using +> `afx cleanup --keep-ignored`. However, `keepFiles()` explicitly skips symlinks … + +Correct. Verified against #1950's code: `keepFiles()` skips every `lstat` symbolic link and +cleanup logs `Not kept (symlinks): …`. `check worktree` counted such a link as a keep file, so +its `REMOVABLE AFTER KEEPING N FILES` and the `--keep-ignored` hint promised something cleanup +does not do. + +Fixed: + +- `ignored` splits the keep-list matches by `lstat`. Links go to a new `details.links` list. + They are not keep files and not data: a link holds no file contents of its own, and a target + inside the worktree is judged as itself. They are printed on their own line ("N keep-list + symlinks not counted (cleanup never copies a link)"), so nothing is lost unseen, and they do + not count as regenerable. +- An `lstat` that fails makes `ignored` `not run`, which makes the verdict NOT REMOVABLE. +- Tests (POSIX; a symlink needs privileges on Windows): two keep-list links next to keep files. + `keep` equals the ignored part of `listKeepCandidates()` with links removed, which is what + `keepFiles()` copies, and `links` equals the removed part. Links alone leave the worktree + REMOVABLE. + +Codex's second line says it could not run vitest in its read-only sandbox. Nothing to change. + +## Claude's non-blocking notes + +1. **`regenerable` undercounts inside a collapsed directory that holds keep files.** Accepted + as a known approximation, not changed. The count is of ignored paths with directories + collapsed, which is what keeps the command fast next to a large `node_modules/`. Counting + inside a kept directory would need a second uncollapsed listing. The Phase 7 docs will say + what the number counts. +2. **Nested-repo `dir/` entries are reported unexpanded.** Accepted, documented rather than + changed. Expanding them needs a directory walk that the audited read-only import list does + not include. Phase 7 docs get one line, and the REVIEW records it. +3. **"live tip not read" when `commits` is skipped.** Fixed. With `commits` skipped the header + reads `base main` with no tip remark. Tested. +4. **`loadKeepIgnored()` runs when `ignored` is skipped.** Fixed, for consistency with "a + skipped check reads nothing of its own". The skip test now carries an invalid keep list + that no longer fails the run. +5. **"N unpushed commits" when the remote read failed.** Fixed, by making the check truthful + rather than only the verdict line. When `origin/` cannot be read and commits are not + on the base, `commits` is `not run` ("… could not be read to check them: "). The + verdict stays conservative (NOT REMOVABLE, because the local tip cannot be shown to be on + the remote branch), and the verdict line says `commits not run`. Tested with an injected + `ls-remote` failure. +6. **`checkPrState(pr as PrLookup, …)` relies on the skip short-circuit.** Fixed: the `pr` + check is `pr === null ? skipped('pr') : checkPrState(pr, …)`, with no cast. + +## Not on the read-only core + +None of this touches the Phase 2 core: the runner, the allow-list, validation and roots are +unchanged. The changes are in `worktree.ts`, its tests and the report-shape helper. diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index eb796f51b..983dc3b74 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -290,3 +290,19 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals uncommitted = this phase's uncommitted work, 2 unpushed = the merge + fold-in commits, PR #1958 OPEN); `air-1938` → REMOVABLE, exit 0 (#1939 MERGED, 1 commit after the merge on its remote branch); `bugfix-1956` → REMOVABLE AFTER KEEPING 2 FILES (two porch review .txt), PR #1965 OPEN, exit 1. +- Architect (2026-11-24 03:03): confirmed 8/8 green at b6f7d4d74; ran check worktree themselves from the main + checkout on air-1938 (REMOVABLE, exit 0), bugfix-1956 (REMOVABLE AFTER KEEPING 2 FILES, PR open), bugfix-1901 + (REMOVABLE, no PR found, exit 1) and pir-1620 (REMOVABLE, PR #1203 open, 70 commits all on origin): all match the + spec incl. 20a, no ref changed. The -uall finding was exactly the main-36 evidence. Skip applied once for + build-complete (config.local.json restored, cmp identical), noted in the PR body. Review round iter1 started. + For Phase 7 the architect asks: guidance shows the three commands at the moments they are used — check pr before + recommending a gate, check deploy after merges, check worktree before cleanup — and says plainly that REMOVABLE + means no data would be lost, not that the builder is finished. +- Review iter1: codex REQUEST_CHANGES — keep-list SYMLINKS counted as keep files, but keepFiles() skips every link + (cleanup logs "Not kept (symlinks)"), so the verdict and the --keep-ignored hint over-promised. Verified, fixed: + `ignored` details gain `links` (keep-list matches that are symlinks: listed on their own line, not keep, not data, + not regenerable); a failed lstat → ignored not run. Claude APPROVE with 6 notes; fixed 3 (header when commits + skipped; keepIgnored not loaded when ignored skipped; no `as PrLookup` cast) and 5 differently than suggested: + a remote-branch read failure with commits off the base now makes `commits` NOT RUN (truthful) rather than + "unpushed". Notes 1 (regenerable approximation in collapsed dirs) and 2 (nested-repo dir/ entries) → Phase 7 + docs + REVIEW. Not on the read-only core. Targeted 910/910 (29 files), build, both tsc, tmp-residue OK. diff --git a/packages/codev/src/commands/check/__tests__/check-worktree.test.ts b/packages/codev/src/commands/check/__tests__/check-worktree.test.ts index 5af55430a..397ba40e6 100644 --- a/packages/codev/src/commands/check/__tests__/check-worktree.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-worktree.test.ts @@ -8,6 +8,7 @@ * stub-PATH audit of every git call is in check-worktree-stubs.test.ts (POSIX). */ +import { spawn as realSpawn } from 'node:child_process'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; @@ -34,6 +35,7 @@ import { } from './helpers/worktree-fixture.js'; const s = (sha: string): string => sha.slice(0, 7); +const isWindows = process.platform === 'win32'; describe('Spec 1951 — check worktree: parsers and the verdict rule', () => { it('parseStatus: change words, a rename with its source, and conflicts', () => { @@ -359,6 +361,51 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, expect(cleanupKeeps).toEqual(['codev/projects/8-x/8-specify-iter1-codex.txt', 'tmp/notes.md']); }); + // keepFiles() skips every symlink it is handed ("Not kept (symlinks)"), so check worktree + // must not count one as a file cleanup would keep. Symlinks need privileges on Windows. + it.skipIf(isWindows)('a keep-list symlink is listed apart: not a keep file, not data, as cleanup never copies it', async () => { + configure(); + const b = withIgnored(); + fs.symlinkSync('notes.md', path.join(b.dir, 'tmp/link.md')); + fs.symlinkSync(path.join(fx.root, 'outside-secret'), path.join(b.dir, 'tmp/env')); + const saved = { ...process.env }; + Object.assign(process.env, fx.env); + let candidates: string[]; + try { + const untracked = listKeepCandidates(b.dir, []).files; + candidates = listKeepCandidates(b.dir, DEFAULT_KEEP_IGNORED).files.filter((f) => !untracked.includes(f)); + } finally { + for (const key of Object.keys(fx.env)) { + if (saved[key] === undefined) delete process.env[key]; + else process.env[key] = saved[key]; + } + } + const isLink = (f: string): boolean => fs.lstatSync(path.join(b.dir, f)).isSymbolicLink(); + + const { report } = await runReport('spir-8', { inspected: b.dir }); + + const ignored = byId(report, 'ignored'); + expect(ignored.details).toEqual({ keep: candidates.filter((f) => !isLink(f)), regenerable: 3, links: candidates.filter(isLink) }); + expect(ignored.details.links).toEqual(['tmp/env', 'tmp/link.md']); + expect(report.removable).toBe('removable-after-keeping'); + expect(ignored.summary).toContain('2 keep-list symlinks not counted (cleanup never copies a link): tmp/env, tmp/link.md'); + }); + + it.skipIf(isWindows)('keep-list symlinks alone leave it REMOVABLE', async () => { + configure({ cleanup: { keepIgnored: ['tmp/**'] } }); + const b = addBuilder(fx, 'spir-8'); + fs.mkdirSync(path.join(b.dir, 'tmp')); + fs.symlinkSync(path.join(fx.root, 'elsewhere'), path.join(b.dir, 'tmp/link')); + mergeBuilder(fx, b); + prIs(b, 8, 'MERGED'); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + + expect(exitCode).toBe(0); + expect(report.removable).toBe('removable'); + expect(byId(report, 'ignored')).toMatchObject({ status: 'ok', details: { keep: [], links: ['tmp/link'] } }); + }); + it('cleanup.keepIgnored [] reports no keep files: REMOVABLE', async () => { configure({ cleanup: { keepIgnored: [] } }); const b = withIgnored(); @@ -380,7 +427,7 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, const { report } = await runReport('spir-8', { inspected: b.dir }); - expect(byId(report, 'ignored').details).toEqual({ keep: ['debug.log'], regenerable: 4 }); + expect(byId(report, 'ignored').details).toEqual({ keep: ['debug.log'], regenerable: 4, links: [] }); }); }); @@ -468,7 +515,8 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, }); it('check.skip ["pr", "ignored"]: both skip by name, the forge is never asked, the base is origin\'s default', async () => { - configure({ check: { skip: ['pr', 'ignored'] } }); + // A skipped check reads nothing of its own: an invalid keep list does not fail the run. + configure({ check: { skip: ['pr', 'ignored'] }, cleanup: { keepIgnored: 'not a list' } }); const b = addBuilder(fx, 'spir-8'); const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); @@ -481,6 +529,39 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, expect(report.worktree.baseRef).toBe('main'); }); + it('check.skip ["commits"]: the base tip is never read, and the header says only the base', async () => { + configure({ check: { skip: ['commits'] } }); + const b = addBuilder(fx, 'spir-8'); + prIs(b, 8, 'OPEN'); + + const { report } = await runReport('spir-8', { inspected: b.dir }); + + expect(report.worktree).toMatchObject({ baseRef: 'main', baseTip: null }); + expect(renderWorktreeHuman(report).split('\n')[2]).toBe('worktree .builders/spir-8 branch builder/spir-8 base main'); + }); + + it('a remote branch that cannot be read: commits not on the base are not run, never called unpushed', async () => { + configure(); + const b = addBuilder(fx, 'spir-8'); + prIs(b, 8, 'OPEN'); + const failBranchRead: SpawnFn = (command, args, options) => + args.includes('ls-remote') && args.includes(`refs/heads/${b.branch}`) + ? realSpawn(process.execPath, ['-e', 'process.stderr.write("fatal: simulated failure\\n"); process.exit(128)'], options) + : realSpawn(command, args, options); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir, spawn: failBranchRead }); + + expect(exitCode).toBe(1); + expect(byId(report, 'commits')).toMatchObject({ + status: 'not-run', + reason: '1 commit not on origin/main, and origin/builder/spir-8 could not be read to check them: ls-remote failed: fatal: simulated failure', + details: { total: 1, notOnBase: [b.head] }, + }); + expect(byId(report, 'remote')).toMatchObject({ status: 'not-run', reason: 'ls-remote failed: fatal: simulated failure' }); + expect(report.removable).toBe('not-removable'); + expect(renderWorktreeHuman(report).split('\n')[0]).toBe('NOT REMOVABLE spir-8 — commits not run, remote not run, PR #8 open: builder not finished'); + }); + it('run from inside another builder worktree, or given as a path, it resolves the same target', async () => { configure(); const b = addBuilder(fx, 'spir-8'); diff --git a/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts b/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts index 425e7e99d..678fff65b 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts @@ -129,7 +129,7 @@ export function expectWorktreeReportShape(report: WorktreeReport): void { expect(['matches', 'ahead', 'behind', 'diverged', 'absent']).toContain(c.details.relation); } if (c.id === 'pr' && 'mergedHead' in c.details) expect(c.details.mergedHead).toMatch(SHA); - if (c.id === 'ignored') expect(c.details).toEqual({ keep: expect.any(Array), regenerable: expect.any(Number) }); + if (c.id === 'ignored') expect(c.details).toEqual({ keep: expect.any(Array), regenerable: expect.any(Number), links: expect.any(Array) }); } const attention = parsed.checks.some((c) => c.status === 'attention' || c.status === 'not-run'); expect(parsed.verdict).toBe(attention ? 'attention' : 'clear'); diff --git a/packages/codev/src/commands/check/worktree.ts b/packages/codev/src/commands/check/worktree.ts index c55d0118b..de9cb2ebf 100644 --- a/packages/codev/src/commands/check/worktree.ts +++ b/packages/codev/src/commands/check/worktree.ts @@ -9,14 +9,17 @@ * remote the local tip against `origin/`: context only * pr the branch's PR: OPEN is attention ("builder not finished") * ignored ignored files matching `cleanup.keepIgnored` that are not dependency or build - * output: the definitions `afx cleanup --keep-ignored` uses (`keep-list.ts`) + * output: the definitions `afx cleanup --keep-ignored` uses (`keep-list.ts`). + * A symbolic link among them is listed apart: cleanup never copies a link, and a + * link holds no file data of its own (a target inside the worktree is judged + * as itself) * * The verdict word describes data only. The exit code also counts the lifecycle and anything * that could not run, so "removable" never silently means "finished". The target is * resolved against the main checkout, so the command reads the same from any worktree. */ -import { realpathSync } from 'node:fs'; +import { lstatSync, realpathSync } from 'node:fs'; import { basename, dirname, isAbsolute, join, resolve } from 'node:path'; import { isBuilderScaffold } from '../../agent-farm/lib/builder-scaffold.js'; import { isNeverKeep } from '../../agent-farm/lib/keep-list.js'; @@ -317,9 +320,15 @@ async function checkCommits(facts: Facts): Promise { }); } if (unsafe.length === 0) return check('commits', 'ok', `${commits} not on origin/${base}, all on origin/${branch}`, details); - const remoteNote = remote.ok ? '' : ` (origin/${branch} not read: ${remote.reason})`; + // Without the remote branch's tip, whether these commits were pushed cannot be told. + if (!remote.ok) { + return notRun('commits', `${commits} not on origin/${base}, and origin/${branch} could not be read to check them: ${remote.reason}`, { + total, + notOnBase: notOnBase.value, + }); + } const listed = fitList(unsafe.map(short), LIST_WIDTH); - return check('commits', 'attention', `${plural(unsafe.length, 'commit')} on no remote branch: ${listed}${remoteNote}`, details); + return check('commits', 'attention', `${plural(unsafe.length, 'commit')} on no remote branch: ${listed}`, details); } async function checkRemote(facts: Facts): Promise { @@ -355,28 +364,44 @@ function checkPrState(lookup: PrLookup, branch: string): Check { } async function checkIgnored(facts: Facts, patterns: readonly string[]): Promise { - let keep: string[] = []; + const keep: string[] = []; + const links: string[] = []; const pathspecs = pathspecArgs({ include: patterns }); if (pathspecs !== null) { const result = await gitIn(facts, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z', ...pathspecs]); if (result.exitCode !== 0) return notRun('ignored', failureReason('ls-files', result, facts.runner.timeoutLabel)); - keep = splitNul(result.stdout).filter((p) => !isNeverKeep(p)).sort(); + const matched = splitNul(result.stdout).filter((p) => !isNeverKeep(p)); + for (const p of matched) { + let isLink: boolean; + try { + isLink = lstatSync(join(facts.target.path, p)).isSymbolicLink(); + } catch (err) { + return notRun('ignored', `could not read ${p}: ${err instanceof Error ? err.message : String(err)}`); + } + (isLink ? links : keep).push(p); + } + keep.sort(); + links.sort(); } const all = await gitIn(facts, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z']); if (all.exitCode !== 0) return notRun('ignored', failureReason('ls-files', all, facts.runner.timeoutLabel)); // Every other ignored path, directories collapsed, is treated as regenerable. - const holdsKept = (entry: string): boolean => keep.some((k) => k === entry || (entry.endsWith('/') && k.startsWith(entry))); - const others = splitNul(all.stdout).filter((entry) => !holdsKept(entry)).sort(); - const details = { keep, regenerable: others.length }; + const matchedAll = [...keep, ...links]; + const holdsMatch = (entry: string): boolean => matchedAll.some((k) => k === entry || (entry.endsWith('/') && k.startsWith(entry))); + const others = splitNul(all.stdout).filter((entry) => !holdsMatch(entry)).sort(); + const details = { keep, regenerable: others.length, links }; const examples = others.length > 0 ? `: ${fitList(others, 40)}` : ''; + const linkLine = + links.length > 0 ? `${plural(links.length, 'keep-list symlink')} not counted (cleanup never copies a link): ${fitList(links, LIST_WIDTH)}` : null; if (keep.length === 0) { const none = patterns.length === 0 ? 'no keep list (cleanup.keepIgnored is empty)' : 'no keep-list files'; const rest = others.length === 0 ? 'no other ignored files' : `${plural(others.length, 'ignored path')} treated as regenerable${examples}`; - return check('ignored', 'ok', `${none}; ${rest}`, details); + return check('ignored', 'ok', [`${none}; ${rest}`, ...(linkLine ? [linkLine] : [])].join('\n'), details); } const lines = [`${plural(keep.length, 'keep-list file')} would be lost: ${fitList(keep, LIST_WIDTH)}`]; if (others.length > 0) lines.push(`(${plural(others.length, 'other ignored path')} treated as regenerable${examples})`); + if (linkLine) lines.push(linkLine); lines.push('→ copy them out first, or use `afx cleanup --keep-ignored`'); return check('ignored', 'attention', lines.join('\n'), details); } @@ -415,9 +440,10 @@ async function buildWorktreeReport(argument: TargetArgument, options: CommandOpt const roots = await resolveRoots(createRunner({ cwd: options.cwd, workspaceRoot: options.cwd, ...runnerOptions })); const runner = createRunner({ cwd: roots.mainRoot, workspaceRoot: roots.mainRoot, ...runnerOptions }); const settings = loadCheckSettings(roots.mainRoot); - const patterns = loadKeepIgnored(roots.mainRoot); const target = await resolveTarget(runner, roots, argument); const skip = (id: string): boolean => settings.skip.has(id); + // A skipped check reads nothing of its own, its configuration included. + const patterns = skip('ignored') ? [] : loadKeepIgnored(roots.mainRoot); // The PR decides the base; without one (or with `pr` skipped), origin's default branch does. const pr = skip('pr') ? null : await lookupPr(runner, target.branch); @@ -449,7 +475,7 @@ async function buildWorktreeReport(argument: TargetArgument, options: CommandOpt await run('uncommitted', () => checkUncommitted(facts)), await run('commits', () => checkCommits(facts)), await run('remote', () => checkRemote(facts)), - await run('pr', () => checkPrState(pr as PrLookup, target.branch)), + pr === null ? skipped('pr') : checkPrState(pr, target.branch), await run('ignored', () => checkIgnored(facts, patterns)), ]; const commitsNotRun = checks.some((c) => c.id === 'commits' && c.status === 'not-run'); @@ -526,12 +552,16 @@ export function renderWorktreeHuman(report: WorktreeReport): string { .map(reasonWords) .filter((r): r is string => r !== null); const verdictLine = `${VERDICT_WORDS[report.removable](keepCount)} ${name}${reasons.length > 0 ? ` — ${reasons.join(', ')}` : ''}`; + // With `commits` skipped the base tip is never read, so there is nothing to say about it. + const tipSkipped = report.checks.some((c) => c.id === 'commits' && c.status === 'skip'); const base = worktree.baseRef === null ? 'base not read' - : worktree.baseTip === null - ? `base ${worktree.baseRef} (live tip not read)` - : `base ${worktree.baseRef} @ ${short(worktree.baseTip)} (origin, live)`; + : worktree.baseTip !== null + ? `base ${worktree.baseRef} @ ${short(worktree.baseTip)} (origin, live)` + : tipSkipped + ? `base ${worktree.baseRef}` + : `base ${worktree.baseRef} (live tip not read)`; return renderHuman({ verdictLine, header: [`worktree ${where} branch ${worktree.branch} ${base}`], From 95ae544b5497720010172d118b86a4a2f728e722 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 19:18:25 -0800 Subject: [PATCH 69/94] chore(porch): 1951 implement re-iter (iter 2) --- .../status.yaml | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 2f78a7810..4a5357ead 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -38,8 +38,8 @@ gates: status: pending verify-approval: status: pending -iteration: 1 -build_complete: true +iteration: 2 +build_complete: false history: - iteration: 1 plan_phase: readonly_core @@ -89,8 +89,20 @@ history: verdict: APPROVE file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_pr_forge-iter1-claude.txt + - iteration: 1 + plan_phase: check_worktree + build_output: '' + reviews: + - model: codex + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter1-codex.txt + - model: claude + verdict: APPROVE + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T03:03:45.217Z' +updated_at: '2026-11-24T03:18:24.966Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From 161f5838d0bfc10ecc84218397d452467a63fa9f Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 19:23:25 -0800 Subject: [PATCH 70/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 4a5357ead..1c841335e 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 2 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: readonly_core @@ -102,7 +102,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T03:18:24.966Z' +updated_at: '2026-11-24T03:23:25.595Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From a56bf9a37af8e1e30c00d5a9b8e53f5c001bb014 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Mon, 23 Nov 2026 19:40:23 -0800 Subject: [PATCH 71/94] =?UTF-8?q?[Spec=201951][Phase:=20check=5Fworktree]?= =?UTF-8?q?=20fix:=20review=20iteration=202=20=E2=80=94=20keep-list=20syml?= =?UTF-8?q?inks=20are=20data;=20spawn's=20links=20are=20scaffold?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A keep-list symlink is data afx cleanup --keep-ignored cannot keep: ignored is ATTN, the verdict NOT REMOVABLE, the verdict line names the links, and the hint no longer offers --keep-ignored for them. Each is printed with its target, or "(target missing)". - A link to a keep-list file inside the worktree is judged as that file. - Links spawn makes (.env, .codev/config.json, every worktree.symlinks entry) point at the same path in the main checkout; builder-scaffold.ts defines that shape (spawnLinkTarget), tied to spawn by a test that runs symlinkConfigFiles. They are scaffold in uncommitted and ignored, never data. - git-forms catalogue gains this phase's read forms (ls-files --directory, plain rev-list). --- .../1951-check_worktree-iter2-rebuttals.md | 75 +++++++++ codev/state/spir-1951_thread.md | 24 +++ .../spec-1951-builder-scaffold.test.ts | 52 +++++- .../src/agent-farm/lib/builder-scaffold.ts | 14 ++ .../check/__tests__/check-worktree.test.ts | 86 ++++++++-- .../check/__tests__/helpers/git-forms.ts | 4 + .../check/__tests__/helpers/report-shape.ts | 5 +- .../commands/check/__tests__/imports.test.ts | 8 +- packages/codev/src/commands/check/worktree.ts | 159 ++++++++++++++---- 9 files changed, 376 insertions(+), 51 deletions(-) create mode 100644 codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter2-rebuttals.md diff --git a/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter2-rebuttals.md b/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter2-rebuttals.md new file mode 100644 index 000000000..018d89299 --- /dev/null +++ b/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter2-rebuttals.md @@ -0,0 +1,75 @@ +# Phase 6 (`check_worktree`) — iteration 2 rebuttal + +Codex: REQUEST_CHANGES. Claude: APPROVE with five non-blocking notes. + +## Codex: keep-list symlinks must block removal (accepted and fixed, with the architect's conditions) + +> `worktree.ts:381-400` excludes matching symlinks from both kept data and the attention +> verdict … a worktree containing only an ignored keep-list symlink [is] `REMOVABLE` with exit +> 0, even though cleanup deletes that symlink. + +Correct. The spec (line 577) says an ignored path that matches `cleanup.keepIgnored` is data. +My iteration-1 fix treated a link as holding no data of its own, which the spec does not say. +`afx cleanup --keep-ignored` deletes such a link, so `REMOVABLE` promised more than cleanup +does. I told the architect before reversing that part of the iteration-1 fix. They agreed +and set two conditions, both now built and tested. + +The fix: + +- A keep-list link is data that `--keep-ignored` cannot keep. `ignored` is ATTN, the verdict + is NOT REMOVABLE, and the verdict line names `N keep-list symlinks`. The hint no longer + offers `--keep-ignored` for them: + - links only: `→ copy them out first (`afx cleanup --keep-ignored` never copies a link)`; + - links and keep files: `→ copy the symlinks out first (… keeps the files, never a link)`. +- **Architect condition 1: links spawn makes are scaffold, never data.** Spawn links the + root `.env` and `.codev/config.json`, and every `worktree.symlinks` entry, from a path in + the worktree to the same path in the main checkout (`symlinkConfigFiles`). + `builder-scaffold.ts` now defines that shape (`spawnLinkTarget`) beside the scaffold files. + A link at P whose target is P in the main checkout counts as scaffold: + - in `ignored`, where it shows as `[N scaffold links not counted]`; + - in `uncommitted`, for a link git does not ignore, where it joins the + `[N scaffold files not counted]` count. + + The tie-to-spawn test runs spawn's own `symlinkConfigFiles`. Its config has a file glob + (`packages/*/.env`), a literal file and a directory entry, and the test asserts that every + link spawn made has that shape. The shape is what each entry produces, so spawn's + node-glob patterns never need matching here. That matching would need the `glob` package, + which does I/O, or `path.matchesGlob`, which the `>=20.0.0` engine range does not + guarantee. A link spawn made from an entry since removed from config still counts, and + removing such a link loses nothing, since what it points at stays in the main checkout. +- **Architect condition 2: each remaining link is printed with its target**, as + `tmp/link -> /…/elsewhere`, or `tmp/env -> /…/outside-secret (target missing)`. The JSON + gives `links: [{ path, target, missing }]`. A link whose target resolves to a keep-list + file inside the worktree is judged as that file, which is kept, so it is not listed. +- `readlinkSync` joins the audited read-only `node:fs` names. `builder-scaffold.ts` now + imports `node:path`, and the pure-module audit lists that. + +Tests: removability with links, with and without keep files; a link to a kept file next to one +whose target is missing, with the agreement with `listKeepCandidates()` kept; links alone; spawn's +links (ignored and not) leave a clean worktree REMOVABLE, exit 0; a link at `.env` pointing +anywhere else is data. The symlink tests are POSIX (a link needs privileges on Windows). + +## Claude's non-blocking notes + +1. **A project that gitignores `.builder-*` would see scaffold as keep-list data.** Accepted + for the Phase 7 docs, as Claude suggests. `--keep-ignored` would copy those files, and the + priority is that the check and cleanup agree. +2. **`details.links` is additive.** It goes into the Phase 7 schema docs, with its new shape + `{ path, target, missing }` and the new `ignored.details.scaffold`. +3. **`allowedForms()` omits this phase's forms.** Fixed: `ls-files … --directory -z` (with + `-C`), `rev-list --not ` and `rev-list --not ` are in the + catalogue. The allow-list test and the stub self-test both run them. +4. **Wording drift from the spec sample.** Not changed: + - `all 31 commits are on origin/main` cannot be said truthfully. The check counts commits + not on the base, and the number of commits "on" it has no defined start. + `every commit is on origin/main` says what was checked. + - `ignored paths`, not `files`: a collapsed entry such as `node_modules/` is a directory. + - `(#1950)`: an issue number in this repository means nothing in an adopter's output. +5. **The two accepted approximations** (`regenerable` within collapsed directories, and + nested-repo `dir/` entries left unexpanded) go into the Phase 7 docs. The `regenerable` + line will say what the number counts. + +## Not on the read-only core + +The runner, allow-list, validation and roots are unchanged. The changes are in `worktree.ts`, +`builder-scaffold.ts` (a pure definition), the imports audit's lists, and tests. diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 983dc3b74..47eb9a679 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -306,3 +306,27 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals a remote-branch read failure with commits off the base now makes `commits` NOT RUN (truthful) rather than "unpushed". Notes 1 (regenerable approximation in collapsed dirs) and 2 (nested-repo dir/ entries) → Phase 7 docs + REVIEW. Not on the read-only core. Targeted 910/910 (29 files), build, both tsc, tmp-residue OK. +- Porch sequencing (2026-11-24 ~03:20): I committed the iter1 fixes (dd21e15ce) and ran the architect-approved + one-time skip + `porch done` BEFORE `porch next` had read the iter1 verdicts, so that `porch done` only re-signalled + the iteration-1 build. The `porch next` after it read codex's REQUEST_CHANGES and opened iteration 2 (95ae544b5, + status.yaml only), whose build/tests criteria start unrun. Code is unchanged since dd21e15ce. Asked the architect + for the skip again for iteration 2's `porch done`, after GitHub's run on 95ae544b5. Architect: covered by the + Phase 4 word (further porch done calls in a phase with no code or test changes); skip applied, build passed. + Correction to my own lesson: porch's round really is rebuttal → `porch done` → `porch next` (re-iter: build/tests) + → `porch done` → `porch next` (consult). After a review round, `porch next` first so the rebuttal task is named. +- Review iter2: codex REQUEST_CHANGES — a keep-list symlink is data (spec line 577) that --keep-ignored deletes, so + links-only must not read REMOVABLE. Told the architect before reversing that line of the iter1 fix; architect + (03:29): Codex is right, go NOT REMOVABLE + honest hint, with two conditions. (1) Links spawn makes are scaffold: + `spawnLinkTarget` in builder-scaffold.ts = the shape every spawn link has (P → P in the main checkout, built-in + `.env`/`.codev/config.json` and every worktree.symlinks entry); recognised by shape, not by re-matching spawn's + node-glob patterns (needs the `glob` package's I/O or path.matchesGlob, which engines >=20.0.0 don't guarantee). + Tie test runs spawn's own symlinkConfigFiles (file glob, literal file, dir entry). Counted in `uncommitted`'s + scaffold (a link git does not ignore) and as `[N scaffold links not counted]` in `ignored`. (2) Each remaining + link printed with its target (`p -> t`, `(target missing)`); JSON `links: [{path, target, missing}]`, plus + `ignored.details.scaffold`. A link to a keep-list file inside the worktree is judged as that file (not listed). + Claude APPROVE; note 3 fixed (git-forms catalogue gains ls-files --directory and the two plain rev-list forms); + notes 1/2/5 → Phase 7 docs; note 4 (sample wording) rebutted. Targeted 925/925 (24 files), build, both tsc, + tmp-residue OK. LIVE: air-1938 with a scratch HOME whose keepIgnored adds `.env*` and `.codev/**`: + `[2 scaffold links not counted]` (.env, .codev/config.json), `.codev/config.local.json` (spawn's snapshot COPY, + a regular file) counted as a keep file — correct, it is a file a builder may edit; default keep list never + matches it. Real-HOME runs on spir-1951/air-1938/bugfix-1956 unchanged. diff --git a/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts index 52de7700a..e0e759194 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts @@ -9,12 +9,14 @@ */ import { execFileSync } from 'node:child_process'; -import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { lstatSync, mkdirSync, mkdtempSync, readdirSync, readlinkSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { dirname, join } from 'node:path'; +import { dirname, join, relative, resolve, sep } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { useFakeHome } from '../../commands/check/__tests__/helpers/fake-home.js'; import { hasUncommittedChanges } from '../commands/cleanup.js'; -import { isBuilderScaffold, OPENCODE_CONFIG_RELPATH, SCAFFOLD_PATHS } from '../lib/builder-scaffold.js'; +import { symlinkConfigFiles } from '../commands/spawn-worktree.js'; +import { isBuilderScaffold, OPENCODE_CONFIG_RELPATH, SCAFFOLD_PATHS, spawnLinkTarget } from '../lib/builder-scaffold.js'; import { DEFAULT_KEEP_IGNORED, isNeverKeep, keepPatterns } from '../lib/keep-list.js'; import * as keepFiles from '../lib/keep-files.js'; import { BUILTIN_HARNESSES } from '../utils/harness.js'; @@ -40,6 +42,50 @@ describe('Spec 1951 — isBuilderScaffold', () => { }); }); +// Native Windows may make a hard link or a copy where POSIX makes a symlink; this is about links. +describe.skipIf(process.platform === 'win32')("Spec 1951 — spawnLinkTarget is the shape of every link spawn makes", { timeout: 30_000 }, () => { + useFakeHome(); + let base: string; + beforeEach(() => { + base = realpathSync(mkdtempSync(join(tmpdir(), 'spec-1951-links-'))); + }); + afterEach(() => { + rmSync(base, { recursive: true, force: true }); + }); + + /** Every symbolic link under `dir`, worktree-relative and `/`-separated. */ + const linksUnder = (dir: string): string[] => + readdirSync(dir, { recursive: true, encoding: 'utf8' }) + .filter((rel) => lstatSync(join(dir, rel)).isSymbolicLink()) + .map((rel) => rel.split(sep).join('/')) + .sort(); + + it('symlinkConfigFiles: the built-in links and each worktree.symlinks entry point at spawnLinkTarget', () => { + const root = join(base, 'main'); + const worktree = join(base, 'wt'); + const put = (rel: string): void => { + mkdirSync(dirname(join(root, rel)), { recursive: true }); + writeFileSync(join(root, rel), `${rel}\n`); + }; + put('.env'); + put('.env.local'); + put('packages/web/.env'); + put('.codev/config.json'); + writeFileSync(join(root, '.codev/config.json'), JSON.stringify({ worktree: { symlinks: ['.env.local', 'packages/*/.env', '.local-data/'] } })); + mkdirSync(worktree); + + symlinkConfigFiles({ workspaceRoot: root } as Parameters[0], worktree); + + const made = linksUnder(worktree); + expect(made).toEqual(['.codev/config.json', '.env', '.env.local', '.local-data', 'packages/web/.env']); + for (const rel of made) { + const abs = join(worktree, ...rel.split('/')); + expect(resolve(dirname(abs), readlinkSync(abs)), rel).toBe(spawnLinkTarget(root, rel)); + } + expect(relative(root, spawnLinkTarget(root, 'packages/web/.env'))).toBe(join('packages', 'web', '.env')); + }); +}); + describe('Spec 1951 — keep-list.ts is the one definition keep-files.ts uses', () => { it('keep-files re-exports the same objects', () => { expect(keepFiles.DEFAULT_KEEP_IGNORED).toBe(DEFAULT_KEEP_IGNORED); diff --git a/packages/codev/src/agent-farm/lib/builder-scaffold.ts b/packages/codev/src/agent-farm/lib/builder-scaffold.ts index d609d83d5..9f7926b66 100644 --- a/packages/codev/src/agent-farm/lib/builder-scaffold.ts +++ b/packages/codev/src/agent-farm/lib/builder-scaffold.ts @@ -10,8 +10,14 @@ * * Only an untracked file is ever scaffold: a change to a tracked file is a real change, * whatever its path. + * + * Spawn also links files from the main checkout into the worktree (`symlinkConfigFiles`): the + * root `.env` and `.codev/config.json` always, and every `worktree.symlinks` entry. Each such + * link points at the same path in the main checkout, so a link of that shape is scaffold + * whichever entry made it: removing it loses nothing (`spawnLinkTarget`). */ +import { join } from 'node:path'; import { GUARD_SCRIPT_RELPATH, GUARD_SETTINGS_RELPATH } from '../utils/worktree-write-guard.js'; /** Worktree-relative path of the OpenCode harness's role-injection file. */ @@ -26,3 +32,11 @@ export const SCAFFOLD_PATHS: readonly string[] = [GUARD_SCRIPT_RELPATH, GUARD_SE export function isBuilderScaffold(path: string): boolean { return (path.startsWith(BUILDER_PREFIX) && !path.includes('/')) || SCAFFOLD_PATHS.includes(path); } + +/** + * The target spawn gives a link at a worktree-relative, `/`-separated `path`: the same path in + * the main checkout. A link at `path` whose target is this is one spawn made. + */ +export function spawnLinkTarget(mainRoot: string, path: string): string { + return join(mainRoot, ...path.split('/')); +} diff --git a/packages/codev/src/commands/check/__tests__/check-worktree.test.ts b/packages/codev/src/commands/check/__tests__/check-worktree.test.ts index 397ba40e6..53eeddcad 100644 --- a/packages/codev/src/commands/check/__tests__/check-worktree.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-worktree.test.ts @@ -12,6 +12,7 @@ import { spawn as realSpawn } from 'node:child_process'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { spawnLinkTarget } from '../../../agent-farm/lib/builder-scaffold.js'; import { listKeepCandidates } from '../../../agent-farm/lib/keep-files.js'; import { DEFAULT_KEEP_IGNORED } from '../../../agent-farm/lib/keep-list.js'; import type { Check, CommandOptions, ErrorReport, Status, WorktreeReport } from '../report.js'; @@ -76,6 +77,10 @@ describe('Spec 1951 — check worktree: parsers and the verdict rule', () => { expect(removability(all('ok', 'not-run', 'ok'), true)).toBe('removable'); expect(removability(all('ok', 'ok', 'not-run'), false)).toBe('not-removable'); expect(removability(all('skip', 'skip', 'skip'), false)).toBe('removable'); + // Keep-list symlinks are data cleanup cannot keep: with or without keep files, they block removal. + const withLinks = (keep: string[]) => [...all('ok', 'ok', 'attention').slice(0, 4), { ...c('ignored', 'attention'), details: { keep, regenerable: 0, links: [{ path: 'tmp/link', target: '/x', missing: false }], scaffold: [] } }]; + expect(removability(withLinks([]), false)).toBe('not-removable'); + expect(removability(withLinks(['tmp/notes.md']), false)).toBe('not-removable'); }); }); @@ -362,8 +367,9 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, }); // keepFiles() skips every symlink it is handed ("Not kept (symlinks)"), so check worktree - // must not count one as a file cleanup would keep. Symlinks need privileges on Windows. - it.skipIf(isWindows)('a keep-list symlink is listed apart: not a keep file, not data, as cleanup never copies it', async () => { + // must not count one as a file cleanup would keep; a link is still data, which nothing but + // copying it out keeps. Symlinks need privileges on Windows. + it.skipIf(isWindows)('a keep-list symlink is listed apart, with its target; one to a kept file is judged as that file', async () => { configure(); const b = withIgnored(); fs.symlinkSync('notes.md', path.join(b.dir, 'tmp/link.md')); @@ -382,18 +388,28 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, } const isLink = (f: string): boolean => fs.lstatSync(path.join(b.dir, f)).isSymbolicLink(); - const { report } = await runReport('spir-8', { inspected: b.dir }); + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); const ignored = byId(report, 'ignored'); - expect(ignored.details).toEqual({ keep: candidates.filter((f) => !isLink(f)), regenerable: 3, links: candidates.filter(isLink) }); - expect(ignored.details.links).toEqual(['tmp/env', 'tmp/link.md']); - expect(report.removable).toBe('removable-after-keeping'); - expect(ignored.summary).toContain('2 keep-list symlinks not counted (cleanup never copies a link): tmp/env, tmp/link.md'); + // The keep files are what keepFiles() copies; tmp/link.md points at tmp/notes.md, which is kept. + expect(candidates.filter(isLink)).toEqual(['tmp/env', 'tmp/link.md']); + expect(ignored.details).toEqual({ + keep: candidates.filter((f) => !isLink(f)), + regenerable: 3, + links: [{ path: 'tmp/env', target: path.join(fx.root, 'outside-secret'), missing: true }], + scaffold: [], + }); + expect(exitCode).toBe(1); + expect(report.removable).toBe('not-removable'); + expect(ignored.status).toBe('attention'); + expect(ignored.summary).toContain(`1 keep-list symlink would be lost: tmp/env -> ${path.join(fx.root, 'outside-secret')} (target missing)`); + expect(ignored.summary).toContain('→ copy the symlinks out first (`afx cleanup --keep-ignored` keeps the files, never a link)'); }); - it.skipIf(isWindows)('keep-list symlinks alone leave it REMOVABLE', async () => { + it.skipIf(isWindows)('keep-list symlinks alone: NOT REMOVABLE, and the hint does not offer --keep-ignored', async () => { configure({ cleanup: { keepIgnored: ['tmp/**'] } }); const b = addBuilder(fx, 'spir-8'); + fs.mkdirSync(path.join(fx.root, 'elsewhere')); fs.mkdirSync(path.join(b.dir, 'tmp')); fs.symlinkSync(path.join(fx.root, 'elsewhere'), path.join(b.dir, 'tmp/link')); mergeBuilder(fx, b); @@ -401,9 +417,59 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + expect(exitCode).toBe(1); + expect(report.removable).toBe('not-removable'); + expect(byId(report, 'ignored')).toMatchObject({ + status: 'attention', + details: { keep: [], links: [{ path: 'tmp/link', target: path.join(fx.root, 'elsewhere'), missing: false }] }, + }); + const human = renderWorktreeHuman(report); + expect(human.split('\n')[0]).toBe('NOT REMOVABLE spir-8 — 1 keep-list symlink'); + expect(human).toContain(`1 keep-list symlink would be lost: tmp/link -> ${path.join(fx.root, 'elsewhere')}\n`); + expect(human).toContain('→ copy them out first (`afx cleanup --keep-ignored` never copies a link)'); + }); + + // A project that keeps '.env*' must not see every worktree it spawns as NOT REMOVABLE. + it.skipIf(isWindows)("the links spawn makes are scaffold, never data, ignored or not", async () => { + configure({ cleanup: { keepIgnored: ['.env*', 'tmp/**'] } }); + fs.mkdirSync(path.join(fx.main, '.git', 'info'), { recursive: true }); + fs.appendFileSync(path.join(fx.main, '.git', 'info', 'exclude'), '.env*\n'); + fs.writeFileSync(path.join(fx.main, '.env'), 'A=1\n'); + fs.writeFileSync(path.join(fx.main, '.env.local'), 'B=2\n'); + const b = addBuilder(fx, 'spir-8'); + // As spawn links them: the built-in .env, a worktree.symlinks file, and a directory entry + // that git does not ignore and whose source does not exist yet (spawn allows that). + for (const rel of ['.env', '.env.local', 'shared-data']) fs.symlinkSync(spawnLinkTarget(fx.main, rel), path.join(b.dir, rel)); + mergeBuilder(fx, b); + prIs(b, 8, 'MERGED'); + + const { report, exitCode } = await runReport('spir-8', { inspected: b.dir }); + expect(exitCode).toBe(0); expect(report.removable).toBe('removable'); - expect(byId(report, 'ignored')).toMatchObject({ status: 'ok', details: { keep: [], links: ['tmp/link'] } }); + expect(byId(report, 'uncommitted')).toMatchObject({ status: 'ok', details: { files: [], scaffold: [...SCAFFOLD_FILES, 'shared-data'].sort() } }); + expect(byId(report, 'ignored')).toMatchObject({ status: 'ok', details: { keep: [], links: [], scaffold: ['.env', '.env.local'] } }); + expect(byId(report, 'uncommitted').summary).toContain(`[${SCAFFOLD_FILES.length + 1} scaffold files not counted]`); + expect(byId(report, 'ignored').summary).toContain('[2 scaffold links not counted]'); + }); + + it.skipIf(isWindows)("a link at spawn's path that points anywhere else is not spawn's: it is data", async () => { + configure({ cleanup: { keepIgnored: ['.env*'] } }); + fs.mkdirSync(path.join(fx.main, '.git', 'info'), { recursive: true }); + fs.appendFileSync(path.join(fx.main, '.git', 'info', 'exclude'), '.env*\n'); + fs.writeFileSync(path.join(fx.root, 'my-env'), 'SECRET=1\n'); + const b = addBuilder(fx, 'spir-8'); + fs.symlinkSync(path.join(fx.root, 'my-env'), path.join(b.dir, '.env')); + mergeBuilder(fx, b); + prIs(b, 8, 'MERGED'); + + const { report } = await runReport('spir-8', { inspected: b.dir }); + + expect(report.removable).toBe('not-removable'); + expect(byId(report, 'ignored')).toMatchObject({ + status: 'attention', + details: { keep: [], links: [{ path: '.env', target: path.join(fx.root, 'my-env'), missing: false }], scaffold: [] }, + }); }); it('cleanup.keepIgnored [] reports no keep files: REMOVABLE', async () => { @@ -427,7 +493,7 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, const { report } = await runReport('spir-8', { inspected: b.dir }); - expect(byId(report, 'ignored').details).toEqual({ keep: ['debug.log'], regenerable: 4, links: [] }); + expect(byId(report, 'ignored').details).toEqual({ keep: ['debug.log'], regenerable: 4, links: [], scaffold: [] }); }); }); diff --git a/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts b/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts index 0d2ae5715..3b64a4b49 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/git-forms.ts @@ -5,6 +5,7 @@ export const SHA = 'a'.repeat(40); export const SHA2 = 'b'.repeat(40); +export const SHA3 = 'c'.repeat(40); export interface GitForm { globals: string[]; @@ -27,6 +28,8 @@ export function allowedForms(dir: string): GitForm[] { form([], 'rev-list', '--first-parent', '--max-count=10', SHA), form([], 'rev-list', '--count', `${SHA}..${SHA2}`), form([], 'rev-list', '--first-parent', '--parents', '--max-count=11', SHA, '--not', SHA2), + form([], 'rev-list', SHA, '--not', SHA2), + form([], 'rev-list', SHA, '--not', SHA2, SHA3), form([], 'merge-base', SHA, SHA2), form([], 'merge-base', '--is-ancestor', SHA, 'refs/remotes/origin/main'), form([], 'log', '--no-ext-diff', '--no-textconv', '-z', '--format=%H%x00%B', `${SHA}..${SHA2}`), @@ -39,6 +42,7 @@ export function allowedForms(dir: string): GitForm[] { form([], 'cat-file', '-t', SHA), form([], 'for-each-ref', '--format=%(refname)', 'refs/heads/main'), form(['-C', dir], 'ls-files', '--others', '--ignored', '--exclude-standard', '-z', '--', ':(top,glob)codev/**'), + form(['-C', dir], 'ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z'), form([], 'ls-remote', 'origin', 'refs/heads/main'), form([], 'ls-remote', '--symref', 'origin', 'HEAD'), form([], 'worktree', 'list', '--porcelain'), diff --git a/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts b/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts index 678fff65b..b5a0d232a 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/report-shape.ts @@ -129,7 +129,10 @@ export function expectWorktreeReportShape(report: WorktreeReport): void { expect(['matches', 'ahead', 'behind', 'diverged', 'absent']).toContain(c.details.relation); } if (c.id === 'pr' && 'mergedHead' in c.details) expect(c.details.mergedHead).toMatch(SHA); - if (c.id === 'ignored') expect(c.details).toEqual({ keep: expect.any(Array), regenerable: expect.any(Number), links: expect.any(Array) }); + if (c.id === 'ignored') { + expect(c.details).toEqual({ keep: expect.any(Array), regenerable: expect.any(Number), links: expect.any(Array), scaffold: expect.any(Array) }); + for (const link of c.details.links as unknown[]) expect(link).toEqual({ path: expect.any(String), target: expect.any(String), missing: expect.any(Boolean) }); + } } const attention = parsed.checks.some((c) => c.status === 'attention' || c.status === 'not-run'); expect(parsed.verdict).toBe(attention ? 'attention' : 'clear'); diff --git a/packages/codev/src/commands/check/__tests__/imports.test.ts b/packages/codev/src/commands/check/__tests__/imports.test.ts index 4fb1eb3a7..0b0dc86ce 100644 --- a/packages/codev/src/commands/check/__tests__/imports.test.ts +++ b/packages/codev/src/commands/check/__tests__/imports.test.ts @@ -25,7 +25,7 @@ interface ImportRule { const ALLOWED: Record = { 'node:path': { names: '*', reason: 'path arithmetic only; no I/O' }, 'node:fs': { - names: ['existsSync', 'readFileSync', 'realpathSync', 'statSync', 'lstatSync'], + names: ['existsSync', 'readFileSync', 'realpathSync', 'statSync', 'lstatSync', 'readlinkSync'], reason: 'read-only file system calls', }, '../../lib/config.js': { @@ -37,8 +37,8 @@ const ALLOWED: Record = { reason: "#1950's keep list as pure definitions, shared with afx cleanup --keep-ignored (audited below)", }, '../../agent-farm/lib/builder-scaffold.js': { - names: ['isBuilderScaffold'], - reason: "spawn's scaffold file list, pure, shared with afx cleanup (audited below)", + names: ['isBuilderScaffold', 'spawnLinkTarget'], + reason: "spawn's scaffold files and the shape of its links, pure, shared with afx cleanup (audited below)", }, }; @@ -49,7 +49,7 @@ const ALLOWED: Record = { */ const PURE_MODULES: Record = { '../../agent-farm/lib/keep-list.ts': { imports: [] }, - '../../agent-farm/lib/builder-scaffold.ts': { imports: ['../utils/worktree-write-guard.js'] }, + '../../agent-farm/lib/builder-scaffold.ts': { imports: ['node:path', '../utils/worktree-write-guard.js'] }, '../../agent-farm/utils/worktree-write-guard.ts': { imports: ['node:path'], scriptText: WORKTREE_WRITE_GUARD_SCRIPT }, }; diff --git a/packages/codev/src/commands/check/worktree.ts b/packages/codev/src/commands/check/worktree.ts index de9cb2ebf..32770918a 100644 --- a/packages/codev/src/commands/check/worktree.ts +++ b/packages/codev/src/commands/check/worktree.ts @@ -3,25 +3,26 @@ * and its local branch lose data, and, separately, is the builder finished. * * uncommitted staged, unstaged and untracked-not-ignored files (`status`, without optional - * locks); spawn's scaffold (`isBuilderScaffold`) is counted apart and is not data + * locks); spawn's scaffold files and links (`builder-scaffold.ts`) are counted + * apart and are not data * commits local commits on neither the live base tip nor the live remote branch tip, * unless the PR is merged and the local tip is its merged head (squash or rebase) * remote the local tip against `origin/`: context only * pr the branch's PR: OPEN is attention ("builder not finished") * ignored ignored files matching `cleanup.keepIgnored` that are not dependency or build * output: the definitions `afx cleanup --keep-ignored` uses (`keep-list.ts`). - * A symbolic link among them is listed apart: cleanup never copies a link, and a - * link holds no file data of its own (a target inside the worktree is judged - * as itself) + * A symbolic link among them is listed apart: one spawn made is scaffold; one to + * a keep-list file inside the worktree is judged as that file; any other is data + * cleanup cannot keep (it never copies a link), so it blocks removal * * The verdict word describes data only. The exit code also counts the lifecycle and anything * that could not run, so "removable" never silently means "finished". The target is * resolved against the main checkout, so the command reads the same from any worktree. */ -import { lstatSync, realpathSync } from 'node:fs'; -import { basename, dirname, isAbsolute, join, resolve } from 'node:path'; -import { isBuilderScaffold } from '../../agent-farm/lib/builder-scaffold.js'; +import { lstatSync, readlinkSync, realpathSync } from 'node:fs'; +import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; +import { isBuilderScaffold, spawnLinkTarget } from '../../agent-farm/lib/builder-scaffold.js'; import { isNeverKeep } from '../../agent-farm/lib/keep-list.js'; import { ancestry, @@ -231,6 +232,8 @@ type Tip = Lookup; interface Facts { runner: Runner; + /** The main checkout, where spawn's links point. */ + mainRoot: string; target: Target; pr: PrLookup | null; /** The base branch, or why there is none. */ @@ -261,6 +264,49 @@ async function revList(runner: Runner, args: string[]): Promise return { ok: true, value: shas }; } +/** A symbolic link: its target as written, where that points, and whether anything is there. */ +interface Link { + target: string; + resolved: string; + missing: boolean; +} + +/** The link at a worktree-relative path, or null when the path is not a link. */ +function linkAt(facts: Facts, rel: string): Lookup { + const abs = join(facts.target.path, ...rel.split('/')); + try { + if (!lstatSync(abs).isSymbolicLink()) return { ok: true, value: null }; + const target = readlinkSync(abs); + const resolved = resolve(dirname(abs), target); + return { ok: true, value: { target, resolved, missing: realPath(resolved) === null } }; + } catch (err) { + return { ok: false, reason: `could not read ${rel}: ${err instanceof Error ? err.message : String(err)}` }; + } +} + +/** A path spelled for comparison: its real path, or, when it does not exist, its parent's. */ +function comparable(p: string): string { + const real = realPath(p); + if (real !== null) return real; + const parent = realPath(dirname(p)); + const spelled = parent === null ? resolve(p) : join(parent, basename(p)); + return process.platform === 'win32' ? spelled.toLowerCase() : spelled; +} + +/** Whether a link is one spawn made: it points at the same path in the main checkout. */ +function isSpawnLink(facts: Facts, rel: string, link: Link): boolean { + return comparable(link.resolved) === comparable(spawnLinkTarget(facts.mainRoot, rel)); +} + +/** The worktree-relative path a link resolves to, or null when it resolves outside the worktree or to nothing. */ +function insideTarget(facts: Facts, link: Link): string | null { + const real = realPath(link.resolved); + if (real === null) return null; + const rel = relative(comparable(facts.target.path), real); + if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) return null; + return rel.split(sep).join('/'); +} + /** Git in the inspected worktree, for the reads that are per worktree. */ function gitIn(facts: Facts, args: string[]): Promise { return facts.runner.git(['-C', facts.target.path, ...args]); @@ -274,9 +320,23 @@ async function checkUncommitted(facts: Facts): Promise { const result = await gitIn(facts, ['--no-optional-locks', 'status', '--porcelain=v1', '-z', '--untracked-files=all']); if (result.exitCode !== 0) return notRun('uncommitted', failureReason('status', result, facts.runner.timeoutLabel)); const entries = parseStatus(result.stdout); - const isScaffold = (e: StatusEntry): boolean => e.change === 'untracked' && isBuilderScaffold(e.path); - const scaffold = entries.filter(isScaffold).map((e) => e.path).sort(); - const files = entries.filter((e) => !isScaffold(e)).sort((x, y) => (x.path < y.path ? -1 : x.path > y.path ? 1 : 0)); + const scaffold: string[] = []; + const files: StatusEntry[] = []; + for (const e of entries) { + let isScaffold = false; + if (e.change === 'untracked') { + isScaffold = isBuilderScaffold(e.path); + if (!isScaffold) { + const link = linkAt(facts, e.path); + if (!link.ok) return notRun('uncommitted', link.reason); + isScaffold = link.value !== null && isSpawnLink(facts, e.path, link.value); + } + } + if (isScaffold) scaffold.push(e.path); + else files.push(e); + } + scaffold.sort(); + files.sort((x, y) => (x.path < y.path ? -1 : x.path > y.path ? 1 : 0)); const note = scaffold.length > 0 ? ` [${plural(scaffold.length, 'scaffold file')} not counted]` : ''; const details = { files, scaffold }; if (files.length === 0) return check('uncommitted', 'ok', `nothing uncommitted${note}`, details); @@ -365,44 +425,68 @@ function checkPrState(lookup: PrLookup, branch: string): Check { async function checkIgnored(facts: Facts, patterns: readonly string[]): Promise { const keep: string[] = []; - const links: string[] = []; + const links: Array<{ path: string; target: string; missing: boolean }> = []; + const scaffold: string[] = []; + let matched: string[] = []; const pathspecs = pathspecArgs({ include: patterns }); if (pathspecs !== null) { const result = await gitIn(facts, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z', ...pathspecs]); if (result.exitCode !== 0) return notRun('ignored', failureReason('ls-files', result, facts.runner.timeoutLabel)); - const matched = splitNul(result.stdout).filter((p) => !isNeverKeep(p)); + matched = splitNul(result.stdout).filter((p) => !isNeverKeep(p)); + const linked: Array<[string, Link]> = []; for (const p of matched) { - let isLink: boolean; - try { - isLink = lstatSync(join(facts.target.path, p)).isSymbolicLink(); - } catch (err) { - return notRun('ignored', `could not read ${p}: ${err instanceof Error ? err.message : String(err)}`); + const link = linkAt(facts, p); + if (!link.ok) return notRun('ignored', link.reason); + if (link.value === null) keep.push(p); + else linked.push([p, link.value]); + } + const key = (p: string): string => (process.platform === 'win32' ? p.toLowerCase() : p); + const kept = new Set(keep.map(key)); + for (const [p, link] of linked) { + if (isSpawnLink(facts, p, link)) { + scaffold.push(p); + continue; } - (isLink ? links : keep).push(p); + // A link to a keep-list file inside the worktree is judged as that file, which is kept. + const inside = insideTarget(facts, link); + if (inside !== null && kept.has(key(inside))) continue; + links.push({ path: p, target: link.target, missing: link.missing }); } keep.sort(); - links.sort(); + links.sort((x, y) => (x.path < y.path ? -1 : x.path > y.path ? 1 : 0)); + scaffold.sort(); } const all = await gitIn(facts, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '-z']); if (all.exitCode !== 0) return notRun('ignored', failureReason('ls-files', all, facts.runner.timeoutLabel)); // Every other ignored path, directories collapsed, is treated as regenerable. - const matchedAll = [...keep, ...links]; - const holdsMatch = (entry: string): boolean => matchedAll.some((k) => k === entry || (entry.endsWith('/') && k.startsWith(entry))); + const holdsMatch = (entry: string): boolean => matched.some((k) => k === entry || (entry.endsWith('/') && k.startsWith(entry))); const others = splitNul(all.stdout).filter((entry) => !holdsMatch(entry)).sort(); - const details = { keep, regenerable: others.length, links }; + const details = { keep, regenerable: others.length, links, scaffold }; const examples = others.length > 0 ? `: ${fitList(others, 40)}` : ''; - const linkLine = - links.length > 0 ? `${plural(links.length, 'keep-list symlink')} not counted (cleanup never copies a link): ${fitList(links, LIST_WIDTH)}` : null; + const note = scaffold.length > 0 ? ` [${plural(scaffold.length, 'scaffold link')} not counted]` : ''; - if (keep.length === 0) { + if (keep.length === 0 && links.length === 0) { const none = patterns.length === 0 ? 'no keep list (cleanup.keepIgnored is empty)' : 'no keep-list files'; const rest = others.length === 0 ? 'no other ignored files' : `${plural(others.length, 'ignored path')} treated as regenerable${examples}`; - return check('ignored', 'ok', [`${none}; ${rest}`, ...(linkLine ? [linkLine] : [])].join('\n'), details); + return check('ignored', 'ok', `${none}; ${rest}${note}`, details); } - const lines = [`${plural(keep.length, 'keep-list file')} would be lost: ${fitList(keep, LIST_WIDTH)}`]; + const lines: string[] = []; + if (keep.length > 0) lines.push(`${plural(keep.length, 'keep-list file')} would be lost: ${fitList(keep, LIST_WIDTH)}`); + // A link is data too, but `afx cleanup --keep-ignored` skips every link, so only copying it + // out by hand keeps it. Each is printed with its target, so the reader can judge what is at stake. + if (links.length > 0) { + const each = links.map((l) => `${l.path} -> ${l.target}${l.missing ? ' (target missing)' : ''}`).join(', '); + lines.push(`${plural(links.length, 'keep-list symlink')} would be lost: ${each}`); + } + lines[0] += note; if (others.length > 0) lines.push(`(${plural(others.length, 'other ignored path')} treated as regenerable${examples})`); - if (linkLine) lines.push(linkLine); - lines.push('→ copy them out first, or use `afx cleanup --keep-ignored`'); + lines.push( + links.length === 0 + ? '→ copy them out first, or use `afx cleanup --keep-ignored`' + : keep.length === 0 + ? '→ copy them out first (`afx cleanup --keep-ignored` never copies a link)' + : '→ copy the symlinks out first (`afx cleanup --keep-ignored` keeps the files, never a link)', + ); return check('ignored', 'attention', lines.join('\n'), details); } @@ -413,16 +497,22 @@ async function checkIgnored(facts: Facts, patterns: readonly string[]): Promise< /** * Data only. A data check that could not run makes the verdict conservative: NOT REMOVABLE, * except `commits` when the local tip is on the live remote branch, which keeps every commit. + * Keep-list symlinks are data `afx cleanup --keep-ignored` cannot keep, so they block removal. */ export function removability(checks: readonly Check[], localOnRemote: boolean): Removable { const status = (id: string): Check['status'] | undefined => checks.find((c) => c.id === id)?.status; const uncommitted = status('uncommitted'); const commits = status('commits'); - if (uncommitted === 'attention' || uncommitted === 'not-run' || status('ignored') === 'not-run') return 'not-removable'; + const links = linkCount(checks.find((c) => c.id === 'ignored')); + if (uncommitted === 'attention' || uncommitted === 'not-run' || status('ignored') === 'not-run' || links > 0) return 'not-removable'; if (commits === 'attention' || (commits === 'not-run' && !localOnRemote)) return 'not-removable'; return status('ignored') === 'attention' ? 'removable-after-keeping' : 'removable'; } +function linkCount(ignored: Check | undefined): number { + return Array.isArray(ignored?.details.links) ? ignored.details.links.length : 0; +} + /** Whether the local tip is reachable from the live remote branch tip. */ async function onRemote(facts: Facts): Promise { const remote = facts.remoteTip; @@ -468,7 +558,7 @@ async function buildWorktreeReport(argument: TargetArgument, options: CommandOpt ], version, ); - const facts: Facts = { runner, target, pr, base, baseTip, remoteTip }; + const facts: Facts = { runner, mainRoot: roots.mainRoot, target, pr, base, baseTip, remoteTip }; const run = async (id: string, fn: () => Check | Promise): Promise => (skip(id) ? skipped(id) : fn()); const checks = [ @@ -521,6 +611,7 @@ const VERDICT_WORDS: Record string> = { /** * What a check needing attention means, in a few words for the verdict line. Keep-list files * are left out: the verdict word, or the data that blocks removal anyway, already says it. + * Keep-list symlinks are named, as they alone can make the verdict NOT REMOVABLE. */ function reasonWords(c: Check): string | null { if (c.status === 'not-run') return `${defaultLabel(c.id)} not run`; @@ -530,8 +621,10 @@ function reasonWords(c: Check): string | null { return `${plural((d.files as unknown[]).length, 'uncommitted file')}`; case 'commits': return `${plural((d.unsafe as unknown[]).length, 'unpushed commit')}`; - case 'ignored': - return null; + case 'ignored': { + const links = linkCount(c); + return links > 0 ? plural(links, 'keep-list symlink') : null; + } case 'pr': if (d.number === undefined) return 'no PR found'; return d.state === 'OPEN' ? `PR #${String(d.number)} open: builder not finished` : `PR #${String(d.number)} ${String(d.state)}`; From 8a66ff91a8296d837583349e320e90f53495282f Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 10:26:48 -0800 Subject: [PATCH 72/94] chore(porch): 1951 implement re-iter (iter 3) --- .../status.yaml | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 1c841335e..b505ba39e 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -38,8 +38,8 @@ gates: status: pending verify-approval: status: pending -iteration: 2 -build_complete: true +iteration: 3 +build_complete: false history: - iteration: 1 plan_phase: readonly_core @@ -101,8 +101,20 @@ history: verdict: APPROVE file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter1-claude.txt + - iteration: 2 + plan_phase: check_worktree + build_output: '' + reviews: + - model: codex + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter2-codex.txt + - model: claude + verdict: APPROVE + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter2-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T03:23:25.595Z' +updated_at: '2026-11-24T18:26:47.921Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From 71358d578f8839cb4d84177fc9aa4b7d427fb5fb Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 10:27:25 -0800 Subject: [PATCH 73/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index b505ba39e..7a743fda7 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 3 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: readonly_core @@ -114,7 +114,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter2-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T18:26:47.921Z' +updated_at: '2026-11-24T18:27:25.403Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From a1ccc442b4261631e52c77d58522eebf37712bd7 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 10:37:25 -0800 Subject: [PATCH 74/94] =?UTF-8?q?[Spec=201951][Phase:=20check=5Fworktree]?= =?UTF-8?q?=20fix:=20review=20iteration=203=20=E2=80=94=20spawn's=20Window?= =?UTF-8?q?s=20link=20fallbacks=20are=20scaffold?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Where a symlink is not allowed, native Windows spawn makes a hard link, else a copy (createWorktreeLink). An entry at P that is a hard link of the main checkout's P, or a copy whose bytes still equal it, is spawn's and is scaffold; a copy that has changed is data. Same rule on every platform, in uncommitted and ignored; a failed read makes the check not run. - Several keep-list links print one per line, each with its target. --- .../1951-check_worktree-iter3-rebuttals.md | 57 +++++++++++++++++++ codev/state/spir-1951_thread.md | 13 +++++ .../check/__tests__/check-worktree.test.ts | 44 +++++++++++++- packages/codev/src/commands/check/worktree.ts | 50 ++++++++++++---- 4 files changed, 149 insertions(+), 15 deletions(-) create mode 100644 codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter3-rebuttals.md diff --git a/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter3-rebuttals.md b/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter3-rebuttals.md new file mode 100644 index 000000000..cd5a46fb0 --- /dev/null +++ b/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter3-rebuttals.md @@ -0,0 +1,57 @@ +# Phase 6 (`check_worktree`) — iteration 3 rebuttal + +Codex: REQUEST_CHANGES. Claude: APPROVE with four non-blocking notes. + +## Codex: native Windows spawn makes hard links and copies (accepted, fixed) + +> `worktree.ts` recognizes spawn-created links only when `lstatSync(...).isSymbolicLink()` is +> true. On native Windows, `createWorktreeLink()` commonly creates file hard links—or copies +> when hard links are unavailable … copied files require careful provenance/content handling +> because they can later diverge and become real data. + +Correct. Where the account may not make a symlink, `createWorktreeLink` makes a hard link of +a file, and failing that a copy. Spawn reports all of these as links. Iteration 2 recognised +only the symlink shape, so on such a Windows host a clean `.env` (with `.env*` kept) or a +`worktree.symlinks` file read as data. That is the noise the architect's condition 1 was +meant to remove. + +The fix, `isSpawnMade` in `worktree.ts`: the entry at P is spawn's when it is +- a symbolic link to P in the main checkout (as before); +- a hard link of that file: the same device and inode, from a `bigint` stat; +- a copy whose bytes still equal that file's, compared by size and then contents. + +A copy that differs (including one of the same size) is data, as Codex asks: the comparison +is made at check time, so an edited copy is never discarded as scaffold. The rule is the same +on every platform. Spawn on POSIX makes only symlinks, but anywhere, an entry the main +checkout holds byte for byte at the same path loses nothing on removal. It applies in both +places a spawn link can show: +- in `uncommitted`, for an entry git does not ignore; +- in `ignored`, for a keep-list match. + +A read that fails makes that check `not run`, which keeps the verdict conservative. No new +import: `statSync` and `readFileSync` are already in the audited read-only set. + +Test (every platform, since a hard link and a copy need no privileges): `.env` as a hard link, +`.env.local` and `shared.json` (which git does not ignore) as unchanged copies, and `.env.test` +as a copy edited to the same size. The first three are scaffold; `.env.test` is a keep file. + +## Claude's non-blocking notes + +1. **The link list was the only list not truncated or wrapped.** Fixed. With more than one + link, each goes on its own continuation line with its target, as Claude suggests. The + architect asked for each link with its target, so the list is not cut short. Tested with + two links, one whose target is missing. +2. **A link to an unkept path inside the worktree blocks removal**, though that content + survives. Kept as is (conservative and visible), and it goes into the Phase 7 docs next + to the two accepted approximations. +3. **Cleanup's dirty notice still counts a spawn link that git does not ignore.** True. It is + the same class as main-36, but that notice is informational, and the plan scoped the + cleanup edit to `isBuilderScaffold()`. Fixing it needs a read-only helper that cleanup can + import as well (the check's helpers live on the check side). I have asked the architect + whether they want it in this PR. Until they answer, it is a known gap for the REVIEW. +4. **The accepted approximations** go into the Phase 7 docs, as recorded in iteration 2. + +## Not on the read-only core + +The runner, allow-list, validation and roots are unchanged. The changes are in `worktree.ts` +and its tests. diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 47eb9a679..29db71096 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -330,3 +330,16 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals `[2 scaffold links not counted]` (.env, .codev/config.json), `.codev/config.local.json` (spawn's snapshot COPY, a regular file) counted as a keep file — correct, it is a file a builder may edit; default keep list never matches it. Real-HOME runs on spir-1951/air-1938/bugfix-1956 unchanged. +- Architect (2026-11-24 18:26, after a ~15 h delivery delay): accepted the shape-based recognition of spawn links + ("cannot drift from what spawn did"), and config.local.json as a kept regular file. Skip applied for the iter2 + rebuttal's porch done (a56bf9a37) and once more for iteration 3's (8a66ff91a, status file only). Machine at load + 32: nothing heavy. +- Review iter3: codex REQUEST_CHANGES — native Windows spawn falls back on a HARD LINK, then a COPY + (createWorktreeLink), which the symlink-only rule read as data. Fixed with `isSpawnMade`: a symlink to P in main, + or a hard link of main's P (bigint dev+ino), or a copy whose bytes still equal it (size, then contents); a changed + copy (even same size) is data. Same rule on every platform (an entry main holds byte for byte at the same path + loses nothing); applied in uncommitted and ignored; a failed read → not run. Test runs on every platform. + Claude APPROVE; note 1 fixed (several links: one per continuation line, each with its target); note 2 (link to an + unkept inside path blocks) → Phase 7 docs; note 3: cleanup's dirty notice still counts a non-ignored spawn link + (same class as main-36, informational, outside the plan's scoped cleanup edit) → asked the architect whether to + fix in this PR (needs a read-only helper cleanup can import); note 4 → Phase 7 docs. diff --git a/packages/codev/src/commands/check/__tests__/check-worktree.test.ts b/packages/codev/src/commands/check/__tests__/check-worktree.test.ts index 53eeddcad..20fde86b2 100644 --- a/packages/codev/src/commands/check/__tests__/check-worktree.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-worktree.test.ts @@ -412,6 +412,7 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, fs.mkdirSync(path.join(fx.root, 'elsewhere')); fs.mkdirSync(path.join(b.dir, 'tmp')); fs.symlinkSync(path.join(fx.root, 'elsewhere'), path.join(b.dir, 'tmp/link')); + fs.symlinkSync(path.join(fx.root, 'gone'), path.join(b.dir, 'tmp/gone')); mergeBuilder(fx, b); prIs(b, 8, 'MERGED'); @@ -421,11 +422,23 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, expect(report.removable).toBe('not-removable'); expect(byId(report, 'ignored')).toMatchObject({ status: 'attention', - details: { keep: [], links: [{ path: 'tmp/link', target: path.join(fx.root, 'elsewhere'), missing: false }] }, + details: { + keep: [], + links: [ + { path: 'tmp/gone', target: path.join(fx.root, 'gone'), missing: true }, + { path: 'tmp/link', target: path.join(fx.root, 'elsewhere'), missing: false }, + ], + }, }); + // One link per line, each with its target, so none is cut off. const human = renderWorktreeHuman(report); - expect(human.split('\n')[0]).toBe('NOT REMOVABLE spir-8 — 1 keep-list symlink'); - expect(human).toContain(`1 keep-list symlink would be lost: tmp/link -> ${path.join(fx.root, 'elsewhere')}\n`); + expect(human.split('\n')[0]).toBe('NOT REMOVABLE spir-8 — 2 keep-list symlinks'); + const lines = byId(report, 'ignored').summary.split('\n'); + expect(lines.slice(0, 3)).toEqual([ + '2 keep-list symlinks would be lost:', + ` tmp/gone -> ${path.join(fx.root, 'gone')} (target missing)`, + ` tmp/link -> ${path.join(fx.root, 'elsewhere')}`, + ]); expect(human).toContain('→ copy them out first (`afx cleanup --keep-ignored` never copies a link)'); }); @@ -453,6 +466,31 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, expect(byId(report, 'ignored').summary).toContain('[2 scaffold links not counted]'); }); + // Where a symlink is not allowed, native Windows spawn makes a hard link, else a copy + // (createWorktreeLink). Both shapes can be made on every platform, so this runs everywhere. + it("spawn's fallbacks: a hard link of the main checkout's file, or a copy still equal to it, is scaffold; a changed copy is data", async () => { + configure({ cleanup: { keepIgnored: ['.env*'] } }); + fs.mkdirSync(path.join(fx.main, '.git', 'info'), { recursive: true }); + fs.appendFileSync(path.join(fx.main, '.git', 'info', 'exclude'), '.env*\n'); + for (const [rel, text] of [['.env', 'A=1\n'], ['.env.local', 'B=2\n'], ['.env.test', 'C=3\n'], ['shared.json', '{}\n']]) { + fs.writeFileSync(path.join(fx.main, rel), text); + } + const b = addBuilder(fx, 'spir-8'); + fs.linkSync(path.join(fx.main, '.env'), path.join(b.dir, '.env')); + fs.copyFileSync(path.join(fx.main, '.env.local'), path.join(b.dir, '.env.local')); + fs.copyFileSync(path.join(fx.main, 'shared.json'), path.join(b.dir, 'shared.json')); + // A copy edited since: same size, different bytes. + fs.writeFileSync(path.join(b.dir, '.env.test'), 'C=4\n'); + mergeBuilder(fx, b); + prIs(b, 8, 'MERGED'); + + const { report } = await runReport('spir-8', { inspected: b.dir }); + + expect(report.removable).toBe('removable-after-keeping'); + expect(byId(report, 'uncommitted')).toMatchObject({ status: 'ok', details: { files: [], scaffold: [...SCAFFOLD_FILES, 'shared.json'].sort() } }); + expect(byId(report, 'ignored')).toMatchObject({ status: 'attention', details: { keep: ['.env.test'], links: [], scaffold: ['.env', '.env.local'] } }); + }); + it.skipIf(isWindows)("a link at spawn's path that points anywhere else is not spawn's: it is data", async () => { configure({ cleanup: { keepIgnored: ['.env*'] } }); fs.mkdirSync(path.join(fx.main, '.git', 'info'), { recursive: true }); diff --git a/packages/codev/src/commands/check/worktree.ts b/packages/codev/src/commands/check/worktree.ts index 32770918a..54c454626 100644 --- a/packages/codev/src/commands/check/worktree.ts +++ b/packages/codev/src/commands/check/worktree.ts @@ -11,16 +11,17 @@ * pr the branch's PR: OPEN is attention ("builder not finished") * ignored ignored files matching `cleanup.keepIgnored` that are not dependency or build * output: the definitions `afx cleanup --keep-ignored` uses (`keep-list.ts`). - * A symbolic link among them is listed apart: one spawn made is scaffold; one to - * a keep-list file inside the worktree is judged as that file; any other is data - * cleanup cannot keep (it never copies a link), so it blocks removal + * What spawn linked in (`isSpawnMade`) is scaffold. A symbolic link among the + * rest is listed apart: one to a keep-list file inside the worktree is judged as + * that file; any other is data cleanup cannot keep (it never copies a link), so + * it blocks removal * * The verdict word describes data only. The exit code also counts the lifecycle and anything * that could not run, so "removable" never silently means "finished". The target is * resolved against the main checkout, so the command reads the same from any worktree. */ -import { lstatSync, readlinkSync, realpathSync } from 'node:fs'; +import { lstatSync, readFileSync, readlinkSync, realpathSync, statSync } from 'node:fs'; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; import { isBuilderScaffold, spawnLinkTarget } from '../../agent-farm/lib/builder-scaffold.js'; import { isNeverKeep } from '../../agent-farm/lib/keep-list.js'; @@ -298,6 +299,29 @@ function isSpawnLink(facts: Facts, rel: string, link: Link): boolean { return comparable(link.resolved) === comparable(spawnLinkTarget(facts.mainRoot, rel)); } +/** + * Whether the entry at `rel` is one spawn made, so removing it loses nothing. Spawn links each + * entry to the same path in the main checkout: a symbolic link where it may make one, else, on + * native Windows, a hard link of that file, else a copy (`createWorktreeLink`). A copy counts + * only while its bytes still equal the main checkout's file: one that has changed is data. + */ +function isSpawnMade(facts: Facts, rel: string, link: Link | null): Lookup { + if (link !== null) return { ok: true, value: isSpawnLink(facts, rel, link) }; + const source = spawnLinkTarget(facts.mainRoot, rel); + const abs = join(facts.target.path, ...rel.split('/')); + try { + const main = statSync(source, { bigint: true, throwIfNoEntry: false }); + if (main === undefined || !main.isFile()) return { ok: true, value: false }; + const mine = statSync(abs, { bigint: true }); + if (!mine.isFile()) return { ok: true, value: false }; + if (mine.dev === main.dev && mine.ino === main.ino) return { ok: true, value: true }; + if (mine.size !== main.size) return { ok: true, value: false }; + return { ok: true, value: readFileSync(abs).equals(readFileSync(source)) }; + } catch (err) { + return { ok: false, reason: `could not compare ${rel} with the main checkout's: ${err instanceof Error ? err.message : String(err)}` }; + } +} + /** The worktree-relative path a link resolves to, or null when it resolves outside the worktree or to nothing. */ function insideTarget(facts: Facts, link: Link): string | null { const real = realPath(link.resolved); @@ -329,7 +353,9 @@ async function checkUncommitted(facts: Facts): Promise { if (!isScaffold) { const link = linkAt(facts, e.path); if (!link.ok) return notRun('uncommitted', link.reason); - isScaffold = link.value !== null && isSpawnLink(facts, e.path, link.value); + const made = isSpawnMade(facts, e.path, link.value); + if (!made.ok) return notRun('uncommitted', made.reason); + isScaffold = made.value; } } if (isScaffold) scaffold.push(e.path); @@ -437,16 +463,15 @@ async function checkIgnored(facts: Facts, patterns: readonly string[]): Promise< for (const p of matched) { const link = linkAt(facts, p); if (!link.ok) return notRun('ignored', link.reason); - if (link.value === null) keep.push(p); + const made = isSpawnMade(facts, p, link.value); + if (!made.ok) return notRun('ignored', made.reason); + if (made.value) scaffold.push(p); + else if (link.value === null) keep.push(p); else linked.push([p, link.value]); } const key = (p: string): string => (process.platform === 'win32' ? p.toLowerCase() : p); const kept = new Set(keep.map(key)); for (const [p, link] of linked) { - if (isSpawnLink(facts, p, link)) { - scaffold.push(p); - continue; - } // A link to a keep-list file inside the worktree is judged as that file, which is kept. const inside = insideTarget(facts, link); if (inside !== null && kept.has(key(inside))) continue; @@ -475,8 +500,9 @@ async function checkIgnored(facts: Facts, patterns: readonly string[]): Promise< // A link is data too, but `afx cleanup --keep-ignored` skips every link, so only copying it // out by hand keeps it. Each is printed with its target, so the reader can judge what is at stake. if (links.length > 0) { - const each = links.map((l) => `${l.path} -> ${l.target}${l.missing ? ' (target missing)' : ''}`).join(', '); - lines.push(`${plural(links.length, 'keep-list symlink')} would be lost: ${each}`); + const each = links.map((l) => `${l.path} -> ${l.target}${l.missing ? ' (target missing)' : ''}`); + if (each.length === 1) lines.push(`1 keep-list symlink would be lost: ${each[0]}`); + else lines.push(`${plural(links.length, 'keep-list symlink')} would be lost:`, ...each.map((e) => ` ${e}`)); } lines[0] += note; if (others.length > 0) lines.push(`(${plural(others.length, 'other ignored path')} treated as regenerable${examples})`); From 927795193474f924111af48785c6f93a54e55840 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 10:44:00 -0800 Subject: [PATCH 75/94] chore(porch): 1951 implement force-advance (safety ceiling reached at iter 3) --- .../status.yaml | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 7a743fda7..06494342c 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -113,8 +113,20 @@ history: verdict: APPROVE file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter2-claude.txt + - iteration: 3 + plan_phase: check_worktree + build_output: '' + reviews: + - model: codex + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter3-codex.txt + - model: claude + verdict: APPROVE + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter3-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T18:27:25.403Z' +updated_at: '2026-11-24T18:44:00.290Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -135,8 +147,8 @@ context_refreshes: at: '2026-11-24T02:32:56.934Z' acknowledged_at: '2026-11-24T02:33:21.252Z' force_advanced: - phase: readonly_core + phase: check_worktree iteration: 3 max_iterations: 3 - rebuttal_file: 1951-readonly_core-iter3-rebuttals.md - at: '2026-11-24T00:24:36.768Z' + rebuttal_file: 1951-check_worktree-iter3-rebuttals.md + at: '2026-11-24T18:44:00.290Z' From 68eef5795f5db9941144dcee1fb63edd21851663 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 10:44:02 -0800 Subject: [PATCH 76/94] =?UTF-8?q?chore(porch):=201951=20advance=20plan=20p?= =?UTF-8?q?hase=20=E2=86=92=20docs=5Fguidance?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../status.yaml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 06494342c..37383727d 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -20,11 +20,11 @@ plan_phases: status: complete - id: check_worktree title: codev check worktree - status: in_progress + status: complete - id: docs_guidance title: Architect guidance and command documentation - status: pending -current_plan_phase: check_worktree + status: in_progress +current_plan_phase: docs_guidance gates: spec-approval: status: approved @@ -38,8 +38,8 @@ gates: status: pending verify-approval: status: pending -iteration: 3 -build_complete: true +iteration: 1 +build_complete: false history: - iteration: 1 plan_phase: readonly_core @@ -126,7 +126,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter3-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T18:44:00.290Z' +updated_at: '2026-11-24T18:44:02.801Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -146,6 +146,8 @@ context_refreshes: - boundary: plan-phase:check_worktree at: '2026-11-24T02:32:56.934Z' acknowledged_at: '2026-11-24T02:33:21.252Z' + - boundary: plan-phase:docs_guidance + at: '2026-11-24T18:44:02.801Z' force_advanced: phase: check_worktree iteration: 3 From d437e74ce9154a1b9e4548d8257aad09d9aeec8e Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 10:45:52 -0800 Subject: [PATCH 77/94] chore(porch): 1951 acknowledge context refresh --- codev/projects/1951-read-only-pr-check-for-archite/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 37383727d..9d2d64946 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -126,7 +126,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter3-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T18:44:02.801Z' +updated_at: '2026-11-24T18:45:52.618Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -148,6 +148,7 @@ context_refreshes: acknowledged_at: '2026-11-24T02:33:21.252Z' - boundary: plan-phase:docs_guidance at: '2026-11-24T18:44:02.801Z' + acknowledged_at: '2026-11-24T18:45:52.617Z' force_advanced: phase: check_worktree iteration: 3 From f93aa60e1bb362af10dfa9b32e2e1aa3756b3fbf Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 10:59:36 -0800 Subject: [PATCH 78/94] [Spec 1951][Phase: docs_guidance] fix: one spawn-entry rule for cleanup and check worktree; path spellings - Move the read-only "is this entry one spawn made" rule (isSpawnMade, linkAt, realPath, comparablePath) from commands/check/worktree.ts into agent-farm/lib/builder-scaffold.ts, so afx cleanup and codev check worktree import one rule (claude iter3 note 3). Cleanup's informational dirty notice no longer counts a spawn symlink, hard link or unchanged copy that git does not ignore; a changed copy still counts. hasUncommittedChanges takes the main checkout root. builder-scaffold.ts now reads the file system (never writes or spawns): the imports auditor holds a pure module's node:fs import to the read-only names. - resolveTarget: derive the builder id for a path argument from real paths, not by comparing two git-listed spellings as they stand. - Windows: the fixture root is fs.realpathSync.native, so expectations use the long path git and the code print, not the runner's 8.3 short name (run 45462452355, 9 failures, all fixture-side). - Tests on every platform (a junction on Windows): the same repository reached through a symlinked parent directory gives the same check worktree and check pr reports as through its real path. --- .../spec-1951-builder-scaffold.test.ts | 62 ++++++++++--- .../codev/src/agent-farm/commands/cleanup.ts | 33 +++++-- .../src/agent-farm/lib/builder-scaffold.ts | 79 ++++++++++++++-- .../check/__tests__/check-pr-readonly.test.ts | 21 ++++- .../check/__tests__/check-worktree.test.ts | 53 ++++++++++- .../check/__tests__/helpers/git-fixture.ts | 26 +++++- .../commands/check/__tests__/imports.test.ts | 15 ++-- packages/codev/src/commands/check/worktree.ts | 89 +++---------------- 8 files changed, 266 insertions(+), 112 deletions(-) diff --git a/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts index e0e759194..17d67367b 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts @@ -6,10 +6,12 @@ * Evidence for the fix: cleanup reported "1 uncommitted file(s)" for two bugfix builders that * had nothing uncommitted. The one file was the write guard's `.claude/hooks/` directory, * which `git status --porcelain` lists as a directory and the old `.builder-` regex missed. + * The notice also leaves out the entries spawn linked in from the main checkout, by the rule + * the check uses (`isSpawnMade`). */ import { execFileSync } from 'node:child_process'; -import { lstatSync, mkdirSync, mkdtempSync, readdirSync, readlinkSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { linkSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readlinkSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { dirname, join, relative, resolve, sep } from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; @@ -102,45 +104,85 @@ describe('Spec 1951 — keep-list.ts is the one definition keep-files.ts uses', }); describe('Spec 1951 — afx cleanup: hasUncommittedChanges and the scaffold (main-36)', () => { + let base: string; + let main: string; let worktree: string; const git = (...args: string[]) => execFileSync('git', ['-c', 'user.email=t@t', '-c', 'user.name=t', ...args], { cwd: worktree, stdio: 'pipe' }); - const write = (rel: string, content = `${rel}\n`): void => { - mkdirSync(dirname(join(worktree, rel)), { recursive: true }); - writeFileSync(join(worktree, rel), content); + const write = (rel: string, content = `${rel}\n`, root = worktree): void => { + mkdirSync(dirname(join(root, rel)), { recursive: true }); + writeFileSync(join(root, rel), content); }; beforeEach(() => { - worktree = realpathSync(mkdtempSync(join(tmpdir(), 'spec-1951-scaffold-'))); + base = realpathSync(mkdtempSync(join(tmpdir(), 'spec-1951-scaffold-'))); + main = join(base, 'main'); + worktree = join(base, 'wt'); + mkdirSync(main); + mkdirSync(worktree); git('init', '-q'); write('src/tracked.ts'); git('add', '.'); git('commit', '-qm', 'init'); for (const rel of ['.builder-prompt.txt', '.builder-role.md', '.builder-start.sh', GUARD_SCRIPT_RELPATH, GUARD_SETTINGS_RELPATH]) write(rel); + write('shared/data.json', '{"from":"main"}\n', main); }); afterEach(() => { - rmSync(worktree, { recursive: true, force: true }); + rmSync(base, { recursive: true, force: true }); }); it('only scaffold files, the write guard included: not dirty', async () => { - expect(await hasUncommittedChanges(worktree)).toEqual({ dirty: false, scaffoldOnly: true, details: '' }); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: false, scaffoldOnly: true, details: '' }); }); it('a clean worktree: not dirty, not scaffold-only', async () => { rmSync(join(worktree, '.claude'), { recursive: true }); for (const rel of ['.builder-prompt.txt', '.builder-role.md', '.builder-start.sh']) rmSync(join(worktree, rel)); - expect(await hasUncommittedChanges(worktree)).toEqual({ dirty: false, scaffoldOnly: false, details: '' }); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: false, scaffoldOnly: false, details: '' }); }); it('another file next to the write guard is dirty, counted by itself', async () => { write('.claude/hooks/mine.cjs'); - expect(await hasUncommittedChanges(worktree)).toEqual({ dirty: true, scaffoldOnly: false, details: '1 uncommitted file(s)' }); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: true, scaffoldOnly: false, details: '1 uncommitted file(s)' }); }); it('a modified tracked file is dirty, whatever the scaffold', async () => { write('src/tracked.ts', 'changed\n'); write('notes.md'); - expect(await hasUncommittedChanges(worktree)).toEqual({ dirty: true, scaffoldOnly: false, details: '2 uncommitted file(s)' }); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: true, scaffoldOnly: false, details: '2 uncommitted file(s)' }); + }); + + // The same rule `codev check worktree` uses (isSpawnMade): an entry spawn linked in from the + // main checkout that git does not ignore is scaffold, however spawn had to make it. + describe('entries spawn linked in from the main checkout', () => { + it.skipIf(process.platform === 'win32')('a symbolic link to the same path in the main checkout: not counted', async () => { + mkdirSync(join(worktree, 'shared')); + symlinkSync(spawnLinkTarget(main, 'shared/data.json'), join(worktree, 'shared/data.json')); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: false, scaffoldOnly: true, details: '' }); + }); + + it('a hard link of the main checkout\'s file: not counted', async () => { + mkdirSync(join(worktree, 'shared')); + linkSync(join(main, 'shared/data.json'), join(worktree, 'shared/data.json')); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: false, scaffoldOnly: true, details: '' }); + }); + + it('an unchanged copy: not counted', async () => { + write('shared/data.json', '{"from":"main"}\n'); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: false, scaffoldOnly: true, details: '' }); + }); + + it('a changed copy is data: counted', async () => { + write('shared/data.json', '{"from":"the builder"}\n'); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: true, scaffoldOnly: false, details: '1 uncommitted file(s)' }); + }); + + it.skipIf(process.platform === 'win32')('a link at that path pointing anywhere else is data: counted', async () => { + write('elsewhere.json', '{"from":"main"}\n', base); + mkdirSync(join(worktree, 'shared')); + symlinkSync(join(base, 'elsewhere.json'), join(worktree, 'shared/data.json')); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: true, scaffoldOnly: false, details: '1 uncommitted file(s)' }); + }); }); }); diff --git a/packages/codev/src/agent-farm/commands/cleanup.ts b/packages/codev/src/agent-farm/commands/cleanup.ts index 4956e570d..e99168643 100644 --- a/packages/codev/src/agent-farm/commands/cleanup.ts +++ b/packages/codev/src/agent-farm/commands/cleanup.ts @@ -29,7 +29,7 @@ import { sameWindowsPath } from '../../lib/platform/windows/host-paths.js'; import { unquoteWindowsCommandLine } from '../../lib/platform/windows/command-line.js'; import { loadConfig } from '../../lib/config.js'; import { AGENT_FARM_DIR } from '../lib/tower-client.js'; -import { isBuilderScaffold } from '../lib/builder-scaffold.js'; +import { isBuilderScaffold, isSpawnMade, linkAt } from '../lib/builder-scaffold.js'; import { keepFiles, keepPatterns, keptDirFor, listKeepCandidates } from '../lib/keep-files.js'; /** @@ -186,11 +186,16 @@ export interface CleanupOptions { } /** - * Check if a worktree has uncommitted changes - * Returns: dirty (has real changes), scaffoldOnly (only has spawn's scaffold files, - * `isBuilderScaffold()`: `.builder-*` and the write guard's files) + * Check if a worktree has uncommitted changes. + * Returns: dirty (has real changes), scaffoldOnly (only spawn's scaffold: the files + * `isBuilderScaffold()` names, and the entries spawn linked in from the main checkout at + * `mainRoot` that git does not ignore, `isSpawnMade()`). The same rule `codev check worktree` + * uses, so the two agree on what is scaffold. */ -export async function hasUncommittedChanges(worktreePath: string): Promise<{ dirty: boolean; scaffoldOnly: boolean; details: string }> { +export async function hasUncommittedChanges( + worktreePath: string, + mainRoot: string, +): Promise<{ dirty: boolean; scaffoldOnly: boolean; details: string }> { if (!existsSync(worktreePath)) { return { dirty: false, scaffoldOnly: false, details: '' }; } @@ -201,9 +206,9 @@ export async function hasUncommittedChanges(worktreePath: string): Promise<{ dir const result = await run('git status --porcelain --untracked-files=all', { cwd: worktreePath }); if (result.stdout.trim()) { - // Count changed files, excluding builder scaffold files (only ever untracked) + // Count changed files, excluding spawn's scaffold (only ever untracked) const allLines = result.stdout.trim().split('\n').filter(Boolean); - const nonScaffoldLines = allLines.filter((line) => !(line.startsWith('?? ') && isBuilderScaffold(line.slice(3)))); + const nonScaffoldLines = allLines.filter((line) => !(line.startsWith('?? ') && isSpawnScaffold(mainRoot, worktreePath, line.slice(3)))); if (nonScaffoldLines.length > 0) { return { @@ -226,6 +231,18 @@ export async function hasUncommittedChanges(worktreePath: string): Promise<{ dir } } +/** + * Whether an untracked entry is spawn's scaffold. An entry that cannot be read (a path git + * printed quoted, say) is counted as a real change: the notice errs toward "dirty". + */ +function isSpawnScaffold(mainRoot: string, worktreePath: string, rel: string): boolean { + if (isBuilderScaffold(rel)) return true; + const link = linkAt(worktreePath, rel); + if (!link.ok) return false; + const made = isSpawnMade(mainRoot, worktreePath, rel, link.value); + return made.ok && made.value; +} + /** * Delete a remote branch */ @@ -386,7 +403,7 @@ async function cleanupBuilder( // Check for uncommitted changes (informational - worktree is preserved) if (!isShellMode) { - const { dirty, details } = await hasUncommittedChanges(builder.worktree); + const { dirty, details } = await hasUncommittedChanges(builder.worktree, config.workspaceRoot); if (dirty) { logger.info(`Worktree has uncommitted changes: ${details}`); } diff --git a/packages/codev/src/agent-farm/lib/builder-scaffold.ts b/packages/codev/src/agent-farm/lib/builder-scaffold.ts index 9f7926b66..c2f985566 100644 --- a/packages/codev/src/agent-farm/lib/builder-scaffold.ts +++ b/packages/codev/src/agent-farm/lib/builder-scaffold.ts @@ -1,7 +1,7 @@ /** * The files `afx spawn` writes into a builder worktree that are not the builder's work - * (Spec 1951). Pure, so `afx cleanup` and `codev check worktree` share one list and agree on - * what is scaffold: + * (Spec 1951). One rule, so `afx cleanup` and `codev check worktree` agree on what is + * scaffold: * * - any root-level `.builder-*` file (the prompt, role, start script, session id, and the * refresh state files, whose names keep that prefix so they classify as scaffold); @@ -13,11 +13,14 @@ * * Spawn also links files from the main checkout into the worktree (`symlinkConfigFiles`): the * root `.env` and `.codev/config.json` always, and every `worktree.symlinks` entry. Each such - * link points at the same path in the main checkout, so a link of that shape is scaffold - * whichever entry made it: removing it loses nothing (`spawnLinkTarget`). + * link points at the same path in the main checkout, so an entry of that shape is scaffold + * whichever entry made it: removing it loses nothing (`isSpawnMade`). + * + * The module reads the file system and never writes to it or spawns anything. */ -import { join } from 'node:path'; +import { lstatSync, readFileSync, readlinkSync, realpathSync, statSync } from 'node:fs'; +import { basename, dirname, join, resolve } from 'node:path'; import { GUARD_SCRIPT_RELPATH, GUARD_SETTINGS_RELPATH } from '../utils/worktree-write-guard.js'; /** Worktree-relative path of the OpenCode harness's role-injection file. */ @@ -40,3 +43,69 @@ export function isBuilderScaffold(path: string): boolean { export function spawnLinkTarget(mainRoot: string, path: string): string { return join(mainRoot, ...path.split('/')); } + +/** A read that worked, or why it did not. */ +export type ScaffoldLookup = { ok: true; value: T } | { ok: false; reason: string }; + +/** A symbolic link: its target as written, where that points, and whether anything is there. */ +export interface WorktreeLink { + target: string; + resolved: string; + missing: boolean; +} + +/** A real path for comparison (long names, on-disk case on Windows), or null when it does not exist. */ +export function realPath(p: string): string | null { + try { + const real = realpathSync.native(p); + return process.platform === 'win32' ? real.toLowerCase() : real; + } catch { + return null; + } +} + +/** A path spelled for comparison: its real path, or, when it does not exist, its parent's. */ +export function comparablePath(p: string): string { + const real = realPath(p); + if (real !== null) return real; + const parent = realPath(dirname(p)); + const spelled = parent === null ? resolve(p) : join(parent, basename(p)); + return process.platform === 'win32' ? spelled.toLowerCase() : spelled; +} + +/** The link at a worktree-relative, `/`-separated path, or null when the path is not a link. */ +export function linkAt(worktree: string, rel: string): ScaffoldLookup { + const abs = join(worktree, ...rel.split('/')); + try { + if (!lstatSync(abs).isSymbolicLink()) return { ok: true, value: null }; + const target = readlinkSync(abs); + const resolved = resolve(dirname(abs), target); + return { ok: true, value: { target, resolved, missing: realPath(resolved) === null } }; + } catch (err) { + return { ok: false, reason: `could not read ${rel}: ${err instanceof Error ? err.message : String(err)}` }; + } +} + +/** + * Whether the entry at `rel` is one spawn made, so removing it loses nothing. Spawn links each + * entry to the same path in the main checkout: a symbolic link where it may make one, else, on + * native Windows, a hard link of that file, else a copy (`createWorktreeLink`). A copy counts + * only while its bytes still equal the main checkout's file: one that has changed is data. + * `link` is `linkAt(worktree, rel)`'s value. + */ +export function isSpawnMade(mainRoot: string, worktree: string, rel: string, link: WorktreeLink | null): ScaffoldLookup { + const source = spawnLinkTarget(mainRoot, rel); + if (link !== null) return { ok: true, value: comparablePath(link.resolved) === comparablePath(source) }; + const abs = join(worktree, ...rel.split('/')); + try { + const main = statSync(source, { bigint: true, throwIfNoEntry: false }); + if (main === undefined || !main.isFile()) return { ok: true, value: false }; + const mine = statSync(abs, { bigint: true }); + if (!mine.isFile()) return { ok: true, value: false }; + if (mine.dev === main.dev && mine.ino === main.ino) return { ok: true, value: true }; + if (mine.size !== main.size) return { ok: true, value: false }; + return { ok: true, value: readFileSync(abs).equals(readFileSync(source)) }; + } catch (err) { + return { ok: false, reason: `could not compare ${rel} with the main checkout's: ${err instanceof Error ? err.message : String(err)}` }; + } +} diff --git a/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts b/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts index 217d3208f..60e933060 100644 --- a/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts @@ -16,7 +16,7 @@ import { checkPr } from '../pr.js'; import type { Check, CommandOptions, ErrorReport, PrReport } from '../report.js'; import type { SpawnFn } from '../runner.js'; import { useFakeHome } from './helpers/fake-home.js'; -import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { createFixture, linkedSpelling, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; import { commitChecksOverride, otherClone, @@ -155,6 +155,25 @@ describe('Spec 1951 — check pr on real repositories', { timeout: 30_000 }, () expect(withoutTime(fromSubdirectory)).toEqual(withoutTime(fromMain)); }); + it('reached through a symlinked parent directory, it reports the same as through the real path', async () => { + const { dir, head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + configure(); + const link = linkedSpelling(fx); + try { + expect(fs.realpathSync.native(link.via(dir))).toBe(dir); + const fromMain = await runReport(); + const fromWorktreeByLink = await runReport({ cwd: link.via(dir) }); + const fromMainByLink = await runReport({ cwd: link.via(fx.main) }); + + expect(fromMain.verdict).toBe('clear'); + expect(withoutTime(fromWorktreeByLink)).toEqual(withoutTime(fromMain)); + expect(withoutTime(fromMainByLink)).toEqual(withoutTime(fromMain)); + } finally { + link.remove(); + } + }); + it('Scenario 11: a head that moves during the run needs attention, naming both SHAs', async () => { const { dir, head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); const next = fx.commit(dir, { 'b.txt': 'b\n' }, 'b'); diff --git a/packages/codev/src/commands/check/__tests__/check-worktree.test.ts b/packages/codev/src/commands/check/__tests__/check-worktree.test.ts index 20fde86b2..8968065ee 100644 --- a/packages/codev/src/commands/check/__tests__/check-worktree.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-worktree.test.ts @@ -19,7 +19,7 @@ import type { Check, CommandOptions, ErrorReport, Status, WorktreeReport } from import type { SpawnFn } from '../runner.js'; import { checkWorktree, parseStatus, pickPr, removability, renderWorktreeHuman } from '../worktree.js'; import { useFakeHome } from './helpers/fake-home.js'; -import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { createFixture, linkedSpelling, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; import { prViewOverride, writeConfig, type PrViewOverride } from './helpers/pr-fixture.js'; import { expectWorktreeReportShape } from './helpers/report-shape.js'; import { @@ -154,7 +154,7 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, expect(report).toMatchObject({ verdict: 'clear', removable: 'removable', - worktree: { path: fs.realpathSync(b.dir), builderId: 'spir-8', branch: b.branch, baseRef: 'main', baseTip: main }, + worktree: { path: fs.realpathSync.native(b.dir), builderId: 'spir-8', branch: b.branch, baseRef: 'main', baseTip: main }, }); expect(byId(report, 'uncommitted')).toMatchObject({ status: 'ok', details: { files: [], scaffold: SCAFFOLD_SORTED } }); expect(byId(report, 'commits')).toMatchObject({ status: 'ok', details: { total: 0, notOnBase: [], unsafe: [] } }); @@ -681,6 +681,51 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, for (const r of [fromOther, byRelative, byAbsolute, fromItself]) expect(withoutTime(r.report)).toEqual(withoutTime(fromMain.report)); }); + // Every comparison of two spellings of one directory goes through real paths: the target + // lookup (resolveTarget), "is it under .builders", "is it the main checkout", and spawn's + // link shape (isSpawnMade). A user whose directory is spelled differently from git's sees + // the same verdicts. + it('reached through a symlinked parent directory, every way of naming the builder gives the same report as the real path', async () => { + configure({ cleanup: { keepIgnored: ['.env*'] } }); + fs.mkdirSync(path.join(fx.main, '.git', 'info'), { recursive: true }); + fs.appendFileSync(path.join(fx.main, '.git', 'info', 'exclude'), '.env*\n'); + fs.writeFileSync(path.join(fx.main, '.env'), 'A=1\n'); + const link = linkedSpelling(fx); + try { + const b = addBuilder(fx, 'spir-8'); + const via = link.via; + expect(via(b.dir)).not.toBe(b.dir); + expect(fs.realpathSync.native(via(b.dir))).toBe(b.dir); + // Spawn links `.env` to the main checkout as its workspace root spells it: here, through the link. + if (isWindows) fs.linkSync(path.join(fx.main, '.env'), path.join(b.dir, '.env')); + else fs.symlinkSync(via(spawnLinkTarget(fx.main, '.env')), path.join(b.dir, '.env')); + mergeBuilder(fx, b); + prIs(b, 8, 'MERGED'); + + const real = await runReport('spir-8', { inspected: b.dir }); + const reports = [ + await runReport('spir-8', { cwd: via(fx.main), inspected: b.dir }), + await runReport(path.join('.builders', 'spir-8'), { cwd: via(fx.main), inspected: b.dir }), + await runReport(via(b.dir), { inspected: b.dir }), + await runReport('.', { cwd: via(b.dir), inspected: b.dir }), + ]; + + expect(real.exitCode).toBe(0); + expect(real.report.removable).toBe('removable'); + expect(real.report.worktree).toMatchObject({ path: b.dir, builderId: 'spir-8' }); + expect(byId(real.report, 'ignored')).toMatchObject({ status: 'ok', details: { keep: [], links: [], scaffold: ['.env'] } }); + for (const r of reports) { + expect(r.exitCode).toBe(real.exitCode); + expect(withoutTime(r.report)).toEqual(withoutTime(real.report)); + } + const mainByLink = await checkWorktree(via(fx.main), { cwd: fx.main, env: fx.env, timeoutMs: 20_000 }); + expect(mainByLink.exitCode).toBe(2); + expect((mainByLink.report as ErrorReport).error.message).toBe(`${fx.main} is the main worktree, not a builder's`); + } finally { + link.remove(); + } + }); + it('a worktree outside .builders/ is reported by its path, with no builder id', async () => { configure(); const dir = path.join(fx.root, 'elsewhere'); @@ -689,8 +734,8 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, const { report } = await runReport(dir, { inspected: dir }); - expect(report.worktree).toMatchObject({ path: fs.realpathSync(dir), builderId: null, branch: 'feature/x' }); - expect(renderWorktreeHuman(report)).toContain(`worktree ${fs.realpathSync(dir)} branch feature/x`); + expect(report.worktree).toMatchObject({ path: fs.realpathSync.native(dir), builderId: null, branch: 'feature/x' }); + expect(renderWorktreeHuman(report)).toContain(`worktree ${fs.realpathSync.native(dir)} branch feature/x`); }); describe('Scenario 21: exit 2', () => { diff --git a/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts b/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts index a02d3c970..8b3613013 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts @@ -45,7 +45,9 @@ export interface Fixture { } export function createFixture(): Fixture { - const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'codev-check-'))); + // The native real path: on Windows `os.tmpdir()` may be an 8.3 short name (`RUNNER~1`) that + // only the native call expands, and git and the code under test print the long one. + const root = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'codev-check-'))); const emptyConfig = path.join(root, 'gitconfig'); fs.writeFileSync(emptyConfig, '[user]\n\tname = Fixture\n\temail = fixture@example.invalid\n[init]\n\tdefaultBranch = main\n'); const env: Record = { @@ -103,6 +105,28 @@ export function createFixture(): Fixture { }; } +/** + * The fixture reached by another spelling of the same directories: a directory link (a + * junction on Windows, which needs no privilege) made under `os.tmpdir()` as the OS spells it, + * not as its real path (`/var/folders/…` on macOS, an 8.3 short name on a Windows runner). + * `via(p)` spells a path under the fixture root through the link. `remove()` deletes the link + * only, never what it points at. + */ +export function linkedSpelling(fixture: Fixture): { via: (p: string) => string; remove: () => void } { + const link = path.join(os.tmpdir(), `${path.basename(fixture.root)}-via`); + fs.symlinkSync(fixture.root, link, 'junction'); + return { + via(p) { + const rel = path.relative(fixture.root, p); + if (rel.startsWith('..') || path.isAbsolute(rel)) throw new Error(`${p} is not under ${fixture.root}`); + return path.join(link, rel); + }, + remove() { + fs.unlinkSync(link); + }, + }; +} + export interface RepoState { refs: string; head: string; diff --git a/packages/codev/src/commands/check/__tests__/imports.test.ts b/packages/codev/src/commands/check/__tests__/imports.test.ts index 0b0dc86ce..fc27ac27c 100644 --- a/packages/codev/src/commands/check/__tests__/imports.test.ts +++ b/packages/codev/src/commands/check/__tests__/imports.test.ts @@ -37,19 +37,20 @@ const ALLOWED: Record = { reason: "#1950's keep list as pure definitions, shared with afx cleanup --keep-ignored (audited below)", }, '../../agent-farm/lib/builder-scaffold.js': { - names: ['isBuilderScaffold', 'spawnLinkTarget'], - reason: "spawn's scaffold files and the shape of its links, pure, shared with afx cleanup (audited below)", + names: ['comparablePath', 'isBuilderScaffold', 'isSpawnMade', 'linkAt', 'realPath'], + reason: "spawn's scaffold files and the entries it links in, one rule shared with afx cleanup; read-only (audited below)", }, }; /** * The modules outside this directory that the check commands import, and everything each may - * import in turn: none of them spawns or does I/O. `scriptText` is a script a module only - * emits as text; a `require` that appears in it is not the module's own. + * import in turn: none of them spawns or writes. A `node:fs` import is held to the read-only + * names ALLOWED lists. `scriptText` is a script a module only emits as text; a `require` that + * appears in it is not the module's own. */ const PURE_MODULES: Record = { '../../agent-farm/lib/keep-list.ts': { imports: [] }, - '../../agent-farm/lib/builder-scaffold.ts': { imports: ['node:path', '../utils/worktree-write-guard.js'] }, + '../../agent-farm/lib/builder-scaffold.ts': { imports: ['node:fs', 'node:path', '../utils/worktree-write-guard.js'] }, '../../agent-farm/utils/worktree-write-guard.ts': { imports: ['node:path'], scriptText: WORKTREE_WRITE_GUARD_SCRIPT }, }; @@ -149,6 +150,10 @@ describe('Spec 1951 — audited imports in commands/check/', () => { const own = dynamic.filter((d) => !rule.scriptText?.includes(d.replace(/^(\w+)\((.*)\)$/, "$1('$2')"))); expect(own, file).toEqual([]); expect(imports.filter((i) => !i.typeOnly).map((i) => i.specifier)).toEqual(rule.imports); + for (const imp of imports.filter((i) => !i.typeOnly && i.specifier === 'node:fs')) { + expect(imp.names, `${file} imports node:fs as a namespace`).not.toBe('*'); + for (const name of imp.names as string[]) expect(ALLOWED['node:fs'].names, `${file} imports ${name} from node:fs`).toContain(name); + } }); it('only index.ts imports commander', () => { diff --git a/packages/codev/src/commands/check/worktree.ts b/packages/codev/src/commands/check/worktree.ts index 54c454626..42a5a577c 100644 --- a/packages/codev/src/commands/check/worktree.ts +++ b/packages/codev/src/commands/check/worktree.ts @@ -21,9 +21,9 @@ * resolved against the main checkout, so the command reads the same from any worktree. */ -import { lstatSync, readFileSync, readlinkSync, realpathSync, statSync } from 'node:fs'; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'; -import { isBuilderScaffold, spawnLinkTarget } from '../../agent-farm/lib/builder-scaffold.js'; +import { comparablePath, isBuilderScaffold, isSpawnMade, linkAt, realPath } from '../../agent-farm/lib/builder-scaffold.js'; +import type { WorktreeLink } from '../../agent-farm/lib/builder-scaffold.js'; import { isNeverKeep } from '../../agent-farm/lib/keep-list.js'; import { ancestry, @@ -75,7 +75,7 @@ function splitNul(output: string): string[] { // ============================================================================= interface Target { - /** Real path. */ + /** The path as `git worktree list` gives it. Every comparison uses real paths (`realPath`). */ path: string; builderId: string | null; branch: string; @@ -83,16 +83,6 @@ interface Target { tip: string; } -/** A real path for comparison (long names, on-disk case on Windows), or null when it does not exist. */ -function realPath(p: string): string | null { - try { - const real = realpathSync.native(p); - return process.platform === 'win32' ? real.toLowerCase() : real; - } catch { - return null; - } -} - /** A builder id is a bare name; anything with a separator, or `.`/`..`, is a path. */ function isPathArgument(raw: string): boolean { return raw === '.' || raw === '..' || raw.includes('/') || raw.includes('\\') || isAbsolute(raw); @@ -133,7 +123,7 @@ async function resolveTarget(runner: Runner, roots: Roots, argument: TargetArgum if (!isRefName(entry.branch)) throw new CheckCommandError(`${entry.path} is on branch ${JSON.stringify(entry.branch)}, which codev check cannot pass to git`); if (entry.head === null || !isFullSha(entry.head)) throw new CheckCommandError(`git worktree list gave no commit for ${entry.path}`); - if (builderId === null && dirname(entry.path) === join(main.path, '.builders')) builderId = basename(entry.path); + if (builderId === null && dirname(wanted) === realPath(join(main.path, '.builders'))) builderId = basename(entry.path); return { path: entry.path, builderId, branch: entry.branch, tip: entry.head }; } @@ -265,68 +255,11 @@ async function revList(runner: Runner, args: string[]): Promise return { ok: true, value: shas }; } -/** A symbolic link: its target as written, where that points, and whether anything is there. */ -interface Link { - target: string; - resolved: string; - missing: boolean; -} - -/** The link at a worktree-relative path, or null when the path is not a link. */ -function linkAt(facts: Facts, rel: string): Lookup { - const abs = join(facts.target.path, ...rel.split('/')); - try { - if (!lstatSync(abs).isSymbolicLink()) return { ok: true, value: null }; - const target = readlinkSync(abs); - const resolved = resolve(dirname(abs), target); - return { ok: true, value: { target, resolved, missing: realPath(resolved) === null } }; - } catch (err) { - return { ok: false, reason: `could not read ${rel}: ${err instanceof Error ? err.message : String(err)}` }; - } -} - -/** A path spelled for comparison: its real path, or, when it does not exist, its parent's. */ -function comparable(p: string): string { - const real = realPath(p); - if (real !== null) return real; - const parent = realPath(dirname(p)); - const spelled = parent === null ? resolve(p) : join(parent, basename(p)); - return process.platform === 'win32' ? spelled.toLowerCase() : spelled; -} - -/** Whether a link is one spawn made: it points at the same path in the main checkout. */ -function isSpawnLink(facts: Facts, rel: string, link: Link): boolean { - return comparable(link.resolved) === comparable(spawnLinkTarget(facts.mainRoot, rel)); -} - -/** - * Whether the entry at `rel` is one spawn made, so removing it loses nothing. Spawn links each - * entry to the same path in the main checkout: a symbolic link where it may make one, else, on - * native Windows, a hard link of that file, else a copy (`createWorktreeLink`). A copy counts - * only while its bytes still equal the main checkout's file: one that has changed is data. - */ -function isSpawnMade(facts: Facts, rel: string, link: Link | null): Lookup { - if (link !== null) return { ok: true, value: isSpawnLink(facts, rel, link) }; - const source = spawnLinkTarget(facts.mainRoot, rel); - const abs = join(facts.target.path, ...rel.split('/')); - try { - const main = statSync(source, { bigint: true, throwIfNoEntry: false }); - if (main === undefined || !main.isFile()) return { ok: true, value: false }; - const mine = statSync(abs, { bigint: true }); - if (!mine.isFile()) return { ok: true, value: false }; - if (mine.dev === main.dev && mine.ino === main.ino) return { ok: true, value: true }; - if (mine.size !== main.size) return { ok: true, value: false }; - return { ok: true, value: readFileSync(abs).equals(readFileSync(source)) }; - } catch (err) { - return { ok: false, reason: `could not compare ${rel} with the main checkout's: ${err instanceof Error ? err.message : String(err)}` }; - } -} - /** The worktree-relative path a link resolves to, or null when it resolves outside the worktree or to nothing. */ -function insideTarget(facts: Facts, link: Link): string | null { +function insideTarget(facts: Facts, link: WorktreeLink): string | null { const real = realPath(link.resolved); if (real === null) return null; - const rel = relative(comparable(facts.target.path), real); + const rel = relative(comparablePath(facts.target.path), real); if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) return null; return rel.split(sep).join('/'); } @@ -351,9 +284,9 @@ async function checkUncommitted(facts: Facts): Promise { if (e.change === 'untracked') { isScaffold = isBuilderScaffold(e.path); if (!isScaffold) { - const link = linkAt(facts, e.path); + const link = linkAt(facts.target.path, e.path); if (!link.ok) return notRun('uncommitted', link.reason); - const made = isSpawnMade(facts, e.path, link.value); + const made = isSpawnMade(facts.mainRoot, facts.target.path, e.path, link.value); if (!made.ok) return notRun('uncommitted', made.reason); isScaffold = made.value; } @@ -459,11 +392,11 @@ async function checkIgnored(facts: Facts, patterns: readonly string[]): Promise< const result = await gitIn(facts, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z', ...pathspecs]); if (result.exitCode !== 0) return notRun('ignored', failureReason('ls-files', result, facts.runner.timeoutLabel)); matched = splitNul(result.stdout).filter((p) => !isNeverKeep(p)); - const linked: Array<[string, Link]> = []; + const linked: Array<[string, WorktreeLink]> = []; for (const p of matched) { - const link = linkAt(facts, p); + const link = linkAt(facts.target.path, p); if (!link.ok) return notRun('ignored', link.reason); - const made = isSpawnMade(facts, p, link.value); + const made = isSpawnMade(facts.mainRoot, facts.target.path, p, link.value); if (!made.ok) return notRun('ignored', made.reason); if (made.value) scaffold.push(p); else if (link.value === null) keep.push(p); From 827eed9d4abf650dd136de48c54910a04f5ce427 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 11:10:47 -0800 Subject: [PATCH 79/94] [Spec 1951][Phase: docs_guidance] docs: architect guidance and codev check reference MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Architect role (both trees): run `codev check pr` before choosing review depth (mechanics; consult --type integration reviews content), again before a merge word with its verdict line in the PRFT Testing paragraph; new "Closing the loop": `codev check deploy` after merges, `codev check worktree` before afx cleanup. REMOVABLE means no data would be lost, not that the builder is finished. - risk-triage Step 1 and the workflow reference (both trees) start from `codev check pr`. Fixed in place: `gh pr diff --stat` does not exist; Step 1 now names `gh pr view --json additions,deletions,changedFiles` and `gh pr diff --name-only`, and the worked examples use `git diff --stat origin/main...origin/`. - codev.md (both trees): the three subcommands with samples pasted from real runs, statuses, exit codes, check ids, configuration (check.* and cleanup.keepIgnored, `:(glob)` pathspecs), forges, the only writes (object-store additions), the trust boundary (a project's own concept overrides, the user's merge drivers), and the JSON reports as shipped: nullable pr.baseTip and worktree.baseRef/baseTip, commits.unsafe, ignored.links/scaffold, what `regenerable` counts, spawn's entries as scaffold, links among keep-list files, checks.lastCodeCommit null, head.relation, forge.reviewDecision, linked-issue.references. - overview.md rows (both trees); the codev skill in four copies (hashes regenerated); the forge skill gains commit-checks and workflow-runs; arch.md Core Components §9. - Thread log: Phase 7. --- .claude/skills/codev/SKILL.md | 30 +- .claude/skills/forge/SKILL.md | 4 + .codex/skills/codev/SKILL.md | 30 +- .codex/skills/forge/SKILL.md | 4 + codev-skeleton/.claude/skills/codev/SKILL.md | 30 +- codev-skeleton/.codex/skills/codev/SKILL.md | 30 +- codev-skeleton/resources/commands/codev.md | 339 +++++++++++++++++- codev-skeleton/resources/commands/overview.md | 3 + codev-skeleton/resources/risk-triage.md | 19 +- .../resources/workflow-reference.md | 4 +- codev-skeleton/roles/architect.md | 31 ++ codev/resources/arch.md | 12 + codev/resources/commands/codev.md | 339 +++++++++++++++++- codev/resources/commands/overview.md | 3 + codev/resources/risk-triage.md | 19 +- codev/resources/workflow-reference.md | 3 +- codev/roles/architect.md | 31 ++ codev/state/spir-1951_thread.md | 38 ++ .../codev/src/lib/shipped-skill-hashes.ts | 2 + 19 files changed, 952 insertions(+), 19 deletions(-) diff --git a/.claude/skills/codev/SKILL.md b/.claude/skills/codev/SKILL.md index fb27e3230..1e56f0a98 100644 --- a/.claude/skills/codev/SKILL.md +++ b/.claude/skills/codev/SKILL.md @@ -1,6 +1,6 @@ --- name: codev -description: Codev project management CLI — init, adopt, bootstrap-docs, update, and doctor commands. Check this skill before running any `codev` command (except `consult`, `porch`, or `afx` which have their own skills). Use when setting up new projects, adding codev to existing repos, updating framework files, or diagnosing missing dependencies. +description: Codev project management CLI — init, adopt, bootstrap-docs, update, doctor, and the read-only check commands (check pr, check deploy, check worktree). Check this skill before running any `codev` command (except `consult`, `porch`, or `afx` which have their own skills). Use when setting up new projects, adding codev to existing repos, updating framework files, diagnosing missing dependencies, checking whether a PR is ready to merge, whether merged PRs reached the deploy branch, or whether a builder worktree can be removed. --- # codev - Project Management CLI @@ -13,6 +13,9 @@ codev adopt Add codev to the current directory codev bootstrap-docs Draft the governance docs from this codebase codev update Update protocols, roles, skills from package codev doctor Check system dependencies +codev check pr Read-only: is PR N ready to recommend for merge +codev check deploy ... Read-only: did merged PRs reach the deploy branch +codev check worktree Read-only: would removing a builder worktree lose data ``` ## codev init @@ -63,6 +66,31 @@ Checks dependencies: Node.js (>=22), git (>=2.5), your forge's CLI and its auth codev doctor ``` +## codev check + +Read-only: never merges, pushes, comments, deletes or moves a ref. Verdict on the first line, +then one line per check (`ok`, `ATTN`, `info`, `not run`, `off`, `skip`). Exit 0 clear, 1 +something needs attention (a check that could not run counts), 2 the command failed. Works +from the main checkout or any builder worktree. + +```bash +codev check pr 42 # before recommending a merge: head, state, mergeability, + # trial merge, CI on the code, attribution, watched files, + # linked issue, size, files to read +codev check deploy 42 43 # after merging: on the deploy branch, in the latest green deploy run +codev check worktree spir-42 # before afx cleanup: would removal lose data +codev check worktree .builders/spir-42 --json # a path works too; --json for agents +``` + +- Run `codev check pr` before `consult --type integration`: it checks mechanics, the + consultation reviews content. +- `REMOVABLE` means no data would be lost, not that the builder is finished: an open PR is + its own `ATTN` line and makes the exit 1. +- Configuration lives under `check.*` in `.codev/config.json` (`attribution`, `watch`, `flag`, + `notForReading`, `deploy.branch`, `deploy.workflow`, `skip`); the keep list is + `cleanup.keepIgnored`. A bad value is exit 2 naming the key and the file. `codev check --help` + and `codev check --help` list the subcommands and options. + ## Common mistakes - There is NO `codev tower` command — use `afx tower start/stop` diff --git a/.claude/skills/forge/SKILL.md b/.claude/skills/forge/SKILL.md index be8fcf3df..be82e3d08 100644 --- a/.claude/skills/forge/SKILL.md +++ b/.claude/skills/forge/SKILL.md @@ -22,6 +22,8 @@ Forge concept commands decouple codev from direct `gh` CLI calls. Each GitHub op | `pr-view` | `CODEV_PR_NUMBER`, `CODEV_INCLUDE_COMMENTS` (optional) | View PR details (JSON or text) | | `pr-diff` | `CODEV_PR_NUMBER`, `CODEV_DIFF_NAME_ONLY` (optional) | Get PR diff | | `auth-status` | — | Check forge authentication status | +| `commit-checks` | `CODEV_COMMIT_SHA` | Check results on one commit (JSON array `[{name, state, url?, workflow?}]`; `state` is `pass`, `fail`, `pending`, `skipped` or `neutral`). Read-only, used by `codev check` | +| `workflow-runs` | `CODEV_WORKFLOW`, `CODEV_BRANCH` | Runs of one workflow on one branch, newest first (JSON array `[{headSha, status, conclusion, url, createdAt}]`). Read-only, used by `codev check deploy` | ## Configuration @@ -45,6 +47,8 @@ In `.codev/config.json`: Built-in presets: `github` (default), `gitlab` (via `glab`), `gitea` (via `tea`), `linear` (Linear API), `jira` (Jira Cloud via `acli`). `linear` and `jira` are hybrid: they serve the issue concepts only, and every PR concept falls through to the `gh` default. Jira takes `jira-site` and `jira-project` keys; issue ids are work item keys (`ENG-123`). +`commit-checks` and `workflow-runs` are served by `github` (and by `linear` and `jira`, which use the github default for PR concepts). `gitlab` and `gitea` disable both, so `codev check` there reports `not run: commit-checks unavailable on gitlab` instead of calling `gh`; set an override to enable them. + **Note:** Non-GitHub presets are best-effort. Output schemas may differ from GitHub's JSON contracts. Non-conforming JSON returns `null` — consumers handle this gracefully. Override individual concepts if a preset doesn't match your CLI version. **`CODEV_REPO` is overloaded.** For `repo-archive` it is an input: the `owner/repo` to download. For the Gitea preset's read concepts (`pr-view`, `pr-list`, `pr-exists`, `issue-view`, `recently-merged`) it is an override — `tea api` needs an explicit `owner/repo` in the endpoint path, which those scripts otherwise derive from the `origin` remote. Set it per invocation, not in your environment: exported globally it retargets every Gitea read at that repo. diff --git a/.codex/skills/codev/SKILL.md b/.codex/skills/codev/SKILL.md index fb27e3230..1e56f0a98 100644 --- a/.codex/skills/codev/SKILL.md +++ b/.codex/skills/codev/SKILL.md @@ -1,6 +1,6 @@ --- name: codev -description: Codev project management CLI — init, adopt, bootstrap-docs, update, and doctor commands. Check this skill before running any `codev` command (except `consult`, `porch`, or `afx` which have their own skills). Use when setting up new projects, adding codev to existing repos, updating framework files, or diagnosing missing dependencies. +description: Codev project management CLI — init, adopt, bootstrap-docs, update, doctor, and the read-only check commands (check pr, check deploy, check worktree). Check this skill before running any `codev` command (except `consult`, `porch`, or `afx` which have their own skills). Use when setting up new projects, adding codev to existing repos, updating framework files, diagnosing missing dependencies, checking whether a PR is ready to merge, whether merged PRs reached the deploy branch, or whether a builder worktree can be removed. --- # codev - Project Management CLI @@ -13,6 +13,9 @@ codev adopt Add codev to the current directory codev bootstrap-docs Draft the governance docs from this codebase codev update Update protocols, roles, skills from package codev doctor Check system dependencies +codev check pr Read-only: is PR N ready to recommend for merge +codev check deploy ... Read-only: did merged PRs reach the deploy branch +codev check worktree Read-only: would removing a builder worktree lose data ``` ## codev init @@ -63,6 +66,31 @@ Checks dependencies: Node.js (>=22), git (>=2.5), your forge's CLI and its auth codev doctor ``` +## codev check + +Read-only: never merges, pushes, comments, deletes or moves a ref. Verdict on the first line, +then one line per check (`ok`, `ATTN`, `info`, `not run`, `off`, `skip`). Exit 0 clear, 1 +something needs attention (a check that could not run counts), 2 the command failed. Works +from the main checkout or any builder worktree. + +```bash +codev check pr 42 # before recommending a merge: head, state, mergeability, + # trial merge, CI on the code, attribution, watched files, + # linked issue, size, files to read +codev check deploy 42 43 # after merging: on the deploy branch, in the latest green deploy run +codev check worktree spir-42 # before afx cleanup: would removal lose data +codev check worktree .builders/spir-42 --json # a path works too; --json for agents +``` + +- Run `codev check pr` before `consult --type integration`: it checks mechanics, the + consultation reviews content. +- `REMOVABLE` means no data would be lost, not that the builder is finished: an open PR is + its own `ATTN` line and makes the exit 1. +- Configuration lives under `check.*` in `.codev/config.json` (`attribution`, `watch`, `flag`, + `notForReading`, `deploy.branch`, `deploy.workflow`, `skip`); the keep list is + `cleanup.keepIgnored`. A bad value is exit 2 naming the key and the file. `codev check --help` + and `codev check --help` list the subcommands and options. + ## Common mistakes - There is NO `codev tower` command — use `afx tower start/stop` diff --git a/.codex/skills/forge/SKILL.md b/.codex/skills/forge/SKILL.md index be8fcf3df..be82e3d08 100644 --- a/.codex/skills/forge/SKILL.md +++ b/.codex/skills/forge/SKILL.md @@ -22,6 +22,8 @@ Forge concept commands decouple codev from direct `gh` CLI calls. Each GitHub op | `pr-view` | `CODEV_PR_NUMBER`, `CODEV_INCLUDE_COMMENTS` (optional) | View PR details (JSON or text) | | `pr-diff` | `CODEV_PR_NUMBER`, `CODEV_DIFF_NAME_ONLY` (optional) | Get PR diff | | `auth-status` | — | Check forge authentication status | +| `commit-checks` | `CODEV_COMMIT_SHA` | Check results on one commit (JSON array `[{name, state, url?, workflow?}]`; `state` is `pass`, `fail`, `pending`, `skipped` or `neutral`). Read-only, used by `codev check` | +| `workflow-runs` | `CODEV_WORKFLOW`, `CODEV_BRANCH` | Runs of one workflow on one branch, newest first (JSON array `[{headSha, status, conclusion, url, createdAt}]`). Read-only, used by `codev check deploy` | ## Configuration @@ -45,6 +47,8 @@ In `.codev/config.json`: Built-in presets: `github` (default), `gitlab` (via `glab`), `gitea` (via `tea`), `linear` (Linear API), `jira` (Jira Cloud via `acli`). `linear` and `jira` are hybrid: they serve the issue concepts only, and every PR concept falls through to the `gh` default. Jira takes `jira-site` and `jira-project` keys; issue ids are work item keys (`ENG-123`). +`commit-checks` and `workflow-runs` are served by `github` (and by `linear` and `jira`, which use the github default for PR concepts). `gitlab` and `gitea` disable both, so `codev check` there reports `not run: commit-checks unavailable on gitlab` instead of calling `gh`; set an override to enable them. + **Note:** Non-GitHub presets are best-effort. Output schemas may differ from GitHub's JSON contracts. Non-conforming JSON returns `null` — consumers handle this gracefully. Override individual concepts if a preset doesn't match your CLI version. **`CODEV_REPO` is overloaded.** For `repo-archive` it is an input: the `owner/repo` to download. For the Gitea preset's read concepts (`pr-view`, `pr-list`, `pr-exists`, `issue-view`, `recently-merged`) it is an override — `tea api` needs an explicit `owner/repo` in the endpoint path, which those scripts otherwise derive from the `origin` remote. Set it per invocation, not in your environment: exported globally it retargets every Gitea read at that repo. diff --git a/codev-skeleton/.claude/skills/codev/SKILL.md b/codev-skeleton/.claude/skills/codev/SKILL.md index fb27e3230..1e56f0a98 100644 --- a/codev-skeleton/.claude/skills/codev/SKILL.md +++ b/codev-skeleton/.claude/skills/codev/SKILL.md @@ -1,6 +1,6 @@ --- name: codev -description: Codev project management CLI — init, adopt, bootstrap-docs, update, and doctor commands. Check this skill before running any `codev` command (except `consult`, `porch`, or `afx` which have their own skills). Use when setting up new projects, adding codev to existing repos, updating framework files, or diagnosing missing dependencies. +description: Codev project management CLI — init, adopt, bootstrap-docs, update, doctor, and the read-only check commands (check pr, check deploy, check worktree). Check this skill before running any `codev` command (except `consult`, `porch`, or `afx` which have their own skills). Use when setting up new projects, adding codev to existing repos, updating framework files, diagnosing missing dependencies, checking whether a PR is ready to merge, whether merged PRs reached the deploy branch, or whether a builder worktree can be removed. --- # codev - Project Management CLI @@ -13,6 +13,9 @@ codev adopt Add codev to the current directory codev bootstrap-docs Draft the governance docs from this codebase codev update Update protocols, roles, skills from package codev doctor Check system dependencies +codev check pr Read-only: is PR N ready to recommend for merge +codev check deploy ... Read-only: did merged PRs reach the deploy branch +codev check worktree Read-only: would removing a builder worktree lose data ``` ## codev init @@ -63,6 +66,31 @@ Checks dependencies: Node.js (>=22), git (>=2.5), your forge's CLI and its auth codev doctor ``` +## codev check + +Read-only: never merges, pushes, comments, deletes or moves a ref. Verdict on the first line, +then one line per check (`ok`, `ATTN`, `info`, `not run`, `off`, `skip`). Exit 0 clear, 1 +something needs attention (a check that could not run counts), 2 the command failed. Works +from the main checkout or any builder worktree. + +```bash +codev check pr 42 # before recommending a merge: head, state, mergeability, + # trial merge, CI on the code, attribution, watched files, + # linked issue, size, files to read +codev check deploy 42 43 # after merging: on the deploy branch, in the latest green deploy run +codev check worktree spir-42 # before afx cleanup: would removal lose data +codev check worktree .builders/spir-42 --json # a path works too; --json for agents +``` + +- Run `codev check pr` before `consult --type integration`: it checks mechanics, the + consultation reviews content. +- `REMOVABLE` means no data would be lost, not that the builder is finished: an open PR is + its own `ATTN` line and makes the exit 1. +- Configuration lives under `check.*` in `.codev/config.json` (`attribution`, `watch`, `flag`, + `notForReading`, `deploy.branch`, `deploy.workflow`, `skip`); the keep list is + `cleanup.keepIgnored`. A bad value is exit 2 naming the key and the file. `codev check --help` + and `codev check --help` list the subcommands and options. + ## Common mistakes - There is NO `codev tower` command — use `afx tower start/stop` diff --git a/codev-skeleton/.codex/skills/codev/SKILL.md b/codev-skeleton/.codex/skills/codev/SKILL.md index fb27e3230..1e56f0a98 100644 --- a/codev-skeleton/.codex/skills/codev/SKILL.md +++ b/codev-skeleton/.codex/skills/codev/SKILL.md @@ -1,6 +1,6 @@ --- name: codev -description: Codev project management CLI — init, adopt, bootstrap-docs, update, and doctor commands. Check this skill before running any `codev` command (except `consult`, `porch`, or `afx` which have their own skills). Use when setting up new projects, adding codev to existing repos, updating framework files, or diagnosing missing dependencies. +description: Codev project management CLI — init, adopt, bootstrap-docs, update, doctor, and the read-only check commands (check pr, check deploy, check worktree). Check this skill before running any `codev` command (except `consult`, `porch`, or `afx` which have their own skills). Use when setting up new projects, adding codev to existing repos, updating framework files, diagnosing missing dependencies, checking whether a PR is ready to merge, whether merged PRs reached the deploy branch, or whether a builder worktree can be removed. --- # codev - Project Management CLI @@ -13,6 +13,9 @@ codev adopt Add codev to the current directory codev bootstrap-docs Draft the governance docs from this codebase codev update Update protocols, roles, skills from package codev doctor Check system dependencies +codev check pr Read-only: is PR N ready to recommend for merge +codev check deploy ... Read-only: did merged PRs reach the deploy branch +codev check worktree Read-only: would removing a builder worktree lose data ``` ## codev init @@ -63,6 +66,31 @@ Checks dependencies: Node.js (>=22), git (>=2.5), your forge's CLI and its auth codev doctor ``` +## codev check + +Read-only: never merges, pushes, comments, deletes or moves a ref. Verdict on the first line, +then one line per check (`ok`, `ATTN`, `info`, `not run`, `off`, `skip`). Exit 0 clear, 1 +something needs attention (a check that could not run counts), 2 the command failed. Works +from the main checkout or any builder worktree. + +```bash +codev check pr 42 # before recommending a merge: head, state, mergeability, + # trial merge, CI on the code, attribution, watched files, + # linked issue, size, files to read +codev check deploy 42 43 # after merging: on the deploy branch, in the latest green deploy run +codev check worktree spir-42 # before afx cleanup: would removal lose data +codev check worktree .builders/spir-42 --json # a path works too; --json for agents +``` + +- Run `codev check pr` before `consult --type integration`: it checks mechanics, the + consultation reviews content. +- `REMOVABLE` means no data would be lost, not that the builder is finished: an open PR is + its own `ATTN` line and makes the exit 1. +- Configuration lives under `check.*` in `.codev/config.json` (`attribution`, `watch`, `flag`, + `notForReading`, `deploy.branch`, `deploy.workflow`, `skip`); the keep list is + `cleanup.keepIgnored`. A bad value is exit 2 naming the key and the file. `codev check --help` + and `codev check --help` list the subcommands and options. + ## Common mistakes - There is NO `codev tower` command — use `afx tower start/stop` diff --git a/codev-skeleton/resources/commands/codev.md b/codev-skeleton/resources/commands/codev.md index 9cfb81472..122e6af72 100644 --- a/codev-skeleton/resources/commands/codev.md +++ b/codev-skeleton/resources/commands/codev.md @@ -1,6 +1,7 @@ # codev - Project Management CLI -The `codev` command manages project setup, maintenance, and framework-level operations. +The `codev` command manages project setup, maintenance, and framework-level operations, and +runs the read-only `codev check` commands architects use at merge and cleanup time. ## Synopsis @@ -219,6 +220,342 @@ codev update codev update --force ``` +### codev check + +Read-only checks an architect runs at the moments that need them: `codev check pr` before +recommending a merge, `codev check deploy` after merges, `codev check worktree` before +`afx cleanup`. + +```bash +codev check pr [--json] +codev check deploy ... [--json] +codev check worktree [--json] +``` + +**What every subcommand shares:** + +- It never merges, approves, pushes, comments, deletes, cleans up or moves a ref. Every + subprocess goes through one runner that checks its argv against a closed allow-list of git + subcommands and flags before it starts, and calls only the read forge concepts `pr-view`, + `pr-search`, `commit-checks` and `workflow-runs`. Anything else is refused and the command + exits 2 naming it. +- The first line is the verdict and what needs attention. Then a header, then one line per + check with a status word: + + | Word | Status | Meaning | + |---|---|---| + | `ok` | `ok` | Passed | + | `ATTN` | `attention` | Blocks a recommendation, or the project flagged it | + | `info` | `info` | Worth knowing; never changes the verdict (size, overlap, files to read, unflagged watched files) | + | `not run` | `not-run` | Could not run, with the reason (the concept, key, call or git version). Always counts as attention, never as passing | + | `off` | `off` | No configuration for it | + | `skip` | `skip` | Declared skipped in `check.skip` | + +- Exit codes: **0** clear (nothing needs attention, nothing failed to run); **1** something + needs attention, including any check that could not run; **2** the command failed and made + no report (bad input, not in a git repository, no `origin`, invalid configuration, a + refused command, for `pr` a PR that cannot be read, for `worktree` a worktree that is not + found). +- `--json` prints exactly one JSON object (schema 1) on stdout; diagnostics go to stderr. + See [JSON reports](#json-reports) below. +- It reads the same from the main checkout, a subdirectory or any builder worktree: + configuration is read from the main checkout, and builder ids resolve under its + `.builders/`. +- Live tips come from `git ls-remote`; the local `origin/` is never trusted. Each forge + call, `ls-remote` and `fetch` has a 30 s limit; a call that times out makes the checks that + needed it `not run`. + +#### codev check pr + +Everything an architect reads before recommending a merge, for one PR: + +| Check id | What it reports | +|---|---| +| `head` | The exact head commit from the forge, against the local branch of that name. Attention when the local branch is ahead of it (not pushed) or has diverged, when origin's branch is past it (a push the forge has not indexed yet), or when it moved during the run | +| `state` | Attention unless the PR is OPEN and not a draft | +| `forge` | The forge's mergeability, with its merge state beside it in the forge's words (`MERGEABLE, BLOCKED (review required)`). `MERGEABLE` is `ok`; `CONFLICTING` is attention, and so is `UNKNOWN` (not computed yet; it is read once more) | +| `attribution` | Lines in the description and in every commit not on the base that match `check.attribution`; any hit is attention | +| `trial-merge` | A merge of the head into the live base tip, computed in the object store (`git merge-tree --write-tree`); any conflict is attention | +| `checks` | CI on the code. When the top commits change only `codev/projects/` (porch state), the runs on the last code commit are shown beside the head's | +| `watched` | Files matching `check.watch` that moved; attention for those matching `check.flag` | +| `linked-issue` | The closing keyword (`Fixes #N`) and whether it names the branch's issue; attention when it names another | +| `overlap` | Files the base also changed since the branch point | +| `size` | Lines added and removed, files changed | +| `to-read` | The files a person still has to read: the PR's files minus `check.notForReading` | + +A PR whose head and state are fine shows them in the header only. Run from the main checkout +on an open bugfix PR: + +``` +$ codev check pr 1965 +CLEAR PR #1965 — ready to recommend + +PR #1965 Fix #1956: cap packages/codev vitest at 3 workers (singleFork was dead since Vitest 4) OPEN builder/bugfix-1956 → main +head 0513558 (local builder/bugfix-1956 matches) base main @ e0e96fd (origin, live) + + ok forge MERGEABLE, BLOCKED (review required) + off attribution no patterns configured (check.attribution) + ok trial merge clean into main @ e0e96fd + ok checks head 0513558: porch-only, 8 passed + ok watched no watched file changed + info linked issue "Fixes #1956" — matches builder/bugfix-1956 + info overlap no file also changed on main since the branch point + info size +157 −11 in 8 files + info to read 6 files (2 not for reading): packages/codev/src/__tests__/bugfix-1956-vitest-worker-cap.test.ts, … +5 +``` + +A draft PR whose CI is still running: + +``` +$ codev check pr 1958 +ATTENTION PR #1958 — state (draft), checks (running) + +PR #1958 [Spec 1951] Read-only PR check for architects: codev check pr | deploy | worktree OPEN (draft) builder/spir-1951 → main +head f93aa60 (local builder/spir-1951 matches) base main @ e0e96fd (origin, live) + + ATTN state OPEN but a draft: it must be marked ready for review first + ok forge MERGEABLE, BLOCKED (review required) + off attribution no patterns configured (check.attribution) + ok trial merge clean into main @ e0e96fd + ATTN checks head f93aa60: 1 passed, 14 still running + ok watched no watched file changed + info linked issue "Fixes #1951" — matches builder/spir-1951 + info overlap no file also changed on main since the branch point + info size +13,297 −60 in 76 files + info to read 65 files (11 not for reading): codev/plans/1951-read-only-pr-check-for-archite.md, … +64 +``` + +`codev check pr` checks the merge mechanics; `consult --type integration` reviews the content. +Run the check first: its `size` and `to read` lines are the inputs to risk triage, and a +blocker it names makes a model review premature. + +**Porch-only heads.** A commit is porch-only when every path it changes from its first parent +is under `codev/projects/`; a merge commit never is. The last code commit is the first commit +that is not porch-only, walking the first-parent chain from the head back to the merge base. +The code's runs are those on the newest commit from that one up to the head that has any +check result. `checks` is `ok` only when those runs all passed (skipped and neutral count as +passed) and nothing on the head failed or is pending. No runs anywhere on the code is +attention. At most 10 commits are queried; beyond that the check is `not run`. + +#### codev check deploy + +For each merged PR: is the merge commit on the deploy branch (`check.deploy.branch`, else the +PR's base, read live), and, with `check.deploy.workflow` set, inside the latest green run of +that workflow on the deploy branch? Without a deploy workflow, `merge-checks` reports CI on +the merge commit itself instead. A PR that cannot be read, or is not merged, is reported as +such and the other PRs are still checked. + +| Check id | What it reports | +|---|---| +| `merged` | Whether the PR is merged; attention when it is not | +| `on-branch` | Whether the deploy branch's live tip contains the merge commit | +| `deploy-run` | Whether the latest green `check.deploy.workflow` run contains the merge commit; `off` without one | +| `merge-checks` | CI on the merge commit; reported when no deploy workflow is configured | + +With nothing configured: + +``` +$ codev check deploy 1972 1962 +ATTENTION #1972 merge checks failed + +#1972 merged 2026-11-24 → main merge e0e96fd + ok on main origin/main @ e0e96fd contains e0e96fd + ATTN merge checks e0e96fd: 8 passed, 2 failed (Verify Release (ubuntu-latest), Verify Release (macos-latest)) + off deploy run no deploy workflow configured (check.deploy.workflow) +#1962 merged 2026-11-24 → main merge adb179f + ok on main origin/main @ e0e96fd contains adb179f + ok merge checks adb179f: 18 passed + off deploy run no deploy workflow configured (check.deploy.workflow) +``` + +With `"check": { "deploy": { "branch": "main", "workflow": "test.yml" } }`, and one PR not +yet merged: + +``` +$ codev check deploy 1962 1965 +ATTENTION #1965 not merged + +#1962 merged 2026-11-24 → main merge adb179f + ok on main origin/main @ e0e96fd contains adb179f + ok deploy run latest green test.yml run (2026-11-24 10:41, e0e96fd) contains adb179f +#1965 OPEN → main + ATTN merged OPEN: not merged + not run on main the PR is not merged (OPEN) + not run deploy run the PR is not merged (OPEN) +``` + +#### codev check worktree + +Would removing a builder's worktree and its local branch lose data? The argument is a +builder id (resolved to `.builders/` under the main checkout) or a path to a registered +worktree; anything else is exit 2. + +| Check id | What it reports | +|---|---| +| `uncommitted` | Staged, unstaged and untracked files git does not ignore. Spawn's scaffold is counted apart and is not data | +| `commits` | Local commits on neither the live base tip nor the live remote branch tip. When the PR is merged by squash or rebase and the local tip is its merged head, every commit was part of what merged | +| `remote` | The local tip against `origin/`: matches, ahead, behind, diverged or absent. Context only | +| `pr` | The branch's PR. OPEN is attention ("builder not finished"); no PR found is attention; MERGED and CLOSED are `ok` | +| `ignored` | Ignored files matching `cleanup.keepIgnored` (and not dependency or build output) would be lost; every other ignored path is counted as regenerable | + +The verdict word describes **data only**: `REMOVABLE`, `REMOVABLE AFTER KEEPING N FILES` (only +keep-list files would be lost: copy them out first, or use `afx cleanup --keep-ignored`) or +`NOT REMOVABLE`. **`REMOVABLE` means no data would be lost, not that the builder is +finished.** An open PR, or a PR state the forge cannot give, makes the exit code 1 without +changing the verdict word. Exit 0 only for `REMOVABLE` with nothing else needing attention. + +``` +$ codev check worktree air-1938 +REMOVABLE air-1938 + +worktree .builders/air-1938 branch builder/air-1938 base main @ e0e96fd (origin, live) + ok uncommitted nothing uncommitted [5 scaffold files not counted] + ok commits 1 commit not on origin/main, all on origin/builder/air-1938 + ok remote origin/builder/air-1938 matches local (07e9090) + ok pr #1939 MERGED + ok ignored no keep-list files; 31 ignored paths treated as regenerable: .claude/settings.local.json, .codev/, … +29 +``` + +``` +$ codev check worktree bugfix-1956 +REMOVABLE AFTER KEEPING 2 FILES bugfix-1956 — PR #1965 open: builder not finished + +worktree .builders/bugfix-1956 branch builder/bugfix-1956 base main @ e0e96fd (origin, live) + ok uncommitted nothing uncommitted [5 scaffold files not counted] + ok commits 7 commits not on origin/main, all on origin/builder/bugfix-1956 + ok remote origin/builder/bugfix-1956 matches local (0513558) + ATTN pr #1965 OPEN: builder not finished + ATTN ignored 2 keep-list files would be lost: codev/projects/bugfix-1956-tests-one-run-of-the-packages-/bugfix-1956-pr-iter1-claude.txt, … +1 + (31 other ignored paths treated as regenerable: .claude/settings.local.json, .codev/, … +29) + → copy them out first, or use `afx cleanup --keep-ignored` +``` + +**What is scaffold, not data.** The files `afx spawn` writes (root `.builder-*` files, the +write guard's hook script and settings, OpenCode's `opencode.json`), when untracked, and the +entries spawn links in from the main checkout: the root `.env`, `.codev/config.json` and each +`worktree.symlinks` entry. Spawn makes each of those as a symbolic link to the same path in the +main checkout, or, where it may not, a hard link of that file, or a copy. Any of the three +shapes is scaffold while it matches (a copy only while its bytes equal the main checkout's +file); a changed copy is data. `afx cleanup`'s uncommitted-changes notice uses the same rule. +A project that gitignores `.builder-*` sees those files under `ignored`, where the default keep +list matches them, so they show as keep-list data instead. + +**Links among the keep-list files.** A symbolic link to a keep-list file inside the worktree is +judged as that file. Any other link (outside the worktree, to a file that is not kept, or to +nothing) is listed apart as `path -> target` and makes the worktree `NOT REMOVABLE`: +`afx cleanup --keep-ignored` never copies a link, so it cannot keep one. This errs on the safe +side: a link to an unkept file inside the worktree also blocks. + +**What `regenerable` counts.** Every ignored path that is not a keep-list file, as +`git ls-files --ignored --directory` lists it: a wholly ignored directory counts once (so the +number is approximate inside collapsed directories), and a directory holding a keep-list match +is left out. A nested repository's `dir/` entry is counted as listed, not expanded. + +#### Configuration + +All keys are read from the main checkout through the usual configuration layers (arrays +replace, never concatenate). A bad value is exit 2, naming the key and the file that set it. + +| Key | Meaning | Default | +|---|---|---| +| `check.attribution` | Regexes (JavaScript syntax, case-insensitive, matched per line) for forbidden attribution lines in the PR description and in every commit message not already on the base | `[]`: `off` | +| `check.watch` | Globs of files whose movement is always listed | `CLAUDE.md`, `AGENTS.md`, `.codev/**`, `.claude/**`, `codev/roles/**`, `codev/protocols/**`, `codev/templates/**`, `codev/resources/arch-critical.md`, `codev/resources/lessons-critical.md` | +| `check.flag` | Globs, within what `check.watch` matches, whose movement is attention | `[]` | +| `check.notForReading` | Globs left out of the files a person still has to read | `codev/projects/**`, `codev/state/**`, and the lockfiles `**/pnpm-lock.yaml`, `**/package-lock.json`, `**/yarn.lock`, `**/Cargo.lock`, `**/poetry.lock`, `**/uv.lock`, `**/go.sum`, `**/Gemfile.lock`, `**/composer.lock` | +| `check.deploy.branch` | The deploy branch for `codev check deploy` | each PR's base branch | +| `check.deploy.workflow` | The workflow (file name or name) whose latest green run on the deploy branch must contain the merge | unset: `deploy run` is `off` and `merge checks` is reported | +| `check.skip` | Check ids to skip, e.g. `["checks"]` for a project with no CI | `[]` | +| `cleanup.keepIgnored` | Ignored-file globs worth keeping (#1950, shared with `afx cleanup --keep-ignored`) | `codev/projects/**`, `codev/state/**`, `.builder-*`, `tmp/**`, `scratch/**` | + +Globs are git `:(glob)` pathspecs, so git does the matching: `*` stays within one directory and +`**` crosses directories. Setting `check.notForReading` replaces the default list; add a +project's generated files there (for example `packages/*/dist/**`). + +Example, in `.codev/config.json`: + +```json +{ + "check": { + "attribution": ["^Co-Authored-By:.*(Claude|Copilot)", "Generated with \\[Claude Code\\]"], + "flag": ["CLAUDE.md", "AGENTS.md"], + "deploy": { "branch": "production", "workflow": "deploy.yml" } + } +} +``` + +#### Forges + +`codev check` reads the forge only through concepts: `pr-view` (with the optional fields +`headRefOid`, `isDraft`, `mergeable`, `mergeStateStatus`, `mergeCommit`, `mergedAt`, +`reviewDecision`), `pr-search`, `commit-checks` and `workflow-runs`; see +[forge](forge.md). A preset that cannot supply one makes the checks that need it `not run`, +naming the concept, never a guess. `gitlab` and `gitea` disable `commit-checks` and +`workflow-runs`, so their `checks`, `merge checks` and `deploy run` lines read +`not run: commit-checks unavailable on gitlab` until an override supplies them. A `pr-view` +without `headRefOid` is exit 2 for `codev check pr`, because nothing can be reported against a +guessed head. + +#### What it writes, and what it trusts + +The only writes are additions to git's object store: the packs a ref-neutral fetch downloads +when the head or base commit is missing locally +(`git -c gc.auto=0 -c maintenance.auto=false fetch --no-write-fetch-head --refmap= origin …`), +and the tree and blob objects the trial merge writes (unreachable; normal gc collects them). No +ref, `HEAD`, index, working-tree file or `FETCH_HEAD` is created, changed or removed. Status +reads use `git --no-optional-locks`. + +The allow-list governs every git command the check runs and which forge concepts it calls. +Two things run that it does not inspect, and both are yours rather than the PR's: + +- **A project's own concept override** (a `forge` entry in your configuration) runs as you + wrote it, as overrides do everywhere in Codev. The shipped scripts for the four concepts + call only `gh pr view`, `gh pr list`, `gh run list` and `gh api` with GET, and tests hold + them to that. +- **A custom merge driver** may run during the trial merge. A PR's `.gitattributes` can name a + driver but cannot define its command: that comes only from your own git configuration. + +#### JSON reports + +`--json` prints one object. Every report has `schema: 1`, `command` (`pr`, `deploy` or +`worktree`), `verdict` (`clear` or `attention`) and `generatedAt` (ISO 8601). A failed command +(exit 2) prints `{ schema: 1, command, error: { message, cause? } }` instead. + +Each check is `{ id, status, summary, details, reason? }`: `status` is one of `ok`, +`attention`, `info`, `not-run`, `off`, `skip`; `summary` is the text the summary line prints; +`reason` says why for `not-run`, `off` and `skip`, and such a check's `details` may be empty or +partial. Paths are repository-relative; SHAs are full. + +| Report | Fields | +|---|---| +| `pr` | `pr: { number, title, url?, state, draft, headRef, head, baseRef, baseTip, localBranch }`, `checks`. `draft` is `null` when the forge does not say; `baseTip` is `null` when the live base tip could not be read (the base checks are then `not run`); `localBranch` is `{ name, sha }` or `null` | +| `deploy` | `deployBranch` (`null`: each PR's own base), `workflow` (or `null`), `prs: [{ number, mergedAt, mergeCommit, baseRef, verdict, checks }]`; the first three of each PR are `null` until known | +| `worktree` | `removable` (`removable`, `removable-after-keeping` or `not-removable`), `worktree: { path, builderId, branch, baseRef, baseTip }`, `checks`. `builderId` is `null` for a worktree outside `.builders/`; `baseRef` is `null` when neither the PR's base nor origin's default branch could be read, and `baseTip` when the live tip could not be (`commits` is then `not run`) | + +`details` per check id: + +| id | `details` | +|---|---| +| `head` | `{ forgeHead, relation, localBranchSha?, aheadOfPr?, behindPr?, originBranchSha?, originAheadOfPr?, movedTo? }`: `relation` is `matches`, `ahead`, `behind`, `diverged`, `absent` (no local branch), `origin-ahead` or `not-origin-branch` (a fork's PR, or the branch moved: the local branch is not compared) | +| `state` | `{ state, draft }` | +| `forge` | `{ mergeable, mergeStateStatus, reviewDecision }`, in the forge's words | +| `attribution` | `{ patterns, hits: [{ where: 'description' or 'commit', sha?, line, text }] }` | +| `trial-merge` | `{ baseTip, head, conflicts, files }` | +| `checks` | `{ head: CommitRuns, code?: CommitRuns, lastCodeCommit, porchOnlyAbove }`, where `CommitRuns` is `{ sha, runs: [{ name, state, url?, workflow? }], passed, failed, pending }`. `lastCodeCommit` is `null` when every commit since the branch point is porch-only | +| `watched` | `{ files: [{ path, flagged }] }` | +| `linked-issue` | `{ references: [{ keyword, issue }], keyword?, issue?, branchIssue? }`: every closing reference, the one chosen, and the issue a `builder/-` branch is for | +| `overlap` | `{ files }` | +| `size` | `{ additions, deletions, files }` | +| `to-read` | `{ files: [{ path, additions, deletions }], excluded }` | +| `merged` | `{ state, mergedAt, mergeCommit }` | +| `on-branch` | `{ branch, tip, contains }` | +| `deploy-run` | `{ workflow, run?: { headSha, url, createdAt }, contains? }` | +| `merge-checks` | `CommitRuns` | +| `uncommitted` | `{ files: [{ path, change }], scaffold }` | +| `commits` | `{ total, notOnBase, unsafe }`: `unsafe` is the commits on no remote branch, which are what blocks removal | +| `remote` | `{ remoteSha, relation }`: `relation` is `matches`, `ahead`, `behind`, `diverged` or `absent`; `remoteSha` is `null` when absent | +| `pr` | `{ number?, state?, mergedHead? }` | +| `ignored` | `{ keep, regenerable, links: [{ path, target, missing }], scaffold }`: `keep` is the keep-list files that would be lost, `regenerable` the count above, `links` the keep-list links that block removal (`missing` when the target does not exist), `scaffold` spawn's links among the ignored files | + --- ## See Also diff --git a/codev-skeleton/resources/commands/overview.md b/codev-skeleton/resources/commands/overview.md index de49cc8b1..3ae5f7d13 100644 --- a/codev-skeleton/resources/commands/overview.md +++ b/codev-skeleton/resources/commands/overview.md @@ -48,6 +48,9 @@ This installs the commands globally: `codev`, `afx`, `porch` and `consult` (plus | `codev doctor` | Check system dependencies | | `codev update` | Update codev templates and protocols | | `codev import ` | AI-assisted protocol import from other projects | +| `codev check pr ` | Read-only merge readiness of a PR: head, state, mergeability, trial merge, CI on the code, attribution, watched files, size, files to read | +| `codev check deploy ...` | Read-only: whether merged PRs reached the deploy branch and the latest green deploy run | +| `codev check worktree ` | Read-only: whether removing a builder worktree would lose data, and whether its PR is finished | See [codev.md](codev.md) for full documentation. diff --git a/codev-skeleton/resources/risk-triage.md b/codev-skeleton/resources/risk-triage.md index fcfaee768..09d4f0333 100644 --- a/codev-skeleton/resources/risk-triage.md +++ b/codev-skeleton/resources/risk-triage.md @@ -9,8 +9,17 @@ When a builder PR arrives, assess risk before choosing review depth. ### Step 1: Check Size and Scope ```bash -gh pr diff --stat -gh pr view --json files | jq '.files[].path' +codev check pr +``` + +Its `size` line (lines added and removed, files changed) and its `to read` line (the files a +person still has to read, once porch state, thread logs and lockfiles are set aside) are the +inputs to Step 2. A blocker it names (a trial-merge conflict, failing or missing checks on the +code, an unpushed head) comes before any review. It reads what you would otherwise type: + +```bash +gh pr view --json additions,deletions,changedFiles +gh pr diff --name-only ``` ### Step 2: Determine Risk Level @@ -65,7 +74,7 @@ gh pr view --json files | jq '.files[].path' ### Low Risk: Bugfix (12 lines, 1 file, tests/) ```bash -$ gh pr diff --stat 120 +$ git diff --stat origin/main...origin/builder/bugfix-120 # what `codev check pr 120` sizes packages/codev/tests/unit/foo.test.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) @@ -83,7 +92,7 @@ afx send spir-42 "PR approved, please merge" ### Medium Risk: New Feature (180 lines, 3 files, commands/) ```bash -$ gh pr diff --stat 121 +$ git diff --stat origin/main...origin/builder/spir-121 # what `codev check pr 121` sizes packages/codev/src/commands/consult/risk.ts | 120 +++++++++++++ packages/codev/src/cli.ts | 15 ++ packages/codev/tests/unit/risk.test.ts | 45 +++++ @@ -96,7 +105,7 @@ consult -m claude --type integration --issue 121 ### High Risk: Protocol Change (650 lines, 14 files, porch/) ```bash -$ gh pr diff --stat 122 +$ git diff --stat origin/main...origin/builder/spir-122 # what `codev check pr 122` sizes packages/codev/src/commands/porch/checks.ts | 200 ++++++++++++------ packages/codev/src/commands/porch/next.ts | 150 ++++++++++---- packages/codev/src/state/project.ts | 80 +++++--- diff --git a/codev-skeleton/resources/workflow-reference.md b/codev-skeleton/resources/workflow-reference.md index 1643a95cf..f277214cd 100644 --- a/codev-skeleton/resources/workflow-reference.md +++ b/codev-skeleton/resources/workflow-reference.md @@ -38,12 +38,12 @@ Quick reference for the 7-stage project workflow. For protocol details, see `cod │ HANDOFF / INTEGRATION │ ├─────────────────────────────────────────────────────────────────────────────────────┤ │ → 6. COMMITTED │ -│ Architect assesses PR risk: gh pr diff --stat N │ +│ Architect assesses PR risk: codev check pr N │ │ Low: Read + merge | Medium: 1-model review | High: 3-way CMAP │ │ Architect iterates with builder via PR comments │ │ Architect tells builder to merge │ │ Builder merges PR (NO --delete-branch flag) │ -│ Architect cleans up builder │ +│ Architect runs codev check worktree , then cleans up │ │ │ │ ⏸️ HUMAN GATE: Validate in production │ │ → 7. INTEGRATED │ diff --git a/codev-skeleton/roles/architect.md b/codev-skeleton/roles/architect.md index 39bed7710..f64a829af 100644 --- a/codev-skeleton/roles/architect.md +++ b/codev-skeleton/roles/architect.md @@ -48,6 +48,14 @@ its own authority. ## Integration review — depth matched to risk +**Run `codev check pr ` first.** One read-only command collects what you would otherwise +gather by hand: the exact head, state and forge mergeability, a trial merge into the live base, +CI on the code (not only on the porch-state commits above it), attribution lines, watched +files, the linked issue, the size, and the files a person still has to read. Its `size` and +`to read` lines feed the risk table below. A blocker it names (a conflict, failing or missing +checks, an unpushed head) comes first: a model review of a PR that cannot merge is premature. +`consult --type integration` reviews the content; `codev check pr` checks the mechanics. + Assess before choosing depth. **Highest single factor wins**: if lines, file count, subsystem or cross-cutting scope puts it in a tier, the whole PR is in that tier. @@ -73,12 +81,35 @@ dev-approval — lead with **Problem · Root Cause · Fix · Testing**, unprompt tier. Verify the root cause yourself: a builder's summary is evidence, not ground truth. The human should be able to answer from your message without opening the diff. +For a merge word or a `pr` gate, run `codev check pr ` again just before you write, and put +its verdict line in the **Testing** paragraph. A `CLEAR` from an older head says nothing about +the commit the human is asked to merge. + ### The owner decisions file A workspace may collect every ask for the human's word in `codev/state/pending-decisions.md`, the dashboard's **Decisions** tab, with the architect `main` as hub and only editor. When the owner asks to use decisions, run `afx decisions init` and follow `codev/resources/decision-protocol.md`. +## Closing the loop + +After a PR merges, two more read-only checks: + +- **`codev check deploy `** where the project deploys: is the merge commit on the deploy + branch (`check.deploy.branch`, else the PR's base) and, with `check.deploy.workflow` set, + inside the latest green run of that workflow? Without a deploy workflow it reports CI on the + merge commit. Run it before telling anyone a change is live. +- **`codev check worktree `** before `afx cleanup`: would removing the worktree and + its local branch lose data? **`REMOVABLE` means no data would be lost, not that the builder is + finished.** A PR still open is reported on its own line (`OPEN: builder not finished`) and + makes the exit code 1 without changing the verdict word. `REMOVABLE AFTER KEEPING N FILES` + names the keep-list files to copy out first, or to keep with `afx cleanup --keep-ignored`; + `NOT REMOVABLE` names what would be lost. + +The three `codev check` commands never merge, push, comment, delete or move a ref. Each prints +its verdict first, takes `--json`, and exits 0 when clear, 1 when something needs attention (a +check that could not run counts) and 2 when the command itself failed. + ## UX verification Before approving anything with UX requirements, exercise the actual user path. A spec that says diff --git a/codev/resources/arch.md b/codev/resources/arch.md index 4a5178b67..346ef7361 100644 --- a/codev/resources/arch.md +++ b/codev/resources/arch.md @@ -2023,6 +2023,18 @@ Terminal rows (delivered/superseded/dismissed) are pruned after `mailbox.retenti `afx whoami` reports the current terminal's agent identity (workspace, type, name) from Tower/global.db's perspective. Identity precedence is fixed: **builder-worktree cwd match** (canonical id verified against global.db — same resolution `afx send` uses, including the #1094 rule that an unverifiable worktree identity throws rather than falling through) → **`CODEV_ARCHITECT_NAME`** (the Tower-injected architect env var, read directly — NOT via `currentArchitectName()`, whose `main` default is deliberately not used here) → **unknown** (exit 1, no implicit `main`). Strictly read-only against global.db: `lookupBuilderSpawningArchitect(builderId, workspacePath?, db?)` accepts an optional connection so whoami passes its own readonly handle instead of the read-write `getDb()` singleton. Workspace display name comes from `known_workspaces` with directory-basename fallback (informational field only — fail-loud applies to type/name). `--json` emits `{workspace, type, name, architect?}`; failures emit `{"error": ...}` on stdout plus a human explanation on stderr. Works without Tower running. The shipped `/arch-init` skill builds on whoami for architect identity adoption + state recovery from `codev/state/.md`; it is maintained in both Claude and Codex provider skill trees. Architect state files are per-person (every team member has their own `main`, so a committed one collides across the team) and gitignored via `codev/state/*.md`; builder thread files (`codev/state/_thread.md`) have the opposite lifecycle and are versioned via a `!codev/state/*_thread.md` negation, since they ship with each builder's PR (Issue #1192). `codev init`/`adopt`/`update` all source this rule pair from the single `CODEV_GITIGNORE_ENTRIES` constant (`packages/codev/src/lib/gitignore.ts`); `codev doctor` audits the split via `auditStateFileIgnore()`. +### 9. Read-only Checks (`codev check`) (Spec 1951) + +**Location**: `packages/codev/src/commands/check/` (`pr.ts`, `deploy.ts`, `worktree.ts`; shared `runner.ts`, `allow-list.ts`, `git-facts.ts`, `porch-only.ts`, `settings.ts`, `render.ts`, `report.ts`) + +`codev check pr `, `codev check deploy …` and `codev check worktree ` collect what an architect reads before recommending a merge, after merges, and before `afx cleanup`. They are read-only by construction, not by convention: + +- **One runner, closed allow-list.** Every subprocess goes through `runner.ts`, which receives an argv (never a shell string) and checks every token against `allow-list.ts` before spawning; an unknown subcommand or flag is refused (exit 2), never passed through. Diff-family commands must carry `--no-ext-diff --no-textconv`; `status` only with `--no-optional-locks`; `merge-tree` only with `--write-tree`; `fetch` only in the ref-neutral form (`-c gc.auto=0 -c maintenance.auto=false fetch --no-write-fetch-head --refmap= origin …`). The only writes are object-store additions (fetched packs, the trial merge's unreachable trees). Live tips come from `ls-remote`; the local `origin/` is never trusted. +- **Audited imports.** `__tests__/imports.test.ts` allows each source file in the directory only listed imports: only `runner.ts` may import `child_process` or the forge dispatcher, only `index.ts` imports commander, and each module imported from outside (`agent-farm/lib/keep-list.ts`, `agent-farm/lib/builder-scaffold.ts`, `worktree-write-guard.ts`) is held to its own import list and to read-only `node:fs` names. The auditor is regex-based: a comment containing `from "x"` reads as an import. Stub-`PATH` tests record every `git`/`gh` argv at run time and fail on anything off the list. +- **Forge concepts.** Only `pr-view` (with optional fields `headRefOid`, `isDraft`, `mergeable`, `mergeStateStatus`, `mergeCommit`, `mergedAt`, `reviewDecision`), `pr-search`, and the two read concepts added for it, `commit-checks` and `workflow-runs`. A preset that cannot supply one makes the dependent check `not run` naming the concept; gitlab and gitea disable the two new ones explicitly so they never fall through to `gh`. A project's own concept override and a user-configured merge driver are trusted, as everywhere in Codev. +- **One scaffold rule with cleanup.** `agent-farm/lib/builder-scaffold.ts` (`isBuilderScaffold`, `isSpawnMade`) defines what spawn put in a worktree — `.builder-*`, the write guard, `opencode.json`, and each entry spawn linked in from the main checkout (symlink, hard link, or unchanged copy of the same path). `codev check worktree` and `afx cleanup`'s dirty notice both import it; `keep-list.ts` likewise gives both `cleanup.keepIgnored`. Path comparisons go through real paths (`realPath`/`comparablePath`), so a directory spelled differently from git's (symlinked parent, macOS `/var`, Windows 8.3 names) gives the same verdicts. +- **Output contract.** Verdict first; statuses `ok`/`attention`/`info`/`not-run`/`off`/`skip`, where `not-run` always counts as attention; exit 0 clear, 1 attention, 2 the command failed. `--json` is schema 1 (`report.ts`). + ## Installation Architecture **Entry Point**: `INSTALL.md` - Instructions for AI agents to install Codev diff --git a/codev/resources/commands/codev.md b/codev/resources/commands/codev.md index 97b270a3c..898690a9a 100644 --- a/codev/resources/commands/codev.md +++ b/codev/resources/commands/codev.md @@ -1,6 +1,7 @@ # codev - Project Management CLI -The `codev` command manages project setup, maintenance, and framework-level operations. +The `codev` command manages project setup, maintenance, and framework-level operations, and +runs the read-only `codev check` commands architects use at merge and cleanup time. ## Synopsis @@ -225,6 +226,342 @@ codev update --force codev update --agent ``` +### codev check + +Read-only checks an architect runs at the moments that need them: `codev check pr` before +recommending a merge, `codev check deploy` after merges, `codev check worktree` before +`afx cleanup`. + +```bash +codev check pr [--json] +codev check deploy ... [--json] +codev check worktree [--json] +``` + +**What every subcommand shares:** + +- It never merges, approves, pushes, comments, deletes, cleans up or moves a ref. Every + subprocess goes through one runner that checks its argv against a closed allow-list of git + subcommands and flags before it starts, and calls only the read forge concepts `pr-view`, + `pr-search`, `commit-checks` and `workflow-runs`. Anything else is refused and the command + exits 2 naming it. +- The first line is the verdict and what needs attention. Then a header, then one line per + check with a status word: + + | Word | Status | Meaning | + |---|---|---| + | `ok` | `ok` | Passed | + | `ATTN` | `attention` | Blocks a recommendation, or the project flagged it | + | `info` | `info` | Worth knowing; never changes the verdict (size, overlap, files to read, unflagged watched files) | + | `not run` | `not-run` | Could not run, with the reason (the concept, key, call or git version). Always counts as attention, never as passing | + | `off` | `off` | No configuration for it | + | `skip` | `skip` | Declared skipped in `check.skip` | + +- Exit codes: **0** clear (nothing needs attention, nothing failed to run); **1** something + needs attention, including any check that could not run; **2** the command failed and made + no report (bad input, not in a git repository, no `origin`, invalid configuration, a + refused command, for `pr` a PR that cannot be read, for `worktree` a worktree that is not + found). +- `--json` prints exactly one JSON object (schema 1) on stdout; diagnostics go to stderr. + See [JSON reports](#json-reports) below. +- It reads the same from the main checkout, a subdirectory or any builder worktree: + configuration is read from the main checkout, and builder ids resolve under its + `.builders/`. +- Live tips come from `git ls-remote`; the local `origin/` is never trusted. Each forge + call, `ls-remote` and `fetch` has a 30 s limit; a call that times out makes the checks that + needed it `not run`. + +#### codev check pr + +Everything an architect reads before recommending a merge, for one PR: + +| Check id | What it reports | +|---|---| +| `head` | The exact head commit from the forge, against the local branch of that name. Attention when the local branch is ahead of it (not pushed) or has diverged, when origin's branch is past it (a push the forge has not indexed yet), or when it moved during the run | +| `state` | Attention unless the PR is OPEN and not a draft | +| `forge` | The forge's mergeability, with its merge state beside it in the forge's words (`MERGEABLE, BLOCKED (review required)`). `MERGEABLE` is `ok`; `CONFLICTING` is attention, and so is `UNKNOWN` (not computed yet; it is read once more) | +| `attribution` | Lines in the description and in every commit not on the base that match `check.attribution`; any hit is attention | +| `trial-merge` | A merge of the head into the live base tip, computed in the object store (`git merge-tree --write-tree`); any conflict is attention | +| `checks` | CI on the code. When the top commits change only `codev/projects/` (porch state), the runs on the last code commit are shown beside the head's | +| `watched` | Files matching `check.watch` that moved; attention for those matching `check.flag` | +| `linked-issue` | The closing keyword (`Fixes #N`) and whether it names the branch's issue; attention when it names another | +| `overlap` | Files the base also changed since the branch point | +| `size` | Lines added and removed, files changed | +| `to-read` | The files a person still has to read: the PR's files minus `check.notForReading` | + +A PR whose head and state are fine shows them in the header only. Run from the main checkout +on an open bugfix PR: + +``` +$ codev check pr 1965 +CLEAR PR #1965 — ready to recommend + +PR #1965 Fix #1956: cap packages/codev vitest at 3 workers (singleFork was dead since Vitest 4) OPEN builder/bugfix-1956 → main +head 0513558 (local builder/bugfix-1956 matches) base main @ e0e96fd (origin, live) + + ok forge MERGEABLE, BLOCKED (review required) + off attribution no patterns configured (check.attribution) + ok trial merge clean into main @ e0e96fd + ok checks head 0513558: porch-only, 8 passed + ok watched no watched file changed + info linked issue "Fixes #1956" — matches builder/bugfix-1956 + info overlap no file also changed on main since the branch point + info size +157 −11 in 8 files + info to read 6 files (2 not for reading): packages/codev/src/__tests__/bugfix-1956-vitest-worker-cap.test.ts, … +5 +``` + +A draft PR whose CI is still running: + +``` +$ codev check pr 1958 +ATTENTION PR #1958 — state (draft), checks (running) + +PR #1958 [Spec 1951] Read-only PR check for architects: codev check pr | deploy | worktree OPEN (draft) builder/spir-1951 → main +head f93aa60 (local builder/spir-1951 matches) base main @ e0e96fd (origin, live) + + ATTN state OPEN but a draft: it must be marked ready for review first + ok forge MERGEABLE, BLOCKED (review required) + off attribution no patterns configured (check.attribution) + ok trial merge clean into main @ e0e96fd + ATTN checks head f93aa60: 1 passed, 14 still running + ok watched no watched file changed + info linked issue "Fixes #1951" — matches builder/spir-1951 + info overlap no file also changed on main since the branch point + info size +13,297 −60 in 76 files + info to read 65 files (11 not for reading): codev/plans/1951-read-only-pr-check-for-archite.md, … +64 +``` + +`codev check pr` checks the merge mechanics; `consult --type integration` reviews the content. +Run the check first: its `size` and `to read` lines are the inputs to risk triage, and a +blocker it names makes a model review premature. + +**Porch-only heads.** A commit is porch-only when every path it changes from its first parent +is under `codev/projects/`; a merge commit never is. The last code commit is the first commit +that is not porch-only, walking the first-parent chain from the head back to the merge base. +The code's runs are those on the newest commit from that one up to the head that has any +check result. `checks` is `ok` only when those runs all passed (skipped and neutral count as +passed) and nothing on the head failed or is pending. No runs anywhere on the code is +attention. At most 10 commits are queried; beyond that the check is `not run`. + +#### codev check deploy + +For each merged PR: is the merge commit on the deploy branch (`check.deploy.branch`, else the +PR's base, read live), and, with `check.deploy.workflow` set, inside the latest green run of +that workflow on the deploy branch? Without a deploy workflow, `merge-checks` reports CI on +the merge commit itself instead. A PR that cannot be read, or is not merged, is reported as +such and the other PRs are still checked. + +| Check id | What it reports | +|---|---| +| `merged` | Whether the PR is merged; attention when it is not | +| `on-branch` | Whether the deploy branch's live tip contains the merge commit | +| `deploy-run` | Whether the latest green `check.deploy.workflow` run contains the merge commit; `off` without one | +| `merge-checks` | CI on the merge commit; reported when no deploy workflow is configured | + +With nothing configured: + +``` +$ codev check deploy 1972 1962 +ATTENTION #1972 merge checks failed + +#1972 merged 2026-11-24 → main merge e0e96fd + ok on main origin/main @ e0e96fd contains e0e96fd + ATTN merge checks e0e96fd: 8 passed, 2 failed (Verify Release (ubuntu-latest), Verify Release (macos-latest)) + off deploy run no deploy workflow configured (check.deploy.workflow) +#1962 merged 2026-11-24 → main merge adb179f + ok on main origin/main @ e0e96fd contains adb179f + ok merge checks adb179f: 18 passed + off deploy run no deploy workflow configured (check.deploy.workflow) +``` + +With `"check": { "deploy": { "branch": "main", "workflow": "test.yml" } }`, and one PR not +yet merged: + +``` +$ codev check deploy 1962 1965 +ATTENTION #1965 not merged + +#1962 merged 2026-11-24 → main merge adb179f + ok on main origin/main @ e0e96fd contains adb179f + ok deploy run latest green test.yml run (2026-11-24 10:41, e0e96fd) contains adb179f +#1965 OPEN → main + ATTN merged OPEN: not merged + not run on main the PR is not merged (OPEN) + not run deploy run the PR is not merged (OPEN) +``` + +#### codev check worktree + +Would removing a builder's worktree and its local branch lose data? The argument is a +builder id (resolved to `.builders/` under the main checkout) or a path to a registered +worktree; anything else is exit 2. + +| Check id | What it reports | +|---|---| +| `uncommitted` | Staged, unstaged and untracked files git does not ignore. Spawn's scaffold is counted apart and is not data | +| `commits` | Local commits on neither the live base tip nor the live remote branch tip. When the PR is merged by squash or rebase and the local tip is its merged head, every commit was part of what merged | +| `remote` | The local tip against `origin/`: matches, ahead, behind, diverged or absent. Context only | +| `pr` | The branch's PR. OPEN is attention ("builder not finished"); no PR found is attention; MERGED and CLOSED are `ok` | +| `ignored` | Ignored files matching `cleanup.keepIgnored` (and not dependency or build output) would be lost; every other ignored path is counted as regenerable | + +The verdict word describes **data only**: `REMOVABLE`, `REMOVABLE AFTER KEEPING N FILES` (only +keep-list files would be lost: copy them out first, or use `afx cleanup --keep-ignored`) or +`NOT REMOVABLE`. **`REMOVABLE` means no data would be lost, not that the builder is +finished.** An open PR, or a PR state the forge cannot give, makes the exit code 1 without +changing the verdict word. Exit 0 only for `REMOVABLE` with nothing else needing attention. + +``` +$ codev check worktree air-1938 +REMOVABLE air-1938 + +worktree .builders/air-1938 branch builder/air-1938 base main @ e0e96fd (origin, live) + ok uncommitted nothing uncommitted [5 scaffold files not counted] + ok commits 1 commit not on origin/main, all on origin/builder/air-1938 + ok remote origin/builder/air-1938 matches local (07e9090) + ok pr #1939 MERGED + ok ignored no keep-list files; 31 ignored paths treated as regenerable: .claude/settings.local.json, .codev/, … +29 +``` + +``` +$ codev check worktree bugfix-1956 +REMOVABLE AFTER KEEPING 2 FILES bugfix-1956 — PR #1965 open: builder not finished + +worktree .builders/bugfix-1956 branch builder/bugfix-1956 base main @ e0e96fd (origin, live) + ok uncommitted nothing uncommitted [5 scaffold files not counted] + ok commits 7 commits not on origin/main, all on origin/builder/bugfix-1956 + ok remote origin/builder/bugfix-1956 matches local (0513558) + ATTN pr #1965 OPEN: builder not finished + ATTN ignored 2 keep-list files would be lost: codev/projects/bugfix-1956-tests-one-run-of-the-packages-/bugfix-1956-pr-iter1-claude.txt, … +1 + (31 other ignored paths treated as regenerable: .claude/settings.local.json, .codev/, … +29) + → copy them out first, or use `afx cleanup --keep-ignored` +``` + +**What is scaffold, not data.** The files `afx spawn` writes (root `.builder-*` files, the +write guard's hook script and settings, OpenCode's `opencode.json`), when untracked, and the +entries spawn links in from the main checkout: the root `.env`, `.codev/config.json` and each +`worktree.symlinks` entry. Spawn makes each of those as a symbolic link to the same path in the +main checkout, or, where it may not, a hard link of that file, or a copy. Any of the three +shapes is scaffold while it matches (a copy only while its bytes equal the main checkout's +file); a changed copy is data. `afx cleanup`'s uncommitted-changes notice uses the same rule. +A project that gitignores `.builder-*` sees those files under `ignored`, where the default keep +list matches them, so they show as keep-list data instead. + +**Links among the keep-list files.** A symbolic link to a keep-list file inside the worktree is +judged as that file. Any other link (outside the worktree, to a file that is not kept, or to +nothing) is listed apart as `path -> target` and makes the worktree `NOT REMOVABLE`: +`afx cleanup --keep-ignored` never copies a link, so it cannot keep one. This errs on the safe +side: a link to an unkept file inside the worktree also blocks. + +**What `regenerable` counts.** Every ignored path that is not a keep-list file, as +`git ls-files --ignored --directory` lists it: a wholly ignored directory counts once (so the +number is approximate inside collapsed directories), and a directory holding a keep-list match +is left out. A nested repository's `dir/` entry is counted as listed, not expanded. + +#### Configuration + +All keys are read from the main checkout through the usual configuration layers (arrays +replace, never concatenate). A bad value is exit 2, naming the key and the file that set it. + +| Key | Meaning | Default | +|---|---|---| +| `check.attribution` | Regexes (JavaScript syntax, case-insensitive, matched per line) for forbidden attribution lines in the PR description and in every commit message not already on the base | `[]`: `off` | +| `check.watch` | Globs of files whose movement is always listed | `CLAUDE.md`, `AGENTS.md`, `.codev/**`, `.claude/**`, `codev/roles/**`, `codev/protocols/**`, `codev/templates/**`, `codev/resources/arch-critical.md`, `codev/resources/lessons-critical.md` | +| `check.flag` | Globs, within what `check.watch` matches, whose movement is attention | `[]` | +| `check.notForReading` | Globs left out of the files a person still has to read | `codev/projects/**`, `codev/state/**`, and the lockfiles `**/pnpm-lock.yaml`, `**/package-lock.json`, `**/yarn.lock`, `**/Cargo.lock`, `**/poetry.lock`, `**/uv.lock`, `**/go.sum`, `**/Gemfile.lock`, `**/composer.lock` | +| `check.deploy.branch` | The deploy branch for `codev check deploy` | each PR's base branch | +| `check.deploy.workflow` | The workflow (file name or name) whose latest green run on the deploy branch must contain the merge | unset: `deploy run` is `off` and `merge checks` is reported | +| `check.skip` | Check ids to skip, e.g. `["checks"]` for a project with no CI | `[]` | +| `cleanup.keepIgnored` | Ignored-file globs worth keeping (#1950, shared with `afx cleanup --keep-ignored`) | `codev/projects/**`, `codev/state/**`, `.builder-*`, `tmp/**`, `scratch/**` | + +Globs are git `:(glob)` pathspecs, so git does the matching: `*` stays within one directory and +`**` crosses directories. Setting `check.notForReading` replaces the default list; add a +project's generated files there (for example `packages/*/dist/**`). + +Example, in `.codev/config.json`: + +```json +{ + "check": { + "attribution": ["^Co-Authored-By:.*(Claude|Copilot)", "Generated with \\[Claude Code\\]"], + "flag": ["CLAUDE.md", "AGENTS.md"], + "deploy": { "branch": "production", "workflow": "deploy.yml" } + } +} +``` + +#### Forges + +`codev check` reads the forge only through concepts: `pr-view` (with the optional fields +`headRefOid`, `isDraft`, `mergeable`, `mergeStateStatus`, `mergeCommit`, `mergedAt`, +`reviewDecision`), `pr-search`, `commit-checks` and `workflow-runs`; see +[forge](forge.md). A preset that cannot supply one makes the checks that need it `not run`, +naming the concept, never a guess. `gitlab` and `gitea` disable `commit-checks` and +`workflow-runs`, so their `checks`, `merge checks` and `deploy run` lines read +`not run: commit-checks unavailable on gitlab` until an override supplies them. A `pr-view` +without `headRefOid` is exit 2 for `codev check pr`, because nothing can be reported against a +guessed head. + +#### What it writes, and what it trusts + +The only writes are additions to git's object store: the packs a ref-neutral fetch downloads +when the head or base commit is missing locally +(`git -c gc.auto=0 -c maintenance.auto=false fetch --no-write-fetch-head --refmap= origin …`), +and the tree and blob objects the trial merge writes (unreachable; normal gc collects them). No +ref, `HEAD`, index, working-tree file or `FETCH_HEAD` is created, changed or removed. Status +reads use `git --no-optional-locks`. + +The allow-list governs every git command the check runs and which forge concepts it calls. +Two things run that it does not inspect, and both are yours rather than the PR's: + +- **A project's own concept override** (a `forge` entry in your configuration) runs as you + wrote it, as overrides do everywhere in Codev. The shipped scripts for the four concepts + call only `gh pr view`, `gh pr list`, `gh run list` and `gh api` with GET, and tests hold + them to that. +- **A custom merge driver** may run during the trial merge. A PR's `.gitattributes` can name a + driver but cannot define its command: that comes only from your own git configuration. + +#### JSON reports + +`--json` prints one object. Every report has `schema: 1`, `command` (`pr`, `deploy` or +`worktree`), `verdict` (`clear` or `attention`) and `generatedAt` (ISO 8601). A failed command +(exit 2) prints `{ schema: 1, command, error: { message, cause? } }` instead. + +Each check is `{ id, status, summary, details, reason? }`: `status` is one of `ok`, +`attention`, `info`, `not-run`, `off`, `skip`; `summary` is the text the summary line prints; +`reason` says why for `not-run`, `off` and `skip`, and such a check's `details` may be empty or +partial. Paths are repository-relative; SHAs are full. + +| Report | Fields | +|---|---| +| `pr` | `pr: { number, title, url?, state, draft, headRef, head, baseRef, baseTip, localBranch }`, `checks`. `draft` is `null` when the forge does not say; `baseTip` is `null` when the live base tip could not be read (the base checks are then `not run`); `localBranch` is `{ name, sha }` or `null` | +| `deploy` | `deployBranch` (`null`: each PR's own base), `workflow` (or `null`), `prs: [{ number, mergedAt, mergeCommit, baseRef, verdict, checks }]`; the first three of each PR are `null` until known | +| `worktree` | `removable` (`removable`, `removable-after-keeping` or `not-removable`), `worktree: { path, builderId, branch, baseRef, baseTip }`, `checks`. `builderId` is `null` for a worktree outside `.builders/`; `baseRef` is `null` when neither the PR's base nor origin's default branch could be read, and `baseTip` when the live tip could not be (`commits` is then `not run`) | + +`details` per check id: + +| id | `details` | +|---|---| +| `head` | `{ forgeHead, relation, localBranchSha?, aheadOfPr?, behindPr?, originBranchSha?, originAheadOfPr?, movedTo? }`: `relation` is `matches`, `ahead`, `behind`, `diverged`, `absent` (no local branch), `origin-ahead` or `not-origin-branch` (a fork's PR, or the branch moved: the local branch is not compared) | +| `state` | `{ state, draft }` | +| `forge` | `{ mergeable, mergeStateStatus, reviewDecision }`, in the forge's words | +| `attribution` | `{ patterns, hits: [{ where: 'description' or 'commit', sha?, line, text }] }` | +| `trial-merge` | `{ baseTip, head, conflicts, files }` | +| `checks` | `{ head: CommitRuns, code?: CommitRuns, lastCodeCommit, porchOnlyAbove }`, where `CommitRuns` is `{ sha, runs: [{ name, state, url?, workflow? }], passed, failed, pending }`. `lastCodeCommit` is `null` when every commit since the branch point is porch-only | +| `watched` | `{ files: [{ path, flagged }] }` | +| `linked-issue` | `{ references: [{ keyword, issue }], keyword?, issue?, branchIssue? }`: every closing reference, the one chosen, and the issue a `builder/-` branch is for | +| `overlap` | `{ files }` | +| `size` | `{ additions, deletions, files }` | +| `to-read` | `{ files: [{ path, additions, deletions }], excluded }` | +| `merged` | `{ state, mergedAt, mergeCommit }` | +| `on-branch` | `{ branch, tip, contains }` | +| `deploy-run` | `{ workflow, run?: { headSha, url, createdAt }, contains? }` | +| `merge-checks` | `CommitRuns` | +| `uncommitted` | `{ files: [{ path, change }], scaffold }` | +| `commits` | `{ total, notOnBase, unsafe }`: `unsafe` is the commits on no remote branch, which are what blocks removal | +| `remote` | `{ remoteSha, relation }`: `relation` is `matches`, `ahead`, `behind`, `diverged` or `absent`; `remoteSha` is `null` when absent | +| `pr` | `{ number?, state?, mergedHead? }` | +| `ignored` | `{ keep, regenerable, links: [{ path, target, missing }], scaffold }`: `keep` is the keep-list files that would be lost, `regenerable` the count above, `links` the keep-list links that block removal (`missing` when the target does not exist), `scaffold` spawn's links among the ignored files | + --- ## See Also diff --git a/codev/resources/commands/overview.md b/codev/resources/commands/overview.md index 99ddac607..0bf64e25c 100644 --- a/codev/resources/commands/overview.md +++ b/codev/resources/commands/overview.md @@ -49,6 +49,9 @@ This installs all five commands globally: `codev`, `afx`, `porch`, `consult`, an | `codev doctor` | Check system dependencies | | `codev update` | Update codev templates and protocols | | `codev import ` | AI-assisted protocol import from other projects | +| `codev check pr ` | Read-only merge readiness of a PR: head, state, mergeability, trial merge, CI on the code, attribution, watched files, size, files to read | +| `codev check deploy ...` | Read-only: whether merged PRs reached the deploy branch and the latest green deploy run | +| `codev check worktree ` | Read-only: whether removing a builder worktree would lose data, and whether its PR is finished | See [codev.md](codev.md) for full documentation. diff --git a/codev/resources/risk-triage.md b/codev/resources/risk-triage.md index fcfaee768..09d4f0333 100644 --- a/codev/resources/risk-triage.md +++ b/codev/resources/risk-triage.md @@ -9,8 +9,17 @@ When a builder PR arrives, assess risk before choosing review depth. ### Step 1: Check Size and Scope ```bash -gh pr diff --stat -gh pr view --json files | jq '.files[].path' +codev check pr +``` + +Its `size` line (lines added and removed, files changed) and its `to read` line (the files a +person still has to read, once porch state, thread logs and lockfiles are set aside) are the +inputs to Step 2. A blocker it names (a trial-merge conflict, failing or missing checks on the +code, an unpushed head) comes before any review. It reads what you would otherwise type: + +```bash +gh pr view --json additions,deletions,changedFiles +gh pr diff --name-only ``` ### Step 2: Determine Risk Level @@ -65,7 +74,7 @@ gh pr view --json files | jq '.files[].path' ### Low Risk: Bugfix (12 lines, 1 file, tests/) ```bash -$ gh pr diff --stat 120 +$ git diff --stat origin/main...origin/builder/bugfix-120 # what `codev check pr 120` sizes packages/codev/tests/unit/foo.test.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) @@ -83,7 +92,7 @@ afx send spir-42 "PR approved, please merge" ### Medium Risk: New Feature (180 lines, 3 files, commands/) ```bash -$ gh pr diff --stat 121 +$ git diff --stat origin/main...origin/builder/spir-121 # what `codev check pr 121` sizes packages/codev/src/commands/consult/risk.ts | 120 +++++++++++++ packages/codev/src/cli.ts | 15 ++ packages/codev/tests/unit/risk.test.ts | 45 +++++ @@ -96,7 +105,7 @@ consult -m claude --type integration --issue 121 ### High Risk: Protocol Change (650 lines, 14 files, porch/) ```bash -$ gh pr diff --stat 122 +$ git diff --stat origin/main...origin/builder/spir-122 # what `codev check pr 122` sizes packages/codev/src/commands/porch/checks.ts | 200 ++++++++++++------ packages/codev/src/commands/porch/next.ts | 150 ++++++++++---- packages/codev/src/state/project.ts | 80 +++++--- diff --git a/codev/resources/workflow-reference.md b/codev/resources/workflow-reference.md index a3fdff14d..679696620 100644 --- a/codev/resources/workflow-reference.md +++ b/codev/resources/workflow-reference.md @@ -38,11 +38,12 @@ Quick reference for the 7-stage project workflow. For protocol details, see `cod │ HANDOFF / INTEGRATION │ ├─────────────────────────────────────────────────────────────────────────────────────┤ │ → 6. COMMITTED │ +│ Architect runs codev check pr N (mechanics, size) │ │ Architect does 3-way integration review │ │ Architect iterates with builder via PR comments │ │ Architect tells builder to merge │ │ Builder merges PR (NO --delete-branch flag) │ -│ Architect cleans up builder │ +│ Architect runs codev check worktree , then cleans up │ │ │ │ ⏸️ HUMAN GATE: Validate in production │ │ → 7. INTEGRATED │ diff --git a/codev/roles/architect.md b/codev/roles/architect.md index 39bed7710..f64a829af 100644 --- a/codev/roles/architect.md +++ b/codev/roles/architect.md @@ -48,6 +48,14 @@ its own authority. ## Integration review — depth matched to risk +**Run `codev check pr ` first.** One read-only command collects what you would otherwise +gather by hand: the exact head, state and forge mergeability, a trial merge into the live base, +CI on the code (not only on the porch-state commits above it), attribution lines, watched +files, the linked issue, the size, and the files a person still has to read. Its `size` and +`to read` lines feed the risk table below. A blocker it names (a conflict, failing or missing +checks, an unpushed head) comes first: a model review of a PR that cannot merge is premature. +`consult --type integration` reviews the content; `codev check pr` checks the mechanics. + Assess before choosing depth. **Highest single factor wins**: if lines, file count, subsystem or cross-cutting scope puts it in a tier, the whole PR is in that tier. @@ -73,12 +81,35 @@ dev-approval — lead with **Problem · Root Cause · Fix · Testing**, unprompt tier. Verify the root cause yourself: a builder's summary is evidence, not ground truth. The human should be able to answer from your message without opening the diff. +For a merge word or a `pr` gate, run `codev check pr ` again just before you write, and put +its verdict line in the **Testing** paragraph. A `CLEAR` from an older head says nothing about +the commit the human is asked to merge. + ### The owner decisions file A workspace may collect every ask for the human's word in `codev/state/pending-decisions.md`, the dashboard's **Decisions** tab, with the architect `main` as hub and only editor. When the owner asks to use decisions, run `afx decisions init` and follow `codev/resources/decision-protocol.md`. +## Closing the loop + +After a PR merges, two more read-only checks: + +- **`codev check deploy `** where the project deploys: is the merge commit on the deploy + branch (`check.deploy.branch`, else the PR's base) and, with `check.deploy.workflow` set, + inside the latest green run of that workflow? Without a deploy workflow it reports CI on the + merge commit. Run it before telling anyone a change is live. +- **`codev check worktree `** before `afx cleanup`: would removing the worktree and + its local branch lose data? **`REMOVABLE` means no data would be lost, not that the builder is + finished.** A PR still open is reported on its own line (`OPEN: builder not finished`) and + makes the exit code 1 without changing the verdict word. `REMOVABLE AFTER KEEPING N FILES` + names the keep-list files to copy out first, or to keep with `afx cleanup --keep-ignored`; + `NOT REMOVABLE` names what would be lost. + +The three `codev check` commands never merge, push, comment, delete or move a ref. Each prints +its verdict first, takes `--json`, and exits 0 when clear, 1 when something needs attention (a +check that could not run counts) and 2 when the command itself failed. + ## UX verification Before approving anything with UX requirements, exercise the actual user path. A spec that says diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 29db71096..4d493cb38 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -343,3 +343,41 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals unkept inside path blocks) → Phase 7 docs; note 3: cleanup's dirty notice still counts a non-ignored spawn link (same class as main-36, informational, outside the plan's scoped cleanup edit) → asked the architect whether to fix in this PR (needs a read-only helper cleanup can import); note 4 → Phase 7 docs. +- Iteration 3 FORCE-ADVANCED by porch (safety ceiling, 927795193); porch moved to docs_guidance (68eef5795). + Architect (18:43): fix claude iter3 note 3 as Phase 7's FIRST commit, so it is reviewed. + +## Phase 7 — docs_guidance (2026-11-24) +- Merged origin/main (32 commits: v3.3.8 release, #1962 Node 22 floor) as 7f2737b07: no conflicts. +- Windows run 45462452355 (a1ccc442b, first Windows run on this branch) FAILED 9 tests, the same 9 in Targeted, + Unit Node 22 and Unit Node 24; 8939 others passed. All in commands/check, one cause, fixture-side: the fixture + root was fs.realpathSync(os.tmpdir()…), which keeps the runner's 8.3 short name C:\Users\RUNNER~1\…, while the + code reports git's long path (runneradmin). Fix: realpathSync.native in helpers/git-fixture.ts + 3 assertions. +- Architect asked whether a USER can produce two spellings of one directory. Audited every comparison: none compares + a raw cwd or config path with a git-reported path. cwd only starts git (roots come from git) or resolves a path + argument that resolveTarget then realPath()s; main-checkout / lookup comparisons are realPath on both sides; the + spawn-link test is comparablePath on both sides (copy / hard link compare bytes / dev+ino); insideTarget likewise. + ONE raw comparison found and fixed: the builder id for a PATH argument compared two git-listed spellings as they + stand (git 2.50 lists real paths for every worktree, checked, so not user-reachable today; effect cosmetic). + New tests on every platform (junction on Windows), helper `linkedSpelling()`: check worktree by id / relative / + absolute link path / '.' and check pr from worktree and main, all through a symlinked parent under the raw + os.tmpdir() spelling, equal the real-path reports. Mutation check: a raw compare in isSpawnMade, or dropping + realPath on the path argument, each fails the new test. Architect accepted (18:56). +- First commit f93aa60e1: isSpawnMade/linkAt/realPath/comparablePath moved into agent-farm/lib/builder-scaffold.ts + (now read-only node:fs; imports auditor holds a pure module's node:fs names to the read-only list); cleanup's + hasUncommittedChanges(worktree, mainRoot) uses it: a spawn symlink, hard link or unchanged copy that git does + not ignore is not counted, a changed copy is. Targeted 977/977, build, both tsc, tmp-residue OK. Windows + re-dispatched on f93aa60e1 (run 45465468867). +- Docs (second commit): architect role (both trees) — `codev check pr` first in Integration review (mechanics vs + consult's content; size/to-read feed the risk table), re-run before a merge word with its verdict line in PRFT + Testing, new "Closing the loop" section (check deploy after merges, check worktree before afx cleanup; + REMOVABLE = no data lost, NOT builder finished). risk-triage Step 1 = `codev check pr`. workflow-reference box. + codev.md (both): full `codev check` section with real samples (#1965 CLEAR, #1958 draft/running, deploy + 1972 1962 unconfigured, deploy 1962 1965 with a scratch-HOME check.deploy, worktree air-1938 and bugfix-1956), + config table, `:(glob)` pathspecs, writes (objects only), trust boundary (own concept overrides, user merge + drivers), JSON with the shipped deltas from the spec's schema: pr.baseTip and worktree.baseRef/baseTip + nullable; commits.unsafe; ignored.links/scaffold; checks.lastCodeCommit null; head.relation (+ behindPr, + originBranchSha, originAheadOfPr); forge.reviewDecision; linked-issue.references. overview.md rows; codev skill + x4 (+ hashes regenerated); forge skill x2 (commit-checks, workflow-runs); arch.md Core Components §9. +- Fixed in place: risk-triage's `gh pr diff --stat` does not exist (gh pr diff has no --stat) — Step 1's raw + commands now `gh pr view --json additions,deletions,changedFiles` + `gh pr diff --name-only`, and the + worked examples use `git diff --stat origin/main...origin/`, which prints the diffstat they show. diff --git a/packages/codev/src/lib/shipped-skill-hashes.ts b/packages/codev/src/lib/shipped-skill-hashes.ts index 1aca8ff13..2ba1c46ab 100644 --- a/packages/codev/src/lib/shipped-skill-hashes.ts +++ b/packages/codev/src/lib/shipped-skill-hashes.ts @@ -78,6 +78,7 @@ export const SHIPPED_SKILL_HASHES: Record = { '13f4f981eb1b4e2fb42a76551f84e3f756fc610fde6a96944885a8cee7b40d67', '177bd31ba5df1fea19761061ff1a0684d1792f5aaf29a24c158b94212b0a83b2', '1b2a5ece1ce53caf489d74947819e9d647530c69f4e7eb8d21befe0b241ad695', + '3f630cacfa43e53701b228f2f363d6ce624f7e1c371370c0c4cac69b2d3375d9', '445ddbf99fd54dc14418fd1920d93448978692199e968b2e92037402b4950862', '4c4d4d24ee553adef89c2268e129ad5fc3be0cb8440ce9c89604f7d30929c30e', '60c64eb94401c1e89c3b48f7e7f809c269c0e7cda534177127c5db3d59f3487f', @@ -191,6 +192,7 @@ export const SHIPPED_SKILL_HASHES: Record = { '101ce03a54139bf7fab1ec95b9ba8c686b4b5dcad88bb1ae4242c7d318bff3a7', '177bd31ba5df1fea19761061ff1a0684d1792f5aaf29a24c158b94212b0a83b2', '1b2a5ece1ce53caf489d74947819e9d647530c69f4e7eb8d21befe0b241ad695', + '3f630cacfa43e53701b228f2f363d6ce624f7e1c371370c0c4cac69b2d3375d9', '60c64eb94401c1e89c3b48f7e7f809c269c0e7cda534177127c5db3d59f3487f', '74162f6225f2e33a6236b7f79accaee5b3a4d51f15aa2c0c16bedd3ce1019914', '9039170e6dae4b3041ad573695dedbb0cad3aa55a2ff4086e5916bb6e7f88800', From d92a07d70408c04a3269da08795a01adf99f41da Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 11:18:50 -0800 Subject: [PATCH 80/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 9d2d64946..811c8f74f 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: readonly_core @@ -126,7 +126,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter3-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T18:45:52.618Z' +updated_at: '2026-11-24T19:18:50.559Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From 0c02478dd92065cfe951062ede2947c9dbe7ebf9 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 11:32:25 -0800 Subject: [PATCH 81/94] =?UTF-8?q?[Spec=201951][Phase:=20docs=5Fguidance]?= =?UTF-8?q?=20fix:=20review=20iteration=201=20=E2=80=94=20cleanup=20reads?= =?UTF-8?q?=20git=20status=20with=20-z?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - cleanup's hasUncommittedChanges read `git status --porcelain` line by line, so git quoted a path holding a space, a quote or a non-ASCII letter, linkAt could not read it, and a spawn-made entry with such a name counted as dirty (codex; claude note 3). It now runs `git status --porcelain -z --untracked-files=all` through execFile (windowsHide), not the shared run(), which trims stdout and would drop the first entry's leading status space. A rename's source path is dropped, so a rename counts once. - Tests: a hard link and an unchanged copy at paths git would quote are not counted (fails with the old parsing); pinned the safe direction: a lone ' M' first entry, a quoted untracked name and a staged rename are each counted once, and a failing git status is still "Unable to check status" (dirty). - codev.md (both trees): an identical copy is scaffold whoever made it; nothing is lost while the main checkout holds the file (claude note 1). - Rebuttal and thread log. --- codev-skeleton/resources/commands/codev.md | 4 +- .../1951-docs_guidance-iter1-rebuttals.md | 60 +++++++++++++++++++ codev/resources/commands/codev.md | 4 +- codev/state/spir-1951_thread.md | 14 +++++ .../spec-1951-builder-scaffold.test.ts | 42 +++++++++++++ .../codev/src/agent-farm/commands/cleanup.ts | 46 ++++++++++---- 6 files changed, 157 insertions(+), 13 deletions(-) create mode 100644 codev/projects/1951-read-only-pr-check-for-archite/1951-docs_guidance-iter1-rebuttals.md diff --git a/codev-skeleton/resources/commands/codev.md b/codev-skeleton/resources/commands/codev.md index 122e6af72..0d8cb701d 100644 --- a/codev-skeleton/resources/commands/codev.md +++ b/codev-skeleton/resources/commands/codev.md @@ -436,7 +436,9 @@ entries spawn links in from the main checkout: the root `.env`, `.codev/config.j `worktree.symlinks` entry. Spawn makes each of those as a symbolic link to the same path in the main checkout, or, where it may not, a hard link of that file, or a copy. Any of the three shapes is scaffold while it matches (a copy only while its bytes equal the main checkout's -file); a changed copy is data. `afx cleanup`'s uncommitted-changes notice uses the same rule. +file); a changed copy is data. So an untracked file whose bytes equal the main checkout's +file at the same path is scaffold whoever made it: removing it loses nothing while the main +checkout still holds that file. `afx cleanup`'s uncommitted-changes notice uses the same rule. A project that gitignores `.builder-*` sees those files under `ignored`, where the default keep list matches them, so they show as keep-list data instead. diff --git a/codev/projects/1951-read-only-pr-check-for-archite/1951-docs_guidance-iter1-rebuttals.md b/codev/projects/1951-read-only-pr-check-for-archite/1951-docs_guidance-iter1-rebuttals.md new file mode 100644 index 000000000..eec9b6a1f --- /dev/null +++ b/codev/projects/1951-read-only-pr-check-for-archite/1951-docs_guidance-iter1-rebuttals.md @@ -0,0 +1,60 @@ +# Phase 7 (`docs_guidance`): iteration 1 rebuttal + +Codex: REQUEST_CHANGES. Claude: APPROVE, with four non-blocking notes. + +## Codex: cleanup does not apply the shared rule to quoted filenames (accepted, fixed) + +> `cleanup.ts:206-212` parses non-`-z` porcelain output by newline and passes Git's quoted +> pathname directly to `isSpawnMade`. + +Correct, and checked against git 2.50 before fixing. Without `-z`, `git status --porcelain` +prints `?? "a b.txt"`, `?? "q\"x.txt"` and `?? "\303\251.txt"`. `linkAt` could not read the +quoted spelling, so `isSpawnScaffold` returned false. A spawn-made entry whose name has a +space, a quote or a non-ASCII letter was therefore counted as dirty. The error went the safe +way (the notice gates no deletion; the architect confirmed on main that `dirty` feeds only +`afx cleanup`'s message). Even so, it broke the promise that cleanup and `codev check +worktree` judge scaffold by one rule. Claude's note 3 is the same gap, seen from the test +side. + +Fixed in `cleanup.ts`: + +- `gitStatusZ()` runs `git status --porcelain -z --untracked-files=all` through `execFile` + with `windowsHide`, `cwd` set to the worktree, and a 10 MB buffer. It does not use the shared + `run()`, which trims stdout: with `-z`, that would drop the leading space of the first + entry's status code (` M file` → `M file`). +- `parseStatusZ()` splits on NUL and reads `XY path`. A rename or copy is followed by its + source path, which is dropped, so a rename counts once. +- `hasUncommittedChanges` counts every entry except an untracked one that is spawn's scaffold. + An entry that cannot be read still counts as dirty, and a failing `git status` is still + `Unable to check status`, which is dirty. + +I did not reuse `commands/check/worktree.ts`'s `parseStatus`. It throws the check's exit-2 +error on output it does not recognise, while cleanup's notice must never fail a cleanup. It +also maps change words that cleanup does not use. Importing it would also make `agent-farm` +depend on `commands/check`, the reverse of the direction the shared modules go. + +Tests (`spec-1951-builder-scaffold.test.ts`, every platform): + +- At a path git would quote (`shared/my data é.json`, `shared/copy ü.json`): a hard link of + the main checkout's file and an unchanged copy are not counted. With the old line-based + parsing put back, this test fails (mutation check). With the fix, it passes. +- The safe direction, pinned as the architect asked: a single modified tracked file as the + first entry (` M`) is counted; an untracked file whose name git would quote is counted; a + staged rename counts once; a worktree whose `.git` points at a missing directory makes + `git status` fail, and the result is `Unable to check status`, dirty. + +All cleanup suites still pass, including those that mock `execFile` (92 tests in 11 files with +the spawn guard and the imports audit). + +## Claude's notes + +1. **The copy rule is broader than "spawn made it".** Accepted. `codev.md` (both trees) now + says so: an untracked file whose bytes equal the main checkout's file at the same path is + scaffold whoever made it, and removing it loses nothing while the main checkout still + holds that file. +2. **A gitignored `.builder-*` file shows as keep-list data.** Already documented, and it errs + on the safe side. No change. +3. **No test for a path git quotes.** Fixed, as part of the codex fix above. +4. **The skeleton's `codev.md` carries this repository's PR numbers and builder ids.** Left as + is. The plan requires samples pasted from real runs, and the skeleton's existing examples + already name this repository's branches. diff --git a/codev/resources/commands/codev.md b/codev/resources/commands/codev.md index 898690a9a..de10d9e18 100644 --- a/codev/resources/commands/codev.md +++ b/codev/resources/commands/codev.md @@ -442,7 +442,9 @@ entries spawn links in from the main checkout: the root `.env`, `.codev/config.j `worktree.symlinks` entry. Spawn makes each of those as a symbolic link to the same path in the main checkout, or, where it may not, a hard link of that file, or a copy. Any of the three shapes is scaffold while it matches (a copy only while its bytes equal the main checkout's -file); a changed copy is data. `afx cleanup`'s uncommitted-changes notice uses the same rule. +file); a changed copy is data. So an untracked file whose bytes equal the main checkout's +file at the same path is scaffold whoever made it: removing it loses nothing while the main +checkout still holds that file. `afx cleanup`'s uncommitted-changes notice uses the same rule. A project that gitignores `.builder-*` sees those files under `ignored`, where the default keep list matches them, so they show as keep-list data instead. diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 4d493cb38..2ac04006c 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -381,3 +381,17 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals - Fixed in place: risk-triage's `gh pr diff --stat` does not exist (gh pr diff has no --stat) — Step 1's raw commands now `gh pr view --json additions,deletions,changedFiles` + `gh pr diff --name-only`, and the worked examples use `git diff --stat origin/main...origin/`, which prints the diffstat they show. +- Architect (19:11): ci-first (main-38) still stands; retiring it is part of open decision main-39 (PR #1965). No + local full suite, capped or not (machine load ~25). 8/8 green on 827eed9d4 confirmed by the architect (19:18); + skip applied once, config.local.json restored + cmp, build passed, porch commit d92a07d70. The Phase 7 review + context file (codev/projects/…/1951-docs_guidance-iter1-context.md) asked both reviewers to review f93aa60e1 + with the docs, since it carries the unreviewed a1ccc442b logic. +- Review iter1: codex REQUEST_CHANGES: cleanup parsed `git status --porcelain` without -z, so a quoted path (space, + quote, non-ASCII) failed linkAt and a spawn-made entry counted dirty. Verified on git 2.50. Claude APPROVE (it + probed the same-size/different-bytes copy branch and the linkedSpelling tests); note 3 = the same gap; note 1 + (copy rule broader than "spawn made it") → one clause in codev.md; notes 2/4 no change. Architect agreed (19:26) + and asked for three more safe-direction tests. Fix: `gitStatusZ()` via execFile + windowsHide (NOT run(), which + trims stdout and would eat the first entry's leading status space), `parseStatusZ()` drops a rename's source. + Tests: hard link + unchanged copy at quoted names not counted (fails with the old parsing: mutation-checked); + ' M' first entry counted; quoted untracked name counted; staged rename counts once; a broken .git → "Unable to + check status" (dirty). Cleanup suites incl. the execFile-mocking ones still pass. diff --git a/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts index 17d67367b..efaf3874f 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1951-builder-scaffold.test.ts @@ -153,6 +153,39 @@ describe('Spec 1951 — afx cleanup: hasUncommittedChanges and the scaffold (mai expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: true, scaffoldOnly: false, details: '2 uncommitted file(s)' }); }); + // The notice gates no deletion; when in doubt it says "dirty". These pin that direction for + // the NUL-separated read (`git status --porcelain -z`). + describe('reading git status: the notice errs toward dirty', () => { + const noScaffold = (): void => { + rmSync(join(worktree, '.claude'), { recursive: true }); + for (const rel of ['.builder-prompt.txt', '.builder-role.md', '.builder-start.sh']) rmSync(join(worktree, rel)); + }; + + it("a single modified tracked file, the first entry (' M'), is counted", async () => { + noScaffold(); + write('src/tracked.ts', 'changed\n'); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: true, scaffoldOnly: false, details: '1 uncommitted file(s)' }); + }); + + it('an untracked file whose name git would quote is counted', async () => { + write('my notes é.md'); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: true, scaffoldOnly: false, details: '1 uncommitted file(s)' }); + }); + + it('a staged rename counts once', async () => { + noScaffold(); + git('mv', 'src/tracked.ts', 'src/moved.ts'); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: true, scaffoldOnly: false, details: '1 uncommitted file(s)' }); + }); + + it('git status failing reports "Unable to check status" as dirty', async () => { + const broken = join(base, 'broken'); + mkdirSync(broken); + writeFileSync(join(broken, '.git'), `gitdir: ${join(base, 'no-such-gitdir')}\n`); + expect(await hasUncommittedChanges(broken, main)).toEqual({ dirty: true, scaffoldOnly: false, details: 'Unable to check status' }); + }); + }); + // The same rule `codev check worktree` uses (isSpawnMade): an entry spawn linked in from the // main checkout that git does not ignore is scaffold, however spawn had to make it. describe('entries spawn linked in from the main checkout', () => { @@ -178,6 +211,15 @@ describe('Spec 1951 — afx cleanup: hasUncommittedChanges and the scaffold (mai expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: true, scaffoldOnly: false, details: '1 uncommitted file(s)' }); }); + it('at a path git would quote: a hard link and an unchanged copy are not counted', async () => { + write('shared/my data é.json', '{"a":1}\n', main); + write('shared/copy ü.json', '{"b":2}\n', main); + mkdirSync(join(worktree, 'shared')); + linkSync(join(main, 'shared/my data é.json'), join(worktree, 'shared/my data é.json')); + write('shared/copy ü.json', '{"b":2}\n'); + expect(await hasUncommittedChanges(worktree, main)).toEqual({ dirty: false, scaffoldOnly: true, details: '' }); + }); + it.skipIf(process.platform === 'win32')('a link at that path pointing anywhere else is data: counted', async () => { write('elsewhere.json', '{"from":"main"}\n', base); mkdirSync(join(worktree, 'shared')); diff --git a/packages/codev/src/agent-farm/commands/cleanup.ts b/packages/codev/src/agent-farm/commands/cleanup.ts index e99168643..b308d55b7 100644 --- a/packages/codev/src/agent-farm/commands/cleanup.ts +++ b/packages/codev/src/agent-farm/commands/cleanup.ts @@ -203,25 +203,22 @@ export async function hasUncommittedChanges( try { // Check for uncommitted changes (staged and unstaged). Untracked files are listed one by // one, so the write guard's `.claude/hooks/` is judged by its file, not as a directory. - const result = await run('git status --porcelain --untracked-files=all', { cwd: worktreePath }); + const entries = parseStatusZ(await gitStatusZ(worktreePath)); - if (result.stdout.trim()) { + if (entries.length > 0) { // Count changed files, excluding spawn's scaffold (only ever untracked) - const allLines = result.stdout.trim().split('\n').filter(Boolean); - const nonScaffoldLines = allLines.filter((line) => !(line.startsWith('?? ') && isSpawnScaffold(mainRoot, worktreePath, line.slice(3)))); + const nonScaffold = entries.filter((e) => !(e.xy === '??' && isSpawnScaffold(mainRoot, worktreePath, e.path))); - if (nonScaffoldLines.length > 0) { + if (nonScaffold.length > 0) { return { dirty: true, scaffoldOnly: false, - details: `${nonScaffoldLines.length} uncommitted file(s)`, + details: `${nonScaffold.length} uncommitted file(s)`, }; } // Only scaffold files present - if (allLines.length > 0) { - return { dirty: false, scaffoldOnly: true, details: '' }; - } + return { dirty: false, scaffoldOnly: true, details: '' }; } return { dirty: false, scaffoldOnly: false, details: '' }; @@ -232,8 +229,35 @@ export async function hasUncommittedChanges( } /** - * Whether an untracked entry is spawn's scaffold. An entry that cannot be read (a path git - * printed quoted, say) is counted as a real change: the notice errs toward "dirty". + * `git status --porcelain -z`: NUL-separated, so git quotes no path, and read whole (the shared + * `run()` trims its output, which would drop the first entry's leading status space). + */ +function gitStatusZ(worktreePath: string): Promise { + return new Promise((resolve, reject) => { + execFile( + 'git', + ['status', '--porcelain', '-z', '--untracked-files=all'], + { cwd: worktreePath, encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024, windowsHide: true }, + (err, out) => (err ? reject(err) : resolve(out)), + ); + }); +} + +/** The entries of `status --porcelain -z`, each `XY path`; a rename or copy is followed by its source, which is dropped. */ +function parseStatusZ(output: string): Array<{ xy: string; path: string }> { + const tokens = output.split('\0').filter((t) => t !== ''); + const entries: Array<{ xy: string; path: string }> = []; + for (let i = 0; i < tokens.length; i++) { + const xy = tokens[i].slice(0, 2); + entries.push({ xy, path: tokens[i].slice(3) }); + if (xy.includes('R') || xy.includes('C')) i++; + } + return entries; +} + +/** + * Whether an untracked entry is spawn's scaffold. An entry that cannot be read is counted as a + * real change: the notice errs toward "dirty". */ function isSpawnScaffold(mainRoot: string, worktreePath: string, rel: string): boolean { if (isBuilderScaffold(rel)) return true; From 32d7a57db705787017bb1297b0a1a6b894297c6e Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 11:46:42 -0800 Subject: [PATCH 82/94] chore(porch): 1951 implement re-iter (iter 2) --- .../status.yaml | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 811c8f74f..16960d68e 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -38,8 +38,8 @@ gates: status: pending verify-approval: status: pending -iteration: 1 -build_complete: true +iteration: 2 +build_complete: false history: - iteration: 1 plan_phase: readonly_core @@ -125,8 +125,20 @@ history: verdict: APPROVE file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-check_worktree-iter3-claude.txt + - iteration: 1 + plan_phase: docs_guidance + build_output: '' + reviews: + - model: codex + verdict: REQUEST_CHANGES + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-docs_guidance-iter1-codex.txt + - model: claude + verdict: APPROVE + file: >- + /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-docs_guidance-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T19:18:50.559Z' +updated_at: '2026-11-24T19:46:41.953Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From 7f24e7afda2bc3e660a1decdbaafb4f126ff2f46 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 11:47:24 -0800 Subject: [PATCH 83/94] chore(porch): 1951 implement build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 16960d68e..2debe8ba9 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 2 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: readonly_core @@ -138,7 +138,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-docs_guidance-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T19:46:41.953Z' +updated_at: '2026-11-24T19:47:24.792Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From 09a6c29518704da8a0a19ec89be7832f23357d58 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 11:53:08 -0800 Subject: [PATCH 84/94] =?UTF-8?q?chore(porch):=201951=20all=20plan=20phase?= =?UTF-8?q?s=20complete=20=E2=86=92=20review?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../status.yaml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 2debe8ba9..1d335bebf 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -1,7 +1,7 @@ id: '1951' title: read-only-pr-check-for-archite protocol: spir -phase: implement +phase: review plan_phases: - id: forge_read_concepts title: Forge read concepts for PR mechanics @@ -23,8 +23,8 @@ plan_phases: status: complete - id: docs_guidance title: Architect guidance and command documentation - status: in_progress -current_plan_phase: docs_guidance + status: complete +current_plan_phase: null gates: spec-approval: status: approved @@ -38,8 +38,8 @@ gates: status: pending verify-approval: status: pending -iteration: 2 -build_complete: true +iteration: 1 +build_complete: false history: - iteration: 1 plan_phase: readonly_core @@ -138,7 +138,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-docs_guidance-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T19:47:24.792Z' +updated_at: '2026-11-24T19:53:08.196Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -161,6 +161,8 @@ context_refreshes: - boundary: plan-phase:docs_guidance at: '2026-11-24T18:44:02.801Z' acknowledged_at: '2026-11-24T18:45:52.617Z' + - boundary: enter:review + at: '2026-11-24T19:53:08.196Z' force_advanced: phase: check_worktree iteration: 3 From 7d312a26743cc99b83507aff27463a974063b748 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 11:55:07 -0800 Subject: [PATCH 85/94] chore(porch): 1951 acknowledge context refresh --- codev/projects/1951-read-only-pr-check-for-archite/status.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 1d335bebf..0d0efc968 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -138,7 +138,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-docs_guidance-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T19:53:08.196Z' +updated_at: '2026-11-24T19:55:06.922Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -163,6 +163,7 @@ context_refreshes: acknowledged_at: '2026-11-24T18:45:52.617Z' - boundary: enter:review at: '2026-11-24T19:53:08.196Z' + acknowledged_at: '2026-11-24T19:55:06.922Z' force_advanced: phase: check_worktree iteration: 3 From 017f0baeaeb9314d39d872bc1dd334670bd5b9dd Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 12:06:21 -0800 Subject: [PATCH 86/94] [Spec 1951][Phase: review] test: cleanup execFile mocks take the dirty notice's real path; hang tests survive load - cleanup's dirty notice calls execFile(cmd, args, options, cb), but three cleanup suites mocked the 3-argument form, so the options object was called as the callback and the notice always read "Unable to check status" (claude, Phase 7 iter2 note 2; architect order). The mocks now take both forms: - air-1950-cleanup-keep-ignored: git status answers from the test; a new case asserts the notice reads "1 uncommitted file(s)", not "Unable to check status". - air-1950-cleanup-keep-ignored-e2e: git status runs for real in the fixture repository; the case asserts the notice counts notes.md. - spec-1658-cleanup-worktree-removal: records 'ps' only for ps. Both new assertions fail with the old mocks put back (checked). - check-deploy / check-pr-forge hang tests: the 1 s limit bounds every call of the run, so at load ~31 an earlier call timed out first (1 failure in a targeted run, passes alone). The limit is 5 s; the stub still sleeps 60 s. --- .../air-1950-cleanup-keep-ignored-e2e.test.ts | 10 +++++++++- .../air-1950-cleanup-keep-ignored.test.ts | 19 ++++++++++++++++++- ...spec-1658-cleanup-worktree-removal.test.ts | 6 ++++-- .../check/__tests__/check-deploy.test.ts | 7 ++++--- .../check/__tests__/check-pr-forge.test.ts | 7 ++++--- 5 files changed, 39 insertions(+), 10 deletions(-) diff --git a/packages/codev/src/agent-farm/__tests__/air-1950-cleanup-keep-ignored-e2e.test.ts b/packages/codev/src/agent-farm/__tests__/air-1950-cleanup-keep-ignored-e2e.test.ts index ef8ccc453..f4471254e 100644 --- a/packages/codev/src/agent-farm/__tests__/air-1950-cleanup-keep-ignored-e2e.test.ts +++ b/packages/codev/src/agent-farm/__tests__/air-1950-cleanup-keep-ignored-e2e.test.ts @@ -30,7 +30,14 @@ vi.mock('node:child_process', async () => { const actual = await vi.importActual('node:child_process'); return { ...actual, // execFileSync stays real: the keep module asks git which files to keep - execFile: vi.fn((_c: string, _a: string[], cb: (e: Error | null, out: string) => void) => { cb(null, ''); return {}; }), + // `ps` (cmd, args, cb) is faked; the dirty notice's `git status` (cmd, args, options, cb) runs for real. + execFile: vi.fn((c: string, a: string[], optionsOrCb: unknown, maybeCb?: unknown) => { + if (typeof optionsOrCb !== 'function') { + return (actual.execFile as unknown as (...args: unknown[]) => unknown)(c, a, optionsOrCb, maybeCb); + } + (optionsOrCb as (e: Error | null, out: string) => void)(null, ''); + return {}; + }), }; }); @@ -132,6 +139,7 @@ describe('afx cleanup --keep-ignored, end to end (#1950)', () => { } expect(logged).toContain(`Kept 3 file(s) in ${keptDir}`); expect(logged).toContain('Not kept (dependency or build output): 1 file(s)'); + expect(logged).toContain('Worktree has uncommitted changes: 1 uncommitted file(s)'); // notes.md, read by real git status expect(steps).toContain(`git worktree remove "${worktree}" --force`); expect(mockRemoveBuilder).toHaveBeenCalledWith('bugfix-7', workspaceRoot); }); diff --git a/packages/codev/src/agent-farm/__tests__/air-1950-cleanup-keep-ignored.test.ts b/packages/codev/src/agent-farm/__tests__/air-1950-cleanup-keep-ignored.test.ts index c0a048dfe..eaa7f1f59 100644 --- a/packages/codev/src/agent-farm/__tests__/air-1950-cleanup-keep-ignored.test.ts +++ b/packages/codev/src/agent-farm/__tests__/air-1950-cleanup-keep-ignored.test.ts @@ -17,11 +17,18 @@ vi.mock('../db/index.js', () => { return { getDb: () => db, getGlobalDb: () => db, closeDb: () => {}, closeGlobalDb: () => {} }; }); vi.mock('../db/mailbox.js', () => ({ dismissHeldForAgent: () => 0 })); +// execFile has two callers: `ps` (cmd, args, cb) and the dirty notice's `git status` +// (cmd, args, options, cb). `gitStatusOut` is what that status reports. +let gitStatusOut = ''; vi.mock('node:child_process', async () => { const actual = await vi.importActual('node:child_process'); return { ...actual, - execFile: vi.fn((_c: string, _a: string[], cb: (e: Error | null, out: string) => void) => { cb(null, ''); return {}; }), + execFile: vi.fn((c: string, a: string[], optionsOrCb: unknown, maybeCb?: unknown) => { + const cb = (typeof optionsOrCb === 'function' ? optionsOrCb : maybeCb) as (e: Error | null, out: string) => void; + cb(null, c === 'git' && a[0] === 'status' ? gitStatusOut : ''); + return {}; + }), }; }); @@ -69,6 +76,7 @@ vi.mock('../lib/keep-files.js', async (importOriginal) => ({ })); const { cleanup } = await import('../commands/cleanup.js'); +const { logger } = await import('../utils/logger.js'); const workspaceRoot = join(root, 'ws'); const worktree = join(workspaceRoot, '.builders', 'bugfix-7'); @@ -101,6 +109,7 @@ describe('afx cleanup --keep-ignored (#1950)', () => { beforeEach(() => { vi.clearAllMocks(); steps.length = 0; + gitStatusOut = ''; rmSync(keptDir, { recursive: true, force: true }); mkdirSync(worktree, { recursive: true }); mockGetConfig.mockReturnValue(config()); @@ -136,6 +145,14 @@ describe('afx cleanup --keep-ignored (#1950)', () => { expect(removed()).toEqual({ worktree: false, branch: false, row: false }); }); + it('the dirty notice reads git status, not the "Unable to check status" fallback', async () => { + gitStatusOut = ' M notes.md\0'; + await cleanup({ issue: 7 }); + const notices = vi.mocked(logger.info).mock.calls.map(([msg]) => String(msg)); + expect(notices).toContain('Worktree has uncommitted changes: 1 uncommitted file(s)'); + expect(notices).not.toContain('Worktree has uncommitted changes: Unable to check status'); + }); + it('keeps nothing without the flag', async () => { await cleanup({ issue: 7 }); expect(mockKeepFiles).not.toHaveBeenCalled(); diff --git a/packages/codev/src/agent-farm/__tests__/spec-1658-cleanup-worktree-removal.test.ts b/packages/codev/src/agent-farm/__tests__/spec-1658-cleanup-worktree-removal.test.ts index eaec0cedf..4b686241f 100644 --- a/packages/codev/src/agent-farm/__tests__/spec-1658-cleanup-worktree-removal.test.ts +++ b/packages/codev/src/agent-farm/__tests__/spec-1658-cleanup-worktree-removal.test.ts @@ -126,8 +126,10 @@ describe('Spec 1658: cleanup removes an ephemeral worktree', () => { mkdirSync(worktree, { recursive: true }); mockGetConfig.mockReturnValue(config()); mockLoadState.mockReturnValue({ builders: [bugfixBuilder], architects: [], utils: [], annotations: [] }); - vi.mocked(execFile).mockImplementation(((_cmd: string, _args: string[], cb: (e: Error | null, out: string) => void) => { - steps.push('ps'); + // Two callers: `ps` (cmd, args, cb) and the dirty notice's `git status` (cmd, args, options, cb). + vi.mocked(execFile).mockImplementation(((cmd: string, _args: string[], optionsOrCb: unknown, maybeCb?: unknown) => { + if (cmd === 'ps') steps.push('ps'); + const cb = (typeof optionsOrCb === 'function' ? optionsOrCb : maybeCb) as (e: Error | null, out: string) => void; cb(null, ''); return {} as ReturnType; }) as unknown as typeof execFile); diff --git a/packages/codev/src/commands/check/__tests__/check-deploy.test.ts b/packages/codev/src/commands/check/__tests__/check-deploy.test.ts index 1c766b82e..1f1950cc9 100644 --- a/packages/codev/src/commands/check/__tests__/check-deploy.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-deploy.test.ts @@ -293,10 +293,11 @@ describe.skipIf(isWindows)('Spec 1951 — check deploy (stub git)', { timeout: 3 runs.hang(); const started = Date.now(); - const { report } = await runReadOnly(['8'], { timeoutMs: 1_000 }); + // The limit bounds every call of the run: 1 s let an earlier call time out first under load. + const { report } = await runReadOnly(['8'], { timeoutMs: 5_000 }); - expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'not-run', reason: 'workflow-runs timed out after 1s' }); - expect(Date.now() - started).toBeLessThan(15_000); + expect(byId(report, 8, 'deploy-run')).toMatchObject({ status: 'not-run', reason: 'workflow-runs timed out after 5s' }); + expect(Date.now() - started).toBeLessThan(20_000); // the stub sleeps 60 s }); it('a deploy branch origin does not have: on-branch not run', async () => { diff --git a/packages/codev/src/commands/check/__tests__/check-pr-forge.test.ts b/packages/codev/src/commands/check/__tests__/check-pr-forge.test.ts index 40c51e837..f10931ef6 100644 --- a/packages/codev/src/commands/check/__tests__/check-pr-forge.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-pr-forge.test.ts @@ -488,11 +488,12 @@ describe.skipIf(isWindows)('Spec 1951 — check pr: forge state and CI (stub git forge.answer(prView(head)); const started = Date.now(); - const { report, exitCode } = await runReadOnly({ timeoutMs: 1_000 }); + // The limit bounds every call of the run: 1 s let an earlier call time out first under load. + const { report, exitCode } = await runReadOnly({ timeoutMs: 5_000 }); expect(exitCode).toBe(1); - expect(byId(report, 'checks')).toMatchObject({ status: 'not-run', reason: 'commit-checks timed out after 1s' }); - expect(Date.now() - started).toBeLessThan(15_000); + expect(byId(report, 'checks')).toMatchObject({ status: 'not-run', reason: 'commit-checks timed out after 5s' }); + expect(Date.now() - started).toBeLessThan(20_000); // the stub sleeps 60 s }); it('check.skip ["checks"] skips it by name without asking the forge', async () => { From cbd70ecd818467e57eef4185d6dd86a7a9e11fe0 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 12:12:26 -0800 Subject: [PATCH 87/94] [Spec 1951] Review: retrospective, consultation dispositions, lessons routed to the cold tier - codev/reviews/1951-read-only-pr-check-for-archite.md: spec compliance, live runs (check pr 1958 at a four-commit porch tail, 1640, earlier phases), deviations per phase, commits no reviewer has seen, per-round consultation dispositions with the allow-list/stub tightening table, flaky tests. - lessons-learned.md (cold): callback-mock arity; three-layer read-only proof; per-run timeouts under load; realpathSync.native on Windows; git status -z parsing; porch review-round order. - pr.ts: one comment on checkCi's own check.skip test (claude, Phase 4 iter2 note 5). - Thread log: review phase. --- codev/resources/lessons-learned.md | 9 + .../1951-read-only-pr-check-for-archite.md | 443 ++++++++++++++++++ codev/state/spir-1951_thread.md | 16 + packages/codev/src/commands/check/pr.ts | 1 + 4 files changed, 469 insertions(+) create mode 100644 codev/reviews/1951-read-only-pr-check-for-archite.md diff --git a/codev/resources/lessons-learned.md b/codev/resources/lessons-learned.md index 42a3e6c0a..babb69456 100644 --- a/codev/resources/lessons-learned.md +++ b/codev/resources/lessons-learned.md @@ -229,6 +229,8 @@ Generalizable wisdom extracted from review documents, ordered by impact. Updated - [From #1658] On Windows, Node's `detached: true` is not `setsid`. libuv never requests job breakaway, so a "detached" child stays in its parent's Job Object and dies with that session. A process that must outlive the session that starts it (the Tower daemon) has to be created outside the job, e.g. through CIM `Win32_Process.Create`. [From #1915] The opposite trap: a job that ALLOWS breakaway loses everything Git Bash starts, because the MSYS runtime asks for breakaway on every native program. Measure job membership (`QueryInformationJobObject` process list) of a real session before trusting "the job holds the session". +- [From 1951] `git status --porcelain` without `-z` C-quotes any path holding a space, a quote or a non-ASCII letter (`?? "a b.txt"`, `?? "\303\251.txt"`), so code that then stats the path fails on it. Use `-z` and read the output whole: a helper that trims stdout (like agent-farm's `run()`) drops the first entry's leading status space (` M f` → `M f`). A rename or copy entry is followed by its source path, which must be skipped. + ## Process - [From #1482] **A conditional authorization is only as good as its condition — verify the condition, not the approval.** A reviewer pre-authorized dropping a UI change *if* browser verification was infeasible. It was feasible (Playwright was installed all along); the condition was false, so the authorization never applied. Disclosing the gap prominently and refusing to claim an unperformed verification was right and is what made it reviewable — but disclosure is not verification. Two minutes running the check would have beaten a commit, a caveat, and a retraction. When citing an approval, restate the condition it rested on and confirm that condition still holds. @@ -488,6 +490,11 @@ Generalizable wisdom extracted from review documents, ordered by impact. Updated - [From #1920] **A fixture recorder that adds environment production does not add records a screen production never shows.** Spec 1658's ConPTY recorder set `TERM=xterm-256color` itself, so every capture drew claude's Unicode `❯` marker, while real architects (launched as bare `claude` with Tower's env and no `TERM`) drew the ASCII fallback `>`, and the gate held all their mail. The suite stayed green for exactly that reason. Record with the env the production launch path builds, and when a recorder must deviate, make it a named switch (`--bare-env`) so the production-shaped capture can still be taken. The quickest diagnosis was a read-only viewer attach to the held session: the replay frame IS the gate's mirror. +- [From 1951] **A mock of a callback API must take every arity the code calls.** Cleanup's dirty notice calls `execFile(cmd, args, options, cb)`, but three suites mocked `execFile(cmd, args, cb)`. The options object was then "called" as the callback, the throw rejected the promise, and every suite silently took the "Unable to check status" path while passing. When a call gains an argument, grep every test that mocks the function. Assert the observable result (the notice's text), and check that the assertion fails with the old mock put back. +- [From 1951] **A read-only claim needs three checks that do not share code.** First, a runtime allow-list in the one module allowed to spawn. Second, stub `git`/`gh` executables first on `PATH` that keep their own grammar and record every argv. Third, a real-repository snapshot (refs, `HEAD`, index bytes, `FETCH_HEAD` in both the worktree and common git dirs, `status`). Each of three review rounds still found the stub too loose: a `symbolic-ref` write form, flags not closed per subcommand, `gh api -XPOST` spelled joined, and arguments left unchecked. `git diff A B` with two file paths is an implicit `--no-index` diff of arbitrary files, and `ls-remote` takes any remote, `ext::` transports included. Check arguments, not only flags. +- [From 1951] A test that sets one short timeout bounding every call of a run can fail on the wrong call under machine load: an earlier call times out first, and the assertion on the hung call's reason fails. Size the limit so the other calls fit (here 5 s against a stub that sleeps 60 s), and assert that the reason names the call that hung. +- [From 1951] On Windows CI, `fs.realpathSync` keeps 8.3 short names (`C:\Users\RUNNER~1\…`) while git prints the long path (`runneradmin`). A fixture root that is compared with git's output needs `fs.realpathSync.native`; nine tests failed on this one cause. + ## UI/UX - [From #1938] React 19 compares `dangerouslySetInnerHTML` by object identity, not by its @@ -712,6 +719,8 @@ Generalizable wisdom extracted from review documents, ordered by impact. Updated - [From 1233] `--resume` restores the transcript, not the momentum: a resumed interactive agent sits idle until a user turn arrives. For unattended agents (builders), deliver a short nudge prompt with the resume (`claude --resume ""` — verified to process the positional prompt as the next turn); otherwise a fix for context loss silently becomes a stalled-lane incident, which is harder to spot because the pane looks healthy. Human-attended sessions (architects) don't need the nudge. - [From #1494] A relay meant to *trigger* an action must read as an imperative instruction, not a past-tense fact. A VS Code gate approval phrased "Human approved X in VS Code" was read by the receiving architect as *already done*, so it never relayed and the builder stalled at the gate; "Approve X, please pass it to the builder" is a call to act. Corollary: message provenance (who sent it, from where) belongs in **structured attribution** (the `from` field and the rendered header `[USER via VS Code]`), not in body text, or it leaks to downstream recipients and can be misread. Both failure modes surfaced only in a live end-to-end run, never in unit tests. +- [From 1951] A porch review round runs: rebuttal → `porch done` → `porch next` (opens the re-iteration; build and tests start unrun) → `porch done` → `porch next` (consultation). Run `porch next` first after a round, so the rebuttal task is named. A `porch done` before it only re-signals the old iteration. When porch force-advances at the three-iteration ceiling, the last round's fix is never reviewed: list those commits under a heading of their own in the PR body and the review, for the pr-phase reviewers. + ## Debugging and Root Cause Analysis - [From #1917] **A symptom seen on one platform can come from a platform-neutral bug that another platform happens to mask.** The Windows double cursor looked like a ConPTY problem. It was Tower's attach snapshot dropping cursor visibility everywhere; on macOS the re-shown hidden cursor sits on claude's drawn one, so nobody could see it. Trace the state through every hop (here: raw stream → mirror → serialized snapshot → client) on a captured stream before blaming the platform layer, and check what a serializer drops, not just what it round-trips: the #1354 round-trip suite compared cells and cursor position and so could not see a lost mode. diff --git a/codev/reviews/1951-read-only-pr-check-for-archite.md b/codev/reviews/1951-read-only-pr-check-for-archite.md new file mode 100644 index 000000000..23ac1640c --- /dev/null +++ b/codev/reviews/1951-read-only-pr-check-for-archite.md @@ -0,0 +1,443 @@ +# Review: Read-only PR check for architects (`codev check pr | deploy | worktree`) + +## Summary + +This project adds `codev check`, a read-only command group: +- `check pr ` collects what an architect reads before recommending a merge; +- `check deploy …` says whether merged PRs reached the deploy branch; +- `check worktree ` says whether removing a builder's worktree would lose data. + +It shipped in seven plan phases: +1. forge read concepts; +2. a read-only runner and report core; +3. `pr` merge mechanics; +4. `pr` forge and CI checks; +5. `deploy`; +6. `worktree`; +7. architect guidance and docs. + +The commands are read-only by construction. One runner spawns every subprocess and checks it against a closed git grammar and four read concepts. Stub `git`/`gh` executables on `PATH` fail the tests on any other invocation. Real-repository snapshot tests show that no ref, `HEAD`, index, `FETCH_HEAD` or working-tree file changes. Each command has been run on real PRs and worktrees in this repository, by the builder and again by the architect from the main checkout. + +## Spec Compliance + +- [x] **The three commands exist, appear in `codev --help`, and produce the specified sections and verdicts.** Phases 3–6. `codev --help` lists `check`, and `codev check --help` lists `pr`, `deploy` and `worktree`. +- [x] **Headline path verified end-to-end** (Phases 3–4, and again in the review). The runs are recorded under *Live runs* below: + - `check pr` on this project's PR, #1958, with a porch-only head; + - an attribution hit on #1657, from a scratch clone with its own patterns. +- [x] **Read-only, enforced at runtime** (Phase 2). `runner.ts` is the only module that may import `child_process` or the forge dispatcher; the audited-imports test enforces this. Any argv outside the closed per-subcommand grammar, or any concept other than `pr-view`, `pr-search`, `commit-checks` and `workflow-runs`, throws `RunnerRefusal` (exit 2) before anything is spawned. `allow-list.test.ts` and `runner.test.ts` cover this. +- [x] **Read-only, enforced in tests** (Phases 2–6). `helpers/stub-bin.ts` puts stub `git` and `gh` first on `PATH`. Each stub keeps its own closed grammar and records every argv. All three commands run under them in the `*-stubs` and stub-git suites. The stub `gh` refuses `pr merge`, `pr comment`, and `gh api` with a method or field flag in any spelling. The tightening is listed round by round under Consultation Feedback. +- [x] **No state change, proven on a real repository** (Phases 2–6). `check-pr-readonly`, `check-deploy-readonly` and the worktree suites snapshot: + - `for-each-ref`, `HEAD` and the index bytes; + - `FETCH_HEAD`, in both the worktree git dir and the common dir; + - `status --porcelain`. + + The runs include a conflicting trial merge, a ref-neutral fetch of missing objects (with tags on origin), and a run from a linked worktree. The snapshots are identical before and after. +- [x] **Live base** (Phase 3). The trial merge uses `ls-remote`'s tip, and a test deliberately leaves the local `origin/main` stale. +- [x] **Exact head, live base, no race** (Phase 3). `pr-view` and `ls-remote` are re-read at the end. A moved head or base is attention ("head|base moved during check"), and overrides a `check.skip` of the check that carries it. There is a test for each. +- [x] **Bounded time** (Phases 1–5). Every forge call, and every `ls-remote` and `fetch`, has a timeout. A hanging `commit-checks` or `workflow-runs` makes its check `not run: … timed out after Ns`. A hanging anchoring `pr-view` is exit 2. +- [x] **Porch-only head** (Phase 4). `porch-only.ts` finds the last code commit by the plan's walk, which reads at most 11 commits and makes at most 10 lookups. The code runs show beside the head's, and they drive the verdict. Tests cover runs only on head, only on an earlier commit, on neither, a failure on either, and main merged into a porch-only branch. +- [x] **Never reported as passing** (Phases 4–6). For each forge-dependent check, a disabled concept and a failing concept both give `not run: …` with exit 1 (Scenario 24 tests). +- [x] **Exit codes** (Phases 3–6). Each command has tests for 0, 1 and 2, and `--json` carries the same verdict. For `check deploy`, a PR that cannot be read is a per-PR `not run` (Scenario 15a, as recorded in the deviations). +- [x] **`--json` matches the schema** (`schema: 1`), including the `error` object on exit 2 (Phases 2–6). The report-shape helpers check every report. The fields this project added beyond the spec's schema are listed under Deviations (Phase 7), and `codev.md` documents them. +- [x] **Input validation** (Phase 2). PR numbers, SHAs, builder ids and paths, and config strings are validated before any subprocess runs. A violation exits 2 naming the value (Scenario 28a). +- [x] **Configuration** (Phases 2–6). Each `check.*` key and `cleanup.keepIgnored` changes behaviour as specified, and arrays replace the defaults. An invalid value exits 2 naming the key and the file it came from, including a fake `~/.codev/config.json` layer. +- [x] **Forge contract** (Phase 1). + - `pr-view` gains seven optional fields. + - The new concepts `commit-checks` and `workflow-runs` have documented contracts. + - github implements them; gitlab and gitea disable them explicitly, so they never fall through to `gh`; linear and jira resolve to github. + - `codev doctor` lists the new concepts. +- [x] **Docs in both trees** (Phase 7). + - The architect role, `risk-triage.md`, the `codev` command reference, `workflow-reference.md` and `overview.md` changed in both trees. + - The `codev` skill changed in all four copies, and the shipped hashes were regenerated. + - The forge skill and `forge.md` document the new concepts and fields. +- [x] **Full test suite and Windows**, with the qualification below. + - Under owner ruling main-38 ("ci-first"), the builder never ran the full suite locally. GitHub's run (8/8, which includes the full unit suite on Node 22 and 24) stood in for porch's local `tests` check at every phase head. The architect confirmed each run, and each skip is listed in the PR body. + - Windows runs: + - 45462452355 failed 9 fixture-side tests (8.3 short names), fixed in `f93aa60e1`; + - 45465468867 and 45471312317 passed; + - a run on the final head is linked in the PR body. + +Test scenarios: 1–28a each have at least one test in `packages/codev/src/commands/check/__tests__/`. Scenario 30 holds: the human summary for #1958 is 15 lines, blank lines included. Scenario 29 was measured on bigger PRs than it names, because no open 25-file PR with a three-commit porch tail existed (see Deviations, Review phase). + +### Live runs + +Every run below changed no ref; the `for-each-ref` and `FETCH_HEAD` checksums were identical before and after. + +**Review phase** (worktree build, 2026-11-24, machine load about 20–31). + +`codev check pr 1958` at head `7d312a2`, which is four porch-only commits above the last code commit `0c02478`. 7.3 s, exit 1: + +``` +ATTENTION PR #1958 — state (draft) + +PR #1958 [Spec 1951] Read-only PR check for architects: codev check pr | deploy | worktree OPEN (draft) builder/spir-1951 → main +head 7d312a2 (local builder/spir-1951 matches) base main @ e0e96fd (origin, live) + + ATTN state OPEN but a draft: it must be marked ready for review first + ok forge MERGEABLE, BLOCKED (review required) + off attribution no patterns configured (check.attribution) + ok trial merge clean into main @ e0e96fd + ok checks head 7d312a2: porch-only, 8 passed + info watched .claude/skills/codev/SKILL.md, .claude/skills/forge/SKILL.md, … +1 + info linked issue "Fixes #1951" — matches builder/spir-1951 + info overlap no file also changed on main since the branch point + info size +14,415 −86 in 95 files + info to read 83 files (12 not for reading): codev/plans/1951-read-only-pr-check-for-archite.md, … +82 +``` + +The head is porch-only and every head run passed, so by the walk's rule the head's result stands and no code line is needed. Phase 4 recorded the two-line case (`code … / head …: porch-only …`) on this PR at `899e8e9`. + +`codev check pr 1640` (44 files, open). 7.6 s, exit 1: + +``` +ATTENTION PR #1640 — forge (conflicts), trial merge (conflicts) + ATTN forge CONFLICTING, DIRTY + ATTN trial merge 15 conflicting files merging into main @ e0e96fd: .claude/skills/afx/SKILL.md, .codex/skills/afx/SKILL.md, … +13 + ok checks head e7458f1: 7 passed + info overlap 30 files also changed on main since the branch point: … + info size +6,163 −248 in 44 files +``` + +The forge's own mergeability agrees with the trial merge. + +**Earlier phases**, from the thread log (`codev/state/spir-1951_thread.md`): +- **Phase 4.** + - #1965: `ATTENTION — checks (running)`, with `code 31d3edf: 4 passed, 4 still running` and `head 0513558: porch-only, 8 still running`; later CLEAR at its pr gate. + - #1957 (draft): `ATTENTION — state (draft), checks (running)`. + - #1958: `code ac72f4a: no runs` and `head 899e8e9: porch-only, 7 passed, 1 still running`. + - **Attribution hit**: #1657 from a scratch clone with `^\s*Co-Authored-By:` and `Generated with \[Claude Code\]` configured: `5 lines: description line 118, commit 23de988 "Co-Authored-By: Claude Opus 5…", … +3`. The forge reported `CONFLICTING, DIRTY`, agreeing with `trial merge 5 conflicting files`. +- **Phase 5.** + - `check deploy 1959 1955` → `CLEAR … on main; checks on the merge commits passed`. + - `check deploy 1959 99999 1965` → `ATTENTION #99999 not read; #1965 not merged`. + - A scratch clone with `check.deploy: {branch: main, workflow: test.yml}` → `ok deploy run latest green test.yml run … contains …`. +- **Phase 6.** + - `check worktree air-1938` → REMOVABLE, exit 0. + - `bugfix-1956` → REMOVABLE AFTER KEEPING 2 FILES, with its PR open (exit 1). + - `spir-1951` → NOT REMOVABLE (work in progress). + - The architect added bugfix-1901 (REMOVABLE, no PR found) and pir-1620 (REMOVABLE, PR #1203 open, 70 commits all on origin). + +## Deviations from Plan + +The architect accepted each of these when it was made. The thread log has the reasoning. + +**Phase 1 (forge_read_concepts)** +- `pr-view` also gained `reviewDecision`. Architect ruling: `forge`'s verdict follows `mergeable` alone, and the merge state and review decision are context. +- gitlab `pr-view` now maps `body`, `baseRefName` and `headRefName`, a contract fix beyond "existing fields pass through". Its pipefail (#1645) and `forge-executable` (#1455) fixes were made in place. + +**Phase 2 (readonly_core)** +- The runner bounds `ls-remote` and `fetch` by subcommand, with no caller flag. +- Pathspecs are `:(top,glob)`, so matching is anchored at the repository root from any cwd. +- `diff` runs with `--no-renames`, so a file renamed away from a watched path still shows. +- `config` allows `--get` only (`--get-regexp` was dropped). +- `fetch` requires `--no-tags --no-recurse-submodules`. +- Porch force-advanced the phase at three iterations (see *Commits no reviewer has seen*). + +**Phase 3 (check_pr_mechanics)** +- `pr.baseTip` is `string | null`: null when `ls-remote` failed or origin lacks the base. +- `head` compares the local branch only when origin's branch of that name is the PR head. Otherwise it is info. This keeps a fork's PR from its own `main` from reading as "diverged". The JSON adds `details` `relation`, `behindPr` and `originBranchSha` (and, after the Phase 4 fold-in, `originAheadOfPr`). +- A moved base or head overrides a `check.skip` of its carrier check. +- Lists are cut by width (72 characters), not by count. +- Group-level usage errors stay human-only on stderr, since they have no command for an `ErrorReport`. + +**Phase 4 (check_pr_forge)** +- *Ten-commit edge.* The walk reads at most 11 commits; more than 10 porch-only commits makes the check `not run`. Lookups stay at 10 with C always among them, so with exactly ten porch-only commits the oldest is never looked up. If that commit alone carried runs and C had none, "no runs" would show for tested code. This is a documented trade-off. +- The verdict qualifier for `checks` goes failed, then running, then none. +- An ok `state` reads in the header (`OPEN`), not on a line of its own, like an ok `head`. This differs from the spec's "one line per check"; the JSON has every check. +- `forge` wording: `MERGEABLE, CLEAN`, `MERGEABLE, BLOCKED (review required)`, and `MERGEABLE (merge state not reported)` when the preset omits it (gitea). +- `linked-issue` with several closing keywords, one of which matches the branch's issue, is info naming the others. `details.references` lists every keyword found. +- `pr.state` is normalized (OPENED → OPEN, merged → MERGED). +- `checks.details.lastCodeCommit` is `null` when every commit since the branch point is porch-only. +- `checks` is computed before the head re-read. After a head move it describes the old head, but the verdict is attention through `head` anyway. + +**Phase 5 (check_deploy)** +- *15a*: the reason for a PR that cannot be read is the forge's own words (`pr-view failed: GraphQL: Could not resolve to a PullRequest …`), not a parsed "PR not found". Telling not-found from other failures would mean parsing provider-specific stderr. The verdict line says `#99999 not read`. +- `workflow-runs` order is trusted to be newest first, as the concept's contract says; it is not re-sorted. +- The JSON order follows `DEPLOY_CHECK_IDS`, and the human order follows the spec sample. `deploy run` lines carry the run's date on attention too. +- There is no end-of-run re-read: a deploy branch only moves forward. +- `merge checks` with no runs is attention. A project with no CI on its base declares `check.skip: ["merge-checks"]`. + +**Phase 6 (check_worktree)** +- `commits.details` is `{ total, notOnBase, unsafe }`. `unsafe` (added) is the subset on no remote branch and not covered by the squash rule. +- `pr`: + - MERGED and CLOSED are ok; CLOSED means finished, and the data is judged by git; + - OPEN and "no PR found" are attention; + - when there are several PRs, the choice is exact `headRefName`, then OPEN, then the newest MERGED, then the newest CLOSED. +- `remote` that does not match is info (context only). A failed read is `not run`. +- `worktree.baseRef` and `baseTip` may be null. +- Keep-list symlinks (decided over three review rounds): + - a keep-list symlink is data that `--keep-ignored` cannot keep, so it makes the worktree NOT REMOVABLE; + - each is printed with its target, and JSON `ignored.details.links` is `[{ path, target, missing }]`; + - entries spawn made are scaffold, recognised by shape (P → P in the main checkout, or a hard link or unchanged copy of it), not by re-matching spawn's node-glob patterns; they are counted in `ignored.details.scaffold`. +- The verdict line omits plain keep files but names keep-list symlinks. +- `regenerable` is approximate inside collapsed directories that hold keep files. +- Nested-repo `dir/` entries from `ls-files` are reported as the entry, not expanded. +- The wording of the spec sample was not matched where it could not be said truthfully (rebutted in iteration 2, note 4). +- *Owner-approved cleanup change (main-36).* `afx cleanup`'s `hasUncommittedChanges` uses the shared `isBuilderScaffold()` and lists untracked files one by one (`--untracked-files=all`). Without that, the write guard showed as the directory `?? .claude/hooks/`, which was the false "1 uncommitted file(s)" behind the decision. + +**Phase 7 (docs_guidance)** +- The JSON as shipped differs from the spec's schema table, and `codev.md` describes what ships: + - `head.relation`, `behindPr`, `originBranchSha` and `originAheadOfPr`; + - `forge.reviewDecision`; + - `linked-issue.references`; + - `commits.unsafe`; + - `ignored.links` and `ignored.scaffold`; + - `checks.lastCodeCommit: null`; + - nullable `pr.baseTip` and `worktree.baseRef`/`baseTip`. +- `workflow-reference.md` was updated beyond the plan's list. +- Fixed in place: `risk-triage.md` told readers to run `gh pr diff --stat`, but `gh pr diff` has no `--stat` flag. +- Cleanup's dirty notice shares `isSpawnMade` with `check worktree` (`f93aa60e1`, architect-ordered from Claude's Phase 6 iteration 3 note 3). It reads status with `-z`, so quoted paths are judged correctly (`0c02478dd`). + +**Review phase** +- Three cleanup suites mocked `execFile` in its three-argument form, so the dirty notice silently took its "Unable to check status" path (`017f0baea`, Claude's Phase 7 iteration 2 note 2, architect order). + - `air-1950-cleanup-keep-ignored` now asserts the real notice; + - `air-1950-cleanup-keep-ignored-e2e` runs `git status` for real; + - `spec-1658-cleanup-worktree-removal` records `ps` only for `ps`. + - The two new assertions fail with the old mocks put back. +- Two of this project's own hang tests failed under load ~31, because their 1 s limit bounds every call of the run. The limit is now 5 s. +- One comment in `checkCi`, from Claude's Phase 4 iteration 2 note 5. +- Scenario 29 names "a 25-file PR with a 3-commit porch tail". Of the 150 most recent PRs with 15–40 files, none ended in three porch commits, and no open PR had about 25 files. Measured instead: + - #1958 (95 files, a four-commit porch tail): 7.3 s; + - #1640 (44 files): 7.6 s; + - #1965 in Phase 4: 6.5 s. + + All are under the 30 s bound. + +## Commits No Reviewer Has Seen + +Porch force-advanced two phases at the three-iteration ceiling, so CMAP never reviewed the round-3 fixes: + +- **Phase 2:** + - `aa7e34f58`: + - the stub `git`'s `ls-remote` accepts only `origin`, then `HEAD` or `refs/…` names; + - the stub refuses path and URL arguments to revision-taking subcommands, which closes an implicit `--no-index` diff of files outside the repository; + - `ls-files` and `status` take no arguments, and `for-each-ref` takes `refs/` patterns only; + - a one-line `liveTip` branch-name guard. + - `c42251ec5`: the `ext::` refusal case no longer uses a `/tmp` path. + - Both are confined to `commands/check/` test helpers, apart from the one-line guard in `git-facts.ts`. +- **Phase 6:** + - `a1ccc442b`: spawn's native-Windows link fallbacks (a hard link, or an unchanged copy) are scaffold, and several keep-list links print one per line. + - At the architect's request, Phase 7's reviewers reviewed this rule through `f93aa60e1`, which moved it into `agent-farm/lib/builder-scaffold.ts`. Both approved in iteration 2. + +## Consultation Feedback + +The lanes were Codex (`gpt-5.6-sol`) and Claude; this project's `porch.consultation.models` does not include Gemini. There was no `CONSULT_ERROR`. + +Several outputs carry a "WORKING TREE CHANGED during the review (#1649)" warning. Each named `.builder-state.md` or the thread log, which the builder wrote while the lanes ran; no reviewed file changed. + +### Specify (Round 1) + +#### Codex — REQUEST_CHANGES +- **Concern**: the live base could race the head. → **Addressed**: the base tip is re-read with the head at the end. +- **Concern**: `check-attr --source` needs git 2.40. → **Addressed**: the "to read" rule is globs only, and `check-attr` was removed from the allow-list. +- **Concern**: the worktree verdict semantics were inconsistent. → **Addressed**: the verdict answers only "would removal lose data?"; lifecycle is the separate `pr` check. +- **Concern**: no JSON schema. → **Addressed**: a typed schema was added. +- **Concern**: the trust boundary was overstated. → **Addressed**: it is stated precisely. + +#### Claude — COMMENT +- **Concern**: `check-attr`. → **Addressed**, as above. +- **Concern**: "merge-tree is the only write". → **Addressed**: object-store additions only. +- **Concern**: no timeouts. → **Addressed**: 30 s per call, as a named `not run`. +- **Concern**: multi-PR deploy errors. → **Addressed**: a per-PR `not run`. +- **Concern**: #1950 landing order. → **Addressed**: a shared definition, with the cross-check test in whichever PR is second. +- **Concern**: no linked-issue check. → **Addressed**: added. +- **Concern**: input validation. → **Addressed**: a section was added. +- **Concern**: `.codex` skill mirrors. → **Addressed**: all four copies are named. + +### Plan (Round 1) + +#### Codex — REQUEST_CHANGES +- **Concern**: the plan assumed `findWorkspaceRoot()` returns the main checkout. → **Addressed**: the roots come from git. +- **Concern**: the allow-list was not closed. → **Addressed**: a closed per-subcommand grammar, with `--no-ext-diff --no-textconv` forced. +- **Concern**: the porch-only algorithm was inconsistent. → **Addressed**: an exact walk. +- **Concern**: deploy did not fetch the run's `headSha`. → **Addressed**. +- **Concern**: the structural test was too shallow. → **Addressed**: an audited-imports test. + +#### Claude — COMMENT +- **Concern**: `findWorkspaceRoot()`. → **Addressed**. +- **Concern**: an empty pathspec becomes "every file". → **Addressed**: short-circuited. +- **Concern**: `exitOverride` swallowed `--help`. → **Addressed**. +- **Concern**: the gitlab `pr-view` shape. → **Addressed**. +- **Concern**: dependency labels. → **Addressed**. +- **Concern**: Phase 3 was too large. → **Addressed**: split, giving seven phases. +- **Concern**: concept-count touchpoints. → **Addressed**. +- **Concern**: `commit-checks` call volume. → **Addressed**: two GETs per commit. +- **Concern**: smaller notes. → **Addressed**. + +### forge_read_concepts (Round 1) + +#### Codex — APPROVE +No concerns raised. + +#### Claude — APPROVE +- **Concern**: `mergeStateStatus` might need push access. → **Addressed**: probed `gh pr view --json mergeStateStatus,reviewDecision` on cli/cli without push access, and it works. +- **Concern**: the gitlab mapping goes beyond the plan. → **Addressed**: named in the PR body. Its `body` now defaults to `""` (`0448553f0`). +- **Concern**: gitlab has no empty-output guard. → **Addressed** (`0448553f0`). +- **Concern**: the legacy `/status` endpoint is not paginated. → **Addressed** (`0448553f0`). +- **Concern**: the repo-local forge skill tables. → **Addressed** in Phase 7. + +### readonly_core (Rounds 1–3) + +The architect ordered this table, so the owner can see how the read-only claim was tightened. + +| Round | Found in the runtime allow-list | Found in the test stubs | +|---|---|---| +| 1 | `fetch` lacked `--no-tags` (Claude); `isRefName` accepted `.lock` components (Codex) | stub `git` had no closed grammar: `symbolic-ref` write form, fetch by non-SHA (Codex); the snapshot read `FETCH_HEAD` only from the common dir (Claude) | +| 2 | `diff-tree` lacked the forced guards; origin's HEAD branch name was unvalidated (Claude) | stub flags not closed per subcommand, so `log` or `diff` without guards passed (Codex); stub `gh` missed joined write flags such as `-XPOST` and `--field=` (Codex); tests read the real `~/.codev` config (Claude) | +| 3 | `liveTip` branch argument not pre-validated (Claude, one line) | stub `ls-remote` arguments unchecked: another remote or an `ext::` transport (Codex). The architect-requested audit then found revision arguments unchecked (an implicit `--no-index` diff of arbitrary files), and `ls-files`/`status`/`for-each-ref` arguments | + +- **Round 1.** + - **Codex — REQUEST_CHANGES**: stub grammar; `.lock`. → **Addressed** (`5dea9be3e`). + - **Claude — REQUEST_CHANGES**: `--no-tags` and a test for the tag case; per-worktree `FETCH_HEAD`; error wording; `--get-regexp`. → **Addressed** (`5dea9be3e`). + - `check.flag` not validated against `check.watch`. → **Rebutted**: glob containment cannot be checked statically, so Phase 4 applies the meaning (a flagged file is a watched file that also matches `flag`). +- **Round 2.** + - **Codex — REQUEST_CHANGES**: per-subcommand stub flags; `gh` joined flags. → **Addressed** (`93a87a41e`). + - **Claude — REQUEST_CHANGES**: fake home; `diff-tree` guards; origin HEAD validation. → **Addressed** (`93a87a41e`). +- **Round 3.** + - **Codex — REQUEST_CHANGES**: stub `ls-remote` arguments. → **Addressed**, with the audit (`aa7e34f58`, `c42251ec5`), approved by the architect before the fix; never re-reviewed. + - **Claude — APPROVE**: `liveTip` guard. → **Addressed**. + - Claude's other notes. → **N/A**: empty versus invalid forge output was left for Phase 6. Strictness about unknown `check.*` keys, the fetch-globals set size and askpass are by design. + +### check_pr_mechanics (Round 1) + +#### Codex — APPROVE +No concerns raised. + +#### Claude — APPROVE +- **Concern**: commander-exit writes were not flushed before exit. → **Addressed** in Phase 4 (`410d5ec14`): `CheckExit` carries the pending writes, and `cli.ts` awaits them. +- **Concern**: `head` was info when origin's branch is ahead of the forge head. → **Addressed** (`410d5ec14`): attention when origin's branch descends from the forge head, decided only when that tip is local. +- **Concern**: `mergeBase()` output with several merge bases. → **Rebutted**: `git merge-base A B` without `--all` prints exactly one. +- **Concern**: local git failures in `numstat`, `changedFiles` or `countRange` exit 2 rather than a named `not run`. → **Not changed**: they run on commits `ensureCommits` has made local, so a failure means a broken repository, which is "the command failed". The reviewer named a shallow clone as the likely path; that was not tested, and it is listed under Follow-up Items. +- **Concern**: `localBranchSha`; `commander` allowed everywhere; `baseTip` nullability in the docs. → **Addressed** (Phases 4 and 7). + +### check_pr_forge (Rounds 1–2) + +- **Round 1.** + - **Codex — REQUEST_CHANGES**: `forge` is ok when `mergeStateStatus` is absent. → **Rebutted**, with the line changed. The architect ruled that the verdict follows `mergeable` alone, and gitea has no merge state, so requiring it would make `forge` not run on every Gitea PR. The line now says `MERGEABLE (merge state not reported)`. The architect kept the ruling. + - **Claude — APPROVE**, six notes: + 1. A git failure in the walk is now a named `not run`. → **Addressed**. + 2. The one-line form is chosen by SHA. → **Addressed**. + 3. The new argv forms are in the shared form table. → **Addressed**. + 4. A walk past the branch point. → **Addressed**: a fixture with main merged in. + 5. An origin tip that is not local stays info. → **Not changed**: the fold-in's scope. + 6. Extra `details` keys are additive. → **N/A**: documented. +- **Round 2.** + - **Codex — APPROVE**: no concerns. + - **Claude — APPROVE**, five notes: + 1. The ten-lookup edge. → **N/A**: a documented trade-off. + 2. `checks` before the re-read. → **N/A**: the verdict is attention anyway. + 3. An ok `state` reads in the header. → **N/A**: deliberate. + 4. `lastCodeCommit: null`. → **Addressed**: documented in Phase 7. + 5. A comment on `checkCi`'s skip test. → **Addressed** in the review phase. + +### check_deploy (Round 1) + +#### Codex — APPROVE +No concerns raised. + +#### Claude — APPROVE +- **Concern**: the `runsOf` cache was keyed by branch only. → **Addressed** (`ef9502a13`). +- **Concern**: newest-first is trusted. → **Rebutted**: it is the concept's contract; recorded above. +- **Concern**: an `isAncestor` failure was exit 2 and dropped the other PRs. → **Addressed** (`ef9502a13`): that PR's check is `not run`. +- **Concern**: "merge not read" when `state` is missing. → **Addressed**: `state not read`. +- **Concern**: test gaps (two bases; skipping `merged`/`on-branch`). → **Addressed** (`ef9502a13`). + +### check_worktree (Rounds 1–3) + +- **Round 1.** + - **Codex — REQUEST_CHANGES**: keep-list symlinks were counted as keep files, but `keepFiles()` never copies a link. → **Addressed** (`dd21e15ce`): links are listed apart. Round 2 reversed the "not data" half. + - **Claude — APPROVE**, six notes: + - The header when `commits` is skipped; `keepIgnored` read when `ignored` is skipped; the `as PrLookup` cast. → **Addressed**. + - "Unpushed" when the remote read failed. → **Addressed** differently: `commits` is `not run`. + - `regenerable` in collapsed directories; nested-repo `dir/` entries. → **N/A**: documented approximations. +- **Round 2.** + - **Codex — REQUEST_CHANGES**: a keep-list symlink is data (spec line 577), so links alone must not read REMOVABLE. → **Addressed** (`a56bf9a37`) with the architect's two conditions: spawn's links are scaffold by shape, and each remaining link is printed with its target. + - **Claude — APPROVE**: + - The `git-forms` catalogue. → **Addressed**. + - A gitignored `.builder-*` file; `details.links`; the two approximations. → **Addressed**: Phase 7 docs. + - The sample wording. → **Rebutted**: `all 31 commits are on origin/main` has no defined count. +- **Round 3** (force-advanced after it). + - **Codex — REQUEST_CHANGES**: native Windows spawn makes hard links and copies. → **Addressed** (`a1ccc442b`): `isSpawnMade`. + - **Claude — APPROVE**: + - Several links get one line each. → **Addressed**. + - A link to an unkept inside path blocks removal. → **N/A**: conservative, documented. + - Cleanup's notice counts a spawn link git does not ignore. → **Addressed** in Phase 7 (`f93aa60e1`) on the architect's order. + - The approximations. → **N/A**: documented. + +### docs_guidance (Rounds 1–2) + +- **Round 1.** + - **Codex — REQUEST_CHANGES**: cleanup parsed `git status --porcelain` without `-z`, so a quoted path counted a spawn-made entry as dirty. → **Addressed** (`0c02478dd`): `gitStatusZ`/`parseStatusZ`, plus the three safe-direction tests the architect asked for. + - **Claude — APPROVE**: + - The copy rule is broader than "spawn made it". → **Addressed**: a clause in `codev.md`. + - No test for a quoted path. → **Addressed**. + - A gitignored `.builder-*`; the skeleton samples name this repository. → **N/A**: already documented; the plan requires real samples. +- **Round 2.** + - **Codex — APPROVE**: no concerns. + - **Claude — APPROVE**, two notes: + 1. Of the four new safe-direction tests, only the quoted hard-link and copy test detects a parsing regression. The lone ` M` first entry, the quoted untracked name and the staged rename pass under the old line parsing too. → **N/A**, recorded here as the architect ordered: they pin the safe direction the architect asked for, and the discriminating test is the mutation-checked one. + 2. `air-1950-cleanup-keep-ignored`'s three-argument `execFile` mock sends the notice down "Unable to check status". → **Addressed** in the review phase (`017f0baea`), with the two sibling suites that had the same shape. + +## Lessons Learned + +### What Went Well + +- **Two independent read-only layers.** The runtime allow-list and the stub executables are separate code with separate grammars, sharing only test cases (`git-forms.ts`). Either one catches a regression in the other. Each review round tightened one of them, and the real-repository snapshot gave a third, behavioural check. +- **Live runs on real PRs at every phase**, repeated by the architect from the main checkout. They caught what tests framed by the code could not. Examples: a fork PR's `main` reading as "diverged"; the write guard's directory making `afx cleanup` report a false "1 uncommitted file(s)"; and `ls-files` without `--untracked-files=all` collapsing scaffold into one directory. +- **Shared definitions instead of parallel ones.** `keep-list.ts` and `builder-scaffold.ts` are imported by both `afx cleanup` and `check worktree`, with agreement tests, so the two cannot drift. +- **Mutation checks on new tests.** Putting the old code back and watching each new test fail caught non-discriminating tests twice (Phase 7's parsing tests; the review phase's mocks). + +### Challenges Encountered + +- **What counts as data.** Keep-list symlinks flipped across three rounds: counted as keep files, then "not data", then data. Spawn's Windows fallbacks (hard links and copies) came up only in round 3. The spec said "ignored keep-list paths are data" without considering file kinds. It resolved when the architect set a rule: an entry spawn made, recognised by shape or bytes, is scaffold; anything else is data, printed with its target. +- **Windows path spellings.** The first Windows run (Phase 6) failed 9 tests, all from the fixture's `realpathSync` keeping the runner's 8.3 short name. The audit that followed found one raw comparison of two git-listed spellings, which was fixed and tested through a symlinked parent on every platform. +- **Machine load.** Porch's local `tests` check failed under load from Phase 1 (#1956). Owner rulings main-32, then main-38 ("ci-first"), made GitHub's run stand in for it. Each phase then needed a push, a wait for 8/8, the architect's word, and a one-time skip. That was slow but auditable; every skip is in the PR body. +- **Porch sequencing.** In Phase 6 a `porch done` ran before `porch next` had read the round's verdicts, so it re-signalled the old iteration. +- **Force-advances.** Two phases hit the three-iteration ceiling with fixes no reviewer saw. Those are now listed under their own heading. +- **Message delivery.** One architect message arrived about 15 hours late. + +### What Would Be Done Differently + +- Settle "what is data" in the spec for every file kind (regular file, symlink, hard link, copy) on every platform spawn supports, before writing the check. +- Dispatch the Windows workflow in Phase 2, when the runner and fixtures first exist, not in Phase 6. +- When changing how a function is called (here `execFile` gained an options argument), grep every test that mocks it and fix their arity in the same commit. + +### Methodology Improvements + +- **Porch force-advance** could list the commits made after the last consultation and offer one closing review of just those, rather than leaving the builder to track them by hand. +- **Porch's `tests` check** could accept a targeted command, or a confirmed CI run on the exact head, as a first-class alternative under load. The present skip-and-restore dance relies on the builder's care. +- **cmap's working-tree-changed warning (#1649)** fires on the builder's own untracked state and thread-log writes. Excluding the builder's untracked state file would leave the warning for real changes. + +## Architecture Updates + +- Routed: cold, `codev/resources/arch.md` Core Components §9 "Read-only Checks (`codev check`) (Spec 1951)". It covers the runner as the single subprocess path, the audited imports, the four forge concepts, and the shared scaffold and keep-list modules with cleanup. Written in Phase 7 (`827eed9d4`). +- No hot-tier change. `codev check` is subsystem detail an agent needs only when touching it, and the architect role already tells architects when to run it. `arch-critical.md` stays within its cap. + +## Lessons Learned Updates + +- Routed: cold, Testing: a mock of a callback API must take every arity the code calls; assert the observable result and check that the assertion fails with the old mock. +- Routed: cold, Testing: a read-only claim needs a runtime allow-list, an independent stub grammar on `PATH`, and a real-repository snapshot. The stub must check arguments, not only flags. +- Routed: cold, Testing: a short timeout that bounds every call of a run fails on the wrong call under load. Size it for the other calls and assert the reason names the call that hung. +- Routed: cold, Testing: on Windows, `fs.realpathSync` keeps 8.3 short names while git prints the long path; fixture roots compared with git output need `realpathSync.native`. +- Routed: cold, Architecture: `git status --porcelain` without `-z` C-quotes unusual paths, and a helper that trims stdout eats the first `-z` entry's leading status space. +- Routed: cold, Protocol Orchestration: a porch review round runs rebuttal → `porch done` → `porch next` → `porch done` → `porch next`. Run `porch next` first after a round, and list the commits a force-advance left unreviewed. +- No hot-tier change. `lessons-critical.md` is at its cap, and none of these is more cross-cutting than what it holds. + +## Flaky Tests + +Pre-existing tests that failed only under machine load, each passing when run alone. Left running, never skipped: +- `packages/codev/src/commands/consult/__tests__/agy-auth-cache.test.ts`: timeouts in Phases 1 and 2. +- `packages/codev/src/agent-farm/__tests__/pir-1233-session-launch-loop.test.ts` and `bugfix-1267-launch-loop.test.ts`: timeouts in Phase 2. In Phase 1 the log names a "launch-loop" test without its prefix. +- `packages/codev/src/__tests__/windows-console-spawn-guard.test.ts`: failed once in porch's Phase 2 `tests` run. +- `packages/codev/src/agent-farm/__tests__/ide-command.test.ts`: failed once in Phase 1's full run. + +Spec 1912's lessons already record the first three as load-sensitive (#1956 is the cause being fixed). Porch's own output did not name them (#1853); vitest's results cache did. Under main-38 these failures took the porch `tests` check out of the loop for this project; each skip is listed in the PR body. + +Not pre-existing, and fixed rather than listed: this project's two hang tests (`check-deploy.test.ts`, `check-pr-forge.test.ts`), in the review phase. + +## Follow-up Items + +None of these needs action before merge. Each is a recorded trade-off or a candidate: +- `check pr` in a shallow clone is untested. Local git failures in `numstat`/`changedFiles` would be exit 2 rather than a named `not run` (Claude, Phase 3). +- `workflow-runs` ordering is trusted, not enforced. `createdAt` is parsed and could defend the "latest green" choice if a preset ever returns another order. +- `regenerable` is exact only outside collapsed directories, and nested-repo `dir/` entries are not expanded. Making either exact needs a directory walk outside the audited read-only imports. +- Retiring ci-first (main-38) is the owner's open decision main-39, tied to #1956 / PR #1965. diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 2ac04006c..ef451f7fa 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -395,3 +395,19 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals Tests: hard link + unchanged copy at quoted names not counted (fails with the old parsing: mutation-checked); ' M' first entry counted; quoted untracked name counted; staged rename counts once; a broken .git → "Unable to check status" (dirty). Cleanup suites incl. the execFile-mocking ones still pass. + +## Review phase (2026-11-24) +- Context refresh at the review boundary; resumed from .builder-state.md. +- Claude iter2 note 2 (architect order): three cleanup suites mocked execFile with 3 params, so the dirty + notice always took "Unable to check status". Fixed in 017f0baea: keep-ignored (new case asserts the real + notice), keep-ignored-e2e (real git status; asserts notes.md counted), spec-1658 ('ps' only for ps). + air-1477 never reaches git status; cleanup-shellper-kill never calls cleanup(). Both new assertions fail + with the old mocks (checked). +- Targeted run at load ~31: 989/990; check-deploy's workflow-runs hang test failed (1 s limit bounds every + call, an earlier one timed out first), passes alone. My own test: limit 5 s there and in check-pr-forge. +- Live runs (worktree build): check pr 1958 at 7d312a2 (4 porch-only commits above 0c02478): ATTENTION + state (draft), checks "head 7d312a2: porch-only, 8 passed", 7.3 s; check pr 1640 (44 files) forge + CONFLICTING/DIRTY + trial merge 15 conflicts, 7.6 s; check pr 1928 (merged) 6.4 s. No ref changed. + Scenario 29: no open ~25-file PR with a 3-commit porch tail exists (scanned 150 recent PRs); recorded. +- Review file written; six cold lessons routed (Testing x4, Architecture, Protocol Orchestration); no hot change. +- checkCi got its one-line skip comment (claude Phase 4 iter2 note 5). diff --git a/packages/codev/src/commands/check/pr.ts b/packages/codev/src/commands/check/pr.ts index 1fdead992..99c6ac7fe 100644 --- a/packages/codev/src/commands/check/pr.ts +++ b/packages/codev/src/commands/check/pr.ts @@ -408,6 +408,7 @@ async function rangeChecks(runner: Runner, pr: PrView, settings: CheckSettings, } async function checkCi(runner: Runner, settings: CheckSettings, anchors: Anchors): Promise { + // Tested here as well as in applySkips, so a skipped `checks` makes no commit-checks call. if (settings.skip.has('checks')) return skipped('checks'); const blocked = anchors.headProblem ?? anchors.baseProblem ?? anchors.rangeProblem; if (blocked) return notRun('checks', blocked); From d97668c21d53a5c98c70d49312efa41afd9ae3ca Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 12:27:15 -0800 Subject: [PATCH 88/94] chore(porch): 1951 review build-complete --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 0d0efc968..45a679970 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -39,7 +39,7 @@ gates: verify-approval: status: pending iteration: 1 -build_complete: false +build_complete: true history: - iteration: 1 plan_phase: readonly_core @@ -138,7 +138,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-docs_guidance-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T19:55:06.922Z' +updated_at: '2026-11-24T20:27:15.801Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' From d5bc0b22797a851fabd87e9d30b78f0eb9715606 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 12:44:43 -0800 Subject: [PATCH 89/94] =?UTF-8?q?[Spec=201951][Phase:=20review]=20fix:=20p?= =?UTF-8?q?r=20review=20round=201=20=E2=80=94=20a=20CLEAR=20describes=20th?= =?UTF-8?q?e=20PR=20as=20it=20is=20at=20the=20end;=20config=20validated=20?= =?UTF-8?q?before=20any=20git=20call=20but=20discovery?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - check pr re-reads pr-view at the end and now compares the base branch, the state and the draft flag as well as the head (codex). A change needs attention, the line naming what changed and asking for a re-run: `state changed during check (OPEN → CLOSED)`, `… (OPEN → OPEN (draft))` even with `state` skipped, `base branch changed during check (main → release)` on the trial merge. - forge: when the first read was UNKNOWN and the head moved, the re-read's answer says which head it is about, `(for the new head )` (claude note 1). - The origin check runs after the configuration is validated, in all three commands, so the only subprocesses before validation are the two that find the main checkout, where the configuration lives: rev-parse --show-toplevel and worktree list --porcelain (codex; option (a), architect). The pr, deploy and worktree config-error tests record every spawn and assert exactly those two. The spec's "before any subprocess" wording is unchanged; the review records the difference for the owner. - parseWorktreeList takes a path verbatim (a trailing space survives) and reads CRLF like LF. Not -z: that needs git 2.36, and the commands run on older git (claude note 3; architect). - codev.md (both trees): check.attribution patterns are trusted and run without a time limit (claude note 2). - Each new test fails with its change taken out (checked). --- codev-skeleton/resources/commands/codev.md | 2 +- codev/resources/commands/codev.md | 2 +- .../__tests__/check-deploy-readonly.test.ts | 8 +- .../check/__tests__/check-pr-readonly.test.ts | 83 ++++++++++++++++++- .../check/__tests__/check-worktree.test.ts | 8 +- .../check/__tests__/helpers/git-fixture.ts | 22 ++++- .../check/__tests__/pr-parsers.test.ts | 13 +++ .../commands/check/__tests__/roots.test.ts | 19 ++++- packages/codev/src/commands/check/deploy.ts | 3 +- packages/codev/src/commands/check/pr.ts | 36 ++++++-- packages/codev/src/commands/check/roots.ts | 22 +++-- packages/codev/src/commands/check/worktree.ts | 5 +- 12 files changed, 196 insertions(+), 27 deletions(-) diff --git a/codev-skeleton/resources/commands/codev.md b/codev-skeleton/resources/commands/codev.md index 0d8cb701d..268df7acf 100644 --- a/codev-skeleton/resources/commands/codev.md +++ b/codev-skeleton/resources/commands/codev.md @@ -460,7 +460,7 @@ replace, never concatenate). A bad value is exit 2, naming the key and the file | Key | Meaning | Default | |---|---|---| -| `check.attribution` | Regexes (JavaScript syntax, case-insensitive, matched per line) for forbidden attribution lines in the PR description and in every commit message not already on the base | `[]`: `off` | +| `check.attribution` | Regexes (JavaScript syntax, case-insensitive, matched per line) for forbidden attribution lines in the PR description and in every commit message not already on the base. They are trusted configuration and run without a time limit, so keep them simple: a pattern that backtracks badly on a long line can hang the command | `[]`: `off` | | `check.watch` | Globs of files whose movement is always listed | `CLAUDE.md`, `AGENTS.md`, `.codev/**`, `.claude/**`, `codev/roles/**`, `codev/protocols/**`, `codev/templates/**`, `codev/resources/arch-critical.md`, `codev/resources/lessons-critical.md` | | `check.flag` | Globs, within what `check.watch` matches, whose movement is attention | `[]` | | `check.notForReading` | Globs left out of the files a person still has to read | `codev/projects/**`, `codev/state/**`, and the lockfiles `**/pnpm-lock.yaml`, `**/package-lock.json`, `**/yarn.lock`, `**/Cargo.lock`, `**/poetry.lock`, `**/uv.lock`, `**/go.sum`, `**/Gemfile.lock`, `**/composer.lock` | diff --git a/codev/resources/commands/codev.md b/codev/resources/commands/codev.md index de10d9e18..cfb5acb36 100644 --- a/codev/resources/commands/codev.md +++ b/codev/resources/commands/codev.md @@ -466,7 +466,7 @@ replace, never concatenate). A bad value is exit 2, naming the key and the file | Key | Meaning | Default | |---|---|---| -| `check.attribution` | Regexes (JavaScript syntax, case-insensitive, matched per line) for forbidden attribution lines in the PR description and in every commit message not already on the base | `[]`: `off` | +| `check.attribution` | Regexes (JavaScript syntax, case-insensitive, matched per line) for forbidden attribution lines in the PR description and in every commit message not already on the base. They are trusted configuration and run without a time limit, so keep them simple: a pattern that backtracks badly on a long line can hang the command | `[]`: `off` | | `check.watch` | Globs of files whose movement is always listed | `CLAUDE.md`, `AGENTS.md`, `.codev/**`, `.claude/**`, `codev/roles/**`, `codev/protocols/**`, `codev/templates/**`, `codev/resources/arch-critical.md`, `codev/resources/lessons-critical.md` | | `check.flag` | Globs, within what `check.watch` matches, whose movement is attention | `[]` | | `check.notForReading` | Globs left out of the files a person still has to read | `codev/projects/**`, `codev/state/**`, and the lockfiles `**/pnpm-lock.yaml`, `**/package-lock.json`, `**/yarn.lock`, `**/Cargo.lock`, `**/poetry.lock`, `**/uv.lock`, `**/go.sum`, `**/Gemfile.lock`, `**/composer.lock` | diff --git a/packages/codev/src/commands/check/__tests__/check-deploy-readonly.test.ts b/packages/codev/src/commands/check/__tests__/check-deploy-readonly.test.ts index 653a188b1..50b3756d5 100644 --- a/packages/codev/src/commands/check/__tests__/check-deploy-readonly.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-deploy-readonly.test.ts @@ -16,7 +16,7 @@ import type { Check, CommandOptions, DeployReport, ErrorReport } from '../report import type { SpawnFn } from '../runner.js'; import { green, mergedView, mergePr, setRemoteBranch, workflowRunsOverride, type MergedPr, type WorkflowRunsOverride } from './helpers/deploy-fixture.js'; import { useFakeHome } from './helpers/fake-home.js'; -import { createFixture, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { createFixture, DISCOVERY_ARGV, recordingSpawn, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; import { commitChecksOverride, passing, @@ -182,15 +182,17 @@ describe('Spec 1951 — check deploy on real repositories', { timeout: 30_000 }, expect(spawn).not.toHaveBeenCalled(); }); - it('Scenario 28a: check.deploy.workflow "--repo=x" is exit 2 naming the value and the file, before any forge call', async () => { + it('Scenario 28a: check.deploy.workflow "--repo=x" is exit 2 naming the value and the file; only the two discovery calls ran', async () => { const file = configure({ deploy: { workflow: '--repo=x' } }); + const recorder = recordingSpawn(); - const result = await checkDeploy(['8'], { cwd: fx.main, env: fx.env }); + const result = await checkDeploy(['8'], { cwd: fx.main, env: fx.env, spawn: recorder.spawn }); expect(result).toEqual({ exitCode: 2, report: { schema: 1, command: 'deploy', error: { message: `check.deploy.workflow "--repo=x" may not begin with '-' (in ${file})` } }, }); + expect(recorder.calls).toEqual(DISCOVERY_ARGV); expect(forge.calls()).toBe(0); }); diff --git a/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts b/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts index 60e933060..b64f30e26 100644 --- a/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-pr-readonly.test.ts @@ -16,7 +16,7 @@ import { checkPr } from '../pr.js'; import type { Check, CommandOptions, ErrorReport, PrReport } from '../report.js'; import type { SpawnFn } from '../runner.js'; import { useFakeHome } from './helpers/fake-home.js'; -import { createFixture, linkedSpelling, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { createFixture, DISCOVERY_ARGV, linkedSpelling, recordingSpawn, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; import { commitChecksOverride, otherClone, @@ -213,6 +213,74 @@ describe('Spec 1951 — check pr on real repositories', { timeout: 30_000 }, () ]); }); + describe('the end-of-run pr-view: a change to what the checks read needs attention (codex, pr review)', () => { + it('a PR closed during the run', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + forge.answerOn(2, prView(head, { state: 'CLOSED' })); + configure(); + + const report = await runReport(); + + expect(report.verdict).toBe('attention'); + const state = byId(report, 'state'); + expect(state).toMatchObject({ status: 'attention', details: { stateNow: 'CLOSED', draftNow: false } }); + expect(state.summary.split('\n')).toEqual(['OPEN, ready for review', 'state changed during check (OPEN → CLOSED); re-run']); + }); + + it('a PR merged during the run', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + forge.answerOn(2, prView(head, { state: 'MERGED', mergedAt: '2026-11-24T20:00:00Z' })); + configure(); + + const state = byId(await runReport(), 'state'); + expect(state.status).toBe('attention'); + expect(state.summary).toContain('state changed during check (OPEN → MERGED); re-run'); + }); + + it('a PR marked draft during the run, even with `state` skipped', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + forge.answerOn(2, prView(head, { isDraft: true })); + configure({ skip: ['state'] }); + + const report = await runReport(); + + expect(report.verdict).toBe('attention'); + expect(byId(report, 'state')).toMatchObject({ + status: 'attention', + summary: 'state changed during check (OPEN → OPEN (draft)); re-run', + details: { stateNow: 'OPEN', draftNow: true }, + }); + }); + + it('a PR retargeted to another base branch during the run', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + forge.answerOn(2, prView(head, { baseRefName: 'release' })); + configure(); + + const report = await runReport(); + + expect(report.verdict).toBe('attention'); + const merge = byId(report, 'trial-merge'); + expect(merge).toMatchObject({ status: 'attention', details: { baseRefNow: 'release' } }); + expect(merge.summary.split('\n')).toContain('base branch changed during check (main → release); re-run'); + }); + + it('nothing changed: CLEAR', async () => { + const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); + forge.answer(prView(head)); + configure(); + + const report = await runReport(); + + expect(forge.calls()).toBe(2); + expect(report.verdict).toBe('clear'); + }); + }); + it('a head that cannot be re-read at the end is not reported as confirmed', async () => { const { head } = pushBranch(fx, [{ files: { 'a.txt': 'a\n' }, message: 'a' }]); forge.answer(prView(head)); @@ -293,6 +361,19 @@ describe('Spec 1951 — check pr on real repositories', { timeout: 30_000 }, () expect(spawn).not.toHaveBeenCalled(); }); + it('Scenario 26: an unparseable check.attribution regex is exit 2 naming the key and the file; only the two discovery calls ran', async () => { + const file = configure({ attribution: ['co-authored-by: (claude'] }); + const recorder = recordingSpawn(); + + const result = await run({ spawn: recorder.spawn }); + + expect(result.exitCode).toBe(2); + expect((result.report as ErrorReport).error.message).toContain('check.attribution pattern "co-authored-by: (claude" is not a valid regex'); + expect((result.report as ErrorReport).error.message).toContain(`(in ${file})`); + expect(recorder.calls).toEqual(DISCOVERY_ARGV); + expect(forge.calls()).toBe(0); + }); + it('outside a git repository is exit 2', async () => { const plain = path.join(fx.root, 'plain'); fs.mkdirSync(plain); diff --git a/packages/codev/src/commands/check/__tests__/check-worktree.test.ts b/packages/codev/src/commands/check/__tests__/check-worktree.test.ts index 8968065ee..7c297f86e 100644 --- a/packages/codev/src/commands/check/__tests__/check-worktree.test.ts +++ b/packages/codev/src/commands/check/__tests__/check-worktree.test.ts @@ -19,7 +19,7 @@ import type { Check, CommandOptions, ErrorReport, Status, WorktreeReport } from import type { SpawnFn } from '../runner.js'; import { checkWorktree, parseStatus, pickPr, removability, renderWorktreeHuman } from '../worktree.js'; import { useFakeHome } from './helpers/fake-home.js'; -import { createFixture, linkedSpelling, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; +import { createFixture, DISCOVERY_ARGV, linkedSpelling, recordingSpawn, snapshotRepoState, type Fixture } from './helpers/git-fixture.js'; import { prViewOverride, writeConfig, type PrViewOverride } from './helpers/pr-fixture.js'; import { expectWorktreeReportShape } from './helpers/report-shape.js'; import { @@ -778,10 +778,12 @@ describe('Spec 1951 — check worktree on real worktrees', { timeout: 30_000 }, expect(spawn).not.toHaveBeenCalled(); }); - it('an invalid cleanup.keepIgnored names the key and the file', async () => { + it('an invalid cleanup.keepIgnored names the key and the file; only the two discovery calls ran', async () => { const file = configure({ cleanup: { keepIgnored: 'tmp/**' } }); addBuilder(fx, 'spir-8'); - expect(await failure('spir-8')).toBe(`cleanup.keepIgnored must be an array of non-empty glob strings (in ${file})`); + const recorder = recordingSpawn(); + expect(await failure('spir-8', { spawn: recorder.spawn })).toBe(`cleanup.keepIgnored must be an array of non-empty glob strings (in ${file})`); + expect(recorder.calls).toEqual(DISCOVERY_ARGV); }); }); }); diff --git a/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts b/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts index 8b3613013..1a7d825df 100644 --- a/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts +++ b/packages/codev/src/commands/check/__tests__/helpers/git-fixture.ts @@ -8,10 +8,11 @@ * machine cannot change the outcome. */ -import { execFileSync } from 'node:child_process'; +import { execFileSync, spawn as realSpawn } from 'node:child_process'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; +import type { SpawnFn } from '../../runner.js'; const EXE = process.platform === 'win32' ? '.exe' : ''; @@ -150,3 +151,22 @@ export function snapshotRepoState(fixture: Fixture, repo: string): RepoState { status: fixture.git(repo, '--no-optional-locks', 'status', '--porcelain=v1'), }; } + +/** + * The only subprocesses a command may start before its configuration is validated: finding the + * checkout and the main checkout, where the configuration lives. Neither takes a config value. + */ +export const DISCOVERY_ARGV: readonly string[][] = [ + ['git', 'rev-parse', '--show-toplevel'], + ['git', 'worktree', 'list', '--porcelain'], +]; + +/** A spawn that runs the real command and records `[command, ...args]` for each call. */ +export function recordingSpawn(): { spawn: SpawnFn; calls: string[][] } { + const calls: string[][] = []; + const spawn: SpawnFn = (command, args, options) => { + calls.push([command, ...args]); + return realSpawn(command, args, options); + }; + return { spawn, calls }; +} diff --git a/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts b/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts index 77c537445..ea7c26e81 100644 --- a/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts +++ b/packages/codev/src/commands/check/__tests__/pr-parsers.test.ts @@ -156,6 +156,19 @@ describe('Spec 1951 — state and forge from pr-view', () => { expect(checkForge(pr({ mergeable: 'CONFLICTING' }), pr())).toMatchObject({ status: 'attention', summary: 'CONFLICTING, CLEAN' }); }); + it("a re-read answer for a head that moved says which head it is about (claude, pr review note 1)", () => { + const next = 'b'.repeat(40); + expect(checkForge(pr({ mergeable: 'UNKNOWN' }), pr({ headRefOid: next }))).toMatchObject({ + status: 'ok', + summary: 'MERGEABLE, CLEAN (for the new head bbbbbbb)', + }); + expect(checkForge(pr({ mergeable: 'UNKNOWN' }), pr({ headRefOid: next, mergeable: 'UNKNOWN' }))).toMatchObject({ + summary: 'forge has not computed mergeability yet; re-run shortly (for the new head bbbbbbb)', + }); + // The first answer stands for the first head, whatever the re-read says. + expect(checkForge(pr(), pr({ headRefOid: next }))).toMatchObject({ summary: 'MERGEABLE, CLEAN' }); + }); + it('a missing or off-contract mergeable is not run, naming the concept', () => { expect(checkForge(pr({ mergeable: undefined }), null)).toMatchObject({ status: 'not-run', reason: 'pr-view did not return mergeable' }); expect(checkForge(pr({ mergeable: 'YES' }), null)).toMatchObject({ diff --git a/packages/codev/src/commands/check/__tests__/roots.test.ts b/packages/codev/src/commands/check/__tests__/roots.test.ts index abdf041f8..bd99a42d6 100644 --- a/packages/codev/src/commands/check/__tests__/roots.test.ts +++ b/packages/codev/src/commands/check/__tests__/roots.test.ts @@ -8,7 +8,7 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { CheckCommandError } from '../report.js'; -import { parseWorktreeList, resolveRoots } from '../roots.js'; +import { parseWorktreeList, requireOrigin, resolveRoots } from '../roots.js'; import { createRunner } from '../runner.js'; import { loadCheckSettings } from '../settings.js'; import { createFixture, type Fixture } from './helpers/git-fixture.js'; @@ -63,9 +63,12 @@ describe('Spec 1951 — roots', () => { } }); - it('without an origin remote, fails', async () => { + it('without an origin remote, requireOrigin fails; finding the roots does not ask', async () => { fx.git(fx.main, 'remote', 'remove', 'origin'); - await expect(rootsFrom(fx.main)).rejects.toThrow('this repository has no "origin" remote'); + await expect(rootsFrom(fx.main)).resolves.toMatchObject({ mainRoot: fx.main }); + await expect(requireOrigin(createRunner({ cwd: fx.main, workspaceRoot: fx.main, env: fx.env }))).rejects.toThrow( + 'this repository has no "origin" remote', + ); }); }); @@ -85,4 +88,14 @@ describe('Spec 1951 — parseWorktreeList', () => { { path: 'bare.git', head: null, branch: null, bare: true }, ]); }); + + it('keeps a path that ends in a space (claude, pr review note 3)', () => { + const entries = parseWorktreeList(['worktree /repo/trail ', 'HEAD ' + 'a'.repeat(40), 'branch refs/heads/t', ''].join('\n')); + expect(entries.map((e) => e.path)).toEqual([path.resolve('/repo/trail ')]); + }); + + it('reads CRLF output like LF', () => { + const entries = parseWorktreeList(['worktree /repo', 'HEAD ' + 'a'.repeat(40), 'branch refs/heads/main', '', ''].join('\r\n')); + expect(entries).toEqual([{ path: path.resolve('/repo'), head: 'a'.repeat(40), branch: 'main', bare: false }]); + }); }); diff --git a/packages/codev/src/commands/check/deploy.ts b/packages/codev/src/commands/check/deploy.ts index b3bbcb3ea..ed2153329 100644 --- a/packages/codev/src/commands/check/deploy.ts +++ b/packages/codev/src/commands/check/deploy.ts @@ -38,7 +38,7 @@ import { type CommitRuns, type DeployReport, } from './report.js'; -import { resolveRoots } from './roots.js'; +import { requireOrigin, resolveRoots } from './roots.js'; import { createRunner, type Runner } from './runner.js'; import { loadCheckSettings, type CheckSettings } from './settings.js'; import { InputError, isFullSha, isRefName, validatePrNumber } from './validate.js'; @@ -306,6 +306,7 @@ async function buildDeployReport(numbers: readonly number[], options: CommandOpt const roots = await resolveRoots(createRunner({ cwd: options.cwd, workspaceRoot: options.cwd, ...runnerOptions })); const runner = createRunner({ cwd: roots.mainRoot, workspaceRoot: roots.mainRoot, ...runnerOptions }); const settings = loadCheckSettings(roots.mainRoot); + await requireOrigin(runner); const ctx: Context = { runner, settings, version: await gitVersion(runner), tips: new Map(), runs: new Map() }; const prs: DeployPr[] = []; diff --git a/packages/codev/src/commands/check/pr.ts b/packages/codev/src/commands/check/pr.ts index 99c6ac7fe..8a6802b55 100644 --- a/packages/codev/src/commands/check/pr.ts +++ b/packages/codev/src/commands/check/pr.ts @@ -64,7 +64,7 @@ import { type CommitRuns, type PrReport, } from './report.js'; -import { resolveRoots } from './roots.js'; +import { requireOrigin, resolveRoots } from './roots.js'; import { createRunner, type Runner } from './runner.js'; import { loadCheckSettings, type AttributionPattern, type CheckSettings } from './settings.js'; import { isFullSha, isRefName, validatePrNumber } from './validate.js'; @@ -271,10 +271,12 @@ export function checkForge(first: PrView, reread: PrView | null): Check { if (!MERGEABILITY.includes(mergeable)) { return notRun('forge', `pr-view returned mergeable ${JSON.stringify(mergeable)}, not ${MERGEABILITY.join(', ')}`); } + // The re-read's answer is about the head it reports, which the rest of the report is not. + const forNewHead = view.head !== first.head ? ` (for the new head ${short(view.head)})` : ''; const details = { mergeable, mergeStateStatus: view.mergeStateStatus, reviewDecision: view.reviewDecision }; - if (mergeable === 'MERGEABLE') return check('forge', 'ok', mergeWords(view), details); - if (mergeable === 'CONFLICTING') return check('forge', 'attention', mergeWords(view), details); - return check('forge', 'attention', 'forge has not computed mergeability yet; re-run shortly', details); + if (mergeable === 'MERGEABLE') return check('forge', 'ok', mergeWords(view) + forNewHead, details); + if (mergeable === 'CONFLICTING') return check('forge', 'attention', mergeWords(view) + forNewHead, details); + return check('forge', 'attention', `forge has not computed mergeability yet; re-run shortly${forNewHead}`, details); } interface AttributionHit { @@ -439,6 +441,13 @@ function flagCheck(checks: Check[], id: string, note: string, extra: Record l.trim()).filter(Boolean); + for (const block of output.replace(/\r\n/g, '\n').split(/\n{2,}/)) { + const lines = block.split('\n').filter((l) => l !== ''); const pathLine = lines.find((l) => l.startsWith('worktree ')); if (!pathLine) continue; const headLine = lines.find((l) => l.startsWith('HEAD ')); @@ -52,7 +56,12 @@ export async function listWorktrees(runner: Runner): Promise { return parseWorktreeList(result.stdout); } -/** Find both roots, and require an `origin` remote. Fails with exit 2 otherwise. */ +/** + * Find both roots: the only two git calls a command makes before its configuration is + * validated, since the configuration is read from the main checkout and only git can name it + * from a linked worktree. Neither takes a configuration value. Fails with exit 2 outside a + * checkout. + */ export async function resolveRoots(runner: Runner): Promise { const top = await runner.git(['rev-parse', '--show-toplevel']); if (top.exitCode !== 0) throw new CheckCommandError('not in a git repository', top.stderr.trim()); @@ -61,10 +70,13 @@ export async function resolveRoots(runner: Runner): Promise { const [main] = await listWorktrees(runner); if (!main) throw new CheckCommandError('git worktree list returned no worktrees'); if (main.bare) throw new CheckCommandError(`the main worktree ${main.path} is a bare repository; run codev check from a checkout`); + return { checkoutRoot, mainRoot: main.path }; +} +/** Require an `origin` remote (exit 2 otherwise). Called after the configuration is validated. */ +export async function requireOrigin(runner: Runner): Promise { const origin = await runner.git(['config', '--get', 'remote.origin.url']); if (origin.exitCode !== 0 || origin.stdout.trim() === '') { throw new CheckCommandError('this repository has no "origin" remote; codev check reads base and head from origin'); } - return { checkoutRoot, mainRoot: main.path }; } diff --git a/packages/codev/src/commands/check/worktree.ts b/packages/codev/src/commands/check/worktree.ts index 42a5a577c..f9b93ffb2 100644 --- a/packages/codev/src/commands/check/worktree.ts +++ b/packages/codev/src/commands/check/worktree.ts @@ -54,7 +54,7 @@ import { type Removable, type WorktreeReport, } from './report.js'; -import { listWorktrees, resolveRoots, type Roots } from './roots.js'; +import { listWorktrees, requireOrigin, resolveRoots, type Roots } from './roots.js'; import { createRunner, type GitResult, type Runner } from './runner.js'; import { loadCheckSettings, loadKeepIgnored } from './settings.js'; import { hasControlChars, InputError, isFullSha, isRefName, validateBuilderId } from './validate.js'; @@ -489,10 +489,11 @@ async function buildWorktreeReport(argument: TargetArgument, options: CommandOpt const roots = await resolveRoots(createRunner({ cwd: options.cwd, workspaceRoot: options.cwd, ...runnerOptions })); const runner = createRunner({ cwd: roots.mainRoot, workspaceRoot: roots.mainRoot, ...runnerOptions }); const settings = loadCheckSettings(roots.mainRoot); - const target = await resolveTarget(runner, roots, argument); const skip = (id: string): boolean => settings.skip.has(id); // A skipped check reads nothing of its own, its configuration included. const patterns = skip('ignored') ? [] : loadKeepIgnored(roots.mainRoot); + await requireOrigin(runner); + const target = await resolveTarget(runner, roots, argument); // The PR decides the base; without one (or with `pr` skipped), origin's default branch does. const pr = skip('pr') ? null : await lookupPr(runner, target.branch); From 1a6eb69ddb0b6e76731294a8e37e3b40caafe6f4 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 12:46:06 -0800 Subject: [PATCH 90/94] [Spec 1951] Review: PR round 1 rebuttal; config-order deviation recorded for the owner - Review file: the config-validation order under Deviations in plain words (what the spec says, what the code does, why; the approved spec and plan text unchanged, for the owner to accept at the pr gate); PR review round 1 under Consultation Feedback; d5bc0b227 under Commits No Reviewer Has Seen; the input-validation and no-race criteria qualified. - Rebuttal 1951-review-iter1-rebuttals.md. - lessons-learned.md (cold, Process): re-read spec criteria when a plan revision changes their premise; record the conflict, do not retitle the test. - Thread log. --- .../1951-review-iter1-rebuttals.md | 44 +++++++++++++++++++ codev/resources/lessons-learned.md | 2 + .../1951-read-only-pr-check-for-archite.md | 36 ++++++++++++++- codev/state/spir-1951_thread.md | 10 +++++ 4 files changed, 90 insertions(+), 2 deletions(-) create mode 100644 codev/projects/1951-read-only-pr-check-for-archite/1951-review-iter1-rebuttals.md diff --git a/codev/projects/1951-read-only-pr-check-for-archite/1951-review-iter1-rebuttals.md b/codev/projects/1951-read-only-pr-check-for-archite/1951-review-iter1-rebuttals.md new file mode 100644 index 000000000..c65983244 --- /dev/null +++ b/codev/projects/1951-read-only-pr-check-for-archite/1951-review-iter1-rebuttals.md @@ -0,0 +1,44 @@ +# Review phase (PR) — iteration 1 rebuttal + +Codex: REQUEST_CHANGES (two issues). Claude: APPROVE (six minor notes). Before changing anything, I checked both of Codex's issues against the code and took them to the architect. The architect ruled on each (2026-11-24 20:35). The fixes are in `d5bc0b227`. + +## Codex 1: the end-of-run re-read compares only the head (accepted, fixed) + +> `pr.ts:487-520` only compares the reread head SHA. Changes to `baseRef`, draft status, or PR state are ignored … + +Correct. `check pr` read the base branch, state and draft flag once, from the anchoring `pr-view`. A PR closed, merged, marked draft or retargeted during the run could still read CLEAR. + +Fixed: the final `pr-view` is compared on head, base branch, state and draft. Any change needs attention, with a line naming what changed and asking for a re-run: +- `state`: `state changed during check (OPEN → CLOSED); re-run`. A draft shows as `OPEN → OPEN (draft)`. This applies even when `state` is in `check.skip`, because a CLEAR must describe the PR as it is when the command returns. +- `trial-merge`: `base branch changed during check (main → release); re-run`. + +Tests, on real repositories with a stub `pr-view` that answers differently on its second call: closed, merged, marked draft with `state` skipped, retargeted, and unchanged (CLEAR, two `pr-view` calls). Each fails with its comparison taken out. + +## Codex 2: config is not validated before any subprocess (accepted in part; the wording goes to the owner) + +> All three implementations call `resolveRoots()`—spawning several git commands—before `loadCheckSettings()` … Either restore the approved behavior … or obtain approval to revise the requirement. + +Correct about the code, and about the test title ("before any forge call"). I never recorded the difference as a deviation; that was my miss. + +The cause is structural. Configuration is read from the main checkout, and from a builder worktree only git can name it. `findWorkspaceRoot()` returns the worktree itself; that was the plan's iteration-1 fix. + +The architect chose option (a): +- The `origin` check (`config --get remote.origin.url`) now runs after validation in all three commands. The only subprocesses before validation are `git rev-parse --show-toplevel` and `git worktree list --porcelain`. Neither takes a configuration value. +- No config value reaches any subprocess, forge call or network call before it is validated. +- The pr (bad `check.attribution` regex), deploy (`check.deploy.workflow: "--repo=x"`) and worktree (non-array `cleanup.keepIgnored`) config-error tests record every spawn. Each asserts exactly those two calls. +- The approved spec and plan text are unchanged. The review file records the difference under Deviations in plain words, and the architect puts it to the owner at the pr gate. + +The rejected option was finding the main checkout without git, by parsing `.git` and `commondir` by hand. That reimplements git's discovery (`GIT_DIR`, `GIT_COMMON_DIR`, ceiling directories) and can disagree with git. + +## Claude's notes + +1. **The forge line for a moved head.** Fixed: when the first read was UNKNOWN and the re-read reports another head, the line ends `(for the new head )`. Unit tests are in `pr-parsers.test.ts`. +2. **`check.attribution` is not time-bounded.** One sentence in `codev.md` (both trees): the patterns are trusted, run without a time limit, and should be kept simple. +3. **`parseWorktreeList` without `-z`.** Fixed differently than suggested. `worktree list -z` needs git 2.36, and the commands run on older git (Ubuntu 22.04 ships 2.34); only the trial merge needs 2.38. The parser now keeps the path verbatim, so a trailing space survives (probed on git 2.50, which prints it raw), and reads CRLF like LF. A newline inside a path cannot be read without `-z`, and the comment says so. The architect agreed. +4. **`isSpawnMade` reads same-size files whole.** Not changed. Only an untracked entry at the same path and size as a main-checkout file is compared. +5. **`scaffoldOnly` is unused.** Not changed: it predates this PR. +6. **The `check pr 1958` sample says `Fixes #1951`.** Not changed. It is the run as captured, before the PR body was rewritten. + +## Checks + +Targeted tests: 1028/1028 in 36 files. Both type-checks, the build and the tmp-residue check passed. diff --git a/codev/resources/lessons-learned.md b/codev/resources/lessons-learned.md index babb69456..968098d84 100644 --- a/codev/resources/lessons-learned.md +++ b/codev/resources/lessons-learned.md @@ -315,6 +315,8 @@ Generalizable wisdom extracted from review documents, ordered by impact. Updated - [From 1313] Trace a contract change end-to-end before calling it specified. A send-outcome change (`delivered` vs `held`+reason) was specified server-side but not client-side (`packages/core/src/tower-client.ts` + `commands/send.ts`, on BOTH the single-send and `--all` paths), and drew repeat REQUEST_CHANGES across the plan and Phase 4. Name every layer the contract crosses (wire → client → each CLI path) in the plan deliverable so the client surfacing isn't discovered at review time. - [From #1819] **A risk-table mitigation that says "covered in the manual pass" is the easiest line in a plan to skip, so make it a test.** The plan said the atomic rename vs an open annotator file tab was covered manually; it had not been checked when the last phase was first reviewed. As an e2e test it passed, and its first failed run exposed a pre-existing annotator gap: the viewer's first mtime reading, about a second after load, is taken as the baseline, so a write in that first second is never shown. Before the review phase, go through the risk table and check that every mitigation points to a test or a recorded check. +- [From 1951] **When a plan revision changes a premise, re-read every spec criterion that rested on it.** Spec 1951 said config is validated "before any subprocess runs". The plan's review then moved config to the main checkout, which only git can find from a worktree, and that made the criterion false. The test was retitled "before any forge call" instead of the gap being recorded as a deviation, and the PR-phase reviewer found it. Name the conflict at the time, as a deviation or a question to the architect; a renamed test hides it. + ## Testing - [From #1915] A test's cleanup that kills every pid it recorded can kill an unrelated process: Windows reuses pids quickly, and the recorded process is often long dead by `afterAll`. Kill a recorded pid only if the live process with that pid was created no later than the recording (`__tests__/helpers/tracked-pids.ts`). This matters more than it looks because vitest 4 ignores `poolOptions.forks.singleFork`, so test files run in parallel workers: one file's cleanup ran inside another file's assertion window and is the likely killer of a CIM-created Tower in tower-lifecycle.windows Phase 4(b). diff --git a/codev/reviews/1951-read-only-pr-check-for-archite.md b/codev/reviews/1951-read-only-pr-check-for-archite.md index 23ac1640c..60cbdfd45 100644 --- a/codev/reviews/1951-read-only-pr-check-for-archite.md +++ b/codev/reviews/1951-read-only-pr-check-for-archite.md @@ -33,13 +33,16 @@ The commands are read-only by construction. One runner spawns every subprocess a The runs include a conflicting trial merge, a ref-neutral fetch of missing objects (with tags on origin), and a run from a linked worktree. The snapshots are identical before and after. - [x] **Live base** (Phase 3). The trial merge uses `ls-remote`'s tip, and a test deliberately leaves the local `origin/main` stale. -- [x] **Exact head, live base, no race** (Phase 3). `pr-view` and `ls-remote` are re-read at the end. A moved head or base is attention ("head|base moved during check"), and overrides a `check.skip` of the check that carries it. There is a test for each. +- [x] **Exact head, live base, no race** (Phase 3; widened in the PR review). `pr-view` and `ls-remote` are re-read at the end. A moved head or base is attention ("head|base moved during check"), and overrides a `check.skip` of the check that carries it. Since the PR review's round 1, a change during the run to the PR's base branch, state or draft flag is attention as well. There is a test for each. - [x] **Bounded time** (Phases 1–5). Every forge call, and every `ls-remote` and `fetch`, has a timeout. A hanging `commit-checks` or `workflow-runs` makes its check `not run: … timed out after Ns`. A hanging anchoring `pr-view` is exit 2. - [x] **Porch-only head** (Phase 4). `porch-only.ts` finds the last code commit by the plan's walk, which reads at most 11 commits and makes at most 10 lookups. The code runs show beside the head's, and they drive the verdict. Tests cover runs only on head, only on an earlier commit, on neither, a failure on either, and main merged into a porch-only branch. - [x] **Never reported as passing** (Phases 4–6). For each forge-dependent check, a disabled concept and a failing concept both give `not run: …` with exit 1 (Scenario 24 tests). - [x] **Exit codes** (Phases 3–6). Each command has tests for 0, 1 and 2, and `--json` carries the same verdict. For `check deploy`, a PR that cannot be read is a per-PR `not run` (Scenario 15a, as recorded in the deviations). - [x] **`--json` matches the schema** (`schema: 1`), including the `error` object on exit 2 (Phases 2–6). The report-shape helpers check every report. The fields this project added beyond the spec's schema are listed under Deviations (Phase 7), and `codev.md` documents them. -- [x] **Input validation** (Phase 2). PR numbers, SHAs, builder ids and paths, and config strings are validated before any subprocess runs. A violation exits 2 naming the value (Scenario 28a). +- [x] **Input validation** (Phase 2), **with one deviation for the owner to accept** (see Deviations, Review phase). + - PR numbers, SHAs, builder ids and paths are validated before any subprocess runs. + - Config values are validated before any subprocess that takes one, and before any forge or network call. Two local git calls that find the main checkout run first. + - A violation exits 2 naming the value (Scenario 28a). - [x] **Configuration** (Phases 2–6). Each `check.*` key and `cleanup.keepIgnored` changes behaviour as specified, and arrays replace the defaults. An invalid value exits 2 naming the key and the file it came from, including a fake `~/.codev/config.json` layer. - [x] **Forge contract** (Phase 1). - `pr-view` gains seven optional fields. @@ -188,6 +191,19 @@ The architect accepted each of these when it was made. The thread log has the re - Cleanup's dirty notice shares `isSpawnMade` with `check worktree` (`f93aa60e1`, architect-ordered from Claude's Phase 6 iteration 3 note 3). It reads status with `-z`, so quoted paths are judged correctly (`0c02478dd`). **Review phase** +- **For the owner to accept: when configuration is validated.** + - *The spec says*: config values are validated "before any subprocess runs" (Success Criteria, Input validation; the plan's Phase 2 acceptance line repeats it). + - *The code does this*: two local, read-only git calls run first, `git rev-parse --show-toplevel` and `git worktree list --porcelain`. + - *Why*: configuration is read from the main checkout, and from a builder worktree only git can name it. `findWorkspaceRoot()` returns the worktree itself; that was the plan's iteration-1 fix. Neither call takes a configuration value. No config value reaches any subprocess, forge call or network call before it is validated. + - *The alternative, not taken*: making the wording literally true would mean finding the main checkout without git, by parsing `.git` and `commondir` by hand. That can disagree with git. The architect agreed it would trade a wording gap for a real risk. + - *How it was found*: until the PR review a third call, the `origin` check, also ran first. The test was titled "before any forge call", and the difference was not recorded as a deviation. Codex found it in the PR review's round 1. + - *What changed*: the `origin` check now runs after validation in all three commands. The pr, deploy and worktree config-error tests record every spawn and assert exactly those two calls. + - The approved spec and plan text are unchanged. The architect puts this to the owner at the pr gate. +- PR review round 1 (`d5bc0b227`): + - the end-of-run `pr-view` now compares the base branch, state and draft flag as well as the head; + - when the head moved, the forge line names the head its answer is about; + - `parseWorktreeList` keeps a path verbatim and reads CRLF. It does not use `-z`, which needs git 2.36; the architect agreed; + - `codev.md` says attribution patterns run without a time limit. - Three cleanup suites mocked `execFile` in its three-argument form, so the dirty notice silently took its "Unable to check status" path (`017f0baea`, Claude's Phase 7 iteration 2 note 2, architect order). - `air-1950-cleanup-keep-ignored` now asserts the real notice; - `air-1950-cleanup-keep-ignored-e2e` runs `git status` for real; @@ -214,6 +230,7 @@ Porch force-advanced two phases at the three-iteration ceiling, so CMAP never re - a one-line `liveTip` branch-name guard. - `c42251ec5`: the `ext::` refusal case no longer uses a `/tmp` path. - Both are confined to `commands/check/` test helpers, apart from the one-line guard in `git-facts.ts`. +- **PR review, round 1:** `d5bc0b227` (the fixes for Codex's two issues and Claude's notes 1–3) and the review-file commit after it were made after the PR-phase consultation. If porch runs a second PR-phase round, it reviews them. If not, the architect has Codex review them before the gate goes to the owner. - **Phase 6:** - `a1ccc442b`: spawn's native-Windows link fallbacks (a hard link, or an unchanged copy) are scaffold, and several keep-list links print one per line. - At the architect's request, Phase 7's reviewers reviewed this rule through `f93aa60e1`, which moved it into `agent-farm/lib/builder-scaffold.ts`. Both approved in iteration 2. @@ -377,6 +394,20 @@ No concerns raised. 1. Of the four new safe-direction tests, only the quoted hard-link and copy test detects a parsing regression. The lone ` M` first entry, the quoted untracked name and the staged rename pass under the old line parsing too. → **N/A**, recorded here as the architect ordered: they pin the safe direction the architect asked for, and the discriminating test is the mutation-checked one. 2. `air-1950-cleanup-keep-ignored`'s three-argument `execFile` mock sends the notice down "Unable to check status". → **Addressed** in the review phase (`017f0baea`), with the two sibling suites that had the same shape. +### Review (PR) Phase (Round 1) + +#### Codex — REQUEST_CHANGES +- **Concern**: `check pr`'s end-of-run re-read compares only the head. A PR retargeted, marked draft, or closed during the run could still read CLEAR. → **Addressed** (`d5bc0b227`). The base branch, state and draft flag are compared too. Each change is attention, its line naming what changed and asking for a re-run, even when the check is skipped. There are stub tests for closed, merged, draft and retargeted PRs, and for an unchanged run staying CLEAR. +- **Concern**: config is not validated before any subprocess, as the spec and plan say; `resolveRoots()` runs git first, and the test was weakened to "before any forge call". → **Addressed in part, and recorded as a deviation for the owner** (architect's option (a)). The `origin` check moved after validation, so only the two calls that find the main checkout precede it. The tests assert exactly those two. Removing them would mean reimplementing git's repository discovery. See Deviations, Review phase. + +#### Claude — APPROVE +- **Concern**: `checkForge` may give the re-read's mergeability for a moved head without saying so. → **Addressed**: `(for the new head )`. +- **Concern**: `check.attribution` regexes are not time-bounded. → **Addressed**: one sentence in `codev.md`, both trees. They remain trusted configuration. +- **Concern**: `parseWorktreeList` trims lines and reads without `-z`. → **Addressed differently**: the path is kept verbatim and CRLF is handled. `-z` was not taken, because it needs git 2.36 and the commands run on older git (Ubuntu 22.04 ships 2.34); the architect agreed. A newline inside a path stays unreadable, and the code says so. +- **Concern**: `isSpawnMade` reads same-size files whole. → **Not changed**: only an untracked entry at the same path and size as a main-checkout file is compared, which in practice is `.env` and config files. +- **Concern**: `scaffoldOnly` has no production consumer. → **Not changed**: it predates this PR. +- **Concern**: the recorded `check pr 1958` sample reads `"Fixes #1951"`, while the body now says `Closes #1951`. → **Not changed**: the sample is the run as it was, captured before the body was rewritten. + ## Lessons Learned ### What Went Well @@ -419,6 +450,7 @@ No concerns raised. - Routed: cold, Testing: a short timeout that bounds every call of a run fails on the wrong call under load. Size it for the other calls and assert the reason names the call that hung. - Routed: cold, Testing: on Windows, `fs.realpathSync` keeps 8.3 short names while git prints the long path; fixture roots compared with git output need `realpathSync.native`. - Routed: cold, Architecture: `git status --porcelain` without `-z` C-quotes unusual paths, and a helper that trims stdout eats the first `-z` entry's leading status space. +- Routed: cold, Process: when a plan revision changes a premise, re-read every spec criterion that rested on it, and record the conflict as a deviation rather than retitling the test. - Routed: cold, Protocol Orchestration: a porch review round runs rebuttal → `porch done` → `porch next` → `porch done` → `porch next`. Run `porch next` first after a round, and list the commits a force-advance left unreviewed. - No hot-tier change. `lessons-critical.md` is at its cap, and none of these is more cross-cutting than what it holds. diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index ef451f7fa..1c9fbe83b 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -411,3 +411,13 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals Scenario 29: no open ~25-file PR with a 3-commit porch tail exists (scanned 150 recent PRs); recorded. - Review file written; six cold lessons routed (Testing x4, Architecture, Protocol Orchestration); no hot change. - checkCi got its one-line skip comment (claude Phase 4 iter2 note 5). +- PR-phase consult round 1: claude APPROVE (6 minor notes), codex REQUEST_CHANGES: (1) the end-of-run pr-view + compared only the head; (2) config is not validated "before any subprocess" (roots come from git first; the + 28a test had been retitled "before any forge call", never recorded as a deviation; my miss). Took both to the + architect before fixing. Rulings (20:35): (1) fix: compare head, baseRef, state and draft, each change + ATTENTION; (2) option (a): origin check after settings, tests assert only the two discovery argv, NO edit to + the approved spec or plan; record as a deviation for the owner at the pr gate. Claude note 3: -z needs git + 2.36 (Ubuntu 22.04 has 2.34), so the path is kept verbatim instead; architect agreed (20:41). +- d5bc0b227: all of it; 6 new tests each fail under mutation. Targeted 1028/1028 (36 files), both tsc, build, + residue OK. Rebuttal 1951-review-iter1-rebuttals.md. One more cold lesson (Process: re-read spec criteria + when a plan revision changes their premise). From 30853b1fea59b33c06b53bad311c06e46b49d68c Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 12:59:54 -0800 Subject: [PATCH 91/94] chore(porch): 1951 pr gate-requested --- .../projects/1951-read-only-pr-check-for-archite/status.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml index 45a679970..0a3c81052 100644 --- a/codev/projects/1951-read-only-pr-check-for-archite/status.yaml +++ b/codev/projects/1951-read-only-pr-check-for-archite/status.yaml @@ -36,6 +36,7 @@ gates: approved_at: '2026-11-23T22:10:01.002Z' pr: status: pending + requested_at: '2026-11-24T20:59:54.752Z' verify-approval: status: pending iteration: 1 @@ -138,7 +139,7 @@ history: file: >- /Users/mwk/Development/cluesmith/codev/.builders/spir-1951/codev/projects/1951-read-only-pr-check-for-archite/1951-docs_guidance-iter1-claude.txt started_at: '2026-11-23T18:53:58.201Z' -updated_at: '2026-11-24T20:27:15.801Z' +updated_at: '2026-11-24T20:59:54.752Z' context_refreshes: - boundary: enter:plan at: '2026-11-23T21:21:59.024Z' @@ -170,3 +171,4 @@ force_advanced: max_iterations: 3 rebuttal_file: 1951-check_worktree-iter3-rebuttals.md at: '2026-11-24T18:44:00.290Z' +pr_ready_for_human: true From 5bede631e4075d55bd6d2e75416a450b128d5a11 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:06:49 -0800 Subject: [PATCH 92/94] [Spec 1951] Review: architect-run codex review of d5bc0b227; full local run on the final head MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Review file: the architect-run Codex review of d5bc0b227 (one finding, rejected by the architect, with the reason); the full local run after ci-first's retirement (440 files, 9,286 tests passed, 363 s, load 18.4 → 27.7). - Thread log. --- codev/reviews/1951-read-only-pr-check-for-archite.md | 12 +++++++++--- codev/state/spir-1951_thread.md | 6 ++++++ 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/codev/reviews/1951-read-only-pr-check-for-archite.md b/codev/reviews/1951-read-only-pr-check-for-archite.md index 60cbdfd45..a83fc7944 100644 --- a/codev/reviews/1951-read-only-pr-check-for-archite.md +++ b/codev/reviews/1951-read-only-pr-check-for-archite.md @@ -53,8 +53,9 @@ The commands are read-only by construction. One runner spawns every subprocess a - The architect role, `risk-triage.md`, the `codev` command reference, `workflow-reference.md` and `overview.md` changed in both trees. - The `codev` skill changed in all four copies, and the shipped hashes were regenerated. - The forge skill and `forge.md` document the new concepts and fields. -- [x] **Full test suite and Windows**, with the qualification below. - - Under owner ruling main-38 ("ci-first"), the builder never ran the full suite locally. GitHub's run (8/8, which includes the full unit suite on Node 22 and 24) stood in for porch's local `tests` check at every phase head. The architect confirmed each run, and each skip is listed in the PR body. +- [x] **Full test suite and Windows.** + - Under owner ruling main-38 ("ci-first"), the builder ran no full local suite during Phases 1–7. GitHub's run (8/8, which includes the full unit suite on Node 22 and 24) stood in for porch's local `tests` check at every phase head. The architect confirmed each run, and each skip is listed in the PR body. + - The owner retired ci-first (decision main-39) once PR #1965's worker cap reached main. After merging it (`e9baeeec0`), one ordinary full local run on the final head (`30853b1fe`, the same tree as `e9baeeec0`), `npm test -- --exclude='**/e2e/**'` from `packages/codev`: 440 files passed and 14 skipped; 9,286 tests passed and 116 skipped; exit 0. Wall time 363 s; one-minute load 18.4 at the start, peak 27.7. No failures. - Windows runs: - 45462452355 failed 9 fixture-side tests (8.3 short names), fixed in `f93aa60e1`; - 45465468867 and 45471312317 passed; @@ -230,7 +231,7 @@ Porch force-advanced two phases at the three-iteration ceiling, so CMAP never re - a one-line `liveTip` branch-name guard. - `c42251ec5`: the `ext::` refusal case no longer uses a `/tmp` path. - Both are confined to `commands/check/` test helpers, apart from the one-line guard in `git-facts.ts`. -- **PR review, round 1:** `d5bc0b227` (the fixes for Codex's two issues and Claude's notes 1–3) and the review-file commit after it were made after the PR-phase consultation. If porch runs a second PR-phase round, it reviews them. If not, the architect has Codex review them before the gate goes to the owner. +- **PR review, round 1:** `d5bc0b227` (the fixes for Codex's two issues and Claude's notes 1–3) and `1a6eb69dd` (review file and rebuttal) were made after the PR-phase consultation, and porch ran no second round. The architect had Codex review `d5bc0b227`: one finding, rejected by the architect (see Consultation Feedback). `1a6eb69dd` is documents only. - **Phase 6:** - `a1ccc442b`: spawn's native-Windows link fallbacks (a hard link, or an unchanged copy) are scaffold, and several keep-list links print one per line. - At the architect's request, Phase 7's reviewers reviewed this rule through `f93aa60e1`, which moved it into `agent-farm/lib/builder-scaffold.ts`. Both approved in iteration 2. @@ -408,6 +409,11 @@ No concerns raised. - **Concern**: `scaffoldOnly` has no production consumer. → **Not changed**: it predates this PR. - **Concern**: the recorded `check pr 1958` sample reads `"Fixes #1951"`, while the body now says `Closes #1951`. → **Not changed**: the sample is the run as it was, captured before the body was rewritten. +#### Architect-run Codex review of `d5bc0b227` +Porch ran no second PR-phase round, so the architect had Codex review `d5bc0b227` from the main checkout, with a brief covering the four changes and the read-only contract. +- **Concern**: the end-of-run comparison uses normalised state words, so a first read of `OPENED` and a final read of `OPEN` would not be flagged. → **Rejected by the architect**: those are two spellings of one state (GitLab's and GitHub's), not a change, and one run reads one forge, so comparing normalised states is correct. The architect also read `pr.ts` 496–518: head, base branch and state with draft are each compared, and each flags its check. +- Nothing else was found on the config order, the worktree-list parser or the allow-list. + ## Lessons Learned ### What Went Well diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 1c9fbe83b..78b6753d1 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -421,3 +421,9 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals - d5bc0b227: all of it; 6 new tests each fail under mutation. Targeted 1028/1028 (36 files), both tsc, build, residue OK. Rebuttal 1951-review-iter1-rebuttals.md. One more cold lesson (Process: re-read spec criteria when a plan revision changes their premise). +- GitHub 8/8 + Windows 45484244459 green on 1a6eb69dd. ci-first RETIRED (owner main-39): merged origin/main + (fa4fc74ee, PR #1965 worker cap) as e9baeeec0, clean; ordinary porch done at load 17.8 → no second consult + round, GATE REQUIRED: pr (30853b1fe). Architect ran codex on d5bc0b227: one finding (normalised state words), + rejected by the architect (two spellings of one state; one forge per run). +- Full local run on 30853b1fe (architect order, the local evidence): npm test -- --exclude='**/e2e/**' → + 440 files passed / 14 skipped, 9286 tests passed / 116 skipped, exit 0, 363 s wall, load 18.4 start, 27.7 peak. From 41fb24c3ec5a6eed93a0976788a70d4bcb132059 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:28:42 -0800 Subject: [PATCH 93/94] [Spec 1951] Review: the check pr run that stopped the gate; second full local run on the merged head - Live runs: codev check pr 1958 found a lessons-learned.md conflict with main (Spec 1940) before the gate, the forge agreeing; merged main as 5d802799f. - Second full local run on 5d802799f: 449 files, 9,885 tests passed, 342 s. - Thread log. --- .../1951-read-only-pr-check-for-archite.md | 16 ++++++++++++++++ codev/state/spir-1951_thread.md | 6 ++++++ 2 files changed, 22 insertions(+) diff --git a/codev/reviews/1951-read-only-pr-check-for-archite.md b/codev/reviews/1951-read-only-pr-check-for-archite.md index a83fc7944..5565707f8 100644 --- a/codev/reviews/1951-read-only-pr-check-for-archite.md +++ b/codev/reviews/1951-read-only-pr-check-for-archite.md @@ -56,6 +56,7 @@ The commands are read-only by construction. One runner spawns every subprocess a - [x] **Full test suite and Windows.** - Under owner ruling main-38 ("ci-first"), the builder ran no full local suite during Phases 1–7. GitHub's run (8/8, which includes the full unit suite on Node 22 and 24) stood in for porch's local `tests` check at every phase head. The architect confirmed each run, and each skip is listed in the PR body. - The owner retired ci-first (decision main-39) once PR #1965's worker cap reached main. After merging it (`e9baeeec0`), one ordinary full local run on the final head (`30853b1fe`, the same tree as `e9baeeec0`), `npm test -- --exclude='**/e2e/**'` from `packages/codev`: 440 files passed and 14 skipped; 9,286 tests passed and 116 skipped; exit 0. Wall time 363 s; one-minute load 18.4 at the start, peak 27.7. No failures. + - Main then moved (Spec 1940, 105 files), and the branch merged it to clear the conflict `check pr` found (`5d802799f`). A second full run on that head: 449 files passed and 14 skipped; 9,885 tests passed and 116 skipped; exit 0. Wall time 342 s; one-minute load 11.0 at the start, peak 39.0. No failures. - Windows runs: - 45462452355 failed 9 fixture-side tests (8.3 short names), fixed in `f93aa60e1`; - 45465468867 and 45471312317 passed; @@ -104,6 +105,21 @@ ATTENTION PR #1640 — forge (conflicts), trial merge (conflicts) The forge's own mergeability agrees with the trial merge. +**The run that stopped the gate.** Before presenting the `pr` gate, a final `codev check pr 1958` on head `5bede63` (5.4 s, exit 1) read: + +``` +ATTENTION PR #1958 — forge (conflicts), trial merge (conflicts) + +head 5bede63 (local builder/spir-1951 matches) base main @ 707e0e9 (origin, live) + + ATTN forge CONFLICTING, DIRTY + ATTN trial merge 1 conflicting file merging into main @ 707e0e9: codev/resources/lessons-learned.md + ok checks head 5bede63: 8 passed + info overlap 5 files also changed on main since the branch point: codev-skeleton/roles/architect.md, codev/resources/arch.md, … +3 +``` + +Every check on the head was green, and the branch had merged main less than an hour earlier. In between, Spec 1940 landed on main and appended lessons at the same two places in `lessons-learned.md`. The trial merge found the one conflicting file and the forge agreed. The `overlap` line named the other files main had changed, which merged cleanly. The fix was a merge of `origin/main` (`5d802799f`, keeping both sides' lessons) before the gate went to the owner. This is the headline path doing its job: a run of one command, at the moment an architect would recommend a merge, naming the specific thing that blocks it. + **Earlier phases**, from the thread log (`codev/state/spir-1951_thread.md`): - **Phase 4.** - #1965: `ATTENTION — checks (running)`, with `code 31d3edf: 4 passed, 4 still running` and `head 0513558: porch-only, 8 still running`; later CLEAR at its pr gate. diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 78b6753d1..097ac38ca 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -427,3 +427,9 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals rejected by the architect (two spellings of one state; one forge per run). - Full local run on 30853b1fe (architect order, the local evidence): npm test -- --exclude='**/e2e/**' → 440 files passed / 14 skipped, 9286 tests passed / 116 skipped, exit 0, 363 s wall, load 18.4 start, 27.7 peak. +- Final check pr 1958 on 5bede63 before the gate: ATTENTION, forge CONFLICTING/DIRTY + trial merge 1 conflict + (lessons-learned.md) against main @ 707e0e9 (Spec 1940 landed). Merged origin/main as 5d802799f, keeping both + sides' lessons; hashes regenerate identically after the merge commit (192 versions); skill/governance tests + 127/127; rebuilt types+sdk (new ./address export), build, both tsc, residue OK. +- Second full local run on 5d802799f: 449 files passed / 14 skipped, 9885 tests passed / 116 skipped, exit 0, + 342 s, load 11.0 start, 39.0 peak. PR #1964 not yet on main at push time. From 7b2e06b8ab3efd2adeef2b445da05bceee781341 Mon Sep 17 00:00:00 2001 From: M Waleed Kadous Date: Tue, 24 Nov 2026 13:34:55 -0800 Subject: [PATCH 94/94] [Spec 1951] Thread log: main merged with PR #1964; hashes regenerated identically --- codev/state/spir-1951_thread.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/codev/state/spir-1951_thread.md b/codev/state/spir-1951_thread.md index 097ac38ca..655e619ba 100644 --- a/codev/state/spir-1951_thread.md +++ b/codev/state/spir-1951_thread.md @@ -433,3 +433,7 @@ All points accepted (rebuttal: codev/projects/1951-…/1951-plan-iter1-rebuttals 127/127; rebuilt types+sdk (new ./address export), build, both tsc, residue OK. - Second full local run on 5d802799f: 449 files passed / 14 skipped, 9885 tests passed / 116 skipped, exit 0, 342 s, load 11.0 start, 39.0 peak. PR #1964 not yet on main at push time. +- PR #1964 (porch saves failed check output) landed at 88bc5e9d1: merged origin/main as 80d25fc9a, clean; it + touches porch code, the porch skill x4 and the hash file only. Hashes regenerate identically after the merge + commit (194 versions); skill/governance/porch tests 161/161; build, tsc OK. No Windows run (no platform code; + architect). No full run (architect).