From 610d3430b3d7bedaf50864402d98584f77064ce5 Mon Sep 17 00:00:00 2001 From: carlos-alm Date: Tue, 11 Aug 2026 09:52:25 -0600 Subject: [PATCH 1/2] fix(skills): fixer step 2g defends against a moved queue head Step 2g's state-recording bash block read queue.json[0] fresh at write time with no check that it was still the issue this dispatch was actually working on. If some other writer shifted queue.json past this issue while 2a-2g was still running for it (e.g. during 2f-bis's I8 post-merge-CI polling), 2g would silently record its outcome under whatever issue now sat at the queue's head -- marking an untouched issue as done and dropping it from the queue with no trace of the mistake. Observed once in practice (#2075 dropped this way while a sub-agent was mid-run on #2074) and manually repaired at the time; the underlying race was still present. 2g now compares queue.json[0] against .codegraph/fixer/dispatching-issue (captured before this issue was ever dispatched, per "Dispatching each issue to a sub-agent") and hard-stops instead of writing when they disagree, mirroring the same defense the validation/reconciliation block already applies after a dispatch returns. Closes #2304 --- .claude/skills/fixer/SKILL.md | 16 +- .../fixer-skill-2g-queue-guard-2304.test.ts | 152 ++++++++++++++++++ 2 files changed, 167 insertions(+), 1 deletion(-) create mode 100644 tests/unit/fixer-skill-2g-queue-guard-2304.test.ts diff --git a/.claude/skills/fixer/SKILL.md b/.claude/skills/fixer/SKILL.md index 32ea0f612..0e744421e 100644 --- a/.claude/skills/fixer/SKILL.md +++ b/.claude/skills/fixer/SKILL.md @@ -1092,6 +1092,20 @@ if [ -z "$ISSUE" ] || [ "$ISSUE" = "null" ]; then echo "ERROR: queue is empty — nothing to record. The loop should have exited already." exit 1 fi +# Defend against a moved queue head (issue #2304): if some other writer shifted +# queue.json past this issue while 2a-2g was still running for it, queue.json[0] +# is no longer this issue — it's whatever comes next. Recording under that wrong +# number would silently mark an untouched issue as done and drop it from the +# queue. dispatching-issue was captured before this issue was ever dispatched +# (see "Dispatching each issue to a sub-agent" above) and must still agree. +if [ -f .codegraph/fixer/dispatching-issue ]; then + DISPATCHED=$(cat .codegraph/fixer/dispatching-issue) + if [ "$DISPATCHED" != "$ISSUE" ]; then + echo "ERROR: queue.json's head is #$ISSUE but this run was dispatched for #$DISPATCHED — something else moved the queue head while this issue was still in progress. Refusing to record the outcome under the wrong issue number." + echo "Investigate .codegraph/fixer/queue.json and state.json before proceeding — do not blindly retry." + exit 1 + fi +fi # STATUS comes from .codegraph/fixer/outcome, written by whichever path this issue # actually took: "abandoned" in 2b, "parked" once the convergence-round cap is hit in # 2f, or "merged" right after a successful `gh pr merge`. Never hardcode it here — that @@ -1517,7 +1531,7 @@ All state is under `.codegraph/fixer/`: | `queue.json` | JSON array of `{issue, title}` | current batch's remaining work, ascending; entries are shifted off as they complete. **A present-but-empty `queue.json` means the batch loop fully completed** — Phase 0 uses this, together with `parked.txt` and `run-complete`, to decide fresh-run vs. resume | | `state.json` | `{"issues":[{issue, status, pr}]}` | per-issue outcome, accumulated across every batch this run has processed; reset to empty whenever Phase 0 detects a fresh run | | `state.json.bak` | JSON | snapshot taken immediately before each issue's sub-agent dispatch (I7); restore from this if a dispatch corrupts `state.json` | -| `dispatching-issue` | text | the issue number captured before the current dispatch; read back by the validation/reconciliation block and by a retry dispatch, since queue.json's head is no longer reliable once 2g has shifted it | +| `dispatching-issue` | text | the issue number captured before the current dispatch; read back by the validation/reconciliation block, by a retry dispatch, and by 2g itself (to detect a moved queue head, #2304) — queue.json's head is no longer reliable once 2g has shifted it | | `dispatch-retry-needed` | marker file | written only when reconciliation determines a second 2a-2g dispatch is needed for the same issue; cleared at the top of every validation-and-reconciliation run | | `parked.txt` | newline-separated PR numbers | accumulated across every batch; input to Phase: Drain Parked PRs; a merged PR's number is removed from this file the moment it merges. **Only ever emptied, never deleted, by a fully-merged drain** — Phase 0 treats a non-empty `parked.txt` as evidence of a resumable (mid-drain) run only if `run-complete` is absent; once Phase: Final Report has actually run and written it, the remaining entries are a closed, already-reported matter, not a resume signal | | `run-complete` | empty marker file | touched by Phase: Final Report as its last action, strictly after the report has been produced — the sole authoritative "this run's outcome was reported" signal Phase 0 checks, deliberately decoupled from `drain-stall`/`drain-pass` (which get written mid-Phase-4 and would otherwise race against the report actually happening); reset (removed) whenever Phase 0 starts a genuinely fresh run | diff --git a/tests/unit/fixer-skill-2g-queue-guard-2304.test.ts b/tests/unit/fixer-skill-2g-queue-guard-2304.test.ts new file mode 100644 index 000000000..e63355998 --- /dev/null +++ b/tests/unit/fixer-skill-2g-queue-guard-2304.test.ts @@ -0,0 +1,152 @@ +/** + * Regression test for issue #2304: `.claude/skills/fixer/SKILL.md` step 2g's + * state-recording bash block read `queue.json[0]` fresh at write time with no + * check that it was still the issue this dispatch was actually working on. If + * some other writer shifted `queue.json` past this issue while 2a-2g was + * still running for it (e.g. during 2f-bis's I8 post-merge-CI polling), 2g + * would silently record its outcome under whatever issue now sat at the + * queue's head — marking an untouched issue as done and dropping it from the + * queue with no trace of the mistake. + * + * The fix compares `queue.json[0]` against `.codegraph/fixer/dispatching-issue` + * (captured before this issue was ever dispatched, per "Dispatching each + * issue to a sub-agent") and refuses to write when they disagree. + * + * Extracts the actual 2g bash block from the real SKILL.md (not a + * reimplementation of its logic) and executes it against a sandboxed + * `.codegraph/fixer/` directory, mirroring fixer-skill-2g-queue-guard-2229.test.ts. + */ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; + +const REPO_ROOT = path.join(import.meta.dirname, '../..'); +const SKILL_PATH = path.join(REPO_ROOT, '.claude/skills/fixer/SKILL.md'); + +/** Extract the first ```bash fenced block following a given section heading. */ +function extractBashBlockAfterHeading(markdown: string, heading: string): string { + const headingIdx = markdown.indexOf(heading); + if (headingIdx === -1) { + throw new Error(`Heading not found in SKILL.md: ${heading}`); + } + const rest = markdown.slice(headingIdx); + const fenceStart = rest.indexOf('```bash'); + if (fenceStart === -1) { + throw new Error(`No \`\`\`bash fence found after heading: ${heading}`); + } + const bodyStart = rest.indexOf('\n', fenceStart) + 1; + const fenceEnd = rest.indexOf('```', bodyStart); + if (fenceEnd === -1) { + throw new Error(`Unterminated \`\`\`bash fence after heading: ${heading}`); + } + return rest.slice(bodyStart, fenceEnd); +} + +function runBlock( + block: string, + sandbox: string, +): { exitCode: number; stdout: string; stderr: string } { + try { + const stdout = execFileSync('bash', ['-c', block], { cwd: sandbox, encoding: 'utf8' }); + return { exitCode: 0, stdout, stderr: '' }; + } catch (err) { + const e = err as { status: number; stdout: string; stderr: string }; + return { exitCode: e.status, stdout: e.stdout ?? '', stderr: e.stderr ?? '' }; + } +} + +function setupSandbox(dispatchingIssue: string | null): string { + const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'fixer-2g-sandbox-2304-')); + fs.mkdirSync(path.join(sandbox, '.codegraph/fixer'), { recursive: true }); + fs.writeFileSync(path.join(sandbox, '.codegraph/fixer/state.json'), '{"issues":[]}'); + fs.writeFileSync( + path.join(sandbox, '.codegraph/fixer/queue.json'), + JSON.stringify([ + { issue: 100, title: 'first' }, + { issue: 200, title: 'second' }, + ]), + ); + fs.writeFileSync(path.join(sandbox, '.codegraph/fixer/outcome'), 'merged'); + fs.writeFileSync(path.join(sandbox, '.codegraph/fixer/current-pr'), '999'); + if (dispatchingIssue !== null) { + fs.writeFileSync(path.join(sandbox, '.codegraph/fixer/dispatching-issue'), dispatchingIssue); + } + return sandbox; +} + +describe('fixer skill 2g moved-queue-head guard (#2304)', () => { + const skillContent = fs.readFileSync(SKILL_PATH, 'utf-8'); + const block = extractBashBlockAfterHeading( + skillContent, + '### 2g. Record the outcome and advance', + ); + + it('extracted a block that checks dispatching-issue', () => { + expect(block).toContain('dispatching-issue'); + }); + + it("refuses to record when dispatching-issue disagrees with queue.json's head", () => { + // Simulates the exact race from #2304: this dispatch was for issue #100, + // but something else shifted queue.json's head to #200 before 2g ran. + const sandbox = setupSandbox('100'); + try { + const queuePath = path.join(sandbox, '.codegraph/fixer/queue.json'); + const queue = JSON.parse(fs.readFileSync(queuePath, 'utf-8')); + // Simulate the shift: #100 already got dispatched, and something else + // moved the head past it while this dispatch was still in progress. + fs.writeFileSync(queuePath, JSON.stringify(queue.slice(1))); + + const result = runBlock(block, sandbox); + expect(result.exitCode).not.toBe(0); + + // state.json must NOT have gained a bogus record for #200. + const state = JSON.parse( + fs.readFileSync(path.join(sandbox, '.codegraph/fixer/state.json'), 'utf-8'), + ); + expect(state.issues).toEqual([]); + + // queue.json must still have #200 at its head — not shifted again. + const finalQueue = JSON.parse(fs.readFileSync(queuePath, 'utf-8')); + expect(finalQueue).toEqual([{ issue: 200, title: 'second' }]); + } finally { + fs.rmSync(sandbox, { recursive: true, force: true }); + } + }); + + it("records normally when dispatching-issue matches queue.json's head", () => { + const sandbox = setupSandbox('100'); + try { + const result = runBlock(block, sandbox); + expect(result.exitCode).toBe(0); + + const state = JSON.parse( + fs.readFileSync(path.join(sandbox, '.codegraph/fixer/state.json'), 'utf-8'), + ); + expect(state.issues).toEqual([{ issue: 100, status: 'merged', pr: 999 }]); + + const queue = JSON.parse( + fs.readFileSync(path.join(sandbox, '.codegraph/fixer/queue.json'), 'utf-8'), + ); + expect(queue).toEqual([{ issue: 200, title: 'second' }]); + } finally { + fs.rmSync(sandbox, { recursive: true, force: true }); + } + }); + + it('records normally when dispatching-issue is absent (defensive: guard is opt-in, not required)', () => { + const sandbox = setupSandbox(null); + try { + const result = runBlock(block, sandbox); + expect(result.exitCode).toBe(0); + + const state = JSON.parse( + fs.readFileSync(path.join(sandbox, '.codegraph/fixer/state.json'), 'utf-8'), + ); + expect(state.issues).toEqual([{ issue: 100, status: 'merged', pr: 999 }]); + } finally { + fs.rmSync(sandbox, { recursive: true, force: true }); + } + }); +}); From 11d15538881bb568f8691a059b160e1a26f3fd62 Mon Sep 17 00:00:00 2001 From: carlos-alm Date: Tue, 11 Aug 2026 10:02:04 -0600 Subject: [PATCH 2/2] fix(skills): close TOCTOU gap between 2g's head check and its queue shift Greptile review on PR #2467: the moved-queue-head guard and the later queue.json shift were two separate reads of the file, with the state.json write happening in between. A writer that moved the head during that window would pass the guard, then have the unconditional `.[1:]` drop whatever untouched issue was now at the head instead of the one whose outcome was just recorded. The shift step now re-validates the head in the same jq invocation that performs the shift, collapsing the check-then-mutate gap to the same single-read-then-atomic-rename pattern already used for every other queue.json/state.json write in this skill. --- .claude/skills/fixer/SKILL.md | 20 +++++-- .../fixer-skill-2g-queue-guard-2304.test.ts | 54 +++++++++++++++++++ 2 files changed, 69 insertions(+), 5 deletions(-) diff --git a/.claude/skills/fixer/SKILL.md b/.claude/skills/fixer/SKILL.md index 0e744421e..2b3dff92b 100644 --- a/.claude/skills/fixer/SKILL.md +++ b/.claude/skills/fixer/SKILL.md @@ -1148,11 +1148,21 @@ fi TMP_QUEUE=$(mktemp "${TMPDIR:-/tmp}/fixer-queue.XXXXXXXXXX") trap 'rm -f "$TMP_QUEUE"' EXIT -# Guarded the same way: if this fails after state.json already succeeded above, -# queue.json[0] is still this (already-resolved) issue — exactly the case Phase 2's -# own resume-detection note (above step 2a) already filters out on the next run. -if ! jq '.[1:]' .codegraph/fixer/queue.json > "$TMP_QUEUE"; then - echo "ERROR: failed to build updated queue.json — issue #$ISSUE was already recorded as $STATUS in state.json. The next run's resume-detection will filter this already-resolved queue head." +# Re-validate the head in the same jq invocation that performs the shift +# (Greptile review, PR #2467): the moved-queue-head guard above and this +# shift are two separate reads of queue.json, with the state.json write +# happening in between — a writer that moves the head during that window +# would otherwise make this unconditional `.[1:]` drop whatever untouched +# issue is now at the head instead of the one whose outcome was just +# recorded. Checking identity and shifting in one jq call collapses that +# gap to the same single-read-then-atomic-rename pattern already used for +# every other queue.json/state.json write in this skill. +if ! jq --argjson issue "$ISSUE" ' + if (.[0].issue // null) == $issue then .[1:] + else error("queue.json head changed to \(.[0].issue // "empty") — expected #\($issue)") + end + ' .codegraph/fixer/queue.json > "$TMP_QUEUE"; then + echo "ERROR: failed to build updated queue.json for issue #$ISSUE — either the write itself failed, or the queue's head moved away from #$ISSUE between recording the outcome and shifting the queue (see the jq error above). Issue #$ISSUE was already recorded as $STATUS in state.json — investigate queue.json before proceeding rather than retrying blind." exit 1 fi if ! mv "$TMP_QUEUE" .codegraph/fixer/queue.json; then diff --git a/tests/unit/fixer-skill-2g-queue-guard-2304.test.ts b/tests/unit/fixer-skill-2g-queue-guard-2304.test.ts index e63355998..2242d18a8 100644 --- a/tests/unit/fixer-skill-2g-queue-guard-2304.test.ts +++ b/tests/unit/fixer-skill-2g-queue-guard-2304.test.ts @@ -44,6 +44,23 @@ function extractBashBlockAfterHeading(markdown: string, heading: string): string return rest.slice(bodyStart, fenceEnd); } +/** Extract the jq program passed to `jq --argjson issue "$ISSUE" '...'` in 2g's queue-shift step. */ +function extractQueueShiftJqProgram(block: string): string { + const marker = 'jq --argjson issue "$ISSUE" \''; + const start = block.indexOf(marker); + if (start === -1) { + throw new Error('Queue-shift jq invocation not found in 2g block'); + } + const programStart = start + marker.length; + // The program body contains only double quotes, so the next single quote + // is reliably the one closing bash's single-quoted argument. + const programEnd = block.indexOf("'", programStart); + if (programEnd === -1) { + throw new Error('Unterminated jq program in queue-shift step'); + } + return block.slice(programStart, programEnd); +} + function runBlock( block: string, sandbox: string, @@ -149,4 +166,41 @@ describe('fixer skill 2g moved-queue-head guard (#2304)', () => { fs.rmSync(sandbox, { recursive: true, force: true }); } }); + + it("the queue-shift step's own jq check refuses to shift when the head no longer matches (Greptile review, PR #2467)", () => { + // The full 2g block can't deterministically reproduce a write landing + // strictly between its own two reads of queue.json — that gap exists for + // an external, concurrent writer during real wall-clock execution, not + // something one synchronous script invocation can race against itself. + // This verifies the shift step's own jq program directly: given a + // queue.json whose head no longer matches the issue being recorded, it + // must refuse to shift rather than silently dropping whatever is there. + const jqProgram = extractQueueShiftJqProgram(block); + const sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'fixer-2g-shift-')); + try { + const queuePath = path.join(sandbox, 'queue.json'); + fs.writeFileSync(queuePath, JSON.stringify([{ issue: 999, title: 'moved' }])); + + expect(() => + execFileSync('jq', ['--argjson', 'issue', '100', jqProgram, queuePath], { + encoding: 'utf8', + }), + ).toThrow(); + + // And it still shifts normally when the head does match. + fs.writeFileSync( + queuePath, + JSON.stringify([ + { issue: 100, title: 'first' }, + { issue: 200, title: 'second' }, + ]), + ); + const shifted = execFileSync('jq', ['--argjson', 'issue', '100', jqProgram, queuePath], { + encoding: 'utf8', + }); + expect(JSON.parse(shifted)).toEqual([{ issue: 200, title: 'second' }]); + } finally { + fs.rmSync(sandbox, { recursive: true, force: true }); + } + }); });