Skip to content
Closed
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions .claude/hooks/report-worker-turn.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
#!/usr/bin/env node

import { execFileSync, spawnSync } from "node:child_process"
import { closeSync, openSync, readFileSync, writeSync } from "node:fs"
import { isAbsolute } from "node:path"

const REPORT_MARKER = "WORKER_REPORT:"
const GATE_RESULTS = new Set(["passed", "failed", "not-run"])
const FALLBACK_BLOCKER = "missing or malformed WORKER_REPORT marker"

const valueAfter = (flag) => {
const index = process.argv.indexOf(flag)
return index === -1 ? null : process.argv[index + 1] ?? null
}

const fail = (message) => {
process.stderr.write(`worker report hook: ${message}\n`)
process.exit(1)
}

const reportsFile = valueAfter("--reports-file")
const ticket = valueAfter("--ticket")

if (!reportsFile || !isAbsolute(reportsFile)) fail("--reports-file must be an absolute path")
if (!/^ORB-\d+$/.test(ticket ?? "")) fail("--ticket must be a Linear identifier such as ORB-136")

const hookInput = (() => {
try {
return JSON.parse(readFileSync(0, "utf8"))
} catch {
return {}
}
})()

const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value)

const declaredReport = (() => {
if (typeof hookInput.last_assistant_message !== "string") return null
const markerLine = hookInput.last_assistant_message
.split(/\r?\n/)
.filter((line) => line.startsWith(REPORT_MARKER))
.at(-1)
if (!markerLine) return null

try {
const parsed = JSON.parse(markerLine.slice(REPORT_MARKER.length).trim())
if (!isRecord(parsed) || !isRecord(parsed.gates)) return null
if (!Object.values(parsed.gates).every((result) => GATE_RESULTS.has(result))) return null
if (!Array.isArray(parsed.contractItems) || !parsed.contractItems.every((item) => typeof item === "string")) return null
if (parsed.blockedOn !== null && typeof parsed.blockedOn !== "string") return null
if (typeof parsed.needsHuman !== "boolean") return null
return parsed
} catch {
return null
}
})()

const worktree = typeof hookInput.cwd === "string" ? hookInput.cwd : process.cwd()

