From b3323f47b8cb6ec074bc755d3b108983a816007a Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Sun, 22 Nov 2026 04:38:59 -0800 Subject: [PATCH] Review and ship tools: read Codex numbered severities, check Remote Control sessions, see every worktree (#4681) Five fixes from outside reports. The too-large-diff fix line now suggests only folders the policy can exclude, Codex findings written as `### 1. High` keep their severity, /autoplan's report check runs in Remote Control sessions, /ship's version picker sees all worktrees, and PR before/after images use the real base. Why: each reproduced on main with a failing test and gave a wrong answer. Nothing to do after merge. Co-authored-by: larsonthune <195244869+larsonthune@users.noreply.github.com> Co-authored-by: vilano93 <244097767+vilano93@users.noreply.github.com> Co-authored-by: szsunyuan <3579304+szsunyuan@users.noreply.github.com> Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=testing Review-Finding: p1/red-team#1 reader=red-team --- bin/gstack-config | 8 ++-- bin/gstack-next-version | 42 ++++++++++++----- bin/gstack-pr-shots | 2 +- .../fix-outside-review-ship-tooling.md | 9 ++++ lib/claude-journal-records.ts | 8 +++- lib/outside-review-result.ts | 6 +-- lib/pr-shots.ts | 19 +++++--- lib/review-exclude.ts | 29 +++++++++--- test/autoplan-publication-hook.test.ts | 27 +++++++++-- test/gstack-next-version.test.ts | 41 +++++++++++++++++ test/outside-review-severity.test.ts | 32 +++++++++++++ test/pr-shots.test.ts | 46 ++++++++++++++++++- test/review-exclude.test.ts | 20 ++++++++ 13 files changed, 250 insertions(+), 39 deletions(-) create mode 100644 changelog.d/fix-outside-review-ship-tooling.md diff --git a/bin/gstack-config b/bin/gstack-config index f69f3ccac..4417ef379 100755 --- a/bin/gstack-config +++ b/bin/gstack-config @@ -316,11 +316,11 @@ CONFIG_HEADER='# gstack configuration — edit freely, changes take effect on ne # # Invalid values are REJECTED (value kept). # # ─── Workspace-aware ship ──────────────────────────────────────────── -# workspace_root: $HOME/conductor/workspaces # Where /ship looks for sibling -# # Conductor worktrees when picking a VERSION slot. +# workspace_root: $HOME/conductor/workspaces # When picking a VERSION slot, +# # /ship checks every git worktree of the repo, +# # wherever it lives, plus /// +# # here, which also finds separate clones. # # Set to "null" to disable sibling scanning entirely. -# # Non-Conductor users can point this at any directory -# # that holds parallel worktrees of the same repo. # ' diff --git a/bin/gstack-next-version b/bin/gstack-next-version index 7e276dd79..203659255 100755 --- a/bin/gstack-next-version +++ b/bin/gstack-next-version @@ -2,7 +2,7 @@ // gstack-next-version — host-aware VERSION allocator for /ship. // // Queries the PR queue (GitHub or GitLab), fetches each open PR's VERSION, -// scans configurable Conductor sibling worktrees, picks the next free version +// scans sibling git worktrees and Conductor workspaces, picks the next free version // slot at the requested bump level, and emits the whole picture as JSON. // // Contract: util NEVER writes files or mutates state. Pure reader + reporter. @@ -38,7 +38,7 @@ // 3 — util bug (unexpected exception) import { execFileSync, spawn, spawnSync } from "node:child_process"; -import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"; +import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs"; import { homedir } from "node:os"; import { join, resolve } from "node:path"; import { @@ -385,22 +385,40 @@ function currentRepoSlug(): string { return m ? m[1] : ""; } -function scanSiblings(root: string | null, versionPath: string, claimed: ClaimedPR[], warnings: string[]): Sibling[] { - if (!root || !existsSync(root)) return []; +function canonicalPath(p: string): string { + try { + return realpathSync(p); + } catch { + return resolve(p); + } +} + +// Conductor layout: ///. Separate clones live here too, +// and git does not list those as worktrees. +function workspaceRootPaths(root: string, warnings: string[]): string[] { + if (!existsSync(root)) return []; const mySlug = currentRepoSlug(); if (!mySlug) { - warnings.push("could not determine current repo slug; skipping sibling scan"); + warnings.push("could not determine current repo slug; skipping the workspace_root scan"); return []; } - const repoName = mySlug.split("/").pop() ?? ""; - // Conductor layout: /// - const repoDir = join(root, repoName); + const repoDir = join(root, mySlug.split("/").pop() ?? ""); if (!existsSync(repoDir)) return []; - const myAbsPath = resolve(process.cwd()); + return readdirSync(repoDir).map((name) => join(repoDir, name)); +} + +function scanSiblings(root: string | null, versionPath: string, claimed: ClaimedPR[], warnings: string[]): Sibling[] { + if (!root) return []; + // Every checkout git links to this repository, wherever it was created (#4196). + const worktrees = runCommand("git", ["worktree", "list", "--porcelain"]); + const linked = worktrees.ok + ? worktrees.stdout.split("\n").filter((line) => line.startsWith("worktree ")).map((line) => line.slice("worktree ".length)) + : []; + const topLevel = runCommand("git", ["rev-parse", "--show-toplevel"]); + const myAbsPath = canonicalPath(topLevel.ok ? topLevel.stdout.trim() : process.cwd()); const results: Sibling[] = []; - for (const name of readdirSync(repoDir)) { - const p = join(repoDir, name); - if (resolve(p) === myAbsPath) continue; + for (const p of new Set([...linked, ...workspaceRootPaths(root, warnings)].map(canonicalPath))) { + if (p === myAbsPath) continue; try { const s = statSync(p); if (!s.isDirectory()) continue; diff --git a/bin/gstack-pr-shots b/bin/gstack-pr-shots index 653d816d2..048d096eb 100755 --- a/bin/gstack-pr-shots +++ b/bin/gstack-pr-shots @@ -27,7 +27,7 @@ const HELP = `gstack-pr-shots — before/after image of a change for a PR body ( --caption required: what changed and why (shown under the title and in the text version) --path a tracked file: base version vs working tree (source text, nothing executed) [--heading ] only that Markdown section (fence-aware, same parser as the Captain brief) - [--base <ref>] default: the merge base with origin/HEAD + [--base <ref>] default: the merge base with the repo's base branch --before <file> --after <file> two captures (terminal output, a rendered prompt) inside the repo or state root [--kind terminal|prompt] pane styling (default prompt; terminal is a dark panel) [--title <text>] [--name <slug>] [--out <dir>] [--json] diff --git a/changelog.d/fix-outside-review-ship-tooling.md b/changelog.d/fix-outside-review-ship-tooling.md new file mode 100644 index 000000000..f7886eae5 --- /dev/null +++ b/changelog.d/fix-outside-review-ship-tooling.md @@ -0,0 +1,9 @@ +**Codex review findings written as numbered headings keep their severity.** A finding like `### 1. High — title` read as having no severity, so a finished second-model review came back `untagged_review`. Contributed by @larsonthune (#4231). + +**/autoplan's phase-report check works in sessions where Remote Control was on from the start.** Claude Code writes a `bridge_status` record as the first line of those sessions, and the check skipped itself with a "not verified" warning on every reviewer call. Reported by @exGeni (#4298). + +**/ship sees every git worktree of a repo when it picks a version.** Worktrees outside the Conductor layout, such as Claude Code's `.claude/worktrees` or a plain `git worktree add`, were invisible, so two of them could take the same version. `workspace_root: null` still turns the scan off. Contributed by @vilano93 (#4196). + +**`gstack-pr-shots --path` compares against the real base branch when `origin/HEAD` points at the feature branch.** Committed changes no longer vanish from the before-and-after image. Contributed by @szsunyuan (#4141, #3733). + +**When a reviewer's diff is too large, the printed fix suggests only folders the review exclusion policy can actually exclude.** Code and tests always stay in review, so a folder of code was a fix that excluded nothing, and once that policy landed the same line asked for it again. The line now says to split the PR when excluding content files cannot get under the limit. Reported by @exGeni (#4369). diff --git a/lib/claude-journal-records.ts b/lib/claude-journal-records.ts index 5170ae015..904bf6617 100644 --- a/lib/claude-journal-records.ts +++ b/lib/claude-journal-records.ts @@ -230,6 +230,8 @@ export interface RecordMeta { message: boolean; role?: string; sessionStart: boolean; + /** Remote Control's status record, written as the conversation root when it is active before the first prompt. */ + bridgeRoot: boolean; timestampValid: boolean; cwd?: string; type?: string; @@ -285,7 +287,9 @@ export function recordMeta(r: Record<string, any>, index: number): RecordMeta { agent: r.agentId != null, sidechain: r.isSidechain !== false, conversation: r.agentId == null && message && (r.message.role === 'user' || r.message.role === 'assistant'), message, role: message && typeof r.message.role === 'string' ? r.message.role : undefined, - sessionStart: sessionStartRecord(r), timestampValid, cwd, + sessionStart: sessionStartRecord(r), + bridgeRoot: r.type === 'system' && r.subtype === 'bridge_status' && r.parentUuid === null && r.message == null, + timestampValid, cwd, type: typeof r.type === 'string' ? r.type : undefined, subtype: typeof r.subtype === 'string' ? r.subtype : undefined, attachmentType: object(r.attachment) && typeof r.attachment.type === 'string' ? r.attachment.type : undefined, version: indexedVersion(r), @@ -384,7 +388,7 @@ export function ownedCausalOrder(metas: readonly RecordMeta[], cwd: string): Own for (const node of genesis ? [root] : top.slice(0, turn + 1)) if (!sameNativePath(node.cwd, cwd)) return { reason: sameRealPath(node.cwd, cwd) ? 'unrecognized_shape:cwd_spelling' : 'foreign_cwd', shape: shape() }; if (!genesis) { - const preamble = top.slice(0, turn).find(n => !n.sessionStart); + const preamble = top.slice(0, turn).find(n => !n.sessionStart && !n.bridgeRoot); const odd = !root.parentNull ? `root_parent:${shapeOf(root)}` : preamble ? `preamble:${shapeOf(preamble)}` : top[turn]!.role !== 'user' ? `first_turn:${shapeOf(top[turn]!)}` : undefined; diff --git a/lib/outside-review-result.ts b/lib/outside-review-result.ts index 6640d44dc..eedb1411a 100644 --- a/lib/outside-review-result.ts +++ b/lib/outside-review-result.ts @@ -166,7 +166,7 @@ const AUTOPLAN_LEVEL: Record<string, Severity | undefined> = { Critical: 'P0', H const WORD = '(critical|high|medium|low)'; const SEVERITY_LABELS = [ new RegExp(`\\b(?:severity|priority)\\b[\\t ]*[:=][\\t ]*(?:\\*\\*|__|\\[|\`)*${WORD}\\b`, 'gim'), - new RegExp(`^[\\t ]*(?:>[\\t ]*)?(?:#{1,6}[\\t ]+|[-+*][\\t ]+|\\(?\\d{1,3}[.)][\\t ]+)?(?:\\*\\*|__)?\\[?${WORD}\\]?(?:\\*\\*|__)?[\\t ]*(?::|\u2014|\u2013|-[\\t ]|\\]|\\(|\\*\\*[\\t ]*(?:\u2014|\u2013|-[\\t ]))`, 'gim'), + new RegExp(`^[\\t ]*(?:>[\\t ]*)?(?:#{1,6}[\\t ]+)?(?:[-+*][\\t ]+|\\(?\\d{1,3}[.)][\\t ]+)?(?:\\*\\*|__)?\\[?${WORD}\\]?(?:\\*\\*|__)?[\\t ]*(?::|\u2014|\u2013|-[\\t ]|\\]|\\(|\\*\\*[\\t ]*(?:\u2014|\u2013|-[\\t ]))`, 'gim'), new RegExp(`(?:\\*\\*|__)\\[?${WORD}\\]?:?(?:\\*\\*|__)`, 'gi'), new RegExp(`\\|[\\t ]*(?:\\*\\*)?${WORD}(?:\\*\\*)?[\\t ]*(?=\\|)`, 'gi'), new RegExp(`[\\t ](?:\u2014|\u2013|-)[\\t ]+(?:\\*\\*|__)?${WORD}(?:\\*\\*|__)?[\\t ]*[.;]?[\\t ]*$`, 'gim'), @@ -216,7 +216,7 @@ function recommendationHeading(text: string): string { * or `Verdict: not ready`, while the evidence for clean keeps it blanked. One pass: * an opener closes only when a later marker of its kind is at least as long. */ -const CODE_LABEL_BEFORE = /^[\t ]*(?:>[\t ]*)?(?:#{1,6}[\t ]+|[-+*][\t ]+|\(?\d{1,3}[.)][\t ]+)?(?:\*\*|__)?$|\b(?:severity|priority)[\t ]*[:=][\t ]*(?:\*\*|__)?$|\|[\t ]*(?:\*\*)?$/i; +const CODE_LABEL_BEFORE = /^[\t ]*(?:>[\t ]*)?(?:#{1,6}[\t ]+)?(?:[-+*][\t ]+|\(?\d{1,3}[.)][\t ]+)?(?:\*\*|__)?$|\b(?:severity|priority)[\t ]*[:=][\t ]*(?:\*\*|__)?$|\|[\t ]*(?:\*\*)?$/i; function withoutCode(text: string, readUnclosed = false): string { const lines = text.split(/\r?\n/); const markers = lines.map(line => /^[\t ]*(`{3,}|~{3,})/.exec(line)?.[1]); @@ -248,7 +248,7 @@ function withoutCode(text: string, readUnclosed = false): string { * bullet, number or bold, as `[P1]`, `P1:`, `P1 —`, `**P1 — x**`, `**P1** — x`, * `P1 (x)` or a bare `P1` ending the line; or a table cell `| P1 |`. */ -const LABEL_START = '^[\\t ]*(?:>[\\t ]*)?(?:#{1,6}[\\t ]+|[-+*][\\t ]+|\\(?\\d{1,3}[.)][\\t ]+)?(?:\\*\\*|__)?'; +const LABEL_START = '^[\\t ]*(?:>[\\t ]*)?(?:#{1,6}[\\t ]+)?(?:[-+*][\\t ]+|\\(?\\d{1,3}[.)][\\t ]+)?(?:\\*\\*|__)?'; const LABELED_P = new RegExp(`${LABEL_START}(?:\\[(P[0-3])\\]|(P[0-3])(?:\\*\\*|__)?[\\t ]*(?::|\u2014|\u2013|-[\\t ]|\\(|$|(?:\\*\\*|__)[\\t ]*(?::|\u2014|\u2013|-[\\t ]|$)))`, 'gm'); const TABLE_P = /\|[\t ]*(?:\*\*)?\[?(P[0-3])\]?(?:\*\*)?[\t ]*(?=\|)/g; const LABEL_P = new RegExp(`${LABEL_START}\\[?P[0-3]\\b`); diff --git a/lib/pr-shots.ts b/lib/pr-shots.ts index 2090edbfc..a06a8947e 100644 --- a/lib/pr-shots.ts +++ b/lib/pr-shots.ts @@ -17,7 +17,8 @@ import { spawnSync } from './spawn-sync'; import * as fs from 'node:fs'; import * as path from 'node:path'; -import { resolveBase } from './gate-diff/git'; +import { defaultBase as defaultBaseRef, mergeBase, resolveBase } from './gate-diff/git'; +import { noDefaultBaseLine } from './default-base'; import { findSection } from './markdown-sections'; import { scan } from './redact-engine'; import type { ResultCodeName } from './result-codes'; @@ -65,13 +66,19 @@ export function resolveCommit(cwd: string, ref: string): string | ShotError { return r.status === 0 ? r.stdout.trim() : { code: 'PR_SHOTS_INPUT_NOT_FOUND', message: `base ref ${ref}` }; } -/** The default base: where this branch left origin's default branch. */ +/** + * The default base: where this branch left its base branch, chosen by the shared default-base rules (a remote HEAD naming + * this branch is skipped, #3733). A stale remote HEAD falls back to main, then master. + */ export function defaultBase(cwd: string): string | ShotError { - for (const ref of ['origin/HEAD', 'origin/main', 'main']) { - const r = git(cwd, ['merge-base', 'HEAD', ref]); - if (r.status === 0 && r.stdout.trim()) return r.stdout.trim(); + const found = defaultBaseRef(cwd); + if ('skipped' in found) return { code: 'PR_SHOTS_INPUT_NOT_FOUND', message: noDefaultBaseLine(found.skipped) }; + for (const ref of [found.ref, 'main', 'master']) { + const base = resolveBase(ref, cwd, 'HEAD'); + const fork = base && mergeBase('HEAD', base.sha, cwd); + if (fork) return fork; } - return { code: 'PR_SHOTS_INPUT_NOT_FOUND', message: 'no merge base with origin/HEAD, origin/main or main; pass --base <ref>' }; + return { code: 'PR_SHOTS_INPUT_NOT_FOUND', message: `no merge base with ${found.ref}, main or master; pass --base <ref>` }; } /** Both sides of a tracked file (or one heading's section of it) at `base` and in the working tree. */ diff --git a/lib/review-exclude.ts b/lib/review-exclude.ts index d22128981..1c58c8485 100644 --- a/lib/review-exclude.ts +++ b/lib/review-exclude.ts @@ -664,17 +664,33 @@ function policyJson(patterns: readonly string[], floor?: string | null): string return JSON.stringify({ review_exclude_paths: patterns, min_gstack_version: min }); } -/** Folders to suggest: the largest top directories, until what is left would fit. */ -function suggest(byDir: ReadonlyArray<[string, number]>, bytes: number): string[] { +/** By path alone, whether review_exclude_paths could exclude a file: content (data, logs, docs, binary assets), never code or tests. */ +const excludableByPath = (p: string) => !SOURCE.test(p) && (DATA_PATH.test(p) || /\.log$/i.test(p) || BINARY_CONTENT_EXT.test(p) || classifyPath(p) === 'docs'); + +/** + * Folders to suggest: the top directories holding the most bytes the policy could exclude (whole folders when only folder + * sizes are known), until what is left would fit; none when they cannot get the reader under the ceiling (#4369). + */ +function suggest(d: { bytes: number; byDir: ReadonlyArray<[string, number]>; byFile?: ReadonlyArray<[string, number]> }): string[] { + let byDir = d.byDir; + if (d.byFile?.length) { + const excludable = new Map<string, number>(); + for (const [file, n] of d.byFile) { + if (!excludableByPath(file)) continue; + const dir = file.includes('/') ? file.split('/')[0]! : '(root)'; + excludable.set(dir, (excludable.get(dir) ?? 0) + n); + } + byDir = [...excludable].sort((a, b) => b[1] - a[1]); + } const out: string[] = []; - let left = bytes; + let left = d.bytes; for (const [dir, n] of byDir) { if (left <= REVIEW_DIFF_MAX_BYTES || out.length >= 3) break; if (dir === '(root)') continue; out.push(`${dir}/**`); left -= n; } - return out; + return left <= REVIEW_DIFF_MAX_BYTES ? out : []; } /** The REVIEW_DIFF_TOO_LARGE line and object: the reader's bytes, the largest folders and files, and a fix chosen by where the policy stands. */ @@ -684,9 +700,10 @@ export function tooLargeLine(context: string, reader: string, d: { bytes: number const largest = (d.byFile ?? []).slice(0, 5); const split = largest.length ? `split the PR (largest files: ${largest.map(([f, n]) => `${named(f)} (${n} bytes)`).join(', ')})` : 'split the PR'; const land = (patterns: readonly string[]) => `ask the repo owner to land ${policyJson(patterns, c.floor)} in ${SHIP_POLICY_PATH} on ${c.base} as its own PR (docs/ship-policy.md#review-exclude-paths), then bring ${c.base} into this branch and rerun once; if it is still over, ${split}`; - const dirs = suggest(d.byDir, d.bytes); + const dirs = suggest(d); + const fresh = dirs.filter(p => !c.record?.patterns.includes(p)); const fix = c.state === 'head-only' ? `this branch declares review_exclude_paths, but only the copy on ${c.base} applies: ${land(c.headPatterns ?? [])}` - : c.state === 'active' ? `still over after excluding ${c.record?.excluded ?? 0} files; ${dirs.length ? land([...(c.record?.patterns ?? []), ...dirs.filter(p => !c.record?.patterns.includes(p))]) : split}` + : c.state === 'active' ? `still over after excluding ${c.record?.excluded ?? 0} files; ${fresh.length ? land([...(c.record?.patterns ?? []), ...fresh]) : split}` : dirs.length ? land(dirs) : split; const files = largest.length ? ` files=${largest.map(([f, n]) => `${/[\s,:"]/.test(f) ? JSON.stringify(f) : f}:${n}`).join(',')}` : ''; const line = `${context}: the reader's diff is over the review ceiling (reader=${reader} bytes=${d.bytes} max=${REVIEW_DIFF_MAX_BYTES} top=${top}${files} policy=${c.source}); fix: ${fix}; nothing was written (REVIEW_DIFF_TOO_LARGE)`; diff --git a/test/autoplan-publication-hook.test.ts b/test/autoplan-publication-hook.test.ts index 9635e38fa..fe2ac2741 100644 --- a/test/autoplan-publication-hook.test.ts +++ b/test/autoplan-publication-hook.test.ts @@ -66,7 +66,7 @@ describe('Autoplan hook journal-root verdicts', () => { const entry = path.join(ROOT, 'autoplan/sections/design-phase.md'); const real = JSON.parse(fs.readFileSync(path.join(ROOT, 'test/fixtures/claude-native-journal-roots-2.1.284.json'), 'utf8')); /** One owned native journal; the current phase-entry Read is its last record unless `current` is false. */ - function session(shape: 'unknown' | 'competing_root' | 'foreign_cwd' | 'sidechain' | 'agent' | 'cycle' | 'startup', + function session(shape: 'unknown' | 'competing_root' | 'foreign_cwd' | 'sidechain' | 'agent' | 'cycle' | 'startup' | 'bridge' | 'bridge_competing', { current = true, partial = false } = {}) { const base = fs.realpathSync(fs.mkdtempSync(path.join(tmpdir(), 'autoplan-hook-roots-'))); dirs.push(base); const cwd = path.join(base, 'project'), project = path.join(base, 'config', 'projects', 'project'); @@ -84,10 +84,13 @@ describe('Autoplan hook journal-root verdicts', () => { rows = real.journals.startup.lines.map((line: string) => JSON.parse(line.replaceAll('__CWD__', JSON.stringify(cwd).slice(1, -1)))); for (const row of rows as any[]) if (row.sessionId) row.sessionId = sessionId; } else { - const head = shape === 'unknown' ? node(null, { type: 'system', subtype: 'local_command' }) : hook(null); + const head = shape === 'unknown' ? node(null, { type: 'system', subtype: 'local_command' }) + : shape.startsWith('bridge') ? node(null, { type: 'system', subtype: 'bridge_status', isMeta: false, + content: '/remote-control is active', url: 'https://claude.ai/code/session_x' }) + : hook(null); const turn = prompt(head.uuid); - rows = [head, turn]; - if (shape === 'competing_root') rows.push(prompt(null)); + rows = shape.startsWith('bridge') ? [{ type: 'bridge-session', sessionId }, head, turn, hook(turn.uuid)] : [head, turn]; + if (shape === 'competing_root' || shape === 'bridge_competing') rows.push(prompt(null)); if (shape === 'foreign_cwd') Object.assign(head, { cwd: path.join(base, 'config') }); if (shape === 'sidechain') Object.assign(head, { isSidechain: true }); if (shape === 'agent') Object.assign(head, { agentId: 'agent-1' }); @@ -171,6 +174,22 @@ describe('Autoplan hook journal-root verdicts', () => { expect(output.hookSpecificOutput.permissionDecisionReason).toContain('Autoplan invocation evidence is unavailable'); }); + // Value: protects=a session with Remote Control active from the start (a system bridge_status record as the journal + // root, #4298) is owned and verified like a plain session, while a competing root next to it still denies; + // fails_when=the bridge head reads as unrecognized_shape and publication enforcement is skipped, or the new + // preamble record hides a second root; why_new=only SessionStart attachments were accepted above the first turn; seam=none + test('a Remote Control bridge_status root is owned and reaches publication evaluation', async () => { + const output = await session('bridge').hookRun(); + expect(output.systemMessage ?? '').not.toContain('NOT verified'); + expect(output.hookSpecificOutput.permissionDecision).toBe('deny'); + expect(output.hookSpecificOutput.permissionDecisionReason).toContain('Autoplan invocation evidence is unavailable'); + }); + test('a bridge_status root next to a second null-parent prompt is still a competing root', async () => { + const output = await session('bridge_competing').hookRun(); + expect(output.hookSpecificOutput.permissionDecision).toBe('deny'); + expect(output.hookSpecificOutput.permissionDecisionReason).toContain('code competing_root'); + }); + test('the shipped shim degrades and denies with real native spellings', () => { // On Windows the hook env and transcript arrive spelled C:/...; the fold must accept them. const forward = (value: string) => process.platform === 'win32' ? value.replaceAll('\\', '/') : value; diff --git a/test/gstack-next-version.test.ts b/test/gstack-next-version.test.ts index 346456a70..a7d067999 100644 --- a/test/gstack-next-version.test.ts +++ b/test/gstack-next-version.test.ts @@ -1378,3 +1378,44 @@ describe("concurrent VERSION fetches (W2-A3)", () => { } }, 30_000); }); + +describe("sibling scan finds git worktrees outside the workspace_root layout (#4196)", () => { + const NEXTVER = join(import.meta.dir, "..", "bin", "gstack-next-version"); + + // Value: protects=a linked worktree anywhere on disk (Claude Code's .claude/worktrees, plain git worktree add) counts + // as a sibling when /ship picks a version, and workspace_root null still turns the scan off; fails_when=only + // <workspace_root>/<repo>/<workspace>/ is read, so two worktrees can take the same version; why_new=every sibling + // case used the Conductor layout or disabled the scan; seam=none + test("a linked worktree outside workspace_root is a sibling; null disables the scan", () => { + const root = mkdtempSync(join(tmpdir(), "nextver-wt-")); + const work = join(root, "work"); + mkdirSync(work); + const git = (cwd: string, ...args: string[]) => + execFileSync("git", ["-c", "user.email=t@t", "-c", "user.name=t", ...args], { cwd, stdio: ["ignore", "pipe", "pipe"], timeout: 30_000 }); + git(work, "init", "-q", "-b", "main"); + writeFileSync(join(work, "VERSION"), "1.0.0.0\n"); + git(work, "add", "-A"); + git(work, "commit", "-qm", "base"); + const wt = join(root, "elsewhere", "wt1"); + git(work, "worktree", "add", "-q", "-b", "feat", wt); + writeFileSync(join(wt, "VERSION"), "1.0.1.0\n"); + git(wt, "commit", "-qam", "bump"); + const stubDir = mkdtempSync(join(tmpdir(), "nextver-stubgh-")); + writeFileSync(join(stubDir, "gh"), "#!/bin/sh\nexit 1\n", { mode: 0o755 }); + const run = (workspaceRoot: string) => { + const proc = Bun.spawnSync( + ["bun", "run", NEXTVER, "--base", "main", "--bump", "patch", "--current-version", "1.0.0.0", "--workspace-root", workspaceRoot], + { cwd: work, env: { ...process.env, PATH: `${stubDir}:${process.env.PATH}` }, timeout: 30_000 }, + ); + return JSON.parse(new TextDecoder().decode(proc.stdout)); + }; + try { + const found = run(join(root, "no-such-root")); + expect(found.siblings.map((s: any) => [s.branch, s.version])).toEqual([["feat", "1.0.1.0"]]); + expect(run("null").siblings).toEqual([]); + } finally { + rmSync(stubDir, { recursive: true, force: true }); + rmSync(root, { recursive: true, force: true }); + } + }, 30_000); +}); diff --git a/test/outside-review-severity.test.ts b/test/outside-review-severity.test.ts index 958193ed5..dc2239330 100644 --- a/test/outside-review-severity.test.ts +++ b/test/outside-review-severity.test.ts @@ -114,3 +114,35 @@ describe('design proposals use the proposal gate', () => { expect(outsideVoiceCommand({ ...ctx, skillName: 'plan-ceo-review' }, { timeoutMs: 300000 })).toMatch(/ review "\$_OUTSIDE_TMP\/text"/); }); }); + +// Value: protects=a numbered heading (`### 1. High — title`, as Codex writes findings) carries its severity word; +// fails_when=the label start allows only one prefix, so no severity is read and a completed review comes back +// untagged_review; why_new=every label case had a heading or a number, never both; seam=none +describe('a numbered heading carries its severity word', () => { + for (const [heading, highest] of [ + ['### 1. High — Make it look good silently removes editing', 'P1'], + ['## 2. Critical — The security model protects the session, not the document', 'P0'], + ['### 3. Medium — Batch import is a toast, not a workflow', 'P2'], + ['### 4. [P1] Tagged numbered heading', 'P1'], + ] as const) { + test(heading, () => { + const text = `${heading}\nBody text.\nRecommendation: fix it because the change loses data.\n\nVERDICT: FINDINGS\n`; + const result = classifyOutsideReview({ text, exitCode: 0, stderr: '', events: '' } as never); + expect(result.findings?.highest).toBe(highest); + expect(result.reason).not.toBe('untagged_review'); + }); + } + test('prose "high-level" under a numbered heading is still not a label', () => { + const text = `### 1. A high-level concern about naming\nBody.\nRecommendation: rename it because readers guess wrong.\n\nVERDICT: FINDINGS\n`; + const result = classifyOutsideReview({ text, exitCode: 0, stderr: '', events: '' } as never); + expect(result.findings?.highest ?? null).toBeNull(); + }); + // Value: protects=a clean second-model review laid out under numbered section headings stays clean; fails_when=numbered + // headings count as unlabeled findings and a VERDICT: CLEAN reply reads as untagged_review; why_new=only FINDINGS replies + // with numbered headings were tested; seam=none + test('a CLEAN review with numbered section headings stays clean', () => { + const text = '## 1. Scope\nI read the diff.\n## 2. Result\nNothing found.\nRecommendation: ship because no issue was found.\n\nVERDICT: CLEAN\n'; + const result = classifyOutsideReview({ text, exitCode: 0, stderr: '', events: '', gate: 'review' } as never); + expect(result.verdict).toBe('clean'); + }); +}); diff --git a/test/pr-shots.test.ts b/test/pr-shots.test.ts index 90d2459ec..2dc7fcd1a 100644 --- a/test/pr-shots.test.ts +++ b/test/pr-shots.test.ts @@ -9,7 +9,7 @@ import { spawnSync } from 'node:child_process'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { buildPage, cleanText, diffLines, hunks, pathSides, resolveCommit } from '../lib/pr-shots'; +import { buildPage, cleanText, defaultBase, diffLines, hunks, pathSides, resolveCommit } from '../lib/pr-shots'; import { wtreeFingerprint } from '../lib/script-invocation'; const ROOT = path.resolve(import.meta.dir, '..'); @@ -27,6 +27,50 @@ function repo(files: Record<string, string>): { dir: string; base: string } { return { dir, base: git('rev-parse', 'HEAD').stdout.trim() }; } +describe('default base (#3733)', () => { + const featureRepo = (baseBranch: string) => { + const r = repo({ 'doc.md': 'before\n' }); + const git = (...a: string[]) => { + const out = spawnSync('git', a, { cwd: r.dir, encoding: 'utf8', env: GIT_ENV, timeout: 30_000 }); + if (out.status !== 0) throw new Error(`fixture git ${a.join(' ')} failed: ${out.stderr}`); + return out.stdout.trim(); + }; + if (baseBranch !== 'main') git('branch', '-m', baseBranch); + const origin = tmp('shots-origin-'); + git('init', '-q', '--bare', '--initial-branch', baseBranch, origin); + git('remote', 'add', 'origin', origin); + git('push', '-q', '-u', 'origin', baseBranch); + git('remote', 'set-head', 'origin', baseBranch); + git('checkout', '-q', '-b', 'feature'); + fs.writeFileSync(path.join(r.dir, 'doc.md'), 'after\n'); + git('add', 'doc.md'); git('commit', '-q', '-m', 'feature text'); + git('push', '-q', '-u', 'origin', 'feature'); + return { ...r, git }; + }; + + // Value: protects=a clone whose origin/HEAD names the pushed feature branch still compares against the real base, so + // committed PR changes show; fails_when=the feature head is its own before-image and generation refuses with + // PR_SHOTS_IDENTICAL; why_new=path-mode tests always passed --base; seam=none + test.each(['main', 'develop'])('origin/HEAD naming the feature branch still compares against %s', baseBranch => { + const r = featureRepo(baseBranch); + expect(defaultBase(r.dir)).toBe(r.base); + r.git('remote', 'set-head', 'origin', 'feature'); + const chosen = defaultBase(r.dir); + expect(chosen).toBe(r.base); + const sides = pathSides(r.dir, 'doc.md', chosen as string); + if ('code' in sides) throw new Error(sides.message); + expect([sides.before.text, sides.after.text]).toEqual(['before\n', 'after\n']); + }); + + // Value: protects=a stale origin/HEAD (its branch is gone) falls back to main instead of refusing; fails_when=the + // dangling target is taken as the base with no fallback; why_new=the case above always resolves; seam=none + test('a dangling origin/HEAD falls back to main', () => { + const r = featureRepo('main'); + r.git('symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/retired'); + expect(defaultBase(r.dir)).toBe(r.base); + }); +}); + describe('diff and hunks', () => { test('a change at line 240 of 300 stays visible; gaps say how much they hide', () => { const a = Array.from({ length: 300 }, (_, i) => `line ${i + 1}`); diff --git a/test/review-exclude.test.ts b/test/review-exclude.test.ts index e3f343100..1f6bbdf56 100644 --- a/test/review-exclude.test.ts +++ b/test/review-exclude.test.ts @@ -267,6 +267,26 @@ describe('the review ceiling lines', () => { expect(over).toEndWith('nothing was written (REVIEW_DIFF_TOO_LARGE)'); }); + // Value: protects=the printed policy names only folders whose files the policy can exclude (content, never code or + // tests), says split the PR when excludable bytes cannot reach the ceiling, and never asks again for a policy that is + // already landed; fails_when=a code-only folder is suggested, or the active line repeats the landed patterns (#4369); + // why_new=every ceiling case had a content-only top folder; seam=tooLargeLine; no_claim=the policy's consumer checks + test('the fix suggests only excludable folders, and says split when the policy cannot get under the ceiling', () => { + const json = (line: string) => JSON.parse(line.match(/land (\{.*?\}) in /)![1]!); + const codeHeavy = { bytes: 2_378_104, byDir: [['src', 2_029_068], ['docs', 349_036]] as Array<[string, number]>, + byFile: [['src/mod0.ts', 676_380], ['src/mod1.ts', 676_357], ['src/mod2.ts', 676_331], ['docs/guide.md', 349_036]] as Array<[string, number]> }; + const none = tooLargeLine('ctx', 'batched', codeHeavy, { state: 'none', base: 'main', source: 'origin/main@abc' }).line; + expect(none).not.toContain('review_exclude_paths'); + expect(none).toContain('fix: split the PR (largest files: src/mod0.ts'); + const landed = tooLargeLine('ctx', 'batched', codeHeavy, { state: 'active', base: 'main', source: 'origin/main@abc', record: { patterns: ['src/**'], excluded: 0 } }).line; + expect(landed).toContain('still over after excluding 0 files; split the PR'); + const mixed = { bytes: 3_000_000, byDir: [['src', 1_600_000], ['results', 1_400_000]] as Array<[string, number]>, + byFile: [['src/a.ts', 1_600_000], ['results/run.jsonl', 1_400_000]] as Array<[string, number]> }; + expect(json(tooLargeLine('ctx', 'batched', mixed, { state: 'none', base: 'main', source: 'origin/main@abc' }).line).review_exclude_paths).toEqual(['results/**']); + const again = tooLargeLine('ctx', 'batched', mixed, { state: 'active', base: 'main', source: 'origin/main@abc', record: { patterns: ['results/**'], excluded: 0 } }).line; + expect(again).toContain('still over after excluding 0 files; split the PR'); + }); + // Value: protects=a REVIEW_DIFF_UNREADABLE stop says timeout or git exit, the timeout, and keeps full stderr in a file with // remote URLs redacted; fails_when=a credential-bearing remote URL reaches the line or the log, or the fix ignores the // reason; why_new=task 5; seam=readSelection and unreadableLine; no_claim=a real 120-second timeout