Skip to content

fix(security-worker): don't fail shards when a scan workspace can't be deleted - #4819

Merged
jesse-merhi merged 4 commits into
mainfrom
fix/security-scan-workspace-cleanup
Nov 17, 2026
Merged

jesse-merhi merged 4 commits into
mainfrom
fix/security-scan-workspace-cleanup

Conversation

@jesse-merhi

@jesse-merhi jesse-merhi commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Summary

Since #4803 and #4805 merged, no Codex scan shard has failed because of claim errors. The one claim Server Error after the merge recovered on retry, as intended. Most remaining shard failures with a log are this bug: about 1–2 an hour, going back to at least 2026-11-16.

Production repro: Production run 43994280032, job 133742337590 (priority-0), 2026-11-17 01:37 UTC:

security_scan_job_completed  jobId=v570zjy2… status=clean targetKind=packageRelease
security_scan_unhandled_process_failure  EACCES: permission denied, rm '/tmp/clawhub-codex-scan-v570zjy2…-nuSLm5'
security_scan_worker_summary  totalClaimed=4 totalCompleted=3 totalFailed=1
##[error]Process completed with exit code 1.

The same sequence appears in runs 43986255864 (shared-7), 43992281182 (priority-0) and 43994280032 (shared-8).

Cause: Docker-sandboxed scans leave root-owned files in the bind-mounted workspace. The bare rm in processJob's finally then throws after the job outcome is recorded. A throw from finally replaces processJob's result. The pool logs an unhandled failure and sets workerMustStop, so the shard stops claiming and exits 1 even though the scans finished.

Fix: deletion moves into removeScanWorkspace. It logs security_scan_workspace_cleanup_failed with the errno code only (no path or message) and never replaces processJob's result or error. The custody path is unchanged: when container removal isn't confirmed, the worker still preserves the workspace and stops. The behaviour, and the accepted leftover files, are recorded in a new "Scan workspace cleanup" section in specs/plugin-qualified-runtime.md.

Not in this PR:

  • The prepublication worker has the same bare rm in its finally (scripts/security/run-prepublication-worker.ts). Follow-up.
  • Some shards end with The runner has received a shutdown signal (exit 143/137). That started before these changes and is being investigated separately.