const gitOutput = (args) => {
try {
return execFileSync("git", ["-C", worktree, ...args], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim()
} catch {
return null
}
}

const headSha = gitOutput(["rev-parse", "--verify", "HEAD"])
const upstream = gitOutput(["rev-parse", "--symbolic-full-name", "@{upstream}"])
const pushed =
Boolean(headSha && upstream?.startsWith("refs/remotes/")) &&
spawnSync("git", ["-C", worktree, "merge-base", "--is-ancestor", headSha, upstream], {
stdio: "ignore",
}).status === 0

const record = {
reportedAt: new Date().toISOString(),
ticket,
headSha,
pushed,
gates: declaredReport?.gates ?? {},
contractItems: declaredReport?.contractItems ?? [],
blockedOn: declaredReport ? declaredReport.blockedOn : FALLBACK_BLOCKER,
needsHuman: declaredReport?.needsHuman ?? true,
}

const line = Buffer.from(`${JSON.stringify(record)}\n`, "utf8")
let handle
try {
handle = openSync(reportsFile, "a")
const written = writeSync(handle, line)
if (written !== line.length) throw new Error(`wrote ${written} of ${line.length} bytes`)
} catch (error) {
fail(`could not append ${reportsFile}: ${error.message}`)
} finally {
if (handle !== undefined) closeSync(handle)
}
112 changes: 111 additions & 1 deletion .claude/hooks/test-hooks.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
// Run: node .claude/hooks/test-hooks.mjs (exits non-zero on any failure)

import { mkdirSync, mkdtempSync, writeFileSync, rmSync, readFileSync, readdirSync, existsSync, statSync } from "node:fs"
import { spawnSync } from "node:child_process"
import { spawn, spawnSync } from "node:child_process"
import { tmpdir } from "node:os"
import { dirname, join } from "node:path"
import { fileURLToPath } from "node:url"
Expand Down Expand Up @@ -1142,6 +1142,116 @@ T("cc raw-tool: every chained command has its own appeal -> 0", appealedChain.st
T("cc raw-tool: chained wave-plan reason is recorded", appealedChain.stdout.includes("wave plan is required"), true)
T("cc raw-tool: chained rollup reason is recorded", appealedChain.stdout.includes("rollup is required"), true)

const reportRepo = join(root, "report-repo")
const reportRemote = join(root, "report-remote.git")
mkdirSync(reportRepo, { recursive: true })
const reportGit = (cwd, args) => spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8" })
for (const args of [
["init", "-q", "--bare", reportRemote],
["init", "-q", "--initial-branch=feature/orb-136", reportRepo],
["config", "user.email", "gate@orbit.test"],
["config", "user.name", "Orbit Gate"],
]) {
const cwd = args[0] === "init" && args.includes("--bare") ? root : reportRepo
const result = reportGit(cwd, args)
T(`worker-report setup: git ${args.join(" ")}`, result.status, 0)
}
writeFileSync(join(reportRepo, "proof.txt"), "reported\n")
for (const args of [
["add", "proof.txt"],
["commit", "-q", "-m", "test report"],
["remote", "add", "origin", reportRemote],
["push", "-q", "-u", "origin", "feature/orb-136"],
]) {
const result = reportGit(reportRepo, args)
T(`worker-report setup: git ${args.join(" ")}`, result.status, 0)
}

const reportHook = join(hooksDir, "report-worker-turn.mjs")
const runReportHook = (reportsFile, payload) =>
spawnSync(process.execPath, [reportHook, "--reports-file", reportsFile, "--ticket", "ORB-136"], {
cwd: reportRepo,
input: JSON.stringify(payload),
encoding: "utf8",
})
const completeReports = join(root, "complete-reports.jsonl")
const completePayload = {
cwd: reportRepo,
last_assistant_message:
'Finished.\nWORKER_REPORT: {"gates":{"lint":"passed","type-check":"passed","test":"passed"},"contractItems":["committed","pushed","pr-open"],"blockedOn":null,"needsHuman":false}',
}
const runReportHookWithArgs = (args) =>
spawnSync(process.execPath, [reportHook, ...args], {
cwd: reportRepo,
input: JSON.stringify(completePayload),
encoding: "utf8",
})
const relativeReports = runReportHookWithArgs(["--reports-file", "reports.jsonl", "--ticket", "ORB-136"])
T("worker-report: relative reports path is rejected", relativeReports.status, 1)
T("worker-report: relative reports path explains the contract", /--reports-file must be an absolute path/.test(relativeReports.stderr), true)
const missingReports = runReportHookWithArgs(["--ticket", "ORB-136"])
T("worker-report: missing reports path is rejected", missingReports.status, 1)
T("worker-report: missing reports path explains the contract", /--reports-file must be an absolute path/.test(missingReports.stderr), true)
const malformedTicket = runReportHookWithArgs(["--reports-file", join(root, "malformed-ticket.jsonl"), "--ticket", "orb-136"])
T("worker-report: malformed ticket is rejected", malformedTicket.status, 1)
T("worker-report: malformed ticket explains the contract", /--ticket must be a Linear identifier/.test(malformedTicket.stderr), true)
const appendFailureTarget = join(root, "append-failure")
mkdirSync(appendFailureTarget)
const appendFailure = runReportHookWithArgs(["--reports-file", appendFailureTarget, "--ticket", "ORB-136"])
T("worker-report: append failure exits nonzero", appendFailure.status, 1)
T("worker-report: append failure names the reports target", appendFailure.stderr.includes(`could not append ${appendFailureTarget}`), true)
T("worker-report: complete turn appends successfully", runReportHook(completeReports, completePayload).status, 0)
const completeRecords = readFileSync(completeReports, "utf8").trim().split(/\r?\n/).map((line) => JSON.parse(line))
const completeRecord = completeRecords[0]
T("worker-report: complete turn appends exactly one record", completeRecords.length, 1)
T("worker-report: ticket is configured by the launcher", completeRecord.ticket, "ORB-136")
T("worker-report: head SHA is derived from git", completeRecord.headSha, reportGit(reportRepo, ["rev-parse", "HEAD"]).stdout.trim())
T("worker-report: pushed state is derived from the upstream", completeRecord.pushed, true)
T("worker-report: gate results survive", completeRecord.gates, { lint: "passed", "type-check": "passed", test: "passed" })
T("worker-report: contract items survive", completeRecord.contractItems, ["committed", "pushed", "pr-open"])
T("worker-report: an unblocked completion stays unblocked", completeRecord.blockedOn, null)
T("worker-report: an unattended completion does not ask for a human", completeRecord.needsHuman, false)
T("worker-report: timestamp is well formed", Number.isNaN(Date.parse(completeRecord.reportedAt)), false)

const fallbackReports = join(root, "fallback-reports.jsonl")
T("worker-report: missing marker still appends", runReportHook(fallbackReports, { cwd: reportRepo, last_assistant_message: "Finished." }).status, 0)
const fallbackRecord = JSON.parse(readFileSync(fallbackReports, "utf8").trim())
T("worker-report: missing marker is explicit", fallbackRecord.blockedOn, "missing or malformed WORKER_REPORT marker")
T("worker-report: missing marker asks for a human", fallbackRecord.needsHuman, true)

const concurrentReports = join(root, "concurrent-reports.jsonl")
const concurrentWrites = Array.from(
{ length: 8 },
() =>
new Promise((resolveWrite) => {
const child = spawn(process.execPath, [reportHook, "--reports-file", concurrentReports, "--ticket", "ORB-136"], {
cwd: reportRepo,
stdio: ["pipe", "ignore", "pipe"],
})
let stderr = ""
child.stderr.on("data", (chunk) => {
stderr += chunk
})
child.on("close", (status) => resolveWrite({ status, stderr }))
child.stdin.end(JSON.stringify(completePayload))
}),
)
const concurrentResults = await Promise.all(concurrentWrites)
T("worker-report: eight concurrent hooks all exit successfully", concurrentResults.map(({ status }) => status), Array(8).fill(0))
const concurrentLines = readFileSync(concurrentReports, "utf8").trim().split(/\r?\n/)
T("worker-report: eight concurrent appends lose no records", concurrentLines.length, 8)
T(
"worker-report: every concurrent line is well formed",
concurrentLines.every((line) => {
try {
return JSON.parse(line).ticket === "ORB-136"
} catch {
return false
}
}),
true,
)

// ---------------------------------------------------------------------------
// 3. Agent frontmatter: the fails-open `Bash(...)` trap
// ---------------------------------------------------------------------------
Expand Down
1 change: 1 addition & 0 deletions .claude/orchestrator.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
"deep": 250000
}
},
"hookVerification": "Measured 2026-07-28 on Windows 11 with the installed codex-cli 0.145.0. A real codex exec invocation with --dangerously-bypass-hook-trust ran a Stop command hook and delivered hook_event_name Stop, the session cwd, and the exact final response in last_assistant_message; feeding that captured payload to .claude/hooks/report-worker-turn.mjs appended the expected record with the derived head SHA and pushed state. The installed CLI help also exposes --dangerously-bypass-hook-trust. The official Codex Hooks contract at https://learn.chatgpt.com/docs/hooks documents project .codex/hooks.json, the same nested hooks.Stop command shape used by launch-worker.mjs, cwd and last_assistant_message on Stop input, and the bypass flag for vetted automation. Project-local hooks still require the project layer to be trusted; the interactive launch path answers that standard trust gate before the worker turn.",
"notes": "Model routing: the default is gpt-5.6-terra at medium reasoning, tier:cheap selects gpt-5.6-luna at low reasoning, and tier:deep selects gpt-5.6-sol at high reasoning. The default is based on the 23 pull requests in the 2026-07-28 unattended run: every pull request ran on Sol at high, with a mean of 2.0 CHANGES_REQUESTED rounds, a median of 1, and worst results of 13, 7 and 5. Sol at high therefore averaged exactly the two rounds that had condemned Terra at medium, so the falsifier fired and the decision was reversed by ADR. The legacy worker:sonnet label is rejected loudly with remediation to use tier:cheap. Requires a paid ChatGPT plan plus codex login; a headless session can start that itself with codex login --device-auth, which prints a URL and a one-time code for the account owner to enter. CODEX_HOME DECIDES WHETHER A WORKER IS LOGGED IN, and it is the first thing to check before believing any auth verdict: Orca redirects codex's home for the terminals it spawns, so on this machine the real credential is C:\\Users\\thoma\\AppData\\Roaming\\orca\\codex-runtime-home\\home\\auth.json, not the default ~/.codex/auth.json. Measured 2026-07-27: a shell that had lost CODEX_HOME reported 'Not logged in' and codex doctor reported 'no Codex credentials were found', while the very same CLI in an Orca terminal in the same worktree reported 'Logged in using ChatGPT' minutes earlier. For an unattended worker those two states are indistinguishable from having no plan at all, and the worker dies on a login screen nobody is there to answer. Two consequences. Never diagnose codex auth from an ad hoc shell without printing CODEX_HOME first. And a codex worker that never reaches tui-idle should be suspected of sitting on the login splash: that splash ANIMATES, so the repaint check in tools/launch-worker.mjs now turns it into a loud exit 1 rather than a prompt pointer typed into a sign-in screen. Reads AGENTS.md natively. The invocation is bare codex with no subcommand, which is what codex --help means by 'If no subcommand is specified, options will be forwarded to the interactive CLI'. codex exec is the NON-interactive subcommand and lands in the same unsupervisable place as claude -p, so tools/launch-worker.mjs still refuses it (per-engine headless tokens: exec and its alias e for codex, -p and --print for claude, because codex's -p is --profile, a legitimate interactive flag). Approval and sandbox policy is --dangerously-bypass-approvals-and-sandbox, not the equivalent pair -a never --sandbox danger-full-access, and never --full-auto: --full-auto is -a on-request --sandbox workspace-write, and on-request lets the MODEL decide when to ask a human who is not at the keyboard. The single flag beats the pair because the pair has a half-state: an edit that drops -a never while keeping the sandbox flag silently restores approval prompts to a worker nobody is watching, which is the exact failure this entry exists to prevent. The containment story is the disposable Orca worktree, the same one that justifies claude's bypassPermissions. Everything below was measured on 2026-07-27 against codex-cli 0.145.0 on Windows 11. -c windows.sandbox=\"unelevated\" is load-bearing: Codex's default Windows sandbox is elevated, its setup needs Administrator rights, and the first-run TUI paints 'Set up default sandbox (requires Administrator permissions)' then sits on 'Setting up sandbox... Input disabled until setup completes' forever in a PTY that has no desktop to raise UAC on. Measured still spinning after 2.5 minutes, with orca terminal wait reporting satisfied: true throughout, a false idle. The unelevated fallback (restricted tokens and ACLs, learn.chatgpt.com/docs/windows/windows-sandbox) needs no elevation, and the worker never executes inside it anyway because the bypass flag runs commands unsandboxed. cwd needs no -C: orca terminal create --worktree already starts the TUI in the worktree. Supervision, all measured: a real TUI opens, so the Orca card carries an Agents row and orca terminal wait --for tui-idle has a state to observe. The first screen in a brand-new worktree is codex's own trust gate, 'Do you trust the contents of this directory?', which normally reports blockedReason codex-interactive-prompt. Orca 1.4.156 was also measured retaining codex-trust-workspace on an idle codex terminal that never saw a trust gate. WHY: PR #629 owner adjudication makes that live capture authoritative over the older one-reason-per-engine mapping. It is a preselected list whose own instruction reads 'Press enter to continue', so the answer is Enter ALONE; the 1 then Enter that answers Claude Code's gate left the codex process exited (-1). launch-worker.mjs therefore keeps the trust answer per engine. Never blind-Enter an unrecognised codex screen: a stray Enter meant for one prompt was measured confirming the NEXT one, which is how the Administrator sandbox setup above got selected. Everything the claude entry says about talking to a live worker holds here unchanged: never send to a terminal that is not tui-idle, and tui-idle means stopped, not done, so it is the trigger to run tools/worker-status.mjs, never a report of success."
}
},
Expand Down
Loading
Loading