← Back to Pull requests

feat(harness): add a Claude Code harness #247

Merged
aramase merged 58 files (5677 lines) on Nov 09, 2026 19:24 UTC
View on GitHub
aramase aramase commented on Nov 05, 2026 19:44 UTC
Author

Adds integrations/claudecode, a separate Go module that runs Claude Code as a sessions harness, served by its own integrations/claudecode/cmd/harnessnode. The first commit moves the root harnessnode's serving code to internal/harnessnode so both binaries share it. It is an unmediated harness: Claude Code owns its model loop, tools and transcript, so there is no MODEL_CALL and no replay determinism, and the harness declares REQUIRES_MEMORY_SNAPSHOT (ForkSafe=false, Streaming=true).

  • One Exec runs one claude -p --output-format stream-json --verbose --include-partial-messages process. The first turn passes --session-id (a UUIDv5 of the session UID plus an attempt counter); later turns pass --resume with the same id. The id lives in harness memory, so nothing extra is journaled.

  • Tools are recorded with sink.Report (TOOL_RESULT), not sink.ToolCall, because the host refuses ToolCall from an unmediated harness. The final text is recorded once as OUTPUT; text deltas are parsed and dropped. Only token counts are recorded as usage.

  • is_error, a non-zero exit, a missing result or 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.

  • Permissions are pinned: every turn passes --setting-sources user --strict-mcp-config, so a work-dir .mcp.json is not loaded. The permission mode is required, and bypassPermissions also needs a separate opt-in (Config.AllowBypassPermissions or HARNESS_CLAUDE_ALLOW_BYPASS_PERMISSIONS=true); setting only one is an error.

  • claude gets an allowlisted environment instead of the node's: PATH, HOME, USER, SHELL, TMPDIR, locale, the ANTHROPIC_* key and base URL vars and CLAUDE_CONFIG_DIR, plus names from HARNESS_CLAUDE_ENV_ALLOWLIST. Proxy and CA variables must be added explicitly.

  • A turn that fails before system/init, such as a --resume whose 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.

  • The harness is Unix-only: it ends a turn's tool processes by killing the turn's process group, so New refuses 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.md now 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 check ForkSafe for a memory-tier fork (spec RT-2). A follow-up issue tracks it; the docs and changelog say the same.

    Tests run offline against a fake claude replaying 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.md has 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 tidy with no diff, go build ./..., go vet ./..., GOOS=windows go vet ./... (new module), go test -race -shuffle=on ./..., golangci-lint, the changelog check, hack/doccheck and hack/check-doc-links.py.

    Diff: 5677 lines (+5265 / -412) across 58 files Reviewer: gambtho Review duration: 5739m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.77) × (1 − Review Confidence (0.90)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.77 · 5677 lines diff across 58 files
    0.77
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.89 · 5 substantive comment(s)
    0.89
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    90%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    40 items
    Copilot Copilot commented on code on Nov 05, 2026 19:59 UTC
    Code Review
    integrations/claudecode/claudecode.go:1
    @@ -0,0 +1,425 @@
    +// Package claudecode is an unmediated, REQUIRES_MEMORY_SNAPSHOT api.Harness that runs Claude Code
    +// in headless mode. Each Run (one Exec) starts exactly one process:
    +//
    +//	claude -p --output-format stream-json --verbose --include-partial-messages \
    +//	  --permission-mode <mode> (--session-id|--resume) <id> [--model m] [--max-turns n] [--max-budget-usd x]
    +//
    +// with the turn's text inputs on stdin, and maps its stream-json events onto the sink.
    +//
    +// Unmediated: Claude Code owns its model loop, tools and transcript, so model calls originate in
    +// the Claude Code process, not through sink.Model. The journal therefore has no MODEL_CALL record,
    +// the harness has no replay determinism, and it supports no reconstruction replay: the session
    +// survives suspend and resume only through a memory snapshot of the compute that runs it. What the
    +// harness journals is what it can observe:
    +//
    +//   - the turn's final assistant text as Output, once, when the turn ends; a text over 1 MiB is
    +//     recorded as several consecutive Output events. Partial text deltas are parsed and dropped;
    +//     the host's EventSink has no ephemeral delta method.
    +//   - each tool result Claude Code executed as a reported TOOL_RESULT (sink.Report). The host
    +//     refuses sink.ToolCall for a tool the harness executes itself (IN_HARNESS_REPORTED), so tool
    +//     calls are never sent as intents. Receipts are bounded (see History size below).
    +//   - the turn's token counts as one Usage, taken from the result event's usage and attributed to
    +//     the model system/init reports. InputTokens counts uncached, cache-read and cache-write input
    +//     tokens. When no result reports nonzero usage, the Usage holds only the input tokens of the
    +//     turn's main-loop assistant messages (subagent messages excluded) and no output tokens. The
    +//     result's total_cost_usd is not recorded: api.Usage has no cost field. Usage is
    +//     observability, not billing.
    +//
    +// A turn the host cancels records nothing after the cancel: no Output, no Usage, and no
    +// TOOL_RESULT for a tool still running.
    +//
    +// Do not point controller.Replay at this harness: on a fresh instance the first recorded execution
    +// looks like a genuine first turn and runs a real, billed Claude Code turn.
    +//
    +// Claude Code session identity is harness memory. The first turn passes --session-id with a UUID
    +// derived from the sessions session UID and an attempt number; once Claude Code's system/init event
    +// confirms that id, later turns pass --resume with the same id. A first turn that fails before
    +// init moves to the next attempt, so a transcript left by a dead attempt cannot block the session.
    +// Nothing extra is persisted: the memory snapshot carries the id, and the runtime's snapshot must
    +// also preserve the filesystem that holds Claude Code's transcripts. A harness instance that holds
    +// no state for a session whose History already has turns (memory lost, a fork child, or a session
    +// that started on another harness) refuses the turn rather than start an empty conversation. A
    +// re-run of an execution this instance already started fails; an interrupted turn is not retried.
    +//
    +// Credentials: the harness never reads, holds or passes a model key. The child process inherits the
    +// harness's environment; the runtime supplies whatever Claude Code needs there.
    +//
    +// The working directory is trusted input: without --bare, claude -p runs the directory's hooks and
    +// MCP configuration with no trust prompt. The configured permission mode bounds what Claude Code
    +// may do; the host does not. Approvals are not supported.
    +//
    +// History size: the host sends the session's whole prior journal as Start.History, bounded by the
    +// harness server's receive limit (HARNESS_MAX_RECV_MSG_SIZE in cmd/harnessnode). Tool receipts
    +// carry at most 2 KiB of input and 2 KiB of content, and shrink to sizes only once a turn's
    +// receipts pass 128 KiB or History passes half of Config.StartLimit. A long session still grows
    +// History; raise the receive limit and Config.StartLimit together.
    +package claudecode
    +
    +import (
    +	"context"
    +	"crypto/sha1"
    +	"errors"
    +	"fmt"
    +	"log/slog"
    +	"math"
    +	"os"
    +	"os/exec"
    +	"path/filepath"
    +	"strconv"
    +	"strings"
    +	"sync"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +)
    +
    +const (
    +	defaultBinary         = "claude"
    +	defaultInterruptGrace = 10 * time.Second
    +	defaultStartLimit     = 4 << 20 // gRPC's default receive limit
    +	defaultPostResult     = 5 * time.Second
    +	defaultDrainGrace     = time.Second
    +
    +	// maxPromptBytes is Claude Code's documented stdin limit for -p.
    +	maxPromptBytes = 10_000_000
    +)
    +
    +// Config configures the harness. Zero values select the defaults documented per field.
    +type Config struct {
    +	// Binary is the claude executable, a path or a name looked up in PATH. Default "claude".
    +	Binary string
    +	// WorkDir is the directory Claude Code runs in. Required; it must exist.
    +	WorkDir string
    +	// Model, when set, is passed as --model and declared in Descriptor.Models. A Start.Model that
    +	// differs fails the turn. When empty, a nonempty Start.Model is passed instead, else Claude
    +	// Code's own default applies.
    +	Model string
    +	// PermissionMode is passed as --permission-mode. Required: the harness cannot answer
    +	// permission prompts, so the operator chooses the mode explicitly.
    +	PermissionMode string
    +	// MaxTurns, when positive, is passed as --max-turns.
    +	MaxTurns int
    +	// MaxBudgetUSD, when positive, is passed as --max-budget-usd. It caps one turn's spend.
    +	MaxBudgetUSD float64
    +	// InterruptGrace is how long the harness waits after SIGINT before it kills the process
    +	// group. Default 10s.
    +	InterruptGrace time.Duration
    +	// StartLimit is the largest Start message, in bytes, the harness server accepts. It sizes tool
    +	// receipts against History. Default 4 MiB (gRPC's default).
    +	StartLimit int
    +}
    +
    +// Harness is the Claude Code harness. Use New; the zero value is not usable. Its state lives only
    +// in process memory, so it must be a single long-lived instance per process.
    +type Harness struct {
    +	cfg    Config
    +	logger *slog.Logger
    +
    +	// postResultGrace bounds how long the process may run after its result event before the
    +	// harness interrupts it. drainGrace bounds how long the harness waits for stdout to close
    +	// once the process exited or was killed. Fields, not constants, so tests can shorten them.
    +	postResultGrace time.Duration
    +	drainGrace      time.Duration
    +
    +	mu       sync.Mutex
    +	sessions map[string]*sessionState
    +	started  map[string]struct{}
    +}
    +
    +// sessionState is the per-session harness memory.
    +type sessionState struct {
    +	attempt     int  // index into the derived Claude Code session ids
    +	established bool // system/init confirmed the id for attempt; later turns resume it
    +	pending     bool // the id for attempt was handed to a process that did not confirm it
    +	running     bool // a turn is in flight
    +}
    +
    +// New validates cfg and returns a harness.
    +func New(cfg Config) (*Harness, error) {
    +	if cfg.Binary == "" {
    +		cfg.Binary = defaultBinary
    +	}
    +	bin, err := exec.LookPath(cfg.Binary)
    +	if err != nil {
    +		return nil, fmt.Errorf("claudecode: find claude binary: %w", err)
    +	}
    +	cfg.Binary = bin
    +	if cfg.WorkDir == "" {
    +		return nil, errors.New("claudecode: WorkDir is required")
    +	}
    +	dir, err := filepath.Abs(cfg.WorkDir)
    +	if err != nil {
    +		return nil, fmt.Errorf("claudecode: WorkDir: %w", err)
    +	}
    +	if fi, err := os.Stat(dir); err != nil {
    +		return nil, fmt.Errorf("claudecode: WorkDir: %w", err)
    +	} else if !fi.IsDir() {
    +		return nil, fmt.Errorf("claudecode: WorkDir %q is not a directory", dir)
    +	}
    +	cfg.WorkDir = dir
    +	if cfg.PermissionMode == "" {
    +		return nil, errors.New("claudecode: PermissionMode is required")
    +	}
    +	if !argValue(cfg.PermissionMode) {
    +		return nil, fmt.Errorf("claudecode: invalid PermissionMode %q", cfg.PermissionMode)
    +	}
    +	if cfg.Model != "" && !argValue(cfg.Model) {
    +		return nil, fmt.Errorf("claudecode: invalid Model %q", cfg.Model)
    +	}
    +	if cfg.MaxTurns < 0 {
    +		return nil, errors.New("claudecode: MaxTurns must not be negative")
    +	}
    +	if cfg.MaxBudgetUSD < 0 || math.IsNaN(cfg.MaxBudgetUSD) || math.IsInf(cfg.MaxBudgetUSD, 0) {
    +		return nil, errors.New("claudecode: MaxBudgetUSD must be a finite, non-negative number")
    +	}
    +	switch {
    +	case cfg.InterruptGrace < 0:
    +		return nil, errors.New("claudecode: InterruptGrace must not be negative")
    +	case cfg.InterruptGrace == 0:
    +		cfg.InterruptGrace = defaultInterruptGrace
    +	}
    +	switch {
    +	case cfg.StartLimit < 0:
    +		return nil, errors.New("claudecode: StartLimit must not be negative")
    +	case cfg.StartLimit == 0:
    +		cfg.StartLimit = defaultStartLimit
    +	}
    +	return &Harness{
    +		cfg:             cfg,
    +		logger:          slog.Default(),
    +		postResultGrace: defaultPostResult,
    +		drainGrace:      defaultDrainGrace,
    +		sessions:        make(map[string]*sessionState),
    +		started:         make(map[string]struct{}),
    +	}, nil
    +}
    +
    +// argValue reports whether v can follow a flag as its own argument: nonempty, no leading '-' (it
    +// would parse as a flag), and no whitespace or control characters.
    +func argValue(v string) bool {
    +	if v == "" || v[0] == '-' {
    +		return false
    +	}
    +	for _, r := range v {
    +		if r <= ' ' || r == 0x7f {
    +			return false
    +		}
    +	}
    +	return true
    +}
    +
    +// Describe declares REQUIRES_MEMORY_SNAPSHOT (the Claude Code session id lives in harness memory and
    +// the transcript on the compute's filesystem), not ForkSafe (a fork child holds no session of its
    +// own), and Streaming.
    +func (h *Harness) Describe(context.Context) (api.Descriptor, error) {
    +	var models []string
    +	if h.cfg.Model != "" {
    +		models = []string{h.cfg.Model}
    +	}
    +	return api.Descriptor{
    +		ID:      "claudecode",
    +		Version: "1", // bump when execution behavior changes, not for host releases
    +		Models:  models,
    +		Capabilities: api.Capabilities{
    +			Resumability: api.ResumabilityRequiresMemorySnapshot,
    +			ForkSafe:     false,
    +			Streaming:    true,
    +		},
    +	}, nil
    +}
    +
    +// Errors returned by Run. Their text is fixed: the host journals a failed turn's error text.
    +var (
    +	errNoSession     = errors.New("claudecode: start has no session UID")
    +	errRerun         = errors.New("claudecode: execution already started on this harness; an interrupted turn is not retried")
    +	errStateLost     = errors.New("claudecode: session has earlier turns but this harness holds no state for it (memory lost, fork, or harness switch)")
    +	errBusy          = errors.New("claudecode: another turn is running for this session")
    +	errNoPrompt      = errors.New("claudecode: inputs carry no text")
    +	errNonText       = errors.New("claudecode: inputs must be text only")
    +	errPromptSize    = errors.New("claudecode: inputs exceed the 10 MB prompt limit")
    +	errModelMismatch = errors.New("claudecode: requested model is not the configured model")
    +	errModelArg      = errors.New("claudecode: requested model is not a valid model argument")
    +)
    +
    +// Run drives one turn: one claude -p process. It returns nil when Claude Code reports a successful
    +// result, and an error when the result is an error, the process fails or exits without a result,
    +// the stream is malformed, or ctx is cancelled (SIGINT, then a group kill after InterruptGrace).
    +// Start.Config is ignored.
    +func (h *Harness) Run(ctx context.Context, s *api.Start, sink api.EventSink) error {
    +	if s == nil || s.SessionUID == "" {
    +		return errNoSession
    +	}
    +	if err := h.begin(s); err != nil {
    +		return err
    +	}
    +	established := false
    +	defer func() { h.end(s.SessionUID, established) }()
    +
    +	prompt, err := promptText(s.Inputs)
    +	if err != nil {
    +		return err
    +	}
    +	model, err := h.turnModel(s.Model)
    +	if err != nil {
    +		return err
    +	}
    +	flag, id := h.sessionArg(s.SessionUID)
    +	t := &turn{
    +		h:         h,
    +		sink:      sink,
    +		sessionID: id,
    +		model:     model,
    +		receipts:  h.receiptMode(s),
    +	}
    +	err = t.run(ctx, h.args(flag, id, model), prompt)

    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.

    Copilot Copilot commented on code on Nov 05, 2026 19:59 UTC
    Code Review
    integrations/claudecode/turn.go:1
    @@ -0,0 +1,571 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"os"
    +	"os/exec"
    +	"strings"
    +	"time"
    +	"unicode/utf8"
    +
    +	"google.golang.org/protobuf/proto"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/wire"
    +)
    +
    +const (
    +	// maxLineBytes bounds one stream-json line. A longer line fails the turn as malformed.
    +	maxLineBytes = 16 << 20
    +	// receiptFieldBytes bounds the tool input and the tool content a full receipt carries.
    +	receiptFieldBytes = 2 << 10
    +	// turnReceiptBudget bounds one turn's full receipts; later receipts in the turn are minimal.
    +	turnReceiptBudget = 128 << 10
    +	// outputChunkBytes bounds one Output call, well under gRPC's default 4 MiB frame limit.
    +	outputChunkBytes = 1 << 20
    +)
    +
    +var (
    +	errMalformed       = errors.New("claudecode: malformed stream-json from claude")
    +	errNoInit          = errors.New("claudecode: claude stream has events before system/init")
    +	errSessionMismatch = errors.New("claudecode: claude reported a different session id")
    +	errNoResult        = errors.New("claudecode: claude stream ended without a result")
    +)
    +
    +// streamLine is one stream-json event. Only the fields the harness maps are decoded; unknown
    +// event types and fields are ignored.
    +type streamLine struct {
    +	Type            string          `json:"type"`
    +	Subtype         string          `json:"subtype"`
    +	SessionID       string          `json:"session_id"`
    +	Model           string          `json:"model"`
    +	ParentToolUseID string          `json:"parent_tool_use_id"`
    +	Message         json.RawMessage `json:"message"`
    +	IsError         bool            `json:"is_error"`
    +	Result          string          `json:"result"`
    +	Usage           *tokenUsage     `json:"usage"`
    +}
    +
    +// message is the Anthropic-shaped message inside assistant and user events. Content is a string or
    +// an array of blocks.
    +type message struct {
    +	ID      string          `json:"id"`
    +	Content json.RawMessage `json:"content"`
    +	Usage   *tokenUsage     `json:"usage"`
    +}
    +
    +type contentBlock struct {
    +	Type      string          `json:"type"`
    +	Text      string          `json:"text"`
    +	ID        string          `json:"id"`
    +	Name      string          `json:"name"`
    +	Input     json.RawMessage `json:"input"`
    +	ToolUseID string          `json:"tool_use_id"`
    +	Content   json.RawMessage `json:"content"`
    +	IsError   bool            `json:"is_error"`
    +}
    +
    +type tokenUsage struct {
    +	InputTokens              int64 `json:"input_tokens"`
    +	OutputTokens             int64 `json:"output_tokens"`
    +	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
    +	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
    +}
    +
    +func (u *tokenUsage) valid() bool {
    +	return u.InputTokens >= 0 && u.OutputTokens >= 0 && u.CacheCreationInputTokens >= 0 && u.CacheReadInputTokens >= 0
    +}
    +
    +// input is every input token the model processed: uncached, cache reads and cache writes.
    +func (u *tokenUsage) input() int64 {
    +	return u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens
    +}
    +
    +type toolUse struct {
    +	name   string
    +	input  json.RawMessage
    +	parent string
    +}
    +
    +// turn is one Run's process and stream state. Only the goroutine running run touches it.
    +type turn struct {
    +	h         *Harness
    +	sink      api.EventSink
    +	sessionID string
    +	model     string
    +	receipts  bool // full receipts; false once the session or turn budget is spent
    +
    +	receiptBytes int
    +	initSeen     bool
    +	initModel    string
    +	tools        map[string]toolUse
    +	toolOrder    []string
    +	seenMsgs     map[string]struct{}
    +	recovered    tokenUsage // main-loop assistant usage, deduplicated by message id
    +	result       *streamLine
    +	sinkErr      error
    +}
    +
    +// receiptMode reports whether full receipts are allowed this turn: History, sized as the wire sends
    +// it, is under half of StartLimit. It warns once History reaches three quarters of it.
    +func (h *Harness) receiptMode(s *api.Start) bool {
    +	n := 0
    +	for _, e := range s.History {
    +		n += proto.Size(wire.EventToProto(e))
    +	}
    +	if n >= h.cfg.StartLimit/4*3 {
    +		h.logger.Warn("claudecode: session history nears the harness receive limit; raise the limit and Config.StartLimit",
    +			"session_uid", s.SessionUID, "history_bytes", n, "start_limit", h.cfg.StartLimit)
    +	}
    +	return n < h.cfg.StartLimit/2
    +}
    +
    +type readResult struct {
    +	line []byte
    +	err  error
    +}
    +
    +// Process phases. Each later phase is entered at most once, in order.
    +const (
    +	phaseRunning     = iota
    +	phaseSettling    // result seen or stdout closed: the process gets postResultGrace to exit
    +	phaseInterrupted // SIGINT sent: the process gets InterruptGrace to exit
    +	phaseKilled      // the group was killed, or the leader exited: stdout gets drainGrace to close
    +)
    +
    +// run starts the process, maps its stream, and returns the turn's outcome.
    +func (t *turn) run(ctx context.Context, args []string, prompt string) error {
    +	t.tools = make(map[string]toolUse)
    +	t.seenMsgs = make(map[string]struct{})
    +
    +	r, w, err := os.Pipe()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = r.Close() }()
    +	cmd := exec.Command(t.h.cfg.Binary, args...)
    +	cmd.Dir = t.h.cfg.WorkDir
    +	cmd.Stdin = strings.NewReader(prompt)
    +	cmd.Stdout = w
    +	// stderr is discarded: it can carry prompt or tool text, which must not reach errors or logs.
    +	cmd.SysProcAttr = sysProcAttr()
    +	cmd.WaitDelay = t.h.drainGrace
    +	err = cmd.Start()
    +	_ = w.Close() // the child holds its own copy
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +
    +	lines := make(chan readResult)
    +	go readLines(r, lines)
    +	exited := make(chan struct{})
    +	go func() {
    +		_ = cmd.Wait() // the outcome is read from cmd.ProcessState
    +		close(exited)
    +	}()
    +
    +	var (
    +		phase    = phaseRunning
    +		deadline <-chan time.Time
    +		done     = ctx.Done()
    +		eof      bool
    +		exitSeen bool
    +		forced   bool // the harness closed stdout itself
    +		signaled bool // the harness signalled the process, so its exit status is not its own verdict
    +		failErr  error
    +	)
    +	enter := func(p int, d time.Duration) {
    +		phase = p
    +		deadline = time.After(d)
    +	}
    +	interrupt := func() {
    +		if phase >= phaseInterrupted {
    +			return
    +		}
    +		interruptProcess(cmd.Process)
    +		signaled = true
    +		enter(phaseInterrupted, t.h.cfg.InterruptGrace)
    +	}
    +	for !eof || !exitSeen {

    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.

    Copilot Copilot commented on code on Nov 05, 2026 19:59 UTC
    Code Review
    harness/claudecode/claudecode.go:1
    @@ -0,0 +1,425 @@
    +// Package claudecode is an unmediated, REQUIRES_MEMORY_SNAPSHOT api.Harness that runs Claude Code
    +// in headless mode. Each Run (one Exec) starts exactly one process:
    +//
    +//	claude -p --output-format stream-json --verbose --include-partial-messages \
    +//	  --permission-mode <mode> (--session-id|--resume) <id> [--model m] [--max-turns n] [--max-budget-usd x]
    +//
    +// with the turn's text inputs on stdin, and maps its stream-json events onto the sink.
    +//
    +// Unmediated: Claude Code owns its model loop, tools and transcript, so model calls originate in
    +// the Claude Code process, not through sink.Model. The journal therefore has no MODEL_CALL record,
    +// the harness has no replay determinism, and it supports no reconstruction replay: the session
    +// survives suspend and resume only through a memory snapshot of the compute that runs it. What the
    +// harness journals is what it can observe:
    +//
    +//   - the turn's final assistant text as Output, once, when the turn ends; a text over 1 MiB is
    +//     recorded as several consecutive Output events. Partial text deltas are parsed and dropped;
    +//     the host's EventSink has no ephemeral delta method.
    +//   - each tool result Claude Code executed as a reported TOOL_RESULT (sink.Report). The host
    +//     refuses sink.ToolCall for a tool the harness executes itself (IN_HARNESS_REPORTED), so tool
    +//     calls are never sent as intents. Receipts are bounded (see History size below).
    +//   - the turn's token counts as one Usage, taken from the result event's usage and attributed to
    +//     the model system/init reports. InputTokens counts uncached, cache-read and cache-write input
    +//     tokens. When no result reports nonzero usage, the Usage holds only the input tokens of the
    +//     turn's main-loop assistant messages (subagent messages excluded) and no output tokens. The
    +//     result's total_cost_usd is not recorded: api.Usage has no cost field. Usage is
    +//     observability, not billing.
    +//
    +// A turn the host cancels records nothing after the cancel: no Output, no Usage, and no
    +// TOOL_RESULT for a tool still running.
    +//
    +// Do not point controller.Replay at this harness: on a fresh instance the first recorded execution
    +// looks like a genuine first turn and runs a real, billed Claude Code turn.
    +//
    +// Claude Code session identity is harness memory. The first turn passes --session-id with a UUID
    +// derived from the sessions session UID and an attempt number; once Claude Code's system/init event
    +// confirms that id, later turns pass --resume with the same id. A first turn that fails before
    +// init moves to the next attempt, so a transcript left by a dead attempt cannot block the session.
    +// Nothing extra is persisted: the memory snapshot carries the id, and the runtime's snapshot must
    +// also preserve the filesystem that holds Claude Code's transcripts. A harness instance that holds
    +// no state for a session whose History already has turns (memory lost, a fork child, or a session
    +// that started on another harness) refuses the turn rather than start an empty conversation. A
    +// re-run of an execution this instance already started fails; an interrupted turn is not retried.
    +//
    +// Credentials: the harness never reads, holds or passes a model key. The child process inherits the
    +// harness's environment; the runtime supplies whatever Claude Code needs there.
    +//
    +// The working directory is trusted input: without --bare, claude -p runs the directory's hooks and
    +// MCP configuration with no trust prompt. The configured permission mode bounds what Claude Code
    +// may do; the host does not. Approvals are not supported.
    +//
    +// History size: the host sends the session's whole prior journal as Start.History, bounded by the
    +// harness server's receive limit (HARNESS_MAX_RECV_MSG_SIZE in cmd/harnessnode). Tool receipts
    +// carry at most 2 KiB of input and 2 KiB of content, and shrink to sizes only once a turn's
    +// receipts pass 128 KiB or History passes half of Config.StartLimit. A long session still grows
    +// History; raise the receive limit and Config.StartLimit together.
    +package claudecode
    +
    +import (
    +	"context"
    +	"crypto/sha1"
    +	"errors"
    +	"fmt"
    +	"log/slog"
    +	"math"
    +	"os"
    +	"os/exec"
    +	"path/filepath"
    +	"strconv"
    +	"strings"
    +	"sync"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +)
    +
    +const (
    +	defaultBinary         = "claude"
    +	defaultInterruptGrace = 10 * time.Second
    +	defaultStartLimit     = 4 << 20 // gRPC's default receive limit
    +	defaultPostResult     = 5 * time.Second
    +	defaultDrainGrace     = time.Second
    +
    +	// maxPromptBytes is Claude Code's documented stdin limit for -p.
    +	maxPromptBytes = 10_000_000
    +)
    +
    +// Config configures the harness. Zero values select the defaults documented per field.
    +type Config struct {
    +	// Binary is the claude executable, a path or a name looked up in PATH. Default "claude".
    +	Binary string
    +	// WorkDir is the directory Claude Code runs in. Required; it must exist.
    +	WorkDir string
    +	// Model, when set, is passed as --model and declared in Descriptor.Models. A Start.Model that
    +	// differs fails the turn. When empty, a nonempty Start.Model is passed instead, else Claude
    +	// Code's own default applies.
    +	Model string
    +	// PermissionMode is passed as --permission-mode. Required: the harness cannot answer
    +	// permission prompts, so the operator chooses the mode explicitly.
    +	PermissionMode string
    +	// MaxTurns, when positive, is passed as --max-turns.
    +	MaxTurns int
    +	// MaxBudgetUSD, when positive, is passed as --max-budget-usd. It caps one turn's spend.
    +	MaxBudgetUSD float64
    +	// InterruptGrace is how long the harness waits after SIGINT before it kills the process
    +	// group. Default 10s.
    +	InterruptGrace time.Duration
    +	// StartLimit is the largest Start message, in bytes, the harness server accepts. It sizes tool
    +	// receipts against History. Default 4 MiB (gRPC's default).
    +	StartLimit int
    +}
    +
    +// Harness is the Claude Code harness. Use New; the zero value is not usable. Its state lives only
    +// in process memory, so it must be a single long-lived instance per process.
    +type Harness struct {
    +	cfg    Config
    +	logger *slog.Logger
    +
    +	// postResultGrace bounds how long the process may run after its result event before the
    +	// harness interrupts it. drainGrace bounds how long the harness waits for stdout to close
    +	// once the process exited or was killed. Fields, not constants, so tests can shorten them.
    +	postResultGrace time.Duration
    +	drainGrace      time.Duration
    +
    +	mu       sync.Mutex
    +	sessions map[string]*sessionState
    +	started  map[string]struct{}
    +}
    +
    +// sessionState is the per-session harness memory.
    +type sessionState struct {
    +	attempt     int  // index into the derived Claude Code session ids
    +	established bool // system/init confirmed the id for attempt; later turns resume it
    +	pending     bool // the id for attempt was handed to a process that did not confirm it
    +	running     bool // a turn is in flight
    +}
    +
    +// New validates cfg and returns a harness.
    +func New(cfg Config) (*Harness, error) {
    +	if cfg.Binary == "" {
    +		cfg.Binary = defaultBinary
    +	}
    +	bin, err := exec.LookPath(cfg.Binary)
    +	if err != nil {
    +		return nil, fmt.Errorf("claudecode: find claude binary: %w", err)
    +	}
    +	cfg.Binary = bin

    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.

    Copilot Copilot commented on code on Nov 05, 2026 19:59 UTC
    Code Review
    harness/claudecode/turn.go:1
    @@ -0,0 +1,571 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"os"
    +	"os/exec"
    +	"strings"
    +	"time"
    +	"unicode/utf8"
    +
    +	"google.golang.org/protobuf/proto"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/wire"
    +)
    +
    +const (
    +	// maxLineBytes bounds one stream-json line. A longer line fails the turn as malformed.
    +	maxLineBytes = 16 << 20
    +	// receiptFieldBytes bounds the tool input and the tool content a full receipt carries.
    +	receiptFieldBytes = 2 << 10
    +	// turnReceiptBudget bounds one turn's full receipts; later receipts in the turn are minimal.
    +	turnReceiptBudget = 128 << 10
    +	// outputChunkBytes bounds one Output call, well under gRPC's default 4 MiB frame limit.
    +	outputChunkBytes = 1 << 20
    +)
    +
    +var (
    +	errMalformed       = errors.New("claudecode: malformed stream-json from claude")
    +	errNoInit          = errors.New("claudecode: claude stream has events before system/init")
    +	errSessionMismatch = errors.New("claudecode: claude reported a different session id")
    +	errNoResult        = errors.New("claudecode: claude stream ended without a result")
    +)
    +
    +// streamLine is one stream-json event. Only the fields the harness maps are decoded; unknown
    +// event types and fields are ignored.
    +type streamLine struct {
    +	Type            string          `json:"type"`
    +	Subtype         string          `json:"subtype"`
    +	SessionID       string          `json:"session_id"`
    +	Model           string          `json:"model"`
    +	ParentToolUseID string          `json:"parent_tool_use_id"`
    +	Message         json.RawMessage `json:"message"`
    +	IsError         bool            `json:"is_error"`
    +	Result          string          `json:"result"`
    +	Usage           *tokenUsage     `json:"usage"`
    +}
    +
    +// message is the Anthropic-shaped message inside assistant and user events. Content is a string or
    +// an array of blocks.
    +type message struct {
    +	ID      string          `json:"id"`
    +	Content json.RawMessage `json:"content"`
    +	Usage   *tokenUsage     `json:"usage"`
    +}
    +
    +type contentBlock struct {
    +	Type      string          `json:"type"`
    +	Text      string          `json:"text"`
    +	ID        string          `json:"id"`
    +	Name      string          `json:"name"`
    +	Input     json.RawMessage `json:"input"`
    +	ToolUseID string          `json:"tool_use_id"`
    +	Content   json.RawMessage `json:"content"`
    +	IsError   bool            `json:"is_error"`
    +}
    +
    +type tokenUsage struct {
    +	InputTokens              int64 `json:"input_tokens"`
    +	OutputTokens             int64 `json:"output_tokens"`
    +	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
    +	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
    +}
    +
    +func (u *tokenUsage) valid() bool {
    +	return u.InputTokens >= 0 && u.OutputTokens >= 0 && u.CacheCreationInputTokens >= 0 && u.CacheReadInputTokens >= 0
    +}
    +
    +// input is every input token the model processed: uncached, cache reads and cache writes.
    +func (u *tokenUsage) input() int64 {
    +	return u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens
    +}
    +
    +type toolUse struct {
    +	name   string
    +	input  json.RawMessage
    +	parent string
    +}
    +
    +// turn is one Run's process and stream state. Only the goroutine running run touches it.
    +type turn struct {
    +	h         *Harness
    +	sink      api.EventSink
    +	sessionID string
    +	model     string
    +	receipts  bool // full receipts; false once the session or turn budget is spent
    +
    +	receiptBytes int
    +	initSeen     bool
    +	initModel    string
    +	tools        map[string]toolUse
    +	toolOrder    []string
    +	seenMsgs     map[string]struct{}
    +	recovered    tokenUsage // main-loop assistant usage, deduplicated by message id
    +	result       *streamLine
    +	sinkErr      error
    +}
    +
    +// receiptMode reports whether full receipts are allowed this turn: History, sized as the wire sends
    +// it, is under half of StartLimit. It warns once History reaches three quarters of it.
    +func (h *Harness) receiptMode(s *api.Start) bool {
    +	n := 0
    +	for _, e := range s.History {
    +		n += proto.Size(wire.EventToProto(e))
    +	}
    +	if n >= h.cfg.StartLimit/4*3 {
    +		h.logger.Warn("claudecode: session history nears the harness receive limit; raise the limit and Config.StartLimit",
    +			"session_uid", s.SessionUID, "history_bytes", n, "start_limit", h.cfg.StartLimit)
    +	}
    +	return n < h.cfg.StartLimit/2
    +}
    +
    +type readResult struct {
    +	line []byte
    +	err  error
    +}
    +
    +// Process phases. Each later phase is entered at most once, in order.
    +const (
    +	phaseRunning     = iota
    +	phaseSettling    // result seen or stdout closed: the process gets postResultGrace to exit
    +	phaseInterrupted // SIGINT sent: the process gets InterruptGrace to exit
    +	phaseKilled      // the group was killed, or the leader exited: stdout gets drainGrace to close
    +)
    +
    +// run starts the process, maps its stream, and returns the turn's outcome.
    +func (t *turn) run(ctx context.Context, args []string, prompt string) error {
    +	t.tools = make(map[string]toolUse)
    +	t.seenMsgs = make(map[string]struct{})
    +
    +	r, w, err := os.Pipe()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = r.Close() }()
    +	cmd := exec.Command(t.h.cfg.Binary, args...)
    +	cmd.Dir = t.h.cfg.WorkDir
    +	cmd.Stdin = strings.NewReader(prompt)
    +	cmd.Stdout = w
    +	// stderr is discarded: it can carry prompt or tool text, which must not reach errors or logs.
    +	cmd.SysProcAttr = sysProcAttr()
    +	cmd.WaitDelay = t.h.drainGrace
    +	err = cmd.Start()
    +	_ = w.Close() // the child holds its own copy
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +
    +	lines := make(chan readResult)
    +	go readLines(r, lines)
    +	exited := make(chan struct{})
    +	go func() {
    +		_ = cmd.Wait() // the outcome is read from cmd.ProcessState
    +		close(exited)
    +	}()
    +
    +	var (
    +		phase    = phaseRunning
    +		deadline <-chan time.Time
    +		done     = ctx.Done()
    +		eof      bool
    +		exitSeen bool
    +		forced   bool // the harness closed stdout itself
    +		signaled bool // the harness signalled the process, so its exit status is not its own verdict
    +		failErr  error
    +	)
    +	enter := func(p int, d time.Duration) {
    +		phase = p
    +		deadline = time.After(d)
    +	}
    +	interrupt := func() {
    +		if phase >= phaseInterrupted {
    +			return
    +		}
    +		interruptProcess(cmd.Process)
    +		signaled = true
    +		enter(phaseInterrupted, t.h.cfg.InterruptGrace)
    +	}
    +	for !eof || !exitSeen {
    +		select {
    +		case m, ok := <-lines:
    +			switch {
    +			case !ok:
    +				lines, eof = nil, true
    +				if phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			case m.err != nil:
    +				if !forced && failErr == nil {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			case failErr != nil || ctx.Err() != nil || t.result != nil:
    +				// Stopping, or past the result: drain.

    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.

    Copilot Copilot commented on code on Nov 05, 2026 19:59 UTC
    Code Review
    cmd/harnessnode/main.go:1
    @@ -37,6 +38,7 @@ import (
     	"github.com/agent-primitives/sessions/api"
     	v1 "github.com/agent-primitives/sessions/api/genpb"
     	"github.com/agent-primitives/sessions/harness/chatagent"
    +	"github.com/agent-primitives/sessions/harness/claudecode"

    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.

    Copilot Copilot commented on code on Nov 05, 2026 19:59 UTC
    Code Review
    harness/claudecode/claudecode.go:1
    @@ -0,0 +1,425 @@
    +// Package claudecode is an unmediated, REQUIRES_MEMORY_SNAPSHOT api.Harness that runs Claude Code
    +// in headless mode. Each Run (one Exec) starts exactly one process:
    +//
    +//	claude -p --output-format stream-json --verbose --include-partial-messages \
    +//	  --permission-mode <mode> (--session-id|--resume) <id> [--model m] [--max-turns n] [--max-budget-usd x]
    +//
    +// with the turn's text inputs on stdin, and maps its stream-json events onto the sink.
    +//
    +// Unmediated: Claude Code owns its model loop, tools and transcript, so model calls originate in
    +// the Claude Code process, not through sink.Model. The journal therefore has no MODEL_CALL record,
    +// the harness has no replay determinism, and it supports no reconstruction replay: the session
    +// survives suspend and resume only through a memory snapshot of the compute that runs it. What the

    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.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 05, 2026 19:59 UTC
    Reviewer

    <!-- 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>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Replay launches a billed turn before rejecting empty history · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Leader exit can leave redirected tool subprocesses running · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Resolve relative binary paths before changing the working directory · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Validate stream lines after a success result · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Move the Claude Code adapter out of the core module · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Update published contracts for unmediated harness behavior · New

  • </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:

  • Runs one Claude Code process per execution, with session resume and bounded shutdown handling.

  • Maps stream-json events to final output, bounded tool receipts, and token usage.

  • Adds environment configuration, offline fixtures, unit tests, and controller-over-harnesswire coverage.
  • | 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>

    aramase aramase commented on code on Nov 05, 2026 22:57 UTC
    Code Review
    integrations/claudecode/turn.go:1
    @@ -0,0 +1,571 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"os"
    +	"os/exec"
    +	"strings"
    +	"time"
    +	"unicode/utf8"
    +
    +	"google.golang.org/protobuf/proto"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/wire"
    +)
    +
    +const (
    +	// maxLineBytes bounds one stream-json line. A longer line fails the turn as malformed.
    +	maxLineBytes = 16 << 20
    +	// receiptFieldBytes bounds the tool input and the tool content a full receipt carries.
    +	receiptFieldBytes = 2 << 10
    +	// turnReceiptBudget bounds one turn's full receipts; later receipts in the turn are minimal.
    +	turnReceiptBudget = 128 << 10
    +	// outputChunkBytes bounds one Output call, well under gRPC's default 4 MiB frame limit.
    +	outputChunkBytes = 1 << 20
    +)
    +
    +var (
    +	errMalformed       = errors.New("claudecode: malformed stream-json from claude")
    +	errNoInit          = errors.New("claudecode: claude stream has events before system/init")
    +	errSessionMismatch = errors.New("claudecode: claude reported a different session id")
    +	errNoResult        = errors.New("claudecode: claude stream ended without a result")
    +)
    +
    +// streamLine is one stream-json event. Only the fields the harness maps are decoded; unknown
    +// event types and fields are ignored.
    +type streamLine struct {
    +	Type            string          `json:"type"`
    +	Subtype         string          `json:"subtype"`
    +	SessionID       string          `json:"session_id"`
    +	Model           string          `json:"model"`
    +	ParentToolUseID string          `json:"parent_tool_use_id"`
    +	Message         json.RawMessage `json:"message"`
    +	IsError         bool            `json:"is_error"`
    +	Result          string          `json:"result"`
    +	Usage           *tokenUsage     `json:"usage"`
    +}
    +
    +// message is the Anthropic-shaped message inside assistant and user events. Content is a string or
    +// an array of blocks.
    +type message struct {
    +	ID      string          `json:"id"`
    +	Content json.RawMessage `json:"content"`
    +	Usage   *tokenUsage     `json:"usage"`
    +}
    +
    +type contentBlock struct {
    +	Type      string          `json:"type"`
    +	Text      string          `json:"text"`
    +	ID        string          `json:"id"`
    +	Name      string          `json:"name"`
    +	Input     json.RawMessage `json:"input"`
    +	ToolUseID string          `json:"tool_use_id"`
    +	Content   json.RawMessage `json:"content"`
    +	IsError   bool            `json:"is_error"`
    +}
    +
    +type tokenUsage struct {
    +	InputTokens              int64 `json:"input_tokens"`
    +	OutputTokens             int64 `json:"output_tokens"`
    +	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
    +	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
    +}
    +
    +func (u *tokenUsage) valid() bool {
    +	return u.InputTokens >= 0 && u.OutputTokens >= 0 && u.CacheCreationInputTokens >= 0 && u.CacheReadInputTokens >= 0
    +}
    +
    +// input is every input token the model processed: uncached, cache reads and cache writes.
    +func (u *tokenUsage) input() int64 {
    +	return u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens
    +}
    +
    +type toolUse struct {
    +	name   string
    +	input  json.RawMessage
    +	parent string
    +}
    +
    +// turn is one Run's process and stream state. Only the goroutine running run touches it.
    +type turn struct {
    +	h         *Harness
    +	sink      api.EventSink
    +	sessionID string
    +	model     string
    +	receipts  bool // full receipts; false once the session or turn budget is spent
    +
    +	receiptBytes int
    +	initSeen     bool
    +	initModel    string
    +	tools        map[string]toolUse
    +	toolOrder    []string
    +	seenMsgs     map[string]struct{}
    +	recovered    tokenUsage // main-loop assistant usage, deduplicated by message id
    +	result       *streamLine
    +	sinkErr      error
    +}
    +
    +// receiptMode reports whether full receipts are allowed this turn: History, sized as the wire sends
    +// it, is under half of StartLimit. It warns once History reaches three quarters of it.
    +func (h *Harness) receiptMode(s *api.Start) bool {
    +	n := 0
    +	for _, e := range s.History {
    +		n += proto.Size(wire.EventToProto(e))
    +	}
    +	if n >= h.cfg.StartLimit/4*3 {
    +		h.logger.Warn("claudecode: session history nears the harness receive limit; raise the limit and Config.StartLimit",
    +			"session_uid", s.SessionUID, "history_bytes", n, "start_limit", h.cfg.StartLimit)
    +	}
    +	return n < h.cfg.StartLimit/2
    +}
    +
    +type readResult struct {
    +	line []byte
    +	err  error
    +}
    +
    +// Process phases. Each later phase is entered at most once, in order.
    +const (
    +	phaseRunning     = iota
    +	phaseSettling    // result seen or stdout closed: the process gets postResultGrace to exit
    +	phaseInterrupted // SIGINT sent: the process gets InterruptGrace to exit
    +	phaseKilled      // the group was killed, or the leader exited: stdout gets drainGrace to close
    +)
    +
    +// run starts the process, maps its stream, and returns the turn's outcome.
    +func (t *turn) run(ctx context.Context, args []string, prompt string) error {
    +	t.tools = make(map[string]toolUse)
    +	t.seenMsgs = make(map[string]struct{})
    +
    +	r, w, err := os.Pipe()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = r.Close() }()
    +	cmd := exec.Command(t.h.cfg.Binary, args...)
    +	cmd.Dir = t.h.cfg.WorkDir
    +	cmd.Stdin = strings.NewReader(prompt)
    +	cmd.Stdout = w
    +	// stderr is discarded: it can carry prompt or tool text, which must not reach errors or logs.
    +	cmd.SysProcAttr = sysProcAttr()
    +	cmd.WaitDelay = t.h.drainGrace
    +	err = cmd.Start()
    +	_ = w.Close() // the child holds its own copy
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +
    +	lines := make(chan readResult)
    +	go readLines(r, lines)
    +	exited := make(chan struct{})
    +	go func() {
    +		_ = cmd.Wait() // the outcome is read from cmd.ProcessState
    +		close(exited)
    +	}()
    +
    +	var (
    +		phase    = phaseRunning
    +		deadline <-chan time.Time
    +		done     = ctx.Done()
    +		eof      bool
    +		exitSeen bool
    +		forced   bool // the harness closed stdout itself
    +		signaled bool // the harness signalled the process, so its exit status is not its own verdict
    +		failErr  error
    +	)
    +	enter := func(p int, d time.Duration) {
    +		phase = p
    +		deadline = time.After(d)
    +	}
    +	interrupt := func() {
    +		if phase >= phaseInterrupted {
    +			return
    +		}
    +		interruptProcess(cmd.Process)
    +		signaled = true
    +		enter(phaseInterrupted, t.h.cfg.InterruptGrace)
    +	}
    +	for !eof || !exitSeen {

    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.

    aramase aramase commented on code on Nov 05, 2026 22:57 UTC
    Code Review
    harness/claudecode/claudecode.go:1
    @@ -0,0 +1,425 @@
    +// Package claudecode is an unmediated, REQUIRES_MEMORY_SNAPSHOT api.Harness that runs Claude Code
    +// in headless mode. Each Run (one Exec) starts exactly one process:
    +//
    +//	claude -p --output-format stream-json --verbose --include-partial-messages \
    +//	  --permission-mode <mode> (--session-id|--resume) <id> [--model m] [--max-turns n] [--max-budget-usd x]
    +//
    +// with the turn's text inputs on stdin, and maps its stream-json events onto the sink.
    +//
    +// Unmediated: Claude Code owns its model loop, tools and transcript, so model calls originate in
    +// the Claude Code process, not through sink.Model. The journal therefore has no MODEL_CALL record,
    +// the harness has no replay determinism, and it supports no reconstruction replay: the session
    +// survives suspend and resume only through a memory snapshot of the compute that runs it. What the
    +// harness journals is what it can observe:
    +//
    +//   - the turn's final assistant text as Output, once, when the turn ends; a text over 1 MiB is
    +//     recorded as several consecutive Output events. Partial text deltas are parsed and dropped;
    +//     the host's EventSink has no ephemeral delta method.
    +//   - each tool result Claude Code executed as a reported TOOL_RESULT (sink.Report). The host
    +//     refuses sink.ToolCall for a tool the harness executes itself (IN_HARNESS_REPORTED), so tool
    +//     calls are never sent as intents. Receipts are bounded (see History size below).
    +//   - the turn's token counts as one Usage, taken from the result event's usage and attributed to
    +//     the model system/init reports. InputTokens counts uncached, cache-read and cache-write input
    +//     tokens. When no result reports nonzero usage, the Usage holds only the input tokens of the
    +//     turn's main-loop assistant messages (subagent messages excluded) and no output tokens. The
    +//     result's total_cost_usd is not recorded: api.Usage has no cost field. Usage is
    +//     observability, not billing.
    +//
    +// A turn the host cancels records nothing after the cancel: no Output, no Usage, and no
    +// TOOL_RESULT for a tool still running.
    +//
    +// Do not point controller.Replay at this harness: on a fresh instance the first recorded execution
    +// looks like a genuine first turn and runs a real, billed Claude Code turn.
    +//
    +// Claude Code session identity is harness memory. The first turn passes --session-id with a UUID
    +// derived from the sessions session UID and an attempt number; once Claude Code's system/init event
    +// confirms that id, later turns pass --resume with the same id. A first turn that fails before
    +// init moves to the next attempt, so a transcript left by a dead attempt cannot block the session.
    +// Nothing extra is persisted: the memory snapshot carries the id, and the runtime's snapshot must
    +// also preserve the filesystem that holds Claude Code's transcripts. A harness instance that holds
    +// no state for a session whose History already has turns (memory lost, a fork child, or a session
    +// that started on another harness) refuses the turn rather than start an empty conversation. A
    +// re-run of an execution this instance already started fails; an interrupted turn is not retried.
    +//
    +// Credentials: the harness never reads, holds or passes a model key. The child process inherits the
    +// harness's environment; the runtime supplies whatever Claude Code needs there.
    +//
    +// The working directory is trusted input: without --bare, claude -p runs the directory's hooks and
    +// MCP configuration with no trust prompt. The configured permission mode bounds what Claude Code
    +// may do; the host does not. Approvals are not supported.
    +//
    +// History size: the host sends the session's whole prior journal as Start.History, bounded by the
    +// harness server's receive limit (HARNESS_MAX_RECV_MSG_SIZE in cmd/harnessnode). Tool receipts
    +// carry at most 2 KiB of input and 2 KiB of content, and shrink to sizes only once a turn's
    +// receipts pass 128 KiB or History passes half of Config.StartLimit. A long session still grows
    +// History; raise the receive limit and Config.StartLimit together.
    +package claudecode
    +
    +import (
    +	"context"
    +	"crypto/sha1"
    +	"errors"
    +	"fmt"
    +	"log/slog"
    +	"math"
    +	"os"
    +	"os/exec"
    +	"path/filepath"
    +	"strconv"
    +	"strings"
    +	"sync"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +)
    +
    +const (
    +	defaultBinary         = "claude"
    +	defaultInterruptGrace = 10 * time.Second
    +	defaultStartLimit     = 4 << 20 // gRPC's default receive limit
    +	defaultPostResult     = 5 * time.Second
    +	defaultDrainGrace     = time.Second
    +
    +	// maxPromptBytes is Claude Code's documented stdin limit for -p.
    +	maxPromptBytes = 10_000_000
    +)
    +
    +// Config configures the harness. Zero values select the defaults documented per field.
    +type Config struct {
    +	// Binary is the claude executable, a path or a name looked up in PATH. Default "claude".
    +	Binary string
    +	// WorkDir is the directory Claude Code runs in. Required; it must exist.
    +	WorkDir string
    +	// Model, when set, is passed as --model and declared in Descriptor.Models. A Start.Model that
    +	// differs fails the turn. When empty, a nonempty Start.Model is passed instead, else Claude
    +	// Code's own default applies.
    +	Model string
    +	// PermissionMode is passed as --permission-mode. Required: the harness cannot answer
    +	// permission prompts, so the operator chooses the mode explicitly.
    +	PermissionMode string
    +	// MaxTurns, when positive, is passed as --max-turns.
    +	MaxTurns int
    +	// MaxBudgetUSD, when positive, is passed as --max-budget-usd. It caps one turn's spend.
    +	MaxBudgetUSD float64
    +	// InterruptGrace is how long the harness waits after SIGINT before it kills the process
    +	// group. Default 10s.
    +	InterruptGrace time.Duration
    +	// StartLimit is the largest Start message, in bytes, the harness server accepts. It sizes tool
    +	// receipts against History. Default 4 MiB (gRPC's default).
    +	StartLimit int
    +}
    +
    +// Harness is the Claude Code harness. Use New; the zero value is not usable. Its state lives only
    +// in process memory, so it must be a single long-lived instance per process.
    +type Harness struct {
    +	cfg    Config
    +	logger *slog.Logger
    +
    +	// postResultGrace bounds how long the process may run after its result event before the
    +	// harness interrupts it. drainGrace bounds how long the harness waits for stdout to close
    +	// once the process exited or was killed. Fields, not constants, so tests can shorten them.
    +	postResultGrace time.Duration
    +	drainGrace      time.Duration
    +
    +	mu       sync.Mutex
    +	sessions map[string]*sessionState
    +	started  map[string]struct{}
    +}
    +
    +// sessionState is the per-session harness memory.
    +type sessionState struct {
    +	attempt     int  // index into the derived Claude Code session ids
    +	established bool // system/init confirmed the id for attempt; later turns resume it
    +	pending     bool // the id for attempt was handed to a process that did not confirm it
    +	running     bool // a turn is in flight
    +}
    +
    +// New validates cfg and returns a harness.
    +func New(cfg Config) (*Harness, error) {
    +	if cfg.Binary == "" {
    +		cfg.Binary = defaultBinary
    +	}
    +	bin, err := exec.LookPath(cfg.Binary)
    +	if err != nil {
    +		return nil, fmt.Errorf("claudecode: find claude binary: %w", err)
    +	}
    +	cfg.Binary = bin

    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.

    aramase aramase commented on code on Nov 05, 2026 22:57 UTC
    Code Review
    harness/claudecode/turn.go:1
    @@ -0,0 +1,571 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"os"
    +	"os/exec"
    +	"strings"
    +	"time"
    +	"unicode/utf8"
    +
    +	"google.golang.org/protobuf/proto"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/wire"
    +)
    +
    +const (
    +	// maxLineBytes bounds one stream-json line. A longer line fails the turn as malformed.
    +	maxLineBytes = 16 << 20
    +	// receiptFieldBytes bounds the tool input and the tool content a full receipt carries.
    +	receiptFieldBytes = 2 << 10
    +	// turnReceiptBudget bounds one turn's full receipts; later receipts in the turn are minimal.
    +	turnReceiptBudget = 128 << 10
    +	// outputChunkBytes bounds one Output call, well under gRPC's default 4 MiB frame limit.
    +	outputChunkBytes = 1 << 20
    +)
    +
    +var (
    +	errMalformed       = errors.New("claudecode: malformed stream-json from claude")
    +	errNoInit          = errors.New("claudecode: claude stream has events before system/init")
    +	errSessionMismatch = errors.New("claudecode: claude reported a different session id")
    +	errNoResult        = errors.New("claudecode: claude stream ended without a result")
    +)
    +
    +// streamLine is one stream-json event. Only the fields the harness maps are decoded; unknown
    +// event types and fields are ignored.
    +type streamLine struct {
    +	Type            string          `json:"type"`
    +	Subtype         string          `json:"subtype"`
    +	SessionID       string          `json:"session_id"`
    +	Model           string          `json:"model"`
    +	ParentToolUseID string          `json:"parent_tool_use_id"`
    +	Message         json.RawMessage `json:"message"`
    +	IsError         bool            `json:"is_error"`
    +	Result          string          `json:"result"`
    +	Usage           *tokenUsage     `json:"usage"`
    +}
    +
    +// message is the Anthropic-shaped message inside assistant and user events. Content is a string or
    +// an array of blocks.
    +type message struct {
    +	ID      string          `json:"id"`
    +	Content json.RawMessage `json:"content"`
    +	Usage   *tokenUsage     `json:"usage"`
    +}
    +
    +type contentBlock struct {
    +	Type      string          `json:"type"`
    +	Text      string          `json:"text"`
    +	ID        string          `json:"id"`
    +	Name      string          `json:"name"`
    +	Input     json.RawMessage `json:"input"`
    +	ToolUseID string          `json:"tool_use_id"`
    +	Content   json.RawMessage `json:"content"`
    +	IsError   bool            `json:"is_error"`
    +}
    +
    +type tokenUsage struct {
    +	InputTokens              int64 `json:"input_tokens"`
    +	OutputTokens             int64 `json:"output_tokens"`
    +	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
    +	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
    +}
    +
    +func (u *tokenUsage) valid() bool {
    +	return u.InputTokens >= 0 && u.OutputTokens >= 0 && u.CacheCreationInputTokens >= 0 && u.CacheReadInputTokens >= 0
    +}
    +
    +// input is every input token the model processed: uncached, cache reads and cache writes.
    +func (u *tokenUsage) input() int64 {
    +	return u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens
    +}
    +
    +type toolUse struct {
    +	name   string
    +	input  json.RawMessage
    +	parent string
    +}
    +
    +// turn is one Run's process and stream state. Only the goroutine running run touches it.
    +type turn struct {
    +	h         *Harness
    +	sink      api.EventSink
    +	sessionID string
    +	model     string
    +	receipts  bool // full receipts; false once the session or turn budget is spent
    +
    +	receiptBytes int
    +	initSeen     bool
    +	initModel    string
    +	tools        map[string]toolUse
    +	toolOrder    []string
    +	seenMsgs     map[string]struct{}
    +	recovered    tokenUsage // main-loop assistant usage, deduplicated by message id
    +	result       *streamLine
    +	sinkErr      error
    +}
    +
    +// receiptMode reports whether full receipts are allowed this turn: History, sized as the wire sends
    +// it, is under half of StartLimit. It warns once History reaches three quarters of it.
    +func (h *Harness) receiptMode(s *api.Start) bool {
    +	n := 0
    +	for _, e := range s.History {
    +		n += proto.Size(wire.EventToProto(e))
    +	}
    +	if n >= h.cfg.StartLimit/4*3 {
    +		h.logger.Warn("claudecode: session history nears the harness receive limit; raise the limit and Config.StartLimit",
    +			"session_uid", s.SessionUID, "history_bytes", n, "start_limit", h.cfg.StartLimit)
    +	}
    +	return n < h.cfg.StartLimit/2
    +}
    +
    +type readResult struct {
    +	line []byte
    +	err  error
    +}
    +
    +// Process phases. Each later phase is entered at most once, in order.
    +const (
    +	phaseRunning     = iota
    +	phaseSettling    // result seen or stdout closed: the process gets postResultGrace to exit
    +	phaseInterrupted // SIGINT sent: the process gets InterruptGrace to exit
    +	phaseKilled      // the group was killed, or the leader exited: stdout gets drainGrace to close
    +)
    +
    +// run starts the process, maps its stream, and returns the turn's outcome.
    +func (t *turn) run(ctx context.Context, args []string, prompt string) error {
    +	t.tools = make(map[string]toolUse)
    +	t.seenMsgs = make(map[string]struct{})
    +
    +	r, w, err := os.Pipe()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = r.Close() }()
    +	cmd := exec.Command(t.h.cfg.Binary, args...)
    +	cmd.Dir = t.h.cfg.WorkDir
    +	cmd.Stdin = strings.NewReader(prompt)
    +	cmd.Stdout = w
    +	// stderr is discarded: it can carry prompt or tool text, which must not reach errors or logs.
    +	cmd.SysProcAttr = sysProcAttr()
    +	cmd.WaitDelay = t.h.drainGrace
    +	err = cmd.Start()
    +	_ = w.Close() // the child holds its own copy
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +
    +	lines := make(chan readResult)
    +	go readLines(r, lines)
    +	exited := make(chan struct{})
    +	go func() {
    +		_ = cmd.Wait() // the outcome is read from cmd.ProcessState
    +		close(exited)
    +	}()
    +
    +	var (
    +		phase    = phaseRunning
    +		deadline <-chan time.Time
    +		done     = ctx.Done()
    +		eof      bool
    +		exitSeen bool
    +		forced   bool // the harness closed stdout itself
    +		signaled bool // the harness signalled the process, so its exit status is not its own verdict
    +		failErr  error
    +	)
    +	enter := func(p int, d time.Duration) {
    +		phase = p
    +		deadline = time.After(d)
    +	}
    +	interrupt := func() {
    +		if phase >= phaseInterrupted {
    +			return
    +		}
    +		interruptProcess(cmd.Process)
    +		signaled = true
    +		enter(phaseInterrupted, t.h.cfg.InterruptGrace)
    +	}
    +	for !eof || !exitSeen {
    +		select {
    +		case m, ok := <-lines:
    +			switch {
    +			case !ok:
    +				lines, eof = nil, true
    +				if phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			case m.err != nil:
    +				if !forced && failErr == nil {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			case failErr != nil || ctx.Err() != nil || t.result != nil:
    +				// Stopping, or past the result: drain.

    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.

    aramase aramase commented on code on Nov 05, 2026 22:58 UTC
    Code Review
    cmd/harnessnode/main.go:1
    @@ -37,6 +38,7 @@ import (
     	"github.com/agent-primitives/sessions/api"
     	v1 "github.com/agent-primitives/sessions/api/genpb"
     	"github.com/agent-primitives/sessions/harness/chatagent"
    +	"github.com/agent-primitives/sessions/harness/claudecode"

    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.

    aramase aramase commented on code on Nov 05, 2026 22:58 UTC
    Code Review
    harness/claudecode/claudecode.go:1
    @@ -0,0 +1,425 @@
    +// Package claudecode is an unmediated, REQUIRES_MEMORY_SNAPSHOT api.Harness that runs Claude Code
    +// in headless mode. Each Run (one Exec) starts exactly one process:
    +//
    +//	claude -p --output-format stream-json --verbose --include-partial-messages \
    +//	  --permission-mode <mode> (--session-id|--resume) <id> [--model m] [--max-turns n] [--max-budget-usd x]
    +//
    +// with the turn's text inputs on stdin, and maps its stream-json events onto the sink.
    +//
    +// Unmediated: Claude Code owns its model loop, tools and transcript, so model calls originate in
    +// the Claude Code process, not through sink.Model. The journal therefore has no MODEL_CALL record,
    +// the harness has no replay determinism, and it supports no reconstruction replay: the session
    +// survives suspend and resume only through a memory snapshot of the compute that runs it. What the

    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".

    aramase aramase commented on code on Nov 05, 2026 22:58 UTC
    Code Review
    integrations/claudecode/claudecode.go:1
    @@ -0,0 +1,425 @@
    +// Package claudecode is an unmediated, REQUIRES_MEMORY_SNAPSHOT api.Harness that runs Claude Code
    +// in headless mode. Each Run (one Exec) starts exactly one process:
    +//
    +//	claude -p --output-format stream-json --verbose --include-partial-messages \
    +//	  --permission-mode <mode> (--session-id|--resume) <id> [--model m] [--max-turns n] [--max-budget-usd x]
    +//
    +// with the turn's text inputs on stdin, and maps its stream-json events onto the sink.
    +//
    +// Unmediated: Claude Code owns its model loop, tools and transcript, so model calls originate in
    +// the Claude Code process, not through sink.Model. The journal therefore has no MODEL_CALL record,
    +// the harness has no replay determinism, and it supports no reconstruction replay: the session
    +// survives suspend and resume only through a memory snapshot of the compute that runs it. What the
    +// harness journals is what it can observe:
    +//
    +//   - the turn's final assistant text as Output, once, when the turn ends; a text over 1 MiB is
    +//     recorded as several consecutive Output events. Partial text deltas are parsed and dropped;
    +//     the host's EventSink has no ephemeral delta method.
    +//   - each tool result Claude Code executed as a reported TOOL_RESULT (sink.Report). The host
    +//     refuses sink.ToolCall for a tool the harness executes itself (IN_HARNESS_REPORTED), so tool
    +//     calls are never sent as intents. Receipts are bounded (see History size below).
    +//   - the turn's token counts as one Usage, taken from the result event's usage and attributed to
    +//     the model system/init reports. InputTokens counts uncached, cache-read and cache-write input
    +//     tokens. When no result reports nonzero usage, the Usage holds only the input tokens of the
    +//     turn's main-loop assistant messages (subagent messages excluded) and no output tokens. The
    +//     result's total_cost_usd is not recorded: api.Usage has no cost field. Usage is
    +//     observability, not billing.
    +//
    +// A turn the host cancels records nothing after the cancel: no Output, no Usage, and no
    +// TOOL_RESULT for a tool still running.
    +//
    +// Do not point controller.Replay at this harness: on a fresh instance the first recorded execution
    +// looks like a genuine first turn and runs a real, billed Claude Code turn.
    +//
    +// Claude Code session identity is harness memory. The first turn passes --session-id with a UUID
    +// derived from the sessions session UID and an attempt number; once Claude Code's system/init event
    +// confirms that id, later turns pass --resume with the same id. A first turn that fails before
    +// init moves to the next attempt, so a transcript left by a dead attempt cannot block the session.
    +// Nothing extra is persisted: the memory snapshot carries the id, and the runtime's snapshot must
    +// also preserve the filesystem that holds Claude Code's transcripts. A harness instance that holds
    +// no state for a session whose History already has turns (memory lost, a fork child, or a session
    +// that started on another harness) refuses the turn rather than start an empty conversation. A
    +// re-run of an execution this instance already started fails; an interrupted turn is not retried.
    +//
    +// Credentials: the harness never reads, holds or passes a model key. The child process inherits the
    +// harness's environment; the runtime supplies whatever Claude Code needs there.
    +//
    +// The working directory is trusted input: without --bare, claude -p runs the directory's hooks and
    +// MCP configuration with no trust prompt. The configured permission mode bounds what Claude Code
    +// may do; the host does not. Approvals are not supported.
    +//
    +// History size: the host sends the session's whole prior journal as Start.History, bounded by the
    +// harness server's receive limit (HARNESS_MAX_RECV_MSG_SIZE in cmd/harnessnode). Tool receipts
    +// carry at most 2 KiB of input and 2 KiB of content, and shrink to sizes only once a turn's
    +// receipts pass 128 KiB or History passes half of Config.StartLimit. A long session still grows
    +// History; raise the receive limit and Config.StartLimit together.
    +package claudecode
    +
    +import (
    +	"context"
    +	"crypto/sha1"
    +	"errors"
    +	"fmt"
    +	"log/slog"
    +	"math"
    +	"os"
    +	"os/exec"
    +	"path/filepath"
    +	"strconv"
    +	"strings"
    +	"sync"
    +	"time"
    +
    +	"github.com/agent-primitives/sessions/api"
    +)
    +
    +const (
    +	defaultBinary         = "claude"
    +	defaultInterruptGrace = 10 * time.Second
    +	defaultStartLimit     = 4 << 20 // gRPC's default receive limit
    +	defaultPostResult     = 5 * time.Second
    +	defaultDrainGrace     = time.Second
    +
    +	// maxPromptBytes is Claude Code's documented stdin limit for -p.
    +	maxPromptBytes = 10_000_000
    +)
    +
    +// Config configures the harness. Zero values select the defaults documented per field.
    +type Config struct {
    +	// Binary is the claude executable, a path or a name looked up in PATH. Default "claude".
    +	Binary string
    +	// WorkDir is the directory Claude Code runs in. Required; it must exist.
    +	WorkDir string
    +	// Model, when set, is passed as --model and declared in Descriptor.Models. A Start.Model that
    +	// differs fails the turn. When empty, a nonempty Start.Model is passed instead, else Claude
    +	// Code's own default applies.
    +	Model string
    +	// PermissionMode is passed as --permission-mode. Required: the harness cannot answer
    +	// permission prompts, so the operator chooses the mode explicitly.
    +	PermissionMode string
    +	// MaxTurns, when positive, is passed as --max-turns.
    +	MaxTurns int
    +	// MaxBudgetUSD, when positive, is passed as --max-budget-usd. It caps one turn's spend.
    +	MaxBudgetUSD float64
    +	// InterruptGrace is how long the harness waits after SIGINT before it kills the process
    +	// group. Default 10s.
    +	InterruptGrace time.Duration
    +	// StartLimit is the largest Start message, in bytes, the harness server accepts. It sizes tool
    +	// receipts against History. Default 4 MiB (gRPC's default).
    +	StartLimit int
    +}
    +
    +// Harness is the Claude Code harness. Use New; the zero value is not usable. Its state lives only
    +// in process memory, so it must be a single long-lived instance per process.
    +type Harness struct {
    +	cfg    Config
    +	logger *slog.Logger
    +
    +	// postResultGrace bounds how long the process may run after its result event before the
    +	// harness interrupts it. drainGrace bounds how long the harness waits for stdout to close
    +	// once the process exited or was killed. Fields, not constants, so tests can shorten them.
    +	postResultGrace time.Duration
    +	drainGrace      time.Duration
    +
    +	mu       sync.Mutex
    +	sessions map[string]*sessionState
    +	started  map[string]struct{}
    +}
    +
    +// sessionState is the per-session harness memory.
    +type sessionState struct {
    +	attempt     int  // index into the derived Claude Code session ids
    +	established bool // system/init confirmed the id for attempt; later turns resume it
    +	pending     bool // the id for attempt was handed to a process that did not confirm it
    +	running     bool // a turn is in flight
    +}
    +
    +// New validates cfg and returns a harness.
    +func New(cfg Config) (*Harness, error) {
    +	if cfg.Binary == "" {
    +		cfg.Binary = defaultBinary
    +	}
    +	bin, err := exec.LookPath(cfg.Binary)
    +	if err != nil {
    +		return nil, fmt.Errorf("claudecode: find claude binary: %w", err)
    +	}
    +	cfg.Binary = bin
    +	if cfg.WorkDir == "" {
    +		return nil, errors.New("claudecode: WorkDir is required")
    +	}
    +	dir, err := filepath.Abs(cfg.WorkDir)
    +	if err != nil {
    +		return nil, fmt.Errorf("claudecode: WorkDir: %w", err)
    +	}
    +	if fi, err := os.Stat(dir); err != nil {
    +		return nil, fmt.Errorf("claudecode: WorkDir: %w", err)
    +	} else if !fi.IsDir() {
    +		return nil, fmt.Errorf("claudecode: WorkDir %q is not a directory", dir)
    +	}
    +	cfg.WorkDir = dir
    +	if cfg.PermissionMode == "" {
    +		return nil, errors.New("claudecode: PermissionMode is required")
    +	}
    +	if !argValue(cfg.PermissionMode) {
    +		return nil, fmt.Errorf("claudecode: invalid PermissionMode %q", cfg.PermissionMode)
    +	}
    +	if cfg.Model != "" && !argValue(cfg.Model) {
    +		return nil, fmt.Errorf("claudecode: invalid Model %q", cfg.Model)
    +	}
    +	if cfg.MaxTurns < 0 {
    +		return nil, errors.New("claudecode: MaxTurns must not be negative")
    +	}
    +	if cfg.MaxBudgetUSD < 0 || math.IsNaN(cfg.MaxBudgetUSD) || math.IsInf(cfg.MaxBudgetUSD, 0) {
    +		return nil, errors.New("claudecode: MaxBudgetUSD must be a finite, non-negative number")
    +	}
    +	switch {
    +	case cfg.InterruptGrace < 0:
    +		return nil, errors.New("claudecode: InterruptGrace must not be negative")
    +	case cfg.InterruptGrace == 0:
    +		cfg.InterruptGrace = defaultInterruptGrace
    +	}
    +	switch {
    +	case cfg.StartLimit < 0:
    +		return nil, errors.New("claudecode: StartLimit must not be negative")
    +	case cfg.StartLimit == 0:
    +		cfg.StartLimit = defaultStartLimit
    +	}
    +	return &Harness{
    +		cfg:             cfg,
    +		logger:          slog.Default(),
    +		postResultGrace: defaultPostResult,
    +		drainGrace:      defaultDrainGrace,
    +		sessions:        make(map[string]*sessionState),
    +		started:         make(map[string]struct{}),
    +	}, nil
    +}
    +
    +// argValue reports whether v can follow a flag as its own argument: nonempty, no leading '-' (it
    +// would parse as a flag), and no whitespace or control characters.
    +func argValue(v string) bool {
    +	if v == "" || v[0] == '-' {
    +		return false
    +	}
    +	for _, r := range v {
    +		if r <= ' ' || r == 0x7f {
    +			return false
    +		}
    +	}
    +	return true
    +}
    +
    +// Describe declares REQUIRES_MEMORY_SNAPSHOT (the Claude Code session id lives in harness memory and
    +// the transcript on the compute's filesystem), not ForkSafe (a fork child holds no session of its
    +// own), and Streaming.
    +func (h *Harness) Describe(context.Context) (api.Descriptor, error) {
    +	var models []string
    +	if h.cfg.Model != "" {
    +		models = []string{h.cfg.Model}
    +	}
    +	return api.Descriptor{
    +		ID:      "claudecode",
    +		Version: "1", // bump when execution behavior changes, not for host releases
    +		Models:  models,
    +		Capabilities: api.Capabilities{
    +			Resumability: api.ResumabilityRequiresMemorySnapshot,
    +			ForkSafe:     false,
    +			Streaming:    true,
    +		},
    +	}, nil
    +}
    +
    +// Errors returned by Run. Their text is fixed: the host journals a failed turn's error text.
    +var (
    +	errNoSession     = errors.New("claudecode: start has no session UID")
    +	errRerun         = errors.New("claudecode: execution already started on this harness; an interrupted turn is not retried")
    +	errStateLost     = errors.New("claudecode: session has earlier turns but this harness holds no state for it (memory lost, fork, or harness switch)")
    +	errBusy          = errors.New("claudecode: another turn is running for this session")
    +	errNoPrompt      = errors.New("claudecode: inputs carry no text")
    +	errNonText       = errors.New("claudecode: inputs must be text only")
    +	errPromptSize    = errors.New("claudecode: inputs exceed the 10 MB prompt limit")
    +	errModelMismatch = errors.New("claudecode: requested model is not the configured model")
    +	errModelArg      = errors.New("claudecode: requested model is not a valid model argument")
    +)
    +
    +// Run drives one turn: one claude -p process. It returns nil when Claude Code reports a successful
    +// result, and an error when the result is an error, the process fails or exits without a result,
    +// the stream is malformed, or ctx is cancelled (SIGINT, then a group kill after InterruptGrace).
    +// Start.Config is ignored.
    +func (h *Harness) Run(ctx context.Context, s *api.Start, sink api.EventSink) error {
    +	if s == nil || s.SessionUID == "" {
    +		return errNoSession
    +	}
    +	if err := h.begin(s); err != nil {
    +		return err
    +	}
    +	established := false
    +	defer func() { h.end(s.SessionUID, established) }()
    +
    +	prompt, err := promptText(s.Inputs)
    +	if err != nil {
    +		return err
    +	}
    +	model, err := h.turnModel(s.Model)
    +	if err != nil {
    +		return err
    +	}
    +	flag, id := h.sessionArg(s.SessionUID)
    +	t := &turn{
    +		h:         h,
    +		sink:      sink,
    +		sessionID: id,
    +		model:     model,
    +		receipts:  h.receiptMode(s),
    +	}
    +	err = t.run(ctx, h.args(flag, id, model), prompt)

    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".

    Copilot Copilot commented on code on Nov 06, 2026 00:56 UTC
    Code Review
    integrations/claudecode/turn.go:1
    @@ -0,0 +1,596 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"os"
    +	"os/exec"
    +	"strings"
    +	"time"
    +	"unicode/utf8"
    +
    +	"google.golang.org/protobuf/proto"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/wire"
    +)
    +
    +const (
    +	// maxLineBytes bounds one stream-json line. A longer line fails the turn as malformed.
    +	maxLineBytes = 16 << 20
    +	// receiptFieldBytes bounds the tool input and the tool content a full receipt carries.
    +	receiptFieldBytes = 2 << 10
    +	// turnReceiptBudget bounds one turn's full receipts; later receipts in the turn are minimal.
    +	turnReceiptBudget = 128 << 10
    +	// outputChunkBytes bounds one Output call, well under gRPC's default 4 MiB frame limit.
    +	outputChunkBytes = 1 << 20
    +)
    +
    +var (
    +	errMalformed       = errors.New("claudecode: malformed stream-json from claude")
    +	errNoInit          = errors.New("claudecode: claude stream has events before system/init")
    +	errSessionMismatch = errors.New("claudecode: claude reported a different session id")
    +	errNoResult        = errors.New("claudecode: claude stream ended without a result")
    +)
    +
    +// streamLine is one stream-json event. Only the fields the harness maps are decoded; unknown
    +// event types and fields are ignored.
    +type streamLine struct {
    +	Type            string          `json:"type"`
    +	Subtype         string          `json:"subtype"`
    +	SessionID       string          `json:"session_id"`
    +	Model           string          `json:"model"`
    +	ParentToolUseID string          `json:"parent_tool_use_id"`
    +	Message         json.RawMessage `json:"message"`
    +	IsError         bool            `json:"is_error"`
    +	Result          string          `json:"result"`
    +	Usage           *tokenUsage     `json:"usage"`
    +}
    +
    +// message is the Anthropic-shaped message inside assistant and user events. Content is a string or
    +// an array of blocks.
    +type message struct {
    +	ID      string          `json:"id"`
    +	Content json.RawMessage `json:"content"`
    +	Usage   *tokenUsage     `json:"usage"`
    +}
    +
    +type contentBlock struct {
    +	Type      string          `json:"type"`
    +	Text      string          `json:"text"`
    +	ID        string          `json:"id"`
    +	Name      string          `json:"name"`
    +	Input     json.RawMessage `json:"input"`
    +	ToolUseID string          `json:"tool_use_id"`
    +	Content   json.RawMessage `json:"content"`
    +	IsError   bool            `json:"is_error"`
    +}
    +
    +type tokenUsage struct {
    +	InputTokens              int64 `json:"input_tokens"`
    +	OutputTokens             int64 `json:"output_tokens"`
    +	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
    +	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
    +}
    +
    +func (u *tokenUsage) valid() bool {
    +	return u.InputTokens >= 0 && u.OutputTokens >= 0 && u.CacheCreationInputTokens >= 0 && u.CacheReadInputTokens >= 0
    +}
    +
    +// input is every input token the model processed: uncached, cache reads and cache writes.
    +func (u *tokenUsage) input() int64 {
    +	return u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens
    +}
    +
    +type toolUse struct {
    +	name   string
    +	input  json.RawMessage
    +	parent string
    +}
    +
    +// turn is one Run's process and stream state. Only the goroutine running run touches it.
    +type turn struct {
    +	h         *Harness
    +	sink      api.EventSink
    +	sessionID string
    +	model     string
    +	receipts  bool // full receipts; false once the session or turn budget is spent
    +
    +	receiptBytes int
    +	initSeen     bool
    +	initModel    string
    +	tools        map[string]toolUse
    +	toolOrder    []string
    +	seenMsgs     map[string]struct{}
    +	recovered    tokenUsage // main-loop assistant usage, deduplicated by message id
    +	result       *streamLine
    +	sinkErr      error
    +}
    +
    +// receiptMode reports whether full receipts are allowed this turn: History, sized as the wire sends
    +// it, is under half of StartLimit. It warns once History reaches three quarters of it.
    +func (h *Harness) receiptMode(s *api.Start) bool {
    +	n := 0
    +	for _, e := range s.History {
    +		n += proto.Size(wire.EventToProto(e))
    +	}
    +	if n >= h.cfg.StartLimit/4*3 {
    +		h.logger.Warn("claudecode: session history nears the harness receive limit; raise the limit and Config.StartLimit",
    +			"session_uid", s.SessionUID, "history_bytes", n, "start_limit", h.cfg.StartLimit)
    +	}
    +	return n < h.cfg.StartLimit/2
    +}
    +
    +type readResult struct {
    +	line []byte
    +	err  error
    +}
    +
    +// Process phases. Each later phase is entered at most once, in order.
    +const (
    +	phaseRunning     = iota
    +	phaseSettling    // result seen or stdout closed: the process gets postResultGrace to exit
    +	phaseInterrupted // SIGINT sent: the process gets InterruptGrace to exit
    +	phaseKilled      // the group was killed, or the leader exited: stdout gets drainGrace to close
    +)
    +
    +// run starts the process, maps its stream, and returns the turn's outcome.
    +func (t *turn) run(ctx context.Context, args []string, prompt string) error {

    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.

    Copilot Copilot commented on code on Nov 06, 2026 00:56 UTC
    Code Review
    integrations/claudecode/turn.go:1
    @@ -0,0 +1,596 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"os"
    +	"os/exec"
    +	"strings"
    +	"time"
    +	"unicode/utf8"
    +
    +	"google.golang.org/protobuf/proto"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/wire"
    +)
    +
    +const (
    +	// maxLineBytes bounds one stream-json line. A longer line fails the turn as malformed.
    +	maxLineBytes = 16 << 20
    +	// receiptFieldBytes bounds the tool input and the tool content a full receipt carries.
    +	receiptFieldBytes = 2 << 10
    +	// turnReceiptBudget bounds one turn's full receipts; later receipts in the turn are minimal.
    +	turnReceiptBudget = 128 << 10
    +	// outputChunkBytes bounds one Output call, well under gRPC's default 4 MiB frame limit.
    +	outputChunkBytes = 1 << 20
    +)
    +
    +var (
    +	errMalformed       = errors.New("claudecode: malformed stream-json from claude")
    +	errNoInit          = errors.New("claudecode: claude stream has events before system/init")
    +	errSessionMismatch = errors.New("claudecode: claude reported a different session id")
    +	errNoResult        = errors.New("claudecode: claude stream ended without a result")
    +)
    +
    +// streamLine is one stream-json event. Only the fields the harness maps are decoded; unknown
    +// event types and fields are ignored.
    +type streamLine struct {
    +	Type            string          `json:"type"`
    +	Subtype         string          `json:"subtype"`
    +	SessionID       string          `json:"session_id"`
    +	Model           string          `json:"model"`
    +	ParentToolUseID string          `json:"parent_tool_use_id"`
    +	Message         json.RawMessage `json:"message"`
    +	IsError         bool            `json:"is_error"`
    +	Result          string          `json:"result"`
    +	Usage           *tokenUsage     `json:"usage"`
    +}
    +
    +// message is the Anthropic-shaped message inside assistant and user events. Content is a string or
    +// an array of blocks.
    +type message struct {
    +	ID      string          `json:"id"`
    +	Content json.RawMessage `json:"content"`
    +	Usage   *tokenUsage     `json:"usage"`
    +}
    +
    +type contentBlock struct {
    +	Type      string          `json:"type"`
    +	Text      string          `json:"text"`
    +	ID        string          `json:"id"`
    +	Name      string          `json:"name"`
    +	Input     json.RawMessage `json:"input"`
    +	ToolUseID string          `json:"tool_use_id"`
    +	Content   json.RawMessage `json:"content"`
    +	IsError   bool            `json:"is_error"`
    +}
    +
    +type tokenUsage struct {
    +	InputTokens              int64 `json:"input_tokens"`
    +	OutputTokens             int64 `json:"output_tokens"`
    +	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
    +	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
    +}
    +
    +func (u *tokenUsage) valid() bool {
    +	return u.InputTokens >= 0 && u.OutputTokens >= 0 && u.CacheCreationInputTokens >= 0 && u.CacheReadInputTokens >= 0
    +}
    +
    +// input is every input token the model processed: uncached, cache reads and cache writes.
    +func (u *tokenUsage) input() int64 {
    +	return u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens
    +}
    +
    +type toolUse struct {
    +	name   string
    +	input  json.RawMessage
    +	parent string
    +}
    +
    +// turn is one Run's process and stream state. Only the goroutine running run touches it.
    +type turn struct {
    +	h         *Harness
    +	sink      api.EventSink
    +	sessionID string
    +	model     string
    +	receipts  bool // full receipts; false once the session or turn budget is spent
    +
    +	receiptBytes int
    +	initSeen     bool
    +	initModel    string
    +	tools        map[string]toolUse
    +	toolOrder    []string
    +	seenMsgs     map[string]struct{}
    +	recovered    tokenUsage // main-loop assistant usage, deduplicated by message id
    +	result       *streamLine
    +	sinkErr      error
    +}
    +
    +// receiptMode reports whether full receipts are allowed this turn: History, sized as the wire sends
    +// it, is under half of StartLimit. It warns once History reaches three quarters of it.
    +func (h *Harness) receiptMode(s *api.Start) bool {
    +	n := 0
    +	for _, e := range s.History {
    +		n += proto.Size(wire.EventToProto(e))
    +	}
    +	if n >= h.cfg.StartLimit/4*3 {
    +		h.logger.Warn("claudecode: session history nears the harness receive limit; raise the limit and Config.StartLimit",
    +			"session_uid", s.SessionUID, "history_bytes", n, "start_limit", h.cfg.StartLimit)
    +	}
    +	return n < h.cfg.StartLimit/2
    +}
    +
    +type readResult struct {
    +	line []byte
    +	err  error
    +}
    +
    +// Process phases. Each later phase is entered at most once, in order.
    +const (
    +	phaseRunning     = iota
    +	phaseSettling    // result seen or stdout closed: the process gets postResultGrace to exit
    +	phaseInterrupted // SIGINT sent: the process gets InterruptGrace to exit
    +	phaseKilled      // the group was killed, or the leader exited: stdout gets drainGrace to close
    +)
    +
    +// run starts the process, maps its stream, and returns the turn's outcome.
    +func (t *turn) run(ctx context.Context, args []string, prompt string) error {
    +	t.tools = make(map[string]toolUse)
    +	t.seenMsgs = make(map[string]struct{})
    +
    +	r, w, err := os.Pipe()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = r.Close() }()
    +	cmd := exec.Command(t.h.cfg.Binary, args...)
    +	cmd.Dir = t.h.cfg.WorkDir
    +	cmd.Stdin = strings.NewReader(prompt)
    +	cmd.Stdout = w
    +	// stderr is discarded: it can carry prompt or tool text, which must not reach errors or logs.
    +	cmd.SysProcAttr = sysProcAttr()
    +	cmd.WaitDelay = t.h.drainGrace
    +	err = cmd.Start()
    +	_ = w.Close() // the child holds its own copy
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +
    +	lines := make(chan readResult)
    +	go readLines(r, lines)
    +	exited := make(chan struct{})
    +	go func() {
    +		_ = cmd.Wait() // the outcome is read from cmd.ProcessState
    +		close(exited)
    +	}()
    +
    +	var (
    +		phase    = phaseRunning
    +		deadline <-chan time.Time
    +		done     = ctx.Done()
    +		eof      bool
    +		exitSeen bool
    +		forced   bool // the harness closed stdout itself
    +		signaled bool // the harness signalled the process, so its exit status is not its own verdict
    +		failErr  error
    +	)
    +	enter := func(p int, d time.Duration) {
    +		phase = p
    +		deadline = time.After(d)
    +	}
    +	interrupt := func() {
    +		if phase >= phaseInterrupted {
    +			return
    +		}
    +		interruptProcess(cmd.Process)
    +		signaled = true
    +		enter(phaseInterrupted, t.h.cfg.InterruptGrace)
    +	}
    +	for !eof || !exitSeen {
    +		select {
    +		case m, ok := <-lines:
    +			switch {
    +			case !ok:
    +				lines, eof = nil, true
    +				if phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			case m.err != nil:
    +				if !forced && failErr == nil {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			case failErr != nil || ctx.Err() != nil:
    +				// Stopping: drain.
    +			case t.result != nil:
    +				// Past the result: no further sink effects, but a malformed line still fails the
    +				// turn, as it would before the result.
    +				if !validLine(m.line) {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			default:
    +				if err := t.handle(ctx, m.line); err != nil {
    +					failErr = err
    +					interrupt()
    +				} else if t.result != nil && phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			}
    +		case <-exited:
    +			exited, exitSeen = nil, true
    +			if !eof && phase < phaseKilled {
    +				// Something the process started still holds stdout.
    +				enter(phaseKilled, t.h.drainGrace)

    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.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 06, 2026 00:56 UTC
    Reviewer

    <!-- 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>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Pre-canceled Run still starts the Claude Code process · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Slow sink processing can exhaust the output drain grace period · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Validate stream lines after a success result

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Resolve relative binary paths before changing the working directory

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Update published contracts for unmediated harness behavior

  • </details>

    <details>
    <summary><strong>3 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Leader exit can leave redirected tool subprocesses running

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Replay launches a billed turn before rejecting empty history

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Move the Claude Code adapter out of the core module

  • </details>

    <sub>Review effort: Balanced</sub>

    gambtho gambtho commented on Nov 08, 2026 03:55 UTC
    Reviewer

    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.

    Copilot Copilot commented on code on Nov 08, 2026 06:59 UTC
    Code Review
    integrations/claudecode/go.mod:1
    @@ -0,0 +1,37 @@
    +module github.com/agent-primitives/sessions/integrations/claudecode
    +
    +go 1.26.0
    +
    +toolchain go1.26.10
    +
    +require (
    +	github.com/agent-primitives/sessions v0.3.0

    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.

    Copilot Copilot commented on code on Nov 08, 2026 06:59 UTC
    Code Review
    integrations/claudecode/proc_other.go:1
    @@ -0,0 +1,22 @@
    +//go:build !unix
    +
    +package claudecode
    +
    +import (
    +	"os"
    +	"syscall"
    +	"time"
    +)
    +
    +// sysProcAttr sets nothing: there is no process group to create.
    +func sysProcAttr() *syscall.SysProcAttr { return nil }
    +
    +// interruptProcess kills the process: there is no SIGINT to send.
    +func interruptProcess(p *os.Process) { _ = p.Kill() }
    +
    +// killGroup kills the process; processes it started are not reached.
    +func killGroup(p *os.Process) { _ = p.Kill() }
    +
    +// stopGroup has no group to stop: the process was already waited for, and processes it started
    +// are not reached.
    +func stopGroup(*os.Process, time.Duration) bool { return true }

    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.

    Copilot Copilot commented on code on Nov 08, 2026 06:59 UTC
    Code Review
    integrations/claudecode/turn.go:1
    @@ -0,0 +1,696 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"os"
    +	"os/exec"
    +	"strings"
    +	"time"
    +	"unicode"
    +	"unicode/utf8"
    +
    +	"google.golang.org/protobuf/proto"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/wire"
    +)
    +
    +const (
    +	// maxLineBytes bounds one stream-json line. A longer line fails the turn as malformed.
    +	maxLineBytes = 16 << 20
    +	// receiptFieldBytes bounds the tool input and the tool content a full receipt carries.
    +	receiptFieldBytes = 2 << 10
    +	// turnReceiptBudget bounds one turn's full receipts; later receipts in the turn are minimal.
    +	turnReceiptBudget = 128 << 10
    +	// outputChunkBytes bounds one Output call, well under gRPC's default 4 MiB frame limit.
    +	outputChunkBytes = 1 << 20
    +	// stderrLineBytes bounds the stderr line logged for a process that failed before system/init.
    +	stderrLineBytes = 256
    +)
    +
    +var (
    +	errMalformed       = errors.New("claudecode: malformed stream-json from claude")
    +	errNoInit          = errors.New("claudecode: claude stream has events before system/init")
    +	errSessionMismatch = errors.New("claudecode: claude reported a different session id")
    +	errNoResult        = errors.New("claudecode: claude stream ended without a result")
    +)
    +
    +// streamLine is one stream-json event. Only the fields the harness maps are decoded; unknown
    +// event types and fields are ignored.
    +type streamLine struct {
    +	Type            string          `json:"type"`
    +	Subtype         string          `json:"subtype"`
    +	SessionID       string          `json:"session_id"`
    +	Model           string          `json:"model"`
    +	ParentToolUseID string          `json:"parent_tool_use_id"`
    +	Message         json.RawMessage `json:"message"`
    +	IsError         bool            `json:"is_error"`
    +	Result          string          `json:"result"`
    +	Usage           *tokenUsage     `json:"usage"`
    +}
    +
    +// message is the Anthropic-shaped message inside assistant and user events. Content is a string or
    +// an array of blocks.
    +type message struct {
    +	ID      string          `json:"id"`
    +	Content json.RawMessage `json:"content"`
    +	Usage   *tokenUsage     `json:"usage"`
    +}
    +
    +type contentBlock struct {
    +	Type      string          `json:"type"`
    +	Text      string          `json:"text"`
    +	ID        string          `json:"id"`
    +	Name      string          `json:"name"`
    +	Input     json.RawMessage `json:"input"`
    +	ToolUseID string          `json:"tool_use_id"`
    +	Content   json.RawMessage `json:"content"`
    +	IsError   bool            `json:"is_error"`
    +}
    +
    +type tokenUsage struct {
    +	InputTokens              int64 `json:"input_tokens"`
    +	OutputTokens             int64 `json:"output_tokens"`
    +	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
    +	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
    +}
    +
    +func (u *tokenUsage) valid() bool {
    +	return u.InputTokens >= 0 && u.OutputTokens >= 0 && u.CacheCreationInputTokens >= 0 && u.CacheReadInputTokens >= 0
    +}
    +
    +// input is every input token the model processed: uncached, cache reads and cache writes.
    +func (u *tokenUsage) input() int64 {
    +	return u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens
    +}
    +
    +type toolUse struct {
    +	name   string
    +	input  json.RawMessage
    +	parent string
    +}
    +
    +// turn is one Run's process and stream state. Only the goroutine running run touches it.
    +type turn struct {
    +	h          *Harness
    +	sink       api.EventSink
    +	sessionUID string
    +	flag       string // --session-id or --resume
    +	sessionID  string
    +	model      string
    +	receipts   bool // full receipts; false once the session or turn budget is spent
    +
    +	receiptBytes int
    +	initSeen     bool
    +	initModel    string
    +	tools        map[string]toolUse
    +	toolOrder    []string
    +	seenMsgs     map[string]struct{}
    +	recovered    tokenUsage // main-loop assistant usage, deduplicated by message id
    +	result       *streamLine
    +	sinkErr      error
    +}
    +
    +// receiptMode reports whether full receipts are allowed this turn: History, sized as the wire sends
    +// it, is under half of StartLimit. It warns once History reaches three quarters of it.
    +func (h *Harness) receiptMode(s *api.Start) bool {
    +	n := 0
    +	for _, e := range s.History {
    +		n += proto.Size(wire.EventToProto(e))
    +	}
    +	if n >= h.cfg.StartLimit/4*3 {
    +		h.logger.Warn("claudecode: session history nears the harness receive limit; raise the limit and Config.StartLimit",
    +			"session_uid", s.SessionUID, "history_bytes", n, "start_limit", h.cfg.StartLimit)
    +	}
    +	return n < h.cfg.StartLimit/2
    +}
    +
    +type readResult struct {
    +	line []byte
    +	err  error
    +}
    +
    +// Process phases. Each later phase is entered at most once, in order.
    +const (
    +	phaseRunning     = iota
    +	phaseSettling    // result seen or stdout closed: the process gets postResultGrace to exit
    +	phaseInterrupted // SIGINT sent: the process gets InterruptGrace to exit
    +	phaseKilled      // group killed or leader exited: stdout gets drainGrace of waiting to close
    +)
    +
    +// run starts the process, maps its stream, and returns the turn's outcome.
    +func (t *turn) run(ctx context.Context, args []string, prompt string) error {
    +	t.tools = make(map[string]toolUse)
    +	t.seenMsgs = make(map[string]struct{})
    +	if err := ctx.Err(); err != nil {
    +		return interruptedErr(err) // cancelled while the inputs were validated: launch nothing
    +	}
    +
    +	r, w, err := os.Pipe()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = r.Close() }()
    +	// stderr can carry prompt or tool text. Only its first line is kept, and logged only for a
    +	// process that failed before system/init. A pipe, not an io.Writer, so cmd.Wait does not wait
    +	// for a descendant that holds stderr.
    +	er, ew, err := os.Pipe()
    +	if err != nil {
    +		_ = w.Close()
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = er.Close() }()
    +	cmd := exec.Command(t.h.cfg.Binary, args...)
    +	cmd.Dir = t.h.cfg.WorkDir
    +	cmd.Env = t.h.env
    +	cmd.Stdin = strings.NewReader(prompt)
    +	cmd.Stdout = w
    +	cmd.Stderr = ew
    +	cmd.SysProcAttr = sysProcAttr()
    +	cmd.WaitDelay = t.h.drainGrace
    +	err = cmd.Start()
    +	_ = w.Close() // the child holds its own copies
    +	_ = ew.Close()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +
    +	stderrLine := make(chan string, 1)
    +	go func() {
    +		br := bufio.NewReader(er)
    +		stderrLine <- firstLine(br)
    +		_, _ = io.Copy(io.Discard, br) // keep draining so the process never blocks on stderr
    +	}()
    +	lines := make(chan readResult)
    +	go readLines(r, lines)
    +	exited := make(chan struct{})
    +	go func() {
    +		_ = cmd.Wait() // the outcome is read from cmd.ProcessState
    +		close(exited)
    +	}()
    +
    +	var (
    +		phase    = phaseRunning
    +		deadline <-chan time.Time
    +		done     = ctx.Done()
    +		eof      bool
    +		exitSeen bool
    +		forced   bool // the harness closed stdout itself
    +		signaled bool // the harness signalled the process, so its exit status is not its own verdict
    +		failErr  error
    +		drainBy  time.Time // phaseKilled: when stdout is closed
    +	)
    +	enter := func(p int, d time.Duration) {
    +		phase = p
    +		if p == phaseKilled {
    +			drainBy, deadline = time.Now().Add(d), nil // armed per wait, below
    +			return
    +		}
    +		deadline = time.After(d)
    +	}
    +	interrupt := func() {
    +		if phase >= phaseInterrupted {
    +			return
    +		}
    +		interruptProcess(cmd.Process)
    +		signaled = true
    +		enter(phaseInterrupted, t.h.cfg.InterruptGrace)
    +	}
    +	for !eof || !exitSeen {
    +		var drain *time.Timer
    +		if phase == phaseKilled && !forced {
    +			drain = time.NewTimer(time.Until(drainBy))
    +			deadline = drain.C
    +		}
    +		select {
    +		case m, ok := <-lines:
    +			switch {
    +			case !ok:
    +				lines, eof = nil, true
    +				if phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			case m.err != nil:
    +				if !forced && failErr == nil {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			case failErr != nil || ctx.Err() != nil:
    +				// Stopping: drain.
    +			case t.result != nil:
    +				// Past the result: no further sink effects, but a malformed line still fails the
    +				// turn, as it would before the result.
    +				if !validLine(m.line) {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			default:
    +				began := time.Now()
    +				err := t.handle(ctx, m.line)
    +				if phase == phaseKilled {
    +					// drainGrace bounds how long stdout stays open while the harness waits on
    +					// it, not how long the sink takes: a slow Report must not cut off lines the
    +					// process wrote before it exited.
    +					drainBy = drainBy.Add(time.Since(began))
    +				}
    +				if err != nil {
    +					failErr = err
    +					interrupt()
    +				} else if t.result != nil && phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			}
    +		case <-exited:
    +			exited, exitSeen = nil, true
    +			if !eof && phase < phaseKilled {
    +				// Something the process started still holds stdout.
    +				enter(phaseKilled, t.h.drainGrace)
    +			}
    +		case <-done:
    +			done = nil
    +			interrupt()
    +		case <-deadline:
    +			switch phase {
    +			case phaseSettling:
    +				interrupt()
    +			case phaseInterrupted:
    +				killGroup(cmd.Process)
    +				enter(phaseKilled, t.h.drainGrace)
    +			default:
    +				killGroup(cmd.Process)
    +				forced = true
    +				_ = r.Close()
    +				deadline = nil
    +			}
    +		}
    +		if drain != nil {
    +			drain.Stop()
    +		}
    +	}
    +
    +	// The loop ends once the leader exited and stdout closed, but the group can outlive its leader:
    +	// a tool Claude Code started that redirected its stdio holds neither. Kill it on every path,
    +	// success included, so nothing the turn started runs once Run returns, or while it records.
    +	if !stopGroup(cmd.Process, t.h.drainGrace) {
    +		t.h.logger.Warn("claudecode: processes of the turn's group remain after the kill",
    +			"pid", cmd.Process.Pid, "wait", t.h.drainGrace)
    +	}
    +
    +	err = t.outcome(ctx, cmd.ProcessState.ExitCode(), signaled, failErr)
    +	if err != nil && !t.initSeen && ctx.Err() == nil {
    +		// Claude Code failed before it confirmed the session, so no tool ran and the model said
    +		// nothing; a failing --resume ends here on every later turn. Its reason is on stderr.
    +		var line string
    +		select {
    +		case line = <-stderrLine:
    +		case <-time.After(t.h.drainGrace): // a descendant outside the group holds stderr
    +		}
    +		t.h.logger.Warn("claudecode: claude failed before system/init",
    +			"session_uid", t.sessionUID, "flag", t.flag, "claude_session_id", t.sessionID,
    +			"exit_status", cmd.ProcessState.String(), "stderr", line)

    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.

    Copilot Copilot commented on code on Nov 08, 2026 06:59 UTC
    Code Review
    integrations/claudecode/claudecode_test.go:1
    @@ -0,0 +1,1098 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"log/slog"
    +	"math"
    +	"os"
    +	"path/filepath"
    +	"reflect"
    +	"regexp"
    +	"slices"
    +	"strings"
    +	"testing"
    +	"time"
    +	"unicode/utf8"
    +
    +	"github.com/agent-primitives/sessions/api"
    +)
    +
    +func TestDescribe(t *testing.T) {
    +	t.Parallel()
    +	for _, test := range []struct {
    +		name  string
    +		model string
    +		want  []string
    +	}{
    +		{name: "no model"},
    +		{name: "configured model", model: "claude-test-model-1", want: []string{"claude-test-model-1"}},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{Model: test.model})
    +			got, err := h.Describe(context.Background())
    +			if err != nil {
    +				t.Fatal(err)
    +			}
    +			// Version is the stable author-owned replay version: bump it only when execution
    +			// behavior changes.
    +			want := api.Descriptor{
    +				ID:      "claudecode",
    +				Version: "1",
    +				Models:  test.want,
    +				Capabilities: api.Capabilities{
    +					Resumability: api.ResumabilityRequiresMemorySnapshot,
    +					ForkSafe:     false,
    +					Streaming:    true,
    +				},
    +			}
    +			if !reflect.DeepEqual(got, want) {
    +				t.Fatalf("Describe = %+v, want %+v", got, want)
    +			}
    +		})
    +	}
    +}
    +
    +func TestNewValidatesConfig(t *testing.T) {
    +	t.Parallel()
    +	exe, err := os.Executable()
    +	if err != nil {
    +		t.Fatal(err)
    +	}
    +	dir := t.TempDir()
    +	file := filepath.Join(dir, "file")
    +	if err := os.WriteFile(file, nil, 0o600); err != nil {
    +		t.Fatal(err)
    +	}
    +	valid := Config{Binary: exe, WorkDir: dir, PermissionMode: "dontAsk"}
    +	for _, test := range []struct {
    +		name   string
    +		mutate func(*Config)
    +		want   string
    +	}{
    +		{name: "binary not found", mutate: func(c *Config) { c.Binary = "claudecode-test-no-such-binary" }, want: "find claude binary"},
    +		{name: "no workdir", mutate: func(c *Config) { c.WorkDir = "" }, want: "WorkDir is required"},
    +		{name: "missing workdir", mutate: func(c *Config) { c.WorkDir = filepath.Join(dir, "missing") }, want: "WorkDir"},
    +		{name: "workdir is a file", mutate: func(c *Config) { c.WorkDir = file }, want: "is not a directory"},
    +		{name: "no permission mode", mutate: func(c *Config) { c.PermissionMode = "" }, want: "PermissionMode is required"},
    +		{name: "permission mode is a flag", mutate: func(c *Config) { c.PermissionMode = "--bare" }, want: "invalid PermissionMode"},
    +		{name: "permission mode with space", mutate: func(c *Config) { c.PermissionMode = "a b" }, want: "invalid PermissionMode"},
    +		{name: "model is a flag", mutate: func(c *Config) { c.Model = "-m" }, want: "invalid Model"},
    +		{name: "model with newline", mutate: func(c *Config) { c.Model = "m\n" }, want: "invalid Model"},
    +		{name: "negative max turns", mutate: func(c *Config) { c.MaxTurns = -1 }, want: "MaxTurns"},
    +		{name: "negative budget", mutate: func(c *Config) { c.MaxBudgetUSD = -1 }, want: "MaxBudgetUSD"},
    +		{name: "NaN budget", mutate: func(c *Config) { c.MaxBudgetUSD = math.NaN() }, want: "MaxBudgetUSD"},
    +		{name: "infinite budget", mutate: func(c *Config) { c.MaxBudgetUSD = math.Inf(1) }, want: "MaxBudgetUSD"},
    +		{name: "negative interrupt grace", mutate: func(c *Config) { c.InterruptGrace = -time.Second }, want: "InterruptGrace"},
    +		{name: "negative start limit", mutate: func(c *Config) { c.StartLimit = -1 }, want: "StartLimit"},
    +		{name: "bypass without opt-in", mutate: func(c *Config) { c.PermissionMode = "bypassPermissions" }, want: "PermissionMode bypassPermissions also requires AllowBypassPermissions"},
    +		{name: "bypass case variant without opt-in", mutate: func(c *Config) { c.PermissionMode = "BYPASSPERMISSIONS" }, want: "requires AllowBypassPermissions"},
    +		{name: "opt-in without bypass", mutate: func(c *Config) { c.AllowBypassPermissions = true }, want: `AllowBypassPermissions is set but PermissionMode is "dontAsk"`},
    +		{name: "empty env name", mutate: func(c *Config) { c.EnvAllowlist = []string{"HTTPS_PROXY", ""} }, want: "invalid EnvAllowlist name"},
    +		{name: "env name with =", mutate: func(c *Config) { c.EnvAllowlist = []string{"A=B"} }, want: "invalid EnvAllowlist name"},
    +		{name: "env name with NUL", mutate: func(c *Config) { c.EnvAllowlist = []string{"A\x00"} }, want: "invalid EnvAllowlist name"},
    +		{name: "env name with space", mutate: func(c *Config) { c.EnvAllowlist = []string{" A"} }, want: "invalid EnvAllowlist name"},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			cfg := valid
    +			test.mutate(&cfg)
    +			_, err := New(cfg)
    +			if err == nil || !strings.Contains(err.Error(), test.want) {
    +				t.Fatalf("New error = %v, want one containing %q", err, test.want)
    +			}
    +		})
    +	}
    +
    +	t.Run("bypass with opt-in", func(t *testing.T) {
    +		t.Parallel()
    +		cfg := valid
    +		cfg.PermissionMode, cfg.AllowBypassPermissions = "bypassPermissions", true
    +		if _, err := New(cfg); err != nil {
    +			t.Fatal(err)
    +		}
    +	})
    +
    +	t.Run("defaults", func(t *testing.T) {
    +		t.Parallel()
    +		h, err := New(valid)
    +		if err != nil {
    +			t.Fatal(err)
    +		}
    +		if h.cfg.InterruptGrace != defaultInterruptGrace || h.cfg.StartLimit != defaultStartLimit {
    +			t.Fatalf("defaults = %v, %d", h.cfg.InterruptGrace, h.cfg.StartLimit)
    +		}
    +		if h.postResultGrace != defaultPostResult || h.drainGrace != defaultDrainGrace {
    +			t.Fatalf("graces = %v, %v", h.postResultGrace, h.drainGrace)
    +		}
    +	})
    +}
    +
    +// TestRelativeBinary: a relative Binary is found from the current directory, and a turn runs it
    +// from WorkDir, a different directory. Not parallel: it changes the current directory.
    +func TestRelativeBinary(t *testing.T) {
    +	exe, err := os.Executable()
    +	if err != nil {
    +		t.Fatal(err)
    +	}
    +	fixture, err := filepath.Abs(filepath.Join("testdata", "text_turn.jsonl"))
    +	if err != nil {
    +		t.Fatal(err)
    +	}
    +	t.Chdir(filepath.Dir(exe))
    +	rel := "." + string(filepath.Separator) + filepath.Base(exe)
    +	h := newTestHarness(t, Config{Binary: rel})
    +	if h.cfg.Binary != exe {
    +		t.Fatalf("Binary = %q, want %q", h.cfg.Binary, exe)
    +	}
    +	setScenario(t, h, scenario{Fixture: fixture})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	if !slices.Equal(sink.outputs, []string{"Hello, world."}) {
    +		t.Fatalf("outputs = %q", sink.outputs)
    +	}
    +}
    +
    +func TestRunRequiresSessionUID(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), nil, sink); !errors.Is(err, errNoSession) {
    +		t.Fatalf("nil start: %v", err)
    +	}
    +	if err := h.Run(context.Background(), startFor("", "e1", nil, "hi"), sink); !errors.Is(err, errNoSession) {
    +		t.Fatalf("empty session UID: %v", err)
    +	}
    +	if got := starts(t, h); len(got) != 0 {
    +		t.Fatalf("spawned %d processes", len(got))
    +	}
    +}
    +
    +var uuidV5 = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`)
    +
    +func TestSessionID(t *testing.T) {
    +	t.Parallel()
    +	a0 := sessionID("uid-a", 0)
    +	if !uuidV5.MatchString(a0) {
    +		t.Fatalf("sessionID = %q, not a UUIDv5", a0)
    +	}
    +	if sessionID("uid-a", 0) != a0 {
    +		t.Fatal("sessionID is not deterministic")
    +	}
    +	for _, other := range []string{sessionID("uid-a", 1), sessionID("uid-b", 0), sessionID("uid-a/0", 0)} {
    +		if other == a0 {
    +			t.Fatalf("sessionID collision: %q", other)
    +		}
    +	}
    +}
    +
    +func TestFirstTurnThenResume(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{Model: "claude-test-model-1", MaxTurns: 7, MaxBudgetUSD: 1.5})
    +	setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +	ctx := context.Background()
    +	id := sessionID("uid", 0)
    +
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(ctx, startFor("uid", "e1", nil, "first", "second"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	got := starts(t, h)
    +	if len(got) != 1 {
    +		t.Fatalf("spawned %d processes, want 1", len(got))
    +	}
    +	wantArgs := []string{
    +		"-p", "--output-format", "stream-json", "--verbose", "--include-partial-messages",
    +		"--permission-mode", "dontAsk", "--setting-sources", "user", "--strict-mcp-config",
    +		"--session-id", id,
    +		"--model", "claude-test-model-1", "--max-turns", "7", "--max-budget-usd", "1.5",
    +	}
    +	if !slices.Equal(got[0].Args, wantArgs) {
    +		t.Fatalf("args = %q, want %q", got[0].Args, wantArgs)
    +	}
    +	if got[0].Stdin != "first\n\nsecond" {
    +		t.Fatalf("stdin = %q", got[0].Stdin)
    +	}
    +	// Partial text deltas are dropped; the result text is the one Output.
    +	if !slices.Equal(sink.outputs, []string{"Hello, world."}) {
    +		t.Fatalf("outputs = %q", sink.outputs)
    +	}
    +	if len(sink.reports) != 0 {
    +		t.Fatalf("reports = %+v", sink.reports)
    +	}
    +	wantUsage := []api.Usage{{Model: "claude-test-model-1", InputTokens: 12 + 100 + 200, OutputTokens: 5}}
    +	if !reflect.DeepEqual(sink.usages, wantUsage) {
    +		t.Fatalf("usages = %+v, want %+v", sink.usages, wantUsage)
    +	}
    +
    +	for i, exec := range []string{"e2", "e3"} {
    +		sink := &recordingSink{t: t}
    +		if err := h.Run(ctx, startFor("uid", exec, priorTurn("e1"), "again"), sink); err != nil {
    +			t.Fatalf("turn %d: %v", i+2, err)
    +		}
    +		got := starts(t, h)
    +		args := got[len(got)-1].Args
    +		if i := slices.Index(args, "--resume"); i < 0 || args[i+1] != id {
    +			t.Fatalf("turn args = %q, want --resume %s", args, id)
    +		}
    +		if slices.Contains(args, "--session-id") {
    +			t.Fatalf("turn args = %q carry --session-id", args)
    +		}
    +		if !slices.Equal(args[:10], wantArgs[:10]) {
    +			t.Fatalf("turn args = %q, want the permission pins %q", args, wantArgs[:10])
    +		}
    +	}
    +}
    +
    +// TestFailedFirstTurnMovesToNextAttempt: an id handed to a process that never confirmed it may
    +// have left a transcript behind, so the next first turn uses a fresh id.
    +func TestFailedFirstTurnMovesToNextAttempt(t *testing.T) {
    +	t.Parallel()
    +	for _, test := range []struct {
    +		name string
    +		sc   scenario
    +		want string
    +	}{
    +		{name: "exit before init", sc: scenario{Exit: 1}, want: "claudecode: claude exited with status 1 before a result"},
    +		{name: "session mismatch", sc: scenario{Fixture: "session_mismatch.jsonl"}, want: errSessionMismatch.Error()},
    +		{name: "events before init", sc: scenario{Fixture: "before_init.jsonl"}, want: errNoInit.Error()},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{})
    +			ctx := context.Background()
    +			setScenario(t, h, test.sc)
    +			err := h.Run(ctx, startFor("uid", "e1", nil, "hi"), &recordingSink{t: t})
    +			if err == nil || err.Error() != test.want {
    +				t.Fatalf("Run = %v, want %q", err, test.want)
    +			}
    +
    +			setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +			if err := h.Run(ctx, startFor("uid", "e2", priorTurn("e1"), "hi"), &recordingSink{t: t}); err != nil {
    +				t.Fatal(err)
    +			}
    +			if err := h.Run(ctx, startFor("uid", "e3", priorTurn("e2"), "hi"), &recordingSink{t: t}); err != nil {
    +				t.Fatal(err)
    +			}
    +			got := starts(t, h)
    +			want := [][]string{
    +				{"--session-id", sessionID("uid", 0)},
    +				{"--session-id", sessionID("uid", 1)},
    +				{"--resume", sessionID("uid", 1)},
    +			}
    +			if len(got) != len(want) {
    +				t.Fatalf("spawned %d processes, want %d", len(got), len(want))
    +			}
    +			for i, w := range want {
    +				j := slices.Index(got[i].Args, w[0])
    +				if j < 0 || got[i].Args[j+1] != w[1] {
    +					t.Fatalf("turn %d args = %q, want %q", i+1, got[i].Args, w)
    +				}
    +			}
    +		})
    +	}
    +}
    +
    +func TestToolResultsReported(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	setScenario(t, h, scenario{Fixture: "tool_turn.jsonl"})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	text := func(s string) []api.Part { return []api.Part{{Text: &api.TextPart{Text: s}}} }
    +	bashIn := `{"command":"ls","description":"List files"}`
    +	grepIn := `{"pattern":"TODO"}`
    +	taskIn := `{"description":"search","prompt":"find TODOs","subagent_type":"general-purpose"}`
    +	readIn := `{"file_path":"a.txt"}`
    +	want := []api.ToolResult{
    +		{ID: "toolu_01", Output: map[string]any{"tool": "Bash", "input": bashIn, "input_bytes": float64(len(bashIn)), "truncated": false}, Content: text("a.txt\nb.txt")},
    +		{ID: "toolu_03", Output: map[string]any{"tool": "Grep", "parent_tool_use_id": "toolu_02", "input": grepIn, "input_bytes": float64(len(grepIn)), "truncated": false}, Content: text("a.txt:1: TODO"), IsError: true},
    +		{ID: "toolu_02", Output: map[string]any{"tool": "Task", "input": taskIn, "input_bytes": float64(len(taskIn)), "truncated": false}, Content: text("Found one TODO.")},
    +		// A result whose tool_use the stream never showed is reported without a tool name.
    +		{ID: "toolu_99", Output: map[string]any{"input": "", "input_bytes": float64(0), "truncated": false}, Content: text("orphan")},
    +		// A tool_use that never got a result is closed out at the end of the turn.
    +		{ID: "toolu_04", Output: map[string]any{"tool": "Read", "input": readIn, "input_bytes": float64(len(readIn)), "truncated": false}, IsError: true, Error: "no result observed"},
    +	}
    +	if !reflect.DeepEqual(sink.reports, want) {
    +		t.Fatalf("reports =\n%+v\nwant\n%+v", sink.reports, want)
    +	}
    +	if !slices.Equal(sink.outputs, []string{"Done."}) {
    +		t.Fatalf("outputs = %q", sink.outputs)
    +	}
    +	wantUsage := []api.Usage{{Model: "claude-test-model-1", InputTokens: 60 + 5 + 180, OutputTokens: 40}}
    +	if !reflect.DeepEqual(sink.usages, wantUsage) {
    +		t.Fatalf("usages = %+v, want %+v", sink.usages, wantUsage)
    +	}
    +}
    +
    +// toolPair returns an assistant tool_use line and its user tool_result line.
    +func toolPair(id, input, content string) []string {
    +	return []string{
    +		fmt.Sprintf(`{"type":"assistant","message":{"id":"msg_%s","content":[{"type":"tool_use","id":"%s","name":"Bash","input":{"command":%q}}]},"parent_tool_use_id":null,"session_id":"{{SESSION_ID}}"}`, id, id, input),
    +		fmt.Sprintf(`{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"%s","content":%q}]},"parent_tool_use_id":null,"session_id":"{{SESSION_ID}}"}`, id, content),
    +	}
    +}
    +
    +const (
    +	initLine    = `{"type":"system","subtype":"init","session_id":"{{SESSION_ID}}","model":"claude-test-model-1"}`
    +	successLine = `{"type":"result","subtype":"success","is_error":false,"result":"ok","session_id":"{{SESSION_ID}}","usage":{"input_tokens":1,"output_tokens":1}}`
    +)
    +
    +func TestReceiptIsBounded(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	big := strings.Repeat("é", 5000) // 10000 bytes; 2048 is not a rune boundary
    +	lines := append([]string{initLine}, toolPair("toolu_big", big, big)...)
    +	setScenario(t, h, scenario{Lines: append(lines, successLine)})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	if len(sink.reports) != 1 {
    +		t.Fatalf("reports = %d", len(sink.reports))
    +	}
    +	tr := sink.reports[0]
    +	in, _ := tr.Output["input"].(string)
    +	content := tr.Content[0].Text.Text
    +	for name, s := range map[string]string{"input": in, "content": content} {
    +		if len(s) > receiptFieldBytes || len(s) < receiptFieldBytes-4 || !utf8.ValidString(s) {
    +			t.Fatalf("%s receipt is %d bytes (valid UTF-8 %v), want at most %d", name, len(s), utf8.ValidString(s), receiptFieldBytes)
    +		}
    +	}
    +	if tr.Output["truncated"] != true || tr.Output["input_bytes"] != float64(len(`{"command":"`+big+`"}`)) {
    +		t.Fatalf("receipt output = %v", tr.Output)
    +	}
    +}
    +
    +// TestReceiptsShrinkPastTurnBudget: once one turn's full receipts pass the budget, the rest of the
    +// turn reports sizes only.
    +func TestReceiptsShrinkPastTurnBudget(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	payload := strings.Repeat("x", 3000)
    +	lines := []string{initLine}
    +	const n = 60 // about 4 KiB each, past the 128 KiB budget
    +	for i := range n {
    +		lines = append(lines, toolPair(fmt.Sprintf("toolu_%02d", i), payload, payload)...)
    +	}
    +	setScenario(t, h, scenario{Lines: append(lines, successLine)})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	if len(sink.reports) != n {
    +		t.Fatalf("reports = %d, want %d", len(sink.reports), n)
    +	}
    +	full := 0
    +	for i, tr := range sink.reports {
    +		if tr.Output["omitted"] == true {
    +			if tr.Content != nil || tr.Output["input"] != nil {
    +				t.Fatalf("minimal receipt %d carries content: %+v", i, tr)
    +			}
    +			if tr.Output["content_bytes"] != float64(len(payload)+2) || tr.Output["tool"] != "Bash" {
    +				t.Fatalf("minimal receipt %d = %v", i, tr.Output)
    +			}
    +			continue
    +		}
    +		if full != i {
    +			t.Fatalf("full receipt %d follows a minimal one", i)
    +		}
    +		full++
    +	}
    +	if full == 0 || full == n {
    +		t.Fatalf("full receipts = %d of %d, want the budget to cut in", full, n)
    +	}
    +}
    +
    +// TestReceiptsShrinkWithLargeHistory: History past half the Start limit leaves no room for full
    +// receipts, and the harness warns once History nears the limit.
    +func TestReceiptsShrinkWithLargeHistory(t *testing.T) {
    +	t.Parallel()
    +	history := []api.Event{{Kind: api.EventOutput, Message: api.TextMessage("assistant", strings.Repeat("h", 3500))}}
    +	for _, test := range []struct {
    +		name        string
    +		limit       int
    +		wantOmitted bool
    +		wantWarn    bool
    +	}{
    +		{name: "small history", limit: 0},
    +		{name: "history past half the limit", limit: 6000, wantOmitted: true},
    +		{name: "history near the limit", limit: 4096, wantOmitted: true, wantWarn: true},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{StartLimit: test.limit})
    +			var logs bytes.Buffer
    +			h.logger = slog.New(slog.NewTextHandler(&logs, nil))
    +			lines := append([]string{initLine}, toolPair("toolu_1", "ls", "a.txt")...)
    +			setScenario(t, h, scenario{Lines: append(lines, successLine)})
    +			sink := &recordingSink{t: t}
    +			if err := h.Run(context.Background(), startFor("uid", "e1", history, "go"), sink); err != nil {
    +				t.Fatal(err)
    +			}
    +			if got := sink.reports[0].Output["omitted"] == true; got != test.wantOmitted {
    +				t.Fatalf("omitted = %v, want %v: %+v", got, test.wantOmitted, sink.reports[0])
    +			}
    +			if got := strings.Contains(logs.String(), "level=WARN"); got != test.wantWarn {
    +				t.Fatalf("warned = %v, want %v: %s", got, test.wantWarn, logs.String())
    +			}
    +		})
    +	}
    +}
    +
    +func TestUsage(t *testing.T) {
    +	t.Parallel()
    +	for _, test := range []struct {
    +		name    string
    +		sc      scenario
    +		wantErr string
    +		want    []api.Usage
    +	}{
    +		{
    +			name: "result usage: token counts only, total_cost_usd dropped",
    +			sc:   scenario{Fixture: "text_turn.jsonl"},
    +			want: []api.Usage{{Model: "claude-test-model-1", InputTokens: 12 + 100 + 200, OutputTokens: 5}},
    +		},
    +		{
    +			name:    "zeroed result usage falls back to main-loop input",
    +			sc:      scenario{Fixture: "zero_usage_result.jsonl"},
    +			wantErr: "claudecode: claude reported an error result (subtype error_during_execution)",
    +			want:    []api.Usage{{Model: "claude-test-model-1", InputTokens: (4 + 2 + 1) + (8 + 0 + 3)}},
    +		},
    +		{
    +			name: "no result: once per message id, subagents excluded",
    +			sc: scenario{Lines: []string{
    +				initLine,
    +				`{"type":"assistant","message":{"id":"msg_a","content":[{"type":"text","text":"a"}],"usage":{"input_tokens":5,"cache_read_input_tokens":2,"output_tokens":1}},"parent_tool_use_id":null}`,
    +				`{"type":"assistant","message":{"id":"msg_a","content":[{"type":"text","text":"b"}],"usage":{"input_tokens":5,"cache_read_input_tokens":2,"output_tokens":1}},"parent_tool_use_id":null}`,
    +				`{"type":"assistant","message":{"id":"msg_s","content":[],"usage":{"input_tokens":999,"output_tokens":1}},"parent_tool_use_id":"toolu_x"}`,
    +			}},
    +			wantErr: errNoResult.Error(),
    +			want:    []api.Usage{{Model: "claude-test-model-1", InputTokens: 7}},
    +		},
    +		{
    +			name:    "nothing to report",
    +			sc:      scenario{Fixture: "init_only.jsonl"},
    +			wantErr: errNoResult.Error(),
    +		},
    +		{
    +			name: "init model missing: the turn's model",
    +			sc: scenario{Lines: []string{
    +				`{"type":"system","subtype":"init","session_id":"{{SESSION_ID}}"}`,
    +				successLine,
    +			}},
    +			want: []api.Usage{{Model: "configured", InputTokens: 1, OutputTokens: 1}},
    +		},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{Model: "configured"})
    +			setScenario(t, h, test.sc)
    +			sink := &recordingSink{t: t}
    +			err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink)
    +			if got := fmt.Sprint(err); (err != nil || test.wantErr != "") && got != test.wantErr {
    +				t.Fatalf("Run = %v, want %q", err, test.wantErr)
    +			}
    +			if !reflect.DeepEqual(sink.usages, test.want) {
    +				t.Fatalf("usages = %+v, want %+v", sink.usages, test.want)
    +			}
    +		})
    +	}
    +}
    +
    +func TestFailedTurns(t *testing.T) {
    +	t.Parallel()
    +	for _, test := range []struct {
    +		name        string
    +		sc          scenario
    +		want        string
    +		wantUsage   []api.Usage
    +		wantReports int
    +	}{
    +		{
    +			name:      "error result",
    +			sc:        scenario{Fixture: "error_result.jsonl"},
    +			want:      "claudecode: claude reported an error result (subtype error_max_turns)",
    +			wantUsage: []api.Usage{{Model: "claude-test-model-1", InputTokens: 10, OutputTokens: 2}},
    +		},
    +		{
    +			name: "error flag with success subtype",
    +			sc: scenario{Lines: []string{initLine,
    +				`{"type":"result","subtype":"success","is_error":true,"result":"API Error: 500","session_id":"{{SESSION_ID}}"}`}},
    +			want: "claudecode: claude reported an error result (subtype success)",
    +		},
    +		{
    +			name: "unsafe subtype",
    +			sc: scenario{Lines: []string{initLine,
    +				`{"type":"result","subtype":"error: sk-secret","is_error":true,"session_id":"{{SESSION_ID}}"}`}},
    +			want: "claudecode: claude reported an error result (subtype unknown)",
    +		},
    +		{
    +			name: "non-zero exit before a result",
    +			sc:   scenario{Fixture: "init_only.jsonl", Exit: 3},
    +			want: "claudecode: claude exited with status 3 before a result",
    +		},
    +		{
    +			name:      "non-zero exit after success",
    +			sc:        scenario{Fixture: "text_turn.jsonl", Exit: 2},
    +			want:      "claudecode: claude exited with status 2 after a success result",
    +			wantUsage: []api.Usage{{Model: "claude-test-model-1", InputTokens: 312, OutputTokens: 5}},
    +		},
    +		{
    +			name:        "stream ends without a result",
    +			sc:          scenario{Fixture: "truncated.jsonl"},
    +			want:        errNoResult.Error(),
    +			wantUsage:   []api.Usage{{Model: "claude-test-model-1", InputTokens: 7}},
    +			wantReports: 1,
    +		},
    +		{
    +			name: "stream cut mid-line",
    +			sc:   scenario{Fixture: "init_only.jsonl", Partial: `{"type":"result","subtype":"succ`},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name: "malformed line",
    +			sc:   scenario{Fixture: "malformed.jsonl"},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name:      "malformed line after a success result",
    +			sc:        scenario{Fixture: "text_turn.jsonl", Lines: []string{`{"type":"assistant","message":`}},
    +			want:      errMalformed.Error(),
    +			wantUsage: []api.Usage{{Model: "claude-test-model-1", InputTokens: 312, OutputTokens: 5}},
    +		},
    +		{
    +			name:      "stream cut mid-line after a success result",
    +			sc:        scenario{Fixture: "text_turn.jsonl", Partial: `{"type":"stream_ev`},
    +			want:      errMalformed.Error(),
    +			wantUsage: []api.Usage{{Model: "claude-test-model-1", InputTokens: 312, OutputTokens: 5}},
    +		},
    +		{
    +			name: "negative usage",
    +			sc: scenario{Lines: []string{initLine,
    +				`{"type":"result","subtype":"success","result":"x","session_id":"{{SESSION_ID}}","usage":{"input_tokens":-1}}`}},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name: "tool_use without id",
    +			sc: scenario{Lines: []string{initLine,
    +				`{"type":"assistant","message":{"id":"m","content":[{"type":"tool_use","name":"Bash","input":{}}]}}`}},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name: "tool_result without tool_use_id",
    +			sc: scenario{Lines: []string{initLine,
    +				`{"type":"user","message":{"content":[{"type":"tool_result","content":"x"}]}}`}},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name: "content is not blocks",
    +			sc:   scenario{Lines: []string{initLine, `{"type":"assistant","message":{"id":"m","content":[1]}}`}},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name: "line over the limit",
    +			sc:   scenario{Lines: []string{initLine, `{"type":"assistant","x":"` + strings.Repeat("x", maxLineBytes) + `"}`, successLine}},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name: "session id changes mid-stream",
    +			sc: scenario{Lines: []string{initLine,
    +				`{"type":"result","subtype":"success","result":"x","session_id":"11111111-1111-4111-8111-111111111111"}`}},
    +			want: errSessionMismatch.Error(),
    +		},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{})
    +			setScenario(t, h, test.sc)
    +			sink := &recordingSink{t: t}
    +			err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink)
    +			if err == nil || err.Error() != test.want {
    +				t.Fatalf("Run = %v, want %q", err, test.want)
    +			}
    +			if len(sink.outputs) != 0 {
    +				t.Fatalf("failed turn recorded output %q", sink.outputs)
    +			}
    +			if !reflect.DeepEqual(sink.usages, test.wantUsage) {
    +				t.Fatalf("usages = %+v, want %+v", sink.usages, test.wantUsage)
    +			}
    +			if len(sink.reports) != test.wantReports {
    +				t.Fatalf("reports = %+v, want %d", sink.reports, test.wantReports)
    +			}
    +		})
    +	}
    +}
    +
    +// TestLinesAfterResult: well-formed lines after the result are decoded but have no sink effect: a
    +// late tool result is not reported and late usage is not counted.
    +func TestLinesAfterResult(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	setScenario(t, h, scenario{Fixture: "text_turn.jsonl", Lines: []string{
    +		"",
    +		`{"type":"assistant","message":{"id":"late","content":[{"type":"tool_use","id":"toolu_late","name":"Bash","input":{}}],"usage":{"input_tokens":999}},"session_id":"{{SESSION_ID}}"}`,
    +		`{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_late","content":"x"}]},"session_id":"{{SESSION_ID}}"}`,
    +		`{"type":"some_future_event"}`,
    +	}})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	if !slices.Equal(sink.outputs, []string{"Hello, world."}) || len(sink.reports) != 0 {
    +		t.Fatalf("outputs = %q, reports = %+v", sink.outputs, sink.reports)
    +	}
    +	if want := []api.Usage{{Model: "claude-test-model-1", InputTokens: 312, OutputTokens: 5}}; !reflect.DeepEqual(sink.usages, want) {
    +		t.Fatalf("usages = %+v, want %+v", sink.usages, want)
    +	}
    +}
    +
    +func TestTruncatedStreamClosesDanglingTool(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	setScenario(t, h, scenario{Fixture: "truncated.jsonl"})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); !errors.Is(err, errNoResult) {
    +		t.Fatalf("Run = %v", err)
    +	}
    +	tr := sink.reports[0]
    +	if tr.ID != "toolu_30" || !tr.IsError || tr.Error != "no result observed" || tr.Output["tool"] != "Bash" {
    +		t.Fatalf("dangling report = %+v", tr)
    +	}
    +}
    +
    +func TestOutputChunked(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	text := strings.Repeat("é", 1_300_000) // 2.6 MB; 1 MiB is not a rune boundary
    +	setScenario(t, h, scenario{Lines: []string{
    +		initLine,
    +		fmt.Sprintf(`{"type":"result","subtype":"success","result":%q,"session_id":"{{SESSION_ID}}"}`, text),
    +	}})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	if len(sink.outputs) != 3 {
    +		t.Fatalf("outputs = %d chunks, want 3", len(sink.outputs))
    +	}
    +	for i, c := range sink.outputs {
    +		if len(c) > outputChunkBytes || !utf8.ValidString(c) {
    +			t.Fatalf("chunk %d: %d bytes, valid UTF-8 %v", i, len(c), utf8.ValidString(c))
    +		}
    +	}
    +	if strings.Join(sink.outputs, "") != text {
    +		t.Fatal("chunks do not rejoin to the result")
    +	}
    +}
    +
    +func TestChunksAndTruncate(t *testing.T) {
    +	t.Parallel()
    +	if got := chunks("", 4); got != nil {
    +		t.Fatalf("chunks of empty = %q", got)
    +	}
    +	if got := chunks("aébc", 2); !slices.Equal(got, []string{"a", "é", "bc"}) {
    +		t.Fatalf("chunks = %q", got)
    +	}
    +	if got := chunks("é", 1); strings.Join(got, "") != "é" {
    +		t.Fatalf("chunks below one rune = %q", got)
    +	}
    +	if s, cut := truncate("abc", 3); s != "abc" || cut {
    +		t.Fatalf("truncate = %q, %v", s, cut)
    +	}
    +	if s, cut := truncate("aé", 2); s != "a" || !cut {
    +		t.Fatalf("truncate = %q, %v", s, cut)
    +	}
    +}
    +
    +func TestRerunRefused(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +	ctx := context.Background()
    +	if err := h.Run(ctx, startFor("uid", "e1", nil, "go"), &recordingSink{t: t}); err != nil {
    +		t.Fatal(err)
    +	}
    +	// A recovery re-run of the same execution must not start a second billed turn.
    +	if err := h.Run(ctx, startFor("uid", "e1", nil, "go"), &recordingSink{t: t}); !errors.Is(err, errRerun) {
    +		t.Fatalf("re-run = %v, want %v", err, errRerun)
    +	}
    +	if got := starts(t, h); len(got) != 1 {
    +		t.Fatalf("spawned %d processes, want 1", len(got))
    +	}
    +}
    +
    +// TestCancelledBeforeStart: a turn whose ctx is done when Run is called launches nothing and is
    +// not recorded as started, so its retry runs. The session's state is still created, so a later
    +// turn whose History shows the cancelled one does not look like lost memory.
    +func TestCancelledBeforeStart(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +	ctx, cancel := context.WithCancel(context.Background())
    +	cancel()
    +	err := h.Run(ctx, startFor("uid", "e1", nil, "go"), &recordingSink{t: t})
    +	if !errors.Is(err, context.Canceled) || err.Error() != "claudecode: turn interrupted: context canceled" {
    +		t.Fatalf("Run = %v", err)
    +	}
    +	if got := starts(t, h); len(got) != 0 {
    +		t.Fatalf("spawned %d processes", len(got))
    +	}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), &recordingSink{t: t}); err != nil {
    +		t.Fatalf("retry = %v", err)
    +	}
    +	// A ctx cancelled after begin, while the inputs are checked, still launches nothing.
    +	tr := &turn{h: h, sink: &recordingSink{t: t}, sessionUID: "uid", flag: "--resume", sessionID: sessionID("uid", 0)}
    +	if err := tr.run(ctx, h.args(tr.flag, tr.sessionID, ""), "go"); !errors.Is(err, context.Canceled) {
    +		t.Fatalf("run = %v", err)
    +	}
    +	if got := starts(t, h); len(got) != 1 {
    +		t.Fatalf("spawned %d processes, want 1", len(got))
    +	}
    +	h2 := newTestHarness(t, Config{})
    +	setScenario(t, h2, scenario{Fixture: "text_turn.jsonl"})
    +	if err := h2.Run(ctx, startFor("uid", "e1", nil, "go"), &recordingSink{t: t}); !errors.Is(err, context.Canceled) {
    +		t.Fatalf("Run = %v", err)
    +	}
    +	if err := h2.Run(context.Background(), startFor("uid", "e2", priorTurn("e1"), "go"), &recordingSink{t: t}); err != nil {
    +		t.Fatalf("next turn = %v", err)
    +	}
    +}
    +
    +func TestLostStateFailsClosed(t *testing.T) {
    +	t.Parallel()
    +	for _, test := range []struct {
    +		name    string
    +		history []api.Event
    +	}{
    +		{name: "earlier execution", history: priorTurn("e0")},
    +		{name: "legacy input", history: []api.Event{{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}}},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{})
    +			setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +			err := h.Run(context.Background(), startFor("uid", "e1", test.history, "go"), &recordingSink{t: t})
    +			if !errors.Is(err, errStateLost) {
    +				t.Fatalf("Run = %v, want %v", err, errStateLost)
    +			}
    +			if got := starts(t, h); len(got) != 0 {
    +				t.Fatalf("spawned %d processes", len(got))
    +			}
    +		})
    +	}
    +}
    +
    +// TestInvalidFirstTurnDoesNotWedge: a first turn refused before it spawns keeps the session's
    +// state, so the next turn, whose History now shows a turn, still starts the session.
    +func TestInvalidFirstTurnDoesNotWedge(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +	ctx := context.Background()
    +	if err := h.Run(ctx, startFor("uid", "e1", nil), &recordingSink{t: t}); !errors.Is(err, errNoPrompt) {
    +		t.Fatalf("Run = %v, want %v", err, errNoPrompt)
    +	}
    +	if err := h.Run(ctx, startFor("uid", "e2", priorTurn("e1"), "go"), &recordingSink{t: t}); err != nil {
    +		t.Fatal(err)
    +	}
    +	got := starts(t, h)
    +	if len(got) != 1 || !slices.Contains(got[0].Args, "--session-id") || !slices.Contains(got[0].Args, sessionID("uid", 0)) {
    +		t.Fatalf("starts = %+v, want one --session-id %s", got, sessionID("uid", 0))
    +	}
    +}
    +
    +func TestInputValidation(t *testing.T) {
    +	t.Parallel()
    +	data := api.Message{Role: "user", Parts: []api.Part{{Data: map[string]any{"k": "v"}}}}
    +	for _, test := range []struct {
    +		name   string
    +		inputs []api.Message
    +		want   error
    +	}{
    +		{name: "no inputs", want: errNoPrompt},
    +		{name: "empty text", inputs: []api.Message{*api.TextMessage("user", "")}, want: errNoPrompt},
    +		{name: "non-text part", inputs: []api.Message{*api.TextMessage("user", "hi"), data}, want: errNonText},
    +		{name: "too large", inputs: []api.Message{*api.TextMessage("user", strings.Repeat("x", maxPromptBytes+1))}, want: errPromptSize},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{})
    +			s := &api.Start{ExecutionID: "e1", SessionUID: "uid", Inputs: test.inputs}
    +			if err := h.Run(context.Background(), s, &recordingSink{t: t}); !errors.Is(err, test.want) {
    +				t.Fatalf("Run = %v, want %v", err, test.want)
    +			}
    +			if got := starts(t, h); len(got) != 0 {
    +				t.Fatalf("spawned %d processes", len(got))
    +			}
    +		})
    +	}
    +}
    +
    +func TestModelSelection(t *testing.T) {
    +	t.Parallel()
    +	for _, test := range []struct {
    +		name      string
    +		cfg       string
    +		requested string
    +		wantModel string // "" means no --model
    +		wantErr   error
    +	}{
    +		{name: "configured", cfg: "claude-test-model-1", wantModel: "claude-test-model-1"},
    +		{name: "configured and requested", cfg: "claude-test-model-1", requested: "claude-test-model-1", wantModel: "claude-test-model-1"},
    +		{name: "requested differs from configured", cfg: "claude-test-model-1", requested: "other", wantErr: errModelMismatch},
    +		{name: "requested only", requested: "claude-test-model-2", wantModel: "claude-test-model-2"},
    +		{name: "requested flag", requested: "--bare", wantErr: errModelArg},
    +		{name: "neither"},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{Model: test.cfg})
    +			setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +			s := startFor("uid", "e1", nil, "go")
    +			s.Model = test.requested
    +			err := h.Run(context.Background(), s, &recordingSink{t: t})
    +			if !errors.Is(err, test.wantErr) {
    +				t.Fatalf("Run = %v, want %v", err, test.wantErr)
    +			}
    +			got := starts(t, h)
    +			if test.wantErr != nil {
    +				if len(got) != 0 {
    +					t.Fatalf("spawned %d processes", len(got))
    +				}
    +				return
    +			}
    +			i := slices.Index(got[0].Args, "--model")
    +			switch {
    +			case test.wantModel == "" && i >= 0:
    +				t.Fatalf("args = %q, want no --model", got[0].Args)
    +			case test.wantModel != "" && (i < 0 || got[0].Args[i+1] != test.wantModel):
    +				t.Fatalf("args = %q, want --model %s", got[0].Args, test.wantModel)
    +			}
    +		})
    +	}
    +}
    +
    +// TestStderrNeverSurfaces: stderr can carry prompt or tool text, so for a process that reached
    +// system/init it reaches no error, sink call or log.
    +func TestStderrNeverSurfaces(t *testing.T) {
    +	t.Parallel()
    +	const sentinel = "STDERR-SENTINEL-must-not-surface"
    +	for _, sc := range []scenario{
    +		{Fixture: "init_only.jsonl", Exit: 3, Stderr: sentinel},
    +		{Fixture: "error_result.jsonl", Stderr: sentinel},
    +		{Fixture: "tool_turn.jsonl", Stderr: sentinel},
    +	} {
    +		h := newTestHarness(t, Config{})
    +		var logs bytes.Buffer
    +		h.logger = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
    +		setScenario(t, h, sc)
    +		sink := &recordingSink{t: t}
    +		err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink)
    +		seen := fmt.Sprint(err, sink.outputs, sink.reports, sink.usages, logs.String())
    +		if strings.Contains(seen, sentinel) {
    +			t.Fatalf("stderr surfaced: %s", seen)
    +		}
    +	}
    +}
    +
    +func TestSinkErrorsFailTheTurn(t *testing.T) {
    +	t.Parallel()
    +	refused := errors.New("refused")
    +	for _, test := range []struct {
    +		name string
    +		sink *recordingSink
    +		want string
    +	}{
    +		{name: "report", sink: &recordingSink{reportErr: refused}, want: "claudecode: record tool result: refused"},
    +		{name: "output", sink: &recordingSink{outputErr: refused}, want: "claudecode: record output: refused"},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{})
    +			setScenario(t, h, scenario{Fixture: "tool_turn.jsonl"})
    +			test.sink.t = t
    +			err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), test.sink)
    +			if err == nil || err.Error() != test.want {
    +				t.Fatalf("Run = %v, want %q", err, test.want)
    +			}
    +		})
    +	}
    +}
    +
    +// TestChildEnvironment: the claude process gets the default and configured variables of the
    +// harness's environment and nothing else. Not parallel: it sets environment variables.
    +func TestChildEnvironment(t *testing.T) {
    +	t.Setenv("CLAUDECODE_TEST_SECRET", "must-not-reach-claude")
    +	t.Setenv("CLAUDECODE_TEST_EXTRA", "x")
    +	t.Setenv("CLAUDECODE_TEST_EMPTY", "")
    +	t.Setenv("ANTHROPIC_BASE_URL", "http://egress.invalid")
    +	t.Setenv("CLAUDECODE_TEST_UNSET", "")
    +	os.Unsetenv("CLAUDECODE_TEST_UNSET")
    +	extra := []string{"CLAUDECODE_TEST_EXTRA", "CLAUDECODE_TEST_EMPTY", "CLAUDECODE_TEST_UNSET", "PATH"}
    +	h := newTestHarness(t, Config{EnvAllowlist: extra})
    +	// Read once at New: a later change does not reach the process.
    +	t.Setenv("CLAUDECODE_TEST_EXTRA", "changed")
    +	setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), &recordingSink{t: t}); err != nil {
    +		t.Fatal(err)
    +	}
    +	got := starts(t, h)[0].Env
    +	for _, name := range []string{"CLAUDECODE_TEST_EXTRA", "CLAUDECODE_TEST_EMPTY", "ANTHROPIC_BASE_URL", "PATH"} {
    +		if !slices.Contains(got, name) {
    +			t.Errorf("claude env %q lacks %s", got, name)
    +		}
    +	}
    +	allowed := slices.Concat(defaultEnv, extra)
    +	for _, name := range got {
    +		if !slices.Contains(allowed, name) {
    +			t.Errorf("claude env has %s, which is not allowlisted", name)
    +		}
    +	}
    +	if slices.Contains(got, "CLAUDECODE_TEST_SECRET") || slices.Contains(got, "CLAUDECODE_TEST_UNSET") {
    +		t.Fatalf("claude env = %q", got)
    +	}
    +	if !slices.Contains(h.env, "CLAUDECODE_TEST_EXTRA=x") || !slices.Contains(h.env, "CLAUDECODE_TEST_EMPTY=") {
    +		t.Fatalf("harness env = %q", h.env)

    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.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 08, 2026 06:59 UTC
    Reviewer

    <!-- 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>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Pin a root-module version containing the harnessnode package · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Implement process cleanup or reject unsupported platforms · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Restrict stderr logging to the expected missing-transcript diagnostic · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Avoid printing environment values in failed assertions · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Validate stream lines after a success result

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Resolve relative binary paths before changing the working directory

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Update published contracts for unmediated harness behavior

  • </details>

    <details>
    <summary><strong>2 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Slow sink processing can exhaust the output drain grace period

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Pre-canceled Run still starts the Claude Code process

  • </details>

    <sub>Review effort: Balanced</sub>

    aramase aramase commented on code on Nov 08, 2026 07:41 UTC
    Code Review
    integrations/claudecode/proc_other.go:1
    @@ -0,0 +1,22 @@
    +//go:build !unix
    +
    +package claudecode
    +
    +import (
    +	"os"
    +	"syscall"
    +	"time"
    +)
    +
    +// sysProcAttr sets nothing: there is no process group to create.
    +func sysProcAttr() *syscall.SysProcAttr { return nil }
    +
    +// interruptProcess kills the process: there is no SIGINT to send.
    +func interruptProcess(p *os.Process) { _ = p.Kill() }
    +
    +// killGroup kills the process; processes it started are not reached.
    +func killGroup(p *os.Process) { _ = p.Kill() }
    +
    +// stopGroup has no group to stop: the process was already waited for, and processes it started
    +// are not reached.
    +func stopGroup(*os.Process, time.Duration) bool { return true }

    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.

    aramase aramase commented on code on Nov 08, 2026 07:41 UTC
    Code Review
    integrations/claudecode/claudecode_test.go:1
    @@ -0,0 +1,1098 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"log/slog"
    +	"math"
    +	"os"
    +	"path/filepath"
    +	"reflect"
    +	"regexp"
    +	"slices"
    +	"strings"
    +	"testing"
    +	"time"
    +	"unicode/utf8"
    +
    +	"github.com/agent-primitives/sessions/api"
    +)
    +
    +func TestDescribe(t *testing.T) {
    +	t.Parallel()
    +	for _, test := range []struct {
    +		name  string
    +		model string
    +		want  []string
    +	}{
    +		{name: "no model"},
    +		{name: "configured model", model: "claude-test-model-1", want: []string{"claude-test-model-1"}},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{Model: test.model})
    +			got, err := h.Describe(context.Background())
    +			if err != nil {
    +				t.Fatal(err)
    +			}
    +			// Version is the stable author-owned replay version: bump it only when execution
    +			// behavior changes.
    +			want := api.Descriptor{
    +				ID:      "claudecode",
    +				Version: "1",
    +				Models:  test.want,
    +				Capabilities: api.Capabilities{
    +					Resumability: api.ResumabilityRequiresMemorySnapshot,
    +					ForkSafe:     false,
    +					Streaming:    true,
    +				},
    +			}
    +			if !reflect.DeepEqual(got, want) {
    +				t.Fatalf("Describe = %+v, want %+v", got, want)
    +			}
    +		})
    +	}
    +}
    +
    +func TestNewValidatesConfig(t *testing.T) {
    +	t.Parallel()
    +	exe, err := os.Executable()
    +	if err != nil {
    +		t.Fatal(err)
    +	}
    +	dir := t.TempDir()
    +	file := filepath.Join(dir, "file")
    +	if err := os.WriteFile(file, nil, 0o600); err != nil {
    +		t.Fatal(err)
    +	}
    +	valid := Config{Binary: exe, WorkDir: dir, PermissionMode: "dontAsk"}
    +	for _, test := range []struct {
    +		name   string
    +		mutate func(*Config)
    +		want   string
    +	}{
    +		{name: "binary not found", mutate: func(c *Config) { c.Binary = "claudecode-test-no-such-binary" }, want: "find claude binary"},
    +		{name: "no workdir", mutate: func(c *Config) { c.WorkDir = "" }, want: "WorkDir is required"},
    +		{name: "missing workdir", mutate: func(c *Config) { c.WorkDir = filepath.Join(dir, "missing") }, want: "WorkDir"},
    +		{name: "workdir is a file", mutate: func(c *Config) { c.WorkDir = file }, want: "is not a directory"},
    +		{name: "no permission mode", mutate: func(c *Config) { c.PermissionMode = "" }, want: "PermissionMode is required"},
    +		{name: "permission mode is a flag", mutate: func(c *Config) { c.PermissionMode = "--bare" }, want: "invalid PermissionMode"},
    +		{name: "permission mode with space", mutate: func(c *Config) { c.PermissionMode = "a b" }, want: "invalid PermissionMode"},
    +		{name: "model is a flag", mutate: func(c *Config) { c.Model = "-m" }, want: "invalid Model"},
    +		{name: "model with newline", mutate: func(c *Config) { c.Model = "m\n" }, want: "invalid Model"},
    +		{name: "negative max turns", mutate: func(c *Config) { c.MaxTurns = -1 }, want: "MaxTurns"},
    +		{name: "negative budget", mutate: func(c *Config) { c.MaxBudgetUSD = -1 }, want: "MaxBudgetUSD"},
    +		{name: "NaN budget", mutate: func(c *Config) { c.MaxBudgetUSD = math.NaN() }, want: "MaxBudgetUSD"},
    +		{name: "infinite budget", mutate: func(c *Config) { c.MaxBudgetUSD = math.Inf(1) }, want: "MaxBudgetUSD"},
    +		{name: "negative interrupt grace", mutate: func(c *Config) { c.InterruptGrace = -time.Second }, want: "InterruptGrace"},
    +		{name: "negative start limit", mutate: func(c *Config) { c.StartLimit = -1 }, want: "StartLimit"},
    +		{name: "bypass without opt-in", mutate: func(c *Config) { c.PermissionMode = "bypassPermissions" }, want: "PermissionMode bypassPermissions also requires AllowBypassPermissions"},
    +		{name: "bypass case variant without opt-in", mutate: func(c *Config) { c.PermissionMode = "BYPASSPERMISSIONS" }, want: "requires AllowBypassPermissions"},
    +		{name: "opt-in without bypass", mutate: func(c *Config) { c.AllowBypassPermissions = true }, want: `AllowBypassPermissions is set but PermissionMode is "dontAsk"`},
    +		{name: "empty env name", mutate: func(c *Config) { c.EnvAllowlist = []string{"HTTPS_PROXY", ""} }, want: "invalid EnvAllowlist name"},
    +		{name: "env name with =", mutate: func(c *Config) { c.EnvAllowlist = []string{"A=B"} }, want: "invalid EnvAllowlist name"},
    +		{name: "env name with NUL", mutate: func(c *Config) { c.EnvAllowlist = []string{"A\x00"} }, want: "invalid EnvAllowlist name"},
    +		{name: "env name with space", mutate: func(c *Config) { c.EnvAllowlist = []string{" A"} }, want: "invalid EnvAllowlist name"},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			cfg := valid
    +			test.mutate(&cfg)
    +			_, err := New(cfg)
    +			if err == nil || !strings.Contains(err.Error(), test.want) {
    +				t.Fatalf("New error = %v, want one containing %q", err, test.want)
    +			}
    +		})
    +	}
    +
    +	t.Run("bypass with opt-in", func(t *testing.T) {
    +		t.Parallel()
    +		cfg := valid
    +		cfg.PermissionMode, cfg.AllowBypassPermissions = "bypassPermissions", true
    +		if _, err := New(cfg); err != nil {
    +			t.Fatal(err)
    +		}
    +	})
    +
    +	t.Run("defaults", func(t *testing.T) {
    +		t.Parallel()
    +		h, err := New(valid)
    +		if err != nil {
    +			t.Fatal(err)
    +		}
    +		if h.cfg.InterruptGrace != defaultInterruptGrace || h.cfg.StartLimit != defaultStartLimit {
    +			t.Fatalf("defaults = %v, %d", h.cfg.InterruptGrace, h.cfg.StartLimit)
    +		}
    +		if h.postResultGrace != defaultPostResult || h.drainGrace != defaultDrainGrace {
    +			t.Fatalf("graces = %v, %v", h.postResultGrace, h.drainGrace)
    +		}
    +	})
    +}
    +
    +// TestRelativeBinary: a relative Binary is found from the current directory, and a turn runs it
    +// from WorkDir, a different directory. Not parallel: it changes the current directory.
    +func TestRelativeBinary(t *testing.T) {
    +	exe, err := os.Executable()
    +	if err != nil {
    +		t.Fatal(err)
    +	}
    +	fixture, err := filepath.Abs(filepath.Join("testdata", "text_turn.jsonl"))
    +	if err != nil {
    +		t.Fatal(err)
    +	}
    +	t.Chdir(filepath.Dir(exe))
    +	rel := "." + string(filepath.Separator) + filepath.Base(exe)
    +	h := newTestHarness(t, Config{Binary: rel})
    +	if h.cfg.Binary != exe {
    +		t.Fatalf("Binary = %q, want %q", h.cfg.Binary, exe)
    +	}
    +	setScenario(t, h, scenario{Fixture: fixture})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	if !slices.Equal(sink.outputs, []string{"Hello, world."}) {
    +		t.Fatalf("outputs = %q", sink.outputs)
    +	}
    +}
    +
    +func TestRunRequiresSessionUID(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), nil, sink); !errors.Is(err, errNoSession) {
    +		t.Fatalf("nil start: %v", err)
    +	}
    +	if err := h.Run(context.Background(), startFor("", "e1", nil, "hi"), sink); !errors.Is(err, errNoSession) {
    +		t.Fatalf("empty session UID: %v", err)
    +	}
    +	if got := starts(t, h); len(got) != 0 {
    +		t.Fatalf("spawned %d processes", len(got))
    +	}
    +}
    +
    +var uuidV5 = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`)
    +
    +func TestSessionID(t *testing.T) {
    +	t.Parallel()
    +	a0 := sessionID("uid-a", 0)
    +	if !uuidV5.MatchString(a0) {
    +		t.Fatalf("sessionID = %q, not a UUIDv5", a0)
    +	}
    +	if sessionID("uid-a", 0) != a0 {
    +		t.Fatal("sessionID is not deterministic")
    +	}
    +	for _, other := range []string{sessionID("uid-a", 1), sessionID("uid-b", 0), sessionID("uid-a/0", 0)} {
    +		if other == a0 {
    +			t.Fatalf("sessionID collision: %q", other)
    +		}
    +	}
    +}
    +
    +func TestFirstTurnThenResume(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{Model: "claude-test-model-1", MaxTurns: 7, MaxBudgetUSD: 1.5})
    +	setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +	ctx := context.Background()
    +	id := sessionID("uid", 0)
    +
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(ctx, startFor("uid", "e1", nil, "first", "second"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	got := starts(t, h)
    +	if len(got) != 1 {
    +		t.Fatalf("spawned %d processes, want 1", len(got))
    +	}
    +	wantArgs := []string{
    +		"-p", "--output-format", "stream-json", "--verbose", "--include-partial-messages",
    +		"--permission-mode", "dontAsk", "--setting-sources", "user", "--strict-mcp-config",
    +		"--session-id", id,
    +		"--model", "claude-test-model-1", "--max-turns", "7", "--max-budget-usd", "1.5",
    +	}
    +	if !slices.Equal(got[0].Args, wantArgs) {
    +		t.Fatalf("args = %q, want %q", got[0].Args, wantArgs)
    +	}
    +	if got[0].Stdin != "first\n\nsecond" {
    +		t.Fatalf("stdin = %q", got[0].Stdin)
    +	}
    +	// Partial text deltas are dropped; the result text is the one Output.
    +	if !slices.Equal(sink.outputs, []string{"Hello, world."}) {
    +		t.Fatalf("outputs = %q", sink.outputs)
    +	}
    +	if len(sink.reports) != 0 {
    +		t.Fatalf("reports = %+v", sink.reports)
    +	}
    +	wantUsage := []api.Usage{{Model: "claude-test-model-1", InputTokens: 12 + 100 + 200, OutputTokens: 5}}
    +	if !reflect.DeepEqual(sink.usages, wantUsage) {
    +		t.Fatalf("usages = %+v, want %+v", sink.usages, wantUsage)
    +	}
    +
    +	for i, exec := range []string{"e2", "e3"} {
    +		sink := &recordingSink{t: t}
    +		if err := h.Run(ctx, startFor("uid", exec, priorTurn("e1"), "again"), sink); err != nil {
    +			t.Fatalf("turn %d: %v", i+2, err)
    +		}
    +		got := starts(t, h)
    +		args := got[len(got)-1].Args
    +		if i := slices.Index(args, "--resume"); i < 0 || args[i+1] != id {
    +			t.Fatalf("turn args = %q, want --resume %s", args, id)
    +		}
    +		if slices.Contains(args, "--session-id") {
    +			t.Fatalf("turn args = %q carry --session-id", args)
    +		}
    +		if !slices.Equal(args[:10], wantArgs[:10]) {
    +			t.Fatalf("turn args = %q, want the permission pins %q", args, wantArgs[:10])
    +		}
    +	}
    +}
    +
    +// TestFailedFirstTurnMovesToNextAttempt: an id handed to a process that never confirmed it may
    +// have left a transcript behind, so the next first turn uses a fresh id.
    +func TestFailedFirstTurnMovesToNextAttempt(t *testing.T) {
    +	t.Parallel()
    +	for _, test := range []struct {
    +		name string
    +		sc   scenario
    +		want string
    +	}{
    +		{name: "exit before init", sc: scenario{Exit: 1}, want: "claudecode: claude exited with status 1 before a result"},
    +		{name: "session mismatch", sc: scenario{Fixture: "session_mismatch.jsonl"}, want: errSessionMismatch.Error()},
    +		{name: "events before init", sc: scenario{Fixture: "before_init.jsonl"}, want: errNoInit.Error()},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{})
    +			ctx := context.Background()
    +			setScenario(t, h, test.sc)
    +			err := h.Run(ctx, startFor("uid", "e1", nil, "hi"), &recordingSink{t: t})
    +			if err == nil || err.Error() != test.want {
    +				t.Fatalf("Run = %v, want %q", err, test.want)
    +			}
    +
    +			setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +			if err := h.Run(ctx, startFor("uid", "e2", priorTurn("e1"), "hi"), &recordingSink{t: t}); err != nil {
    +				t.Fatal(err)
    +			}
    +			if err := h.Run(ctx, startFor("uid", "e3", priorTurn("e2"), "hi"), &recordingSink{t: t}); err != nil {
    +				t.Fatal(err)
    +			}
    +			got := starts(t, h)
    +			want := [][]string{
    +				{"--session-id", sessionID("uid", 0)},
    +				{"--session-id", sessionID("uid", 1)},
    +				{"--resume", sessionID("uid", 1)},
    +			}
    +			if len(got) != len(want) {
    +				t.Fatalf("spawned %d processes, want %d", len(got), len(want))
    +			}
    +			for i, w := range want {
    +				j := slices.Index(got[i].Args, w[0])
    +				if j < 0 || got[i].Args[j+1] != w[1] {
    +					t.Fatalf("turn %d args = %q, want %q", i+1, got[i].Args, w)
    +				}
    +			}
    +		})
    +	}
    +}
    +
    +func TestToolResultsReported(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	setScenario(t, h, scenario{Fixture: "tool_turn.jsonl"})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	text := func(s string) []api.Part { return []api.Part{{Text: &api.TextPart{Text: s}}} }
    +	bashIn := `{"command":"ls","description":"List files"}`
    +	grepIn := `{"pattern":"TODO"}`
    +	taskIn := `{"description":"search","prompt":"find TODOs","subagent_type":"general-purpose"}`
    +	readIn := `{"file_path":"a.txt"}`
    +	want := []api.ToolResult{
    +		{ID: "toolu_01", Output: map[string]any{"tool": "Bash", "input": bashIn, "input_bytes": float64(len(bashIn)), "truncated": false}, Content: text("a.txt\nb.txt")},
    +		{ID: "toolu_03", Output: map[string]any{"tool": "Grep", "parent_tool_use_id": "toolu_02", "input": grepIn, "input_bytes": float64(len(grepIn)), "truncated": false}, Content: text("a.txt:1: TODO"), IsError: true},
    +		{ID: "toolu_02", Output: map[string]any{"tool": "Task", "input": taskIn, "input_bytes": float64(len(taskIn)), "truncated": false}, Content: text("Found one TODO.")},
    +		// A result whose tool_use the stream never showed is reported without a tool name.
    +		{ID: "toolu_99", Output: map[string]any{"input": "", "input_bytes": float64(0), "truncated": false}, Content: text("orphan")},
    +		// A tool_use that never got a result is closed out at the end of the turn.
    +		{ID: "toolu_04", Output: map[string]any{"tool": "Read", "input": readIn, "input_bytes": float64(len(readIn)), "truncated": false}, IsError: true, Error: "no result observed"},
    +	}
    +	if !reflect.DeepEqual(sink.reports, want) {
    +		t.Fatalf("reports =\n%+v\nwant\n%+v", sink.reports, want)
    +	}
    +	if !slices.Equal(sink.outputs, []string{"Done."}) {
    +		t.Fatalf("outputs = %q", sink.outputs)
    +	}
    +	wantUsage := []api.Usage{{Model: "claude-test-model-1", InputTokens: 60 + 5 + 180, OutputTokens: 40}}
    +	if !reflect.DeepEqual(sink.usages, wantUsage) {
    +		t.Fatalf("usages = %+v, want %+v", sink.usages, wantUsage)
    +	}
    +}
    +
    +// toolPair returns an assistant tool_use line and its user tool_result line.
    +func toolPair(id, input, content string) []string {
    +	return []string{
    +		fmt.Sprintf(`{"type":"assistant","message":{"id":"msg_%s","content":[{"type":"tool_use","id":"%s","name":"Bash","input":{"command":%q}}]},"parent_tool_use_id":null,"session_id":"{{SESSION_ID}}"}`, id, id, input),
    +		fmt.Sprintf(`{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"%s","content":%q}]},"parent_tool_use_id":null,"session_id":"{{SESSION_ID}}"}`, id, content),
    +	}
    +}
    +
    +const (
    +	initLine    = `{"type":"system","subtype":"init","session_id":"{{SESSION_ID}}","model":"claude-test-model-1"}`
    +	successLine = `{"type":"result","subtype":"success","is_error":false,"result":"ok","session_id":"{{SESSION_ID}}","usage":{"input_tokens":1,"output_tokens":1}}`
    +)
    +
    +func TestReceiptIsBounded(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	big := strings.Repeat("é", 5000) // 10000 bytes; 2048 is not a rune boundary
    +	lines := append([]string{initLine}, toolPair("toolu_big", big, big)...)
    +	setScenario(t, h, scenario{Lines: append(lines, successLine)})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	if len(sink.reports) != 1 {
    +		t.Fatalf("reports = %d", len(sink.reports))
    +	}
    +	tr := sink.reports[0]
    +	in, _ := tr.Output["input"].(string)
    +	content := tr.Content[0].Text.Text
    +	for name, s := range map[string]string{"input": in, "content": content} {
    +		if len(s) > receiptFieldBytes || len(s) < receiptFieldBytes-4 || !utf8.ValidString(s) {
    +			t.Fatalf("%s receipt is %d bytes (valid UTF-8 %v), want at most %d", name, len(s), utf8.ValidString(s), receiptFieldBytes)
    +		}
    +	}
    +	if tr.Output["truncated"] != true || tr.Output["input_bytes"] != float64(len(`{"command":"`+big+`"}`)) {
    +		t.Fatalf("receipt output = %v", tr.Output)
    +	}
    +}
    +
    +// TestReceiptsShrinkPastTurnBudget: once one turn's full receipts pass the budget, the rest of the
    +// turn reports sizes only.
    +func TestReceiptsShrinkPastTurnBudget(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	payload := strings.Repeat("x", 3000)
    +	lines := []string{initLine}
    +	const n = 60 // about 4 KiB each, past the 128 KiB budget
    +	for i := range n {
    +		lines = append(lines, toolPair(fmt.Sprintf("toolu_%02d", i), payload, payload)...)
    +	}
    +	setScenario(t, h, scenario{Lines: append(lines, successLine)})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	if len(sink.reports) != n {
    +		t.Fatalf("reports = %d, want %d", len(sink.reports), n)
    +	}
    +	full := 0
    +	for i, tr := range sink.reports {
    +		if tr.Output["omitted"] == true {
    +			if tr.Content != nil || tr.Output["input"] != nil {
    +				t.Fatalf("minimal receipt %d carries content: %+v", i, tr)
    +			}
    +			if tr.Output["content_bytes"] != float64(len(payload)+2) || tr.Output["tool"] != "Bash" {
    +				t.Fatalf("minimal receipt %d = %v", i, tr.Output)
    +			}
    +			continue
    +		}
    +		if full != i {
    +			t.Fatalf("full receipt %d follows a minimal one", i)
    +		}
    +		full++
    +	}
    +	if full == 0 || full == n {
    +		t.Fatalf("full receipts = %d of %d, want the budget to cut in", full, n)
    +	}
    +}
    +
    +// TestReceiptsShrinkWithLargeHistory: History past half the Start limit leaves no room for full
    +// receipts, and the harness warns once History nears the limit.
    +func TestReceiptsShrinkWithLargeHistory(t *testing.T) {
    +	t.Parallel()
    +	history := []api.Event{{Kind: api.EventOutput, Message: api.TextMessage("assistant", strings.Repeat("h", 3500))}}
    +	for _, test := range []struct {
    +		name        string
    +		limit       int
    +		wantOmitted bool
    +		wantWarn    bool
    +	}{
    +		{name: "small history", limit: 0},
    +		{name: "history past half the limit", limit: 6000, wantOmitted: true},
    +		{name: "history near the limit", limit: 4096, wantOmitted: true, wantWarn: true},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{StartLimit: test.limit})
    +			var logs bytes.Buffer
    +			h.logger = slog.New(slog.NewTextHandler(&logs, nil))
    +			lines := append([]string{initLine}, toolPair("toolu_1", "ls", "a.txt")...)
    +			setScenario(t, h, scenario{Lines: append(lines, successLine)})
    +			sink := &recordingSink{t: t}
    +			if err := h.Run(context.Background(), startFor("uid", "e1", history, "go"), sink); err != nil {
    +				t.Fatal(err)
    +			}
    +			if got := sink.reports[0].Output["omitted"] == true; got != test.wantOmitted {
    +				t.Fatalf("omitted = %v, want %v: %+v", got, test.wantOmitted, sink.reports[0])
    +			}
    +			if got := strings.Contains(logs.String(), "level=WARN"); got != test.wantWarn {
    +				t.Fatalf("warned = %v, want %v: %s", got, test.wantWarn, logs.String())
    +			}
    +		})
    +	}
    +}
    +
    +func TestUsage(t *testing.T) {
    +	t.Parallel()
    +	for _, test := range []struct {
    +		name    string
    +		sc      scenario
    +		wantErr string
    +		want    []api.Usage
    +	}{
    +		{
    +			name: "result usage: token counts only, total_cost_usd dropped",
    +			sc:   scenario{Fixture: "text_turn.jsonl"},
    +			want: []api.Usage{{Model: "claude-test-model-1", InputTokens: 12 + 100 + 200, OutputTokens: 5}},
    +		},
    +		{
    +			name:    "zeroed result usage falls back to main-loop input",
    +			sc:      scenario{Fixture: "zero_usage_result.jsonl"},
    +			wantErr: "claudecode: claude reported an error result (subtype error_during_execution)",
    +			want:    []api.Usage{{Model: "claude-test-model-1", InputTokens: (4 + 2 + 1) + (8 + 0 + 3)}},
    +		},
    +		{
    +			name: "no result: once per message id, subagents excluded",
    +			sc: scenario{Lines: []string{
    +				initLine,
    +				`{"type":"assistant","message":{"id":"msg_a","content":[{"type":"text","text":"a"}],"usage":{"input_tokens":5,"cache_read_input_tokens":2,"output_tokens":1}},"parent_tool_use_id":null}`,
    +				`{"type":"assistant","message":{"id":"msg_a","content":[{"type":"text","text":"b"}],"usage":{"input_tokens":5,"cache_read_input_tokens":2,"output_tokens":1}},"parent_tool_use_id":null}`,
    +				`{"type":"assistant","message":{"id":"msg_s","content":[],"usage":{"input_tokens":999,"output_tokens":1}},"parent_tool_use_id":"toolu_x"}`,
    +			}},
    +			wantErr: errNoResult.Error(),
    +			want:    []api.Usage{{Model: "claude-test-model-1", InputTokens: 7}},
    +		},
    +		{
    +			name:    "nothing to report",
    +			sc:      scenario{Fixture: "init_only.jsonl"},
    +			wantErr: errNoResult.Error(),
    +		},
    +		{
    +			name: "init model missing: the turn's model",
    +			sc: scenario{Lines: []string{
    +				`{"type":"system","subtype":"init","session_id":"{{SESSION_ID}}"}`,
    +				successLine,
    +			}},
    +			want: []api.Usage{{Model: "configured", InputTokens: 1, OutputTokens: 1}},
    +		},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{Model: "configured"})
    +			setScenario(t, h, test.sc)
    +			sink := &recordingSink{t: t}
    +			err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink)
    +			if got := fmt.Sprint(err); (err != nil || test.wantErr != "") && got != test.wantErr {
    +				t.Fatalf("Run = %v, want %q", err, test.wantErr)
    +			}
    +			if !reflect.DeepEqual(sink.usages, test.want) {
    +				t.Fatalf("usages = %+v, want %+v", sink.usages, test.want)
    +			}
    +		})
    +	}
    +}
    +
    +func TestFailedTurns(t *testing.T) {
    +	t.Parallel()
    +	for _, test := range []struct {
    +		name        string
    +		sc          scenario
    +		want        string
    +		wantUsage   []api.Usage
    +		wantReports int
    +	}{
    +		{
    +			name:      "error result",
    +			sc:        scenario{Fixture: "error_result.jsonl"},
    +			want:      "claudecode: claude reported an error result (subtype error_max_turns)",
    +			wantUsage: []api.Usage{{Model: "claude-test-model-1", InputTokens: 10, OutputTokens: 2}},
    +		},
    +		{
    +			name: "error flag with success subtype",
    +			sc: scenario{Lines: []string{initLine,
    +				`{"type":"result","subtype":"success","is_error":true,"result":"API Error: 500","session_id":"{{SESSION_ID}}"}`}},
    +			want: "claudecode: claude reported an error result (subtype success)",
    +		},
    +		{
    +			name: "unsafe subtype",
    +			sc: scenario{Lines: []string{initLine,
    +				`{"type":"result","subtype":"error: sk-secret","is_error":true,"session_id":"{{SESSION_ID}}"}`}},
    +			want: "claudecode: claude reported an error result (subtype unknown)",
    +		},
    +		{
    +			name: "non-zero exit before a result",
    +			sc:   scenario{Fixture: "init_only.jsonl", Exit: 3},
    +			want: "claudecode: claude exited with status 3 before a result",
    +		},
    +		{
    +			name:      "non-zero exit after success",
    +			sc:        scenario{Fixture: "text_turn.jsonl", Exit: 2},
    +			want:      "claudecode: claude exited with status 2 after a success result",
    +			wantUsage: []api.Usage{{Model: "claude-test-model-1", InputTokens: 312, OutputTokens: 5}},
    +		},
    +		{
    +			name:        "stream ends without a result",
    +			sc:          scenario{Fixture: "truncated.jsonl"},
    +			want:        errNoResult.Error(),
    +			wantUsage:   []api.Usage{{Model: "claude-test-model-1", InputTokens: 7}},
    +			wantReports: 1,
    +		},
    +		{
    +			name: "stream cut mid-line",
    +			sc:   scenario{Fixture: "init_only.jsonl", Partial: `{"type":"result","subtype":"succ`},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name: "malformed line",
    +			sc:   scenario{Fixture: "malformed.jsonl"},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name:      "malformed line after a success result",
    +			sc:        scenario{Fixture: "text_turn.jsonl", Lines: []string{`{"type":"assistant","message":`}},
    +			want:      errMalformed.Error(),
    +			wantUsage: []api.Usage{{Model: "claude-test-model-1", InputTokens: 312, OutputTokens: 5}},
    +		},
    +		{
    +			name:      "stream cut mid-line after a success result",
    +			sc:        scenario{Fixture: "text_turn.jsonl", Partial: `{"type":"stream_ev`},
    +			want:      errMalformed.Error(),
    +			wantUsage: []api.Usage{{Model: "claude-test-model-1", InputTokens: 312, OutputTokens: 5}},
    +		},
    +		{
    +			name: "negative usage",
    +			sc: scenario{Lines: []string{initLine,
    +				`{"type":"result","subtype":"success","result":"x","session_id":"{{SESSION_ID}}","usage":{"input_tokens":-1}}`}},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name: "tool_use without id",
    +			sc: scenario{Lines: []string{initLine,
    +				`{"type":"assistant","message":{"id":"m","content":[{"type":"tool_use","name":"Bash","input":{}}]}}`}},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name: "tool_result without tool_use_id",
    +			sc: scenario{Lines: []string{initLine,
    +				`{"type":"user","message":{"content":[{"type":"tool_result","content":"x"}]}}`}},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name: "content is not blocks",
    +			sc:   scenario{Lines: []string{initLine, `{"type":"assistant","message":{"id":"m","content":[1]}}`}},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name: "line over the limit",
    +			sc:   scenario{Lines: []string{initLine, `{"type":"assistant","x":"` + strings.Repeat("x", maxLineBytes) + `"}`, successLine}},
    +			want: errMalformed.Error(),
    +		},
    +		{
    +			name: "session id changes mid-stream",
    +			sc: scenario{Lines: []string{initLine,
    +				`{"type":"result","subtype":"success","result":"x","session_id":"11111111-1111-4111-8111-111111111111"}`}},
    +			want: errSessionMismatch.Error(),
    +		},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{})
    +			setScenario(t, h, test.sc)
    +			sink := &recordingSink{t: t}
    +			err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink)
    +			if err == nil || err.Error() != test.want {
    +				t.Fatalf("Run = %v, want %q", err, test.want)
    +			}
    +			if len(sink.outputs) != 0 {
    +				t.Fatalf("failed turn recorded output %q", sink.outputs)
    +			}
    +			if !reflect.DeepEqual(sink.usages, test.wantUsage) {
    +				t.Fatalf("usages = %+v, want %+v", sink.usages, test.wantUsage)
    +			}
    +			if len(sink.reports) != test.wantReports {
    +				t.Fatalf("reports = %+v, want %d", sink.reports, test.wantReports)
    +			}
    +		})
    +	}
    +}
    +
    +// TestLinesAfterResult: well-formed lines after the result are decoded but have no sink effect: a
    +// late tool result is not reported and late usage is not counted.
    +func TestLinesAfterResult(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	setScenario(t, h, scenario{Fixture: "text_turn.jsonl", Lines: []string{
    +		"",
    +		`{"type":"assistant","message":{"id":"late","content":[{"type":"tool_use","id":"toolu_late","name":"Bash","input":{}}],"usage":{"input_tokens":999}},"session_id":"{{SESSION_ID}}"}`,
    +		`{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_late","content":"x"}]},"session_id":"{{SESSION_ID}}"}`,
    +		`{"type":"some_future_event"}`,
    +	}})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	if !slices.Equal(sink.outputs, []string{"Hello, world."}) || len(sink.reports) != 0 {
    +		t.Fatalf("outputs = %q, reports = %+v", sink.outputs, sink.reports)
    +	}
    +	if want := []api.Usage{{Model: "claude-test-model-1", InputTokens: 312, OutputTokens: 5}}; !reflect.DeepEqual(sink.usages, want) {
    +		t.Fatalf("usages = %+v, want %+v", sink.usages, want)
    +	}
    +}
    +
    +func TestTruncatedStreamClosesDanglingTool(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	setScenario(t, h, scenario{Fixture: "truncated.jsonl"})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); !errors.Is(err, errNoResult) {
    +		t.Fatalf("Run = %v", err)
    +	}
    +	tr := sink.reports[0]
    +	if tr.ID != "toolu_30" || !tr.IsError || tr.Error != "no result observed" || tr.Output["tool"] != "Bash" {
    +		t.Fatalf("dangling report = %+v", tr)
    +	}
    +}
    +
    +func TestOutputChunked(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	text := strings.Repeat("é", 1_300_000) // 2.6 MB; 1 MiB is not a rune boundary
    +	setScenario(t, h, scenario{Lines: []string{
    +		initLine,
    +		fmt.Sprintf(`{"type":"result","subtype":"success","result":%q,"session_id":"{{SESSION_ID}}"}`, text),
    +	}})
    +	sink := &recordingSink{t: t}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink); err != nil {
    +		t.Fatal(err)
    +	}
    +	if len(sink.outputs) != 3 {
    +		t.Fatalf("outputs = %d chunks, want 3", len(sink.outputs))
    +	}
    +	for i, c := range sink.outputs {
    +		if len(c) > outputChunkBytes || !utf8.ValidString(c) {
    +			t.Fatalf("chunk %d: %d bytes, valid UTF-8 %v", i, len(c), utf8.ValidString(c))
    +		}
    +	}
    +	if strings.Join(sink.outputs, "") != text {
    +		t.Fatal("chunks do not rejoin to the result")
    +	}
    +}
    +
    +func TestChunksAndTruncate(t *testing.T) {
    +	t.Parallel()
    +	if got := chunks("", 4); got != nil {
    +		t.Fatalf("chunks of empty = %q", got)
    +	}
    +	if got := chunks("aébc", 2); !slices.Equal(got, []string{"a", "é", "bc"}) {
    +		t.Fatalf("chunks = %q", got)
    +	}
    +	if got := chunks("é", 1); strings.Join(got, "") != "é" {
    +		t.Fatalf("chunks below one rune = %q", got)
    +	}
    +	if s, cut := truncate("abc", 3); s != "abc" || cut {
    +		t.Fatalf("truncate = %q, %v", s, cut)
    +	}
    +	if s, cut := truncate("aé", 2); s != "a" || !cut {
    +		t.Fatalf("truncate = %q, %v", s, cut)
    +	}
    +}
    +
    +func TestRerunRefused(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +	ctx := context.Background()
    +	if err := h.Run(ctx, startFor("uid", "e1", nil, "go"), &recordingSink{t: t}); err != nil {
    +		t.Fatal(err)
    +	}
    +	// A recovery re-run of the same execution must not start a second billed turn.
    +	if err := h.Run(ctx, startFor("uid", "e1", nil, "go"), &recordingSink{t: t}); !errors.Is(err, errRerun) {
    +		t.Fatalf("re-run = %v, want %v", err, errRerun)
    +	}
    +	if got := starts(t, h); len(got) != 1 {
    +		t.Fatalf("spawned %d processes, want 1", len(got))
    +	}
    +}
    +
    +// TestCancelledBeforeStart: a turn whose ctx is done when Run is called launches nothing and is
    +// not recorded as started, so its retry runs. The session's state is still created, so a later
    +// turn whose History shows the cancelled one does not look like lost memory.
    +func TestCancelledBeforeStart(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +	ctx, cancel := context.WithCancel(context.Background())
    +	cancel()
    +	err := h.Run(ctx, startFor("uid", "e1", nil, "go"), &recordingSink{t: t})
    +	if !errors.Is(err, context.Canceled) || err.Error() != "claudecode: turn interrupted: context canceled" {
    +		t.Fatalf("Run = %v", err)
    +	}
    +	if got := starts(t, h); len(got) != 0 {
    +		t.Fatalf("spawned %d processes", len(got))
    +	}
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), &recordingSink{t: t}); err != nil {
    +		t.Fatalf("retry = %v", err)
    +	}
    +	// A ctx cancelled after begin, while the inputs are checked, still launches nothing.
    +	tr := &turn{h: h, sink: &recordingSink{t: t}, sessionUID: "uid", flag: "--resume", sessionID: sessionID("uid", 0)}
    +	if err := tr.run(ctx, h.args(tr.flag, tr.sessionID, ""), "go"); !errors.Is(err, context.Canceled) {
    +		t.Fatalf("run = %v", err)
    +	}
    +	if got := starts(t, h); len(got) != 1 {
    +		t.Fatalf("spawned %d processes, want 1", len(got))
    +	}
    +	h2 := newTestHarness(t, Config{})
    +	setScenario(t, h2, scenario{Fixture: "text_turn.jsonl"})
    +	if err := h2.Run(ctx, startFor("uid", "e1", nil, "go"), &recordingSink{t: t}); !errors.Is(err, context.Canceled) {
    +		t.Fatalf("Run = %v", err)
    +	}
    +	if err := h2.Run(context.Background(), startFor("uid", "e2", priorTurn("e1"), "go"), &recordingSink{t: t}); err != nil {
    +		t.Fatalf("next turn = %v", err)
    +	}
    +}
    +
    +func TestLostStateFailsClosed(t *testing.T) {
    +	t.Parallel()
    +	for _, test := range []struct {
    +		name    string
    +		history []api.Event
    +	}{
    +		{name: "earlier execution", history: priorTurn("e0")},
    +		{name: "legacy input", history: []api.Event{{Kind: api.EventInput, Message: api.TextMessage("user", "hi")}}},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{})
    +			setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +			err := h.Run(context.Background(), startFor("uid", "e1", test.history, "go"), &recordingSink{t: t})
    +			if !errors.Is(err, errStateLost) {
    +				t.Fatalf("Run = %v, want %v", err, errStateLost)
    +			}
    +			if got := starts(t, h); len(got) != 0 {
    +				t.Fatalf("spawned %d processes", len(got))
    +			}
    +		})
    +	}
    +}
    +
    +// TestInvalidFirstTurnDoesNotWedge: a first turn refused before it spawns keeps the session's
    +// state, so the next turn, whose History now shows a turn, still starts the session.
    +func TestInvalidFirstTurnDoesNotWedge(t *testing.T) {
    +	t.Parallel()
    +	h := newTestHarness(t, Config{})
    +	setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +	ctx := context.Background()
    +	if err := h.Run(ctx, startFor("uid", "e1", nil), &recordingSink{t: t}); !errors.Is(err, errNoPrompt) {
    +		t.Fatalf("Run = %v, want %v", err, errNoPrompt)
    +	}
    +	if err := h.Run(ctx, startFor("uid", "e2", priorTurn("e1"), "go"), &recordingSink{t: t}); err != nil {
    +		t.Fatal(err)
    +	}
    +	got := starts(t, h)
    +	if len(got) != 1 || !slices.Contains(got[0].Args, "--session-id") || !slices.Contains(got[0].Args, sessionID("uid", 0)) {
    +		t.Fatalf("starts = %+v, want one --session-id %s", got, sessionID("uid", 0))
    +	}
    +}
    +
    +func TestInputValidation(t *testing.T) {
    +	t.Parallel()
    +	data := api.Message{Role: "user", Parts: []api.Part{{Data: map[string]any{"k": "v"}}}}
    +	for _, test := range []struct {
    +		name   string
    +		inputs []api.Message
    +		want   error
    +	}{
    +		{name: "no inputs", want: errNoPrompt},
    +		{name: "empty text", inputs: []api.Message{*api.TextMessage("user", "")}, want: errNoPrompt},
    +		{name: "non-text part", inputs: []api.Message{*api.TextMessage("user", "hi"), data}, want: errNonText},
    +		{name: "too large", inputs: []api.Message{*api.TextMessage("user", strings.Repeat("x", maxPromptBytes+1))}, want: errPromptSize},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{})
    +			s := &api.Start{ExecutionID: "e1", SessionUID: "uid", Inputs: test.inputs}
    +			if err := h.Run(context.Background(), s, &recordingSink{t: t}); !errors.Is(err, test.want) {
    +				t.Fatalf("Run = %v, want %v", err, test.want)
    +			}
    +			if got := starts(t, h); len(got) != 0 {
    +				t.Fatalf("spawned %d processes", len(got))
    +			}
    +		})
    +	}
    +}
    +
    +func TestModelSelection(t *testing.T) {
    +	t.Parallel()
    +	for _, test := range []struct {
    +		name      string
    +		cfg       string
    +		requested string
    +		wantModel string // "" means no --model
    +		wantErr   error
    +	}{
    +		{name: "configured", cfg: "claude-test-model-1", wantModel: "claude-test-model-1"},
    +		{name: "configured and requested", cfg: "claude-test-model-1", requested: "claude-test-model-1", wantModel: "claude-test-model-1"},
    +		{name: "requested differs from configured", cfg: "claude-test-model-1", requested: "other", wantErr: errModelMismatch},
    +		{name: "requested only", requested: "claude-test-model-2", wantModel: "claude-test-model-2"},
    +		{name: "requested flag", requested: "--bare", wantErr: errModelArg},
    +		{name: "neither"},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{Model: test.cfg})
    +			setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +			s := startFor("uid", "e1", nil, "go")
    +			s.Model = test.requested
    +			err := h.Run(context.Background(), s, &recordingSink{t: t})
    +			if !errors.Is(err, test.wantErr) {
    +				t.Fatalf("Run = %v, want %v", err, test.wantErr)
    +			}
    +			got := starts(t, h)
    +			if test.wantErr != nil {
    +				if len(got) != 0 {
    +					t.Fatalf("spawned %d processes", len(got))
    +				}
    +				return
    +			}
    +			i := slices.Index(got[0].Args, "--model")
    +			switch {
    +			case test.wantModel == "" && i >= 0:
    +				t.Fatalf("args = %q, want no --model", got[0].Args)
    +			case test.wantModel != "" && (i < 0 || got[0].Args[i+1] != test.wantModel):
    +				t.Fatalf("args = %q, want --model %s", got[0].Args, test.wantModel)
    +			}
    +		})
    +	}
    +}
    +
    +// TestStderrNeverSurfaces: stderr can carry prompt or tool text, so for a process that reached
    +// system/init it reaches no error, sink call or log.
    +func TestStderrNeverSurfaces(t *testing.T) {
    +	t.Parallel()
    +	const sentinel = "STDERR-SENTINEL-must-not-surface"
    +	for _, sc := range []scenario{
    +		{Fixture: "init_only.jsonl", Exit: 3, Stderr: sentinel},
    +		{Fixture: "error_result.jsonl", Stderr: sentinel},
    +		{Fixture: "tool_turn.jsonl", Stderr: sentinel},
    +	} {
    +		h := newTestHarness(t, Config{})
    +		var logs bytes.Buffer
    +		h.logger = slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
    +		setScenario(t, h, sc)
    +		sink := &recordingSink{t: t}
    +		err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), sink)
    +		seen := fmt.Sprint(err, sink.outputs, sink.reports, sink.usages, logs.String())
    +		if strings.Contains(seen, sentinel) {
    +			t.Fatalf("stderr surfaced: %s", seen)
    +		}
    +	}
    +}
    +
    +func TestSinkErrorsFailTheTurn(t *testing.T) {
    +	t.Parallel()
    +	refused := errors.New("refused")
    +	for _, test := range []struct {
    +		name string
    +		sink *recordingSink
    +		want string
    +	}{
    +		{name: "report", sink: &recordingSink{reportErr: refused}, want: "claudecode: record tool result: refused"},
    +		{name: "output", sink: &recordingSink{outputErr: refused}, want: "claudecode: record output: refused"},
    +	} {
    +		t.Run(test.name, func(t *testing.T) {
    +			t.Parallel()
    +			h := newTestHarness(t, Config{})
    +			setScenario(t, h, scenario{Fixture: "tool_turn.jsonl"})
    +			test.sink.t = t
    +			err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), test.sink)
    +			if err == nil || err.Error() != test.want {
    +				t.Fatalf("Run = %v, want %q", err, test.want)
    +			}
    +		})
    +	}
    +}
    +
    +// TestChildEnvironment: the claude process gets the default and configured variables of the
    +// harness's environment and nothing else. Not parallel: it sets environment variables.
    +func TestChildEnvironment(t *testing.T) {
    +	t.Setenv("CLAUDECODE_TEST_SECRET", "must-not-reach-claude")
    +	t.Setenv("CLAUDECODE_TEST_EXTRA", "x")
    +	t.Setenv("CLAUDECODE_TEST_EMPTY", "")
    +	t.Setenv("ANTHROPIC_BASE_URL", "http://egress.invalid")
    +	t.Setenv("CLAUDECODE_TEST_UNSET", "")
    +	os.Unsetenv("CLAUDECODE_TEST_UNSET")
    +	extra := []string{"CLAUDECODE_TEST_EXTRA", "CLAUDECODE_TEST_EMPTY", "CLAUDECODE_TEST_UNSET", "PATH"}
    +	h := newTestHarness(t, Config{EnvAllowlist: extra})
    +	// Read once at New: a later change does not reach the process.
    +	t.Setenv("CLAUDECODE_TEST_EXTRA", "changed")
    +	setScenario(t, h, scenario{Fixture: "text_turn.jsonl"})
    +	if err := h.Run(context.Background(), startFor("uid", "e1", nil, "go"), &recordingSink{t: t}); err != nil {
    +		t.Fatal(err)
    +	}
    +	got := starts(t, h)[0].Env
    +	for _, name := range []string{"CLAUDECODE_TEST_EXTRA", "CLAUDECODE_TEST_EMPTY", "ANTHROPIC_BASE_URL", "PATH"} {
    +		if !slices.Contains(got, name) {
    +			t.Errorf("claude env %q lacks %s", got, name)
    +		}
    +	}
    +	allowed := slices.Concat(defaultEnv, extra)
    +	for _, name := range got {
    +		if !slices.Contains(allowed, name) {
    +			t.Errorf("claude env has %s, which is not allowlisted", name)
    +		}
    +	}
    +	if slices.Contains(got, "CLAUDECODE_TEST_SECRET") || slices.Contains(got, "CLAUDECODE_TEST_UNSET") {
    +		t.Fatalf("claude env = %q", got)
    +	}
    +	if !slices.Contains(h.env, "CLAUDECODE_TEST_EXTRA=x") || !slices.Contains(h.env, "CLAUDECODE_TEST_EMPTY=") {
    +		t.Fatalf("harness env = %q", h.env)

    Fixed in d603af5: the env assertions now report variable names only, never values.

    aramase aramase commented on code on Nov 08, 2026 07:41 UTC
    Code Review
    integrations/claudecode/go.mod:1
    @@ -0,0 +1,37 @@
    +module github.com/agent-primitives/sessions/integrations/claudecode
    +
    +go 1.26.0
    +
    +toolchain go1.26.10
    +
    +require (
    +	github.com/agent-primitives/sessions v0.3.0

    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.

    aramase aramase commented on code on Nov 08, 2026 07:41 UTC
    Code Review
    integrations/claudecode/turn.go:1
    @@ -0,0 +1,696 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"os"
    +	"os/exec"
    +	"strings"
    +	"time"
    +	"unicode"
    +	"unicode/utf8"
    +
    +	"google.golang.org/protobuf/proto"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/wire"
    +)
    +
    +const (
    +	// maxLineBytes bounds one stream-json line. A longer line fails the turn as malformed.
    +	maxLineBytes = 16 << 20
    +	// receiptFieldBytes bounds the tool input and the tool content a full receipt carries.
    +	receiptFieldBytes = 2 << 10
    +	// turnReceiptBudget bounds one turn's full receipts; later receipts in the turn are minimal.
    +	turnReceiptBudget = 128 << 10
    +	// outputChunkBytes bounds one Output call, well under gRPC's default 4 MiB frame limit.
    +	outputChunkBytes = 1 << 20
    +	// stderrLineBytes bounds the stderr line logged for a process that failed before system/init.
    +	stderrLineBytes = 256
    +)
    +
    +var (
    +	errMalformed       = errors.New("claudecode: malformed stream-json from claude")
    +	errNoInit          = errors.New("claudecode: claude stream has events before system/init")
    +	errSessionMismatch = errors.New("claudecode: claude reported a different session id")
    +	errNoResult        = errors.New("claudecode: claude stream ended without a result")
    +)
    +
    +// streamLine is one stream-json event. Only the fields the harness maps are decoded; unknown
    +// event types and fields are ignored.
    +type streamLine struct {
    +	Type            string          `json:"type"`
    +	Subtype         string          `json:"subtype"`
    +	SessionID       string          `json:"session_id"`
    +	Model           string          `json:"model"`
    +	ParentToolUseID string          `json:"parent_tool_use_id"`
    +	Message         json.RawMessage `json:"message"`
    +	IsError         bool            `json:"is_error"`
    +	Result          string          `json:"result"`
    +	Usage           *tokenUsage     `json:"usage"`
    +}
    +
    +// message is the Anthropic-shaped message inside assistant and user events. Content is a string or
    +// an array of blocks.
    +type message struct {
    +	ID      string          `json:"id"`
    +	Content json.RawMessage `json:"content"`
    +	Usage   *tokenUsage     `json:"usage"`
    +}
    +
    +type contentBlock struct {
    +	Type      string          `json:"type"`
    +	Text      string          `json:"text"`
    +	ID        string          `json:"id"`
    +	Name      string          `json:"name"`
    +	Input     json.RawMessage `json:"input"`
    +	ToolUseID string          `json:"tool_use_id"`
    +	Content   json.RawMessage `json:"content"`
    +	IsError   bool            `json:"is_error"`
    +}
    +
    +type tokenUsage struct {
    +	InputTokens              int64 `json:"input_tokens"`
    +	OutputTokens             int64 `json:"output_tokens"`
    +	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
    +	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
    +}
    +
    +func (u *tokenUsage) valid() bool {
    +	return u.InputTokens >= 0 && u.OutputTokens >= 0 && u.CacheCreationInputTokens >= 0 && u.CacheReadInputTokens >= 0
    +}
    +
    +// input is every input token the model processed: uncached, cache reads and cache writes.
    +func (u *tokenUsage) input() int64 {
    +	return u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens
    +}
    +
    +type toolUse struct {
    +	name   string
    +	input  json.RawMessage
    +	parent string
    +}
    +
    +// turn is one Run's process and stream state. Only the goroutine running run touches it.
    +type turn struct {
    +	h          *Harness
    +	sink       api.EventSink
    +	sessionUID string
    +	flag       string // --session-id or --resume
    +	sessionID  string
    +	model      string
    +	receipts   bool // full receipts; false once the session or turn budget is spent
    +
    +	receiptBytes int
    +	initSeen     bool
    +	initModel    string
    +	tools        map[string]toolUse
    +	toolOrder    []string
    +	seenMsgs     map[string]struct{}
    +	recovered    tokenUsage // main-loop assistant usage, deduplicated by message id
    +	result       *streamLine
    +	sinkErr      error
    +}
    +
    +// receiptMode reports whether full receipts are allowed this turn: History, sized as the wire sends
    +// it, is under half of StartLimit. It warns once History reaches three quarters of it.
    +func (h *Harness) receiptMode(s *api.Start) bool {
    +	n := 0
    +	for _, e := range s.History {
    +		n += proto.Size(wire.EventToProto(e))
    +	}
    +	if n >= h.cfg.StartLimit/4*3 {
    +		h.logger.Warn("claudecode: session history nears the harness receive limit; raise the limit and Config.StartLimit",
    +			"session_uid", s.SessionUID, "history_bytes", n, "start_limit", h.cfg.StartLimit)
    +	}
    +	return n < h.cfg.StartLimit/2
    +}
    +
    +type readResult struct {
    +	line []byte
    +	err  error
    +}
    +
    +// Process phases. Each later phase is entered at most once, in order.
    +const (
    +	phaseRunning     = iota
    +	phaseSettling    // result seen or stdout closed: the process gets postResultGrace to exit
    +	phaseInterrupted // SIGINT sent: the process gets InterruptGrace to exit
    +	phaseKilled      // group killed or leader exited: stdout gets drainGrace of waiting to close
    +)
    +
    +// run starts the process, maps its stream, and returns the turn's outcome.
    +func (t *turn) run(ctx context.Context, args []string, prompt string) error {
    +	t.tools = make(map[string]toolUse)
    +	t.seenMsgs = make(map[string]struct{})
    +	if err := ctx.Err(); err != nil {
    +		return interruptedErr(err) // cancelled while the inputs were validated: launch nothing
    +	}
    +
    +	r, w, err := os.Pipe()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = r.Close() }()
    +	// stderr can carry prompt or tool text. Only its first line is kept, and logged only for a
    +	// process that failed before system/init. A pipe, not an io.Writer, so cmd.Wait does not wait
    +	// for a descendant that holds stderr.
    +	er, ew, err := os.Pipe()
    +	if err != nil {
    +		_ = w.Close()
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = er.Close() }()
    +	cmd := exec.Command(t.h.cfg.Binary, args...)
    +	cmd.Dir = t.h.cfg.WorkDir
    +	cmd.Env = t.h.env
    +	cmd.Stdin = strings.NewReader(prompt)
    +	cmd.Stdout = w
    +	cmd.Stderr = ew
    +	cmd.SysProcAttr = sysProcAttr()
    +	cmd.WaitDelay = t.h.drainGrace
    +	err = cmd.Start()
    +	_ = w.Close() // the child holds its own copies
    +	_ = ew.Close()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +
    +	stderrLine := make(chan string, 1)
    +	go func() {
    +		br := bufio.NewReader(er)
    +		stderrLine <- firstLine(br)
    +		_, _ = io.Copy(io.Discard, br) // keep draining so the process never blocks on stderr
    +	}()
    +	lines := make(chan readResult)
    +	go readLines(r, lines)
    +	exited := make(chan struct{})
    +	go func() {
    +		_ = cmd.Wait() // the outcome is read from cmd.ProcessState
    +		close(exited)
    +	}()
    +
    +	var (
    +		phase    = phaseRunning
    +		deadline <-chan time.Time
    +		done     = ctx.Done()
    +		eof      bool
    +		exitSeen bool
    +		forced   bool // the harness closed stdout itself
    +		signaled bool // the harness signalled the process, so its exit status is not its own verdict
    +		failErr  error
    +		drainBy  time.Time // phaseKilled: when stdout is closed
    +	)
    +	enter := func(p int, d time.Duration) {
    +		phase = p
    +		if p == phaseKilled {
    +			drainBy, deadline = time.Now().Add(d), nil // armed per wait, below
    +			return
    +		}
    +		deadline = time.After(d)
    +	}
    +	interrupt := func() {
    +		if phase >= phaseInterrupted {
    +			return
    +		}
    +		interruptProcess(cmd.Process)
    +		signaled = true
    +		enter(phaseInterrupted, t.h.cfg.InterruptGrace)
    +	}
    +	for !eof || !exitSeen {
    +		var drain *time.Timer
    +		if phase == phaseKilled && !forced {
    +			drain = time.NewTimer(time.Until(drainBy))
    +			deadline = drain.C
    +		}
    +		select {
    +		case m, ok := <-lines:
    +			switch {
    +			case !ok:
    +				lines, eof = nil, true
    +				if phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			case m.err != nil:
    +				if !forced && failErr == nil {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			case failErr != nil || ctx.Err() != nil:
    +				// Stopping: drain.
    +			case t.result != nil:
    +				// Past the result: no further sink effects, but a malformed line still fails the
    +				// turn, as it would before the result.
    +				if !validLine(m.line) {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			default:
    +				began := time.Now()
    +				err := t.handle(ctx, m.line)
    +				if phase == phaseKilled {
    +					// drainGrace bounds how long stdout stays open while the harness waits on
    +					// it, not how long the sink takes: a slow Report must not cut off lines the
    +					// process wrote before it exited.
    +					drainBy = drainBy.Add(time.Since(began))
    +				}
    +				if err != nil {
    +					failErr = err
    +					interrupt()
    +				} else if t.result != nil && phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			}
    +		case <-exited:
    +			exited, exitSeen = nil, true
    +			if !eof && phase < phaseKilled {
    +				// Something the process started still holds stdout.
    +				enter(phaseKilled, t.h.drainGrace)
    +			}
    +		case <-done:
    +			done = nil
    +			interrupt()
    +		case <-deadline:
    +			switch phase {
    +			case phaseSettling:
    +				interrupt()
    +			case phaseInterrupted:
    +				killGroup(cmd.Process)
    +				enter(phaseKilled, t.h.drainGrace)
    +			default:
    +				killGroup(cmd.Process)
    +				forced = true
    +				_ = r.Close()
    +				deadline = nil
    +			}
    +		}
    +		if drain != nil {
    +			drain.Stop()
    +		}
    +	}
    +
    +	// The loop ends once the leader exited and stdout closed, but the group can outlive its leader:
    +	// a tool Claude Code started that redirected its stdio holds neither. Kill it on every path,
    +	// success included, so nothing the turn started runs once Run returns, or while it records.
    +	if !stopGroup(cmd.Process, t.h.drainGrace) {
    +		t.h.logger.Warn("claudecode: processes of the turn's group remain after the kill",
    +			"pid", cmd.Process.Pid, "wait", t.h.drainGrace)
    +	}
    +
    +	err = t.outcome(ctx, cmd.ProcessState.ExitCode(), signaled, failErr)
    +	if err != nil && !t.initSeen && ctx.Err() == nil {
    +		// Claude Code failed before it confirmed the session, so no tool ran and the model said
    +		// nothing; a failing --resume ends here on every later turn. Its reason is on stderr.
    +		var line string
    +		select {
    +		case line = <-stderrLine:
    +		case <-time.After(t.h.drainGrace): // a descendant outside the group holds stderr
    +		}
    +		t.h.logger.Warn("claudecode: claude failed before system/init",
    +			"session_uid", t.sessionUID, "flag", t.flag, "claude_session_id", t.sessionID,
    +			"exit_status", cmd.ProcessState.String(), "stderr", line)

    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.

    aramase aramase commented on Nov 08, 2026 07:41 UTC
    Author

    @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?

    Copilot Copilot commented on code on Nov 08, 2026 18:22 UTC
    Code Review
    integrations/claudecode/turn.go:1
    @@ -0,0 +1,696 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"os"
    +	"os/exec"
    +	"strings"
    +	"time"
    +	"unicode"
    +	"unicode/utf8"
    +
    +	"google.golang.org/protobuf/proto"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/wire"
    +)
    +
    +const (
    +	// maxLineBytes bounds one stream-json line. A longer line fails the turn as malformed.
    +	maxLineBytes = 16 << 20
    +	// receiptFieldBytes bounds the tool input and the tool content a full receipt carries.
    +	receiptFieldBytes = 2 << 10
    +	// turnReceiptBudget bounds one turn's full receipts; later receipts in the turn are minimal.
    +	turnReceiptBudget = 128 << 10
    +	// outputChunkBytes bounds one Output call, well under gRPC's default 4 MiB frame limit.
    +	outputChunkBytes = 1 << 20
    +	// stderrLineBytes bounds the stderr line logged for a process that failed before system/init.
    +	stderrLineBytes = 256
    +)
    +
    +var (
    +	errMalformed       = errors.New("claudecode: malformed stream-json from claude")
    +	errNoInit          = errors.New("claudecode: claude stream has events before system/init")
    +	errSessionMismatch = errors.New("claudecode: claude reported a different session id")
    +	errNoResult        = errors.New("claudecode: claude stream ended without a result")
    +)
    +
    +// streamLine is one stream-json event. Only the fields the harness maps are decoded; unknown
    +// event types and fields are ignored.
    +type streamLine struct {
    +	Type            string          `json:"type"`
    +	Subtype         string          `json:"subtype"`
    +	SessionID       string          `json:"session_id"`
    +	Model           string          `json:"model"`
    +	ParentToolUseID string          `json:"parent_tool_use_id"`
    +	Message         json.RawMessage `json:"message"`
    +	IsError         bool            `json:"is_error"`
    +	Result          string          `json:"result"`
    +	Usage           *tokenUsage     `json:"usage"`
    +}
    +
    +// message is the Anthropic-shaped message inside assistant and user events. Content is a string or
    +// an array of blocks.
    +type message struct {
    +	ID      string          `json:"id"`
    +	Content json.RawMessage `json:"content"`
    +	Usage   *tokenUsage     `json:"usage"`
    +}
    +
    +type contentBlock struct {
    +	Type      string          `json:"type"`
    +	Text      string          `json:"text"`
    +	ID        string          `json:"id"`
    +	Name      string          `json:"name"`
    +	Input     json.RawMessage `json:"input"`
    +	ToolUseID string          `json:"tool_use_id"`
    +	Content   json.RawMessage `json:"content"`
    +	IsError   bool            `json:"is_error"`
    +}
    +
    +type tokenUsage struct {
    +	InputTokens              int64 `json:"input_tokens"`
    +	OutputTokens             int64 `json:"output_tokens"`
    +	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
    +	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
    +}
    +
    +func (u *tokenUsage) valid() bool {
    +	return u.InputTokens >= 0 && u.OutputTokens >= 0 && u.CacheCreationInputTokens >= 0 && u.CacheReadInputTokens >= 0
    +}
    +
    +// input is every input token the model processed: uncached, cache reads and cache writes.
    +func (u *tokenUsage) input() int64 {
    +	return u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens
    +}
    +
    +type toolUse struct {
    +	name   string
    +	input  json.RawMessage
    +	parent string
    +}
    +
    +// turn is one Run's process and stream state. Only the goroutine running run touches it.
    +type turn struct {
    +	h          *Harness
    +	sink       api.EventSink
    +	sessionUID string
    +	flag       string // --session-id or --resume
    +	sessionID  string
    +	model      string
    +	receipts   bool // full receipts; false once the session or turn budget is spent
    +
    +	receiptBytes int
    +	initSeen     bool
    +	initModel    string
    +	tools        map[string]toolUse
    +	toolOrder    []string
    +	seenMsgs     map[string]struct{}
    +	recovered    tokenUsage // main-loop assistant usage, deduplicated by message id
    +	result       *streamLine
    +	sinkErr      error
    +}
    +
    +// receiptMode reports whether full receipts are allowed this turn: History, sized as the wire sends
    +// it, is under half of StartLimit. It warns once History reaches three quarters of it.
    +func (h *Harness) receiptMode(s *api.Start) bool {
    +	n := 0
    +	for _, e := range s.History {
    +		n += proto.Size(wire.EventToProto(e))
    +	}
    +	if n >= h.cfg.StartLimit/4*3 {
    +		h.logger.Warn("claudecode: session history nears the harness receive limit; raise the limit and Config.StartLimit",
    +			"session_uid", s.SessionUID, "history_bytes", n, "start_limit", h.cfg.StartLimit)
    +	}
    +	return n < h.cfg.StartLimit/2
    +}
    +
    +type readResult struct {
    +	line []byte
    +	err  error
    +}
    +
    +// Process phases. Each later phase is entered at most once, in order.
    +const (
    +	phaseRunning     = iota
    +	phaseSettling    // result seen or stdout closed: the process gets postResultGrace to exit
    +	phaseInterrupted // SIGINT sent: the process gets InterruptGrace to exit
    +	phaseKilled      // group killed or leader exited: stdout gets drainGrace of waiting to close
    +)
    +
    +// run starts the process, maps its stream, and returns the turn's outcome.
    +func (t *turn) run(ctx context.Context, args []string, prompt string) error {
    +	t.tools = make(map[string]toolUse)
    +	t.seenMsgs = make(map[string]struct{})
    +	if err := ctx.Err(); err != nil {
    +		return interruptedErr(err) // cancelled while the inputs were validated: launch nothing
    +	}
    +
    +	r, w, err := os.Pipe()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = r.Close() }()
    +	// stderr can carry prompt or tool text. Only its first line is kept, and logged only for a
    +	// process that failed before system/init. A pipe, not an io.Writer, so cmd.Wait does not wait
    +	// for a descendant that holds stderr.
    +	er, ew, err := os.Pipe()
    +	if err != nil {
    +		_ = w.Close()
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = er.Close() }()
    +	cmd := exec.Command(t.h.cfg.Binary, args...)
    +	cmd.Dir = t.h.cfg.WorkDir
    +	cmd.Env = t.h.env
    +	cmd.Stdin = strings.NewReader(prompt)
    +	cmd.Stdout = w
    +	cmd.Stderr = ew
    +	cmd.SysProcAttr = sysProcAttr()
    +	cmd.WaitDelay = t.h.drainGrace
    +	err = cmd.Start()
    +	_ = w.Close() // the child holds its own copies
    +	_ = ew.Close()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +
    +	stderrLine := make(chan string, 1)
    +	go func() {
    +		br := bufio.NewReader(er)
    +		stderrLine <- firstLine(br)
    +		_, _ = io.Copy(io.Discard, br) // keep draining so the process never blocks on stderr
    +	}()
    +	lines := make(chan readResult)
    +	go readLines(r, lines)
    +	exited := make(chan struct{})
    +	go func() {
    +		_ = cmd.Wait() // the outcome is read from cmd.ProcessState
    +		close(exited)
    +	}()
    +
    +	var (
    +		phase    = phaseRunning
    +		deadline <-chan time.Time
    +		done     = ctx.Done()
    +		eof      bool
    +		exitSeen bool
    +		forced   bool // the harness closed stdout itself
    +		signaled bool // the harness signalled the process, so its exit status is not its own verdict
    +		failErr  error
    +		drainBy  time.Time // phaseKilled: when stdout is closed
    +	)
    +	enter := func(p int, d time.Duration) {
    +		phase = p
    +		if p == phaseKilled {
    +			drainBy, deadline = time.Now().Add(d), nil // armed per wait, below
    +			return
    +		}
    +		deadline = time.After(d)
    +	}
    +	interrupt := func() {
    +		if phase >= phaseInterrupted {
    +			return
    +		}
    +		interruptProcess(cmd.Process)
    +		signaled = true

    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.

    Copilot Copilot commented on code on Nov 08, 2026 18:22 UTC
    Code Review
    integrations/claudecode/turn.go:1
    @@ -0,0 +1,696 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"os"
    +	"os/exec"
    +	"strings"
    +	"time"
    +	"unicode"
    +	"unicode/utf8"
    +
    +	"google.golang.org/protobuf/proto"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/wire"
    +)
    +
    +const (
    +	// maxLineBytes bounds one stream-json line. A longer line fails the turn as malformed.
    +	maxLineBytes = 16 << 20
    +	// receiptFieldBytes bounds the tool input and the tool content a full receipt carries.
    +	receiptFieldBytes = 2 << 10
    +	// turnReceiptBudget bounds one turn's full receipts; later receipts in the turn are minimal.
    +	turnReceiptBudget = 128 << 10
    +	// outputChunkBytes bounds one Output call, well under gRPC's default 4 MiB frame limit.
    +	outputChunkBytes = 1 << 20
    +	// stderrLineBytes bounds the stderr line logged for a process that failed before system/init.
    +	stderrLineBytes = 256
    +)
    +
    +var (
    +	errMalformed       = errors.New("claudecode: malformed stream-json from claude")
    +	errNoInit          = errors.New("claudecode: claude stream has events before system/init")
    +	errSessionMismatch = errors.New("claudecode: claude reported a different session id")
    +	errNoResult        = errors.New("claudecode: claude stream ended without a result")
    +)
    +
    +// streamLine is one stream-json event. Only the fields the harness maps are decoded; unknown
    +// event types and fields are ignored.
    +type streamLine struct {
    +	Type            string          `json:"type"`
    +	Subtype         string          `json:"subtype"`
    +	SessionID       string          `json:"session_id"`
    +	Model           string          `json:"model"`
    +	ParentToolUseID string          `json:"parent_tool_use_id"`
    +	Message         json.RawMessage `json:"message"`
    +	IsError         bool            `json:"is_error"`
    +	Result          string          `json:"result"`
    +	Usage           *tokenUsage     `json:"usage"`
    +}
    +
    +// message is the Anthropic-shaped message inside assistant and user events. Content is a string or
    +// an array of blocks.
    +type message struct {
    +	ID      string          `json:"id"`
    +	Content json.RawMessage `json:"content"`
    +	Usage   *tokenUsage     `json:"usage"`
    +}
    +
    +type contentBlock struct {
    +	Type      string          `json:"type"`
    +	Text      string          `json:"text"`
    +	ID        string          `json:"id"`
    +	Name      string          `json:"name"`
    +	Input     json.RawMessage `json:"input"`
    +	ToolUseID string          `json:"tool_use_id"`
    +	Content   json.RawMessage `json:"content"`
    +	IsError   bool            `json:"is_error"`
    +}
    +
    +type tokenUsage struct {
    +	InputTokens              int64 `json:"input_tokens"`
    +	OutputTokens             int64 `json:"output_tokens"`
    +	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
    +	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
    +}
    +
    +func (u *tokenUsage) valid() bool {
    +	return u.InputTokens >= 0 && u.OutputTokens >= 0 && u.CacheCreationInputTokens >= 0 && u.CacheReadInputTokens >= 0
    +}
    +
    +// input is every input token the model processed: uncached, cache reads and cache writes.
    +func (u *tokenUsage) input() int64 {
    +	return u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens
    +}
    +
    +type toolUse struct {
    +	name   string
    +	input  json.RawMessage
    +	parent string
    +}
    +
    +// turn is one Run's process and stream state. Only the goroutine running run touches it.
    +type turn struct {
    +	h          *Harness
    +	sink       api.EventSink
    +	sessionUID string
    +	flag       string // --session-id or --resume
    +	sessionID  string
    +	model      string
    +	receipts   bool // full receipts; false once the session or turn budget is spent
    +
    +	receiptBytes int
    +	initSeen     bool
    +	initModel    string
    +	tools        map[string]toolUse
    +	toolOrder    []string
    +	seenMsgs     map[string]struct{}
    +	recovered    tokenUsage // main-loop assistant usage, deduplicated by message id
    +	result       *streamLine
    +	sinkErr      error
    +}
    +
    +// receiptMode reports whether full receipts are allowed this turn: History, sized as the wire sends
    +// it, is under half of StartLimit. It warns once History reaches three quarters of it.
    +func (h *Harness) receiptMode(s *api.Start) bool {
    +	n := 0
    +	for _, e := range s.History {
    +		n += proto.Size(wire.EventToProto(e))
    +	}
    +	if n >= h.cfg.StartLimit/4*3 {
    +		h.logger.Warn("claudecode: session history nears the harness receive limit; raise the limit and Config.StartLimit",
    +			"session_uid", s.SessionUID, "history_bytes", n, "start_limit", h.cfg.StartLimit)
    +	}
    +	return n < h.cfg.StartLimit/2
    +}
    +
    +type readResult struct {
    +	line []byte
    +	err  error
    +}
    +
    +// Process phases. Each later phase is entered at most once, in order.
    +const (
    +	phaseRunning     = iota
    +	phaseSettling    // result seen or stdout closed: the process gets postResultGrace to exit
    +	phaseInterrupted // SIGINT sent: the process gets InterruptGrace to exit
    +	phaseKilled      // group killed or leader exited: stdout gets drainGrace of waiting to close
    +)
    +
    +// run starts the process, maps its stream, and returns the turn's outcome.
    +func (t *turn) run(ctx context.Context, args []string, prompt string) error {
    +	t.tools = make(map[string]toolUse)
    +	t.seenMsgs = make(map[string]struct{})
    +	if err := ctx.Err(); err != nil {
    +		return interruptedErr(err) // cancelled while the inputs were validated: launch nothing
    +	}
    +
    +	r, w, err := os.Pipe()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = r.Close() }()
    +	// stderr can carry prompt or tool text. Only its first line is kept, and logged only for a
    +	// process that failed before system/init. A pipe, not an io.Writer, so cmd.Wait does not wait
    +	// for a descendant that holds stderr.
    +	er, ew, err := os.Pipe()
    +	if err != nil {
    +		_ = w.Close()
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = er.Close() }()
    +	cmd := exec.Command(t.h.cfg.Binary, args...)
    +	cmd.Dir = t.h.cfg.WorkDir
    +	cmd.Env = t.h.env
    +	cmd.Stdin = strings.NewReader(prompt)
    +	cmd.Stdout = w
    +	cmd.Stderr = ew
    +	cmd.SysProcAttr = sysProcAttr()
    +	cmd.WaitDelay = t.h.drainGrace
    +	err = cmd.Start()
    +	_ = w.Close() // the child holds its own copies
    +	_ = ew.Close()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +
    +	stderrLine := make(chan string, 1)
    +	go func() {
    +		br := bufio.NewReader(er)
    +		stderrLine <- firstLine(br)
    +		_, _ = io.Copy(io.Discard, br) // keep draining so the process never blocks on stderr
    +	}()
    +	lines := make(chan readResult)
    +	go readLines(r, lines)
    +	exited := make(chan struct{})
    +	go func() {
    +		_ = cmd.Wait() // the outcome is read from cmd.ProcessState
    +		close(exited)
    +	}()
    +
    +	var (
    +		phase    = phaseRunning
    +		deadline <-chan time.Time
    +		done     = ctx.Done()
    +		eof      bool
    +		exitSeen bool
    +		forced   bool // the harness closed stdout itself
    +		signaled bool // the harness signalled the process, so its exit status is not its own verdict
    +		failErr  error
    +		drainBy  time.Time // phaseKilled: when stdout is closed
    +	)
    +	enter := func(p int, d time.Duration) {
    +		phase = p
    +		if p == phaseKilled {
    +			drainBy, deadline = time.Now().Add(d), nil // armed per wait, below
    +			return
    +		}
    +		deadline = time.After(d)
    +	}
    +	interrupt := func() {
    +		if phase >= phaseInterrupted {
    +			return
    +		}
    +		interruptProcess(cmd.Process)
    +		signaled = true
    +		enter(phaseInterrupted, t.h.cfg.InterruptGrace)
    +	}
    +	for !eof || !exitSeen {
    +		var drain *time.Timer
    +		if phase == phaseKilled && !forced {
    +			drain = time.NewTimer(time.Until(drainBy))
    +			deadline = drain.C
    +		}
    +		select {
    +		case m, ok := <-lines:
    +			switch {
    +			case !ok:
    +				lines, eof = nil, true
    +				if phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			case m.err != nil:
    +				if !forced && failErr == nil {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			case failErr != nil || ctx.Err() != nil:
    +				// Stopping: drain.
    +			case t.result != nil:
    +				// Past the result: no further sink effects, but a malformed line still fails the
    +				// turn, as it would before the result.
    +				if !validLine(m.line) {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			default:
    +				began := time.Now()
    +				err := t.handle(ctx, m.line)
    +				if phase == phaseKilled {
    +					// drainGrace bounds how long stdout stays open while the harness waits on
    +					// it, not how long the sink takes: a slow Report must not cut off lines the
    +					// process wrote before it exited.
    +					drainBy = drainBy.Add(time.Since(began))
    +				}
    +				if err != nil {
    +					failErr = err
    +					interrupt()
    +				} else if t.result != nil && phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			}
    +		case <-exited:
    +			exited, exitSeen = nil, true
    +			if !eof && phase < phaseKilled {
    +				// Something the process started still holds stdout.
    +				enter(phaseKilled, t.h.drainGrace)
    +			}
    +		case <-done:
    +			done = nil
    +			interrupt()
    +		case <-deadline:
    +			switch phase {
    +			case phaseSettling:
    +				interrupt()
    +			case phaseInterrupted:
    +				killGroup(cmd.Process)
    +				enter(phaseKilled, t.h.drainGrace)
    +			default:
    +				killGroup(cmd.Process)
    +				forced = true
    +				_ = r.Close()
    +				deadline = nil
    +			}
    +		}
    +		if drain != nil {
    +			drain.Stop()
    +		}
    +	}
    +
    +	// The loop ends once the leader exited and stdout closed, but the group can outlive its leader:
    +	// a tool Claude Code started that redirected its stdio holds neither. Kill it on every path,
    +	// success included, so nothing the turn started runs once Run returns, or while it records.
    +	if !stopGroup(cmd.Process, t.h.drainGrace) {
    +		t.h.logger.Warn("claudecode: processes of the turn's group remain after the kill",
    +			"pid", cmd.Process.Pid, "wait", t.h.drainGrace)
    +	}
    +
    +	err = t.outcome(ctx, cmd.ProcessState.ExitCode(), signaled, failErr)
    +	if err != nil && !t.initSeen && ctx.Err() == nil {
    +		// Claude Code failed before it confirmed the session, so no tool ran and the model said
    +		// nothing; a failing --resume ends here on every later turn. Its reason is on stderr.
    +		var line string
    +		select {
    +		case line = <-stderrLine:
    +		case <-time.After(t.h.drainGrace): // a descendant outside the group holds stderr
    +		}
    +		t.h.logger.Warn("claudecode: claude failed before system/init",
    +			"session_uid", t.sessionUID, "flag", t.flag, "claude_session_id", t.sessionID,
    +			"exit_status", cmd.ProcessState.String(), "stderr", line)
    +	}
    +	return err
    +}
    +
    +// outcome records the turn's remaining effects and returns its result, once the process is gone.
    +func (t *turn) outcome(ctx context.Context, code int, signaled bool, failErr error) error {
    +	if err := ctx.Err(); err != nil {
    +		return interruptedErr(err)
    +	}
    +	if t.sinkErr != nil {
    +		return t.sinkErr
    +	}
    +	if err := t.finish(ctx); err != nil {
    +		return err
    +	}
    +	if failErr != nil {
    +		return failErr
    +	}
    +	if t.result == nil {
    +		if !signaled && code != 0 {
    +			return fmt.Errorf("claudecode: claude exited with status %d before a result", code)
    +		}
    +		return errNoResult
    +	}
    +	if t.result.IsError || t.result.Subtype != "success" {
    +		return fmt.Errorf("claudecode: claude reported an error result (subtype %s)", subtype(t.result.Subtype))
    +	}
    +	if !signaled && code != 0 {
    +		return fmt.Errorf("claudecode: claude exited with status %d after a success result", code)
    +	}
    +	for _, chunk := range chunks(t.result.Result, outputChunkBytes) {
    +		if err := t.sink.Output(ctx, chunk); err != nil {
    +			return fmt.Errorf("claudecode: record output: %w", err)
    +		}
    +	}
    +	return nil
    +}
    +
    +// interruptedErr is the error of a turn whose ctx is done.
    +func interruptedErr(err error) error {
    +	return fmt.Errorf("claudecode: turn interrupted: %w", err)
    +}
    +
    +// readLines sends each stdout line, then a read error if any, then closes out. After an error it
    +// keeps draining so the process never blocks on a full pipe.
    +func readLines(r io.Reader, out chan<- readResult) {
    +	defer close(out)
    +	sc := bufio.NewScanner(r)
    +	sc.Buffer(make([]byte, 0, 64<<10), maxLineBytes)
    +	for sc.Scan() {
    +		out <- readResult{line: bytes.Clone(sc.Bytes())}
    +	}
    +	if err := sc.Err(); err != nil {
    +		out <- readResult{err: err}
    +		_, _ = io.Copy(io.Discard, r)
    +	}
    +}
    +
    +// firstLine returns the first non-blank line of r, cut to stderrLineBytes, with invalid UTF-8,
    +// control and format characters (bidi overrides included) replaced. Leading space is skipped
    +// across ReadLine's chunks, so a long line that starts with spaces is still that line. It reads
    +// to the end of that line and no further; "" at EOF.
    +func firstLine(r *bufio.Reader) string {
    +	var b []byte
    +	for {
    +		chunk, more, err := r.ReadLine()
    +		if len(b) == 0 {
    +			chunk = bytes.TrimLeftFunc(chunk, unicode.IsSpace)
    +		}
    +		b = append(b, chunk[:min(len(chunk), stderrLineBytes-len(b))]...)
    +		if more && err == nil {
    +			continue
    +		}
    +		if len(b) > 0 {
    +			break
    +		}
    +		if err != nil {
    +			return ""
    +		}
    +	}
    +	s := strings.Map(func(c rune) rune {
    +		if unicode.IsControl(c) || unicode.Is(unicode.Cf, c) {
    +			return '?'
    +		}
    +		return c
    +	}, strings.ToValidUTF8(string(bytes.TrimRightFunc(b, unicode.IsSpace)), "\uFFFD"))
    +	s, _ = truncate(s, stderrLineBytes)
    +	return s
    +}
    +
    +// validLine reports whether line is blank or a stream-json event, by the same decoding handle
    +// applies.
    +func validLine(line []byte) bool {
    +	if len(bytes.TrimSpace(line)) == 0 {
    +		return true
    +	}
    +	var ev streamLine
    +	return json.Unmarshal(line, &ev) == nil
    +}
    +
    +// handle maps one stream-json line.
    +func (t *turn) handle(ctx context.Context, line []byte) error {
    +	if len(bytes.TrimSpace(line)) == 0 {
    +		return nil
    +	}
    +	var ev streamLine
    +	if err := json.Unmarshal(line, &ev); err != nil {
    +		return errMalformed
    +	}
    +	switch ev.Type {
    +	case "system":
    +		if ev.Subtype != "init" {
    +			return nil
    +		}
    +		if ev.SessionID != t.sessionID {
    +			return errSessionMismatch
    +		}
    +		t.initSeen, t.initModel = true, ev.Model
    +		return nil
    +	case "stream_event":
    +		// Partial message deltas: there is no sink method for an ephemeral delta, so they are
    +		// dropped. The turn's text is recorded once from the result.
    +		return nil
    +	case "assistant", "user", "result":
    +	default:
    +		return nil
    +	}
    +	if !t.initSeen {
    +		return errNoInit
    +	}
    +	if ev.SessionID != "" && ev.SessionID != t.sessionID {
    +		return errSessionMismatch
    +	}
    +	switch ev.Type {
    +	case "assistant":
    +		return t.assistant(&ev)
    +	case "user":
    +		return t.user(ctx, &ev)
    +	default:
    +		if ev.Usage != nil && !ev.Usage.valid() {
    +			return errMalformed
    +		}
    +		t.result = &ev
    +		return nil
    +	}
    +}
    +
    +// assistant holds tool_use blocks until their result and records main-loop usage once per message
    +// id, the fallback when no result reports usage.
    +func (t *turn) assistant(ev *streamLine) error {
    +	var msg message
    +	if err := json.Unmarshal(ev.Message, &msg); err != nil {
    +		return errMalformed
    +	}
    +	blocks, err := contentBlocks(msg.Content)
    +	if err != nil {
    +		return err
    +	}
    +	for _, b := range blocks {
    +		if b.Type != "tool_use" {
    +			continue
    +		}
    +		if b.ID == "" {
    +			return errMalformed
    +		}
    +		if _, ok := t.tools[b.ID]; !ok {
    +			t.toolOrder = append(t.toolOrder, b.ID)
    +		}
    +		t.tools[b.ID] = toolUse{name: b.Name, input: b.Input, parent: ev.ParentToolUseID}
    +	}
    +	if msg.Usage != nil {
    +		if !msg.Usage.valid() {
    +			return errMalformed
    +		}
    +		if ev.ParentToolUseID == "" && msg.ID != "" {
    +			if _, ok := t.seenMsgs[msg.ID]; !ok {
    +				t.seenMsgs[msg.ID] = struct{}{}
    +				t.recovered.InputTokens += msg.Usage.InputTokens
    +				t.recovered.CacheReadInputTokens += msg.Usage.CacheReadInputTokens
    +				t.recovered.CacheCreationInputTokens += msg.Usage.CacheCreationInputTokens
    +			}
    +		}
    +	}
    +	return nil
    +}
    +
    +// user reports each tool_result block.
    +func (t *turn) user(ctx context.Context, ev *streamLine) error {
    +	var msg message
    +	if err := json.Unmarshal(ev.Message, &msg); err != nil {
    +		return errMalformed
    +	}
    +	blocks, err := contentBlocks(msg.Content)
    +	if err != nil {
    +		return err
    +	}
    +	for _, b := range blocks {
    +		if b.Type != "tool_result" {
    +			continue
    +		}
    +		if b.ToolUseID == "" {
    +			return errMalformed
    +		}
    +		use, ok := t.tools[b.ToolUseID]
    +		if ok {
    +			delete(t.tools, b.ToolUseID)
    +		} else {
    +			use = toolUse{parent: ev.ParentToolUseID} // orphan: reported with no tool name
    +		}
    +		text, n := toolContent(b.Content)
    +		tr := t.receipt(b.ToolUseID, use, text, n)
    +		tr.IsError = b.IsError
    +		if err := t.report(ctx, tr); err != nil {
    +			return err
    +		}
    +	}
    +	return nil
    +}
    +
    +// receipt builds a tool result receipt: full while the budgets allow, else sizes only.
    +func (t *turn) receipt(id string, use toolUse, content string, contentBytes int) api.ToolResult {
    +	if t.receipts {
    +		input, inTrunc := truncate(string(use.input), receiptFieldBytes)
    +		text, outTrunc := truncate(content, receiptFieldBytes)
    +		out := map[string]any{
    +			"input":       input,
    +			"input_bytes": float64(len(use.input)),
    +			"truncated":   inTrunc || outTrunc,
    +		}
    +		tagTool(out, use)
    +		tr := api.ToolResult{ID: id, Output: out}
    +		if text != "" {
    +			tr.Content = []api.Part{{Text: &api.TextPart{Text: text}}}
    +		}
    +		size := proto.Size(wire.ToolResultToProto(&tr))
    +		if t.receiptBytes+size <= turnReceiptBudget {
    +			t.receiptBytes += size
    +			return tr
    +		}
    +		t.receipts = false
    +	}
    +	out := map[string]any{
    +		"input_bytes":   float64(len(use.input)),
    +		"content_bytes": float64(contentBytes),
    +		"omitted":       true,
    +	}
    +	tagTool(out, use)
    +	return api.ToolResult{ID: id, Output: out}
    +}
    +
    +func tagTool(out map[string]any, use toolUse) {
    +	if use.name != "" {
    +		out["tool"] = use.name
    +	}
    +	if use.parent != "" {
    +		out["parent_tool_use_id"] = use.parent
    +	}
    +}
    +
    +func (t *turn) report(ctx context.Context, tr api.ToolResult) error {
    +	if err := t.sink.Report(ctx, tr); err != nil {
    +		t.sinkErr = fmt.Errorf("claudecode: record tool result: %w", err)
    +		return t.sinkErr
    +	}
    +	return nil
    +}
    +
    +// finish reports tool calls that never got a result and the turn's usage.
    +func (t *turn) finish(ctx context.Context) error {
    +	for _, id := range t.toolOrder {
    +		use, ok := t.tools[id]
    +		if !ok {
    +			continue
    +		}
    +		delete(t.tools, id)
    +		tr := t.receipt(id, use, "", 0)
    +		tr.IsError, tr.Error = true, "no result observed"
    +		if err := t.report(ctx, tr); err != nil {
    +			return err
    +		}
    +	}
    +	var u tokenUsage
    +	if t.result != nil && t.result.Usage != nil {
    +		u = *t.result.Usage
    +	}
    +	if u.input() == 0 && u.OutputTokens == 0 {
    +		u = t.recovered // crashed or zeroed result: input and cache tokens only
    +	}
    +	if u.input() == 0 && u.OutputTokens == 0 {
    +		return nil
    +	}
    +	model := t.initModel
    +	if model == "" {
    +		model = t.model
    +	}
    +	if err := t.sink.Usage(ctx, api.Usage{Model: model, InputTokens: u.input(), OutputTokens: u.OutputTokens}); err != nil {
    +		return fmt.Errorf("claudecode: record usage: %w", err)
    +	}
    +	return nil
    +}
    +
    +// contentBlocks decodes message content: an array of blocks, or a string, which has none.
    +func contentBlocks(raw json.RawMessage) ([]contentBlock, error) {
    +	raw = bytes.TrimSpace(raw)
    +	if len(raw) == 0 || raw[0] != '[' {
    +		return nil, nil
    +	}

    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.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 08, 2026 18:22 UTC
    Reviewer

    <!-- 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>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Only ignore exit status when SIGINT was delivered · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Reject non-string, non-array message content · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Validate stream lines after a success result

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Resolve relative binary paths before changing the working directory

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Update published contracts for unmediated harness behavior

  • </details>

    <details>
    <summary><strong>4 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Restrict stderr logging to the expected missing-transcript diagnostic

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Implement process cleanup or reject unsupported platforms

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Pin a root-module version containing the harnessnode package

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Avoid printing environment values in failed assertions

  • </details>

    <sub>Review effort: Balanced</sub>

    gambtho gambtho commented on Nov 08, 2026 20:02 UTC
    Reviewer

    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.

    Copilot Copilot commented on code on Nov 09, 2026 00:03 UTC
    Code Review
    integrations/claudecode/proc_unix.go:1
    @@ -0,0 +1,69 @@
    +//go:build unix
    +
    +package claudecode
    +
    +import (
    +	"errors"
    +	"os"
    +	"syscall"
    +	"time"
    +)
    +
    +// checkPlatform accepts this platform: it has process groups.
    +func checkPlatform() error { return nil }
    +
    +// sysProcAttr puts the process in its own process group, so the harness can kill everything it
    +// started.
    +func sysProcAttr() *syscall.SysProcAttr { return &syscall.SysProcAttr{Setpgid: true} }
    +
    +// interruptProcess sends SIGINT to the process itself, which Claude Code handles by ending the
    +// turn. A nil error means it was sent to a process not yet waited for, which may already have
    +// exited; os.Process refuses a process that was waited for (os.ErrProcessDone).
    +func interruptProcess(p *os.Process) error { return p.Signal(os.Interrupt) }
    +
    +// stoppedByHarness reports whether the process died of a signal the harness delivered to it:
    +// SIGINT when interrupted, SIGKILL when killed. Claude Code 2.1.311 handles SIGINT and exits 0,
    +// which needs no excuse; any nonzero exit status, or a death by a signal the harness did not
    +// deliver, is the process's own verdict.
    +func stoppedByHarness(ps *os.ProcessState, interrupted, killed bool) bool {
    +	if ps == nil {
    +		return false
    +	}
    +	ws, ok := ps.Sys().(syscall.WaitStatus)
    +	if !ok || !ws.Signaled() {
    +		return false
    +	}
    +	switch ws.Signal() {
    +	case syscall.SIGINT:
    +		return interrupted
    +	case syscall.SIGKILL:
    +		return killed
    +	}
    +	return false
    +}
    +
    +// killGroup sends SIGKILL to the process and then to the process group it leads (sysProcAttr sets
    +// Setpgid). It reports whether the process itself took the signal: one already waited for refuses
    +// it. The kernel does not reuse a pid while a process group with that id has members, so -pid
    +// reaches only this group while any member lives. A descendant that left the group (setsid) is not
    +// reached.
    +func killGroup(p *os.Process) bool {
    +	delivered := p.Signal(os.Kill) == nil
    +	_ = syscall.Kill(-p.Pid, syscall.SIGKILL)

    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.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 09, 2026 00:03 UTC
    Reviewer

    <!-- 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>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Prevent process-group ID reuse before cleanup signals the group · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Validate stream lines after a success result

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Resolve relative binary paths before changing the working directory

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Update published contracts for unmediated harness behavior

  • </details>

    <details>
    <summary><strong>2 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Only ignore exit status when SIGINT was delivered

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Reject non-string, non-array message content

  • </details>

    <sub>Review effort: Balanced</sub>

    aramase aramase commented on code on Nov 09, 2026 04:02 UTC
    Code Review
    integrations/claudecode/proc_unix.go:1
    @@ -0,0 +1,69 @@
    +//go:build unix
    +
    +package claudecode
    +
    +import (
    +	"errors"
    +	"os"
    +	"syscall"
    +	"time"
    +)
    +
    +// checkPlatform accepts this platform: it has process groups.
    +func checkPlatform() error { return nil }
    +
    +// sysProcAttr puts the process in its own process group, so the harness can kill everything it
    +// started.
    +func sysProcAttr() *syscall.SysProcAttr { return &syscall.SysProcAttr{Setpgid: true} }
    +
    +// interruptProcess sends SIGINT to the process itself, which Claude Code handles by ending the
    +// turn. A nil error means it was sent to a process not yet waited for, which may already have
    +// exited; os.Process refuses a process that was waited for (os.ErrProcessDone).
    +func interruptProcess(p *os.Process) error { return p.Signal(os.Interrupt) }
    +
    +// stoppedByHarness reports whether the process died of a signal the harness delivered to it:
    +// SIGINT when interrupted, SIGKILL when killed. Claude Code 2.1.311 handles SIGINT and exits 0,
    +// which needs no excuse; any nonzero exit status, or a death by a signal the harness did not
    +// deliver, is the process's own verdict.
    +func stoppedByHarness(ps *os.ProcessState, interrupted, killed bool) bool {
    +	if ps == nil {
    +		return false
    +	}
    +	ws, ok := ps.Sys().(syscall.WaitStatus)
    +	if !ok || !ws.Signaled() {
    +		return false
    +	}
    +	switch ws.Signal() {
    +	case syscall.SIGINT:
    +		return interrupted
    +	case syscall.SIGKILL:
    +		return killed
    +	}
    +	return false
    +}
    +
    +// killGroup sends SIGKILL to the process and then to the process group it leads (sysProcAttr sets
    +// Setpgid). It reports whether the process itself took the signal: one already waited for refuses
    +// it. The kernel does not reuse a pid while a process group with that id has members, so -pid
    +// reaches only this group while any member lives. A descendant that left the group (setsid) is not
    +// reached.
    +func killGroup(p *os.Process) bool {
    +	delivered := p.Signal(os.Kill) == nil
    +	_ = syscall.Kill(-p.Pid, syscall.SIGKILL)

    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.

    Copilot Copilot commented on code on Nov 09, 2026 04:08 UTC
    Code Review
    integrations/claudecode/turn.go:1
    @@ -0,0 +1,760 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"os"
    +	"os/exec"
    +	"strings"
    +	"sync/atomic"
    +	"time"
    +	"unicode"
    +	"unicode/utf8"
    +
    +	"google.golang.org/protobuf/proto"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/wire"
    +)
    +
    +const (
    +	// maxLineBytes bounds one stream-json line. A longer line fails the turn as malformed.
    +	maxLineBytes = 16 << 20
    +	// receiptFieldBytes bounds the tool input and the tool content a full receipt carries.
    +	receiptFieldBytes = 2 << 10
    +	// turnReceiptBudget bounds one turn's full receipts; later receipts in the turn are minimal.
    +	turnReceiptBudget = 128 << 10
    +	// outputChunkBytes bounds one Output call, well under gRPC's default 4 MiB frame limit.
    +	outputChunkBytes = 1 << 20
    +	// stderrLineBytes bounds the stderr line logged for a process that failed before system/init.
    +	stderrLineBytes = 256
    +)
    +
    +var (
    +	errMalformed       = errors.New("claudecode: malformed stream-json from claude")
    +	errNoInit          = errors.New("claudecode: claude stream has events before system/init")
    +	errSessionMismatch = errors.New("claudecode: claude reported a different session id")
    +	errNoResult        = errors.New("claudecode: claude stream ended without a result")
    +)
    +
    +// streamLine is one stream-json event. Only the fields the harness maps are decoded; unknown
    +// event types and fields are ignored.
    +type streamLine struct {
    +	Type            string          `json:"type"`
    +	Subtype         string          `json:"subtype"`
    +	SessionID       string          `json:"session_id"`
    +	Model           string          `json:"model"`
    +	ParentToolUseID string          `json:"parent_tool_use_id"`
    +	Message         json.RawMessage `json:"message"`
    +	IsError         bool            `json:"is_error"`
    +	Result          string          `json:"result"`
    +	Usage           *tokenUsage     `json:"usage"`
    +}
    +
    +// message is the Anthropic-shaped message inside assistant and user events. Content is a string or
    +// an array of blocks.
    +type message struct {
    +	ID      string          `json:"id"`
    +	Content json.RawMessage `json:"content"`
    +	Usage   *tokenUsage     `json:"usage"`
    +}
    +
    +type contentBlock struct {
    +	Type      string          `json:"type"`
    +	Text      string          `json:"text"`
    +	ID        string          `json:"id"`
    +	Name      string          `json:"name"`
    +	Input     json.RawMessage `json:"input"`
    +	ToolUseID string          `json:"tool_use_id"`
    +	Content   json.RawMessage `json:"content"`
    +	IsError   bool            `json:"is_error"`
    +}
    +
    +type tokenUsage struct {
    +	InputTokens              int64 `json:"input_tokens"`
    +	OutputTokens             int64 `json:"output_tokens"`
    +	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
    +	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
    +}
    +
    +func (u *tokenUsage) valid() bool {
    +	return u.InputTokens >= 0 && u.OutputTokens >= 0 && u.CacheCreationInputTokens >= 0 && u.CacheReadInputTokens >= 0
    +}
    +
    +// input is every input token the model processed: uncached, cache reads and cache writes.
    +func (u *tokenUsage) input() int64 {
    +	return u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens
    +}
    +
    +type toolUse struct {
    +	name   string
    +	input  json.RawMessage
    +	parent string
    +}
    +
    +// turn is one Run's process and stream state. Only the goroutine running run touches it.
    +type turn struct {
    +	h          *Harness
    +	sink       api.EventSink
    +	sessionUID string
    +	flag       string // --session-id or --resume
    +	sessionID  string
    +	model      string
    +	receipts   bool // full receipts; false once the session or turn budget is spent
    +
    +	receiptBytes int
    +	initSeen     bool
    +	initModel    string
    +	tools        map[string]toolUse
    +	toolOrder    []string
    +	seenMsgs     map[string]struct{}
    +	recovered    tokenUsage // main-loop assistant usage, deduplicated by message id
    +	result       *streamLine
    +	sinkErr      error
    +}
    +
    +// receiptMode reports whether full receipts are allowed this turn: History, sized as the wire sends
    +// it, is under half of StartLimit. It warns once History reaches three quarters of it.
    +func (h *Harness) receiptMode(s *api.Start) bool {
    +	n := 0
    +	for _, e := range s.History {
    +		n += proto.Size(wire.EventToProto(e))
    +	}
    +	if n >= h.cfg.StartLimit/4*3 {
    +		h.logger.Warn("claudecode: session history nears the harness receive limit; raise the limit and Config.StartLimit",
    +			"session_uid", s.SessionUID, "history_bytes", n, "start_limit", h.cfg.StartLimit)
    +	}
    +	return n < h.cfg.StartLimit/2
    +}
    +
    +type readResult struct {
    +	line []byte
    +	err  error
    +}
    +
    +// Process phases. Each later phase is entered at most once, in order.
    +const (
    +	phaseRunning     = iota
    +	phaseSettling    // result seen or stdout closed: the process gets postResultGrace to exit
    +	phaseInterrupted // SIGINT sent: the process gets InterruptGrace to exit
    +	phaseKilled      // group killed or leader exited: stdout gets drainGrace of waiting to close
    +)
    +
    +// run starts the process, maps its stream, and returns the turn's outcome.
    +func (t *turn) run(ctx context.Context, args []string, prompt string) error {
    +	t.tools = make(map[string]toolUse)
    +	t.seenMsgs = make(map[string]struct{})
    +	if err := ctx.Err(); err != nil {
    +		return interruptedErr(err) // cancelled while the inputs were validated: launch nothing
    +	}
    +
    +	r, w, err := os.Pipe()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = r.Close() }()
    +	// stderr can carry prompt or tool text. Only its first line is kept, and logged only for a
    +	// process that failed before system/init. A pipe, not an io.Writer, so cmd.Wait does not wait
    +	// for a descendant that holds stderr.
    +	er, ew, err := os.Pipe()
    +	if err != nil {
    +		_ = w.Close()
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = er.Close() }()
    +	cmd := exec.Command(t.h.cfg.Binary, args...)
    +	cmd.Dir = t.h.cfg.WorkDir
    +	cmd.Env = t.h.env
    +	cmd.Stdin = strings.NewReader(prompt)
    +	cmd.Stdout = w
    +	cmd.Stderr = ew
    +	cmd.SysProcAttr = sysProcAttr()
    +	cmd.WaitDelay = t.h.drainGrace
    +	err = cmd.Start()
    +	_ = w.Close() // the child holds its own copies
    +	_ = ew.Close()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +
    +	stderrLine := make(chan string, 1)
    +	go func() {
    +		br := bufio.NewReader(er)
    +		stderrLine <- firstLine(br)
    +		_, _ = io.Copy(io.Discard, br) // keep draining so the process never blocks on stderr
    +	}()
    +	lines := make(chan readResult)
    +	go readLines(r, lines)
    +	// The leader is reaped only once its group is killed for the last time (stopGroup, below):
    +	// until then the zombie reserves the id every kill of the group signals. The outcome is read
    +	// from cmd.ProcessState after the reap.
    +	var (
    +		exited       = make(chan struct{})
    +		leaderExited atomic.Bool // the observer saw the leader exit
    +		reaped       bool        // the observer had to reap it; read only after exited closed
    +	)
    +	go func() {
    +		wait := waitExit
    +		if t.h.waitExit != nil {
    +			wait = t.h.waitExit
    +		}
    +		if err := wait(cmd.Process); err != nil {
    +			if !errors.Is(err, errors.ErrUnsupported) {
    +				t.h.waitExitWarn.Do(func() {
    +					t.h.logger.Warn("claudecode: cannot wait for claude's exit without reaping it; "+
    +						"its process group id is not reserved after it exits", "err", err)
    +				})
    +			}
    +			_ = cmd.Wait()
    +			reaped = true
    +		}
    +		leaderExited.Store(true)
    +		if t.h.exitObserved != nil {
    +			t.h.exitObserved()
    +		}
    +		close(exited)
    +	}()
    +
    +	var (
    +		phase    = phaseRunning
    +		deadline <-chan time.Time
    +		done     = ctx.Done()
    +		eof      bool
    +		exitSeen bool
    +		forced   bool // the harness closed stdout itself
    +		signaled bool // SIGINT reached the process before the turn saw it exit
    +		killed   bool // SIGKILL reached the process before the turn saw it exit
    +		failErr  error
    +		drainBy  time.Time // phaseKilled: when stdout is closed
    +	)
    +	enter := func(p int, d time.Duration) {
    +		phase = p
    +		if p == phaseKilled {
    +			drainBy, deadline = time.Now().Add(d), nil // armed per wait, below
    +			return
    +		}
    +		if t.h.after != nil {
    +			deadline = t.h.after(d)
    +			return
    +		}
    +		deadline = time.After(d)
    +	}
    +	interrupt := func() {
    +		if phase >= phaseInterrupted {
    +			return
    +		}
    +		// An unreaped zombie takes the signal, so delivery counts only before the turn saw the
    +		// process exit. Delivery alone does not excuse the exit status either: outcome also needs
    +		// the status to show it died of SIGINT.
    +		running := !leaderExited.Load()
    +		signaled = interruptProcess(cmd.Process) == nil && running
    +		enter(phaseInterrupted, t.h.cfg.InterruptGrace)
    +	}
    +	// kill kills the group and reports whether SIGKILL reached the process before the turn saw it
    +	// exit, as interrupt does for SIGINT.
    +	kill := func() bool {
    +		running := !leaderExited.Load()
    +		return killGroup(cmd.Process) && running
    +	}
    +	for !eof || !exitSeen {
    +		var drain *time.Timer
    +		if phase == phaseKilled && !forced {
    +			drain = time.NewTimer(time.Until(drainBy))
    +			deadline = drain.C
    +		}
    +		select {
    +		case m, ok := <-lines:
    +			switch {
    +			case !ok:
    +				lines, eof = nil, true
    +				if phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			case m.err != nil:
    +				if !forced && failErr == nil {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			case failErr != nil || ctx.Err() != nil:
    +				// Stopping: drain.
    +			case t.result != nil:
    +				// Past the result: no further sink effects, but a malformed line still fails the
    +				// turn, as it would before the result.
    +				if !validLine(m.line) {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			default:
    +				began := time.Now()
    +				err := t.handle(ctx, m.line)
    +				if phase == phaseKilled {
    +					// drainGrace bounds how long stdout stays open while the harness waits on
    +					// it, not how long the sink takes: a slow Report must not cut off lines the
    +					// process wrote before it exited.
    +					drainBy = drainBy.Add(time.Since(began))
    +				}
    +				if err != nil {
    +					failErr = err
    +					interrupt()
    +				} else if t.result != nil && phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			}
    +		case <-exited:
    +			exited, exitSeen = nil, true
    +			if !eof && phase < phaseKilled {
    +				// Something the process started still holds stdout.
    +				enter(phaseKilled, t.h.drainGrace)
    +			}
    +		case <-done:
    +			done = nil
    +			interrupt()
    +		case <-deadline:
    +			switch phase {
    +			case phaseSettling:
    +				interrupt()
    +			case phaseInterrupted:
    +				killed = kill() || killed
    +				enter(phaseKilled, t.h.drainGrace)
    +			default:
    +				killed = kill() || killed
    +				forced = true
    +				_ = r.Close()
    +				deadline = nil
    +			}
    +		}
    +		if drain != nil {
    +			drain.Stop()
    +		}
    +	}
    +
    +	// The loop ends once the leader exited and stdout closed, but the group can outlive its leader:
    +	// a tool Claude Code started that redirected its stdio holds neither. Kill it on every path,
    +	// success included, so nothing the turn started runs once Run returns, or while it records.
    +	reap := func() {
    +		if t.h.beforeReap != nil {
    +			t.h.beforeReap(cmd.Process.Pid)
    +		}
    +		if !reaped {
    +			_ = cmd.Wait()
    +		}
    +	}
    +	if !stopGroup(cmd.Process, reap, t.h.drainGrace) {
    +		t.h.logger.Warn("claudecode: processes of the turn's group remain after the kill",
    +			"pid", cmd.Process.Pid, "wait", t.h.drainGrace)
    +	}
    +
    +	err = t.outcome(ctx, cmd.ProcessState.ExitCode(), stoppedByHarness(cmd.ProcessState, signaled, killed), failErr)
    +	if err != nil && !t.initSeen && ctx.Err() == nil {
    +		// Claude Code failed before it confirmed the session, so no tool ran and the model said
    +		// nothing; a failing --resume ends here on every later turn. Its reason is on stderr.
    +		var line string
    +		select {
    +		case line = <-stderrLine:
    +		case <-time.After(t.h.drainGrace): // a descendant outside the group holds stderr
    +		}
    +		t.h.logger.Warn("claudecode: claude failed before system/init",
    +			"session_uid", t.sessionUID, "flag", t.flag, "claude_session_id", t.sessionID,
    +			"exit_status", cmd.ProcessState.String(), "stderr", line)
    +	}
    +	return err
    +}
    +
    +// outcome records the turn's remaining effects and returns its result, once the process is gone.
    +// stopped reports that a signal the harness delivered ended the process, so its exit status is not
    +// its own verdict.
    +func (t *turn) outcome(ctx context.Context, code int, stopped bool, failErr error) error {
    +	if err := ctx.Err(); err != nil {
    +		return interruptedErr(err)
    +	}
    +	if t.sinkErr != nil {
    +		return t.sinkErr
    +	}
    +	if err := t.finish(ctx); err != nil {
    +		return err
    +	}
    +	if failErr != nil {
    +		return failErr
    +	}
    +	if t.result == nil {
    +		if !stopped && code != 0 {
    +			return fmt.Errorf("claudecode: claude exited with status %d before a result", code)
    +		}
    +		return errNoResult
    +	}
    +	if t.result.IsError || t.result.Subtype != "success" {
    +		return fmt.Errorf("claudecode: claude reported an error result (subtype %s)", subtype(t.result.Subtype))
    +	}
    +	if !stopped && code != 0 {
    +		return fmt.Errorf("claudecode: claude exited with status %d after a success result", code)
    +	}
    +	for _, chunk := range chunks(t.result.Result, outputChunkBytes) {
    +		if err := t.sink.Output(ctx, chunk); err != nil {
    +			return fmt.Errorf("claudecode: record output: %w", err)
    +		}
    +	}
    +	return nil
    +}
    +
    +// interruptedErr is the error of a turn whose ctx is done.
    +func interruptedErr(err error) error {
    +	return fmt.Errorf("claudecode: turn interrupted: %w", err)
    +}
    +
    +// readLines sends each stdout line, then a read error if any, then closes out. After an error it
    +// keeps draining so the process never blocks on a full pipe.
    +func readLines(r io.Reader, out chan<- readResult) {
    +	defer close(out)
    +	sc := bufio.NewScanner(r)
    +	sc.Buffer(make([]byte, 0, 64<<10), maxLineBytes)
    +	for sc.Scan() {
    +		out <- readResult{line: bytes.Clone(sc.Bytes())}
    +	}
    +	if err := sc.Err(); err != nil {
    +		out <- readResult{err: err}
    +		_, _ = io.Copy(io.Discard, r)
    +	}
    +}
    +
    +// firstLine returns the first non-blank line of r, cut to stderrLineBytes, with invalid UTF-8,
    +// control and format characters (bidi overrides included) replaced. Leading space is skipped
    +// across ReadLine's chunks, so a long line that starts with spaces is still that line. It reads
    +// to the end of that line and no further; "" at EOF.
    +func firstLine(r *bufio.Reader) string {
    +	var b []byte
    +	for {
    +		chunk, more, err := r.ReadLine()
    +		if len(b) == 0 {
    +			chunk = bytes.TrimLeftFunc(chunk, unicode.IsSpace)
    +		}
    +		b = append(b, chunk[:min(len(chunk), stderrLineBytes-len(b))]...)
    +		if more && err == nil {
    +			continue
    +		}
    +		if len(b) > 0 {
    +			break
    +		}
    +		if err != nil {
    +			return ""
    +		}
    +	}
    +	s := strings.Map(func(c rune) rune {
    +		if unicode.IsControl(c) || unicode.Is(unicode.Cf, c) {
    +			return '?'
    +		}
    +		return c
    +	}, strings.ToValidUTF8(string(bytes.TrimRightFunc(b, unicode.IsSpace)), "\uFFFD"))
    +	s, _ = truncate(s, stderrLineBytes)
    +	return s
    +}
    +
    +// validLine reports whether line is blank or a stream-json event, by the same decoding handle
    +// applies.
    +func validLine(line []byte) bool {
    +	if len(bytes.TrimSpace(line)) == 0 {
    +		return true
    +	}
    +	var ev streamLine
    +	return json.Unmarshal(line, &ev) == nil
    +}
    +
    +// handle maps one stream-json line.
    +func (t *turn) handle(ctx context.Context, line []byte) error {
    +	if len(bytes.TrimSpace(line)) == 0 {
    +		return nil
    +	}
    +	var ev streamLine
    +	if err := json.Unmarshal(line, &ev); err != nil {
    +		return errMalformed
    +	}
    +	switch ev.Type {
    +	case "system":
    +		if ev.Subtype != "init" {
    +			return nil
    +		}
    +		if ev.SessionID != t.sessionID {
    +			return errSessionMismatch
    +		}
    +		t.initSeen, t.initModel = true, ev.Model
    +		return nil
    +	case "stream_event":
    +		// Partial message deltas: there is no sink method for an ephemeral delta, so they are
    +		// dropped. The turn's text is recorded once from the result.
    +		return nil
    +	case "assistant", "user", "result":
    +	default:
    +		return nil
    +	}
    +	if !t.initSeen {
    +		return errNoInit
    +	}
    +	if ev.SessionID != "" && ev.SessionID != t.sessionID {
    +		return errSessionMismatch
    +	}
    +	switch ev.Type {
    +	case "assistant":
    +		return t.assistant(&ev)
    +	case "user":
    +		return t.user(ctx, &ev)
    +	default:
    +		if ev.Usage != nil && !ev.Usage.valid() {
    +			return errMalformed
    +		}
    +		t.result = &ev
    +		return nil
    +	}
    +}
    +
    +// assistant holds tool_use blocks until their result and records main-loop usage once per message
    +// id, the fallback when no result reports usage.
    +func (t *turn) assistant(ev *streamLine) error {
    +	var msg message
    +	if err := json.Unmarshal(ev.Message, &msg); err != nil {
    +		return errMalformed
    +	}
    +	blocks, err := contentBlocks(msg.Content)
    +	if err != nil {
    +		return err
    +	}
    +	for _, b := range blocks {
    +		if b.Type != "tool_use" {
    +			continue
    +		}
    +		if b.ID == "" {
    +			return errMalformed
    +		}
    +		if _, ok := t.tools[b.ID]; !ok {
    +			t.toolOrder = append(t.toolOrder, b.ID)
    +		}
    +		t.tools[b.ID] = toolUse{name: b.Name, input: b.Input, parent: ev.ParentToolUseID}
    +	}
    +	if msg.Usage != nil {
    +		if !msg.Usage.valid() {
    +			return errMalformed
    +		}
    +		if ev.ParentToolUseID == "" && msg.ID != "" {
    +			if _, ok := t.seenMsgs[msg.ID]; !ok {
    +				t.seenMsgs[msg.ID] = struct{}{}
    +				t.recovered.InputTokens += msg.Usage.InputTokens
    +				t.recovered.CacheReadInputTokens += msg.Usage.CacheReadInputTokens
    +				t.recovered.CacheCreationInputTokens += msg.Usage.CacheCreationInputTokens
    +			}
    +		}
    +	}
    +	return nil
    +}
    +
    +// user reports each tool_result block.
    +func (t *turn) user(ctx context.Context, ev *streamLine) error {
    +	var msg message
    +	if err := json.Unmarshal(ev.Message, &msg); err != nil {
    +		return errMalformed
    +	}
    +	blocks, err := contentBlocks(msg.Content)
    +	if err != nil {
    +		return err
    +	}
    +	for _, b := range blocks {
    +		if b.Type != "tool_result" {
    +			continue
    +		}
    +		if b.ToolUseID == "" {
    +			return errMalformed
    +		}
    +		use, ok := t.tools[b.ToolUseID]
    +		if ok {
    +			delete(t.tools, b.ToolUseID)
    +		} else {
    +			use = toolUse{parent: ev.ParentToolUseID} // orphan: reported with no tool name
    +		}
    +		text, n, err := toolContent(b.Content)
    +		if err != nil {
    +			return err
    +		}

    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.

    Copilot Copilot commented on code on Nov 09, 2026 04:08 UTC
    Code Review
    CONTRIBUTING.md:1
    @@ -10,11 +10,13 @@ go build ./...
     go test -race -shuffle=on ./...
     ```
     
    -`integrations/substrate` is a separate Go module and is not reached by `./...` from the root. If you
    -touch it, test it on its own:
    +Each module under `integrations/` (`integrations/substrate`, `integrations/claudecode`) is a
    +separate Go module and is not reached by `./...` from the root. If you touch one, test it on its
    +own:
     
     ```bash
     cd integrations/substrate && go test -race -shuffle=on ./...
    +cd integrations/claudecode && go test -race -shuffle=on ./...

    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.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Nov 09, 2026 04:08 UTC
    Reviewer

    <!-- 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>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Malformed tool results can drop pending tools without a receipt · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Validate stream lines after a success result

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/medium-v2-light.png" alt="Medium severity" width="62" height="18" align="texttop"></picture> Resolve relative binary paths before changing the working directory

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Run each test command from the repository root · New

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/low-v2-light.png" alt="Low severity" width="62" height="18" align="texttop"></picture> Update published contracts for unmediated harness behavior

  • </details>

    <details>
    <summary><strong>1 resolved since last review</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Prevent process-group ID reuse before cleanup signals the group

  • </details>

    <sub>Review effort: Balanced</sub>

    gambtho gambtho commented on code on Nov 09, 2026 19:14 UTC
    Code Review
    integrations/claudecode/turn.go:1
    @@ -0,0 +1,760 @@
    +package claudecode
    +
    +import (
    +	"bufio"
    +	"bytes"
    +	"context"
    +	"encoding/json"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"os"
    +	"os/exec"
    +	"strings"
    +	"sync/atomic"
    +	"time"
    +	"unicode"
    +	"unicode/utf8"
    +
    +	"google.golang.org/protobuf/proto"
    +
    +	"github.com/agent-primitives/sessions/api"
    +	"github.com/agent-primitives/sessions/wire"
    +)
    +
    +const (
    +	// maxLineBytes bounds one stream-json line. A longer line fails the turn as malformed.
    +	maxLineBytes = 16 << 20
    +	// receiptFieldBytes bounds the tool input and the tool content a full receipt carries.
    +	receiptFieldBytes = 2 << 10
    +	// turnReceiptBudget bounds one turn's full receipts; later receipts in the turn are minimal.
    +	turnReceiptBudget = 128 << 10
    +	// outputChunkBytes bounds one Output call, well under gRPC's default 4 MiB frame limit.
    +	outputChunkBytes = 1 << 20
    +	// stderrLineBytes bounds the stderr line logged for a process that failed before system/init.
    +	stderrLineBytes = 256
    +)
    +
    +var (
    +	errMalformed       = errors.New("claudecode: malformed stream-json from claude")
    +	errNoInit          = errors.New("claudecode: claude stream has events before system/init")
    +	errSessionMismatch = errors.New("claudecode: claude reported a different session id")
    +	errNoResult        = errors.New("claudecode: claude stream ended without a result")
    +)
    +
    +// streamLine is one stream-json event. Only the fields the harness maps are decoded; unknown
    +// event types and fields are ignored.
    +type streamLine struct {
    +	Type            string          `json:"type"`
    +	Subtype         string          `json:"subtype"`
    +	SessionID       string          `json:"session_id"`
    +	Model           string          `json:"model"`
    +	ParentToolUseID string          `json:"parent_tool_use_id"`
    +	Message         json.RawMessage `json:"message"`
    +	IsError         bool            `json:"is_error"`
    +	Result          string          `json:"result"`
    +	Usage           *tokenUsage     `json:"usage"`
    +}
    +
    +// message is the Anthropic-shaped message inside assistant and user events. Content is a string or
    +// an array of blocks.
    +type message struct {
    +	ID      string          `json:"id"`
    +	Content json.RawMessage `json:"content"`
    +	Usage   *tokenUsage     `json:"usage"`
    +}
    +
    +type contentBlock struct {
    +	Type      string          `json:"type"`
    +	Text      string          `json:"text"`
    +	ID        string          `json:"id"`
    +	Name      string          `json:"name"`
    +	Input     json.RawMessage `json:"input"`
    +	ToolUseID string          `json:"tool_use_id"`
    +	Content   json.RawMessage `json:"content"`
    +	IsError   bool            `json:"is_error"`
    +}
    +
    +type tokenUsage struct {
    +	InputTokens              int64 `json:"input_tokens"`
    +	OutputTokens             int64 `json:"output_tokens"`
    +	CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
    +	CacheReadInputTokens     int64 `json:"cache_read_input_tokens"`
    +}
    +
    +func (u *tokenUsage) valid() bool {
    +	return u.InputTokens >= 0 && u.OutputTokens >= 0 && u.CacheCreationInputTokens >= 0 && u.CacheReadInputTokens >= 0
    +}
    +
    +// input is every input token the model processed: uncached, cache reads and cache writes.
    +func (u *tokenUsage) input() int64 {
    +	return u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens
    +}
    +
    +type toolUse struct {
    +	name   string
    +	input  json.RawMessage
    +	parent string
    +}
    +
    +// turn is one Run's process and stream state. Only the goroutine running run touches it.
    +type turn struct {
    +	h          *Harness
    +	sink       api.EventSink
    +	sessionUID string
    +	flag       string // --session-id or --resume
    +	sessionID  string
    +	model      string
    +	receipts   bool // full receipts; false once the session or turn budget is spent
    +
    +	receiptBytes int
    +	initSeen     bool
    +	initModel    string
    +	tools        map[string]toolUse
    +	toolOrder    []string
    +	seenMsgs     map[string]struct{}
    +	recovered    tokenUsage // main-loop assistant usage, deduplicated by message id
    +	result       *streamLine
    +	sinkErr      error
    +}
    +
    +// receiptMode reports whether full receipts are allowed this turn: History, sized as the wire sends
    +// it, is under half of StartLimit. It warns once History reaches three quarters of it.
    +func (h *Harness) receiptMode(s *api.Start) bool {
    +	n := 0
    +	for _, e := range s.History {
    +		n += proto.Size(wire.EventToProto(e))
    +	}
    +	if n >= h.cfg.StartLimit/4*3 {
    +		h.logger.Warn("claudecode: session history nears the harness receive limit; raise the limit and Config.StartLimit",
    +			"session_uid", s.SessionUID, "history_bytes", n, "start_limit", h.cfg.StartLimit)
    +	}
    +	return n < h.cfg.StartLimit/2
    +}
    +
    +type readResult struct {
    +	line []byte
    +	err  error
    +}
    +
    +// Process phases. Each later phase is entered at most once, in order.
    +const (
    +	phaseRunning     = iota
    +	phaseSettling    // result seen or stdout closed: the process gets postResultGrace to exit
    +	phaseInterrupted // SIGINT sent: the process gets InterruptGrace to exit
    +	phaseKilled      // group killed or leader exited: stdout gets drainGrace of waiting to close
    +)
    +
    +// run starts the process, maps its stream, and returns the turn's outcome.
    +func (t *turn) run(ctx context.Context, args []string, prompt string) error {
    +	t.tools = make(map[string]toolUse)
    +	t.seenMsgs = make(map[string]struct{})
    +	if err := ctx.Err(); err != nil {
    +		return interruptedErr(err) // cancelled while the inputs were validated: launch nothing
    +	}
    +
    +	r, w, err := os.Pipe()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = r.Close() }()
    +	// stderr can carry prompt or tool text. Only its first line is kept, and logged only for a
    +	// process that failed before system/init. A pipe, not an io.Writer, so cmd.Wait does not wait
    +	// for a descendant that holds stderr.
    +	er, ew, err := os.Pipe()
    +	if err != nil {
    +		_ = w.Close()
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +	defer func() { _ = er.Close() }()
    +	cmd := exec.Command(t.h.cfg.Binary, args...)
    +	cmd.Dir = t.h.cfg.WorkDir
    +	cmd.Env = t.h.env
    +	cmd.Stdin = strings.NewReader(prompt)
    +	cmd.Stdout = w
    +	cmd.Stderr = ew
    +	cmd.SysProcAttr = sysProcAttr()
    +	cmd.WaitDelay = t.h.drainGrace
    +	err = cmd.Start()
    +	_ = w.Close() // the child holds its own copies
    +	_ = ew.Close()
    +	if err != nil {
    +		return fmt.Errorf("claudecode: start claude: %w", err)
    +	}
    +
    +	stderrLine := make(chan string, 1)
    +	go func() {
    +		br := bufio.NewReader(er)
    +		stderrLine <- firstLine(br)
    +		_, _ = io.Copy(io.Discard, br) // keep draining so the process never blocks on stderr
    +	}()
    +	lines := make(chan readResult)
    +	go readLines(r, lines)
    +	// The leader is reaped only once its group is killed for the last time (stopGroup, below):
    +	// until then the zombie reserves the id every kill of the group signals. The outcome is read
    +	// from cmd.ProcessState after the reap.
    +	var (
    +		exited       = make(chan struct{})
    +		leaderExited atomic.Bool // the observer saw the leader exit
    +		reaped       bool        // the observer had to reap it; read only after exited closed
    +	)
    +	go func() {
    +		wait := waitExit
    +		if t.h.waitExit != nil {
    +			wait = t.h.waitExit
    +		}
    +		if err := wait(cmd.Process); err != nil {
    +			if !errors.Is(err, errors.ErrUnsupported) {
    +				t.h.waitExitWarn.Do(func() {
    +					t.h.logger.Warn("claudecode: cannot wait for claude's exit without reaping it; "+
    +						"its process group id is not reserved after it exits", "err", err)
    +				})
    +			}
    +			_ = cmd.Wait()
    +			reaped = true
    +		}
    +		leaderExited.Store(true)
    +		if t.h.exitObserved != nil {
    +			t.h.exitObserved()
    +		}
    +		close(exited)
    +	}()
    +
    +	var (
    +		phase    = phaseRunning
    +		deadline <-chan time.Time
    +		done     = ctx.Done()
    +		eof      bool
    +		exitSeen bool
    +		forced   bool // the harness closed stdout itself
    +		signaled bool // SIGINT reached the process before the turn saw it exit
    +		killed   bool // SIGKILL reached the process before the turn saw it exit
    +		failErr  error
    +		drainBy  time.Time // phaseKilled: when stdout is closed
    +	)
    +	enter := func(p int, d time.Duration) {
    +		phase = p
    +		if p == phaseKilled {
    +			drainBy, deadline = time.Now().Add(d), nil // armed per wait, below
    +			return
    +		}
    +		if t.h.after != nil {
    +			deadline = t.h.after(d)
    +			return
    +		}
    +		deadline = time.After(d)
    +	}
    +	interrupt := func() {
    +		if phase >= phaseInterrupted {
    +			return
    +		}
    +		// An unreaped zombie takes the signal, so delivery counts only before the turn saw the
    +		// process exit. Delivery alone does not excuse the exit status either: outcome also needs
    +		// the status to show it died of SIGINT.
    +		running := !leaderExited.Load()
    +		signaled = interruptProcess(cmd.Process) == nil && running
    +		enter(phaseInterrupted, t.h.cfg.InterruptGrace)
    +	}
    +	// kill kills the group and reports whether SIGKILL reached the process before the turn saw it
    +	// exit, as interrupt does for SIGINT.
    +	kill := func() bool {
    +		running := !leaderExited.Load()
    +		return killGroup(cmd.Process) && running
    +	}
    +	for !eof || !exitSeen {
    +		var drain *time.Timer
    +		if phase == phaseKilled && !forced {
    +			drain = time.NewTimer(time.Until(drainBy))
    +			deadline = drain.C
    +		}
    +		select {
    +		case m, ok := <-lines:
    +			switch {
    +			case !ok:
    +				lines, eof = nil, true
    +				if phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			case m.err != nil:
    +				if !forced && failErr == nil {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			case failErr != nil || ctx.Err() != nil:
    +				// Stopping: drain.
    +			case t.result != nil:
    +				// Past the result: no further sink effects, but a malformed line still fails the
    +				// turn, as it would before the result.
    +				if !validLine(m.line) {
    +					failErr = errMalformed
    +					interrupt()
    +				}
    +			default:
    +				began := time.Now()
    +				err := t.handle(ctx, m.line)
    +				if phase == phaseKilled {
    +					// drainGrace bounds how long stdout stays open while the harness waits on
    +					// it, not how long the sink takes: a slow Report must not cut off lines the
    +					// process wrote before it exited.
    +					drainBy = drainBy.Add(time.Since(began))
    +				}
    +				if err != nil {
    +					failErr = err
    +					interrupt()
    +				} else if t.result != nil && phase == phaseRunning {
    +					enter(phaseSettling, t.h.postResultGrace)
    +				}
    +			}
    +		case <-exited:
    +			exited, exitSeen = nil, true
    +			if !eof && phase < phaseKilled {
    +				// Something the process started still holds stdout.
    +				enter(phaseKilled, t.h.drainGrace)
    +			}
    +		case <-done:
    +			done = nil
    +			interrupt()
    +		case <-deadline:
    +			switch phase {
    +			case phaseSettling:
    +				interrupt()
    +			case phaseInterrupted:
    +				killed = kill() || killed
    +				enter(phaseKilled, t.h.drainGrace)
    +			default:
    +				killed = kill() || killed
    +				forced = true
    +				_ = r.Close()
    +				deadline = nil
    +			}
    +		}
    +		if drain != nil {
    +			drain.Stop()
    +		}
    +	}
    +
    +	// The loop ends once the leader exited and stdout closed, but the group can outlive its leader:
    +	// a tool Claude Code started that redirected its stdio holds neither. Kill it on every path,
    +	// success included, so nothing the turn started runs once Run returns, or while it records.
    +	reap := func() {
    +		if t.h.beforeReap != nil {
    +			t.h.beforeReap(cmd.Process.Pid)
    +		}
    +		if !reaped {
    +			_ = cmd.Wait()
    +		}
    +	}
    +	if !stopGroup(cmd.Process, reap, t.h.drainGrace) {
    +		t.h.logger.Warn("claudecode: processes of the turn's group remain after the kill",
    +			"pid", cmd.Process.Pid, "wait", t.h.drainGrace)
    +	}
    +
    +	err = t.outcome(ctx, cmd.ProcessState.ExitCode(), stoppedByHarness(cmd.ProcessState, signaled, killed), failErr)
    +	if err != nil && !t.initSeen && ctx.Err() == nil {
    +		// Claude Code failed before it confirmed the session, so no tool ran and the model said
    +		// nothing; a failing --resume ends here on every later turn. Its reason is on stderr.
    +		var line string
    +		select {
    +		case line = <-stderrLine:
    +		case <-time.After(t.h.drainGrace): // a descendant outside the group holds stderr
    +		}
    +		t.h.logger.Warn("claudecode: claude failed before system/init",
    +			"session_uid", t.sessionUID, "flag", t.flag, "claude_session_id", t.sessionID,
    +			"exit_status", cmd.ProcessState.String(), "stderr", line)
    +	}
    +	return err
    +}
    +
    +// outcome records the turn's remaining effects and returns its result, once the process is gone.
    +// stopped reports that a signal the harness delivered ended the process, so its exit status is not
    +// its own verdict.
    +func (t *turn) outcome(ctx context.Context, code int, stopped bool, failErr error) error {
    +	if err := ctx.Err(); err != nil {
    +		return interruptedErr(err)
    +	}
    +	if t.sinkErr != nil {
    +		return t.sinkErr
    +	}
    +	if err := t.finish(ctx); err != nil {
    +		return err
    +	}
    +	if failErr != nil {
    +		return failErr
    +	}
    +	if t.result == nil {
    +		if !stopped && code != 0 {
    +			return fmt.Errorf("claudecode: claude exited with status %d before a result", code)
    +		}
    +		return errNoResult
    +	}
    +	if t.result.IsError || t.result.Subtype != "success" {
    +		return fmt.Errorf("claudecode: claude reported an error result (subtype %s)", subtype(t.result.Subtype))
    +	}
    +	if !stopped && code != 0 {
    +		return fmt.Errorf("claudecode: claude exited with status %d after a success result", code)
    +	}
    +	for _, chunk := range chunks(t.result.Result, outputChunkBytes) {
    +		if err := t.sink.Output(ctx, chunk); err != nil {
    +			return fmt.Errorf("claudecode: record output: %w", err)
    +		}
    +	}
    +	return nil
    +}
    +
    +// interruptedErr is the error of a turn whose ctx is done.
    +func interruptedErr(err error) error {
    +	return fmt.Errorf("claudecode: turn interrupted: %w", err)
    +}
    +
    +// readLines sends each stdout line, then a read error if any, then closes out. After an error it
    +// keeps draining so the process never blocks on a full pipe.
    +func readLines(r io.Reader, out chan<- readResult) {
    +	defer close(out)
    +	sc := bufio.NewScanner(r)
    +	sc.Buffer(make([]byte, 0, 64<<10), maxLineBytes)
    +	for sc.Scan() {
    +		out <- readResult{line: bytes.Clone(sc.Bytes())}
    +	}
    +	if err := sc.Err(); err != nil {
    +		out <- readResult{err: err}
    +		_, _ = io.Copy(io.Discard, r)
    +	}
    +}
    +
    +// firstLine returns the first non-blank line of r, cut to stderrLineBytes, with invalid UTF-8,
    +// control and format characters (bidi overrides included) replaced. Leading space is skipped
    +// across ReadLine's chunks, so a long line that starts with spaces is still that line. It reads
    +// to the end of that line and no further; "" at EOF.
    +func firstLine(r *bufio.Reader) string {
    +	var b []byte
    +	for {
    +		chunk, more, err := r.ReadLine()
    +		if len(b) == 0 {
    +			chunk = bytes.TrimLeftFunc(chunk, unicode.IsSpace)
    +		}
    +		b = append(b, chunk[:min(len(chunk), stderrLineBytes-len(b))]...)
    +		if more && err == nil {
    +			continue
    +		}
    +		if len(b) > 0 {
    +			break
    +		}
    +		if err != nil {
    +			return ""
    +		}
    +	}
    +	s := strings.Map(func(c rune) rune {
    +		if unicode.IsControl(c) || unicode.Is(unicode.Cf, c) {
    +			return '?'
    +		}
    +		return c
    +	}, strings.ToValidUTF8(string(bytes.TrimRightFunc(b, unicode.IsSpace)), "\uFFFD"))
    +	s, _ = truncate(s, stderrLineBytes)
    +	return s
    +}
    +
    +// validLine reports whether line is blank or a stream-json event, by the same decoding handle
    +// applies.
    +func validLine(line []byte) bool {
    +	if len(bytes.TrimSpace(line)) == 0 {
    +		return true
    +	}
    +	var ev streamLine
    +	return json.Unmarshal(line, &ev) == nil
    +}
    +
    +// handle maps one stream-json line.
    +func (t *turn) handle(ctx context.Context, line []byte) error {
    +	if len(bytes.TrimSpace(line)) == 0 {
    +		return nil
    +	}
    +	var ev streamLine
    +	if err := json.Unmarshal(line, &ev); err != nil {
    +		return errMalformed
    +	}
    +	switch ev.Type {
    +	case "system":
    +		if ev.Subtype != "init" {
    +			return nil
    +		}
    +		if ev.SessionID != t.sessionID {
    +			return errSessionMismatch
    +		}
    +		t.initSeen, t.initModel = true, ev.Model
    +		return nil
    +	case "stream_event":
    +		// Partial message deltas: there is no sink method for an ephemeral delta, so they are
    +		// dropped. The turn's text is recorded once from the result.
    +		return nil
    +	case "assistant", "user", "result":
    +	default:
    +		return nil
    +	}
    +	if !t.initSeen {
    +		return errNoInit
    +	}
    +	if ev.SessionID != "" && ev.SessionID != t.sessionID {
    +		return errSessionMismatch
    +	}
    +	switch ev.Type {
    +	case "assistant":
    +		return t.assistant(&ev)
    +	case "user":
    +		return t.user(ctx, &ev)
    +	default:
    +		if ev.Usage != nil && !ev.Usage.valid() {
    +			return errMalformed
    +		}
    +		t.result = &ev
    +		return nil
    +	}
    +}
    +
    +// assistant holds tool_use blocks until their result and records main-loop usage once per message
    +// id, the fallback when no result reports usage.
    +func (t *turn) assistant(ev *streamLine) error {
    +	var msg message
    +	if err := json.Unmarshal(ev.Message, &msg); err != nil {
    +		return errMalformed
    +	}
    +	blocks, err := contentBlocks(msg.Content)
    +	if err != nil {
    +		return err
    +	}
    +	for _, b := range blocks {
    +		if b.Type != "tool_use" {
    +			continue
    +		}
    +		if b.ID == "" {
    +			return errMalformed
    +		}
    +		if _, ok := t.tools[b.ID]; !ok {
    +			t.toolOrder = append(t.toolOrder, b.ID)
    +		}
    +		t.tools[b.ID] = toolUse{name: b.Name, input: b.Input, parent: ev.ParentToolUseID}
    +	}
    +	if msg.Usage != nil {
    +		if !msg.Usage.valid() {
    +			return errMalformed
    +		}
    +		if ev.ParentToolUseID == "" && msg.ID != "" {
    +			if _, ok := t.seenMsgs[msg.ID]; !ok {
    +				t.seenMsgs[msg.ID] = struct{}{}
    +				t.recovered.InputTokens += msg.Usage.InputTokens
    +				t.recovered.CacheReadInputTokens += msg.Usage.CacheReadInputTokens
    +				t.recovered.CacheCreationInputTokens += msg.Usage.CacheCreationInputTokens
    +			}
    +		}
    +	}
    +	return nil
    +}
    +
    +// user reports each tool_result block.
    +func (t *turn) user(ctx context.Context, ev *streamLine) error {
    +	var msg message
    +	if err := json.Unmarshal(ev.Message, &msg); err != nil {
    +		return errMalformed
    +	}
    +	blocks, err := contentBlocks(msg.Content)
    +	if err != nil {
    +		return err
    +	}
    +	for _, b := range blocks {
    +		if b.Type != "tool_result" {
    +			continue
    +		}
    +		if b.ToolUseID == "" {
    +			return errMalformed
    +		}
    +		use, ok := t.tools[b.ToolUseID]
    +		if ok {
    +			delete(t.tools, b.ToolUseID)
    +		} else {
    +			use = toolUse{parent: ev.ParentToolUseID} // orphan: reported with no tool name
    +		}
    +		text, n, err := toolContent(b.Content)
    +		if err != nil {
    +			return err
    +		}

    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.

    gambtho gambtho approved these changes on Nov 09, 2026 19:14 UTC
    Approved Reviewer

    Approved these changes.

    Reviewers
    Assignees
    aramase aramase
    Labels
    risk: low confidence: 90.4% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 76.5% (HIGH) · Higher = larger blast radius
    76.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 90.4% · Lower = rushed or shallow review
    90.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.4% · Safe to merge
    7.4%