Tests and review

  • Regression test: it runs the real processJob, then locks a subdirectory of its workspace after the outcome is recorded. It asserts the completed result and the logged errno code, and that the path isn't logged. With the old bare rm put back, it fails with the same EACCES rejection seen in production.
  • End-to-end CLI proof (trace and sources): the unmodified bun scripts/security/run-codex-scan-worker.ts entry point runs on Linux with Bun 1.4.4 against a fake Convex HTTP deployment, with 5 jobs, two of them permission-locked. Main's worker exits 1 after 3 claims. The PR's worker claims and completes all 5 and exits 0.
  • Linux + Bun 1.4.4 proof (trace, setup and probe source): the real worker pool runs as non-root in oven/bun:1.4.4 with 5 jobs, two of them permission-locked.
    • Before (main's worker): the cleanup error escapes, claims stop, and it ends with totalClaimed 3, totalFailed 1.
    • After: each locked job logs security_scan_workspace_cleanup_failed code=EACCES, later jobs are still claimed and completed, and it ends with totalCompleted 5, totalFailed 0. Only the locked subtree is left behind.
  • bunx vitest run scripts/security/run-codex-scan-worker.test.ts: 41 passed.
  • bun run ci:static and bunx tsc -p tsconfig.json --noEmit: passed.
  • bun run coverage: failed locally. Subprocess-heavy scanner suites failed with spawnSync python3 ETIMEDOUT and 15 s timeouts. Rerun alone, 8 tests in 4 files still failed. With this change reverted, 4 tests in 2 of those files still failed, and the set changed between runs. None of those suites touch the changed code. CI unit is the full run.
  • Code review council (GPT-6 Astra, GPT-6.1 Sol, Claude Fable 5.2 and Claude Opus 5.5, high effort) on 2434893a: no blocking findings, all four high confidence. The minor findings were wording, spec placement and the test's errno assertion; 7ef546f1 fixes them.

@vercel

vercel Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
clawhub Ready Ready Preview Nov 17, 2026 3:10am UTC

Request Review

Copilot AI balanced review requested due to automatic review settings November 17, 2026 02:43
@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

Make removeScanWorkspace private and drop its test-only return value.
Prove the fix through processJob's recorded result instead of the helper,
narrow the errno code without a cast, and tighten the spec note.
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 17, 2026
@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR makes scan-workspace deletion best effort so permission errors do not replace job outcomes or stop subsequent claims.

Example: A five-job worker queue encounters undeletable workspace subdirectories for jobs 2 and 5.

  • Before: The CLI claims three jobs, records one unhandled failure, and exits 1.
  • After: The CLI completes all five jobs, logs cleanup warnings without paths, and exits 0.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, validated fix with shipped-entry-point proof and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The supplied before/after trace runs the unmodified worker CLI as non-root on Linux with Bun 1.4.4, using a fake Convex HTTP service to inject real EACCES failures after completion; the candidate continues claiming, completes five jobs, and exits 0.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Completed scans can cause their shard to exit as failed and stop processing queued work because temporary files cannot be deleted.
Reason: The narrow fix preserves recorded outcomes and existing custody safeguards; the maintainer-authored PR explicitly accepts temporary residue, with prepublication cleanup disclosed as separate work.

Merge readiness

✅ Ready for maintainer review

No blocking findings. This maintainer-authored PR fixes a current-main shard failure while preserving container-custody safeguards, and the supplied CLI proof exercises the changed behavior successfully.

Priority: P2
Reviewed head: f5149d6e16587638b7524a517275fe4ca3a0bd1e

Before merge

None.

Findings

None.

Agent review details

How this fits together

The security worker claims backend scan jobs, processes artifacts, records outcomes, and removes temporary workspaces before accepting more work.

flowchart TD
  A[Convex job queue] --> B[Worker CLI and pool]
  B --> C[Process scan job]
  C --> D[Record job outcome]
  D --> E[Workspace cleanup]
  E --> F[Continue claiming]
  C --> G[Unconfirmed container removal]
  G --> H[Preserve workspace and stop]
Loading

Technical review

Best possible solution:

Land the focused outcome-preserving cleanup change with its regression test and explicit residue policy.

Do we have a high-confidence way to reproduce the issue?

Current-main source establishes the failing finally-to-pool path, supported by the contributor's production excerpt and paired Linux CLI trace; no target code was executed during this review.

Is this the best way to solve the issue?

Best-fix verdict: best for preserving shard outcomes; catching at the pool would lose the recorded result, while privileged deletion would add machinery beyond the accepted residue policy, and the inspected CLI, processJob, logger, custody branch, qualification helper, and sibling prepublication worker support this boundary.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4fff91800b08.

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Patrick Erichsen: Raw commit 560125d adds scripts/security/run-codex-scan-worker.ts:2651 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 560125d8ef84; files: scripts/security/run-codex-scan-worker.ts)
  • Jesse Merhi: Raw commit 2deb1b7 adds scripts/security/run-codex-scan-worker.ts:1146 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2deb1b75e997; files: scripts/security/run-codex-scan-worker.ts)
  • Peter Steinberger: Raw commit 35aa372 adds scripts/security/run-codex-scan-worker.ts:275 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 35aa372b24a3; files: scripts/security/run-codex-scan-worker.ts)

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Change size Production +20/-1; tests +59/-2; spec +15 The added regression exercises processJob with a real filesystem permission failure; production growth stays confined to cleanup error handling.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Cleanup permission failures prematurely stop scan shards, reducing queue throughput while recorded scan outcomes remain intact.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (3 earlier review cycles)
  • reviewed 2026-11-17T03:04:30.713Z sha 7ef546f :: needs maintainer review before merge. :: none
  • reviewed 2026-11-17T03:12:18.653Z sha f5149d6 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-17T03:19:36.343Z sha f5149d6 :: needs maintainer review before merge. :: none

Reviewed November 16, 2026, 10:24 PM ET / November 17, 2026, 03:24 UTC (Revision 4).

@jesse-merhi

Copy link
Copy Markdown
Member Author

After-fix proof: real worker pool under Bun 1.4.4 on Linux

Run against f5149d6e, the PR head (the worker code is unchanged since 7ef546f1). The before run swaps in origin/main's run-codex-scan-worker.ts and changes nothing else.

