Skip to content

refactor(platform): every gh call goes through PlatformProvider; FakeGitHubProvider replays captured gh output so no test fakes gh through child_process #1506

Closed

Description

@admarble

Epic: graph-2026-10-fundamentals Tier: judgment Execution: sequant_run Blocked by: #1504

Problem

The fix-seam audit (59 merged fixes, 28 days) found the one seam tested through mocks is subprocess: 3 of 4 subprocess defects were tested by mocking child_process, and two logic fixes used hand-typed fixtures of gh's output shape (#1229, #1214) — the failure "don't mock types you don't own" names: the fixture drifts, the test stays green, the code is wrong. 31 test files mock child_process; 6 of them fake gh inside the mock. GitHubProvider already owns 27 gh call sites, but 4 remain outside it: batch-executor.ts (gh issue view --json title,labels at :328 and --json body,labels at :388), chain-preflight.ts (gh issue view --json body,state,title at :207), merge-check/report.ts (gh pr comment at :314). All four are expressible through the existing PlatformProvider interface (fetchIssue, postPRComment).

Design: consumers take an optional provider?: PlatformProvider defaulting to new GitHubProvider() (D-D: no module-level test setter). FakeGitHubProvider implements the interface by replaying JSON fixtures under src/lib/workflow/platforms/__fixtures__/gh/, each produced by scripts/capture-gh-fixtures.ts, which runs the real gh and stamps command, capturedAt, exitCode, stdout, stderr (D-G). A fixture with exitCode != 0 makes the fake throw the same error class GitHubProvider throws, so the gh-exit-status seam the audit flagged (#1319, #1320, #1464, #1268) is testable without child_process.

Acceptance Criteria

  • AC-1: No gh spawn outside the provider. Evidence: grep -rlzE 'spawnSync\(\s*"gh"' src --include='*.ts' --exclude='*.test.ts' | grep -v 'platforms/github.ts' | wc -l | tr -d ' ' → 0
  • AC-2: Captured fixtures exist and carry provenance. Evidence: n=$(ls src/lib/workflow/platforms/__fixtures__/gh/*.json | wc -l | tr -d ' '); for f in src/lib/workflow/platforms/__fixtures__/gh/*.json; do jq -e '.command and .capturedAt and (.exitCode != null)' "$f" > /dev/null || echo "bad $f"; done; echo "fixtures=$n" → fixtures=≥ 4 and no bad line
  • AC-3: The fake implements the whole interface and surfaces non-zero exits as the provider's error class. Evidence: npx vitest run src/lib/workflow/platforms/fake-github.test.ts → ≥ 4 passed, 0 failed (new file: every PlatformProvider method resolves from a fixture; an exitCode: 1 fixture throws the same class as GitHubProvider; an unknown command throws a fixture-missing error naming the capture script)
  • AC-4: No test fakes gh through child_process. Evidence: grep -rlE 'vi\.mock\(\s*["'"'"'](node:)?child_process' src scripts __tests__ 2>/dev/null | xargs grep -l '"gh"' | wc -l | tr -d ' ' → 0
  • AC-5: The capture script exists and runs real gh. Evidence: test -f scripts/capture-gh-fixtures.ts && grep -c 'spawnSync' scripts/capture-gh-fixtures.ts → ≥ 1
  • AC-6: Existing behaviour holds, including the integration test against real gh. Evidence: npx vitest run src/lib/workflow/platforms/ src/lib/workflow/chain-preflight.test.ts src/lib/merge-check/ → 0 failed (must run against the real dependency: github.integration.test.ts stays unmocked)
  • AC-7: The baseline moves down with the PR. Evidence: jq '.ghCallFilesOutsideProvider' scripts/qa/health-baseline.json → 0
  • AC-2, AC-3 and AC-5 are classified as gate tests by isGateTestEvidence; the PR body carries a SEQUANT_MUTATION record for each (delete one fixture → the fake's test for that method fails; restore).

Prior fixes / producers

May touch

src/lib/workflow/platforms/{github.ts,platform-provider.ts,fake-github.ts (new),fake-github.test.ts (new),__fixtures__/gh/ (new)}, scripts/capture-gh-fixtures.ts (new), src/lib/workflow/batch-executor.ts (the two helpers at :328/:388 and their callers' optional parameter only), src/lib/workflow/chain-preflight.ts, src/lib/merge-check/report.ts, the 6 test files that fake gh, scripts/qa/health-baseline.json (I-4), CHANGELOG entry.

Non-Goals

  • A git wrapper or fake (git is tested against real repos in 80 files).
  • Removing child_process mocks that fake git, codex, opencode or claude (they are not the audited seam).
  • Any PlatformProvider method beyond what the four call sites need.
  • No edits under plugin/, .claude/skills/, templates/skills/ (I-1).

Done when

A gh failure in a test is a fixture, not a shifted mock queue, and grep finds no gh spawn outside the provider.

Activity

  1. added
    graph-2026-10-fundamentals
    on Oct 18, 2026
  2. admarble commented on Oct 20, 2026

    @admarble
    ContributorAuthor

    Runner context, 2026-10-20, before launch (fundamentals W2; stop-at-PR; judgment tier, all phases on Opus). main = 2e041f0.

    Changed since filing:

    Safety for the fixture capture (AC-2, AC-5):

    • Capture only read-only gh calls (issue view, pr view, api GETs) against sequant-io/sequant.
    • Never run a writing call (issue comment, pr create, pr merge, label, api -X POST/PATCH/DELETE), not even to capture a fixture. Hand-write fixtures for write paths from the documented response shape and mark them "provenance": "hand-written".

    #1505 (empty catches, including platforms/github.ts) is held until this merges.

    For every phase, and the qa phase by name: run the full suite at most once, in the foreground, under timeout, after a WIP commit. Each MCP-dispatched phase has a 30-minute wall. Prefer the targeted npx vitest run <files> for the ACs.
    CHANGELOG: add [Unreleased] lines under the existing ### Added / ### Changed headings, not changelog.d/ fragments, and never add a second heading of the same name.
    Lint: #1503 made no-unused-vars, no-empty-object-type and prefer-const errors, and knip counts unused exports. Don't export what nothing imports.
    Health baseline: regenerate scripts/qa/health-baseline.json (npx tsx scripts/qa/health-report.ts --write-baseline) only to record a metric that went down. If npm run lint:health reports a rise, restructure so it holds. Otherwise leave the baseline alone and name the rise in the PR body. Owner ruling: a proseGate.lines rise caused by tests in files that mention SKILL.md only as a path may be absorbed, and must be said so.
    Freeze: nothing under plugin/, .claude/skills/ or templates/skills/.

  3. admarble commented on Oct 20, 2026

    @admarble
    ContributorAuthor

    Complexity: Complex (7 ACs, 8 directories)

    AC Quality Check

    lintAcceptanceCriteria: 7/7 pass. Every AC declares Evidence:. I ran each command-shaped Evidence against main @ 2e041f0:

    AC On main Gates?
    AC-1 3 (batch-executor, chain-preflight, merge-check/report) ✅ fails today
    AC-2 no __fixtures__/gh/ ✅
    AC-3 file missing ✅
    AC-4 6 (system, state-utils, github, run, doctor, run-resume) ✅, but see ⚠️ below
    AC-5 script missing ✅
    AC-6 passes today regression guard (intended)
    AC-7 3 ✅

    ⚠️ AC-4's grep is both too wide and too narrow.

    • False positives: system.test.ts has "gh" only as the commandExists("gh") / getInstallHint("gh") argument. That is the which probe the issue exempts at wizard.ts:41, not a gh fake.
    • False negatives: get-issue-info.test.ts, dependency-markers.test.ts and github-gh-failure.test.ts fake gh output through vi.mock("child_process") but never write the literal "gh", so the grep misses them.

    The first two of those test the consumers this issue rewires, and the third is the core of "a gh failure is a fixture". All three are converted below. The literal AC still holds.

    ⚠️ AC-5 and AC-7 conflict as written. health-report.ts:249 scans scripts/ too (/^(src|bin|scripts)\//). A scripts/capture-gh-fixtures.ts that calls spawnSync("gh"…) (which AC-5 requires) makes ghCallFilesOutsideProvider = 1, not 0 (AC-7). See Open Question 1.


    Scope Assessment

    Non-Goals: present (no git fake; non-gh child_process mocks stay; no extra PlatformProvider methods; no plugin/skills edits).

    Metric Value Status
    Feature count 1 (provider seam + fake) ✅
    AC items 7 ✅
    Directory spread 8 ⚠️
    Test lines touched ~9 files, gh-faking parts of run (2812), doctor (1791), state-utils (1250), github (652) ⚠️

    Verdict: ⚠️ SCOPE_WARNING. One coherent change, but it converts a lot of tests. The quality loop is on.


    Acceptance Criteria

    AC-1: No gh spawn outside the provider

    Verification: Integration Test (Evidence grep)
    Scenario: Given the 4 sites → When rewired to provider methods → Then the grep prints 0
    Assumptions: parseDependencies stays sync. Its caller chain is sortByDependencies → RunOrchestrator.resolveConfig (sync, static) → run.ts:104, and run.ts is outside "May touch". So that site needs a sync provider method (Open Question 2).

    AC-2: Fixtures exist with provenance

    Verification: Integration Test
    Scenario: Given the capture script has run → Then ≥ 4 JSON files exist, each with command, capturedAt, exitCode, stdout, stderr and provenance ("captured" | "hand-written")
    Assumptions: Write paths (issue comment, issue edit --add/remove-label, pr create, pr comment) are hand-written per the runner comment and carry "provenance": "hand-written". Gate test: needs a SEQUANT_MUTATION record.

    AC-3: Fake implements the whole interface; non-zero exit → provider's error class

    Verification: Unit Test (fake-github.test.ts)
    Scenario: Each of the 9 PlatformProvider methods resolves from a fixture. An exitCode: 1 fixture rejects with the GitHubProvider error class. An unknown argv throws GhFixtureMissingError, whose message names scripts/capture-gh-fixtures.ts.
    Assumptions: ⚠️ There is no provider error class today. runGhOrThrow (github.ts:111) throws a plain Error, and fetchIssue (github.ts:987) throws Failed to fetch issue N with stderr dropped. So this AC requires introducing GhCommandError extends Error { args, exitCode, signal, stderr }. Gate test: needs a mutation record.

    AC-4: No test fakes gh through child_process

    Verification: Integration Test (Evidence grep) + review of the 3 grep-invisible files
    Scenario: The gh-faking parts of the 6 grep hits and the 3 grep-invisible files use FakeGitHubProvider → grep 0

    AC-5: Capture script exists and runs real gh

    Verification: Integration Test. Gate test, needs a mutation record.
    Assumptions: Read-only calls only, against sequant-io/sequant. The script refuses any argv whose verb is in a write denylist (comment, create, merge, edit, close, label, api -X/--method other than GET), so a write cannot be captured by accident.

    AC-6: Existing behaviour holds; github.integration.test.ts stays unmocked

    Verification: Integration Test

    AC-7: ghCallFilesOutsideProvider → 0

    Verification: Integration Test. Regenerate the baseline (the metric goes down; that is allowed).


    Implementation Plan

    Phase 1: One gh seam inside GitHubProvider (github.ts)

    1. Add type GhRunner = (args: string[], opts?: {input?: string; timeout?: number}) => GhRunResult, where GhRunResult is {status, stdout, stderr, signal, error}. The default implementation is the only spawnSync("gh", …) in the file. Route all ~27 spawnSync("gh") sites and execSync("gh auth status") (:208) through this.run. The constructor takes { run?: GhRunner } (constructor injection, not a module setter, which satisfies D-D).
    2. Add export class GhCommandError. runGhOrThrow throws it. fetchIssue goes through it too, so stderr survives. Without that, getIssueInfo loses fix(doctor/run): doctor and run --dry-run report success when nothing would work #1257 notFound and the fix(worktree): an existing branch for issue N is reused whatever the title — a gh blip or a retitle cuts feature/N-issue-n from main and QA reviews main #1487 reason when migrated. Sibling scan: the other if (result.status !== 0) return null/[] sync helpers keep their tolerant contract. Do not widen to them (chore(lib): convert the remaining ~94 empty catches to noteSuppressed, forbid empty catch bodies by lint, show the count in sequant logs #1505 owns that file's catches next).
    3. Add fetchIssueSync(id): Issue (a GitHubProvider helper, not added to PlatformProvider). fetchIssue becomes async around it.

    Phase 2: Fixtures + fake (platforms/)

    1. Add gh-fixtures.ts: fixture type, loader for __fixtures__/gh/*.json, fixtureRunner(fixtures) (exact-argv match; a "<*>" token matches any value, needed for --body), and GhFixtureMissingError. This module does not import github.ts, so tests can vi.mock("…/github.js") without a cycle.
    2. fake-github.ts: class FakeGitHubProvider extends GitHubProvider, which calls super({ run: fixtureRunner([...defaults, ...extra]) }). Because it is the real class with a replay runner, every interface method and every sync helper uses the production parsing and throws the production error. That is what "same error class" means here.
    3. scripts/capture-gh-fixtures.ts: a list of read-only argv. It runs real gh and writes {command, args, capturedAt, exitCode, stdout, stderr, provenance:"captured"}. Capture at least: issue view <n> --json number,title,body,labels,state; issue view <n> --json comments --jq …; pr view <n> --json state,mergedAt; one not-found (issue view 999999, exitCode 1); and auth status (exit code only, stdout/stderr scrubbed). Then hand-write the 5 write-path fixtures. Security: fixtures ship in a public repo, so capture only public sequant-io/sequant data and scrub token/host lines from auth status.
    4. fake-github.test.ts: 9 interface methods + exitCode-1 → GhCommandError + missing → GhFixtureMissingError.

    Phase 3: Rewire the 4 consumers (provider? defaulting to new GitHubProvider())

    1. getIssueInfo(n, provider?: PlatformProvider) uses fetchIssue. Not-found = err instanceof GhCommandError && ISSUE_NOT_FOUND_RE.test(err.stderr). parseDependencies(n, provider?: GitHubProvider) uses fetchIssueSync. sortByDependencies passes it through as optional. Do not grow runIssueWithLogging.
    2. chain-preflight.ts: fetchPreflightIssue(n, provider) becomes async, and runChainPreflight(order, provider?) awaits it. Map Issue.state lowercase → the existing state string comparisons (check computePreflightWarnings for "CLOSED" vs "closed").
    3. merge-check/report.ts: postReportToGitHub(report, provider?) becomes async over postPRComment. index.ts:329 awaits it. Keep the never-empty reason (fix(merge-check): combined-branch-test runs npm test/build without reinstalling deps after a lockfile change → false BLOCKED #803): use the error message, falling back to exit N.

    Phase 4: Convert tests (only the gh-faking parts)

    1. github.test.ts, github-gh-failure.test.ts: construct FakeGitHubProvider / new GitHubProvider({run}). Failure cases become fixtures. Timeout and ENOENT are hand-written fixtures with signal/error.
    2. get-issue-info.test.ts, dependency-markers.test.ts, merge-check report tests: pass a fake.
    3. run.test.ts, doctor.test.ts, state-utils.test.ts, run-resume.test.ts: their sources construct GitHubProvider internally and are outside "May touch". Use vi.mock("…/platforms/github.js", async (orig) => ({...await orig(), GitHubProvider: <subclass of orig's class with fixtureRunner>})). That mocks a type we own, which is what the issue's principle allows. Remove the cmd === "gh" branches. Their child_process mocks for git and other tools stay (Non-Goal).
    4. system.test.ts: move the getInstallHint cases (a pure table lookup) to a test without the child_process mock. The commandExists cases test which generically and use a non-gh name. Say in the PR body that this was a grep false positive, not a gh fake.

    Phase 5: Close-out

    1. Health baseline (AC-7), CHANGELOG ### Changed line, ADR, and a merge of origin/main (PR chore(#1510): every @deprecated names its removal version — lint:deprecations in CI, CONTRIBUTING rule #1568 touches batch-executor.ts, health-baseline.json and CHANGELOG.md, so expect conflicts there). PR body: the 3 mutation records and the test(workflow): the #533 label-shortcut tests take ~850 ms with every phase mocked — one hit 5785 ms on CI and turned main red at da9c4fd49 #1560 leak answer for run-orchestrator.test.ts / skills-preflight.test.ts.

    Design Review

    1. Where does it belong? platforms/github.ts owns every gh spawn. The fake lives beside it. Consumers only receive a provider.
    2. Simplest correct approach: a runner seam + a fake subclass. Rejected: a standalone FakeGitHubProvider implements PlatformProvider (the issue's literal wording). It would cover only the 9 interface methods, but the 6 test files exercise sync helpers (fetchIssueCommentBodiesSync, listClosedIssuesSync, getPRMergeStatusSync, createPRCliSync…). It would also re-implement parsing, which brings back the hand-typed-shape drift this issue exists to remove. ADR required in docs/adr/ (next NNNN).
    3. Pattern / re-patch count: the gh exit-status seam has been fixed 4× (fix(#1312): GitHubProvider.postComment ignores gh's exit status, so a failed QA verdict post is silent #1319, fix(#1315): PlatformProvider has no error contract — postPRComment is still unchecked and the ready gate's report-post catch is empty (#1312 follow-up) #1320, fix(#1396): phase agents no longer receive claude.ai connectors #1464, fix(#1257): doctor warns on a missing GitHub remote and uncommitted core skills; dry run errors on a missing issue #1268), plus bug(run): GitHubProvider.postComment ignores gh's exit status, so a failed QA verdict post is silent #1312, fix(platforms): PlatformProvider has no error contract — postPRComment is still unchecked and the ready gate's report-post catch is empty (#1312 follow-up) #1315 and fix(doctor/run): doctor and run --dry-run report success when nothing would work #1257/fix(worktree): an existing branch for issue N is reused whatever the title — a gh blip or a retitle cuts feature/N-issue-n from main and QA reviews main #1487 on the same lines. That is a class, and this plan fixes the class: one spawn site, one error type, with failures as fixtures. Not a divergence.
    4. Senior pushback: "Why not make sortByDependencies async?" Because it ripples into the sync resolveConfig and run.ts. "Isn't vi.mock of github.js the mock queue again?" No. It substitutes our own class, and the gh shape still comes from captured fixtures.
    5. Producers/consumers:
      • gh spawns, after the change: GitHubProvider's default runner and capture-gh-fixtures.ts. That is 2 producers, by design: the script records exactly what the runner sees. Parity: the script calls the runner with the same spawn options, or the same options are exported as a constant (the exec phase picks one and records it).
      • Fixture consumers: fixtureRunner only.
      • GhCommandError consumers: getIssueInfo, postReportToGitHub, postQaVerdictComment (already catches Error, unaffected).

    Feature Quality Planning

    Standard checks pass. Notable:

    Derived ACs

    Source Derived AC Priority
    Error paths AC-8: getIssueInfo with a not-found fixture → notFound: true; with a 502 fixture → error contains gh's stderr (get-issue-info.test.ts) High
    Safety AC-9: the capture script refuses a write argv (unit test of the denylist) Medium

    Open Questions

    1. AC-5 vs AC-7. Recommendation: exempt the capture script by name in health-report.ts (a GH_CAPTURE_SCRIPT constant next to GH_PROVIDER), so both ACs hold literally. A const GH = "gh" dodge would game the regex and should not be used. Impact if wrong: AC-7 reads 1, or the owner rewrites AC-5's evidence.
    2. parseDependencies takes a GitHubProvider, not a PlatformProvider, because it needs fetchIssueSync. Recommendation: accept that. The alternative is async resolveConfig, which edits run.ts. Impact: one consumer's parameter type differs from the issue's design sentence.
    3. Test-specific gh data (doctor's closed issues, state-utils' PR states). Recommendation: a deriveFixture(captured, mutateJson) helper that starts from a captured fixture and records derivedFrom, so the shape stays real. Purely invented stdout is not allowed.
    4. system.test.ts is a grep false positive (see AC-4). Recommendation: the split described in step 14, disclosed in the PR body.

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: enabled
    Reasoning: A complex refactor with SCOPE_WARNING across 8 directories. The new test file is the AC-3 deliverable, so testgen stubs add nothing. No UI.

    Label Review

    Current: graph-2026-10-fundamentals
    Recommended: + refactor, planned
    Reason: The title is a refactor, and it is a class fix across the provider seam.

  4. added
    planned
    on Oct 20, 2026
  5. admarble commented on Oct 20, 2026

    @admarble
    ContributorAuthor

    Runner note, 2026-10-20: the first run was killed by the MCP server's 30-minute no-progress watchdog during exec. Its work is committed on the branch through ea680c9 (provider runner seam, fixtures, fake, consumers rewired, ADR-0019, the capture-script probe and the failure fixtures), and the tree is clean.

    For the re-run of exec:

    1. Run this issue's AC Evidence commands first, to see what is left.
    2. Finish only that.
    3. Commit at least every 10 minutes. A phase with no commit or boundary for 30 minutes is killed again.

    The suite rule from the context comment still applies: run it once, in the foreground, under timeout.

  6. admarble commented on Oct 20, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_NOT_MET

    AC coverage: 7/7 met

    Gaps:

    • capture-gh-fixtures.ts writes gh stdout verbatim, committing a real Claude session URL; add redaction of session_/cse_ ids and re-capture the fixture
    • health-baseline.json was not regenerated after the last commit
    • Fixing HEAD does not clear Gitleaks; needs a branch history rewrite (user force-push) or an owner-approved .gitleaksignore entry for an already-public URL
    • Required test check has not reported yet
  7. admarble commented on Oct 21, 2026

    @admarble
    ContributorAuthor

    Security Review: one gh provider, fake GitHub, captured fixtures (#1506)

    PRs: #1570 (closed, superseded) → #1576
    Domains: Data protection, Infrastructure (secrets)
    Risk level: Medium, now remediated
    Files reviewed: 35 fixtures, scripts/capture-gh-fixtures.ts, platforms/github.ts, fake-github.ts, main's tree, and the repo's issue comments and PR bodies

    Threat model

    • Attack surface: real gh output, written verbatim into committed fixtures in a public repo; a capture script that runs gh with the maintainer's credentials; a runner seam that selects real or replayed gh.
    • Threat actors: public readers of the repo and its PR history; a future editor of the capture list.
    • Primary attack vectors: secrets or personal data in captured output; a capture that writes to GitHub; the fake provider being switched on in production.

    Findings

    Medium (remediated)

    1. A captured fixture carried a real Claude session link (__fixtures__/gh/pr-view-by-branch.json on refactor(#1506): every gh call goes through PlatformProvider; FakeGitHubProvider replays captured gh output so no test fakes gh through child_process #1570's branch).

    Low (remediated)

    1. The capture script's read-only guard was a deny list (scripts/capture-gh-fixtures.ts).
      • It missed attached short flags (-XPOST, -fkey=v, -Fkey=v) and writing verbs such as run, rerun, cancel, set and fork.
      • It is now an allowlist: only reading verbs, --version, and api calls with no method or body flag; api graphql is refused.
      • Exposure was limited because only the fixed CAPTURES list runs.

    Checked and passed

    • The fake provider is selected only by constructor injection. No environment variable switches it, and no production code constructs it.
    • auth status output is scrubbed.
    • No home paths, emails or tokens appear in any fixture, in the current tree or in branch history.
    • Write-path fixtures are hand-written.
    • main holds no real session link in tracked files.

    Checklist status

    Domain Passed Failed Manual Total
    Authentication 0 0 0 8 (N/A)
    Authorization 0 0 0 6 (N/A)
    API Security 1 0 0 7
    Data Protection 3 0 1 5
    Infrastructure 2 0 0 5

    The manual Data Protection item is whether a session link is viewable without a login. A no-cookie request was challenged by Cloudflare, so it is unconfirmed.

    Verdict

    WARNINGS. Both findings are fixed in #1576, and both fixes are mutation-verified. The residual exposure is old commits on GitHub, which only GitHub support can purge.


    🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    graph-2026-10-fundamentalsplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions