feat(harness): add a Claude Code harness #247
On a fresh harness with no transcript, controller.Replay passes the first execution with empty History, so this call launches a new billed turn and real tools before the replay sink can reject it. Reject reconstruction before process creation through a host-enforced replay eligibility check or an explicit invocation mode that also works over harnesswire; a package warning does not enforce read-only replay.
After cancellation, SIGINT can stop the leader while a tool subprocess with redirected stdout remains alive. The loop then exits on leader exit and stdout EOF, allowing the tool to keep modifying the workspace after Run returns. Make process-group cleanup independent of stdout ownership before releasing the turn, and cover a cancelled turn with a child whose stdio is redirected.
LookPath can return a relative path for an explicitly relative Binary such as ./bin/claude. New validates that path relative to the node's current directory, but run sets cmd.Dir to WorkDir, so execution resolves it against a different directory and either fails to start or runs a different executable. Convert the resolved binary path to an absolute path before storing it.
After a success result, every subsequent line bypasses JSON decoding. A stream containing a valid success result followed by a truncated JSON line therefore returns success and journals OUTPUT, despite Run's malformed-stream failure contract. Continue validating post-result lines while suppressing further sink effects, rather than skipping parsing altogether.
This directly incorporates Claude Code-specific execution and message handling into the root module. CONTRIBUTING.md:55–57 requires that module to remain free of provider-specific code and naming, with concrete integrations in separate modules or repositories. Please move the Claude Code adapter into a separate integration module and serve it from an integration-owned entry point or a vendor-neutral registration boundary rather than importing it into the core harnessnode.
This unmediated harness conflicts with the published contract: spec.md EXE-13 requires deterministic execution, while docs/harness-authoring.md requires model calls through sink.Model and keeps model credentials out of the harness environment. Update the specification and authoring guide to explicitly scope those guarantees and describe this tier's unsupported operations and credential ownership. Package comments and a changelog alone leave these requirements contradictory.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Replay can launch billed turns and real tools before rejection, while cancelled turns can leave tool subprocesses modifying the workspace after Run returns.
<details open>
<summary><strong>6 open issues</strong></summary>
</details>
<details>
<summary><strong>What changed in this PR</strong></summary>
Adds Claude Code as an unmediated sessions harness, selectable through HARNESS_KIND=claudecode. Session continuity requires memory and filesystem snapshots rather than replay.
Changes:
| File | Description |
| ---- | ----------- |
| harness/claudecode/turn.go | Process lifecycle, stream parsing, and event reporting. |
| harness/claudecode/testdata/zero_usage_result.jsonl | Zero-usage fallback fixture. |
| harness/claudecode/testdata/truncated.jsonl | Missing-result and unfinished-tool fixture. |
| harness/claudecode/testdata/tool_turn.jsonl | Tool and subagent receipt fixture. |
| harness/claudecode/testdata/text_turn.jsonl | Successful text and usage fixture. |
| harness/claudecode/testdata/session_mismatch.jsonl | Incorrect session identity fixture. |
| harness/claudecode/testdata/README.md | Documents synthetic fixture formats. |
| harness/claudecode/testdata/malformed.jsonl | Invalid JSON fixture. |
| harness/claudecode/testdata/init_only.jsonl | Initialization-only fixture. |
| harness/claudecode/testdata/error_result.jsonl | Failed-result fixture. |
| harness/claudecode/testdata/before_init.jsonl | Event-before-initialization fixture. |
| harness/claudecode/proc_unix.go | Unix signaling and process-group helpers. |
| harness/claudecode/proc_unix_test.go | Cancellation and descendant-process tests. |
| harness/claudecode/proc_other.go | Non-Unix process termination helpers. |
| harness/claudecode/integration_test.go | Controller and harnesswire integration coverage. |
| harness/claudecode/fake_test.go | Offline fake CLI and test helpers. |
| harness/claudecode/claudecode.go | Harness configuration, capabilities, and session state. |
| harness/claudecode/claudecode_test.go | Configuration, reporting, and failure-path tests. |
| cmd/harnessnode/main.go | Harness selection and environment configuration. |
| cmd/harnessnode/main_test.go | Configuration validation tests. |
| changelog/unreleased/claudecode-harness.md | Documents the harness and its limitations. |
</details>
<sub>Review effort: Balanced</sub>
Fixed in "feat(claudecode): add the claudecode harness integration module". Run now kills the turn's process group on every path, success included, and waits (up to the drain grace) until the group is empty before returning, so a background process a tool started cannot outlive the turn. TestGroupKilledWhenRunReturns covers a cancelled and a successful turn whose child redirected its stdio to /dev/null.
Fixed in "feat(claudecode): add the claudecode harness integration module". New makes the LookPath result absolute, so a relative Binary resolves against the current directory, not WorkDir. TestRelativeBinary runs a turn with ./<binary> and a different WorkDir.
Fixed in "feat(claudecode): add the claudecode harness integration module". Lines after the success result are still decoded. They have no sink effects, but a malformed line, or a stream cut mid-line, fails the turn as it would before the result. Covered by two TestFailedTurns cases and TestLinesAfterResult.
Moved. The harness is now its own module, integrations/claudecode, with replace => ../.. like integrations/substrate ("feat(claudecode): add the claudecode harness integration module"). The harnessnode server moved to internal/harnessnode, and cmd/harnessnode is a thin main over it ("refactor(harnessnode): serve harnesses through internal/harnessnode"). integrations/claudecode/cmd/harnessnode serves only this harness through harnessnode.WithHarness ("feat(claudecode): serve the claudecode harness from its own harnessnode"). The integrations CI job tests both modules, the root gate now also fails if the root links anything under integrations/, and dependabot, the path filter and the docs list the new module. The root module no longer names the provider.
Resolved by #246. The package doc and changelog now use its terms: unmediated per spec §8.8 (EXE-37), REQUIRES_MEMORY_SNAPSHOT (EXE-38), placeholder credential only (EXE-40), spend, audit and replay given up (EXE-41), no re-run of a started execution (EXE-42). Updated in "feat(claudecode): add the claudecode harness integration module".
Not changing this here. Refusing replay needs the harness to declare its class through the API and controller.Replay to check it before starting the harness, over harnesswire too. That is an API change, not something this harness can do alone. The package doc keeps the warning and now points at EXE-41. Tracked in the follow-up issue "Refuse reconstruction replay for an unmediated harness".
An already-canceled Run still launches Claude Code: exec.Command/cmd.Start do not observe ctx, and cancellation is only checked in the select loop after the child has started. This also applies when the harnesswire stream is canceled before Run is invoked. Check ctx.Err() before starting the child, and add a pre-canceled-context test that asserts no process was spawned.
After the CLI exits, slow sink.Report calls can consume the one-second drain grace while ordinary output is still unread. The deadline then closes stdout, potentially dropping receipts and the final result and failing an otherwise successful turn. Bound stalled pipe reads separately from sink-processing time, preserve process-group cleanup, and add a slow-sink regression test.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
The turn runner can drop valid output when slow sink processing exhausts the drain grace period and can spawn Claude Code despite an already-canceled context.
<details open>
<summary><strong>5 open issues</strong></summary>
</details>
<details>
<summary><strong>3 resolved since last review</strong></summary>
</details>
<sub>Review effort: Balanced</sub>
This looks good, a few thoughts:
1. Since Claude Code's own permissions are the only gate here, could we pin them down a bit? Passing --setting-sources user and --strict-mcp-config would stop settings or .mcp.json in the work dir from widening them, and bypassPermissions could use a second explicit opt-in.
2. The child gets the full harnessnode environment, so a real key set by mistake could land in the journal through a tool result. An allowlisted env would be a cheap second line behind the placeholder.
3. When --resume fails, every later turn fails and the reason is dropped. Logging a short reason to the node log would make that easy to debug.
4. One recorded fixture from the pinned CLI version (a tool turn and a resume) would catch flag or format changes the fake can't.
Small one: docs/harness-authoring.md:966 says no harness implements the rerun check, but this one does.
The new entry point imports github.com/agent-primitives/sessions/internal/harnessnode, but that package is absent from the pinned root release v0.3.0. Dependency consumers ignore this module's replace, so building the entry point outside this checkout resolves a root version that cannot satisfy the import. Before publishing the integration, require a root-module release or pseudo-version containing the server refactor.
On Windows and other non-Unix builds, New still accepts the harness, but this reports successful cleanup without terminating any tool subprocesses. A child with redirected stdio can therefore keep modifying the workspace after a successful or cancelled Run, despite the harness's cleanup guarantee. Reject unsupported platforms before launching Claude, or implement process-tree cleanup (for example, a Windows Job Object) instead of returning success unconditionally.
Absence of a valid system/init does not make stderr safe: malformed or mismatched init events also leave t.initSeen false, causing arbitrary child diagnostics to reach operational logs. Truncation and control-character removal preserve any prompt text, credentials or private endpoints in those diagnostics. Allowlist the known missing-transcript diagnostic for the expected session ID and omit other stderr.
h.env contains environment values, including any inherited ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN. If this assertion fails when a developer runs the offline tests with credentials configured, it prints those credentials into the test log. Report only the failed expectation or environment variable names, rather than the complete environment.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Unresolved issues can expose sensitive data in logs, prevent downstream builds with the pinned dependency, and leave tool subprocesses running after non-Unix cleanup reports success.
<details open>
<summary><strong>7 open issues</strong></summary>
</details>
<details>
<summary><strong>2 resolved since last review</strong></summary>
</details>
<sub>Review effort: Balanced</sub>
Fixed in d603af5: New now refuses non-Unix platforms with an unsupported-platform error (checkPlatform in proc_other.go), and the non-Unix stopGroup returns false, so it can never report a cleanup it did not do.
Fixed in d603af5: the env assertions now report variable names only, never values.
This follows the repo's release flow for nested modules (CONTRIBUTING.md): the module's require is bumped after the root tag that contains internal/harnessnode, the same way integrations/substrate moved to v0.3.0. Until then the replace keeps in-repo builds working, and the module is not tagged before that bump.
Keeping this one. The line is logged only when a turn fails before system/init, so no tool has run, and the prompt goes to claude on stdin, not argv. It is one line, capped at 256 bytes with control characters replaced, and it is the diagnostic asked for in review to debug a failing --resume.
@gambtho thanks for the review. All five are in d603af5:
1. Every turn passes --setting-sources user --strict-mcp-config, and the bypass permission mode also needs its own opt-in (HARNESS_CLAUDE_ALLOW_BYPASS_PERMISSIONS=true).
2. claude gets only an allowlisted env (PATH, HOME, locale, the ANTHROPIC_* key and base URL, CLAUDE_CONFIG_DIR), extendable with HARNESS_CLAUDE_ENV_ALLOWLIST.
3. A turn that fails before system/init, such as a failed --resume, logs its exit status and first stderr line (at most 256 bytes).
4. Three scrubbed fixtures recorded from Claude Code 2.1.311 (a tool turn, a resume, a missing resume) with replay tests; the capture command is in testdata/README.md.
The harness-authoring.md line is fixed too, and the harness now refuses non-Unix platforms, since it can only clean up a turn's tool processes through the process group.
One thing I have not probed: whether --setting-sources user also keeps a project .claude/settings.json and its hooks from loading on 2.1.311. I checked only .mcp.json. Mind taking another look?
If the post-result grace timer and the leader's exit notification are both ready, the select can take the timer first even though the leader has already exited with status 2. In that case SIGINT returns os.ErrProcessDone, but this still sets signaled = true, so outcome ignores the nonzero status and records successful output. Return the signaling error from interruptProcess and only mark the exit as harness-induced when the signal was actually delivered.
This accepts every non-array value as text, so an assistant/user event with object, numeric or boolean message.content is silently ignored. A subsequent success result then completes the turn despite the malformed content. Accept strings explicitly and return errMalformed for these other content shapes.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
A critical timer race can misreport a nonzero process exit as success, and malformed message content is silently accepted.
<details open>
<summary><strong>5 open issues</strong></summary>
</details>
<details>
<summary><strong>4 resolved since last review</strong></summary>
</details>
<sub>Review effort: Balanced</sub>
Tested on 2.1.311 against a local API stub: --setting-sources user does keep the project's settings.json and settings.local.json out. No hooks on the first turn or resume, and their permission rules are ignored too. Only caveat is CLAUDE_CONFIG_DIR: anything there counts as user settings, so it needs to live somewhere the agent can't write.
The fixes look good. I could also reproduce both of Copilot's new threads (the exit-status race and the malformed content), so those seem worth fixing here.
cmd.Wait reaps the leader before stdout processing finishes, so a slow sink can leave cleanup holding a numeric process-group ID whose original group has already emptied. If that ID is reused, this unconditional group signal can kill unrelated processes even though p.Signal returns os.ErrProcessDone. Keep the original group identity reserved through cleanup, for example by separating exit observation from leader reaping in turn.go.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Cleanup can signal a reused process-group ID after cmd.Wait reaps the leader, potentially killing unrelated processes.
<details open>
<summary><strong>4 open issues</strong></summary>
</details>
<details>
<summary><strong>2 resolved since last review</strong></summary>
</details>
<sub>Review effort: Balanced</sub>
Fixed. The turn now waits for the leader's exit without reaping it (waitid WNOWAIT on Linux, kqueue NOTE_EXIT on macOS), so every kill of the group, the drain-deadline one included, goes out while the zombie leader still holds the pgid. It reaps only after the final group SIGKILL. Other platforms fall back to the old reap-first order.
When a known tool's result has malformed content (for example, null or an object), this deletes the pending tool before toolContent rejects the event. outcome subsequently calls finish, but the deleted ID is skipped, so the observed tool receives neither its result nor the existing "no result observed" receipt. Validate the content before deleting the tool, and cover a malformed result following a valid tool_use.
Executing this block leaves the shell in integrations/substrate after the first command, so the new command tries to enter integrations/substrate/integrations/claudecode and fails instead of testing the new module. Run each command in a subshell so both paths resolve from the repository root.
<!-- ccr-overview-v2 -->
🟡 Changes recommended
Malformed tool results can remove pending tools before validation, preventing both result and fallback receipts, and the documented test commands fail due to an incorrect working directory.
<details open>
<summary><strong>5 open issues</strong></summary>
</details>
<details>
<summary><strong>1 resolved since last review</strong></summary>
</details>
<sub>Review effort: Balanced</sub>
Reproduced: a valid tool_use followed by a tool_result with null content fails the turn, but that tool gets no record at all, not even "no result observed". Fine to fix here or in a follow-up.
Approved these changes.
gambtho
aramase
Adds
integrations/claudecode, a separate Go module that runs Claude Code as a sessions harness, served by its ownintegrations/claudecode/cmd/harnessnode. The first commit moves the root harnessnode's serving code tointernal/harnessnodeso both binaries share it. It is an unmediated harness: Claude Code owns its model loop, tools and transcript, so there is noMODEL_CALLand no replay determinism, and the harness declaresREQUIRES_MEMORY_SNAPSHOT(ForkSafe=false, Streaming=true).claude -p --output-format stream-json --verbose --include-partial-messagesprocess. The first turn passes--session-id(a UUIDv5 of the session UID plus an attempt counter); later turns pass--resumewith the same id. The id lives in harness memory, so nothing extra is journaled.sink.Report(TOOL_RESULT), notsink.ToolCall, because the host refusesToolCallfrom an unmediated harness. The final text is recorded once asOUTPUT; text deltas are parsed and dropped. Only token counts are recorded as usage.is_error, a non-zero exit, a missingresultor a malformed line fails the turn. Cancellation sends SIGINT, waits a bounded time, then kills the process group. The stdout drain grace counts only time spent waiting on stdout, not time blocked in the sink.--setting-sources user --strict-mcp-config, so a work-dir.mcp.jsonis not loaded. The permission mode is required, andbypassPermissionsalso needs a separate opt-in (Config.AllowBypassPermissionsorHARNESS_CLAUDE_ALLOW_BYPASS_PERMISSIONS=true); setting only one is an error.claudegets an allowlisted environment instead of the node's:PATH,HOME,USER,SHELL,TMPDIR, locale, theANTHROPIC_*key and base URL vars andCLAUDE_CONFIG_DIR, plus names fromHARNESS_CLAUDE_ENV_ALLOWLIST. Proxy and CA variables must be added explicitly.system/init, such as a--resumewhose transcript is gone, logs its exit status and the first stderr line (at most 256 bytes, control characters replaced) to the node log. The prompt and tool content are not logged by the harness.Newrefuses other platforms such as Windows with an unsupported-platform error instead of reporting a cleanup it cannot do. A test checks the refusal and the package doc and changelog say so.docs/harness-authoring.mdnow says this harness implements the rerun check, using an in-memory record of the execution IDs it started.Known limitation: on a runtime that snapshots memory, forking a session that has run a turn creates a child whose every turn fails with
claudecode: session has earlier turns but this harness holds no state for it. The child holds no Claude Code session of its own, and placement does not checkForkSafefor a memory-tier fork (specRT-2). A follow-up issue tracks it; the docs and changelog say the same.Tests run offline against a fake
claudereplaying stream-json fixtures, plus a controller-over-harnesswire test. Three fixtures are scrubbed recordings from Claude Code 2.1.311 (a tool turn, its resume, and a resume of an unknown session);testdata/README.mdhas the capture command and scrub filter. The rest are built from the documented message formats. The replay conformance suite does not apply here, since this harness has no replay, fork or mediated tools.Ran, in the root module and
integrations/claudecode:gofmt -l .,go mod tidywith no diff,go build ./...,go vet ./...,GOOS=windows go vet ./...(new module),go test -race -shuffle=on ./..., golangci-lint, the changelog check,hack/doccheckandhack/check-doc-links.py.