Setup: docker run --user bun oven/bun:1.4.4 (Linux aarch64, uid 1000, non-root), with the checkout mounted read-only. The probe drives the real runContinuouslyRefilledWorkerPool → processJob path. It uses concurrency 2 and a queue of 5 endor-report-only package-release jobs.

  • Simulated: the Convex client, which records the outcome and returns null, and the claim queue.
  • Simulated: root-owned Docker output. After the outcome of jobs 2 and 5 is recorded, a mode-0500 subdirectory is created in their real workspace. The container runs as non-root, so rm hits a real EACCES.
  • Real: the pool, processJob, mkdtemp workspaces, Bun's rm and the worker logger. Timestamps and job UUIDs are redacted.

Result

  • Before: job 2's cleanup error escaped as security_scan_unhandled_process_failure. The pool stopped claiming, with totalClaimed 3, totalFailed 1 and 2 jobs never claimed.
  • After: both locked jobs log security_scan_workspace_cleanup_failed with code: "EACCES" (no path). Each resolves completed: true. The pool keeps claiming: job 2's failed deletion is followed by jobs 3, 4 and 5 being claimed and completed, with totalClaimed 5, totalCompleted 5, totalFailed 0. Only the locked sandbox-output subtree is left behind.
uname: Linux aarch64  bun: 1.4.4  uid: 1000

===== before (origin/main worker)
PROBE claimed job(s) 1,2
PROBE job 1 outcome recorded
PROBE job 2 outcome recorded (workspace will be locked)
PROBE job 1 processJob resolved {"completed":true,"hardFailed":false,"retryableFailed":false}
PROBE claimed job(s) 3
{"level":50,"service":"security-scan-worker","event":"security_scan_unhandled_process_failure","publicReason":"EACCES: permission denied, rm '/tmp/clawhub-codex-scan-securityScanJobs:probe-<uuid>-QG46Tj'","scannerPhase":"process","msg":"security scan job escaped worker error handling"}
PROBE job 3 outcome recorded
PROBE job 3 processJob resolved {"completed":true,"hardFailed":false,"retryableFailed":false}
PROBE stats {"totalClaimed":3,"totalClaimFailures":0,"totalCompleted":2,"totalFailed":1,"totalRetryableFailed":0} unclaimed 2
PROBE left gone(ENOENT)
PROBE left sandbox-output
PROBE left gone(ENOENT)

===== after (PR head worker)
PROBE claimed job(s) 1,2
PROBE job 2 outcome recorded (workspace will be locked)
PROBE job 1 outcome recorded
PROBE job 1 processJob resolved {"completed":true,"hardFailed":false,"retryableFailed":false}
PROBE claimed job(s) 3
{"level":40,"service":"security-scan-worker","event":"security_scan_workspace_cleanup_failed","jobId":"securityScanJobs:probe-<uuid>","code":"EACCES","msg":"security scan workspace cleanup failed; leaving it in place"}
PROBE job 2 processJob resolved {"completed":true,"hardFailed":false,"retryableFailed":false}
PROBE claimed job(s) 4
PROBE job 3 outcome recorded
PROBE job 3 processJob resolved {"completed":true,"hardFailed":false,"retryableFailed":false}
PROBE claimed job(s) 5
PROBE job 4 outcome recorded
PROBE job 5 outcome recorded (workspace will be locked)
PROBE job 4 processJob resolved {"completed":true,"hardFailed":false,"retryableFailed":false}
{"level":40,"service":"security-scan-worker","event":"security_scan_workspace_cleanup_failed","jobId":"securityScanJobs:probe-<uuid>","code":"EACCES","msg":"security scan workspace cleanup failed; leaving it in place"}
PROBE job 5 processJob resolved {"completed":true,"hardFailed":false,"retryableFailed":false}
PROBE stats {"totalClaimed":5,"totalClaimFailures":0,"totalCompleted":5,"totalFailed":0,"totalRetryableFailed":0} unclaimed 0
PROBE left sandbox-output
PROBE left gone(ENOENT)
PROBE left gone(ENOENT)
PROBE left gone(ENOENT)
PROBE left sandbox-output
Probe source (pool-probe.ts)
// Proof probe: drive the real runContinuouslyRefilledWorkerPool -> processJob path
// under Bun. Jobs 2 and 5 get a non-writable subdirectory (stand-in for the
// root-owned files Docker sandboxes leave) after their outcome is recorded.
// Simulated: the Convex client (records the outcome, returns null) and the
// claim queue. Real: the pool, processJob, workspace creation and rm.
import { randomUUID } from "node:crypto";
import { chmod, mkdir, readdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const rev = process.argv[2]!;
const { processJob, runContinuouslyRefilledWorkerPool } = await import(
  join(rev, "scripts/security/run-codex-scan-worker.ts")
);

const locked: string[] = [];
const workspaces: string[] = [];
function makeJob(lock: boolean) {
  const jobId = `securityScanJobs:probe-${randomUUID()}`;
  return {
    lock,
    claimed: {
      job: {
        _id: jobId,
        hasMaliciousSignal: false,
        leaseToken: "lease",
        scanMode: "endor-report-only",
        source: "publish",
        targetKind: "packageRelease",
      },
      target: {},
    },
  };
}
let seq = 0;
const order = new Map<string, number>();
const client = (lock: boolean, jobId: string) => ({
  action: async () => {
    console.log(`PROBE job ${order.get(jobId)} outcome recorded${lock ? " (workspace will be locked)" : ""}`);
    const name = (await readdir(tmpdir())).find((n) => n.startsWith(`clawhub-codex-scan-${jobId}-`));
    if (!name) throw new Error("workspace not found");
    const ws = join(tmpdir(), name);
    workspaces.push(ws);
    if (lock) {
      const dir = join(ws, "sandbox-output");
      await mkdir(dir);
      await writeFile(join(dir, "log.txt"), "x");
      await chmod(dir, 0o500);
      locked.push(dir);
    }
    return null;
  },
});

const queue = [makeJob(false), makeJob(true), makeJob(false), makeJob(false), makeJob(true)];
const stats = await runContinuouslyRefilledWorkerPool({
  concurrency: 2,
  maxJobs: undefined,
  canClaim: () => true,
  claimJobs: async (limit: number) => {
    const jobs = queue.splice(0, limit);
    for (const j of jobs) order.set(j.claimed.job._id, ++seq);
    if (jobs.length) console.log(`PROBE claimed job(s) ${jobs.map((j) => order.get(j.claimed.job._id)).join(",")}`);
    return { claimedCount: jobs.length, jobs };
  },
  processClaimedJob: async (j: ReturnType<typeof makeJob>) => {
    const result = await processJob(client(j.lock, j.claimed.job._id), "token", j.claimed, undefined);
    console.log(`PROBE job ${order.get(j.claimed.job._id)} processJob resolved ${JSON.stringify(result)}`);
    return result;
  },
});
console.log("PROBE stats", JSON.stringify(stats), "unclaimed", queue.length);
for (const ws of workspaces) {
  const left = await readdir(ws).catch((e) => `gone(${e.code})`);
  console.log("PROBE left", Array.isArray(left) ? left.join(",") : left);
}
for (const d of locked) await chmod(d, 0o700).catch(() => {});
for (const ws of workspaces) await rm(ws, { recursive: true, force: true });
Container runner (run.sh)
#!/bin/sh
# Runs inside oven/bun:1.4.4 as the non-root "bun" user. /src is the PR checkout (read-only).
set -eu
echo "uname: $(uname -sm)  bun: $(bun --version)  uid: $(id -u)"
for variant in before after; do
  dir=/tmp/$variant
  mkdir -p $dir
  # Real copy of scripts/ (so the worker can be swapped); everything else symlinked.
  for entry in /src/* /src/.[!.]*; do
    name=$(basename "$entry")
    [ "$name" = scripts ] && continue
    ln -s "$entry" "$dir/$name" 2>/dev/null || true
  done
  cp -R /src/scripts $dir/scripts
  if [ $variant = before ]; then cp /proof/worker-main.ts $dir/scripts/security/run-codex-scan-worker.ts; fi
  echo; echo "===== $variant ($( [ $variant = before ] && echo 'origin/main worker' || echo 'PR head worker'))"
  bun /proof/pool-probe.ts $dir 2>&1 | grep -E 'PROBE|security_scan_(workspace_cleanup_failed|unhandled_process_failure|job_completed)' \
    | sed -E 's/"time":[0-9]+,//; s/probe-[0-9a-f-]{36}/probe-<uuid>/g'
done

@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@jesse-merhi

Copy link
Copy Markdown
Member Author

End-to-end proof: the deployed worker CLI under Bun 1.4.4 on Linux

This runs the worker the way .github/workflows/security-scan-codex.yml does: bun scripts/security/run-codex-scan-worker.ts --batch-limit … --lane shared …, as its own process with no in-process harness. The PR head is f5149d6e. The before run swaps in origin/main's run-codex-scan-worker.ts.

Setup: docker run --user bun oven/bun:1.4.4 (Linux aarch64, uid 1000), with the checkout mounted read-only.

  • Simulated: the Convex deployment only. fake-convex.ts is a separate process that speaks ConvexHttpClient's POST /api/action protocol. It serves 5 endor-report-only package-release jobs. When jobs 2 and 5 report completion, it adds a mode-0500 subdirectory to their real workspace, standing in for root-owned Docker output.
  • Real, unmodified: the CLI entry point, arg parsing, the worker pool, processJob, workspace creation and deletion, Bun's rm, the worker logger and the process exit code.

Result

Claimed Completed Failed Exit code
Before 3 (jobs 4–5 never claimed) 2 1 1
After 5 5 0 0
  • Before: job 2's EACCES escapes as security_scan_unhandled_process_failure. The shard stops claiming and exits 1, which is the Production failure.
  • After: jobs 2 and 5 log security_scan_workspace_cleanup_failed with code: "EACCES" (no path). Claiming continues after job 2, and the CLI exits 0.
  • Left behind: only the locked sandbox-output subdirectory of jobs 2 and 5.

The fake server logs to stderr and the worker to stdout, so their lines interleave by buffering, not by time.

uname: Linux aarch64  bun: 1.4.4  uid: 1000

===== before (origin/main worker)
FAKE-CONVEX listening
FAKE-CONVEX leased job(s) 1,2
FAKE-CONVEX recorded completion for job 1
FAKE-CONVEX recorded completion for job 2
FAKE-CONVEX locked workspace subdirectory for job 2
FAKE-CONVEX leased job(s) 3
FAKE-CONVEX recorded completion for job 3
{"level":30,"service":"security-scan-worker","claimed":2,"event":"security_scan_jobs_claimed","hydrated":2,"lane":"shared","leaseMs":3600000,"requeued":0,"requested":2,"workerId":"proof-shard","msg":"claimed security scan jobs"}
{"level":30,"service":"security-scan-worker","claimed":1,"event":"security_scan_jobs_claimed","hydrated":1,"lane":"shared","leaseMs":3600000,"requeued":0,"requested":1,"workerId":"proof-shard","msg":"claimed security scan jobs"}
{"level":50,"service":"security-scan-worker","event":"security_scan_unhandled_process_failure","publicReason":"EACCES: permission denied, rm '/tmp/clawhub-codex-scan-securityScanJobs:proof-job-2-Sa3gQc'","scannerPhase":"process","msg":"security scan job escaped worker error handling"}
{"level":30,"service":"security-scan-worker","event":"security_scan_worker_summary","lane":"shared","totalClaimed":3,"totalClaimFailures":0,"totalCompleted":2,"totalFailed":1,"totalRetryableFailed":0,"workerId":"proof-shard","msg":"security scan worker summary"}
WORKER exit code: 1
left in /tmp: proof-job-2[sandbox-output] 

===== after (PR head worker)
FAKE-CONVEX listening
FAKE-CONVEX leased job(s) 1,2
FAKE-CONVEX recorded completion for job 2
FAKE-CONVEX recorded completion for job 1
FAKE-CONVEX locked workspace subdirectory for job 2
FAKE-CONVEX leased job(s) 3
FAKE-CONVEX leased job(s) 4
FAKE-CONVEX recorded completion for job 3
FAKE-CONVEX recorded completion for job 4
FAKE-CONVEX leased job(s) 5
FAKE-CONVEX recorded completion for job 5
FAKE-CONVEX locked workspace subdirectory for job 5
{"level":30,"service":"security-scan-worker","claimed":2,"event":"security_scan_jobs_claimed","hydrated":2,"lane":"shared","leaseMs":3600000,"requeued":0,"requested":2,"workerId":"proof-shard","msg":"claimed security scan jobs"}
{"level":40,"service":"security-scan-worker","event":"security_scan_workspace_cleanup_failed","jobId":"securityScanJobs:proof-job-2","code":"EACCES","msg":"security scan workspace cleanup failed; leaving it in place"}
{"level":30,"service":"security-scan-worker","claimed":1,"event":"security_scan_jobs_claimed","hydrated":1,"lane":"shared","leaseMs":3600000,"requeued":0,"requested":1,"workerId":"proof-shard","msg":"claimed security scan jobs"}
{"level":30,"service":"security-scan-worker","claimed":1,"event":"security_scan_jobs_claimed","hydrated":1,"lane":"shared","leaseMs":3600000,"requeued":0,"requested":1,"workerId":"proof-shard","msg":"claimed security scan jobs"}
{"level":30,"service":"security-scan-worker","claimed":1,"event":"security_scan_jobs_claimed","hydrated":1,"lane":"shared","leaseMs":3600000,"requeued":0,"requested":1,"workerId":"proof-shard","msg":"claimed security scan jobs"}
{"level":30,"service":"security-scan-worker","claimed":0,"event":"security_scan_jobs_claimed","hydrated":0,"lane":"shared","leaseMs":3600000,"requeued":0,"requested":1,"workerId":"proof-shard","msg":"claimed security scan jobs"}
{"level":40,"service":"security-scan-worker","event":"security_scan_workspace_cleanup_failed","jobId":"securityScanJobs:proof-job-5","code":"EACCES","msg":"security scan workspace cleanup failed; leaving it in place"}
{"level":30,"service":"security-scan-worker","event":"security_scan_worker_summary","lane":"shared","totalClaimed":5,"totalClaimFailures":0,"totalCompleted":5,"totalFailed":0,"totalRetryableFailed":0,"workerId":"proof-shard","msg":"security scan worker summary"}
WORKER exit code: 0
left in /tmp: proof-job-2[sandbox-output] proof-job-5[sandbox-output] 
fake-convex.ts
// Fake Convex deployment for the worker CLI proof. It speaks the HTTP action
// protocol ConvexHttpClient uses (POST /api/action). It serves a queue of 5
// endor-report-only package-release jobs. When a locked job's outcome arrives
// (completeCodexScanJob), it adds a mode-0500 subdirectory to that job's real
// workspace, standing in for root-owned Docker sandbox output. The worker is
// unmodified and runs as a separate process.
import { chmod, mkdir, readdir, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

const jobs = [1, 2, 3, 4, 5].map((n) => ({
  n,
  id: `securityScanJobs:proof-job-${n}`,
  locked: n === 2 || n === 5,
}));
const queue = [...jobs];
const log = (msg: string) => console.error(`FAKE-CONVEX ${msg}`);
const ok = (value: unknown) => Response.json({ status: "success", value, logLines: [] });

Bun.serve({
  port: Number(process.env.FAKE_CONVEX_PORT ?? 3210),
  async fetch(request) {
    const { path, args } = (await request.json()) as { path: string; args: [Record<string, unknown>] };
    const input = args[0] ?? {};
    switch (path) {
      case "securityScan:claimCodexScanJobLeases": {
        const leased = queue.splice(0, Number(input.limit));
        if (leased.length) log(`leased job(s) ${leased.map((j) => j.n).join(",")}`);
        return ok(leased.map((j) => ({ _id: j.id, leaseToken: `lease-${j.n}` })));
      }
      case "securityScan:hydrateCodexScanJob": {
        const job = jobs.find((j) => j.id === input.jobId)!;
        return ok({
          job: {
            _id: job.id,
            leaseToken: `lease-${job.n}`,
            hasMaliciousSignal: false,
            scanMode: "endor-report-only",
            source: "backfill",
            targetKind: "packageRelease",
          },
          target: {},
        });
      }
      case "securityScan:completeCodexScanJob": {
        const job = jobs.find((j) => j.id === input.jobId)!;
        log(`recorded completion for job ${job.n}`);
        if (job.locked) {
          const name = (await readdir(tmpdir())).find((entry) =>
            entry.startsWith(`clawhub-codex-scan-${job.id}-`),
          );
          if (!name) throw new Error(`workspace for job ${job.n} not found`);
          const locked = join(tmpdir(), name, "sandbox-output");
          await mkdir(locked);
          await writeFile(join(locked, "scanner.log"), "root-owned in production");
          await chmod(locked, 0o500);
          log(`locked workspace subdirectory for job ${job.n}`);
        }
        return ok(null);
      }
      case "securityScan:getCodexScanQueueHealth":
        return ok({
          snapshotAt: Date.now(),
          queueDepth: queue.length,
          queueDepthIsEstimate: false,
          readyQueueDepth: queue.length,
          readyQueueDepthIsEstimate: false,
          oldestReadyJobAgeSeconds: 0,
          oldestReadyJobNextRunAt: null,
        });
      default:
        log(`unexpected call ${path}`);
        return ok(null);
    }
  },
});
log("listening");
run-cli.sh
#!/bin/sh
# Runs inside oven/bun:1.4.4 as the non-root "bun" user. /src is the PR checkout (read-only).
# Starts the real worker CLI exactly as the workflow does, against fake-convex.ts.
set -u
echo "uname: $(uname -sm)  bun: $(bun --version)  uid: $(id -u)"
for variant in before after; do
  dir=/tmp/$variant
  mkdir -p $dir
  for entry in /src/* /src/.[!.]*; do
    name=$(basename "$entry")
    [ "$name" = scripts ] && continue
    ln -s "$entry" "$dir/$name" 2>/dev/null || true
  done
  cp -R /src/scripts $dir/scripts
  [ $variant = before ] && cp /proof/worker-main.ts $dir/scripts/security/run-codex-scan-worker.ts
  rm -rf /tmp/clawhub-codex-scan-* 2>/dev/null; chmod -R u+w /tmp/clawhub-codex-scan-* 2>/dev/null; rm -rf /tmp/clawhub-codex-scan-*
  echo; echo "===== $variant ($( [ $variant = before ] && echo 'origin/main worker' || echo 'PR head worker'))"
  bun /proof/fake-convex.ts 2>&1 &
  fake=$!
  sleep 1
  (
    cd $dir
    CLAWHUB_ALLOW_LOCAL_CODEX_SCAN=1 CODEX_HOME=/tmp/codex-home CONVEX_URL=http://127.0.0.1:3210 \
    SECURITY_SCAN_WORKER_TOKEN=fixture-worker-token CODEX_SECURITY_SCAN_WORKER_ID=proof-shard \
    CODEX_SECURITY_SCAN_DIAGNOSTICS_DIR=/tmp/diag-$variant \
    bun scripts/security/run-codex-scan-worker.ts \
      --batch-limit 2 --lane shared --max-jobs "" --max-runtime-minutes 1 --lease-minutes 60
    echo "WORKER exit code: $?"
  ) 2>&1 | grep -E 'FAKE-CONVEX|WORKER exit|security_scan_(jobs_claimed|workspace_cleanup_failed|unhandled_process_failure|worker_summary)' \
    | sed -E 's/"time":[0-9]+,//; s/"elapsedMs":[0-9]+,//'
  kill $fake 2>/dev/null; wait $fake 2>/dev/null
  echo "left in /tmp: $(for d in /tmp/clawhub-codex-scan-*; do [ -e "$d" ] && printf '%s[%s] ' "$(basename "$d" | sed -E 's/-[A-Za-z0-9]{6}$//; s/^clawhub-codex-scan-securityScanJobs://')" "$(ls "$d" | tr '\n' ' ' | sed 's/ $//')"; done)"
  chmod -R u+w /tmp/clawhub-codex-scan-* 2>/dev/null; rm -rf /tmp/clawhub-codex-scan-*
done

@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 17, 2026
@clawsweeper clawsweeper Bot added the status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. label Nov 17, 2026
@jesse-merhi

Copy link
Copy Markdown
Member Author

/clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@jesse-merhi
jesse-merhi merged commit 04ec35b into main Nov 17, 2026
65 of 66 checks passed
@jesse-merhi
jesse-merhi deleted the fix/security-scan-workspace-cleanup branch November 17, 2026 03:25

This branch was successfully deployed

1 active deployment
Preview – clawhub — f5149d6e Deployed Nov 17, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants