From 694582438eaa9b692612a7f64881dede949175bb Mon Sep 17 00:00:00 2001 From: David Abram Date: Mon, 23 Nov 2026 14:45:48 +0100 Subject: [PATCH 1/6] context: Add Claude subagent attribution plan Define the staged plan for resolving Claude subagent models from local transcripts, seeding exact-scope state, and enriching patch attribution while preserving no-inheritance behavior. Plan: claude-subagent-attribution (T01-T04) Co-authored-by: SCE --- context/plans/claude-subagent-attribution.md | 175 +++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 context/plans/claude-subagent-attribution.md diff --git a/context/plans/claude-subagent-attribution.md b/context/plans/claude-subagent-attribution.md new file mode 100644 index 000000000..5fed2e44e --- /dev/null +++ b/context/plans/claude-subagent-attribution.md @@ -0,0 +1,175 @@ +# Plan: claude-subagent-attribution + +## Change summary + +A live run of five concurrent Claude `general-purpose` subagents (parent session +`e51f92c1-4aad-4319-8b98-cae1f5d74c26`, 2026-11-23) showed that SCE captures +subagent file mutations but loses most of the subagent identity on the way to +the control plane: + +- All ten subagent mutation scopes stored `mutation_trace_scope_provenance.model_id = NULL`. Main-agent scopes in the same session stored `claude/claude-opus-5-5`. +- `claude_model_state` held only the main-agent row (`agent_id = ""`). Claude sends no `SessionStart` for a subagent, and the accepted decision `2026-09-01-claude-model-attribution-state` forbids inheritance from the main agent. A subagent therefore always resolves to `NULL`. +- Each subagent `Write` produced an assistant `patch` part under the main session. Its patch JSON carried `model_id: null` on every hunk and `session_id: null` on every line, and no agent or tool identity. The ClickHouse warehouse could attribute a patch to a subagent only by timing. + +Claude already writes the needed facts locally. Each subagent has its own +transcript at `//subagents/agent-.jsonl`. +Its assistant records carry `message.model`, `agentId`, and `isSidechain: true`, +and each record that issues a tool call names that call's `tool_use_id`. A +sibling `agent-.meta.json` carries `agentType` and `toolUseId`, which +is the `tool_use_id` of the parent `Agent` call that spawned the subagent. + +This plan extends existing behavior. It moves the Claude model attribution +chain into one Claude-specific resolver. Structured diff traces, mutation-scope +provenance, and conversation-trace patch parts all call that resolver. For a +subagent event, the resolver uses only exact evidence: the direct event model, +then the exact `tool_use_id` record in the subagent transcript, then `NULL`. It +never uses a transcript record that is not proven to belong to the event, it +never reads the main-agent state row, and it seeds no `claude_model_state` row. +Main-agent resolution keeps its existing precedence unchanged. + +Transcript lookup becomes bounded. The reader scans only a fixed tail window of +the transcript, skips oversized records, and returns `NULL` when the exact +record is not inside those bounds. Each hook invocation scans a given +transcript for a given `tool_use_id` at most once. + +Mutation-scope provenance gains one narrow write-once transition. When a +Claude scope was admitted with `model_id = NULL`, the `PostToolUse` or +`PostToolUseFailure` completion boundary may set `model_id` once, from exact +evidence only. A non-`NULL` model is never overwritten, and every other +provenance field stays insert-once. + +Patch parts fill the existing hunk `model_id` and line `session_id` fields and +add one optional `attribution` object. The plan supersedes one guardrail of +`2026-09-01-claude-model-attribution-state`: Claude `agent_id` may now leave +the machine inside synchronized patch parts. It also replaces the "a stored +`NULL` is never backfilled" rule of `context/cli/mutation-scope-provenance.md` +for Claude scopes with the exact-evidence completion fill. + +Missing attribution is preferred to incorrect attribution. + +## Acceptance criteria + +How this plan is proven complete. Each criterion is observable and names the +check that proves it. `/validate` runs these checks; no task in the stack +performs final validation. + +- [ ] AC1: An accepted decision record states the subagent precedence (direct event model, exact `tool_use_id` record in the subagent transcript, `NULL`), the preserved no-inheritance rule, the rule that transcript-derived models are never written to `claude_model_state`, the single-resolver rule, the transcript bounds and their rationale, the write-once completion fill of `mutation_trace_scope_provenance.model_id` from exact evidence, and the synchronized patch-part `attribution` fields. It names the superseded `agent_id` export guardrail of `2026-09-01-claude-model-attribution-state` and the replaced no-backfill rule for Claude provenance. + - Validate: inspect `context/decisions/` for the new record and its `Supersedes` lines; `git diff --stat -- context/decisions/2026-09-01-claude-model-attribution-state.md` is empty. +- [ ] AC2: A subagent event (`agent_id` present) resolves its model from the direct event model when present. Otherwise it resolves from the assistant record in the subagent transcript whose content names the event's `tool_use_id`. When no such record exists inside the transcript bounds, the result is `NULL`, even when other assistant records in that transcript name a model. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_subagent_model`. +- [ ] AC3: When a subagent switches models during its run, each event resolves to the model on its own tool-call record. With a fixture where tool call A is on model X and a later tool call B is on model Y, A resolves to X and B resolves to Y. A tool call C with no record yet resolves to `NULL`, not Y. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_subagent_model`. +- [ ] AC4: A subagent event never resolves through the main-agent `(cc_, "")` state row or the bridge-session chain, and subagent resolution writes no `claude_model_state` row. With a fixture that has a main-agent state row and no subagent transcript record, the subagent result is `NULL` and the state table is unchanged. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_subagent_model`. +- [ ] AC5: One Claude resolver module owns the attribution chain. Structured diff traces, mutation-scope provenance admission, the mutation-scope completion fill, and conversation-trace patch parts call it. No consumer calls the transcript reader or the model-state lookup directly. + - Validate: `rg -n "claude_transcript::|claude_model_state_by_session_and_agent|seed_diff_trace_model_from_bridge_chain" cli/src/services --glob '!**/tests/**'` lists call sites only inside the resolver module and the definitions. +- [ ] AC6: Main-agent events keep the existing precedence: direct event model, exact `tool_use_id` record in the main transcript, exact `(cc_, "")` state row, bridge-session chain, then `NULL`. The existing main-agent attribution and model-state tests pass without change. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_model_attribution`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_model_state`. +- [ ] AC7: The transcript reader scans at most the last 4 MiB of a transcript, starting at the first complete record inside that window. It skips any record longer than 1 MiB and any record that is not valid UTF-8 JSON, and it continues with the next record. It returns the model of the exact `tool_use_id` record, or no model when that record is outside the window, is oversized, is malformed, or is absent. An open or read failure is reported as a typed reader error, and the resolver maps every reader error to `NULL`. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_transcript_bounds`. +- [ ] AC8: A lookup of a missing `tool_use_id` in a synthetic 32 MiB transcript reads no more than 5 MiB (the 4 MiB window plus one 1 MiB record) and returns no model. The test also asserts a loose wall-clock bound of 500 ms; the byte bound is the authoritative check. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_transcript_bounds`. +- [ ] AC9: Within one hook invocation, each `(transcript path, tool_use_id)` pair is scanned at most once. The resolver result for an event is computed once and passed to every use in that invocation. No persistent cache, index, table, or cross-process coordination exists. + - Validate: inspect the diff-trace, conversation-trace, and mutation-scope invocation paths for one resolver call per event; `git diff --stat origin/main -- cli/migrations` is empty. +- [ ] AC10: Claude mutation-scope provenance attribution is correct at both boundaries: + - (a) When the exact record exists at admission, the scope stores that model at admission, and completion leaves it unchanged. + - (b) When the exact record is missing at admission but present at `PostToolUse` or `PostToolUseFailure`, completion changes `model_id` from `NULL` to that model. + - (c) When the exact record is missing at both boundaries, `model_id` stays `NULL`. + - (d) A stored non-`NULL` `model_id` is never overwritten, including when completion resolves a different model. + - (e) A duplicate completion event leaves the row unchanged and succeeds. + - The completion fill uses only the direct event model and the exact `tool_use_id` record, never `claude_model_state` or the bridge-session chain. It changes no field other than `model_id`. A fill failure never fails the hook or the close. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_provenance_fill`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_mutation_scope`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml scope_provenance`. +- [ ] AC11: A Claude `PostToolUse` `Write` or `Edit` patch part sets every touched line's `session_id` to `cc_` and every hunk's `model_id` to the resolver result or `null`. It carries one `attribution` object with `agent_id`, `agent_type`, `tool_use_id`, and `parent_tool_use_id`. A subagent patch has the event's `agent_id`; `agent_type` comes from the event, or from `agentType` in the meta file when the event has none; `parent_tool_use_id` comes from `toolUseId` in the meta file. A main-agent patch has `agent_id`, `agent_type`, and `parent_tool_use_id` set to `null`. No line or hunk carries agent fields. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml conversation_trace`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml patch`. +- [ ] AC12: A missing, unreadable, or malformed subagent transcript or meta file yields `NULL` for each affected field. The hook still exits successfully, writes nothing to stdout, persists the patch part or scope, and never denies the tool. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_subagent_model`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml conversation_trace`. +- [ ] AC13: Patch JSON serialized before this change, with no `attribution` key, still loads and still feeds the Agent Trace generator. The `parts` sync stream sends the enriched patch JSON unchanged in the existing `text` field, with no new remote stream, cursor, column, migration, or `/state` field. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml patch`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml sync`; `git diff --stat origin/main -- cli/src/services/sync cli/src/services/agent_trace_export cli/migrations` is empty. +- [ ] AC14: A manual rerun of the concurrent-subagent experiment shows correct attribution in the local repository Agent Trace DB. Every non-`NULL` subagent scope `model_id` equals the model on that tool call's record in the subagent transcript. Every subagent patch part has the `agent_id` of the subagent that wrote the file and the `parent_tool_use_id` from that subagent's meta file. A `NULL` model is acceptable only when the exact record was in the transcript at neither boundary. + - Validate: manual. Rerun five concurrent `general-purpose` subagents that each `Write` one file. Query `mutation_trace_scope_provenance` and the session's `patch` parts with `turso --readonly --experimental-multiprocess-wal `, and compare each value with `/subagents/agent-.jsonl` and `.meta.json`. + +### Full validation + +Repository-wide checks `/validate` runs after the last task, regardless of +which criterion they map to. + +- `nix flake check` +- `nix run .#pkl-check-generated` + +### Context sync + +- `context/cli/mutation-scope-provenance.md`: the Claude producer obtains its model from the shared Claude resolver, and Claude scopes have one write-once `NULL`-to-model completion fill from exact evidence. The "no `UPDATE` path" and "a stored `NULL` is never backfilled" statements must name this exception. +- `context/sce/claude-raw-hook-capture.md`: the single Claude resolver, its main-agent and subagent precedence, the transcript bounds and their consequences, and the conversation-trace patch part attribution. +- `context/cli/patch-service.md`: the optional `attribution` object on `ParsedPatch`. +- `context/cli/agent-trace-sync-command.md`: the `parts` stream carries the enriched patch JSON as opaque text, control-plane compatibility was verified, and warehouse joins against Claude OpenTelemetry metrics must strip the `cc_` prefix from SCE session IDs. +- `context/glossary.md`: `subagent transcript` and `parent tool use ID`, if the glossary does not already define them. + +## Task context synchronization lifecycle + +Persist this field in every plan; this is durable plan state, not chat state: + +- **Task context synchronization:** every task carries `pending | synced | blocked`. + A completed task must be `synced` before another task can start or the plan can + finish. +- For `blocked`, record **Blocker**, **Required action**, and **Retry condition** + beside the status. Never infer `synced` from conversation history; write every + lifecycle transition to the plan file. + +## Constraints and non-goals + +- **In scope:** `cli/src/services/hooks/claude_transcript.rs`, `cli/src/services/hooks/diff_trace.rs`, `cli/src/services/hooks/claude_model_state.rs`, one resolver module under `cli/src/services/hooks/`, `cli/src/services/hooks/claude_mutation_scope/`, `cli/src/services/mutation_trace/store.rs` (one conditional provenance model fill), `cli/src/services/hooks/claude_transforms.rs`, `cli/src/services/hooks/conversation_trace.rs`, `cli/src/services/patch.rs`, their tests, one new decision record, and the context files listed under `Context sync`. +- **Out of scope:** synchronizing `mutation_trace_scopes`, `mutation_trace_scope_provenance`, or `mutation_trace_events` to the control plane; control-plane, warehouse, and ClickHouse changes; per-subagent token or cost metrics, which Claude Code OpenTelemetry owns; changing the canonical `cc_` session prefix; capturing subagent prompts, `Read` calls, or model turns as conversation messages; changing main-agent precedence or the accepted main-agent post-switch race; changes to the generic mutation-scope ingress or to the Codex, OpenCode, and Pi producers; a provenance fill for non-Claude scopes. +- **Constraints:** a subagent must never inherit the main-agent `claude_model_state` row. A model observation that is not proven to belong to the event must not attribute it. Every transcript and meta read must be local, bounded, and fail-open, and must never deny a Claude tool or write to stdout. The resolver must be a concrete Claude-specific module with a concrete evidence struct; no new trait, provider interface, injection seam, or cross-harness abstraction. The existing `ClaudeModelStateResolver` closure seam may change its argument to that evidence struct. The bounded reader is generic over `Read + Seek` for fixture tests, which is static dispatch. New code uses typed errors and does not introduce `anyhow`; the store method keeps the store's existing error type. No background job, polling, retry, or new lifecycle phase. Run Cargo only through `nix develop -c ./scripts/run-cli-cargo.sh`. Automated tests must use fixture transcripts, never real `~/.claude` data. +- **Compatibility (verified):** control-plane commit `d016aeba` was inspected on 2026-11-23. The ingestion API decodes part `text` as `Schema.String` (`apps/api/src/api.ts`). The loader stores it verbatim in `raw.parts.text String` (`apps/agent-trace-dwh-loader/migrations/001_raw_tables.sql`). The event transformer hashes and gzips it as an opaque payload bounded by `MAX_PART_PAYLOAD_BYTES` (64 MiB) (`apps/event-dwh-transformer/src/transform.ts`, `limits.ts`). The API presentation layer and the web app pass `text` through unparsed. No control-plane component decodes the patch JSON shape, so the added `attribution` key and filled `model_id` and `session_id` values are preserved. No control-plane change and no release ordering are required. Querying the new fields in ClickHouse needs JSON extraction from `raw.parts.text`; that is later warehouse work. Mutation-scope provenance stays local, so the completion fill has no control-plane effect. +- **Non-goal:** a generic cross-editor subagent model, a model-state cache for subagents, a generic provenance reconciliation framework, or a transcript index. + +## Assumptions + +- The subagent transcript path is `//subagents/agent-.jsonl`, and the meta file has the same stem with `.meta.json`. The layout was observed in Claude Code transcripts on 2026-11-23. When the event `transcript_path` already names `subagents/agent-.jsonl`, the resolver uses it directly. One function owns this derivation. +- The Claude hook contract provides no authoritative event timestamp or sequence number (decision `2026-09-01-claude-model-attribution-state`). No reliable ordering exists to prove that a non-matching transcript record precedes an event, so the "latest preceding observation" step is omitted for subagents. +- `claude_model_state` records only local observation time. A transcript-derived model written there would look like a current observation and could overwrite a newer `PostModelSwitch`. The plan therefore seeds no transcript-derived row. +- Transcript bounds rest on 634 local Claude transcripts measured on 2026-11-23. File size: median 1.1 MB, p99 4.1 MB, maximum 8.9 MB. Record length: median 1.1 KB, p99 47 KB, p99.9 131 KB, maximum 0.99 MB. The record for the event's tool call is appended last or near last before the hook runs, so a 4 MiB tail window covers it with wide margin and covers the whole file for about 99% of transcripts. A 1 MiB record cap covers every measured record. Consequence of exceeding a bound: an assistant record that carries a `Write` input larger than about 1 MiB, or an exact record more than 4 MiB from the end, resolves to `NULL`. For a main-agent event, resolution then continues to the existing state and bridge steps, as it does today when the transcript has no match. +- The existing reader aborts the whole lookup on the first unreadable line (`line.ok()?`). The bounded reader skips a malformed record instead. This can only add exact matches, never change one. +- The completion fill is placed in the Claude adapter, after `handle_close` reports a successful close and before the adapter attempt is removed. It calls one store method that runs `UPDATE mutation_trace_scope_provenance SET model_id = ? WHERE scope_id = ? AND model_id IS NULL` and returns a typed outcome (`Filled`, `AlreadySet`, `NoRow`). This keeps the generic ingress, the protocol state, and the CAS batch unchanged. The trade-off: the fill is a Claude-specific store write outside the generic ingress, and it applies to Claude scopes only. A generic `close` provenance field was rejected because it would change the ingress contract and the conformance suite for every harness. +- The fill runs only when the stored row exists and its `model_id` is `NULL`, so a scope that already has a model costs one indexed read and no transcript scan. The fill applies to main-agent and subagent Claude scopes alike, because both use exact evidence only. Main-agent admission precedence is unchanged. +- Provenance is read at commit time by `mutation_trace/runtime/mutation_attribution.rs`. A fill at `PostToolUse` precedes any commit of that mutation, so the commit-time read observes it. +- The `attribution` object uses `#[serde(default)]` and is serialized only when present, following the existing optional `model_id` and `session_id` fields in `cli/src/services/patch.rs`. +- Patch-part `session_id` uses the canonical `cc_` form, matching `messages.session_id` and `parts.session_id`. + +## Task stack + +- [ ] T01: `Record the Claude subagent attribution decision` (status:todo) + - Task ID: T01 + - Scope: In — one new decision record under `context/decisions/` covering the subagent precedence, the omitted ordering step and why, the no-seeding rule, the preserved no-inheritance rule, the single-resolver rule, the transcript bounds and their consequences, the Claude-only write-once provenance completion fill and its rejected generic alternative, and the synchronized `attribution` fields, with `Supersedes` lines for the `agent_id` export guardrail of `2026-09-01-claude-model-attribution-state` and the Claude no-backfill provenance rule. Out — code changes, and edits to the historical decision file. + - Dependencies: none + - Done when: the decision record exists with status Accepted, names this plan, and states each rule that AC2–AC12 rely on. + - Verify: inspect the new record; `git diff --stat -- context/decisions/2026-09-01-claude-model-attribution-state.md` is empty. + - Context synchronization: pending + +- [ ] T02: `Add the shared Claude model resolver with bounded exact-record transcript lookup` (status:todo) + - Task ID: T02 + - Scope: In — the bounded transcript reader in `claude_transcript.rs` (4 MiB tail window, 1 MiB record cap, skip malformed records, typed reader error, generic over `Read + Seek`); one resolver module with a concrete evidence struct (canonical session, optional `agent_id`, `tool_use_id`, `transcript_path`, direct model) and two entry points: the full chain, and an exact-evidence-only chain (direct model, then exact record) for the completion fill; the main-agent branch moved from `diff_trace.rs` without precedence change; the subagent branch; the subagent path derivation; structured diff traces switched to one resolver call per event; fixture tests named `claude_subagent_model` (AC2, AC3, AC4, transcript cases of AC12) and `claude_transcript_bounds` (AC7, AC8). Out — mutation-scope provenance (T03), patch parts (T04), and any `claude_model_state` write for subagents. + - Dependencies: T01 + - Done when: AC2, AC3, AC4, AC6, AC7, and AC8 hold, and structured diff traces obtain their model only through the resolver, with one transcript scan per event. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_subagent_model`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_transcript_bounds`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_model_attribution`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_model_state`. + - Context synchronization: pending + +- [ ] T03: `Resolve and fill Claude mutation-scope provenance models through the shared resolver` (status:todo) + - Task ID: T03 + - Scope: In — the production `ClaudeModelStateResolver` in `claude_mutation_scope/lifecycle.rs` builds the evidence struct from the admitted event and calls the T02 full chain; the closure argument changes to that struct; the `PostToolUse` and `PostToolUseFailure` identity carries `transcript_path` when present; one `MutationTraceStore` method for the conditional `NULL`-to-model fill with a typed outcome; the fill call in `handle_close` after a successful close, using the T02 exact-evidence chain, logged and fail-open; tests named `claude_provenance_fill` for AC10 (a)–(e), and a store test under `scope_provenance` for the conditional update. Out — provenance insert-once rules for `session_id`, admission-bounded creation, the generic ingress, protocol state, the CAS batch, non-Claude producers, and new seams. + - Dependencies: T02 + - Done when: AC10 holds, the lifecycle module no longer calls the model-state lookup directly, and a resolver or fill failure still admits and closes the scope. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_provenance_fill`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_mutation_scope`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml scope_provenance`. + - Context synchronization: pending + +- [ ] T04: `Fill session, model, and subagent attribution on Claude patch parts` (status:todo) + - Task ID: T04 + - Scope: In — an optional `attribution` object (`agent_id`, `agent_type`, `tool_use_id`, `parent_tool_use_id`) on `ParsedPatch`; the Claude `PostToolUse` patch builder taking the resolved model and attribution as inputs while staying free of storage access; the conversation-trace persist path calling the T02 resolver once per event and a bounded meta-file reader (1 MiB cap, typed error, fail-open); tests for main-agent, subagent, missing or malformed meta, and historical-JSON cases. Out — new `parts` columns, per-line or per-hunk agent fields, sync wire changes, and non-Claude producers. + - Dependencies: T02 + - Done when: AC5, AC9, AC11, AC12, and AC13 hold, and the Agent Trace generator tests that consume patch parts pass. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml conversation_trace`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml patch`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml sync`. + - Context synchronization: pending + +## Open questions + +- Should mutation scopes and provenance sync to the control plane? Only that data can represent contended concurrent writes, such as the `ai_contended` song-3 and song-5 changes in the experiment. Patch-part attribution identifies the writer of each patch, but not contention. This plan leaves it out because it adds a fourth remote stream and a control-plane schema. This question does not block any task. From 007000607725f5ee3580494098f93ebb20cf8ae2 Mon Sep 17 00:00:00 2001 From: David Abram Date: Mon, 23 Nov 2026 15:45:02 +0100 Subject: [PATCH 2/6] context: Record Claude subagent attribution decision Document exact local evidence rules for Claude subagent model attribution, bounded transcript lookup, write-once provenance completion, and patch-part metadata. Update the plan and context map to register the accepted decision and complete T01 while preserving unresolved cases as NULL and preventing model inheritance. Plan: `context/plans/claude-subagent-attribution.md` Task: T01 Co-authored-by: SCE --- context/context-map.md | 3 +- .../2026-11-23-claude-subagent-attribution.md | 291 ++++++++++++++++++ context/plans/claude-subagent-attribution.md | 9 +- 3 files changed, 300 insertions(+), 3 deletions(-) create mode 100644 context/decisions/2026-11-23-claude-subagent-attribution.md diff --git a/context/context-map.md b/context/context-map.md index 14fa28a40..94974c9e8 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -148,6 +148,7 @@ Supporting repo docs: Recent decision records: +- `context/decisions/2026-11-23-claude-subagent-attribution.md` (Claude subagent events resolve their model from exact local evidence only: direct event model, then the exact `tool_use_id` record in the bounded subagent transcript, then `NULL`; one Claude resolver owns the chain; no inheritance or `claude_model_state` seeding; Claude provenance gains a write-once `NULL`-to-model completion fill; patch parts carry an optional `attribution` object. Partially supersedes the `agent_id` export guardrail of `2026-09-01-claude-model-attribution-state.md` and the Claude no-backfill provenance rule. Implementation lands in later tasks of `context/plans/claude-subagent-attribution.md`) - `context/decisions/2026-11-10-setup-upgrades-config-schema-declarations.md` (`sce setup` is the only writer that upgrades an older-series config `$schema` declaration. It covers only the canonical repository and global files, changes only `$schema`, validates the candidate first, never downgrades, does no field migrations, and reports skips without failing setup. It amends the read-only global-config statement of `2026-10-22-setup-writes-access-answers-to-repository-config.md`) - `context/decisions/2026-11-10-config-schema-accepts-release-series-declarations.md` (the config schema accepts canonical `$schema` declarations within the CLI's `major.minor` series, derived from `.version`; the `$id` stays the concrete versioned URL) - `context/decisions/2026-10-22-repository-telemetry-enabled-grants-consent.md` (a `telemetry.enabled: true` in any layer, including the repository `.sce/config.json`, grants telemetry consent unless some layer opts out; removes `no_user_consent` and its warning; supersedes only the user-side-only consent rule of `2026-10-20-consent-gated-access-policy-precedence.md`) @@ -164,7 +165,7 @@ Recent decision records: - `context/decisions/2026-08-23-codex-event-scoped-apply-patch-evidence-identities.md` (uses bounded, deterministic `tool_use_id`-derived synthetic line identities for Codex apply_patch evidence; positions are evidence identities rather than source line numbers, with existing patch combination/intersection semantics unchanged) - `context/decisions/2026-08-23-codex-truthful-model-provenance.md` (preserves non-empty Codex model IDs unchanged, leaves blank/missing values nullable, and forbids inferred provider prefixes or a fabricated provider field) - `context/decisions/2026-08-23-codex-root-aware-hook-invocation.md` (requires generated Codex hook commands to resolve the Git root at invocation time, quote the helper path, preserve STDIN, and fail open when root resolution fails) -- `context/decisions/2026-09-01-claude-model-attribution-state.md` (accepts a Claude-specific local latest-model-state register as a bounded exception to the prior no-session-level-cache attribution constraint, with best-effort local observation-time ordering and no export/sync scope) +- `context/decisions/2026-09-01-claude-model-attribution-state.md` (partially superseded by `2026-11-23-claude-subagent-attribution.md` for the `agent_id` export guardrail; accepts a Claude-specific local latest-model-state register as a bounded exception to the prior no-session-level-cache attribution constraint, with best-effort local observation-time ordering and no export/sync scope) - `context/decisions/2026-09-01-claude-post-model-switch-compatibility.md` (accepts unconditional installation of the Claude `PostModelSwitch` registration after Claude Code 2.1.250/2.1.251 compatibility smoke showed unknown-event tolerance and settings preservation) - `context/decisions/2026-08-26-setup-storage-fail-closed-on-invalid-config.md` (keeps general startup degradation for invalid discovered config while making setup and Agent Trace storage fail closed before side effects or fallback identity selection) - `context/decisions/2026-09-04-setup-storage-degrade-invalid-discovered-config.md` (supersedes the prior fail-closed boundary: setup and Agent Trace storage now consume shared degradation for invalid default-discovered config while explicit selections remain fatal) diff --git a/context/decisions/2026-11-23-claude-subagent-attribution.md b/context/decisions/2026-11-23-claude-subagent-attribution.md new file mode 100644 index 000000000..4e888c5b7 --- /dev/null +++ b/context/decisions/2026-11-23-claude-subagent-attribution.md @@ -0,0 +1,291 @@ +# Decision: Attribute Claude subagent events from exact local evidence only + +Date: 2026-11-23 +Status: Accepted +Plan: `context/plans/claude-subagent-attribution.md` +Task: T01 +Supersedes: The guardrail "Do not add `agent_id` to `diff_traces`, Agent Trace payloads, or related external interfaces" in `2026-09-01-claude-model-attribution-state`, only for the conversation-trace patch-part `attribution` object defined below (the historical decision file remains unchanged) +Supersedes: The rule in `context/cli/mutation-scope-provenance.md` that a stored provenance `model_id` of `NULL` is never backfilled and that no `UPDATE` path exists, only for Claude scopes and only for the write-once completion fill defined below + +## Context + +A live run of five concurrent Claude `general-purpose` subagents (parent +session `e51f92c1-4aad-4319-8b98-cae1f5d74c26`, 2026-11-23) showed that SCE +captures subagent file mutations but loses the subagent identity: + +- Every subagent mutation scope stored `mutation_trace_scope_provenance.model_id = NULL`. + Main-agent scopes in the same session stored a model. +- `claude_model_state` held only the main-agent row (`agent_id = ""`). Claude + sends no `SessionStart` for a subagent, and + `2026-09-01-claude-model-attribution-state` forbids inheritance from the main + agent. A subagent therefore always resolved to `NULL`. +- Each subagent `Write` produced a `patch` part under the main session whose + hunks carried `model_id: null`, whose lines carried `session_id: null`, and + which named no agent or tool. The warehouse could attribute it only by timing. + +Claude already writes the needed facts locally. Each subagent has its own +transcript at `//subagents/agent-.jsonl`. +Its assistant records carry `message.model`, `agentId`, and +`isSidechain: true`, and each record that issues a tool call names that call's +`tool_use_id`. A sibling `agent-.meta.json` carries `agentType` and +`toolUseId`, which is the `tool_use_id` of the parent `Agent` call that spawned +the subagent. + +The Claude hook contract provides no authoritative event timestamp or sequence +number. SCE cannot prove that a transcript record that does not name the +event's `tool_use_id` precedes that event. + +Attribution logic is currently duplicated across structured diff traces, +mutation-scope provenance admission, and conversation-trace patch parts. + +## Decision + +### One Claude resolver + +One concrete Claude-specific resolver module under `cli/src/services/hooks/` +owns the Claude model attribution chain. It accepts one concrete evidence +struct: canonical session ID, optional `agent_id`, `tool_use_id`, +`transcript_path`, and direct event model. It exposes two entry points: + +- the **full chain**, used by structured diff traces, mutation-scope + provenance admission, and conversation-trace patch parts; +- the **exact-evidence chain** (direct event model, then exact `tool_use_id` + record), used by the mutation-scope completion fill. + +No consumer calls the transcript reader, the `claude_model_state` lookup, or the +bridge-session chain directly. The resolver adds no trait, provider interface, +injection seam, or cross-harness abstraction. The existing +`ClaudeModelStateResolver` closure seam may take the evidence struct as its +argument. + +Within one hook invocation, the resolver result for an event is computed once +and passed to every use, so each `(transcript path, tool_use_id)` pair is +scanned at most once. No persistent cache, index, table, or cross-process +coordination is added. + +### Main-agent precedence (unchanged) + +An event without `agent_id` resolves in this order: + +1. direct Claude event model; +2. the exact `tool_use_id` record in the main transcript; +3. the exact `(cc_, "")` `claude_model_state` row; +4. the bridge-session chain; +5. `NULL`. + +### Subagent precedence + +An event with `agent_id` resolves in this order: + +1. direct Claude event model; +2. the assistant record in the subagent transcript whose content names the + event's `tool_use_id`; +3. `NULL`. + +A subagent event never resolves through the main-agent state row or the +bridge-session chain. It never uses a transcript record that does not name the +event's `tool_use_id`, even when other records in that transcript name a model. +When a subagent switches models, each event resolves to the model on its own +tool-call record, and an event whose record is not yet written resolves to +`NULL`, not to the latest observed model. + +The "latest preceding observation" step is omitted for subagents. Without an +authoritative event order, a non-matching record cannot be proven to precede +the event, so using it could attribute the event to the wrong model. + +### No inheritance and no seeding + +The no-inheritance rule of `2026-09-01-claude-model-attribution-state` is +preserved: a subagent never inherits the main-agent `claude_model_state` row. +Subagent resolution writes no `claude_model_state` row, and no +transcript-derived model is written to `claude_model_state` for any agent. +`claude_model_state` records only local observation time, so a +transcript-derived row would look like a current observation and could +overwrite a newer `PostModelSwitch`. + +### Subagent file paths + +The subagent transcript path is +`//subagents/agent-.jsonl`, +and the meta file has the same stem with `.meta.json`. When the event +`transcript_path` already names `subagents/agent-.jsonl`, the +resolver uses it directly. One function owns this derivation. + +### Transcript bounds + +The transcript reader: + +- scans at most the last 4 MiB of a transcript, starting at the first complete + record inside that window; +- skips any record longer than 1 MiB and any record that is not valid UTF-8 + JSON, and continues with the next record; +- returns the model of the exact `tool_use_id` record, or no model when that + record is outside the window, oversized, malformed, or absent; +- reports an open or read failure as a typed reader error, which the resolver + maps to `NULL`; +- is generic over `Read + Seek` so fixture tests use static dispatch. + +A lookup of a missing `tool_use_id` reads no more than the window plus one +capped record (5 MiB). + +The meta-file reader is bounded to 1 MiB, uses a typed error, and fails open: +a missing, unreadable, or malformed meta file yields `NULL` for each field it +would supply. + +### Write-once completion fill for Claude provenance + +When a Claude mutation scope was admitted with +`mutation_trace_scope_provenance.model_id = NULL`, the Claude adapter may set +`model_id` once at the `PostToolUse` or `PostToolUseFailure` completion +boundary: + +- The fill runs after `handle_close` reports a successful close and before the + adapter attempt is removed. +- It uses only the exact-evidence chain, never `claude_model_state` or the + bridge-session chain. +- It calls one store method that runs + `UPDATE mutation_trace_scope_provenance SET model_id = ? WHERE scope_id = ? AND model_id IS NULL` + and returns a typed outcome (`Filled`, `AlreadySet`, `NoRow`). +- A non-`NULL` `model_id` is never overwritten, including when completion + resolves a different model. A duplicate completion leaves the row unchanged + and succeeds. +- It changes no field other than `model_id`. Every other provenance field stays + insert-once. +- A resolver or fill failure is logged and never fails the hook or the close. +- When the stored row already has a model, the fill costs one indexed read and + no transcript scan. + +The fill applies to main-agent and subagent Claude scopes alike, because both +use exact evidence only. Main-agent admission precedence is unchanged. +Provenance is read at commit time, so a fill at `PostToolUse` is visible to the +commit of that mutation. The fill does not apply to non-Claude scopes. + +### Patch-part attribution + +A Claude `PostToolUse` `Write` or `Edit` patch part: + +- sets every touched line's `session_id` to `cc_`; +- sets every hunk's `model_id` to the full-chain resolver result, or `null`; +- carries one optional `attribution` object with `agent_id`, `agent_type`, + `tool_use_id`, and `parent_tool_use_id`. + +For a subagent patch, `agent_id` is the event's `agent_id`; `agent_type` comes +from the event, or from `agentType` in the meta file when the event has none; +and `parent_tool_use_id` comes from `toolUseId` in the meta file. For a +main-agent patch, `agent_id`, `agent_type`, and `parent_tool_use_id` are +`null`. No line or hunk carries agent fields. + +The `attribution` object uses `#[serde(default)]` and is serialized only when +present. Patch JSON without it still loads. The `parts` sync stream sends the +enriched patch JSON unchanged in its existing `text` field. Claude `agent_id` +may therefore leave the machine inside synchronized patch parts. No new remote +stream, cursor, column, migration, or `/state` field is added. + +## Rationale + +Missing attribution is preferred to incorrect attribution. An exact +`tool_use_id` match proves that a transcript record belongs to the event. Any +weaker signal, such as the latest record, the main-agent state, or a seeded +state row, can name the wrong model when the subagent switches models or when +the main agent and subagent run different models. + +One resolver removes duplicated precedence logic and makes AC-level guarantees +checkable at one call site per consumer. + +The transcript bounds rest on 634 local Claude transcripts measured on +2026-11-23: file size median 1.1 MB, p99 4.1 MB, maximum 8.9 MB; record length +median 1.1 KB, p99 47 KB, p99.9 131 KB, maximum 0.99 MB. The event's tool-call +record is appended last or near last before the hook runs, so a 4 MiB tail +window covers it with wide margin and covers the whole file for about 99% of +transcripts. A 1 MiB record cap covers every measured record. Skipping a +malformed record, instead of aborting the lookup as the previous reader did, +can only add exact matches, never change one. + +The completion fill exists because Claude writes the transcript asynchronously: +the exact record is often missing at admission but present by `PostToolUse`. +Restricting the fill to `NULL`-to-model and exact evidence keeps provenance +monotonic and free of guessed values. + +## Alternatives considered + +- **Seed a subagent `claude_model_state` row from the transcript** — rejected: + the row would carry local observation time and could overwrite a newer + `PostModelSwitch`, and it would turn an unproven observation into durable + state. +- **Use the latest model in the subagent transcript** — rejected: no + authoritative event order proves that record precedes the event, so a model + switch would misattribute events. +- **Inherit the main-agent model** — rejected: subagents may run a different + model, and the existing decision forbids it. +- **A generic `close` provenance field in the mutation-scope ingress** — + rejected: it would change the ingress contract and the conformance suite for + every harness to solve a Claude-specific timing gap. The chosen fill is a + Claude-specific store write outside the generic ingress. +- **Unbounded transcript scan** — rejected: transcripts reach several MB, and a + high-frequency hook must stay bounded. +- **A transcript index or persistent lookup cache** — rejected: it adds state, + invalidation, and coordination for a per-invocation lookup. +- **Per-line or per-hunk agent fields** — rejected: agent identity is constant + per patch, so one object avoids repetition. + +## Compatibility and risks + +- An exact record more than 4 MiB from the end of the transcript, or longer + than 1 MiB (for example a `Write` input larger than about 1 MiB), resolves to + `NULL`. For a main-agent event, resolution then continues to the state and + bridge steps. +- A subagent tool call whose record is missing at both admission and completion + keeps `model_id = NULL`. +- The transcript and meta-file layout was observed in Claude Code on + 2026-11-23 and is not a documented contract. A layout change yields `NULL`, + never a wrong attribution. +- Control-plane commit `d016aeba` was inspected on 2026-11-23. No component + decodes patch JSON; part `text` is stored and forwarded as an opaque string. + The added `attribution` key and the filled `model_id` and `session_id` values + are preserved, and no control-plane change or release ordering is required. + Querying the new fields in the warehouse needs JSON extraction from + `raw.parts.text`. +- Warehouse joins against Claude OpenTelemetry metrics must strip the `cc_` + prefix from SCE session IDs. + +## Guardrails + +- Do not let a subagent inherit the main-agent `claude_model_state` row or use + the bridge-session chain. +- Do not write any transcript-derived model to `claude_model_state`. +- Do not attribute an event from a transcript record that does not name its + `tool_use_id`. +- Do not call the transcript reader, the model-state lookup, or the + bridge-session chain outside the resolver module. +- Do not read transcripts or meta files without the stated bounds, and never + let a read failure deny a Claude tool, write to stdout, or fail the hook. +- Do not overwrite a non-`NULL` provenance `model_id`, and do not change any + other provenance field after insert. +- Do not add a provenance fill for non-Claude scopes. +- Do not export `claude_model_state`, mutation scopes, or provenance; `agent_id` + leaves the machine only inside the patch-part `attribution` object. +- Do not add a persistent transcript cache, index, background job, polling, or + retry. + +## Consequences + +Claude subagent events gain exact model attribution in structured diff traces, +mutation-scope provenance, and patch parts, while unresolved cases remain +`NULL`. Synchronized patch parts identify the writing agent and its parent +`Agent` call. Main-agent attribution is unchanged. Claude provenance gains one +narrow `NULL`-to-model transition; all other provenance stays insert-once. No +migration, sync stream, or control-plane schema changes. + +## Follow-up + +T02 implements the resolver and bounded reader, T03 the provenance admission and +completion fill, and T04 the patch-part attribution. Whether mutation scopes and +provenance should sync to the control plane remains an open question in the +plan. + +## References + +- Plan: [`claude-subagent-attribution`](../plans/claude-subagent-attribution.md) +- Partly superseded guardrail: [`2026-09-01-claude-model-attribution-state`](2026-09-01-claude-model-attribution-state.md) +- Bridge-session chain: [`2026-09-08-claude-bridge-session-model-inheritance`](2026-09-08-claude-bridge-session-model-inheritance.md) +- Provenance rules: [`mutation-scope-provenance`](../cli/mutation-scope-provenance.md) diff --git a/context/plans/claude-subagent-attribution.md b/context/plans/claude-subagent-attribution.md index 5fed2e44e..205cc903c 100644 --- a/context/plans/claude-subagent-attribution.md +++ b/context/plans/claude-subagent-attribution.md @@ -138,13 +138,18 @@ Persist this field in every plan; this is durable plan state, not chat state: ## Task stack -- [ ] T01: `Record the Claude subagent attribution decision` (status:todo) +- [x] T01: `Record the Claude subagent attribution decision` (status:done) - Task ID: T01 - Scope: In — one new decision record under `context/decisions/` covering the subagent precedence, the omitted ordering step and why, the no-seeding rule, the preserved no-inheritance rule, the single-resolver rule, the transcript bounds and their consequences, the Claude-only write-once provenance completion fill and its rejected generic alternative, and the synchronized `attribution` fields, with `Supersedes` lines for the `agent_id` export guardrail of `2026-09-01-claude-model-attribution-state` and the Claude no-backfill provenance rule. Out — code changes, and edits to the historical decision file. - Dependencies: none - Done when: the decision record exists with status Accepted, names this plan, and states each rule that AC2–AC12 rely on. - Verify: inspect the new record; `git diff --stat -- context/decisions/2026-09-01-claude-model-attribution-state.md` is empty. - - Context synchronization: pending + - Completed: 2026-11-23 + - Files changed: `context/decisions/2026-11-23-claude-subagent-attribution.md`, `context/plans/claude-subagent-attribution.md` + - Result: Added the Accepted decision `2026-11-23-claude-subagent-attribution` naming this plan. It states the single Claude resolver with full and exact-evidence entry points, unchanged main-agent precedence, subagent precedence (direct model, exact `tool_use_id` record, `NULL`) and the omitted ordering step, preserved no-inheritance and no-seeding rules, subagent path derivation, the 4 MiB window and 1 MiB record transcript bounds with typed fail-open errors, the bounded meta reader, per-invocation single scan, the Claude-only write-once `NULL`-to-model completion fill with its typed outcome and rejected generic `close` alternative, and the patch-part `session_id`, `model_id`, and `attribution` fields. Two `Supersedes` lines name the `agent_id` export guardrail of `2026-09-01-claude-model-attribution-state` and the Claude no-backfill provenance rule. + - Verify outcomes: inspected the new record against AC2–AC12, and each rule is stated; `git diff --stat -- context/decisions/2026-09-01-claude-model-attribution-state.md` printed nothing. + - Context impact: localized — one new decision record; current-state context files change in later tasks when behavior lands. + - Context synchronization: synced - [ ] T02: `Add the shared Claude model resolver with bounded exact-record transcript lookup` (status:todo) - Task ID: T02 From ad58da09260507f008fa182d8a889529888f7536 Mon Sep 17 00:00:00 2001 From: David Abram Date: Mon, 23 Nov 2026 16:01:39 +0100 Subject: [PATCH 3/6] cli: Centralize Claude model attribution in shared resolver Replace consumer-specific Claude attribution with one bounded resolver used by structured diff traces, preserving direct > transcript precedence and separating main-agent state/bridge fallback from subagent exact-transcript lookup. Add bounded transcript reading and subagent path derivation, then synchronize the hook contracts and plan documentation for the completed resolver task. Plan: `context/plans/claude-subagent-attribution.md` Task: T02 Co-authored-by: SCE --- .../services/hooks/claude_model_resolver.rs | 513 ++++++++++++++++++ cli/src/services/hooks/claude_transcript.rs | 438 +++++++++++++-- cli/src/services/hooks/diff_trace.rs | 190 ++++--- cli/src/services/hooks/mod.rs | 1 + context/architecture.md | 4 +- context/context-map.md | 3 +- context/glossary.md | 6 +- context/overview.md | 6 +- context/patterns.md | 2 +- context/plans/claude-subagent-attribution.md | 10 +- context/sce/agent-trace-db.md | 2 +- .../sce/agent-trace-hooks-command-routing.md | 6 +- context/sce/claude-model-resolver.md | 97 ++++ context/sce/claude-raw-hook-capture.md | 6 +- 14 files changed, 1136 insertions(+), 148 deletions(-) create mode 100644 cli/src/services/hooks/claude_model_resolver.rs create mode 100644 context/sce/claude-model-resolver.md diff --git a/cli/src/services/hooks/claude_model_resolver.rs b/cli/src/services/hooks/claude_model_resolver.rs new file mode 100644 index 000000000..727b06afb --- /dev/null +++ b/cli/src/services/hooks/claude_model_resolver.rs @@ -0,0 +1,513 @@ +use std::path::{Path, PathBuf}; + +use anyhow::Result; + +use crate::services::agent_trace_db::repository::RepositoryAgentTraceDb; +use crate::services::agent_trace_db::{ClaudeModelStateObservation, ObservationKind}; + +use super::claude_model_state; +use super::claude_transcript; +use super::diff_trace::normalize_claude_model_id; +use super::runtime::{current_unix_time_ms, DIFF_TRACE_CLAUDE_SESSION_ID_PREFIX}; + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub(crate) struct ClaudeModelEvidence { + pub(crate) session_id: String, + pub(crate) agent_id: Option, + pub(crate) tool_use_id: Option, + pub(crate) transcript_path: Option, + pub(crate) direct_model_id: Option, +} + +pub(crate) async fn resolve_claude_model( + db: &RepositoryAgentTraceDb, + evidence: &ClaudeModelEvidence, +) -> Result> { + if let Some(model_id) = resolve_claude_model_from_exact_evidence(evidence) { + return Ok(Some(model_id)); + } + if evidence.agent_id.is_some() { + return Ok(None); + } + + if let Some(state) = db + .claude_model_state_by_session_and_agent(&evidence.session_id, "") + .await? + { + return Ok(Some(state.model_id)); + } + + Ok(seed_main_agent_model_from_bridge_chain(db, evidence).await) +} + +pub(crate) fn resolve_claude_model_from_exact_evidence( + evidence: &ClaudeModelEvidence, +) -> Option { + if let Some(model_id) = evidence + .direct_model_id + .as_deref() + .and_then(normalize_claude_model_id) + { + return Some(model_id); + } + + let tool_use_id = evidence.tool_use_id.as_deref()?; + let transcript_path = evidence.transcript_path.as_deref()?; + let transcript_path = match evidence.agent_id.as_deref() { + Some(agent_id) => { + claude_subagent_transcript_path(transcript_path, &evidence.session_id, agent_id)? + } + None => transcript_path.to_path_buf(), + }; + + claude_transcript::find_claude_transcript_tool_use_model(&transcript_path, tool_use_id) + .ok() + .flatten() + .and_then(|model| normalize_claude_model_id(&model)) +} + +pub(crate) fn claude_subagent_transcript_path( + transcript_path: &Path, + session_id: &str, + agent_id: &str, +) -> Option { + let raw_session_id = session_id + .strip_prefix(DIFF_TRACE_CLAUDE_SESSION_ID_PREFIX) + .unwrap_or(session_id); + if !is_safe_path_component(raw_session_id) || !is_safe_path_component(agent_id) { + return None; + } + + let file_name = format!("agent-{agent_id}.jsonl"); + let names_subagent_transcript = transcript_path + .file_name() + .is_some_and(|name| name == file_name.as_str()) + && transcript_path + .parent() + .and_then(Path::file_name) + .is_some_and(|name| name == "subagents"); + if names_subagent_transcript { + return Some(transcript_path.to_path_buf()); + } + + Some( + transcript_path + .parent()? + .join(raw_session_id) + .join("subagents") + .join(file_name), + ) +} + +fn is_safe_path_component(value: &str) -> bool { + !value.is_empty() + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_') +} + +async fn seed_main_agent_model_from_bridge_chain( + db: &RepositoryAgentTraceDb, + evidence: &ClaudeModelEvidence, +) -> Option { + let transcript_path = evidence.transcript_path.as_deref()?; + let model_id = claude_model_state::newest_bridge_chain_model(db, transcript_path).await?; + + let observed_at_ms = current_unix_time_ms().ok()?; + match db + .upsert_claude_model_state(ClaudeModelStateObservation { + session_id: evidence.session_id.clone(), + agent_id: String::new(), + model_id: model_id.clone(), + observation_kind: ObservationKind::SessionStart, + source: String::from("bridge_inherited"), + observed_at_ms, + }) + .await + { + Ok(_) => Some(model_id), + Err(_) => None, + } +} + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + + use crate::services::agent_trace_db::repository::RepositoryAgentTraceDb; + use crate::services::agent_trace_db::{ClaudeModelStateObservation, ObservationKind}; + + use super::{claude_subagent_transcript_path, resolve_claude_model, ClaudeModelEvidence}; + + const SESSION: &str = "5f0c2a7e-1111-4222-8333-944445555666"; + const CANONICAL_SESSION: &str = "cc_5f0c2a7e-1111-4222-8333-944445555666"; + const AGENT: &str = "a1b2c3d4e5f6"; + + struct Fixture { + _dir: tempfile::TempDir, + project_dir: PathBuf, + db: RepositoryAgentTraceDb, + } + + impl Fixture { + async fn new() -> Self { + let dir = tempfile::tempdir().expect("temp dir"); + let project_dir = dir.path().join("project"); + std::fs::create_dir_all(&project_dir).expect("project dir"); + let db = RepositoryAgentTraceDb::new_at(dir.path().join("agent-trace.db")) + .await + .expect("db"); + Self { + _dir: dir, + project_dir, + db, + } + } + + fn main_transcript(&self) -> PathBuf { + self.project_dir.join(format!("{SESSION}.jsonl")) + } + + fn subagent_transcript(&self) -> PathBuf { + self.project_dir + .join(SESSION) + .join("subagents") + .join(format!("agent-{AGENT}.jsonl")) + } + + async fn seed_state(&self, session_id: &str, model_id: &str) { + self.db + .upsert_claude_model_state(ClaudeModelStateObservation { + session_id: session_id.to_string(), + agent_id: String::new(), + model_id: model_id.to_string(), + observation_kind: ObservationKind::SessionStart, + source: String::from("startup"), + observed_at_ms: 1_000, + }) + .await + .expect("seed state"); + } + + async fn state_rows(&self) -> Vec<(String, String, String)> { + self.db + .query_map( + "SELECT session_id, agent_id, model_id FROM claude_model_state ORDER BY session_id, agent_id", + (), + |row| { + Ok(( + row.get::(0)?, + row.get::(1)?, + row.get::(2)?, + )) + }, + ) + .await + .expect("read state rows") + } + + fn main_evidence(&self, tool_use_id: &str) -> ClaudeModelEvidence { + ClaudeModelEvidence { + session_id: CANONICAL_SESSION.to_string(), + agent_id: None, + tool_use_id: Some(tool_use_id.to_string()), + transcript_path: Some(self.main_transcript()), + direct_model_id: None, + } + } + + fn subagent_evidence(&self, tool_use_id: &str) -> ClaudeModelEvidence { + ClaudeModelEvidence { + agent_id: Some(AGENT.to_string()), + ..self.main_evidence(tool_use_id) + } + } + } + + fn write_transcript(path: &Path, records: &[String]) { + std::fs::create_dir_all(path.parent().unwrap()).expect("transcript dir"); + let mut contents = records.join("\n"); + contents.push('\n'); + std::fs::write(path, contents).expect("write transcript"); + } + + fn tool_use(tool_use_id: &str, model: &str) -> String { + serde_json::json!({ + "type": "assistant", + "isSidechain": true, + "agentId": AGENT, + "message": { + "role": "assistant", + "model": model, + "content": [{"type": "tool_use", "id": tool_use_id, "name": "Write"}] + } + }) + .to_string() + } + + fn text_only(model: &str) -> String { + serde_json::json!({ + "type": "assistant", + "message": {"role": "assistant", "model": model, "content": [{"type": "text", "text": "hi"}]} + }) + .to_string() + } + + #[tokio::test] + async fn claude_subagent_model_prefers_direct_event_model() { + let fixture = Fixture::new().await; + write_transcript( + &fixture.subagent_transcript(), + &[tool_use("toolu_a", "claude-haiku-5-5")], + ); + let evidence = ClaudeModelEvidence { + direct_model_id: Some(String::from("claude-sonnet-5-5")), + ..fixture.subagent_evidence("toolu_a") + }; + + let model = resolve_claude_model(&fixture.db, &evidence).await.unwrap(); + + assert_eq!(model.as_deref(), Some("claude/claude-sonnet-5-5")); + } + + #[tokio::test] + async fn claude_subagent_model_uses_exact_record_not_latest_record() { + let fixture = Fixture::new().await; + write_transcript( + &fixture.subagent_transcript(), + &[ + tool_use("toolu_target", "claude-haiku-5-5"), + tool_use("toolu_later", "claude-opus-5-5"), + text_only("claude-opus-5-5"), + ], + ); + + let model = resolve_claude_model(&fixture.db, &fixture.subagent_evidence("toolu_target")) + .await + .unwrap(); + + assert_eq!(model.as_deref(), Some("claude/claude-haiku-5-5")); + } + + #[tokio::test] + async fn claude_subagent_model_is_null_when_exact_record_is_absent() { + let fixture = Fixture::new().await; + write_transcript( + &fixture.subagent_transcript(), + &[ + tool_use("toolu_other", "claude-opus-5-5"), + text_only("claude-opus-5-5"), + ], + ); + + let model = resolve_claude_model(&fixture.db, &fixture.subagent_evidence("toolu_target")) + .await + .unwrap(); + + assert_eq!(model, None); + } + + #[tokio::test] + async fn claude_subagent_model_follows_each_tool_call_across_a_model_switch() { + let fixture = Fixture::new().await; + write_transcript( + &fixture.subagent_transcript(), + &[ + tool_use("toolu_a", "claude-sonnet-5-5"), + tool_use("toolu_b", "claude-opus-5-5"), + ], + ); + + let mut resolved = Vec::new(); + for tool_use_id in ["toolu_a", "toolu_b", "toolu_c"] { + resolved.push( + resolve_claude_model(&fixture.db, &fixture.subagent_evidence(tool_use_id)) + .await + .unwrap(), + ); + } + + assert_eq!( + resolved, + vec![ + Some(String::from("claude/claude-sonnet-5-5")), + Some(String::from("claude/claude-opus-5-5")), + None, + ] + ); + } + + #[tokio::test] + async fn claude_subagent_model_never_reads_or_writes_claude_model_state() { + let fixture = Fixture::new().await; + fixture + .seed_state(CANONICAL_SESSION, "claude/claude-opus-5-5") + .await; + write_transcript( + &fixture.main_transcript(), + &[tool_use("toolu_target", "claude-opus-5-5")], + ); + let before = fixture.state_rows().await; + + let model = resolve_claude_model(&fixture.db, &fixture.subagent_evidence("toolu_target")) + .await + .unwrap(); + + assert_eq!(model, None); + assert_eq!(fixture.state_rows().await, before); + } + + #[tokio::test] + async fn claude_subagent_model_never_uses_bridge_session_chain() { + let fixture = Fixture::new().await; + let bridge_member = write_bridge_chain(&fixture); + fixture + .seed_state(&bridge_member, "claude/claude-opus-5-5") + .await; + let before = fixture.state_rows().await; + + let model = resolve_claude_model(&fixture.db, &fixture.subagent_evidence("toolu_target")) + .await + .unwrap(); + + assert_eq!(model, None); + assert_eq!(fixture.state_rows().await, before); + } + + #[tokio::test] + async fn claude_subagent_model_missing_transcript_is_null() { + let fixture = Fixture::new().await; + + let model = resolve_claude_model(&fixture.db, &fixture.subagent_evidence("toolu_target")) + .await + .unwrap(); + + assert_eq!(model, None); + } + + #[test] + fn claude_subagent_model_transcript_path_derivation() { + let main = Path::new("/projects/repo/5f0c2a7e.jsonl"); + assert_eq!( + claude_subagent_transcript_path(main, "cc_5f0c2a7e", "abc123"), + Some(PathBuf::from( + "/projects/repo/5f0c2a7e/subagents/agent-abc123.jsonl" + )) + ); + + let already_subagent = Path::new("/projects/repo/5f0c2a7e/subagents/agent-abc123.jsonl"); + assert_eq!( + claude_subagent_transcript_path(already_subagent, "cc_5f0c2a7e", "abc123"), + Some(already_subagent.to_path_buf()) + ); + + let other_subagent = Path::new("/projects/repo/5f0c2a7e/subagents/agent-zzz999.jsonl"); + assert_eq!( + claude_subagent_transcript_path(other_subagent, "cc_5f0c2a7e", "abc123"), + Some(PathBuf::from( + "/projects/repo/5f0c2a7e/subagents/5f0c2a7e/subagents/agent-abc123.jsonl" + )) + ); + + assert_eq!( + claude_subagent_transcript_path(main, "cc_5f0c2a7e", "../escape"), + None + ); + assert_eq!( + claude_subagent_transcript_path(main, "cc_../x", "abc123"), + None + ); + } + + #[tokio::test] + async fn claude_model_attribution_main_agent_prefers_direct_model_over_transcript() { + let fixture = Fixture::new().await; + write_transcript( + &fixture.main_transcript(), + &[tool_use("toolu_a", "claude-haiku-5-5")], + ); + let evidence = ClaudeModelEvidence { + direct_model_id: Some(String::from("claude/claude-sonnet-5-5")), + ..fixture.main_evidence("toolu_a") + }; + + let model = resolve_claude_model(&fixture.db, &evidence).await.unwrap(); + + assert_eq!(model.as_deref(), Some("claude/claude-sonnet-5-5")); + } + + #[tokio::test] + async fn claude_model_attribution_main_agent_prefers_transcript_over_state_row() { + let fixture = Fixture::new().await; + fixture + .seed_state(CANONICAL_SESSION, "claude/claude-opus-5-5") + .await; + write_transcript( + &fixture.main_transcript(), + &[tool_use("toolu_a", "claude-haiku-5-5")], + ); + + let model = resolve_claude_model(&fixture.db, &fixture.main_evidence("toolu_a")) + .await + .unwrap(); + + assert_eq!(model.as_deref(), Some("claude/claude-haiku-5-5")); + } + + #[tokio::test] + async fn claude_model_attribution_main_agent_falls_back_to_state_row() { + let fixture = Fixture::new().await; + fixture + .seed_state(CANONICAL_SESSION, "claude/claude-opus-5-5") + .await; + write_transcript( + &fixture.main_transcript(), + &[tool_use("toolu_other", "claude-haiku-5-5")], + ); + + let model = resolve_claude_model(&fixture.db, &fixture.main_evidence("toolu_a")) + .await + .unwrap(); + + assert_eq!(model.as_deref(), Some("claude/claude-opus-5-5")); + } + + #[tokio::test] + async fn claude_model_attribution_main_agent_falls_back_to_bridge_chain_and_seeds_state() { + let fixture = Fixture::new().await; + let bridge_member = write_bridge_chain(&fixture); + fixture + .seed_state(&bridge_member, "claude/claude-opus-5-5") + .await; + + let model = resolve_claude_model(&fixture.db, &fixture.main_evidence("toolu_a")) + .await + .unwrap(); + + assert_eq!(model.as_deref(), Some("claude/claude-opus-5-5")); + let seeded = fixture + .db + .claude_model_state_by_session_and_agent(CANONICAL_SESSION, "") + .await + .unwrap() + .expect("bridge model seeded for the main agent"); + assert_eq!(seeded.model_id, "claude/claude-opus-5-5"); + assert_eq!(seeded.source, "bridge_inherited"); + } + + fn write_bridge_chain(fixture: &Fixture) -> String { + let bridge_record = + serde_json::json!({"type": "bridge-session", "bridgeSessionId": "bridge-1"}) + .to_string(); + write_transcript( + &fixture.main_transcript(), + std::slice::from_ref(&bridge_record), + ); + let member_session = "0a0a0a0a-2222-4333-8444-955556666777"; + write_transcript( + &fixture.project_dir.join(format!("{member_session}.jsonl")), + &[bridge_record], + ); + format!("cc_{member_session}") + } +} diff --git a/cli/src/services/hooks/claude_transcript.rs b/cli/src/services/hooks/claude_transcript.rs index f2dfdc42b..d6c558c22 100644 --- a/cli/src/services/hooks/claude_transcript.rs +++ b/cli/src/services/hooks/claude_transcript.rs @@ -1,83 +1,407 @@ +use std::fmt; use std::fs::File; -use std::io::{self, BufRead, BufReader}; -use std::path::Path; +use std::io::{self, BufRead, BufReader, Read, Seek, SeekFrom}; +use std::path::{Path, PathBuf}; use serde_json::Value; -pub fn extract_claude_transcript_model( +pub const CLAUDE_TRANSCRIPT_TAIL_WINDOW_BYTES: u64 = 4 * 1024 * 1024; +pub const CLAUDE_TRANSCRIPT_MAX_RECORD_BYTES: usize = 1024 * 1024; + +#[derive(Debug)] +pub enum ClaudeTranscriptReadError { + Open { path: PathBuf, source: io::Error }, + Seek(io::Error), + Read(io::Error), +} + +impl fmt::Display for ClaudeTranscriptReadError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Open { path, source } => write!( + f, + "failed to open Claude transcript '{}': {source}", + path.display() + ), + Self::Seek(source) => write!(f, "failed to seek Claude transcript: {source}"), + Self::Read(source) => write!(f, "failed to read Claude transcript: {source}"), + } + } +} + +impl std::error::Error for ClaudeTranscriptReadError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Open { source, .. } | Self::Seek(source) | Self::Read(source) => Some(source), + } + } +} + +pub fn find_claude_transcript_tool_use_model( transcript_path: &Path, tool_use_id: &str, -) -> Option { - extract_claude_transcript_model_from_reader( - File::open(transcript_path).map(BufReader::new), - tool_use_id, - ) +) -> Result, ClaudeTranscriptReadError> { + let file = File::open(transcript_path).map_err(|source| ClaudeTranscriptReadError::Open { + path: transcript_path.to_path_buf(), + source, + })?; + find_tool_use_model_in(file, tool_use_id) } -fn extract_claude_transcript_model_from_reader( - reader: io::Result, +pub(crate) fn find_tool_use_model_in( + mut source: R, tool_use_id: &str, -) -> Option { - let reader = reader.ok()?; +) -> Result, ClaudeTranscriptReadError> { + let length = source + .seek(SeekFrom::End(0)) + .map_err(ClaudeTranscriptReadError::Seek)?; + let window_start = length.saturating_sub(CLAUDE_TRANSCRIPT_TAIL_WINDOW_BYTES); + let read_start = window_start.saturating_sub(1); + source + .seek(SeekFrom::Start(read_start)) + .map_err(ClaudeTranscriptReadError::Seek)?; + let mut reader = BufReader::new(source.take(length - read_start)); + + let mut record = Vec::new(); + if window_start > 0 { + read_capped_record(&mut reader, &mut record).map_err(ClaudeTranscriptReadError::Read)?; + } - for line in reader.lines() { - let line = line.ok()?; - if line.trim().is_empty() { + while let Some(outcome) = + read_capped_record(&mut reader, &mut record).map_err(ClaudeTranscriptReadError::Read)? + { + if outcome == RecordRead::Oversized { continue; } - - let Ok(parsed) = serde_json::from_str::(&line) else { + let Ok(parsed) = serde_json::from_slice::(&record) else { continue; }; - let Some(record) = parsed.as_object() else { - continue; + if let Some(message) = matching_assistant_message(&parsed, tool_use_id) { + return Ok(message + .get("model") + .and_then(Value::as_str) + .map(str::trim) + .filter(|model| !model.is_empty()) + .map(str::to_string)); + } + } + + Ok(None) +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RecordRead { + Complete, + Oversized, +} + +fn read_capped_record( + reader: &mut R, + record: &mut Vec, +) -> io::Result> { + record.clear(); + let mut oversized = false; + let mut consumed_any = false; + + loop { + let available = match reader.fill_buf() { + Ok(available) => available, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(error), }; + if available.is_empty() { + break; + } + consumed_any = true; - let message = if let Some(message) = record.get("message").and_then(Value::as_object) { - let is_assistant = record + let newline = available.iter().position(|byte| *byte == b'\n'); + let chunk = &available[..newline.unwrap_or(available.len())]; + if !oversized { + if record.len() + chunk.len() > CLAUDE_TRANSCRIPT_MAX_RECORD_BYTES { + oversized = true; + record.clear(); + } else { + record.extend_from_slice(chunk); + } + } + + let consumed = newline.map_or(available.len(), |index| index + 1); + reader.consume(consumed); + if newline.is_some() { + break; + } + } + + if !consumed_any { + return Ok(None); + } + Ok(Some(if oversized { + RecordRead::Oversized + } else { + RecordRead::Complete + })) +} + +fn matching_assistant_message<'a>( + record: &'a Value, + tool_use_id: &str, +) -> Option<&'a serde_json::Map> { + let record = record.as_object()?; + + let message = if let Some(message) = record.get("message").and_then(Value::as_object) { + let is_assistant = record + .get("type") + .and_then(Value::as_str) + .is_some_and(|value| value == "assistant") + || message + .get("role") + .and_then(Value::as_str) + .is_some_and(|value| value == "assistant"); + if !is_assistant { + return None; + } + message + } else { + if record.get("role").and_then(Value::as_str) != Some("assistant") { + return None; + } + record + }; + + let content = message.get("content").and_then(Value::as_array)?; + let has_matching_tool_use = content.iter().any(|block| { + block.as_object().is_some_and(|block| { + block .get("type") .and_then(Value::as_str) - .is_some_and(|value| value == "assistant") - || message - .get("role") + .is_some_and(|value| value == "tool_use") + && block + .get("id") .and_then(Value::as_str) - .is_some_and(|value| value == "assistant"); - if !is_assistant { - continue; + .is_some_and(|value| value == tool_use_id) + }) + }); + has_matching_tool_use.then_some(message) +} + +#[cfg(test)] +mod tests { + use std::io::{self, Cursor, Read, Seek, SeekFrom}; + use std::time::{Duration, Instant}; + + use super::{ + find_claude_transcript_tool_use_model, find_tool_use_model_in, ClaudeTranscriptReadError, + CLAUDE_TRANSCRIPT_MAX_RECORD_BYTES, CLAUDE_TRANSCRIPT_TAIL_WINDOW_BYTES, + }; + + const MIB: usize = 1024 * 1024; + + fn tool_use_record(tool_use_id: &str, model: &str) -> String { + serde_json::json!({ + "type": "assistant", + "message": { + "role": "assistant", + "model": model, + "content": [{"type": "tool_use", "id": tool_use_id, "name": "Write"}] } - message - } else { - if record.get("role").and_then(Value::as_str) != Some("assistant") { - continue; + }) + .to_string() + } + + fn tool_use_record_of_length(tool_use_id: &str, model: &str, length: usize) -> String { + let empty = serde_json::json!({ + "type": "assistant", + "pad": "", + "message": { + "role": "assistant", + "model": model, + "content": [{"type": "tool_use", "id": tool_use_id, "name": "Write"}] } - record - }; + }) + .to_string(); + let record = empty.replacen( + "\"pad\":\"\"", + &format!("\"pad\":\"{}\"", "x".repeat(length - empty.len())), + 1, + ); + assert_eq!(record.len(), length); + record + } - let Some(content) = message.get("content").and_then(Value::as_array) else { - continue; - }; - let has_matching_tool_use = content.iter().any(|block| { - block.as_object().is_some_and(|block| { - block - .get("type") - .and_then(Value::as_str) - .is_some_and(|value| value == "tool_use") - && block - .get("id") - .and_then(Value::as_str) - .is_some_and(|value| value == tool_use_id) - }) - }); - - if has_matching_tool_use { - return message - .get("model") - .and_then(Value::as_str) - .map(str::trim) - .filter(|model| !model.is_empty()) - .map(str::to_string); + fn filler(length: usize) -> String { + let mut out = String::new(); + while out.len() < length { + let remaining = length - out.len(); + let record = if remaining > 1100 { + format!("{{\"type\":\"user\",\"pad\":\"{}\"}}\n", "y".repeat(1000)) + } else { + let overhead = "{\"type\":\"user\",\"pad\":\"\"}\n".len(); + if remaining > overhead { + format!( + "{{\"type\":\"user\",\"pad\":\"{}\"}}\n", + "y".repeat(remaining - overhead) + ) + } else { + format!("{}\n", " ".repeat(remaining - 1)) + } + }; + out.push_str(&record); } + assert_eq!(out.len(), length); + out + } + + fn lookup(bytes: Vec, tool_use_id: &str) -> Option { + find_tool_use_model_in(Cursor::new(bytes), tool_use_id).expect("in-memory read succeeds") + } + + struct CountingReader { + inner: R, + bytes_read: u64, } - None + impl Read for CountingReader { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + let read = self.inner.read(buf)?; + self.bytes_read += read as u64; + Ok(read) + } + } + + impl Seek for CountingReader { + fn seek(&mut self, pos: SeekFrom) -> io::Result { + self.inner.seek(pos) + } + } + + struct FailingReader; + + impl Read for FailingReader { + fn read(&mut self, _buf: &mut [u8]) -> io::Result { + Err(io::Error::other("disk gone")) + } + } + + impl Seek for FailingReader { + fn seek(&mut self, _pos: SeekFrom) -> io::Result { + Ok(64) + } + } + + #[test] + fn claude_transcript_bounds_record_starting_exactly_at_window_start_is_found() { + let record = tool_use_record("toolu_edge", "claude-opus-5-5"); + let window = usize::try_from(CLAUDE_TRANSCRIPT_TAIL_WINDOW_BYTES).unwrap(); + let tail = filler(window - record.len() - 1); + let transcript = format!("{}{record}\n{tail}", filler(MIB)); + + assert_eq!(transcript.len() - transcript.find(&record).unwrap(), window); + assert_eq!( + lookup(transcript.into_bytes(), "toolu_edge").as_deref(), + Some("claude-opus-5-5") + ); + } + + #[test] + fn claude_transcript_bounds_record_starting_one_byte_before_window_is_skipped() { + let record = tool_use_record("toolu_edge", "claude-opus-5-5"); + let window = usize::try_from(CLAUDE_TRANSCRIPT_TAIL_WINDOW_BYTES).unwrap(); + let tail = filler(window - record.len()); + let transcript = format!("{}{record}\n{tail}", filler(MIB)); + + assert_eq!( + transcript.len() - transcript.find(&record).unwrap(), + window + 1 + ); + assert_eq!(lookup(transcript.into_bytes(), "toolu_edge"), None); + } + + #[test] + fn claude_transcript_bounds_record_at_cap_is_found_and_one_byte_over_is_skipped() { + let at_cap = tool_use_record_of_length( + "toolu_cap", + "claude-opus-5-5", + CLAUDE_TRANSCRIPT_MAX_RECORD_BYTES, + ); + let over_cap = tool_use_record_of_length( + "toolu_over", + "claude-opus-5-5", + CLAUDE_TRANSCRIPT_MAX_RECORD_BYTES + 1, + ); + let transcript = format!("{at_cap}\n{over_cap}\n"); + + assert_eq!( + lookup(transcript.clone().into_bytes(), "toolu_cap").as_deref(), + Some("claude-opus-5-5") + ); + assert_eq!(lookup(transcript.into_bytes(), "toolu_over"), None); + } + + #[test] + fn claude_transcript_bounds_skips_oversized_and_malformed_records_and_continues() { + let oversized = tool_use_record_of_length( + "toolu_target", + "claude-haiku-5-5", + CLAUDE_TRANSCRIPT_MAX_RECORD_BYTES + 10, + ); + let mut transcript = Vec::new(); + transcript.extend_from_slice(oversized.as_bytes()); + transcript.push(b'\n'); + transcript + .extend_from_slice(b"{\"type\":\"assistant\",\"message\":{\"model\":\"\xff\xfe\"}}\n"); + transcript.extend_from_slice(b"{not json\n"); + transcript.extend_from_slice(tool_use_record("toolu_target", "claude-opus-5-5").as_bytes()); + transcript.push(b'\n'); + + assert_eq!( + lookup(transcript, "toolu_target").as_deref(), + Some("claude-opus-5-5") + ); + } + + #[test] + fn claude_transcript_bounds_missing_id_in_32_mib_transcript_reads_at_most_5_mib() { + let transcript = filler(32 * MIB).into_bytes(); + let mut reader = CountingReader { + inner: Cursor::new(transcript), + bytes_read: 0, + }; + + let started = Instant::now(); + let model = find_tool_use_model_in(&mut reader, "toolu_missing").expect("read succeeds"); + let elapsed = started.elapsed(); + + assert_eq!(model, None); + assert!( + reader.bytes_read <= 5 * MIB as u64, + "read {} bytes", + reader.bytes_read + ); + assert!(elapsed < Duration::from_millis(500), "took {elapsed:?}"); + } + + #[test] + fn claude_transcript_bounds_open_failure_is_a_typed_error() { + let dir = tempfile::tempdir().expect("temp dir"); + let missing = dir.path().join("missing.jsonl"); + + let error = find_claude_transcript_tool_use_model(&missing, "toolu_a") + .expect_err("missing transcript must fail to open"); + + assert!( + matches!(&error, ClaudeTranscriptReadError::Open { path, .. } if path == &missing), + "unexpected error: {error:?}" + ); + } + + #[test] + fn claude_transcript_bounds_read_failure_is_a_typed_error() { + let error = find_tool_use_model_in(FailingReader, "toolu_a") + .expect_err("failing reader must surface an error"); + + assert!( + matches!(error, ClaudeTranscriptReadError::Read(_)), + "unexpected error: {error:?}" + ); + } } diff --git a/cli/src/services/hooks/diff_trace.rs b/cli/src/services/hooks/diff_trace.rs index 05d918909..c43e8ee8b 100644 --- a/cli/src/services/hooks/diff_trace.rs +++ b/cli/src/services/hooks/diff_trace.rs @@ -1,4 +1,4 @@ -use std::path::Path; +use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{anyhow, bail, Context, Result}; @@ -7,22 +7,20 @@ use serde_json::Value; use crate::services::agent_trace_db::repository::RepositoryAgentTraceDb; use crate::services::agent_trace_db::{ - ClaudeModelStateObservation, DiffTraceInsert, ObservationKind, PAYLOAD_TYPE_PATCH, - PAYLOAD_TYPE_STRUCTURED, + DiffTraceInsert, PAYLOAD_TYPE_PATCH, PAYLOAD_TYPE_STRUCTURED, }; use crate::services::structured_patch::{ derive_claude_structured_patch, ClaudeStructuredPatchDerivationResult, }; -use super::claude_model_state; -use super::claude_transcript; +use super::claude_model_resolver::{self, ClaudeModelEvidence}; use super::conversation_trace::{ diff_trace_fail_open_session_id, non_empty_string, required_field, required_non_empty_string_field, }; use super::runtime::{ - current_unix_time_ms, open_agent_trace_db_for_hook_runtime, prefixed_diff_trace_session_id, - read_hook_stdin, CLAUDE_MODEL_ID_PREFIX, CLAUDE_TOOL_NAME, + open_agent_trace_db_for_hook_runtime, prefixed_diff_trace_session_id, read_hook_stdin, + CLAUDE_MODEL_ID_PREFIX, CLAUDE_TOOL_NAME, }; #[derive(Clone, Debug, Eq, PartialEq, Serialize)] @@ -36,6 +34,8 @@ pub(crate) struct DiffTracePayload { pub(crate) agent_id: Option, #[serde(skip)] pub(crate) transcript_path: Option, + #[serde(skip)] + pub(crate) tool_use_id: Option, pub(crate) tool_name: String, pub(crate) tool_version: Option, pub(crate) payload_type: String, @@ -192,6 +192,7 @@ pub(crate) fn parse_diff_trace_payload(stdin_payload: &str) -> Result) -> Option { - resolve_claude_model_id_with(payload, claude_transcript::extract_claude_transcript_model) -} - -pub(crate) fn resolve_claude_model_id_with( - payload: &serde_json::Map, - transcript_lookup: F, -) -> Option -where - F: FnOnce(&Path, &str) -> Option, -{ - extract_direct_claude_model_id(payload).or_else(|| { - let transcript_path = non_empty_string(payload.get("transcript_path"))?; - let tool_use_id = non_empty_string(payload.get("tool_use_id"))?; - - transcript_lookup(Path::new(transcript_path), tool_use_id) - .and_then(|model| normalize_claude_model_id(&model)) - }) -} - pub(crate) fn extract_direct_claude_model_id( payload: &serde_json::Map, ) -> Option { @@ -537,60 +519,124 @@ pub(crate) async fn resolve_diff_trace_model_id( db: &RepositoryAgentTraceDb, payload: &DiffTracePayload, ) -> Result> { - if payload.model_id.is_some() - || payload.tool_name != CLAUDE_TOOL_NAME - || payload.payload_type != PAYLOAD_TYPE_STRUCTURED - { + if payload.tool_name != CLAUDE_TOOL_NAME || payload.payload_type != PAYLOAD_TYPE_STRUCTURED { return Ok(payload.model_id.clone()); } - let session_id = prefixed_diff_trace_session_id(CLAUDE_TOOL_NAME, &payload.session_id); - let agent_id = payload.agent_id.as_deref().unwrap_or(""); - if let Some(state) = db - .claude_model_state_by_session_and_agent(&session_id, agent_id) - .await? - { - return Ok(Some(state.model_id)); - } + let evidence = ClaudeModelEvidence { + session_id: prefixed_diff_trace_session_id(CLAUDE_TOOL_NAME, &payload.session_id), + agent_id: payload.agent_id.clone(), + tool_use_id: payload.tool_use_id.clone(), + transcript_path: payload.transcript_path.as_deref().map(PathBuf::from), + direct_model_id: payload.model_id.clone(), + }; + claude_model_resolver::resolve_claude_model(db, &evidence).await +} - Ok(seed_diff_trace_model_from_bridge_chain(db, payload, &session_id, agent_id).await) +pub(crate) fn diff_trace_db_time_ms(time: u64) -> Result { + i64::try_from(time).map_err(|_| { + anyhow!(StdinPayloadKind::DiffTrace.validation_error( + "field 'time' must fit in a signed 64-bit Unix epoch millisecond value for Agent Trace DB storage" + )) + }) } -pub(crate) async fn seed_diff_trace_model_from_bridge_chain( - db: &RepositoryAgentTraceDb, - payload: &DiffTracePayload, - session_id: &str, - agent_id: &str, -) -> Option { - if !agent_id.is_empty() { - return None; +#[cfg(test)] +mod tests { + use std::path::Path; + + use serde_json::Value; + + use crate::services::agent_trace_db::repository::RepositoryAgentTraceDb; + + use super::{ + parse_diff_trace_payload, persist_diff_trace_payload_to_agent_trace_db_with_db, + DiffTraceParseResult, + }; + + const SESSION: &str = "7d1e3b8f-1111-4222-8333-944445555666"; + const AGENT: &str = "f00dfeed"; + const TOOL_USE_ID: &str = "toolu_write_1"; + + fn tool_use_record(model: &str) -> String { + format!( + "{}\n", + serde_json::json!({ + "type": "assistant", + "message": { + "role": "assistant", + "model": model, + "content": [{"type": "tool_use", "id": TOOL_USE_ID, "name": "Write"}] + } + }) + ) + } + + fn post_tool_use_payload(transcript_path: &Path, agent_id: Option<&str>) -> String { + let mut payload: Value = serde_json::from_str(include_str!( + "../structured_patch/fixtures/write_create_simple/claude-post-tool-use.json" + )) + .expect("fixture JSON"); + let object = payload.as_object_mut().expect("fixture object"); + object.insert("session_id".into(), SESSION.into()); + object.insert("tool_use_id".into(), TOOL_USE_ID.into()); + object.insert( + "transcript_path".into(), + transcript_path.display().to_string().into(), + ); + if let Some(agent_id) = agent_id { + object.insert("agent_id".into(), agent_id.into()); + } + payload.to_string() } - let transcript_path = payload.transcript_path.as_deref()?; - let model_id = - claude_model_state::newest_bridge_chain_model(db, Path::new(transcript_path)).await?; - - let observed_at_ms = current_unix_time_ms().ok()?; - match db - .upsert_claude_model_state(ClaudeModelStateObservation { - session_id: session_id.to_string(), - agent_id: String::new(), - model_id: model_id.clone(), - observation_kind: ObservationKind::SessionStart, - source: String::from("bridge_inherited"), - observed_at_ms, + async fn persisted_model_id(agent_id: Option<&str>) -> Option { + let dir = tempfile::tempdir().expect("temp dir"); + let main_transcript = dir.path().join(format!("{SESSION}.jsonl")); + std::fs::write(&main_transcript, tool_use_record("claude-opus-5-5")).expect("main"); + let subagent_dir = dir.path().join(SESSION).join("subagents"); + std::fs::create_dir_all(&subagent_dir).expect("subagent dir"); + std::fs::write( + subagent_dir.join(format!("agent-{AGENT}.jsonl")), + tool_use_record("claude-haiku-5-5"), + ) + .expect("subagent"); + let db = RepositoryAgentTraceDb::new_at(dir.path().join("agent-trace.db")) + .await + .expect("db"); + + let DiffTraceParseResult::Persist(payload) = + parse_diff_trace_payload(&post_tool_use_payload(&main_transcript, agent_id)) + .expect("payload parses") + else { + panic!("fixture must produce a diff trace"); + }; + persist_diff_trace_payload_to_agent_trace_db_with_db(&db, &payload) + .await + .expect("persist"); + + db.query_map("SELECT model_id FROM diff_traces", (), |row| { + row.get::>(0).map_err(Into::into) }) .await - { - Ok(_) => Some(model_id), - Err(_) => None, + .expect("read diff traces") + .pop() + .expect("one diff trace") } -} -pub(crate) fn diff_trace_db_time_ms(time: u64) -> Result { - i64::try_from(time).map_err(|_| { - anyhow!(StdinPayloadKind::DiffTrace.validation_error( - "field 'time' must fit in a signed 64-bit Unix epoch millisecond value for Agent Trace DB storage" - )) - }) + #[tokio::test] + async fn claude_subagent_model_diff_trace_resolves_from_subagent_transcript() { + assert_eq!( + persisted_model_id(Some(AGENT)).await.as_deref(), + Some("claude/claude-haiku-5-5") + ); + } + + #[tokio::test] + async fn claude_model_attribution_diff_trace_main_agent_resolves_from_main_transcript() { + assert_eq!( + persisted_model_id(None).await.as_deref(), + Some("claude/claude-opus-5-5") + ); + } } diff --git a/cli/src/services/hooks/mod.rs b/cli/src/services/hooks/mod.rs index d621f00a0..1dd64315c 100644 --- a/cli/src/services/hooks/mod.rs +++ b/cli/src/services/hooks/mod.rs @@ -1,5 +1,6 @@ use anyhow::Context; +mod claude_model_resolver; mod claude_transforms; mod commit_hooks; mod commit_patch_id; diff --git a/context/architecture.md b/context/architecture.md index 26ba801b2..4fe1dd020 100644 --- a/context/architecture.md +++ b/context/architecture.md @@ -77,8 +77,8 @@ The repository includes a new placeholder Rust binary crate at `cli/`. - `cli/src/services/doctor/mod.rs` owns the current doctor request/report surface while focused submodules (`doctor/inspect.rs`, `doctor/render.rs`, `doctor/fixes.rs`, `doctor/types.rs`) split report fact collection, rendering, manual fix reporting, and doctor-owned domain types into smaller seams; `cli/src/services/doctor/command.rs` owns the `DoctorCommand` payload used by the static `RuntimeCommand` enum and executes against any context implementing repo-root scoping. Runtime doctor execution resolves a repository root, derives a scoped context, requests the shared static lifecycle provider catalog with hooks included for service-owned `diagnose` and `fix` behavior, adapts lifecycle-owned health/fix records into doctor-owned problem/fix records, and then renders stable text/JSON problem records with category/severity/fixability/remediation fields plus deterministic fix-result reporting in fix mode. Agent Trace database inspection is no longer a doctor-adjacent command surface; doctor owns repository-scoped DB health and checkout identity facts, while `sce sync` owns control-plane synchronization. Report fact collection preserves environment/repository/hook/integration display data and adds a non-launching `post_commit_auto_sync` fact based on canonical post-commit managed-block currency plus resolved `agent_trace.auto_sync` source/value; this fact does not launch `sce sync`, and existing hook problem/remediation/readiness semantics remain authoritative. Service-owned lifecycle providers own config validation, local DB and repository-scoped Agent Trace DB readiness/bootstrap, and hook rollout diagnosis/repair. Integration inspection in `doctor/inspect.rs` is scoped twice over: `resolve_doctor_integration_targets` picks which targets to inspect, and `persisted_optional_workflows` (reused from setup) resolves which optional workflows the repository selected, which the OpenCode/Claude/Pi/Codex child collectors apply through `iter_embedded_assets_for_setup_target_with_selection`. An unselected optional workflow therefore contributes no expected children at all, so no row and no missing/mismatch problem can be produced for it, while a selected one keeps the unchanged presence and content-hash checks. Codex's collector (`collect_codex_integration_groups`) is the one exception to the single-target-directory shape the other three share: since `CODEX_EMBEDDED_ASSETS` relative paths already carry their own `.agents/`/`.codex/` prefix, it resolves its integration root through `InstallTargetPaths::codex_target_dir()` (the repository root itself) rather than a `RepoPaths` per-target subdirectory, and splits assets into `Skills` (`.agents/skills/` prefix) and `Hooks` (`.codex/` prefix) groups instead of Pi's `Extensions`/`Prompts`/`Skills` split. Its `.codex/hooks.json` reporting is per-registration rather than one whole-file child: `codex_hook_config::diagnose_document` classifies each required registration — the four `sce hooks codex` registrations plus the six `sce hooks codex-mutation-scope` ones, the latter reported under distinct `#(mutation-scope)` rows — as `PresentAndCurrent`/`Missing`/`Stale` (or the whole document as `Malformed` when it cannot be structurally validated) without writing anything, so unrelated user handlers never create a false whole-document mismatch. For a structurally current registration, `codex_hook_trust` separately reads (never writes) Codex's own durable `$CODEX_HOME/config.toml` hook-trust state — reproducing upstream's `hook_hash`/`hook_key`/`hook_trust_status` exactly — and reports `Trusted`/`Untrusted`/`Modified`/`Disabled`/`Unknown`, and `codex_hook_policy` probes Codex's effective hook-discovery policy once per invocation; only a structurally current registration that is trusted *and* policy-allowed renders healthy. `sce doctor --fix` repairs a structurally unhealthy `.codex/hooks.json` through the existing merge-install path, but a registration that is current yet not-yet-trusted or policy-blocked is never "fixed", since SCE cannot grant Codex hook trust or change managed policy. - `cli/src/services/version/mod.rs` defines the version command parser/rendering contract (`parse_version_request`, `render_version`) with deterministic text output and stable JSON runtime-identification fields; `cli/src/services/version/command.rs` owns the `VersionCommand` payload used by the static `RuntimeCommand` enum. - `cli/src/services/completion/mod.rs` defines completion parser/rendering contract (`parse_completion_request`, `render_completion`) with deterministic Bash/Zsh/Fish script output aligned to current parser-valid command/flag surfaces; `cli/src/services/completion/command.rs` owns the `CompletionCommand` payload used by the static `RuntimeCommand` enum. -- `cli/src/services/hooks/mod.rs` defines the current local hook runtime parsing/dispatch (`HookSubcommand`, `run_hooks_subcommand`), including the `claude-model-state` lifecycle intake (silent) delegated to `cli/src/services/hooks/claude_model_state.rs`, the hidden non-fail-open `mutation-scope` runtime ingress delegated to `cli/src/services/hooks/mutation_scope.rs` (STDIN normalized JSON → one `mutation_trace::runtime` `coordinate()` / `abandon_scope()` call with a lazy DB provider; see `context/cli/mutation-scope-hook-ingress.md`), the hidden non-fail-open `claude-mutation-scope` adapter delegated to `cli/src/services/hooks/claude_mutation_scope/` (STDIN raw Claude hook JSON → tool classification + identity/`ScopeId` derivation → the same `mutation_scope.rs` `pub(crate)` in-process seam, one mutation `ScopeId` per mutation-capable tool execution; registered by `sce setup`; see `context/cli/claude-mutation-scope-integration.md`), plus a commit-msg co-author policy seam (`apply_commit_msg_coauthor_policy`) that injects one canonical SCE trailer only when the enabled-by-default attribution-hooks config/env control is not opted out, `SCE_DISABLED` is false, and the staged-diff AI-overlap preflight confirms AI/editor evidence (`StagedDiffAiOverlapResult::Overlap`); the preflight is wired into `run_commit_msg_subcommand_in_repo` and logs `sce.hooks.commit_msg.ai_overlap_error` on error paths; `cli/src/services/hooks/command.rs` owns the `HooksCommand` payload used by the static `RuntimeCommand` enum. In the current attribution-only baseline, `pre-commit` and `post-rewrite` are deterministic no-op surfaces; `post-commit` requires validated `--remote-url`, threads that URL through the Agent Trace flow, prints it to stderr, and remains an active intersection + Agent Trace persistence entrypoint (captures the exact commit OID, timestamp, and patch; derives a trusted commit-time cutoff or, when the timestamp is untrusted, makes both evidence sources unavailable so touched lines are unknown; queries repository-level `diff_traces` whose reported time and `created_at` precede the commit second, keeping each row separate for fresh, exact, single-session matching (`agent_trace/evidence.rs`); persists the direct-only intersection metadata to `post_commit_patch_intersections`; resolves read-only mutation lineage for every committed touched line from up to 128 of the invoking worktree's events inserted before the cutoff, against the captured commit's trees, with no `diff_traces` or mutation-cursor write; resolves each line with mutation lineage first and accepted direct evidence only for lines lineage leaves unresolved — see `context/cli/mutation-trace-agent-attribution.md`; and persists the built Agent Trace payloads with range-level `content_hash` values to `agent_traces` in the repository-scoped Agent Trace DB without post-commit file artifacts); after successful validation and persistence, the setup-enabled config-file-only `agent_trace.auto_sync` gate launches one detached sync-owned `sync --format json` child when its resolved value is true (a newly created setup config supplies the explicit `true`; omitted configuration resolves to `false`), with launcher failures ignored and no high-frequency hook trigger; `diff-trace` performs STDIN JSON intake, validates required non-empty `sessionID`/`diff`/`tool_name`, optional `model_id` (absent/`null` → `None`), required nullable/non-empty `tool_version` plus required `u64` `time` (Unix epoch milliseconds), rejects values that cannot fit signed `time_ms` storage, prefixes the stored `diff_traces.session_id` before insert construction (`oc_` for OpenCode, `cc_` for Claude, `pi_` for Pi, same-tool idempotent), and inserts the parsed payload fields into `RepositoryAgentTraceDb` without creating a parsed-payload `context/tmp` artifact; Claude structured `PostToolUse` diff-trace intake resolves model attribution with `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL`: direct top-level or nested metadata wins, otherwise the event's `transcript_path` is scanned for the assistant envelope whose `tool_use.id` matches `tool_use_id`, then persistence performs one exact local `claude_model_state` lookup using canonical session and ephemeral agent scope. Only for a raw structured payload in the exact main-session scope, a state miss then resolves the newest `claude_model_state` observation across the transcript's bridge-linked chain members (bounded leading-record reads, one exact-scope read per member, winner by `observed_at_ms`) and, on a hit, writes a `claude_model_state` row for the current session (`source="bridge_inherited"`) before using that model — the only diff-trace resolution path that writes state. Model values normalize once through `claude/`, subagents do not inherit main-session state, and unresolved values remain nullable. `session-model` is no longer a supported hook route. -- Generated Claude settings register `SessionStart` and `PostModelSwitch` only for the local model-state hook; `sce hooks session-model` is no longer a supported hook command. Claude Code 2.1.250 and 2.1.251 compatibility smoke passed with the unknown `PostModelSwitch` registration, so SCE installs it unconditionally without a raised minimum or capability gate. The `session_models` table/API and generic session-level fallback lookup were removed in T02 of the `remove-session-models-direct-claude-model-id` plan; the separate `sce hooks claude-model-state` command writes Claude lifecycle observations into the non-exported exact-scope register through the no-migration hook-runtime DB path, without restoring that generic abstraction. `diff-trace` uses direct-first/event-transcript-second Claude `model_id` resolution and consults the exact local lifecycle state only as its final fallback, with direct `tool_version` values. +- `cli/src/services/hooks/mod.rs` defines the current local hook runtime parsing/dispatch (`HookSubcommand`, `run_hooks_subcommand`), including the `claude-model-state` lifecycle intake (silent) delegated to `cli/src/services/hooks/claude_model_state.rs`, the hidden non-fail-open `mutation-scope` runtime ingress delegated to `cli/src/services/hooks/mutation_scope.rs` (STDIN normalized JSON → one `mutation_trace::runtime` `coordinate()` / `abandon_scope()` call with a lazy DB provider; see `context/cli/mutation-scope-hook-ingress.md`), the hidden non-fail-open `claude-mutation-scope` adapter delegated to `cli/src/services/hooks/claude_mutation_scope/` (STDIN raw Claude hook JSON → tool classification + identity/`ScopeId` derivation → the same `mutation_scope.rs` `pub(crate)` in-process seam, one mutation `ScopeId` per mutation-capable tool execution; registered by `sce setup`; see `context/cli/claude-mutation-scope-integration.md`), plus a commit-msg co-author policy seam (`apply_commit_msg_coauthor_policy`) that injects one canonical SCE trailer only when the enabled-by-default attribution-hooks config/env control is not opted out, `SCE_DISABLED` is false, and the staged-diff AI-overlap preflight confirms AI/editor evidence (`StagedDiffAiOverlapResult::Overlap`); the preflight is wired into `run_commit_msg_subcommand_in_repo` and logs `sce.hooks.commit_msg.ai_overlap_error` on error paths; `cli/src/services/hooks/command.rs` owns the `HooksCommand` payload used by the static `RuntimeCommand` enum. In the current attribution-only baseline, `pre-commit` and `post-rewrite` are deterministic no-op surfaces; `post-commit` requires validated `--remote-url`, threads that URL through the Agent Trace flow, prints it to stderr, and remains an active intersection + Agent Trace persistence entrypoint (captures the exact commit OID, timestamp, and patch; derives a trusted commit-time cutoff or, when the timestamp is untrusted, makes both evidence sources unavailable so touched lines are unknown; queries repository-level `diff_traces` whose reported time and `created_at` precede the commit second, keeping each row separate for fresh, exact, single-session matching (`agent_trace/evidence.rs`); persists the direct-only intersection metadata to `post_commit_patch_intersections`; resolves read-only mutation lineage for every committed touched line from up to 128 of the invoking worktree's events inserted before the cutoff, against the captured commit's trees, with no `diff_traces` or mutation-cursor write; resolves each line with mutation lineage first and accepted direct evidence only for lines lineage leaves unresolved — see `context/cli/mutation-trace-agent-attribution.md`; and persists the built Agent Trace payloads with range-level `content_hash` values to `agent_traces` in the repository-scoped Agent Trace DB without post-commit file artifacts); after successful validation and persistence, the setup-enabled config-file-only `agent_trace.auto_sync` gate launches one detached sync-owned `sync --format json` child when its resolved value is true (a newly created setup config supplies the explicit `true`; omitted configuration resolves to `false`), with launcher failures ignored and no high-frequency hook trigger; `diff-trace` performs STDIN JSON intake, validates required non-empty `sessionID`/`diff`/`tool_name`, optional `model_id` (absent/`null` → `None`), required nullable/non-empty `tool_version` plus required `u64` `time` (Unix epoch milliseconds), rejects values that cannot fit signed `time_ms` storage, prefixes the stored `diff_traces.session_id` before insert construction (`oc_` for OpenCode, `cc_` for Claude, `pi_` for Pi, same-tool idempotent), and inserts the parsed payload fields into `RepositoryAgentTraceDb` without creating a parsed-payload `context/tmp` artifact; Claude structured `PostToolUse` diff-trace intake resolves model attribution with main-agent `direct > exact transcript > exact main-session state > bridge-derived chain state > NULL` and subagent `direct > exact subagent-transcript record > NULL`: direct top-level or nested metadata wins, otherwise the event's `transcript_path` is scanned for the assistant envelope whose `tool_use.id` matches `tool_use_id`, then, for a main-agent event only, persistence performs one exact local `claude_model_state` lookup for `(cc_, "")`, and a state miss then resolves the newest `claude_model_state` observation across the transcript's bridge-linked chain members (bounded leading-record reads, one exact-scope read per member, winner by `observed_at_ms`) and, on a hit, writes a `claude_model_state` row for the current session (`source="bridge_inherited"`) before using that model — the only diff-trace resolution path that writes state. Model values normalize once through `claude/`, subagents do not inherit main-session state, and unresolved values remain nullable. `session-model` is no longer a supported hook route. +- Generated Claude settings register `SessionStart` and `PostModelSwitch` only for the local model-state hook; `sce hooks session-model` is no longer a supported hook command. Claude Code 2.1.250 and 2.1.251 compatibility smoke passed with the unknown `PostModelSwitch` registration, so SCE installs it unconditionally without a raised minimum or capability gate. The `session_models` table/API and generic session-level fallback lookup were removed in T02 of the `remove-session-models-direct-claude-model-id` plan; the separate `sce hooks claude-model-state` command writes Claude lifecycle observations into the non-exported exact-scope register through the no-migration hook-runtime DB path, without restoring that generic abstraction. `diff-trace` resolves Claude `model_id` through the one Claude model resolver (`cli/src/services/hooks/claude_model_resolver.rs`; see `context/sce/claude-model-resolver.md`), with direct `tool_version` values. - `cli/src/services/resilience.rs` defines bounded retry/timeout/backoff execution policy (`RetryPolicy`, `run_with_retry`) for transient operation hardening with deterministic failure messaging and retry observability. - `context/cli/agent-trace-auto-sync.md` documents the sync-owned, one-shot post-commit launcher boundary: it reuses `sce sync`, has no daemon or local retry machinery, and fails open when child startup cannot be completed; doctor reports this capability without invoking the launcher. - `cli/src/services/sync/progress.rs` owns the sync-local, consumer-typed progress seam: generic `ProgressReporter` supports event delivery plus explicit successful finalization, closure-based collectors, and a no-op implementation alongside the fixed `indicatif` stderr presentation adapter. `cli/src/services/sync/sync.rs` owns `SyncProgressEvent` and its payload semantics for the three remotely synchronized streams (`messages`, `parts`, `agent_traces`; `diff_traces` is captured locally but not synchronized), while `sync/command.rs` selects the terminal adapter for text and the no-op reporter for JSON. There is no top-level `cli/src/services/progress/` module; sync orchestration depends only on its sync-owned contract, so terminal-library details stay at the sync presentation boundary. diff --git a/context/context-map.md b/context/context-map.md index 94974c9e8..33aeed822 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -103,7 +103,8 @@ Feature/domain context: - `context/sce/agent-trace-retry-queue-observability.md` (inactive local-hook retry path plus historical retry/metrics reference) - `context/sce/agent-trace-local-hooks-mvp-contract-gap-matrix.md` (T01 Local Hooks MVP production contract freeze and deterministic gap matrix for `agent-trace-local-hooks-production-mvp`) - `context/sce/agent-trace-minimal-generator.md` (implemented a library minimal Agent Trace generator seam at `cli/src/services/agent_trace.rs`, used by the active post-commit hook flow to produce strict `0.1.0` JSON payloads with top-level `version`, UUIDv7 `id` derived from commit-time metadata, caller-provided commit-time `timestamp`, optional top-level `vcs` metadata emitted when present (`type` from enum `git|jj|hg|svn`, `revision` from metadata input; current post-commit flow provides `git`), optional top-level `tool` metadata (`name`/`version`) sourced from builder metadata inputs when overlapping AI content exists, always-emitted `metadata.sce.version` sourced from the compiled `sce` CLI package version, and always-emitted `metadata.sce.line_changes` (`{ai,non_exclusive,unknown}` each `{added,removed}` `u64` counters, `#[serde(default)]` for backward-compatible deserialization) carrying exact per-line attribution counts with one bucket increment per canonical `post_commit_patch` touched line from the same per-line decisions that build revision-positioned ranges: only surviving added lines at their post-commit positions, coalesced by identical decision/session/model and grouped into conversations by accepted session (Git hunks never decide contributors; SCE never generates `mixed`), with optional conversation-level `contributor`, optional range-level `contributor` overrides, session links only from a conversation's own lines, and optional range `content_hash` = Murmur3 (seed 0) of the exact committed blob bytes at `vcs.revision`, read by `GitCommittedFiles` and omitted when unavailable) -- `context/sce/agent-trace-hooks-command-routing.md` (implemented `sce hooks` command routing plus current runtime behavior: enabled-by-default commit-msg attribution with explicit opt-out controls, no-op `pre-commit`/`post-rewrite` entrypoints, active `post-commit` intersection and Agent Trace DB persistence (direct and mutation evidence both restricted by a trusted commit-time cutoff that fails closed to unknown attribution) with a best-effort canonical `git patch-id --stable` commit patch ID stored in nullable `agent_traces.commit_patch_id` (sanitized warning and `NULL` on failure), DB-only `diff-trace` STDIN intake with OpenCode normalized payloads and Claude structured `PostToolUse` payload classification, tool-prefixed stored `diff_traces.session_id` values (`oc_` for OpenCode, `cc_` for Claude, `pi_` for Pi) while hook diagnostics route with unprefixed producer-native sessions when available, nullable `model_id`/direct `tool_version` persistence with Claude `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL` attribution, Claude direct-first model metadata extraction from top-level or nested fields followed by fail-open `transcript_path` + `tool_use_id` JSONL lookup and exact local state lookup when model is absent, a main-session-scope-only bridge chain state-miss fallback that seeds a `source="bridge_inherited"` row for the current session (the one diff-trace path that writes state), `claude/` prefix normalization, no parsed-payload artifact persistence under `context/tmp`, the silent local-only `sce hooks claude-model-state` lifecycle intake for synchronous `SessionStart` and asynchronous `PostModelSwitch` writes whose own model-less `SessionStart` bridge attempt cannot read its lazily created transcript, `session-model` removed from the supported hook surface, and `conversation-trace` STDIN intake for normalized batches plus supported raw Claude events with per-item and first-valid-insert batch diagnostic routing; this document also owns the current `diff-trace`, `conversation-trace`, and Claude model-state fail-open intake contracts, and now also routes the hidden non-fail-open `sce hooks mutation-scope` mutation-scope-runtime ingress with its two carried-outcome success variants — distinct from the fail-open `diff-trace`/`conversation-trace` intakes — and the hidden non-fail-open `sce hooks claude-mutation-scope` first-concrete-adapter route (now registered by `sce setup`), deferring the full contracts to `context/cli/mutation-scope-hook-ingress.md` and `context/cli/claude-mutation-scope-integration.md`.) +- `context/sce/claude-model-resolver.md` (the one Claude model resolver: `ClaudeModelEvidence`, full and exact-evidence entry points, main-agent and subagent precedence, subagent transcript path derivation, and the 4 MiB window / 1 MiB record transcript bounds) +- `context/sce/agent-trace-hooks-command-routing.md` (implemented `sce hooks` command routing plus current runtime behavior: enabled-by-default commit-msg attribution with explicit opt-out controls, no-op `pre-commit`/`post-rewrite` entrypoints, active `post-commit` intersection and Agent Trace DB persistence (direct and mutation evidence both restricted by a trusted commit-time cutoff that fails closed to unknown attribution) with a best-effort canonical `git patch-id --stable` commit patch ID stored in nullable `agent_traces.commit_patch_id` (sanitized warning and `NULL` on failure), DB-only `diff-trace` STDIN intake with OpenCode normalized payloads and Claude structured `PostToolUse` payload classification, tool-prefixed stored `diff_traces.session_id` values (`oc_` for OpenCode, `cc_` for Claude, `pi_` for Pi) while hook diagnostics route with unprefixed producer-native sessions when available, nullable `model_id`/direct `tool_version` persistence with Claude main-agent `direct > exact transcript > exact main-session state > bridge-derived chain state > NULL` and subagent `direct > exact subagent-transcript record > NULL` attribution, Claude direct-first model metadata extraction from top-level or nested fields followed by fail-open `transcript_path` + `tool_use_id` JSONL lookup and exact local state lookup when model is absent, a main-session-scope-only bridge chain state-miss fallback that seeds a `source="bridge_inherited"` row for the current session (the one diff-trace path that writes state), `claude/` prefix normalization, no parsed-payload artifact persistence under `context/tmp`, the silent local-only `sce hooks claude-model-state` lifecycle intake for synchronous `SessionStart` and asynchronous `PostModelSwitch` writes whose own model-less `SessionStart` bridge attempt cannot read its lazily created transcript, `session-model` removed from the supported hook surface, and `conversation-trace` STDIN intake for normalized batches plus supported raw Claude events with per-item and first-valid-insert batch diagnostic routing; this document also owns the current `diff-trace`, `conversation-trace`, and Claude model-state fail-open intake contracts, and now also routes the hidden non-fail-open `sce hooks mutation-scope` mutation-scope-runtime ingress with its two carried-outcome success variants — distinct from the fail-open `diff-trace`/`conversation-trace` intakes — and the hidden non-fail-open `sce hooks claude-mutation-scope` first-concrete-adapter route (now registered by `sce setup`), deferring the full contracts to `context/cli/mutation-scope-hook-ingress.md` and `context/cli/claude-mutation-scope-integration.md`.) - `context/sce/automated-profile-contract.md` (deterministic gate policy for automated OpenCode profile, including 10 gate categories, permission mappings, automated `/commit` single-commit execution behavior, and automated profile constraints) - `context/sce/bash-tool-policy-enforcement-contract.md` (approved bash-tool blocking contract plus current Rust evaluator seam and OpenCode/Claude delegation references, including config schema, argv-prefix matching, shell/nix unwrapping, custom-policy `satisfied_by` wrapper exemption, fixed preset catalog/messages, and precedence rules) - `context/sce/bash-policy-satisfied-by-wrapper-exemption.md` (custom-policy `satisfied_by` field: optional list of wrapper argv prefixes that exempt a policy from firing when the matched command was unwrapped from one of them; `NormalizedSegment` wrapper-chain tracking, matching model, examples, and scope) diff --git a/context/glossary.md b/context/glossary.md index ec52334c4..a1dc4a66e 100644 --- a/context/glossary.md +++ b/context/glossary.md @@ -95,7 +95,7 @@ - `committed-file outcome`: The result of `CommittedFileReader::read_committed_file` for a post-commit path: `Blob` (regular or executable file, `100644`/`100755` blob; ranges validated and hashed), `NotLineAddressable` (symlink `120000` blob, gitlink `160000` commit, or directory `040000` tree; no ranges, counters kept), `Missing` (absent at the revision; trace generation fails), or `Unverified` (test-only, `#[cfg(test)]`: hashless ranges whose positions are not independently verified; production readers never produce it). Operational failures are a separate `CommittedFileReadError` (`TreeLookupFailed`, `MalformedTreeEntry`, `BlobReadFailed`) and also fail trace generation. Canonical counters in `metadata.sce.line_changes` always cover every touched line regardless of which files emit ranges. - `Git path identity`: The exact repository-relative path of a patch file after decoding Git's C-quoted form (`patch/git_path.rs`): escapes decode to bytes, the result must be valid UTF-8 without NUL, and `a/`/`b/` prefixes are removed only after decoding. Undecodable names fail patch parsing explicitly. The same identity is used for attribution lookup, `files[].path`, and committed-file lookup. - `external-mutation guard` / `external-mutation supervisor`: `arm_external_mutation_guard` + `ArmedExternalMutationGuard::exec` (`cli/src/services/mutation_trace/runtime/external_mutation_guard.rs`, hidden `sce hooks external-mutation-guard`, Unix-only), the harness-neutral, not-Pi-specific mechanism that lets a human-initiated shell command (Pi's `!`/`!!` `user_bash`) mutate a worktree without ever creating a mutation scope: it acquires the same `ProtectedWorktree` guard `coordinate()` uses, reports it armed, itself spawns the human shell as its own child (never signaled or stopped by control-channel closure — only by an explicit cancel request, which it enacts by signaling the shell's own process group), finishes exclusively on the shell's real process termination, and only then forces the existing `database_failure`+`recover` composition on the already-held worktree via `coordinate_on_held_worktree` before clearing the marker with `ProtectedWorktree::complete()`. See [`mutation-trace-external-mutation-guard.md`](cli/mutation-trace-external-mutation-guard.md). -- `Claude diff-trace attribution`: Diff-trace enrichment rule where one Claude `PostToolUse` event resolves its model with `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL`: direct top-level/nested metadata first, then that event's `transcript_path` matched by `tool_use_id` to an assistant envelope's `tool_use.id`, then one exact `(cc_, agent_id)` lookup in local `claude_model_state`. Only for a raw structured Claude payload in the exact main-session scope (`agent_id` empty), a state miss then falls back to `bridge session correlation` across the transcript's bridge-linked chain; when that resolves, persistence writes a `claude_model_state` row for the current session (`source="bridge_inherited"`) — the one diff-trace resolution path that writes state — and uses that model, so later traces of the same session resolve from their own exact-scope row. Model sources receive one `claude/` normalization step, ephemeral agent context is never exported, and subagents do not inherit main-session state. +- `Claude diff-trace attribution`: Model resolution for one Claude `PostToolUse` structured diff trace, performed once per event at persist time by the `Claude model resolver` (`cli/src/services/hooks/claude_model_resolver.rs`). A main-agent event resolves `direct > exact transcript > exact (cc_, "") state > bridge-derived chain state > NULL`; the bridge step alone writes a `claude_model_state` row (`source="bridge_inherited"`). A subagent event resolves `direct > exact record in its subagent transcript (//subagents/agent-.jsonl) > NULL` and never reads or writes state. A transcript record attributes an event only when it names the event's `tool_use_id`, inside a 4 MiB tail window with a 1 MiB record cap. See [sce/claude-model-resolver.md](sce/claude-model-resolver.md). - `bridge session correlation`: Claude-specific local correlation using the `bridgeSessionId` in leading transcript records to relate a Claude session's transcript to its sibling transcripts sharing that ID. Selection resolves the newest `claude_model_state` observation across all bridge-linked chain members by `observed_at_ms` (deterministic session-ID tie-break), not the chain origin and not the most recently modified sibling transcript. Discovery is bounded (leading records only) and fail-open, uses existing exact-scope `claude_model_state` rows without persisting the bridge ID, and does not claim authoritative session ordering. One selection rule serves both call sites — the `diff-trace` state-miss path and the `sce hooks claude-model-state` `SessionStart` path — with no most-recently-modified-sibling pick left in the code. See [the read-path bridge-seeding decision](decisions/2026-09-10-claude-bridge-seeding-on-diff-trace.md) and [the bridge-session inheritance decision](decisions/2026-09-08-claude-bridge-session-model-inheritance.md). - `DiffTraceInsert`: Insert payload in `cli/src/services/agent_trace_db/mod.rs` carrying `time_ms`, tool-prefixed `session_id`, `patch`, `model_id`, `tool_name`, nullable `tool_version`, and `payload_type` for parameterized writes to the `diff_traces` table; `payload_type` uses `PAYLOAD_TYPE_PATCH` (`"patch"`) for `OpenCode` unified-diff payloads and `PAYLOAD_TYPE_STRUCTURED` (`"structured"`) for `Claude` `PostToolUse` structured payloads. - `diff_traces payload_type discriminator`: `TEXT NOT NULL DEFAULT 'patch'` column in `diff_traces` added by migration `015_add_diff_traces_payload_type`; values are `PAYLOAD_TYPE_PATCH` (`"patch"`) for `OpenCode` unified-diff source payloads and `PAYLOAD_TYPE_STRUCTURED` (`"structured"`) for `Claude` `PostToolUse` structured source payloads; existing rows default to `"patch"` for backward compatibility. @@ -180,7 +180,7 @@ - `setup catalog-derived pruning`: `prune_stale_assets_for_concrete_target` in `cli/src/services/setup/mod.rs`, run after per-asset install, deletes every path the full embedded catalog for a concrete target claims but the resolved selection did not install (a deselected optional workflow, or an asset a newer catalog renamed or dropped), then `remove_empty_ancestor_directories` removes any parent directory left empty by that deletion, walking upward until it reaches the target root or a directory that still holds something (a user file inside an SCE-owned skill directory keeps that directory from being removed). Pruning is stateless and derives only from the compiled-in catalog; no install manifest is persisted, so an orphaned file installed by an older `sce` binary under a name the current catalog no longer knows is left alone. - `setup config-merge seam`: Pure JSON merge services covering `.claude/settings.json`, `.opencode/opencode.json`, and Codex's `.codex/hooks.json`; the latter is owned by shared `cli/src/services/codex_hook_config.rs`, which validates structure and requires both the generated helper path and the `sce hooks codex` command contract before replacing stale or duplicate registrations. Both `merge_or_create_claude_settings` and `merge_or_create_opencode_config` share the shape `(existing_bytes: Option<&[u8]>, generated_bytes: &[u8], source_path: &str) -> Result>`: each returns `generated_bytes` verbatim when no existing file is present; otherwise each parses both as JSON (an existing-file parse failure is a hard error naming `source_path`, with no write) and delegates to a pure merge function that copies the SCE-owned `$schema` key from the generated document and preserves every other top-level key from the existing document untouched. `merge_claude_settings` additionally replaces, per hook event key the generated `hooks` object declares, only the entries whose `hooks[].command` contains the SCE ownership marker `run-sce-or-show-install-guidance.sh`, appended after the surviving non-SCE entries; event keys the generated document does not declare are left untouched. `merge_opencode_config` additionally merges the `plugin` array as a set: existing entries whose path starts with the SCE ownership marker `./plugins/sce-` are dropped structurally (so a stale plugin path an older or renamed catalog installed is recognized and pruned even after the current generated document stops declaring it), then the generated document's `plugin` entries are appended. `install_single_asset_with_rename` (`mod install` in `cli/src/services/setup/mod.rs`) detects each merge target via `is_claude_settings_merge_target` / `is_opencode_config_merge_target` / `is_codex_hooks_merge_target` and stages the merged bytes instead of the embedded asset's bytes before the shared stage/swap step. The shared Codex service also exposes `diagnose_document`, which classifies each of the four required registrations as `PresentAndCurrent`/`Missing`/`Stale` (or the whole document as `Malformed` when it fails structural validation) without writing anything; a `PresentAndCurrent` result always implies a no-op merge. `cli/src/services/doctor/inspect.rs` uses the Claude/OpenCode fragment functions to inspect those merge targets and the Codex diagnosis (instead of byte-exact `sha256` or whole-document comparison) to inspect `.codex/hooks.json` per registration, further gating a structurally current registration on `codex_hook_trust::trust_readiness` (reads Codex's own `$CODEX_HOME`/`~/.codex/config.toml` hook-trust state read-only; see `context/architecture.md`), and `crate::services::setup::repair_merge_target_asset` lets `sce doctor --fix` repair all three repairable merge targets, including Codex's, by reinstalling just that one asset through the same merge-install path — never to grant trust. - `setup atomic-swap`: Per-file replacement choreography in `cli/src/services/setup/mod.rs` where staged content is renamed directly over an existing destination file, without ever unlinking that destination first — `fs::rename` replaces it atomically on both Unix and Windows, so a rename failure leaves the prior destination content and permissions untouched; on swap failure, the engine cleans that file's staging artifact and returns deterministic recovery guidance naming its path (recover from version control). No backup artifacts are created. Config install (`install_embedded_setup_assets`) applies this at individual-asset granularity and never removes an integration target directory as a whole; required-hook install applies it per hook file. Formerly called "setup remove-and-replace"; that name predates the removal of the pre-swap unlink step. -- `hooks command routing contract`: Current hook command parser/dispatcher plus runtime wiring in `cli/src/services/hooks/mod.rs` (`HookSubcommand`, `run_hooks_subcommand`) supports `pre-commit`, `commit-msg `, `post-commit`, `post-rewrite `, `diff-trace`, `conversation-trace`, and `codex` with deterministic invocation validation/usage errors; `session-model` is no longer supported. `commit-msg` is the only active attribution path behind the attribution hooks gate and staged-diff AI-overlap preflight; `pre-commit`/`post-rewrite` are no-ops; `post-commit` persists intersections and built Agent Trace payloads; `diff-trace` persists DB-only AgentTraceDb rows using tool-prefixed `session_id`, Claude `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL` attribution, and direct `tool_version`, while keeping agent context ephemeral and state local-only; `codex` is Codex's own single dispatcher subcommand (`cli/src/services/hooks/codex/`), classifying its raw hook JSON internally by `(hook_event_name, tool_name)` rather than routing through `diff-trace`/`conversation-trace` like the other three tools — all four of its supported arms now have real behavior: `UserPromptSubmit` and `Stop` capture real conversation evidence into `messages`/`parts`, `PreToolUse(Bash)` delegates to the existing Bash policy engine, and `PostToolUse(apply_patch)` outer-normalizes supported raw/heredoc input before parsing, resolves paths from event `cwd` against the real Git root into safe repository-relative paths, then parses/normalizes/persists a `diff_traces` row for provable Add/Update evidence using event-scoped synthetic line identities derived from `tool_use_id` (see `context/sce/codex-integration-runtime.md`). Invalid cwd/path mappings or identity/range failures fail open before persistence. +- `hooks command routing contract`: Current hook command parser/dispatcher plus runtime wiring in `cli/src/services/hooks/mod.rs` (`HookSubcommand`, `run_hooks_subcommand`) supports `pre-commit`, `commit-msg `, `post-commit`, `post-rewrite `, `diff-trace`, `conversation-trace`, and `codex` with deterministic invocation validation/usage errors; `session-model` is no longer supported. `commit-msg` is the only active attribution path behind the attribution hooks gate and staged-diff AI-overlap preflight; `pre-commit`/`post-rewrite` are no-ops; `post-commit` persists intersections and built Agent Trace payloads; `diff-trace` persists DB-only AgentTraceDb rows using tool-prefixed `session_id`, Claude main-agent `direct > exact transcript > exact main-session state > bridge-derived chain state > NULL` and subagent `direct > exact subagent-transcript record > NULL` attribution, and direct `tool_version`, while keeping agent context ephemeral and state local-only; `codex` is Codex's own single dispatcher subcommand (`cli/src/services/hooks/codex/`), classifying its raw hook JSON internally by `(hook_event_name, tool_name)` rather than routing through `diff-trace`/`conversation-trace` like the other three tools — all four of its supported arms now have real behavior: `UserPromptSubmit` and `Stop` capture real conversation evidence into `messages`/`parts`, `PreToolUse(Bash)` delegates to the existing Bash policy engine, and `PostToolUse(apply_patch)` outer-normalizes supported raw/heredoc input before parsing, resolves paths from event `cwd` against the real Git root into safe repository-relative paths, then parses/normalizes/persists a `diff_traces` row for provable Add/Update evidence using event-scoped synthetic line identities derived from `tool_use_id` (see `context/sce/codex-integration-runtime.md`). Invalid cwd/path mappings or identity/range failures fail open before persistence. - `Claude raw hook capture (removed)`: Former hidden/internal `sce hooks claude-capture ` intake path removed in T05 of the `claude-typescript-model-cache-remove-rust-capture` plan. Rust now exposes `diff-trace` and `conversation-trace` intakes for active Claude/OpenCode editor runtimes; `session-model` is also removed from the supported hook command surface. The removed route previously wrote pretty-printed JSON artifacts under `context/tmp/claude/` without AgentTraceDb writes. See `context/sce/claude-raw-hook-capture.md`. - `deferred sync command` (historical): An earlier implementation note deferred a user-invocable sync command; it was superseded first by nested `sce trace sync` and now by the top-level `sce sync` command (see `context/cli/sync-command.md` and `context/cli/agent-trace-sync-command.md`). Local DB initialization and health ownership remain split between setup and doctor. - `sce CLI onboarding guide`: Crate-local documentation at `cli/README.md` that defines runnable placeholder commands, non-goals/safety limits, and roadmap mapping to service modules. @@ -196,7 +196,7 @@ - `agent trace historical reference docs`: Retained `context/sce/agent-trace-*.md` artifacts that describe the removed pre-v0.3 Agent Trace design and task slices; they are reference-only and do not describe the active local-hook runtime. - `agent trace commit-msg co-author policy`: Current contract in `cli/src/services/hooks/mod.rs` (`apply_commit_msg_coauthor_policy`) that applies exactly one canonical trailer (`Co-authored-by: SCE `) only when attribution hooks are enabled, SCE is not disabled, and the staged-diff AI-overlap preflight confirms AI/editor evidence (`StagedDiffAiOverlapResult::Overlap`); `NoOverlap` and `Error` both suppress the trailer, with `Error` logged via `sce.hooks.commit_msg.ai_overlap_error`; duplicate canonical trailers are deduped idempotently. - `local DB migration contract`: `cli/src/services/local_db/mod.rs` delegates migration execution to `TursoDb` through the `DbSpec::migrations()` contract. The current `LocalDbSpec` migration list is empty, so `LocalDb::new()` opens/creates the canonical local DB without creating local tables. -- `hook no-op baseline`: Current `cli/src/services/hooks/mod.rs` runtime posture where `pre-commit` and `post-rewrite` return deterministic no-op status text, `commit-msg` is a gated mutating path, `post-commit` persists intersections and built Agent Trace payloads without post-commit file artifacts, `diff-trace` validates STDIN payloads, resolves Claude `model_id` with `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL` precedence, persists direct `tool_version`, applies stored `session_id` prefixes (`oc_`/`cc_`/`pi_`), and inserts DB-only AgentTraceDb rows, `conversation-trace` is the active message/part intake path, and `codex` (`cli/src/services/hooks/codex/`) classifies its own raw hook JSON into four supported dispatch arms — `UserPromptSubmit` and `Stop` capture real conversation evidence, `PreToolUse(Bash)` delegates to the existing Bash policy engine, `PostToolUse(apply_patch)` parses/normalizes/persists a `diff_traces` row using event-scoped synthetic line identities — with every other event/tool combination (including `PreToolUse(apply_patch)`) and malformed STDIN failing open as a no-op. `session-model` is no longer a supported hook route. +- `hook no-op baseline`: Current `cli/src/services/hooks/mod.rs` runtime posture where `pre-commit` and `post-rewrite` return deterministic no-op status text, `commit-msg` is a gated mutating path, `post-commit` persists intersections and built Agent Trace payloads without post-commit file artifacts, `diff-trace` validates STDIN payloads, resolves Claude `model_id` through the Claude model resolver, persists direct `tool_version`, applies stored `session_id` prefixes (`oc_`/`cc_`/`pi_`), and inserts DB-only AgentTraceDb rows, `conversation-trace` is the active message/part intake path, and `codex` (`cli/src/services/hooks/codex/`) classifies its own raw hook JSON into four supported dispatch arms — `UserPromptSubmit` and `Stop` capture real conversation evidence, `PreToolUse(Bash)` delegates to the existing Bash policy engine, `PostToolUse(apply_patch)` parses/normalizes/persists a `diff_traces` row using event-scoped synthetic line identities — with every other event/tool combination (including `PreToolUse(apply_patch)`) and malformed STDIN failing open as a no-op. `session-model` is no longer a supported hook route. - `sce doctor` operator-health contract: `cli/src/services/doctor/mod.rs` is the stable doctor entrypoint, with focused `doctor/{inspect,render,fixes,types,managed_telemetry,access}.rs` submodules (`access.rs` owns the `SCE login` row — a blocking failure under effective `auth.mode: mandatory` without a confirmed WorkOS session, where an expired access token is refreshed against WorkOS and a rejected refresh fails with the WorkOS reason in its problem summary; telemetry readiness and enrollment are independent, and unreadable storage, an incomplete lookup, or WorkOS unreachable for more than 24h since the last confirmation yield an `unavailable` warning with a reason — and the managed-telemetry policy state and source, see [doctor human text](sce/doctor-human-text-contract.md#sce-login-row)) implementing the current approved operator-health surface in `context/sce/agent-trace-hook-doctor.md`: `sce doctor --fix` selects repair intent, Agent Trace DB discovery is repository-scoped only (the checkout-scoped `sce trace --legacy` surface was removed by the `retire-legacy-agent-trace-db` plan), and output exposes deterministic doctor mode, readiness, stable problem taxonomy/fixability fields, checkout/database records, and fix-result records. The runtime validates state-root resolution, global and repo-local `sce/config.json` readability/schema health, local DB and repository-scoped Agent Trace DB path/health, DB-parent readiness barriers, git availability, non-repo vs bare-repo targeting failures, effective hook-path source resolution, required hook presence/executable/content drift against canonical embedded hook assets, and repo-root installed OpenCode, Claude, Pi, plus Codex integration content health. Human text mode uses the approved sectioned layout (`Environment`, `Configuration` with repository-scoped Agent Trace DB rows when available, `Repository`, `Git Hooks`, `Integrations`), `SCE doctor diagnose` / `SCE doctor fix` headers, bracketed `[PASS]`/`[FAIL]`/`[MISS]` status tokens with shared-style green/red colorization when enabled, simplified `label (path)` row formatting, top-level-only hook rows, and integration parent/child rows where missing files surface as `[MISS]`, mismatches/read failures as `[FAIL]`, and affected parent groups as `[FAIL]`. Agent Trace DB rows include repository ID, identity source, safe canonical identity, configured remote name, and never raw remote URLs. Current integration groups include `OpenCode plugins`, `OpenCode agents`, `OpenCode commands`, `OpenCode skills`, `ClaudeCode plugins`, `ClaudeCode commands`, `ClaudeCode skills`, `Pi prompts`, `Pi skills`, `Pi extensions`, `Codex skills`, and `Codex hooks`; Claude `settings.json` plus `hooks/**` belong to `ClaudeCode plugins`, including `.claude/hooks/run-sce-or-show-install-guidance.sh`, Pi `prompts/**` and `skills/**` map to the Pi groups, and Codex's `.agents/skills/**` plus `.codex/hooks.json`/`.codex/hooks/**` map to the Codex groups (the latter also carrying a Codex hook trust/review reminder when unhealthy). Fix mode reuses canonical setup hook installation for missing/stale/non-executable required hooks and missing hooks directories and can bootstrap canonical missing SCE-owned DB parent directories. - `compact doctor text report`: Current human-readable `sce doctor` rendering collapses healthy state, repository, and typed integration-area checks into the `Environment`/`Repository`/`Integrations` hierarchy, suppresses healthy paths and identity metadata, and uses `--format json` as the full-detail route. The canonical current contract is [doctor human text](sce/doctor-human-text-contract.md). - `cli warnings-denied lint policy`: `cli/Cargo.toml` sets `warnings = "deny"`, so plain `cargo clippy --manifest-path cli/Cargo.toml` already fails on warnings without needing an extra `-- -D warnings` tail. diff --git a/context/overview.md b/context/overview.md index 653cf8ca4..ae12d8e99 100644 --- a/context/overview.md +++ b/context/overview.md @@ -86,7 +86,7 @@ Setup repository preflight: every `sce setup` mode, including `--bootstrap-conte Sync owns the complete progress boundary in `cli/src/services/sync/progress.rs`: the consumer-typed `ProgressReporter` contract, no-op reporter, focused contract tests, and fixed `indicatif` terminal adapter. `SyncProgressEvent` remains owned by `cli/src/services/sync/sync.rs`; `sync/command.rs` selects the adapter or no-op implementation by output format, there is no top-level `cli/src/services/progress/` module, and JSON callers use the sync-owned no-op reporter. The same config resolver now also owns the attribution-hooks gate used by local hook runtime: opt-out env `SCE_ATTRIBUTION_HOOKS_DISABLED` overrides `policies.attribution_hooks.enabled` with inverted semantics, and the gate defaults to enabled unless explicitly disabled. The config service split now includes `cli/src/services/config/resolver.rs` as the focused owner for config-file discovery, file-layer merging, env/flag/default precedence, auth-key resolution, observability resolution, attribution-hooks resolution, and default-discovered invalid-file degradation; `cli/src/services/config/mod.rs` remains the facade/rendering orchestration surface while preserving existing `services::config` imports. -Generated config now includes repo-local OpenCode plugin assets: `sce-bash-policy.ts` plus `sce-agent-trace.ts` are emitted under `config/.opencode/plugins/`; the OpenCode agent-trace plugin extracts `{ sessionID, diff, time, model_id }` from user `message.updated` events with diffs, tracks per-session OpenCode client version from `session.created`/`session.updated`, and sends payloads to `sce hooks diff-trace` with `tool_name="opencode"` plus optional `tool_version`. Claude generated config registers `SessionStart` and `PostModelSwitch` for local model-state intake through `sce hooks claude-model-state`, while supported `PostToolUse Write|Edit|MultiEdit|NotebookEdit` events remain routed directly to `sce hooks diff-trace`; it does not call the retired `sce hooks session-model` route. Rust handles extraction, validation, and persistence without a TypeScript intermediary; the former `config/.claude/plugins/sce-agent-trace.ts` Bun runtime was removed in T07 of the `claude-rust-diff-trace` plan. The Rust hook validates required fields, resolves Claude `model_id` with `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL` precedence using direct metadata, matching `transcript_path`/`tool_use_id` JSONL fallback, then one exact local state lookup while keeping `tool_version` direct (without restoring `session_models`), and persists tool-prefixed `session_id` values (`oc*`for OpenCode,`cc*`for Claude,`pi*`for Pi),`model_id`, `tool_name`, and nullable `tool_version`into`diff_traces`through AgentTraceDb. Bash-policy now delegates OpenCode enforcement to the Rust`sce policy bash`command: the generated OpenCode plugin at`config/.opencode/plugins/sce-bash-policy.ts`is a thin wrapper that calls`sce policy bash --input normalized --output json`via`spawnSync`and throws on deny decisions; it no longer contains independent TypeScript policy logic. The former`bash-policy/runtime.ts`TypeScript runtime has been removed. Preset... +Generated config now includes repo-local OpenCode plugin assets: `sce-bash-policy.ts` plus `sce-agent-trace.ts` are emitted under `config/.opencode/plugins/`; the OpenCode agent-trace plugin extracts `{ sessionID, diff, time, model_id }` from user `message.updated` events with diffs, tracks per-session OpenCode client version from `session.created`/`session.updated`, and sends payloads to `sce hooks diff-trace` with `tool_name="opencode"` plus optional `tool_version`. Claude generated config registers `SessionStart` and `PostModelSwitch` for local model-state intake through `sce hooks claude-model-state`, while supported `PostToolUse Write|Edit|MultiEdit|NotebookEdit` events remain routed directly to `sce hooks diff-trace`; it does not call the retired `sce hooks session-model` route. Rust handles extraction, validation, and persistence without a TypeScript intermediary; the former `config/.claude/plugins/sce-agent-trace.ts` Bun runtime was removed in T07 of the `claude-rust-diff-trace` plan. The Rust hook validates required fields, resolves Claude `model_id` with main-agent `direct > exact transcript > exact main-session state > bridge-derived chain state > NULL` and subagent `direct > exact subagent-transcript record > NULL` precedence using direct metadata, matching `transcript_path`/`tool_use_id` JSONL fallback, then one exact local state lookup while keeping `tool_version` direct (without restoring `session_models`), and persists tool-prefixed `session_id` values (`oc*`for OpenCode,`cc*`for Claude,`pi*`for Pi),`model_id`, `tool_name`, and nullable `tool_version`into`diff_traces`through AgentTraceDb. Bash-policy now delegates OpenCode enforcement to the Rust`sce policy bash`command: the generated OpenCode plugin at`config/.opencode/plugins/sce-bash-policy.ts`is a thin wrapper that calls`sce policy bash --input normalized --output json`via`spawnSync`and throws on deny decisions; it no longer contains independent TypeScript policy logic. The former`bash-policy/runtime.ts`TypeScript runtime has been removed. Preset... Claude bash-policy enforcement is also generated through`.claude/settings.json`as a`PreToolUse` `Bash`command hook running`sce policy bash`, so Claude and OpenCode both delegate to the Rust policy evaluator without a Claude TypeScript runtime. Pi bash-policy enforcement is delegated the same way through a project-local Pi extension (`config/lib/pi-plugin/sce-pi-extension.ts`, emitted to `config/.pi/extensions/sce/index.ts`) whose `tool_call`handler blocks denied bash commands via`sce policy bash`and fails open when the policy check cannot run (see`context/sce/pi-extension-runtime.md`). Local database bootstrap is now owned by `LocalDbLifecycle::setup`and`AgentTraceDbLifecycle::setup`aggregated by the setup command. Agent Trace lifecycle setup creates or migrates the repository-scoped`/sce/repos//agent-trace.db`; hook runtime uses the same repository-storage identity/path resolution without running migrations, and missing or stale schema causes hook paths to fail open with the existing`Run 'sce setup'.`guidance. Doctor validates the repository-scoped DB path/health and can bootstrap missing parent directories; outside a Git repository it reports an actionable "requires a Git repository" diagnostic instead of probing a sentinel path.`sce sync`is fully implemented: it resolves repository-scoped storage, authenticates against the control plane with stored WorkOS credentials, fetches authoritative cursors once, synchronizes three of the four local Agent Trace capture streams (`messages`, `parts`, `agent_traces`) concurrently while preserving sequential batches within each stream, leaves `diff_traces` local, and renders the documented concise text/JSON output (see`context/cli/sync-command.md`). The former `sce trace` command group and its database inspection surfaces are unavailable. The repository-root flake (`flake.nix`) applies a Rust overlay-backed stable toolchain pinned to `1.95.0`(with`rustfmt`and`clippy`), reads package/check version from the repo-root `.version`file, and builds`packages.sce`through a Crane`buildDepsOnly`+`buildPackage`pipeline. One deterministic pre-Cargo Nix derivation invokes the shared generated-input producer and supplies its validated`SCE_CLI_GENERATED_INPUT_DIR`store path to native, release, test, and Clippy Cargo derivations. Pkl is absent from those Cargo environments; dependency-only and format derivations do not receive the handoff, so canonical generation changes invalidate compiling outputs without invalidating dependency artifacts or formatting.`cli-tests`, `cli-clippy`, and `cli-fmt`remain Crane-backed check derivations. @@ -113,10 +113,10 @@ The current supported automated release target matrix is `x86_64-unknown-linux-m Context sync uses an important-change gate: cross-cutting/policy/architecture/terminology changes require root shared-file edits, while localized tasks run verify-only root checks without default churn. OpenCode and Claude no longer generate legacy bootstrap or context-sync skills; `/commit` and `/handover` are generated only as catalog-registered composite workflow packages. OpenCode retains only thin routing agents, while Claude emits no agents. The superseded grouped Markdown catalog and automated OpenCode profile have been removed from Pkl ownership and generated outputs. The prior no-git-wrapper Agent Trace design artifacts under `context/sce/agent-trace-*.md` are retained only as historical reference; the current CLI runtime no longer wires the removed Agent Trace schema adaptation, payload building, retry replay, or rewrite handling paths into local hook execution. - The hooks service now uses a minimal attribution-only runtime: `commit-msg` is the only hook that mutates behavior, conditionally injecting exactly one canonical SCE trailer when the attribution-hooks gate is enabled, `SCE_DISABLED` is false, and the staged-diff AI-overlap preflight confirms AI/editor evidence (`StagedDiffAiOverlapResult::Overlap`); when the preflight returns `NoOverlap` or `Error` (including DB open failure, schema not ready, query error, staged diff read failure, or zero overlap), the trailer is not appended and errors are logged via `sce.hooks.commit_msg.ai_overlap_error`; `pre-commit` and `post-rewrite` remain deterministic no-op entrypoints; `post-commit` requires validated `--remote-url`, threads that URL through the Agent Trace flow, prints it to stderr, then (1) captures the exact commit OID once from `HEAD` and reads that OID's committer timestamp and patch; (2) accepts the timestamp as a trusted commit-time cutoff only under a conservative heuristic (no `GIT_COMMITTER_DATE` override, not in the future, at most 5 minutes old), otherwise both evidence sources become unavailable and every committed touched line is unknown while the trace is still persisted; (3) queries direct `diff_traces` evidence whose reported `time_ms` and database `created_at` both precede the commit second (dispatching `patch` rows through unified-diff parsing and `structured` rows through `structured_patch::derive_claude_structured_patch` at read time); (4) resolves read-only mutation lineage for the invoking worktree from mutation events whose `created_at` precedes the same cutoff (filtered in SQL before the 128-event window) against the commit and first-parent trees of the captured OID, without writing `diff_traces` or mutation-cursor state; (5) resolves each committed touched line independently — AI-exclusive lineage → AI, non-exclusive lineage → `NonExclusive`, unresolved lineage plus accepted exact single-session direct evidence → AI, otherwise `Unknown` (conflicting direct candidates fail closed to unknown, and a matching direct session may only supply a model the mutation scope lacks); (6) builds and validates ranges, hashes, and per-line counters; and (7) persists the schema-validated built Agent Trace payload (the direct-only intersection metadata is already written to `post_commit_patch_intersections` right after step 3) (see `context/cli/mutation-trace-agent-attribution.md#commit-time-cutoff`), including optional top-level `tool` metadata from recent diff-trace rows (direct evidence only), top-level `metadata.sce.version` from the compiled `sce` CLI package version, always-emitted `metadata.sce.line_changes` per-line `{ai,non_exclusive,unknown}` attribution counts over the combined direct+mutation line decisions, and range-level `content_hash` values, to AgentTraceDb `agent_traces` (DB-only, no post-commit Agent Trace file artifact); `diff-trace` currently validates/persists required non-empty `sessionID`/`diff`/`tool_name`, optional `model_id` (absent or `null` → `None`, present+non-empty → `Some`, present+empty → error), required nullable/non-empty `tool_version`, plus required `u64` millisecond `time`, uses `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL` Claude `model_id` resolution plus direct `tool_version`, with ephemeral agent scope and no generic `session_models` runtime, and continues with `None` when all sources cannot resolve attribution, with same-tool-idempotent stored `session_id` prefixing (`oc_` for OpenCode, `cc_` for Claude, `pi_` for Pi), non-lossy AgentTraceDb `time_ms` conversion, and no parsed-payload artifact fallback. Claude structured `PostToolUse` diff-trace intake prefers direct top-level or nested model metadata, then matches the event's `tool_use_id` in its JSONL `transcript_path`, consults exact local lifecycle state only when both event-local sources fail, normalizes model values once with the `claude/` prefix, and fails open to `None` when no source resolves. + The hooks service now uses a minimal attribution-only runtime: `commit-msg` is the only hook that mutates behavior, conditionally injecting exactly one canonical SCE trailer when the attribution-hooks gate is enabled, `SCE_DISABLED` is false, and the staged-diff AI-overlap preflight confirms AI/editor evidence (`StagedDiffAiOverlapResult::Overlap`); when the preflight returns `NoOverlap` or `Error` (including DB open failure, schema not ready, query error, staged diff read failure, or zero overlap), the trailer is not appended and errors are logged via `sce.hooks.commit_msg.ai_overlap_error`; `pre-commit` and `post-rewrite` remain deterministic no-op entrypoints; `post-commit` requires validated `--remote-url`, threads that URL through the Agent Trace flow, prints it to stderr, then (1) captures the exact commit OID once from `HEAD` and reads that OID's committer timestamp and patch; (2) accepts the timestamp as a trusted commit-time cutoff only under a conservative heuristic (no `GIT_COMMITTER_DATE` override, not in the future, at most 5 minutes old), otherwise both evidence sources become unavailable and every committed touched line is unknown while the trace is still persisted; (3) queries direct `diff_traces` evidence whose reported `time_ms` and database `created_at` both precede the commit second (dispatching `patch` rows through unified-diff parsing and `structured` rows through `structured_patch::derive_claude_structured_patch` at read time); (4) resolves read-only mutation lineage for the invoking worktree from mutation events whose `created_at` precedes the same cutoff (filtered in SQL before the 128-event window) against the commit and first-parent trees of the captured OID, without writing `diff_traces` or mutation-cursor state; (5) resolves each committed touched line independently — AI-exclusive lineage → AI, non-exclusive lineage → `NonExclusive`, unresolved lineage plus accepted exact single-session direct evidence → AI, otherwise `Unknown` (conflicting direct candidates fail closed to unknown, and a matching direct session may only supply a model the mutation scope lacks); (6) builds and validates ranges, hashes, and per-line counters; and (7) persists the schema-validated built Agent Trace payload (the direct-only intersection metadata is already written to `post_commit_patch_intersections` right after step 3) (see `context/cli/mutation-trace-agent-attribution.md#commit-time-cutoff`), including optional top-level `tool` metadata from recent diff-trace rows (direct evidence only), top-level `metadata.sce.version` from the compiled `sce` CLI package version, always-emitted `metadata.sce.line_changes` per-line `{ai,non_exclusive,unknown}` attribution counts over the combined direct+mutation line decisions, and range-level `content_hash` values, to AgentTraceDb `agent_traces` (DB-only, no post-commit Agent Trace file artifact); `diff-trace` currently validates/persists required non-empty `sessionID`/`diff`/`tool_name`, optional `model_id` (absent or `null` → `None`, present+non-empty → `Some`, present+empty → error), required nullable/non-empty `tool_version`, plus required `u64` millisecond `time`, uses main-agent `direct > exact transcript > exact main-session state > bridge-derived chain state > NULL` and subagent `direct > exact subagent-transcript record > NULL` Claude `model_id` resolution plus direct `tool_version`, with ephemeral agent scope and no generic `session_models` runtime, and continues with `None` when all sources cannot resolve attribution, with same-tool-idempotent stored `session_id` prefixing (`oc_` for OpenCode, `cc_` for Claude, `pi_` for Pi), non-lossy AgentTraceDb `time_ms` conversion, and no parsed-payload artifact fallback. Claude structured `PostToolUse` diff-trace intake prefers direct top-level or nested model metadata, then matches the event's `tool_use_id` in its JSONL `transcript_path`, consults exact local lifecycle state only when both event-local sources fail, normalizes model values once with the `claude/` prefix, and fails open to `None` when no source resolves. The CLI now also includes an approved operator-environment doctor contract documented in `context/sce/agent-trace-hook-doctor.md`; the runtime includes `sce doctor --fix` parsing/help, stable problem/fix-result reporting, canonical hook-repair reuse, bounded doctor-owned local-DB directory bootstrap for the missing SCE-owned DB parent path, and target-scoped integration inventory: Claude reports `Plugins`, `Commands`, and `Skills`; OpenCode reports `Plugins`, `Agents`, `Commands`, and `Skills`; Pi reports `Extensions`, `Prompts`, and `Skills`; and Codex reports `Skills` and `Hooks` (see `context/sce/doctor-human-text-contract.md`). Its non-launching post-commit Agent Trace auto-sync fact reports enabled/current, explicit disabled, not-ready, and not-applicable states using canonical managed-block currency and resolved configuration; existing hook remediation and readiness semantics remain unchanged. The local DB service now provides `LocalDb` as a thin `TursoDb` alias in `cli/src/services/local_db/mod.rs`; `LocalDbSpec` resolves the canonical local DB path from the shared default-path catalog and currently declares zero migrations. Shared Turso infrastructure lives in `cli/src/services/db/mod.rs`, where `DbSpec` and generic `TursoDb` support local or remote sync-mode opens, parent-directory creation, connection setup, synchronous query helpers, embedded migration execution, and shared DB lifecycle helpers. Auth DB persistence uses encrypted `AuthDb = EncryptedTursoDb` and token storage persists credentials through the `auth_credentials` table. Agent Trace persistence uses the sole `RepositoryAgentTraceDb = TursoDb` adapter at `/sce/repos//agent-trace.db`, with a one-file repository schema for `repository_metadata`, `diff_traces`, `post_commit_patch_intersections`, `agent_traces`, `messages`, `parts`, indexes/triggers, and no `checkout_id` columns on trace rows. The checkout-scoped `AgentTraceDb = TursoDb` adapter, its `agent_trace_db_path()`/`agent_trace_db_path_for_checkout()` helpers, and the 15-file `cli/migrations/agent-trace/` chain were removed by the `retire-legacy-agent-trace-db` plan; active hook runtime writes nullable event-local diff-trace attribution without a `session_models` API/table dependency. - The hooks command surface now also supports concrete runtime subcommand routing (`pre-commit`, `commit-msg`, `post-commit`, `post-rewrite`, `diff-trace`, `conversation-trace`, and `claude-model-state`) with deterministic argument/STDIN validation; `session-model` is no longer supported. Claude settings install the model-state command for both `SessionStart` and `PostModelSwitch`; compatibility smoke against Claude Code 2.1.251 and immediately older 2.1.250 showed that the older client safely ignores the unknown event, so installation is unconditional without a raised minimum or capability gate. Current runtime behavior keeps commit-msg attribution enabled by default unless explicitly opted out: the attribution gate enables canonical trailer insertion in `commit-msg` only when the staged-diff AI-overlap preflight confirms AI/editor evidence (no trailer is appended when the preflight finds no overlap or encounters any error); `pre-commit`/`post-rewrite` remain deterministic no-ops, `post-commit` requires validated `--remote-url`, threads that URL into the Agent Trace flow, prints it to stderr, remains the active bounded recent-diff-trace intersection path, and after successful Agent Trace persistence optionally launches the detached sync-owned `sync --format json` child when config-file-only `agent_trace.auto_sync` is true; `diff-trace` is the active intake path for parsed STDIN `{ sessionID, diff, time, model_id?, tool_name, tool_version }` payload persistence with optional `model_id`, required non-empty `tool_name`, required nullable/non-empty `tool_version`, `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL` Claude `model_id` plus direct `tool_version` values (exact local state only; no generic session-model fallback or cache), required `u64` millisecond `time`, same-tool-idempotent stored `session_id` prefixing (`oc_` for OpenCode, `cc_` for Claude, `pi_` for Pi), non-lossy AgentTraceDb `time_ms` conversion, and no parsed-payload artifact fallback. This behavior is documented in `context/sce/agent-trace-hooks-command-routing.md`. The removed `sce hooks claude-capture` raw capture route is documented in `context/sce/claude-raw-hook-capture.md` as a removed feature. + The hooks command surface now also supports concrete runtime subcommand routing (`pre-commit`, `commit-msg`, `post-commit`, `post-rewrite`, `diff-trace`, `conversation-trace`, and `claude-model-state`) with deterministic argument/STDIN validation; `session-model` is no longer supported. Claude settings install the model-state command for both `SessionStart` and `PostModelSwitch`; compatibility smoke against Claude Code 2.1.251 and immediately older 2.1.250 showed that the older client safely ignores the unknown event, so installation is unconditional without a raised minimum or capability gate. Current runtime behavior keeps commit-msg attribution enabled by default unless explicitly opted out: the attribution gate enables canonical trailer insertion in `commit-msg` only when the staged-diff AI-overlap preflight confirms AI/editor evidence (no trailer is appended when the preflight finds no overlap or encounters any error); `pre-commit`/`post-rewrite` remain deterministic no-ops, `post-commit` requires validated `--remote-url`, threads that URL into the Agent Trace flow, prints it to stderr, remains the active bounded recent-diff-trace intersection path, and after successful Agent Trace persistence optionally launches the detached sync-owned `sync --format json` child when config-file-only `agent_trace.auto_sync` is true; `diff-trace` is the active intake path for parsed STDIN `{ sessionID, diff, time, model_id?, tool_name, tool_version }` payload persistence with optional `model_id`, required non-empty `tool_name`, required nullable/non-empty `tool_version`, main-agent `direct > exact transcript > exact main-session state > bridge-derived chain state > NULL` and subagent `direct > exact subagent-transcript record > NULL` Claude `model_id` plus direct `tool_version` values (exact local state only; no generic session-model fallback or cache), required `u64` millisecond `time`, same-tool-idempotent stored `session_id` prefixing (`oc_` for OpenCode, `cc_` for Claude, `pi_` for Pi), non-lossy AgentTraceDb `time_ms` conversion, and no parsed-payload artifact fallback. This behavior is documented in `context/sce/agent-trace-hooks-command-routing.md`. The removed `sce hooks claude-capture` raw capture route is documented in `context/sce/claude-raw-hook-capture.md` as a removed feature. The setup service now also exposes deterministic required-hook embedded asset accessor (`iter_required_hook_assets`) backed by canonical templates in `cli/assets/hooks/` for `pre-commit`, `commit-msg`, and `post-commit`; this behavior is documented in `context/sce/setup-githooks-hook-asset-packaging.md`. The setup service now also includes required-hook install orchestration (`install_required_git_hooks`) that resolves repository root and effective hooks path from git truth, computes the bytes to stage by merging the canonical hook template with any existing hook (preserving a foreign hook's content as an exact prefix with the SCE managed block appended, or bringing an SCE-owned block current in place) rather than writing canonical bytes verbatim, enforces deterministic per-hook outcomes (`Installed`/`Updated`/`Skipped`) against that merged content, surfaces a deterministic advisory when an appended block would be unreachable, and uses a unified atomic-swap policy that renames staged content directly over existing hooks without unlinking them first, with deterministic recovery guidance on swap failures; this behavior is documented in `context/sce/setup-githooks-install-flow.md`. The setup command parser/dispatch now also supports composable setup+hooks runs (`sce setup --opencode|--claude|--pi|--codex|--all --hooks`) plus hooks-only mode (`sce setup --hooks` with optional `--repo `), enforces deterministic compatibility validation (`--repo` requires `--hooks`; target flags remain mutually exclusive), and emits deterministic setup/hook outcome messaging (`installed`/`updated`/`skipped`); this behavior is documented in `context/sce/setup-githooks-cli-ux.md`. diff --git a/context/patterns.md b/context/patterns.md index 08db164ca..05643da5a 100644 --- a/context/patterns.md +++ b/context/patterns.md @@ -169,7 +169,7 @@ - For `diff-trace` hook intake, keep producer-facing failure behavior fail-open: STDIN read and parse/validation failures use `sce.hooks.diff_trace.error`; AgentTraceDb open failures use the error-level `sce.hooks.diff_trace.agent_trace_db_open_failed`; later conversion/insert failures retain `sce.hooks.diff_trace.agent_trace_db_write_failed`. Preserve existing output text and emit only the most specific persistence diagnostic for one failure. - For `conversation-trace` hook intake, keep producer-facing failure behavior fail-open: STDIN read, top-level parse/validation, and unsupported raw Claude hook events use `sce.hooks.conversation_trace.error`; AgentTraceDb open failures use the error-level `sce.hooks.conversation_trace.agent_trace_db_open_failed`; later batch inserts retain their existing warning event. Preserve valid-payload mixed-batch accounting, skipped-item logging, output text, and one diagnostic per DB-open failure. - For generated Codex hook invocation, resolve the Git repository root at runtime and invoke the installed helper with quoted expansions; exit successfully and silently when Git-root resolution fails, and preserve the helper's existing missing-CLI stderr guidance and STDIN forwarding. For `codex` hook intake, route every Codex hook event through the single `sce hooks codex` subcommand and classify it internally (`(hook_event_name, tool_name)` → `UserPromptSubmit`/`Stop`/`PreToolUse(Bash)`/`PostToolUse(apply_patch)`/`NoOp`) rather than adding per-event subcommands like Claude's native hook script does; keep producer-facing failure behavior fail-open, using `sce.hooks.codex.error` for STDIN read and JSON parse failures, and route every unrecognized `hook_event_name`/`tool_name` combination (including `PreToolUse(apply_patch)`) to the same deterministic silent `NoOp` success rather than an error. -- For raw structured Claude diff-trace attribution persistence, keep model resolution ordered `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL`: prefer direct payload metadata, then use only that event's `transcript_path` and `tool_use_id` for fail-open JSONL lookup, then one exact lookup in the local `claude_model_state` register using canonical `cc_` plus the event's exact agent scope. Only when that misses for a raw structured payload in the exact main-session scope, resolve `bridge session correlation` across the event's `transcript_path` chain (bounded leading-record reads of sibling transcripts, one exact-scope state read per member, winner by greatest `observed_at_ms`) and, on a hit, write one `claude_model_state` row for the current session (`source="bridge_inherited"`, `observation_kind=session_start`) through the existing guarded write path before using that model — the only diff-trace resolution path that writes state, and self-limiting because the seeded row satisfies the exact-scope read on every later trace. Normalized payloads, even with `tool_name="claude"`, are not eligible for the state fallback or the bridge fallback. Normalize model values through the `claude/` convention and store unresolved attribution as `NULL` in `diff_traces`; persist `tool_version` directly. Every bridge branch fails open to `NULL` with no state write. Do not restore the former generic `session_models` abstraction, broaden subagent scope to the main session, poll/wait for lifecycle state, run a second selection rule, scan a full transcript, or reparse stored raw Claude JSON; the parser remains storage-free and unsupported events remain DB-free. +- Resolve every Claude model attribution through the one Claude model resolver (`cli/src/services/hooks/claude_model_resolver.rs`); do not call the transcript reader, the `claude_model_state` lookup, or the bridge-session chain from a consumer. Main-agent precedence is `direct > exact transcript > exact (cc_, "") state > bridge-derived chain state > NULL`; subagent precedence is `direct > exact subagent-transcript record > NULL`. Match a transcript record only by the event's `tool_use_id`, keep transcript reads inside the 4 MiB tail window and 1 MiB record cap, and map every reader error to `NULL`. Only the main-agent bridge step writes state (`source="bridge_inherited"`); never write a transcript-derived model to `claude_model_state`, and never let a subagent inherit main-session state. Normalized payloads, even with `tool_name="claude"`, keep their direct `model_id` and skip the resolver. Contract in [sce/claude-model-resolver.md](sce/claude-model-resolver.md). - For `sce hooks claude-model-state`, parse raw Claude `SessionStart` and `PostModelSwitch` events without database access, normalize `cc_`/`claude/`, map absent or null `agent_id` to the exact main-session scope `""`, and trim present agent IDs while rejecting empty or non-string values before any DB access. For a model-less `SessionStart`, use only the event's `transcript_path` and the same shared newest-chain-observation selection rule as the `diff-trace` state-miss path (bounded leading-record reads of chain siblings sharing the `bridgeSessionId`, one exact-scope state read per member, winner by greatest `observed_at_ms`) and seed the current session with `source="bridge_inherited"` when a chain observation exists; every discovery or state failure remains the existing no-op. Keep exactly one selection rule for both call sites — no most-recently-modified-sibling pick. This `SessionStart` attempt fires before Claude has created the session's transcript, so it always no-ops in practice — bridge inheritance for a cleared session is carried by the `diff-trace` state-miss path above — but it is kept in place cheaply against the chance Claude ever creates transcripts eagerly. Write directly through the no-migration repository hook path before the process exits. PostModelSwitch validates both model fields but persists `to_model`. Current Claude sources include `command`, `picker`, `sdk`, `auto`, and `resume`, but SCE accepts any non-empty source string and stores it opaquely. Keep the command local-only, logger-diagnostic-only, fail-open, empty-stdout, and free of migration, sync, polling, or detached/background work; SessionStart is synchronous relative to Claude execution while PostModelSwitch is asynchronous and may overlap. - For recent structured diff-trace reconstruction, treat persisted row attribution as canonical: assign the row `model_id` to every reconstructed hunk and the tool-prefixed row `session_id` to every reconstructed touched line before combination/intersection. Never reuse the raw unprefixed Claude payload session as touched-line provenance. - For commit-msg co-author policy seams, gate canonical trailer insertion on runtime controls (`SCE_DISABLED` plus the shared attribution-hooks enablement gate) plus the staged-diff AI-overlap evidence gate (`StagedDiffAiOverlapResult::Overlap` maps to `ai_contribution_present = true`; `NoOverlap` and `Error` both map to `false`), and enforce idempotent dedupe so allowed cases end with exactly one `Co-authored-by: SCE ` trailer. diff --git a/context/plans/claude-subagent-attribution.md b/context/plans/claude-subagent-attribution.md index 205cc903c..c54794747 100644 --- a/context/plans/claude-subagent-attribution.md +++ b/context/plans/claude-subagent-attribution.md @@ -151,13 +151,19 @@ Persist this field in every plan; this is durable plan state, not chat state: - Context impact: localized — one new decision record; current-state context files change in later tasks when behavior lands. - Context synchronization: synced -- [ ] T02: `Add the shared Claude model resolver with bounded exact-record transcript lookup` (status:todo) +- [x] T02: `Add the shared Claude model resolver with bounded exact-record transcript lookup` (status:done) - Task ID: T02 - Scope: In — the bounded transcript reader in `claude_transcript.rs` (4 MiB tail window, 1 MiB record cap, skip malformed records, typed reader error, generic over `Read + Seek`); one resolver module with a concrete evidence struct (canonical session, optional `agent_id`, `tool_use_id`, `transcript_path`, direct model) and two entry points: the full chain, and an exact-evidence-only chain (direct model, then exact record) for the completion fill; the main-agent branch moved from `diff_trace.rs` without precedence change; the subagent branch; the subagent path derivation; structured diff traces switched to one resolver call per event; fixture tests named `claude_subagent_model` (AC2, AC3, AC4, transcript cases of AC12) and `claude_transcript_bounds` (AC7, AC8). Out — mutation-scope provenance (T03), patch parts (T04), and any `claude_model_state` write for subagents. - Dependencies: T01 - Done when: AC2, AC3, AC4, AC6, AC7, and AC8 hold, and structured diff traces obtain their model only through the resolver, with one transcript scan per event. - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_subagent_model`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_transcript_bounds`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_model_attribution`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_model_state`. - - Context synchronization: pending + - Completed: 2026-11-23 + - Files changed: `cli/src/services/hooks/claude_transcript.rs`, `cli/src/services/hooks/claude_model_resolver.rs` (new), `cli/src/services/hooks/diff_trace.rs`, `cli/src/services/hooks/mod.rs`, `context/plans/claude-subagent-attribution.md` + - Result: Replaced the unbounded transcript reader with `find_claude_transcript_tool_use_model` / `find_tool_use_model_in`. It scans the last 4 MiB starting at the first complete record, drains records longer than 1 MiB without buffering them, skips non-JSON or invalid-UTF-8 records, and reports open, seek, and read failures as `ClaudeTranscriptReadError`. Added the private `hooks::claude_model_resolver` module with the concrete `ClaudeModelEvidence` struct and two entry points: `resolve_claude_model` (full chain) and `resolve_claude_model_from_exact_evidence` (direct model, then the exact record; no DB access). Main-agent precedence is unchanged: direct, main transcript, `(cc_, "")` row, then the bridge chain, keeping its existing `bridge_inherited` seed. A subagent resolves from direct model, then the exact record in the derived subagent transcript, then `NULL`. It reads no state row, uses no bridge chain, and writes nothing. `claude_subagent_transcript_path` owns the path derivation and rejects `agent_id` or session values that are not `[A-Za-z0-9_-]`. Structured diff traces now keep only the direct model at parse time and resolve once per event at persist time through `resolve_claude_model`. `resolve_claude_model_id`, `resolve_claude_model_id_with`, and `seed_diff_trace_model_from_bridge_chain` were removed from `diff_trace.rs`. + - Verify outcomes: `claude_subagent_model` 9 passed (resolver AC2–AC4 cases, missing transcript, path derivation, subagent diff-trace persist); `claude_transcript_bounds` 7 passed (window-start boundary on both sides, record cap at 1 MiB and 1 MiB + 1, skip-and-continue past oversized and malformed records, 32 MiB missing-id lookup reads ≤ 5 MiB and < 500 ms, typed open and read errors); `claude_model_attribution` 5 passed (direct > transcript > state row > bridge chain with seed, main-agent diff-trace persist); `claude_model_state` 3 passed. Also: full CLI suite 875 passed; `clippy --all-targets -D warnings` clean; `cargo fmt` applied. + - Deviation: the `claude_model_attribution` and `claude_model_state` suites named in Verify were deleted in commit `d21869ee`, so there were no existing tests to keep unchanged for AC6. New main-agent precedence tests carry the `claude_model_attribution_` prefix so that filter checks AC6. The `claude_model_state` filter matches two pre-existing setup/parse tests plus one new subagent test. + - Context impact: localized — Claude model attribution moves into one resolver, and subagent precedence and transcript bounds change. `context/sce/claude-raw-hook-capture.md` should describe the resolver, precedence, and bounds. + - Context synchronization: synced - [ ] T03: `Resolve and fill Claude mutation-scope provenance models through the shared resolver` (status:todo) - Task ID: T03 diff --git a/context/sce/agent-trace-db.md b/context/sce/agent-trace-db.md index 101d0a88f..40780042e 100644 --- a/context/sce/agent-trace-db.md +++ b/context/sce/agent-trace-db.md @@ -127,7 +127,7 @@ Per-table columns, lookup indexes, and `updated_at` triggers produced by the mig `sce hooks diff-trace` is the current runtime writer for `diff_traces`. -- The hook path validates required normalized STDIN `{ sessionID, diff, time, tool_name, tool_version }` fields and supported raw Claude structured events before persistence, with `model_id` accepted as optional (absent or `null`) and `tool_version` accepted as nullable. Raw structured Claude attribution remains `direct > exact transcript > exact session/agent state > bridge-derived chain state > NULL`: when direct and matching-transcript sources fail, the already-open repository DB is queried once for the canonical `(cc_, exact agent_id)` in the local `claude_model_state` register; normalized payloads with `tool_name="claude"` do not qualify. Missing state remains `None`; main-session missing/null agent context maps to `""`, and subagents do not inherit that scope. The separate lifecycle intake writes the register directly through the same no-migration hook-runtime DB boundary; the state is never exported or synchronized. +- The hook path validates required normalized STDIN `{ sessionID, diff, time, tool_name, tool_version }` fields and supported raw Claude structured events before persistence, with `model_id` accepted as optional (absent or `null`) and `tool_version` accepted as nullable. Raw structured Claude attribution goes through the [Claude model resolver](./claude-model-resolver.md): only a main-agent event reads the exact `(cc_, "")` `claude_model_state` row, and a subagent event never reads the register. Normalized payloads with `tool_name="claude"` do not qualify. The separate lifecycle intake writes the register directly through the same no-migration hook-runtime DB boundary; the state is never exported or synchronized. - The resolved `model_id` and direct `tool_version` pass into `DiffTraceInsert`. The stored `session_id` is tool-prefixed before insert construction: `opencode` payloads store `oc_`, `claude` structured payloads store `cc_`, `pi` normalized payloads store `pi_`, and same-tool-prefixed values are not double-prefixed. The `payload_type` field is set to `PAYLOAD_TYPE_PATCH` for `OpenCode` normalized diff-trace payloads and `PAYLOAD_TYPE_STRUCTURED` for Claude structured `PostToolUse` payloads. Claude structured intake resolves direct `model`/`model_id`/`modelId` metadata, including nested `model.id` / `model.model` / `model.name`, before optionally matching the event's `tool_use_id` in its `transcript_path` JSONL assistant-message envelopes. Direct metadata always wins; transcript access and matching fail open; either resolved source is normalized once with the `claude/` prefix; when both sources fail, persistence performs one exact local state lookup only for raw structured Claude payloads; normalized payloads do not receive that fallback, and unresolved attribution remains `NULL`. - `time` is accepted as a `u64` Unix epoch millisecond input and must fit the signed `i64` `time_ms` column before any persistence starts. - The hook inserts the parsed payload fields plus nullable event-local attribution through `RepositoryAgentTraceDb::insert_diff_trace()` without writing a parsed-payload artifact under `context/tmp`. diff --git a/context/sce/agent-trace-hooks-command-routing.md b/context/sce/agent-trace-hooks-command-routing.md index 23dc54497..80dc29ba1 100644 --- a/context/sce/agent-trace-hooks-command-routing.md +++ b/context/sce/agent-trace-hooks-command-routing.md @@ -82,11 +82,11 @@ Interactive `sce setup` persists the independent confirmations at `agent_trace.a - After Agent Trace validation and `agent_traces` persistence succeed, post-commit resolves the config-file-only `agent_trace.auto_sync` gate. When it is `true`, the hook invokes the sync-owned one-shot launcher exactly once with the repository root; the launcher starts the current `sce` executable as detached `sync --format json` work and is not awaited. Explicit `false` configuration and omitted configuration do not launch; a newly created setup config launches because it contains an explicit `true`. Validation or persistence failure reaches the existing error path before the gate. Launcher/current-executable/spawn failures are fail-open and do not change the successful post-commit result. No `pre-commit`, `diff-trace`, or `conversation-trace` path invokes automatic synchronization. - `post-rewrite` is a deterministic no-op entrypoint. - `diff-trace` reads STDIN JSON and classifies the payload: - - **Claude structured payloads** (detected by presence of top-level `hook_event_name`): the STDIN JSON is validated through `derive_claude_structured_patch`. Supported `PostToolUse` `Write` create and `Edit` structured-patch events produce a `DiffTracePayload` with `payload_type="structured"` and the raw event JSON stored as the `diff` column without conversion to unified-diff text. Model attribution is resolved with `direct > exact transcript > exact Claude state > bridge-derived chain state > NULL`: top-level `model`, `model_id`, or `modelId`, or nested `model.id`, `model.model`, or `model.name`, wins when present. Otherwise, when the event provides both `transcript_path` and `tool_use_id`, Rust scans that Claude JSONL transcript for the assistant-message envelope whose `tool_use.id` matches, skipping malformed unrelated records. Either source is normalized once with the `claude/` prefix. For these raw structured Claude payloads only, if both event-local sources are unavailable, persistence performs one exact `(cc_, agent_id)` lookup in the local `claude_model_state` register after opening the repository DB; normalized payloads with `tool_name="claude"` do not qualify. When that exact lookup also misses and the payload is in the exact main-session scope (`agent_id` empty) and carries an ephemeral `transcript_path`, persistence resolves the newest `claude_model_state` observation across the transcript's bridge-linked chain members — bounded leading-record reads of sibling `.jsonl` transcripts sharing the `bridgeSessionId`, one exact-scope `(cc_, "")` read per member, winner by greatest `observed_at_ms` with a deterministic session-ID tie-break — and, on a hit, writes one `claude_model_state` row for the current session (`source="bridge_inherited"`, `observation_kind=session_start`) through the existing guarded write path before using that model for the trace in hand. This is the only `diff-trace` resolution path that writes state; the seeded row satisfies the exact lookup on every later trace, so bridge discovery runs at most once per session. Ephemeral `agent_id` is trimmed for exact lookup, with missing/null main-session context mapped to `""`; subagents never inherit main-session state or trigger the bridge fallback. The ephemeral `transcript_path` used for this resolution is carried on `DiffTracePayload` as a `#[serde(skip)]` field and is never written to `diff_traces` or any exported payload. Missing/unreadable transcripts, unmatched tool calls, missing models, absent lookup fields, an absent or malformed bridge record, no other chain member, no member state, or a state read/write failure leave the parser's `model_id` nullable and write no state row without rejecting the hook. No polling, waiting, second selection rule, full-transcript scan, or stored-raw-event reparsing participates. Unsupported Claude events (non-`PostToolUse`, unsupported tools, invalid payloads) produce a deterministic `NoOp` success result. + - **Claude structured payloads** (detected by presence of top-level `hook_event_name`): the STDIN JSON is validated through `derive_claude_structured_patch`. Supported `PostToolUse` `Write` create and `Edit` structured-patch events produce a `DiffTracePayload` with `payload_type="structured"` and the raw event JSON stored as the `diff` column without conversion to unified-diff text. The parser extracts only the direct model (top-level `model`, `model_id`, or `modelId`, or nested `model.id`, `model.model`, or `model.name`) and carries `agent_id`, `tool_use_id`, and `transcript_path` as `#[serde(skip)]` fields that are never written to `diff_traces` or any exported payload. Persistence calls the Claude model resolver once per event after opening the repository DB: the main agent resolves `direct > exact transcript > exact (cc_, "") state > bridge-derived chain state > NULL`, and a subagent resolves `direct > exact subagent-transcript record > NULL`. The bridge step is the only `diff-trace` resolution path that writes state. A missing, unreadable, or out-of-bounds transcript, an unmatched tool call, or a failed bridge step leaves `model_id` `NULL` without rejecting the hook. Contract in [claude-model-resolver.md](./claude-model-resolver.md). Unsupported Claude events (non-`PostToolUse`, unsupported tools, invalid payloads) produce a deterministic `NoOp` success result. - **OpenCode normalized payloads** (no `hook_event_name`): existing flat `{ sessionID, diff, time, model_id?, tool_name, tool_version }` validation applies unchanged, with `payload_type="patch"`. - The `DiffTracePayload` struct carries a `payload_type: String` field consumed by `persist_diff_trace_payload_to_agent_trace_db_with` to pass the correct discriminator to `DiffTraceInsert`. - Before `DiffTraceInsert` construction, Rust prefixes the stored `diff_traces.session_id` by source tool: OpenCode normalized payloads store `oc_`, Claude structured payloads store `cc_`, Pi normalized payloads (`tool_name: "pi"`) store `pi_`, and already same-tool-prefixed values are left unchanged. Unknown `tool_name` values pass the raw session ID through unprefixed. Raw non-empty session-ID validation still happens before prefixing. - - Missing `model_id` or `tool_version` stays nullable. Claude's event-local transcript fallback is used only when direct event metadata is absent; for raw structured Claude payloads only, when both event-local sources fail, persistence consults the exact Claude lifecycle-state scope once. The resolved model and direct tool-version value are persisted after payload-specific validation/normalization, making `diff_traces.model_id` the only exported model-attribution value; `claude_model_state` remains local-only. + - Missing `model_id` or `tool_version` stays nullable. Raw structured Claude payloads resolve the model through the Claude model resolver; normalized payloads with `tool_name="claude"` keep their direct value. The resolved model and direct tool-version value are persisted after payload-specific validation/normalization, making `diff_traces.model_id` the only exported model-attribution value; `claude_model_state` remains local-only. - Persistence: resolves the current repository-scoped `RepositoryAgentTraceDb` lazily and inserts the parsed payload fields via `DiffTraceInsert` + `insert_diff_trace()` using tool-prefixed `session_id` plus nullable event-resolved `model_id` and direct `tool_version`. No parsed-payload artifact is written under `context/tmp`. - Current producers are the OpenCode agent-trace plugin and the generated Claude `sce hooks` command hooks (no TypeScript intermediary). - OpenCode forwards user-message `message` diffs with `tool_name="opencode"`, always including `model_id`, and nullable OpenCode client-version metadata. @@ -131,7 +131,7 @@ Interactive `sce setup` persists the independent confirmations at `agent_trace.a - Fail-open output for conversation-trace intake failures is `conversation-trace hook intake failed open; error logged.` so hook callers do not receive app-level classified errors or non-zero exits for intake failures. - The generated OpenCode agent-trace plugin emits this mixed-batch shape for conversation-trace handoff with `tool_name: "opencode"`: ordinary message/part events produce one-item mixed envelopes, completed question-tool parts produce `message.part` items with `part_type: "question"`, and diff-backed message events produce one envelope containing the synthetic parent `message` item plus patch `message.part` items. The Pi extension uses the same shape with `tool_name: "pi"`. - `sce hooks claude-model-state` is a local-only lifecycle intake for raw Claude `SessionStart` and `PostModelSwitch` events. It is silent; the Claude session login notice is owned by the `sce-info` hooks module ([access policy: enforcement](../cli/access-policy.md#enforcement)). A model-bearing `SessionStart` writes normalized `claude/` state, while a `PostModelSwitch` validates `from_model` and `to_model` but writes normalized `to_model`; both use canonical `cc_` plus exact optional `agent_id` scope (`""` for the main conversation). Missing or null `agent_id` means the main scope; a present string is trimmed and must remain non-empty, so malformed empty or non-string values fail open without a state write. Current Claude sources include `command`, `picker`, `sdk`, `auto`, and `resume`; SCE accepts any non-empty source string and stores it opaquely. A model-less `SessionStart` first attempts bounded, local-only bridge-session correlation through the event's `transcript_path`: it reads only leading records for the `bridgeSessionId`, then resolves the model through the same single newest-chain-observation selection rule the `diff-trace` state-miss path uses — bounded leading-record reads of sibling `.jsonl` transcripts sharing that `bridgeSessionId`, one exact-scope `(cc_, "")` read per member, winner by greatest `observed_at_ms` with a deterministic session-ID tie-break — and seeds the current session with that model as `source="bridge_inherited"` when a chain observation exists. There is no separate SessionStart selection rule and no most-recently-modified-sibling pick. Missing or malformed discovery inputs, no chain observation, filesystem races, and DB reads fail open to the existing no-op. In practice this `SessionStart` attempt fires before Claude has created the session's transcript file, so it reads nothing and always no-ops; bridge inheritance for a cleared session is actually carried by the `diff-trace` state-miss path above, and this attempt is kept only for the case Claude ever creates transcripts eagerly. The command uses the existing guarded latest-locally-observed register and local SCE observation time. The command reads and writes directly through the no-migration hook-runtime repository DB path before returning, does not migrate, sync, or access the network, and returns zero stdout bytes with logger-only fail-open diagnostics for input, clock, DB-open, DB-read, and DB-write failures. Claude's SessionStart invocation is synchronous relative to Claude execution, while PostModelSwitch is asynchronous; overlapping hooks and bridge/model-switch races are accepted and local observation time does not prove Claude causal ordering. Generated Claude settings register both lifecycle events for this command, while the existing five SCE registrations remain unchanged. Claude Code 2.1.250 and 2.1.251 compatibility smoke passed with an unknown PostModelSwitch registration, so installation remains unconditional with no raised minimum or capability gate. -- `session-model` is no longer a supported `sce hooks` subcommand and generated Claude settings no longer produce the retired generic session-model route. The `session_models` DB API/table and generic fallback are removed from active code; upgraded databases may still contain the retired table, but runtime paths no longer read or write it. The separate `sce hooks claude-model-state` command is a Claude-specific local register, and `diff-trace` consults its exact `(cc_, agent_id)` state after direct and transcript attribution fail, then — for a main-session-scope raw structured payload only — the newest observation across the transcript's bridge-linked chain, seeding a `source="bridge_inherited"` row for the current session; this remains Claude-specific and does not restore the generic abstraction. +- `session-model` is no longer a supported `sce hooks` subcommand and generated Claude settings no longer produce the retired generic session-model route. The `session_models` DB API/table and generic fallback are removed from active code; upgraded databases may still contain the retired table, but runtime paths no longer read or write it. The separate `sce hooks claude-model-state` command is a Claude-specific local register, and `diff-trace` consults, for a main-agent event only, its exact `(cc_, "")` state after direct and transcript attribution fail, then the newest observation across the transcript's bridge-linked chain, seeding a `source="bridge_inherited"` row for the current session; this remains Claude-specific and does not restore the generic abstraction. - `sce hooks codex` is a separate single dispatcher subcommand (not routed through `diff-trace`/`conversation-trace`), classifying raw Codex hook JSON internally instead. Its `UserPromptSubmit` and `Stop` arms are each a second writer into the same `messages`/`parts` tables, calling the shared `insert_conversation_text_event` atomic primitive rather than the plain `insert_messages`/`insert_parts` calls described above. Its `PostToolUse(apply_patch)` arm is a second, independent writer into `diff_traces` via the existing `insert_diff_trace`, carrying `tool_name = "codex"` and the same `cx_`-prefixed `session_id`; it is independent of the concrete Codex mutation-scope adapter. Apply_patch persistence requires a trimmed non-empty session, preserves reported model IDs without fabricating a provider prefix, and returns empty stdout on every non-policy success or fail-open path. Before persistence it resolves source and move-destination paths independently from the event `cwd` against the canonical Git root: valid `..` components and absolute-inside paths are accepted, missing Add File targets are allowed through their nearest existing prefix, and outside or symlink-escaping mappings are rejected. The existing Codex command resolves that Git root at invocation time and invokes the installed helper with quoted paths, so root and nested cwd (including spaced repository paths) share one entrypoint; its root-resolution failure remains silent and fail-open where designed. The Codex setup/doctor boundary is separate from evidence intake: `.codex/hooks.json` is merged through the shared structural `codex_hook_config` service, which preserves valid user handlers and recognizes the generated helper path plus either the `sce hooks codex` or `sce hooks codex-mutation-scope` command contract, attributing each handler to whichever it matches and merging the two contracts' registrations independently. The mutation-scope `PreToolUse`/`PostToolUse` registrations use matcher `^(Bash|apply_patch)$`; `Stop`/`Interrupt`/`SubagentStop`/`SessionEnd` are unmatched and feed the generic mutation-scope ingress ([../cli/mutation-scope-hook-ingress.md](../cli/mutation-scope-hook-ingress.md)). - `sce hooks mutation-scope` (hidden) is a separate single ingress (not routed through `diff-trace`/`conversation-trace`) that drives the mutation-scope runtime rather than writing conversation/diff evidence. It reads one normalized JSON lifecycle object from STDIN via the shared `read_hook_stdin`, strictly parses it into exactly `start`/`advance`/`close`/`flush`/`abandon`, and translates it into one `RuntimeBoundary` (`start`/`advance`/`close` → `Start`/`Advance`/`Close`; `flush` → `Flush`) passed to `mutation_trace::runtime::coordinate(...)`, or a direct `mutation_trace::runtime::abandon_scope(...)` call for `abandon`. `scope_id`/`event_id`/`actor_kind` (`claude_code`/`codex`/`opencode`/`pi`) are forwarded verbatim — no trim, prefix, hash, UUID, or timestamp — because `EventId` equality is the runtime's replay/idempotency key; `start` alone additionally accepts an optional `provenance` object (non-blank `session_id`, optional `model_id`) forwarded the same way as `RuntimeBoundary::Start`'s `StartProvenance` and, when the runtime's admission-bounded rule allows it, durably registered before the protocol commits — a row may only be created while the durable scope is still `NeverSeen`, so a `start` replayed against an already-admitted scope that has no provenance still succeeds and still persists none, while an existing row is validated on every provenance-carrying `start` and a differing `session_id` remains a hard conflict — while `advance`/`close`/`flush`/`abandon` reject the key; any `worktree_id` key is a hard rejection (worktree identity is derived by the runtime from the invoking checkout). DB acquisition is lazy: a `FnOnce` provider closure reusing `open_agent_trace_db_for_hook_runtime` is passed into `coordinate()`/`abandon_scope()` so it runs inside the runtime's protected-worktree ordering, never before. **Non-fail-open intake contract, distinct from `diff-trace`/`conversation-trace`:** a lost lifecycle boundary can change which scope stays live and therefore alter attribution, so the dispatch arm is unwrapped like `pre-commit` (no `Ok(...)` fail-open shim) and there is no dropped-boundary / `exit 0` branch. Results are classified by durable completion — a malformed payload or any pre-completion `CoordinateError`/`AbandonScopeError` returns `CliError`/non-zero; `CoordinateError::MarkerClearAfterCommit` and `AbandonScopeError::MarkerClearAfterCompletion` are the two carried-outcome success variants (the durable transition already succeeded and only the trailing external-taint marker cleanup failed), reported as empty-stdout `Ok` with the failure logged via `sce.hooks.mutation_scope.marker_clear_after_durable_completion` and the transition **not** retried. Every successful execution emits empty stdout with no serialized outcome/revision/worktree/scope state. It writes `mutation_trace_*` rows only — never `diff_traces`, `post_commit_patch_intersections`, or `agent_traces`. A first Claude Code adapter driver now consumes it in-process (see below); the Codex adapter also consumes it in-process, while OpenCode and Pi still have no lifecycle adapter. See [mutation-scope-hook-ingress.md](../cli/mutation-scope-hook-ingress.md) for the full contract. - `sce hooks claude-mutation-scope` (hidden) is the first concrete harness adapter targeting the mutation-scope runtime: it reads one raw Claude hook JSON event from STDIN, classifies the tool, and drives `mutation_scope::run_mutation_scope_from_payload` (the same in-process `pub(crate)` seam above, called directly — not by re-invoking `sce hooks mutation-scope`) to `start`/`close`/`abandon`/`flush` a scope per event. The dispatch arm is unwrapped like `mutation-scope`, not fail-open. Registered by `sce setup` (`config/pkl/renderers/claude-content.pkl`) for `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionDenied`, `UserPromptSubmit`, `Stop`, `StopFailure`, `SubagentStop`, `SessionEnd`, and `WorktreeRemove`, with no `matcher` (the adapter classifies tools in Rust), so a real Claude Code session now reaches it. Full contract, event mapping, and design rationale are in [../cli/claude-mutation-scope-integration.md](../cli/claude-mutation-scope-integration.md). diff --git a/context/sce/claude-model-resolver.md b/context/sce/claude-model-resolver.md new file mode 100644 index 000000000..fd8463b6c --- /dev/null +++ b/context/sce/claude-model-resolver.md @@ -0,0 +1,97 @@ +# Claude Model Resolver + +`cli/src/services/hooks/claude_model_resolver.rs` is the one module that resolves +the model of a Claude hook event. Decision: +[`2026-11-23-claude-subagent-attribution`](../decisions/2026-11-23-claude-subagent-attribution.md). + +## Evidence + +The resolver takes one concrete `ClaudeModelEvidence` struct: + +- `session_id`: the canonical `cc_`. +- `agent_id`: present only for a subagent event. +- `tool_use_id`, `transcript_path`, and `direct_model_id`: copied from the event. + +The module adds no trait, provider interface, or injection seam. + +## Entry points + +- `resolve_claude_model(db, evidence)` runs the full chain. +- `resolve_claude_model_from_exact_evidence(evidence)` runs only the direct + model step and the exact-record step. It has no database access. + +Each model source is normalized once with the `claude/` prefix. + +```mermaid +flowchart TD + A[direct event model] -->|missing| B[exact tool_use_id record in the event's transcript] + B -->|missing| C{agent_id present?} + C -->|yes: subagent| N[NULL] + C -->|no: main agent| D["(cc_session, '') claude_model_state row"] + D -->|missing| E[bridge-session chain, seeds a bridge_inherited row] + E -->|missing| N +``` + +## Main-agent precedence + +An event without `agent_id` resolves in this order: + +1. The direct event model. +2. The exact `tool_use_id` record in the main transcript. +3. The exact `(cc_, "")` `claude_model_state` row. +4. The bridge-session chain. On a hit, the resolver writes one + `claude_model_state` row for the session with `source="bridge_inherited"`. + This is the only write the resolver makes. +5. `NULL`. + +## Subagent precedence + +An event with `agent_id` resolves in this order: + +1. The direct event model. +2. The exact `tool_use_id` record in the subagent transcript. +3. `NULL`. + +A subagent event never reads `claude_model_state`, never uses the bridge-session +chain, and writes no state row. A record that does not name the event's +`tool_use_id` never attributes the event. After a model switch, each event +resolves to the model on its own tool-call record. An event whose record is not +yet written resolves to `NULL`. + +## Subagent transcript path + +`claude_subagent_transcript_path` is the one function that derives the subagent +transcript path: +`//subagents/agent-.jsonl`. +When the event `transcript_path` already names that file, the function returns +it unchanged. The function returns no path when the session ID (without `cc_`) +or the `agent_id` contains a character outside `[A-Za-z0-9_-]`. + +## Transcript bounds + +`claude_transcript::find_claude_transcript_tool_use_model` reads the transcript. +Its generic core `find_tool_use_model_in` serves fixture tests. + +- It scans at most the last 4 MiB (`CLAUDE_TRANSCRIPT_TAIL_WINDOW_BYTES`). The + scan starts at the first complete record inside that window. +- It skips a record longer than 1 MiB (`CLAUDE_TRANSCRIPT_MAX_RECORD_BYTES`) + without buffering it, and continues with the next record. +- It skips a record that is not valid UTF-8 JSON and continues. +- It returns the model of the first assistant record whose content has a + `tool_use` block with the event's `tool_use_id`. +- It reports an open, seek, or read failure as `ClaudeTranscriptReadError`. The + resolver maps every reader error to `NULL`. + +A lookup reads no more than the window plus one capped record. An exact record +more than 4 MiB from the end, or longer than 1 MiB, resolves to `NULL` at the +transcript step. A main-agent event then continues to the state and bridge +steps. + +## Consumers + +- Structured Claude `diff-trace` keeps only the direct model at parse time. At + persist time it calls `resolve_claude_model` once per event. See + [agent-trace-hooks-command-routing.md](./agent-trace-hooks-command-routing.md). +- Mutation-scope provenance admission does not use the resolver. It calls + `claude_model_state_by_session_and_agent` directly in + `claude_mutation_scope/lifecycle.rs`. diff --git a/context/sce/claude-raw-hook-capture.md b/context/sce/claude-raw-hook-capture.md index 9731f4987..26dfe6e67 100644 --- a/context/sce/claude-raw-hook-capture.md +++ b/context/sce/claude-raw-hook-capture.md @@ -2,11 +2,11 @@ ## Removal summary -The `sce hooks claude-capture ` CLI route, `ClaudeCaptureEvent`, `HookSubcommand::ClaudeCapture`, the `claude_transcript.rs` enrichment module, and `RepoPaths::claude_capture_tmp_dir()` were removed in T05 of the `claude-typescript-model-cache-remove-rust-capture` plan. +The `sce hooks claude-capture ` CLI route, `ClaudeCaptureEvent`, `HookSubcommand::ClaudeCapture`, the former `claude_transcript.rs` enrichment module (the current `claude_transcript.rs` is the bounded transcript reader used by the Claude model resolver), and `RepoPaths::claude_capture_tmp_dir()` were removed in T05 of the `claude-typescript-model-cache-remove-rust-capture` plan. Rust now exposes these active intakes for Claude/OpenCode editor runtimes: -- `sce hooks diff-trace` — STDIN JSON intake for OpenCode normalized or Claude structured diff-trace payloads with optional/nullable direct attribution. Rust persists direct payload-derived `model_id` and `tool_version` values as-is; Claude model metadata is extracted best-effort from the raw `PostToolUse` event and falls back to exact transcript and Claude lifecycle state when available. The state fallback is Claude-specific and does not restore the generic session-level abstraction. +- `sce hooks diff-trace` — STDIN JSON intake for OpenCode normalized or Claude structured diff-trace payloads with optional/nullable direct attribution. Rust persists direct payload-derived `model_id` and `tool_version` values as-is; Claude model metadata is resolved by the [Claude model resolver](./claude-model-resolver.md), which does not restore the generic session-level abstraction. - `sce hooks conversation-trace` — STDIN JSON intake for normalized mixed-batch message/part payloads and supported raw Claude `UserPromptSubmit`, `Stop`, and `PostToolUse` events. Runtime intake failures log `sce.hooks.conversation_trace.error` and fail open to the hook producer. `sce hooks session-model` is no longer supported. Generated Claude settings register `SessionStart` for local model-state attribution only and newly register `PostModelSwitch`; neither event is part of the removed raw-capture route. @@ -29,7 +29,7 @@ The generated Claude TypeScript runtime at `config/.claude/plugins/sce-agent-tra - Generated `.claude/settings.json` also registers the hidden `sce hooks claude-mutation-scope` mutation-scope adapter through the same Bash helper, with **no** `matcher`, on `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionDenied`, `UserPromptSubmit`, `Stop`, `StopFailure`, `SubagentStop`, `SessionEnd`, and `WorktreeRemove`. These are additional entries alongside the model-state, bash-policy, `diff-trace`, and `conversation-trace` registrations, not replacements, and still do not restore raw event capture (the adapter drives the mutation-cursor runtime, writing `mutation_trace_*` rows only). Full contract in [../cli/claude-mutation-scope-integration.md](../cli/claude-mutation-scope-integration.md). - The former Claude TypeScript runtime at `config/.claude/plugins/sce-agent-trace.ts` was removed in T07 of the `claude-rust-diff-trace` plan. - Rust owns normalized persistence: `diff-trace` inserts into `diff_traces` with `payload_type` classification (`"patch"` for OpenCode, `"structured"` for Claude), while `conversation-trace` inserts normalized messages/parts. -- Claude `diff-trace` attempts best-effort direct `model_id` extraction from the raw `PostToolUse` payload, then exact transcript lookup and exact Claude lifecycle-state lookup, storing the resulting nullable attribution in `diff_traces`; OpenCode sends `model_id` directly and may send nullable `tool_version`. Missing metadata is persisted as `NULL`; Claude lifecycle state is local-only and is not a generic session cache. +- Claude `diff-trace` stores the nullable model from the [Claude model resolver](./claude-model-resolver.md) in `diff_traces`; OpenCode sends `model_id` directly and may send nullable `tool_version`. Missing metadata is persisted as `NULL`; Claude lifecycle state is local-only and is not a generic session cache. - No raw Claude hook payload artifacts are written by TypeScript or Rust. See also: [agent-trace-hooks-command-routing.md](./agent-trace-hooks-command-routing.md), [../context-map.md](../context-map.md) From 5929201f7cf5619045072bfca4897228696bd4d2 Mon Sep 17 00:00:00 2001 From: David Abram Date: Mon, 23 Nov 2026 16:16:29 +0100 Subject: [PATCH 4/6] hooks: Fill Claude mutation-scope provenance at completion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude mutation-scope admission now resolves model evidence through the shared resolver, while PostToolUse boundaries can fill a NULL model from exact direct or transcript evidence after durable close. Add the conditional store update, fail-open lifecycle handling, and regressions for precedence, idempotence, and missing evidence. Plan: `claude-subagent-attribution` — T03 Co-authored-by: SCE --- .../hooks/claude_mutation_scope/events.rs | 31 ++ .../hooks/claude_mutation_scope/lifecycle.rs | 123 ++++-- .../hooks/claude_mutation_scope/mod.rs | 3 + .../provenance_fill_tests.rs | 371 ++++++++++++++++++ cli/src/services/mutation_trace/store.rs | 105 +++++ .../cli/claude-mutation-scope-integration.md | 20 +- context/cli/mutation-scope-provenance.md | 55 ++- context/context-map.md | 4 +- context/glossary.md | 2 +- context/plans/claude-subagent-attribution.md | 10 +- context/sce/claude-model-resolver.md | 8 +- 11 files changed, 660 insertions(+), 72 deletions(-) create mode 100644 cli/src/services/hooks/claude_mutation_scope/provenance_fill_tests.rs diff --git a/cli/src/services/hooks/claude_mutation_scope/events.rs b/cli/src/services/hooks/claude_mutation_scope/events.rs index 1191fa1ca..d1d357ed6 100644 --- a/cli/src/services/hooks/claude_mutation_scope/events.rs +++ b/cli/src/services/hooks/claude_mutation_scope/events.rs @@ -1,6 +1,11 @@ +use std::path::PathBuf; + use anyhow::{anyhow, bail, Context, Result}; use serde_json::{Map, Value}; +use crate::services::hooks; +use crate::services::hooks::claude_model_resolver::ClaudeModelEvidence; + pub(super) const HOOK_EVENT_NAME_FIELD: &str = "hook_event_name"; pub(super) const SESSION_ID_FIELD: &str = "session_id"; pub(super) const CWD_FIELD: &str = "cwd"; @@ -12,6 +17,7 @@ pub(super) const RUN_IN_BACKGROUND_FIELD: &str = "run_in_background"; pub(super) const PROMPT_ID_FIELD: &str = "prompt_id"; pub(super) const AGENT_TYPE_FIELD: &str = "agent_type"; pub(super) const WORKTREE_PATH_FIELD: &str = "worktree_path"; +pub(super) const TRANSCRIPT_PATH_FIELD: &str = "transcript_path"; pub(super) const HOOK_EVENT_PRE_TOOL_USE: &str = "PreToolUse"; pub(super) const HOOK_EVENT_POST_TOOL_USE: &str = "PostToolUse"; @@ -49,6 +55,8 @@ pub(crate) struct ClaudeToolIdentity { pub agent_id: Option, pub tool_name: String, pub tool_use_id: String, + pub transcript_path: Option, + pub direct_model_id: Option, } impl ClaudeToolIdentity { @@ -59,6 +67,19 @@ impl ClaudeToolIdentity { tool_use_id: self.tool_use_id.clone(), } } + + pub(crate) fn model_evidence(&self) -> ClaudeModelEvidence { + ClaudeModelEvidence { + session_id: hooks::prefixed_diff_trace_session_id( + hooks::CLAUDE_TOOL_NAME, + &self.session_id, + ), + agent_id: self.agent_id.clone(), + tool_use_id: Some(self.tool_use_id.clone()), + transcript_path: self.transcript_path.as_deref().map(PathBuf::from), + direct_model_id: self.direct_model_id.clone(), + } + } } #[derive(Clone, Debug, Eq, PartialEq)] @@ -202,6 +223,8 @@ pub(super) fn parse_tool_identity(object: &Map) -> Result, field: &str) -> Option { + object + .get(field) + .and_then(Value::as_str) + .filter(|value| !value.trim().is_empty()) + .map(str::to_owned) +} + pub(super) fn validation_error(detail: &str) -> String { format!("Invalid Claude hook event payload from STDIN: {detail}.") } diff --git a/cli/src/services/hooks/claude_mutation_scope/lifecycle.rs b/cli/src/services/hooks/claude_mutation_scope/lifecycle.rs index eebf1cafb..920269ecd 100644 --- a/cli/src/services/hooks/claude_mutation_scope/lifecycle.rs +++ b/cli/src/services/hooks/claude_mutation_scope/lifecycle.rs @@ -2,9 +2,15 @@ use std::path::{Path, PathBuf}; use anyhow::Result; +use crate::services::agent_trace_db::repository::RepositoryAgentTraceDb; use crate::services::hooks; +use crate::services::hooks::claude_model_resolver::{ + resolve_claude_model, resolve_claude_model_from_exact_evidence, ClaudeModelEvidence, +}; use crate::services::managed_telemetry::trace_export::{in_child_span, ManagedChildSpan}; use crate::services::mutation_trace::runtime::resolve_git_dir; +use crate::services::mutation_trace::store::{MutationTraceStore, ScopeProvenanceModelFill}; +use crate::services::mutation_trace::types::ScopeId; use super::events::BASH_TOOL_NAME; use super::state; @@ -26,6 +32,8 @@ pub(super) const PRE_TOOL_USE_FAIL_CLOSED_EVENT: &str = "sce.hooks.claude_mutation_scope.pre_tool_use_fail_closed"; pub(super) const MODEL_STATE_UNAVAILABLE_EVENT: &str = "sce.hooks.claude_mutation_scope.model_state_unavailable"; +pub(super) const PROVENANCE_MODEL_FILL_FAILED_EVENT: &str = + "sce.hooks.claude_mutation_scope.provenance_model_fill_failed"; pub(super) fn log_pre_tool_use_fail_closed( logger: Option<&L>, @@ -62,16 +70,13 @@ pub(crate) async fn run_claude_mutation_scope_from_payload< logger: Option<&L>, ) -> Result { let resolve_git_dir_fn = async |cwd: &str| resolve_git_dir(Path::new(cwd)).await; - let model_state_resolver = async |repository_root: &Path, session_id: &str, agent_id: &str| { + let model_state_resolver = async |repository_root: &Path, evidence: &ClaudeModelEvidence| { let db = hooks::open_agent_trace_db_for_hook_runtime( repository_root, "Failed to open Agent Trace DB for Claude mutation-scope model resolution.", ) .await?; - Ok(db - .claude_model_state_by_session_and_agent(session_id, agent_id) - .await? - .map(|state| state.model_id)) + resolve_claude_model(&db, evidence).await }; let seam_fn = async |repository_root: &Path, payload: &str, logger: Option<&L>| { hooks::mutation_scope::run_mutation_scope_from_payload(repository_root, payload, logger) @@ -94,7 +99,7 @@ pub(super) async fn run_claude_mutation_scope_from_payload_with_resolver< stdin_payload: &str, logger: Option<&L>, resolve_git_dir: &impl std::ops::AsyncFn(&str) -> Result, - model_state_resolver: &impl std::ops::AsyncFn(&Path, &str, &str) -> Result>, + model_state_resolver: &impl std::ops::AsyncFn(&Path, &ClaudeModelEvidence) -> Result>, seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, ) -> Result { let event = parse_claude_hook_event(stdin_payload)?; @@ -121,7 +126,7 @@ pub(super) async fn dispatch_claude_hook_event< event: ClaudeHookEvent, logger: Option<&L>, resolve_git_dir: &impl std::ops::AsyncFn(&str) -> Result, - model_state_resolver: &impl std::ops::AsyncFn(&Path, &str, &str) -> Result>, + model_state_resolver: &impl std::ops::AsyncFn(&Path, &ClaudeModelEvidence) -> Result>, seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, ) -> Result { match event { @@ -136,14 +141,7 @@ pub(super) async fn dispatch_claude_hook_event< ClaudeHookEvent::PostToolUse(identity) | ClaudeHookEvent::PostToolUseFailure(identity) => { let git_dir = resolve_git_dir(&identity.cwd).await?; let repository_root = Path::new(&identity.cwd); - handle_close( - &git_dir, - repository_root, - &identity.attempt_key(), - logger, - seam, - ) - .await + handle_close(&git_dir, repository_root, &identity, logger, seam).await } ClaudeHookEvent::PermissionDenied(identity) => { let git_dir = resolve_git_dir(&identity.cwd).await?; @@ -208,7 +206,7 @@ pub(super) async fn handle_pre_tool_use, resolve_git_dir: &impl std::ops::AsyncFn(&str) -> Result, - model_state_resolver: &impl std::ops::AsyncFn(&Path, &str, &str) -> Result>, + model_state_resolver: &impl std::ops::AsyncFn(&Path, &ClaudeModelEvidence) -> Result>, seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, ) -> String { let identity = &execution.identity; @@ -318,34 +316,31 @@ pub(super) async fn establish_start, - model_state_resolver: &impl std::ops::AsyncFn(&Path, &str, &str) -> Result>, + model_state_resolver: &impl std::ops::AsyncFn(&Path, &ClaudeModelEvidence) -> Result>, seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, ) -> Result<()> { let allocated = state::allocate_attempt(git_dir, &identity.attempt_key(), &identity.tool_name).await?; let scope_id = &allocated.attempt.scope_id; - let canonical_session_id = - hooks::prefixed_diff_trace_session_id(hooks::CLAUDE_TOOL_NAME, &identity.session_id); - let agent_id = identity.agent_id.as_deref().unwrap_or(""); - let model_id = - match model_state_resolver(repository_root, &canonical_session_id, agent_id).await { - Ok(model_id) => model_id.and_then(|model| hooks::normalize_claude_model_id(&model)), - Err(error) => { - if let Some(log) = logger { - log.warn( - MODEL_STATE_UNAVAILABLE_EVENT, - &error.to_string(), - &[("agent_id", agent_id)], - Some(&canonical_session_id), - ); - } - None + let evidence = identity.model_evidence(); + let model_id = match model_state_resolver(repository_root, &evidence).await { + Ok(model_id) => model_id.and_then(|model| hooks::normalize_claude_model_id(&model)), + Err(error) => { + if let Some(log) = logger { + log.warn( + MODEL_STATE_UNAVAILABLE_EVENT, + &error.to_string(), + &[("agent_id", identity.agent_id.as_deref().unwrap_or(""))], + Some(&evidence.session_id), + ); } - }; + None + } + }; let start_payload = scope_start_payload( scope_id, &claude_scope_start_event_id(scope_id), - &canonical_session_id, + &evidence.session_id, model_id.as_deref(), ); @@ -357,15 +352,16 @@ pub(super) async fn establish_start( git_dir: &Path, repository_root: &Path, - key: &AttemptKey, + identity: &ClaudeToolIdentity, logger: Option<&L>, seam: &impl std::ops::AsyncFn(&Path, &str, Option<&L>) -> Result, ) -> Result { + let key = identity.attempt_key(); let current = state::read_state(git_dir).await?; let Some(attempt) = current .attempts .iter() - .find(|attempt| attempt_matches_key(attempt, key)) + .find(|attempt| attempt_matches_key(attempt, &key)) .cloned() else { return Ok(String::new()); @@ -383,6 +379,8 @@ pub(super) async fn handle_close( + repository_root: &Path, + scope_id: &str, + identity: &ClaudeToolIdentity, + logger: Option<&L>, +) { + let evidence = identity.model_evidence(); + let filled = async { + let mut db = hooks::open_agent_trace_db_for_hook_runtime( + repository_root, + "Failed to open Agent Trace DB for Claude mutation-scope provenance model fill.", + ) + .await?; + fill_claude_scope_provenance_model(&mut db, scope_id, &evidence).await + } + .await; + + if let (Err(error), Some(log)) = (filled, logger) { + log.warn( + PROVENANCE_MODEL_FILL_FAILED_EVENT, + &error.to_string(), + &[("scope_id", scope_id)], + Some(&evidence.session_id), + ); + } +} + +pub(super) async fn fill_claude_scope_provenance_model( + db: &mut RepositoryAgentTraceDb, + scope_id: &str, + evidence: &ClaudeModelEvidence, +) -> Result> { + let scope_id = ScopeId(scope_id.to_owned()); + let store = MutationTraceStore::new(db); + match store.load_scope_provenance(&scope_id).await? { + None => return Ok(Some(ScopeProvenanceModelFill::NoRow)), + Some(stored) if stored.model_id.is_some() => { + return Ok(Some(ScopeProvenanceModelFill::AlreadySet)); + } + Some(_) => {} + } + + let Some(model_id) = resolve_claude_model_from_exact_evidence(evidence) else { + return Ok(None); + }; + store + .fill_null_scope_provenance_model(&scope_id, &model_id) + .await + .map(Some) +} + pub(super) async fn handle_permission_denied( git_dir: &Path, repository_root: &Path, diff --git a/cli/src/services/hooks/claude_mutation_scope/mod.rs b/cli/src/services/hooks/claude_mutation_scope/mod.rs index 3a93ed92d..924f23f79 100644 --- a/cli/src/services/hooks/claude_mutation_scope/mod.rs +++ b/cli/src/services/hooks/claude_mutation_scope/mod.rs @@ -53,3 +53,6 @@ use payload::{ abandon_payload, flush_payload, pre_tool_use_deny_json, scope_boundary_payload, scope_start_payload, }; + +#[cfg(test)] +mod provenance_fill_tests; diff --git a/cli/src/services/hooks/claude_mutation_scope/provenance_fill_tests.rs b/cli/src/services/hooks/claude_mutation_scope/provenance_fill_tests.rs new file mode 100644 index 000000000..38f92ddf7 --- /dev/null +++ b/cli/src/services/hooks/claude_mutation_scope/provenance_fill_tests.rs @@ -0,0 +1,371 @@ +use std::cell::RefCell; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use anyhow::Result; +use serde_json::Value; + +use crate::services::agent_trace_db::repository::RepositoryAgentTraceDb; +use crate::services::agent_trace_db::{ClaudeModelStateObservation, ObservationKind}; +use crate::services::error::CliError; +use crate::services::hooks::claude_model_resolver::{resolve_claude_model, ClaudeModelEvidence}; +use crate::services::mutation_trace::store::{ + MutationTraceStore, ScopeProvenance, ScopeProvenanceModelFill, +}; +use crate::services::mutation_trace::types::{ActorKind, ScopeId, TreeId, WorktreeId}; +use crate::services::observability::traits::Logger; + +use super::lifecycle::{ + establish_start, fill_claude_scope_provenance_model, handle_close, + PROVENANCE_MODEL_FILL_FAILED_EVENT, +}; +use super::{state, ClaudeToolIdentity}; + +const SESSION: &str = "7d1e9b20-aaaa-4bbb-8ccc-1234567890ab"; +const CANONICAL_SESSION: &str = "cc_7d1e9b20-aaaa-4bbb-8ccc-1234567890ab"; +const AGENT: &str = "f00dfeed1234"; +const TOOL_USE: &str = "toolu_write_1"; +const HAIKU: &str = "claude-haiku-5-5"; +const OPUS: &str = "claude-opus-5-5"; +const MAIN_MODEL: &str = "claude-sonnet-5-5"; + +#[derive(Default)] +struct RecordingLogger { + warning_events: Mutex>, +} + +impl Logger for RecordingLogger { + fn info(&self, _: &str, _: &str, _: &[(&str, &str)], _: Option<&str>) {} + fn debug(&self, _: &str, _: &str, _: &[(&str, &str)], _: Option<&str>) {} + fn warn(&self, event_id: &str, _: &str, _: &[(&str, &str)], _: Option<&str>) { + self.warning_events + .lock() + .unwrap() + .push(event_id.to_owned()); + } + fn error(&self, _: &str, _: &str, _: &[(&str, &str)], _: Option<&str>) {} + fn log_cli_error(&self, _: &CliError, _: Option<&str>) {} +} + +struct Fixture { + dir: tempfile::TempDir, + db: RepositoryAgentTraceDb, +} + +impl Fixture { + async fn new() -> Self { + let dir = tempfile::tempdir().expect("temp dir"); + std::fs::create_dir_all(dir.path().join("project")).expect("project dir"); + std::fs::create_dir_all(dir.path().join("git")).expect("git dir"); + let db = RepositoryAgentTraceDb::new_at(dir.path().join("agent-trace.db")) + .await + .expect("db"); + Self { dir, db } + } + + fn git_dir(&self) -> PathBuf { + self.dir.path().join("git") + } + + fn repository_root(&self) -> PathBuf { + self.dir.path().join("not-a-repository") + } + + fn main_transcript(&self) -> PathBuf { + self.dir + .path() + .join("project") + .join(format!("{SESSION}.jsonl")) + } + + fn subagent_transcript(&self) -> PathBuf { + self.dir + .path() + .join("project") + .join(SESSION) + .join("subagents") + .join(format!("agent-{AGENT}.jsonl")) + } + + fn identity(&self, agent_id: Option<&str>) -> ClaudeToolIdentity { + ClaudeToolIdentity { + session_id: SESSION.to_owned(), + cwd: self.repository_root().display().to_string(), + agent_id: agent_id.map(str::to_owned), + tool_name: String::from("Write"), + tool_use_id: TOOL_USE.to_owned(), + transcript_path: Some(self.main_transcript().display().to_string()), + direct_model_id: None, + } + } + + async fn seed_main_agent_state(&self) { + self.db + .upsert_claude_model_state(ClaudeModelStateObservation { + session_id: CANONICAL_SESSION.to_owned(), + agent_id: String::new(), + model_id: MAIN_MODEL.to_owned(), + observation_kind: ObservationKind::SessionStart, + source: String::from("startup"), + observed_at_ms: 1_000, + }) + .await + .expect("seed main-agent state"); + } + + async fn admit(&mut self, identity: &ClaudeToolIdentity) -> ScopeId { + let payloads = RefCell::new(Vec::::new()); + let db = &self.db; + let resolver = async |_: &Path, evidence: &ClaudeModelEvidence| { + resolve_claude_model(db, evidence).await + }; + let seam = async |_: &Path, payload: &str, _: Option<&RecordingLogger>| -> Result { + payloads.borrow_mut().push(payload.to_owned()); + Ok(String::new()) + }; + establish_start( + &self.git_dir(), + &self.repository_root(), + identity, + None::<&RecordingLogger>, + &resolver, + &seam, + ) + .await + .expect("establish start"); + + let start: Value = + serde_json::from_str(&payloads.borrow()[0]).expect("start payload is JSON"); + let scope_id = ScopeId(start["scope_id"].as_str().unwrap().to_owned()); + let provenance = ScopeProvenance { + scope_id: scope_id.clone(), + session_id: start["provenance"]["session_id"] + .as_str() + .unwrap() + .to_owned(), + model_id: start["provenance"]["model_id"].as_str().map(str::to_owned), + }; + + let worktree = WorktreeId(String::from("main")); + let store = MutationTraceStore::new(&mut self.db); + store + .initialize_worktree(&worktree, &TreeId(String::from("tree-0"))) + .await + .expect("worktree"); + store + .register_scope(&scope_id, &worktree, ActorKind::ClaudeCode) + .await + .expect("scope"); + store + .register_scope_provenance(&provenance) + .await + .expect("provenance"); + scope_id + } + + async fn complete( + &mut self, + scope_id: &ScopeId, + identity: &ClaudeToolIdentity, + ) -> Option { + fill_claude_scope_provenance_model(&mut self.db, &scope_id.0, &identity.model_evidence()) + .await + .expect("fill") + } + + async fn stored(&mut self, scope_id: &ScopeId) -> ScopeProvenance { + MutationTraceStore::new(&mut self.db) + .load_scope_provenance(scope_id) + .await + .expect("load provenance") + .expect("provenance row") + } + + async fn state_row_count(&self) -> usize { + self.db + .query_map("SELECT session_id FROM claude_model_state", (), |row| { + Ok(row.get::(0)?) + }) + .await + .expect("state rows") + .len() + } +} + +fn write_transcript(path: &Path, records: &[String]) { + std::fs::create_dir_all(path.parent().unwrap()).expect("transcript dir"); + let mut contents = records.join("\n"); + contents.push('\n'); + std::fs::write(path, contents).expect("write transcript"); +} + +fn tool_use(tool_use_id: &str, model: &str) -> String { + serde_json::json!({ + "type": "assistant", + "isSidechain": true, + "agentId": AGENT, + "message": { + "role": "assistant", + "model": model, + "content": [{"type": "tool_use", "id": tool_use_id, "name": "Write"}] + } + }) + .to_string() +} + +fn claude(model: &str) -> String { + format!("claude/{model}") +} + +#[tokio::test] +async fn claude_provenance_fill_keeps_model_admitted_from_exact_record() { + let mut fixture = Fixture::new().await; + let identity = fixture.identity(Some(AGENT)); + write_transcript(&fixture.subagent_transcript(), &[tool_use(TOOL_USE, HAIKU)]); + + let scope_id = fixture.admit(&identity).await; + assert_eq!( + fixture.stored(&scope_id).await.model_id, + Some(claude(HAIKU)) + ); + + write_transcript(&fixture.subagent_transcript(), &[tool_use(TOOL_USE, OPUS)]); + let outcome = fixture.complete(&scope_id, &identity).await; + + assert_eq!(outcome, Some(ScopeProvenanceModelFill::AlreadySet)); + let stored = fixture.stored(&scope_id).await; + assert_eq!(stored.model_id, Some(claude(HAIKU))); + assert_eq!(stored.session_id, CANONICAL_SESSION); +} + +#[tokio::test] +async fn claude_provenance_fill_sets_model_when_record_appears_by_completion() { + let mut fixture = Fixture::new().await; + fixture.seed_main_agent_state().await; + let identity = fixture.identity(Some(AGENT)); + write_transcript( + &fixture.subagent_transcript(), + &[tool_use("toolu_earlier", OPUS)], + ); + + let scope_id = fixture.admit(&identity).await; + assert_eq!(fixture.stored(&scope_id).await.model_id, None); + + write_transcript( + &fixture.subagent_transcript(), + &[tool_use("toolu_earlier", OPUS), tool_use(TOOL_USE, HAIKU)], + ); + let outcome = fixture.complete(&scope_id, &identity).await; + + assert_eq!(outcome, Some(ScopeProvenanceModelFill::Filled)); + let stored = fixture.stored(&scope_id).await; + assert_eq!(stored.model_id, Some(claude(HAIKU))); + assert_eq!(stored.session_id, CANONICAL_SESSION); + assert_eq!(fixture.state_row_count().await, 1); +} + +#[tokio::test] +async fn claude_provenance_fill_leaves_null_when_record_is_missing_at_both_boundaries() { + let mut fixture = Fixture::new().await; + let identity = fixture.identity(Some(AGENT)); + write_transcript( + &fixture.subagent_transcript(), + &[tool_use("toolu_other", OPUS)], + ); + + let scope_id = fixture.admit(&identity).await; + let outcome = fixture.complete(&scope_id, &identity).await; + + assert_eq!(outcome, None); + assert_eq!(fixture.stored(&scope_id).await.model_id, None); +} + +#[tokio::test] +async fn claude_provenance_fill_never_overwrites_a_stored_model() { + let mut fixture = Fixture::new().await; + let identity = ClaudeToolIdentity { + direct_model_id: Some(OPUS.to_owned()), + ..fixture.identity(Some(AGENT)) + }; + let scope_id = fixture.admit(&identity).await; + assert_eq!(fixture.stored(&scope_id).await.model_id, Some(claude(OPUS))); + + write_transcript(&fixture.subagent_transcript(), &[tool_use(TOOL_USE, HAIKU)]); + let completion = ClaudeToolIdentity { + direct_model_id: None, + ..identity + }; + let outcome = fixture.complete(&scope_id, &completion).await; + + assert_eq!(outcome, Some(ScopeProvenanceModelFill::AlreadySet)); + assert_eq!(fixture.stored(&scope_id).await.model_id, Some(claude(OPUS))); +} + +#[tokio::test] +async fn claude_provenance_fill_ignores_model_state_and_bridge_chain() { + let mut fixture = Fixture::new().await; + let identity = fixture.identity(None); + write_transcript(&fixture.main_transcript(), &[tool_use("toolu_other", OPUS)]); + let scope_id = fixture.admit(&identity).await; + assert_eq!(fixture.stored(&scope_id).await.model_id, None); + + fixture.seed_main_agent_state().await; + let outcome = fixture.complete(&scope_id, &identity).await; + + assert_eq!(outcome, None); + assert_eq!(fixture.stored(&scope_id).await.model_id, None); +} + +#[tokio::test] +async fn claude_provenance_fill_failure_does_not_fail_close() { + let fixture = Fixture::new().await; + let identity = fixture.identity(Some(AGENT)); + let git_dir = fixture.git_dir(); + let allocated = state::allocate_attempt(&git_dir, &identity.attempt_key(), "Write") + .await + .expect("allocate"); + state::mark_active(&git_dir, &allocated.attempt.scope_id) + .await + .expect("mark active"); + let operations = RefCell::new(Vec::::new()); + let seam = async |_: &Path, payload: &str, _: Option<&RecordingLogger>| -> Result { + let payload: Value = serde_json::from_str(payload)?; + operations + .borrow_mut() + .push(payload["operation"].as_str().unwrap_or_default().to_owned()); + Ok(String::new()) + }; + let logger = RecordingLogger::default(); + + let output = handle_close( + &git_dir, + &fixture.repository_root(), + &identity, + Some(&logger), + &seam, + ) + .await + .expect("close succeeds"); + let duplicate = handle_close( + &git_dir, + &fixture.repository_root(), + &identity, + Some(&logger), + &seam, + ) + .await + .expect("duplicate close succeeds"); + + assert_eq!(output, ""); + assert_eq!(duplicate, ""); + assert_eq!(*operations.borrow(), vec![String::from("close")]); + assert!(state::read_state(&git_dir) + .await + .expect("state") + .attempts + .is_empty()); + assert_eq!( + *logger.warning_events.lock().unwrap(), + vec![PROVENANCE_MODEL_FILL_FAILED_EVENT.to_owned()] + ); +} diff --git a/cli/src/services/mutation_trace/store.rs b/cli/src/services/mutation_trace/store.rs index e5a181730..0ad142244 100644 --- a/cli/src/services/mutation_trace/store.rs +++ b/cli/src/services/mutation_trace/store.rs @@ -259,6 +259,9 @@ const INSERT_SCOPE_PROVENANCE_IF_ABSENT_SQL: &str = "INSERT INTO mutation_trace_scope_provenance (scope_id, session_id, model_id) VALUES (?1, ?2, ?3) ON CONFLICT (scope_id) DO NOTHING"; +const FILL_NULL_SCOPE_PROVENANCE_MODEL_SQL: &str = + "UPDATE mutation_trace_scope_provenance SET model_id = ?1 + WHERE scope_id = ?2 AND model_id IS NULL"; const UPDATE_WORKTREE_CAS_SQL: &str = "UPDATE mutation_trace_worktrees SET cursor_tree = ?1, revision = ?2, tainted = ?3, failure_kind = ?4, needs_rebaseline = ?5, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') @@ -493,6 +496,13 @@ pub struct ScopeProvenance { pub model_id: Option, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ScopeProvenanceModelFill { + Filled, + AlreadySet, + NoRow, +} + pub struct MutationTraceStore<'a> { db: &'a mut RepositoryAgentTraceDb, } @@ -910,6 +920,28 @@ impl<'a> MutationTraceStore<'a> { Ok(rows.into_iter().next()) } + pub async fn fill_null_scope_provenance_model( + &self, + scope_id: &ScopeId, + model_id: &str, + ) -> Result { + let updated = self + .db + .execute_idempotent_write( + FILL_NULL_SCOPE_PROVENANCE_MODEL_SQL, + (model_id, scope_id.0.as_str()), + ) + .await?; + if updated > 0 { + return Ok(ScopeProvenanceModelFill::Filled); + } + + Ok(match self.load_scope_provenance(scope_id).await? { + Some(_) => ScopeProvenanceModelFill::AlreadySet, + None => ScopeProvenanceModelFill::NoRow, + }) + } + pub async fn load_worktree_state( &self, worktree: &WorktreeId, @@ -1376,3 +1408,76 @@ fn reconstruct_boundary( } } } + +#[cfg(test)] +mod tests { + use super::{MutationTraceStore, ScopeProvenance, ScopeProvenanceModelFill}; + use crate::services::agent_trace_db::repository::RepositoryAgentTraceDb; + use crate::services::mutation_trace::types::{ActorKind, ScopeId, TreeId, WorktreeId}; + + #[tokio::test] + async fn scope_provenance_model_fill_only_replaces_null() { + let dir = tempfile::tempdir().expect("temp dir"); + let mut db = RepositoryAgentTraceDb::new_at(dir.path().join("agent-trace.db")) + .await + .expect("db"); + let store = MutationTraceStore::new(&mut db); + let worktree = WorktreeId(String::from("main")); + store + .initialize_worktree(&worktree, &TreeId(String::from("tree-0"))) + .await + .expect("worktree"); + let null_scope = ScopeId(String::from("scope-null")); + let set_scope = ScopeId(String::from("scope-set")); + for (scope_id, model_id) in [(&null_scope, None), (&set_scope, Some("model-a"))] { + store + .register_scope(scope_id, &worktree, ActorKind::ClaudeCode) + .await + .expect("scope"); + store + .register_scope_provenance(&ScopeProvenance { + scope_id: scope_id.clone(), + session_id: String::from("cc_session"), + model_id: model_id.map(str::to_owned), + }) + .await + .expect("provenance"); + } + + let filled = store + .fill_null_scope_provenance_model(&null_scope, "model-b") + .await + .expect("fill null"); + let refill = store + .fill_null_scope_provenance_model(&null_scope, "model-c") + .await + .expect("refill"); + let kept = store + .fill_null_scope_provenance_model(&set_scope, "model-b") + .await + .expect("fill set"); + let missing = store + .fill_null_scope_provenance_model(&ScopeId(String::from("scope-missing")), "model-b") + .await + .expect("fill missing"); + + assert_eq!( + [filled, refill, kept, missing], + [ + ScopeProvenanceModelFill::Filled, + ScopeProvenanceModelFill::AlreadySet, + ScopeProvenanceModelFill::AlreadySet, + ScopeProvenanceModelFill::NoRow, + ] + ); + for (scope_id, expected) in [(&null_scope, "model-b"), (&set_scope, "model-a")] { + let stored = store + .load_scope_provenance(scope_id) + .await + .expect("load") + .expect("row"); + assert_eq!(stored.model_id.as_deref(), Some(expected)); + assert_eq!(stored.session_id, "cc_session"); + } + } +} diff --git a/context/cli/claude-mutation-scope-integration.md b/context/cli/claude-mutation-scope-integration.md index 47daf9ccf..22a0de422 100644 --- a/context/cli/claude-mutation-scope-integration.md +++ b/context/cli/claude-mutation-scope-integration.md @@ -111,14 +111,9 @@ can form. The adapter may call `checkout::resolve_git_dir` but not ## PreToolUse: write-ahead Start, fail-closed For a mutation-capable tool, `handle_pre_tool_use` runs: background-`Bash` untracked allow (empty success, nothing below runs) -> explicit-background-shell deny (`PowerShell`) -> resolve `git_dir` -> recovery barrier -> -write-ahead `Start` — persist `phase=pending_start`, resolve the canonical -`cc_` and the exact model-state key (`agent_id = ""` for the main -agent), call the seam with the optional provenance snapshot, persist -`pending_start -> active`, return empty success. The resolver is injectable for tests; production reads `claude_model_state_by_session_and_agent` from the -repository Agent Trace DB. Missing state or resolver errors become a null model -and never deny the mutation-capable tool. The seam receives the raw `cwd` as its -`repository_root` and SCE derives the `WorktreeId`, so durable generic-ingress -`Start` is reached before the hook returns success to Claude. +write-ahead `Start` — persist `phase=pending_start`, resolve the model from the event's `ClaudeModelEvidence` through the injectable resolver closure (production: the [Claude model resolver](../sce/claude-model-resolver.md) full chain), call the seam with the optional provenance snapshot, persist `pending_start -> active`, return empty success. +`transcript_path` and the direct model are parsed leniently, so a malformed value is absent, not a rejected event. A missing model or resolver error becomes a null model and never denies the tool. +The seam receives the raw `cwd` as its `repository_root` and SCE derives the `WorktreeId`, so durable generic-ingress `Start` is reached before the hook returns success to Claude. **Fail-closed via Claude's deny decision.** Claude treats ordinary non-2 hook failures as non-blocking, so a generic non-zero exit would let the tool run without its `Start`. Therefore **any** failure in the mutation-capable @@ -143,8 +138,11 @@ For an `active` tracked attempt, both events map to a `close` operation `2.1.258` exactly one of the two fires per attempt, never both (T01, D10), and a failed tool that already changed files still gets its final tree captured. The attempt is removed from adapter state only after durable `Close` success; a -duplicate `PostToolUse` after cleanup is a safe no-op. Two uncertain-boundary -rules: +duplicate `PostToolUse` after cleanup is a safe no-op. Between `Close` success +and attempt removal, the adapter runs the fail-open +[Claude completion fill](mutation-scope-provenance.md#claude-completion-fill) +(failures log `sce.hooks.claude_mutation_scope.provenance_model_fill_failed`). +Two uncertain-boundary rules: - **`pending_start` + terminal signal -> abandon, not late-Start (D11).** The adapter cannot prove `Start` committed, and a late `Start` after the tool ran @@ -155,7 +153,7 @@ rules: observation time is lost, so the adapter must not retry that `Close` later as the original observation; it abandons and arms `recovery_pending`. The ingress carried-success variants (`MarkerClearAfterCommit` / - `MarkerClearAfterCompletion`) are durable success and do not enter this path. The admission snapshot is carried into the mutation-derived Agent Trace path: the real `Bash` regression persists the exact `(cc_, "")` model state captured before the tool runs, then verifies the model and related session URL in `agent_traces.trace_json` after commit. + `MarkerClearAfterCompletion`) are durable success and do not enter this path. The admission snapshot is carried into the mutation-derived Agent Trace path: the real `Bash` regression persists the main-agent model resolved before the tool runs, then verifies the model and related session URL in `agent_traces.trace_json` after commit. ## Abandonment cleanup signals diff --git a/context/cli/mutation-scope-provenance.md b/context/cli/mutation-scope-provenance.md index 866ab993e..bdbb7d6ba 100644 --- a/context/cli/mutation-scope-provenance.md +++ b/context/cli/mutation-scope-provenance.md @@ -36,6 +36,10 @@ whichever row is stored afterwards. `MutationTraceStore::load_scope_provenance(scope_id) -> Result>` is the read seam; a scope with no provenance reads back `None`, which is an ordinary absence of metadata rather than an error. +`MutationTraceStore::fill_null_scope_provenance_model(scope_id, model_id) -> +Result` is the one conditional update seam. It sets +`model_id` only while the stored value is `NULL`, and returns `Filled`, +`AlreadySet`, or `NoRow`. Only the Claude adapter calls it. ## Insert-once semantics @@ -43,9 +47,12 @@ The first persisted row always wins: - `session_id` is immutable identity. A `scope_id` belongs to exactly one session, permanently. -- `model_id` is immutable first-observed descriptive metadata. A stored `NULL` - is never backfilled by a later discovery, and a stored model is never cleared - by a later `None` or overwritten by a disagreeing one. No `UPDATE` path exists. +- `model_id` is immutable first-observed descriptive metadata. A stored model is + never cleared by a later `None` or overwritten by a disagreeing one. A stored + `NULL` is never backfilled, with one exception: the + [Claude completion fill](#claude-completion-fill) may change a Claude scope's + `NULL` to a model once, from exact evidence only. No other `UPDATE` path + exists, and no path changes `session_id`. Every replay carrying the same `session_id` therefore succeeds and returns the stored row unchanged, whatever its model says. The **only** provenance condition @@ -79,8 +86,8 @@ an explicit `null` both mean "no model". A blank or whitespace-only `model_id` is rejected rather than coerced: both shipped producers normalize an unknown model to an absent value, so a blank string is malformed input, not an expression of "unknown". `advance`, `close`, `flush`, and `abandon` reject the -key outright, so provenance is only ever established at admission and never -updated by a later boundary. Every rejection uses the ingress's existing +key outright, so the ingress establishes provenance only at admission and never +updates it at a later boundary. Every rejection uses the ingress's existing `Invalid mutation-scope payload from STDIN: .` diagnostic. The ingress stays harness-neutral: it forwards the already-canonical @@ -114,17 +121,33 @@ A Codex session-identity conflict is unreachable in practice: the The [Claude adapter](claude-mutation-scope-integration.md) resolves provenance through an injectable `ClaudeModelStateResolver` with the shape -`(repository_root, canonical_session_id, agent_id) -> Result>`. -The production resolver uses the existing repository Agent Trace DB lookup for -`claude_model_state_by_session_and_agent`, after canonicalizing the raw session -to `cc_`. It passes `agent_id = ""` for the main agent and the exact -Claude `agent_id` for a subagent; a subagent never inherits the main-agent row. -The lookup runs when the scope is admitted, before the generic `Start` ingress -is called, and the returned Claude model is normalized before being sent as -provenance. Missing state, `Ok(None)`, an unusable model, or a resolver error -all produce `model_id = NULL` while retaining the canonical session and -allowing `Start` to succeed. A later `PostModelSwitch` changes only current -model state; insert-once scope provenance remains the original snapshot. +`(repository_root, &ClaudeModelEvidence) -> Result>`. The +production resolver calls the full chain of the +[Claude model resolver](../sce/claude-model-resolver.md). The main agent uses +the direct model, the exact transcript record, the `(cc_, "")` state +row, and then the bridge-session chain. A subagent uses only the direct model +and the exact record in its subagent transcript, and never inherits the +main-agent row. Resolution runs when the scope is admitted, before the generic +`Start` ingress is called, and the returned model is normalized before being +sent as provenance. A missing model or a resolver error produces +`model_id = NULL`, keeps the canonical session, and allows `Start` to succeed. +A later `PostModelSwitch` changes only current model state. + +### Claude completion fill + +A Claude scope admitted with `model_id = NULL` may gain its model once, at the +`PostToolUse` or `PostToolUseFailure` boundary. The adapter runs the fill after +durable `Close` success and before it removes its attempt. The fill reads the +stored row first. A missing row or a non-`NULL` model ends the fill without a +transcript scan. Otherwise the fill resolves the model from exact evidence only +(the direct event model, then the exact `tool_use_id` transcript record). It +never uses `claude_model_state` or the bridge-session chain. A found model is +written through `fill_null_scope_provenance_model`, so a concurrent fill can +never overwrite a stored model. The fill changes no field other than `model_id`. +A fill failure is logged and never fails the hook or the close. Provenance is +read at commit time, so a fill at `PostToolUse` is visible to the commit of that +mutation. See +[Claude subagent attribution](../decisions/2026-11-23-claude-subagent-attribution.md). ## Durable `Start` ordering diff --git a/context/context-map.md b/context/context-map.md index 33aeed822..e8c1a19f1 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -34,7 +34,7 @@ Feature/domain context: - `context/cli/mutation-trace-revision-refinement.md` (the Quint `revision: int` → Rust `WorktreeState::revision: u64` bounded-integer refinement: the private `next_revision` checked-arithmetic helper `commit`/`taint`/`abandon`/`recover` all route through instead of a raw `+ 1`, so a worktree at `revision: u64::MAX` is a guarded no-op/rejection rather than a silent wrap to `0`) - `context/cli/mutation-trace-quint-connect.md` (`#[cfg(test)]`-only Quint Connect model-based-testing harness in `cli/src/services/mutation_trace/mbt/` continuously checking `protocol.rs` against `spec/mutation_cursor.qnt`: the verification-only `mbtAction`/`MbtAction` record-payload transport excluded from comparison, the operation-identity-vs-`MbtStutter` distinction on guarded/no-op branches with its two deterministic regressions, finite ID mapping, the AC5 comparable-state field list, `randomPrepare` staying a single `step` branch, deterministic/generated (500×30, seed-reproducible) test coverage, and the two Nix checks — generic `checks.cli-tests` and dedicated `checks.mutation-trace-quint-connect` — that both require the pinned Quint binary plus the top-level `spec/` directory in `workspaceSrc`'s Nix fileset) - `context/cli/mutation-trace-store.md` (durable persistence for the mutation-cursor protocol in `cli/src/services/mutation_trace/store.rs`, built by the `mutation-cursor-store-persistence` plan: the one-directional `protocol.rs` -> `DurableTransition::between` (pure structural diff) -> `store.rs` (SQL translation) -> `RepositoryAgentTraceDb` boundary; migration `004_mutation_trace_protocol.sql`'s five tables; migration `006_mutation_trace_health_invariant.sql`'s transactional rebuild of the worktree and event tables with a cross-column `tainted`/`failure_kind` health `CHECK`, `failure_kind`-authoritative legacy normalization, and a re-runnable SQL body, plus the shared fail-closed `validate_health_encoding` used by all three health-row decoders; `AttemptState`/`external_taint` non-persistence; the 8-byte big-endian `BLOB` revision encoding plus explicit non-`Debug` enum codecs; the bounded hot-path `load_worktree` read vs. the cold-path `load_mutation_event` and descending, exact-worktree, cursor-paged `load_mutation_event_page` reader capped at 32 rows plus its post-commit `load_mutation_event_page_before_commit` variant that filters `created_at` by the commit-time cutoff before the limit; the public cold-path single-row `load_scope` scope seam that returns one `mutation_trace_scopes` row as `Option` without widening into a projection and, unlike `load_worktree`, never adjudicates worktree identity (a cross-worktree scope is returned as-is, and the mismatch is the caller's decision); the cold-path read-only `load_tree_roots` (one worktree) / `load_all_tree_roots` (repository-wide) durable-tree-SHA queries for ref reconciliation, each a single-statement `UNION` of `cursor_tree`/`before_tree`/`after_tree` read from one DB snapshot; `commit`'s single-`BEGIN IMMEDIATE` CAS batch via `TursoDb::execute_transactional_cas_batch`, distinguishing `Conflict`/retryable-transient/deterministic-`Err` outcomes; and the store's non-goals — no Git/filesystem I/O, no attribution/boundary-kind decisions, no retry-after-`Conflict` loop, no row deletion) -- `context/cli/mutation-scope-provenance.md` (the insert-once `mutation_trace_scope_provenance` table from migration `005_mutation_scope_provenance.sql` and its `MutationTraceStore::register_scope_provenance` / `load_scope_provenance` seams: `scope_id -> session_id + model_id?` metadata *about* an established scope, stored beside but never inside protocol state — outside `ProtocolState` and the CAS batch, and never an input to `IneligibleUnscoped` / `AiExclusive` / `AiContended`; `session_id` is immutable identity and `model_id` immutable first-observed metadata, so the first persisted row wins in both directions and only a differing `session_id` for an existing `scope_id` errors; the supported `MutationTraceStore` write seam requires an existing owning `mutation_trace_scopes` row and never creates one implicitly, enforced in the store rather than by a `FOREIGN KEY`, leaving `004_mutation_trace_protocol.sql` unchanged; creation is additionally admission-bounded in the runtime — a row may be created only while the durable scope is `NeverSeen`, so after admission absent provenance stays absent permanently and a later `Start` replay cannot backfill it, while an existing row is still validated on every provenance-carrying `Start`; producers own canonicalization — both Codex and Claude adapters supply provenance today, with Claude resolving exact `(cc_, agent_id)` model state at admission and degrading unavailable models to `NULL`) +- `context/cli/mutation-scope-provenance.md` (the insert-once `mutation_trace_scope_provenance` table from migration `005_mutation_scope_provenance.sql` and its `MutationTraceStore::register_scope_provenance` / `load_scope_provenance` / `fill_null_scope_provenance_model` seams: `scope_id -> session_id + model_id?` metadata *about* an established scope, stored beside but never inside protocol state — outside `ProtocolState` and the CAS batch, and never an input to `IneligibleUnscoped` / `AiExclusive` / `AiContended`; `session_id` is immutable identity and `model_id` immutable first-observed metadata, so the first persisted row wins in both directions and only a differing `session_id` for an existing `scope_id` errors; the supported `MutationTraceStore` write seam requires an existing owning `mutation_trace_scopes` row and never creates one implicitly, enforced in the store rather than by a `FOREIGN KEY`, leaving `004_mutation_trace_protocol.sql` unchanged; creation is additionally admission-bounded in the runtime — a row may be created only while the durable scope is `NeverSeen`, so after admission absent provenance stays absent permanently and a later `Start` replay cannot backfill it, while an existing row is still validated on every provenance-carrying `Start`; producers own canonicalization — both Codex and Claude adapters supply provenance today, with Claude resolving its model through the shared Claude model resolver at admission, degrading unavailable models to `NULL`, and filling a `NULL` model once at completion from exact evidence only) - `context/cli/mutation-trace-runtime-coordinator.md` (imperative-shell runtime layer in `cli/src/services/mutation_trace/runtime/`, built by the `mutation-cursor-runtime-coordinator` plan: the per-worktree OS advisory lock, `runtime::worktree_lock::WorktreeLock::acquire_async(git_dir, timeout)` at `/sce/mutation-cursor.lock`, bounded `try_lock()` polling with a distinct matchable timeout error and RAII release, and its distinction from the separate checkout-identity-creation lock; the isolated Git snapshot service `runtime::git_snapshot::GitSnapshotService` (documented in `mutation-trace-snapshot-service.md`); and `runtime::coordinator`'s protocol-integration pipeline (`RuntimeBoundary`/`CoordinateOutcome`/`CoordinateError`, the load → recover-if-needed → prepare/commit CAS-retry loop, and its own bounded snapshot-failure taint-retry loop) plus the public `coordinate(repository_root, boundary, open_db)` entrypoint that runs the shared `runtime::protected_worktree` prefix (`WorktreeLock` -> external-taint write-ahead fence -> `WorktreeId`, extracted so a second entrypoint cannot drift from it and documented in `mutation-trace-protected-worktree.md`), invokes the caller-supplied `open_db` provider so DB acquisition falls inside that fence, drives the pipeline under one held lock, and clears the marker through `ProtectedWorktree::complete()` only on success; an inherited external-taint marker is overlaid onto `protocol::database_failure` recovery on the next invocation, against the single captured snapshot and re-injected across a losing recovery CAS; the private `runtime::ref_reconciliation` per-worktree snapshot-ref maintenance pass (documented in `mutation-trace-ref-reconciliation.md`) shares the same `WorktreeLock`; `coordinate()` and `abandon_scope()` are now `pub(crate)` re-exported from `runtime/mod.rs` (documented in `mutation-scope-runtime.md`) while the runtime submodules themselves stay private; a generic `sce hooks mutation-scope` CLI ingress now drives both entrypoints, joined by current Claude Code and Codex adapter drivers (registered by `sce setup`/`sce setup --codex` and reachable) and an OpenCode adapter driver (lifecycle + recovery wired, and now generated as the final `sce-mutation-scope.ts` plugin and installed by `sce setup`), documented in `mutation-scope-runtime.md`) - `context/cli/mutation-trace-protected-worktree.md` (the shared safety prefix every mutation-cursor runtime entrypoint runs behind, in `cli/src/services/mutation_trace/runtime/protected_worktree.rs`, extracted from `coordinate()` by the `mutation-scope-runtime-integration` plan so a second entrypoint cannot drift from it: `ProtectedWorktree::acquire(repository_root)` running the safety-critical fixed order resolve `git_dir` → `WorktreeLock` (module-owned 10s `WORKTREE_LOCK_TIMEOUT`) → `ExternalTaintMarker::exists()` → `persist()` (fence armed write-ahead of every fallible step that follows, including DB acquisition) → `resolve_worktree_id` as `WorktreeId`; the `worktree_id()` / `inherited_external_taint()` / consuming `complete()` surface, where `complete()` clears the marker under the still-held lock and is the only thing that ever clears it while `Drop` releases only the lock; and the one-variant-per-prefix-step `ProtectedWorktreeError` (`GitDirResolution` | `LockAcquisition` | `ExternalTaintMarker { operation, source }` | `WorktreeIdentity`) each entrypoint maps onto its own error surface — `coordinate()` onto exactly the `CoordinateError` variants that step produced before the extraction) - `context/cli/mutation-trace-scope-abandonment.md` (the mutation-cursor runtime's second protected entrypoint in `cli/src/services/mutation_trace/runtime/scope_runtime.rs`, built by the `mutation-scope-runtime-integration` plan and the first production call site for `protocol::abandon`: `abandon_scope(repository_root, scope, open_db) -> Result` retires a scope whose final worktree boundary was never observed, sharing `coordinate()`'s `ProtectedWorktree` prefix but deliberately capturing **no** Git snapshot, pin, diff, reconciliation, scope registration, or worktree initialization — so abandonment is not a `RuntimeBoundary` and needs no Quint change; the classify-before-transition order that recovers what `protocol::abandon`'s uniform guarded no-op cannot report (`load_scope` first for the missing-row and cross-worktree cases the projection seam treats as errors, then `load_worktree` for the `NeverSeen` / terminal / `Active` split); the `Abandoned` / `AlreadyTerminal` / `RecoveryRequired` outcomes and the `InheritedExternalTaint` | `MissingScope` | `NeverSeenScope` | `MissingWorktreeState` recovery reasons; the inherited-marker short-circuit that returns before the DB provider is ever invoked; the fence-completion rule that clears the marker only for a settled abandonment or proven-terminal no-op and leaves it armed for every recovery-required outcome and every error, with `MarkerClearAfterCompletion` carrying the already-settled outcome; the CAS retry bounded by the coordinator's shared `MAX_CAS_RETRY_ATTEMPTS`, settling on a competitor's terminal status rather than overwriting it; and the deliberate false-negative tradeoff whereby a missing or `NeverSeen` target forces conservative strong recovery that may abandon unrelated live scopes, because attribution safety outranks preserving potentially valid evidence) @@ -124,7 +124,7 @@ Feature/domain context: Additional mutation-scope integration context: -- `context/cli/mutation-scope-provenance.md` (observational `ScopeProvenance` keyed by `ScopeId`: insert-once canonical session plus nullable first-observed model, admission-bounded creation while the owning scope is `NeverSeen`, exact producer snapshots for Claude and Codex, read-time enrichment of mutation-AI lines and conservative Agent Trace hunk model agreement, and the explicit boundary that mutation protocol attribution proves ownership while scope provenance describes the owning scope; real Claude/Codex `Bash` persistence regressions cover the full path) +- `context/cli/mutation-scope-provenance.md` (observational `ScopeProvenance` keyed by `ScopeId`: insert-once canonical session plus nullable first-observed model, admission-bounded creation while the owning scope is `NeverSeen`, exact producer snapshots for Claude and Codex, the Claude-only write-once `NULL`-to-model completion fill, read-time enrichment of mutation-AI lines and conservative Agent Trace hunk model agreement, and the explicit boundary that mutation protocol attribution proves ownership while scope provenance describes the owning scope; real Claude/Codex `Bash` persistence regressions cover the full path) - `context/cli/codex-mutation-scope-integration.md` (the second concrete harness adapter: Codex tracked/delegation/untracked classification, partial-by-tool-surface coverage, identity and checkout-local recovery state, write-ahead fail-closed lifecycle, cleanup signals, boundary-aware attribution confirmation, Codex setup/doctor ownership, and the scope provenance it sends with every tracked `Start` — the `cx_`-prefixed canonical session plus the normalized `model` read off the same `PreToolUse` payload, for both `Bash` and `apply_patch`, with a deliberately lenient `model` read so an absent, blank, or non-string model records no model instead of denying a mutation-capable tool) - `context/cli/codex-mutation-scope-health.md` (the `doctor-mutation-scope-health` plan's T03: `classify_health` in `cli/src/services/hooks/codex_mutation_scope/health.rs` maps the adapter's `RecoveryState`/attempt-state combinations onto `healthy | recovering | blocked | invalid`, proven by driving the real dispatch/recovery functions rather than reading enum names — `Pending` with attempts empty, `Pending` with unresolved attempts, and an orphaned `Flushing` are all `recovering`: the production `PreToolUse` order runs `sweep_stale_lane_predecessors` before the global `RecoveryBlocked` gate, so a same-`(session_id, turn_id)`-lane successor can retry and clear a stuck attempt and self-admit through a flush, even though an unrelated session/lane still denies fail-closed in the meantime; `Flushing` with unresolved attempts and any read/parse failure are `invalid`) - `context/sce/codex-apply-patch-diff-runtime.md` (the complementary Codex `PostToolUse(apply_patch)` parsing, path containment, normalization, and `diff_traces` evidence contract) diff --git a/context/glossary.md b/context/glossary.md index a1dc4a66e..662bb5c37 100644 --- a/context/glossary.md +++ b/context/glossary.md @@ -90,7 +90,7 @@ - `effective remover`: The recorded transition that removed a parent line, as opposed to whoever originally wrote it. That removal must still hold in the committed tree. A healthy `AiExclusive` remover yields AI attribution with its scope provenance, any other recorded remover yields `NonExclusive`, and an `Unobserved` remover yields `Unknown`. A later addition of matching content to the same parent file (plausible restoration) makes the removal claim `Unknown` permanently. The claim counts only when an uninterrupted replay from the exact parent tree reconciles with the commit tree for that path; otherwise the removal is unresolved. Deleted lines appear only in `metadata.sce.line_changes`, never as ranges. - `LineAttribution`: The single final per-line attribution decision in `cli/src/services/agent_trace.rs` — `Ai(ResolvedLine)` (AI-exclusive mutation lineage, or accepted direct evidence for an otherwise unresolved line), `NonExclusive` (mutation lineage resolved a non-exclusive or unscoped transition; not human authorship; cannot be overridden by direct evidence), or `Unknown` (unresolved). Exactly one decision exists per canonical touched line and feeds both revision-positioned ranges and `metadata.sce.line_changes`. See `context/sce/agent-trace-minimal-generator.md`. - `Agent Trace SCE metadata`: Implementation-owned top-level metadata emitted by `build_agent_trace_from_evidence(...)` under `metadata.sce`, carrying `version` (sourced from the compiled `sce` CLI package version via `env!("CARGO_PKG_VERSION")`) and `line_changes` (exact `{ai,non_exclusive,unknown}` × `{added,removed}` `u64` per-line attribution counts: every canonical `post_commit_patch` touched line increments exactly one bucket from its final `LineAttribution` decision — the same decisions ranges are built from — so totals equal the committed patch's touched lines independent of hunk boundaries and of emitted ranges; `#[serde(default)]` for backward-compatible deserialization of pre-existing payloads); the whole object is schema-validated with the rest of the payload and persisted in AgentTraceDb `agent_traces.trace_json` without changing the top-level Agent Trace payload/schema `version`. -- `ScopeProvenance`: Optional insert-once metadata keyed by a mutation `ScopeId`, storing canonical SCE `session_id` and nullable first-observed `model_id`. It is registered only at `Start` admission while the owning scope is `NeverSeen`, remains outside `ProtocolState` and the CAS transition, and is resolved during mutation projection. `ScopeId` proves mutation ownership; `ScopeProvenance` describes the owning scope. Model/session provenance is observational and never changes `AiExclusive`/`AiContended`/`IneligibleUnscoped` protocol decisions. +- `ScopeProvenance`: Optional insert-once metadata keyed by a mutation `ScopeId`, storing canonical SCE `session_id` and nullable first-observed `model_id`. For a Claude scope only, a `NULL` `model_id` may be filled once at `PostToolUse`/`PostToolUseFailure` from exact evidence (the Claude completion fill). It is registered only at `Start` admission while the owning scope is `NeverSeen`, remains outside `ProtocolState` and the CAS transition, and is resolved during mutation projection. `ScopeId` proves mutation ownership; `ScopeProvenance` describes the owning scope. Model/session provenance is observational and never changes `AiExclusive`/`AiContended`/`IneligibleUnscoped` protocol decisions. - `Agent Trace range content_hash`: Optional per-range `content_hash` emitted as `murmur3:<8 lowercase hex>` (Murmur3 x86 32-bit, seed 0) over exactly the committed bytes of the inclusive range at `vcs.revision`, including the lines' own LF/CRLF terminators; excludes paths, positions, hunk metadata, attribution, and IDs. Omitted, never fabricated, only when the caller explicitly reports `CommittedFile::Unverified`; the production post-commit hook never does, and fails instead on a missing path or Git read error. See `context/sce/agent-trace-minimal-generator.md`. - `committed-file outcome`: The result of `CommittedFileReader::read_committed_file` for a post-commit path: `Blob` (regular or executable file, `100644`/`100755` blob; ranges validated and hashed), `NotLineAddressable` (symlink `120000` blob, gitlink `160000` commit, or directory `040000` tree; no ranges, counters kept), `Missing` (absent at the revision; trace generation fails), or `Unverified` (test-only, `#[cfg(test)]`: hashless ranges whose positions are not independently verified; production readers never produce it). Operational failures are a separate `CommittedFileReadError` (`TreeLookupFailed`, `MalformedTreeEntry`, `BlobReadFailed`) and also fail trace generation. Canonical counters in `metadata.sce.line_changes` always cover every touched line regardless of which files emit ranges. - `Git path identity`: The exact repository-relative path of a patch file after decoding Git's C-quoted form (`patch/git_path.rs`): escapes decode to bytes, the result must be valid UTF-8 without NUL, and `a/`/`b/` prefixes are removed only after decoding. Undecodable names fail patch parsing explicitly. The same identity is used for attribution lookup, `files[].path`, and committed-file lookup. diff --git a/context/plans/claude-subagent-attribution.md b/context/plans/claude-subagent-attribution.md index c54794747..8b554e370 100644 --- a/context/plans/claude-subagent-attribution.md +++ b/context/plans/claude-subagent-attribution.md @@ -165,13 +165,19 @@ Persist this field in every plan; this is durable plan state, not chat state: - Context impact: localized — Claude model attribution moves into one resolver, and subagent precedence and transcript bounds change. `context/sce/claude-raw-hook-capture.md` should describe the resolver, precedence, and bounds. - Context synchronization: synced -- [ ] T03: `Resolve and fill Claude mutation-scope provenance models through the shared resolver` (status:todo) +- [x] T03: `Resolve and fill Claude mutation-scope provenance models through the shared resolver` (status:done) - Task ID: T03 - Scope: In — the production `ClaudeModelStateResolver` in `claude_mutation_scope/lifecycle.rs` builds the evidence struct from the admitted event and calls the T02 full chain; the closure argument changes to that struct; the `PostToolUse` and `PostToolUseFailure` identity carries `transcript_path` when present; one `MutationTraceStore` method for the conditional `NULL`-to-model fill with a typed outcome; the fill call in `handle_close` after a successful close, using the T02 exact-evidence chain, logged and fail-open; tests named `claude_provenance_fill` for AC10 (a)–(e), and a store test under `scope_provenance` for the conditional update. Out — provenance insert-once rules for `session_id`, admission-bounded creation, the generic ingress, protocol state, the CAS batch, non-Claude producers, and new seams. - Dependencies: T02 - Done when: AC10 holds, the lifecycle module no longer calls the model-state lookup directly, and a resolver or fill failure still admits and closes the scope. - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_provenance_fill`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_mutation_scope`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml scope_provenance`. - - Context synchronization: pending + - Completed: 2026-11-23 + - Files changed: `cli/src/services/hooks/claude_mutation_scope/events.rs`, `cli/src/services/hooks/claude_mutation_scope/lifecycle.rs`, `cli/src/services/hooks/claude_mutation_scope/mod.rs`, `cli/src/services/hooks/claude_mutation_scope/provenance_fill_tests.rs` (new), `cli/src/services/mutation_trace/store.rs`, `context/plans/claude-subagent-attribution.md` + - Result: `ClaudeToolIdentity` now carries an optional `transcript_path` and direct model, both parsed leniently so malformed values never reject the event, and builds `ClaudeModelEvidence` through `model_evidence()`. The admission resolver closure takes `(&Path, &ClaudeModelEvidence)`, and the production closure calls `resolve_claude_model`. The lifecycle module no longer calls `claude_model_state_by_session_and_agent`. Added `MutationTraceStore::fill_null_scope_provenance_model` (`UPDATE … SET model_id = ? WHERE scope_id = ? AND model_id IS NULL`) with the typed outcome `ScopeProvenanceModelFill { Filled, AlreadySet, NoRow }`. `handle_close` now takes the tool identity. After the seam close succeeds and before the adapter attempt is removed, it calls `fill_provenance_model_after_close`. That function opens the hook-runtime DB and calls `fill_claude_scope_provenance_model`, which reads the stored row first: a missing row or a non-`NULL` model costs no transcript scan. Otherwise it resolves through `resolve_claude_model_from_exact_evidence` once. Any failure is logged as `sce.hooks.claude_mutation_scope.provenance_model_fill_failed` and never fails the close. + - Verify outcomes: `claude_provenance_fill` 6 passed (AC10 a: admitted exact-record model kept when completion sees a different model; b: `NULL` at admission despite a main-agent state row, filled at completion, no state row written; c: `NULL` at both boundaries; d: stored model never overwritten; ignores the state row and bridge chain for a main-agent fill; e and fail-open: `handle_close` with an unopenable DB succeeds, removes the attempt, logs the fill failure, and a duplicate close succeeds with no further seam call); `claude_mutation_scope` 10 passed; `scope_provenance` 2 passed (store fill: `NULL` → `Filled`, refill → `AlreadySet`, pre-set model kept → `AlreadySet`, missing → `NoRow`, `session_id` unchanged). Also: full CLI suite 882 passed; `clippy --all-targets -D warnings` clean; `cargo fmt` applied. + - Deviation: the production `fill_provenance_model_after_close` wrapper is exercised only on its failure path, because opening the real hook-runtime DB in tests would write to user state. The fill core is tested with a temporary DB. + - Context impact: localized — Claude mutation-scope provenance now resolves through the shared resolver and has a write-once `NULL`-to-model completion fill. `context/cli/mutation-scope-provenance.md` must name this exception to its "no `UPDATE` path" and "a stored `NULL` is never backfilled" statements. + - Context synchronization: synced - [ ] T04: `Fill session, model, and subagent attribution on Claude patch parts` (status:todo) - Task ID: T04 diff --git a/context/sce/claude-model-resolver.md b/context/sce/claude-model-resolver.md index fd8463b6c..b5557c2e8 100644 --- a/context/sce/claude-model-resolver.md +++ b/context/sce/claude-model-resolver.md @@ -92,6 +92,8 @@ steps. - Structured Claude `diff-trace` keeps only the direct model at parse time. At persist time it calls `resolve_claude_model` once per event. See [agent-trace-hooks-command-routing.md](./agent-trace-hooks-command-routing.md). -- Mutation-scope provenance admission does not use the resolver. It calls - `claude_model_state_by_session_and_agent` directly in - `claude_mutation_scope/lifecycle.rs`. +- Claude mutation-scope provenance admission calls `resolve_claude_model` once + per admitted event. The `PostToolUse` / `PostToolUseFailure` completion fill + calls `resolve_claude_model_from_exact_evidence` only when the stored model is + `NULL`. See + [claude-mutation-scope-integration.md](../cli/claude-mutation-scope-integration.md). From 67779b4f860a8c07b1b6d0f9af1eb1cc78ce475b Mon Sep 17 00:00:00 2001 From: David Abram Date: Mon, 23 Nov 2026 17:11:03 +0100 Subject: [PATCH 5/6] hooks+patch: Preserve Claude subagent attribution in patch parts Resolve Claude model and writer metadata from exact bounded transcript and meta-file evidence when building conversation-trace patch parts. Extend the patch model with backward-compatible optional attribution while keeping non-Claude producers and historical JSON unchanged. Complete the Claude subagent attribution plan's T04 implementation and synchronize its supporting context. Ref: context/plans/claude-subagent-attribution.md (T04) Co-authored-by: SCE --- .../agent_trace/committed_content/tests.rs | 2 +- cli/src/services/agent_trace/tests.rs | 16 +- .../services/hooks/claude_model_resolver.rs | 91 ++-- cli/src/services/hooks/claude_transcript.rs | 157 ++++++- cli/src/services/hooks/claude_transforms.rs | 81 +++- cli/src/services/hooks/commit_hooks.rs | 4 +- .../hooks/commit_hooks/attribution_tests.rs | 6 +- .../hooks/commit_hooks/path_identity_tests.rs | 2 +- cli/src/services/hooks/conversation_trace.rs | 411 ++++++++++++++++-- .../services/mutation_trace/attribution.rs | 10 +- .../runtime/mutation_attribution.rs | 2 +- .../runtime/mutation_attribution/tests.rs | 1 + cli/src/services/patch.rs | 17 +- cli/src/services/patch/tests.rs | 16 +- cli/src/services/structured_patch.rs | 2 + context/cli/agent-trace-sync-command.md | 4 + context/cli/patch-service.md | 3 +- context/context-map.md | 4 +- context/plans/claude-subagent-attribution.md | 91 +++- .../sce/agent-trace-hooks-command-routing.md | 2 +- context/sce/claude-model-resolver.md | 26 ++ context/sce/claude-raw-hook-capture.md | 2 +- 22 files changed, 805 insertions(+), 145 deletions(-) diff --git a/cli/src/services/agent_trace/committed_content/tests.rs b/cli/src/services/agent_trace/committed_content/tests.rs index ac7051852..fb68e8956 100644 --- a/cli/src/services/agent_trace/committed_content/tests.rs +++ b/cli/src/services/agent_trace/committed_content/tests.rs @@ -321,7 +321,7 @@ fn build_entry_trace( build_agent_trace_from_evidence, AgentTraceEvidence, AgentTraceMetadataInput, RepositoryRoot, }; - let empty = crate::services::patch::ParsedPatch { files: Vec::new() }; + let empty = crate::services::patch::ParsedPatch::default(); build_agent_trace_from_evidence( AgentTraceEvidence { repository_root: &RepositoryRoot::new(Path::new("/workspace/project")), diff --git a/cli/src/services/agent_trace/tests.rs b/cli/src/services/agent_trace/tests.rs index 7765ce0c6..06f4d3d95 100644 --- a/cli/src/services/agent_trace/tests.rs +++ b/cli/src/services/agent_trace/tests.rs @@ -203,7 +203,7 @@ fn assert_builds_expected_agent_trace(scenario: AgentTraceScenario) { parse_patch(scenario.post_commit, None).expect("fixture patch should parse"); let golden: Value = serde_json::from_str(scenario.golden).expect("golden json should load"); validate_agent_trace_value(&golden).expect("golden json should validate against schema"); - let empty_mutation_patch = ParsedPatch { files: Vec::new() }; + let empty_mutation_patch = ParsedPatch::default(); let direct_sources: Vec<_> = direct_patches .iter() .map(DirectEvidenceSource::repository_relative) @@ -403,7 +403,7 @@ fn assert_builds_expected_agent_trace_from_evidence(scenario: EvidenceScenario) repository_root: &RepositoryRoot::new(Path::new(TEST_REPOSITORY_ROOT)), direct_sources: std::slice::from_ref(&direct_source), mutation_ai_patch: &mutation_ai_patch, - mutation_non_ai_patch: &ParsedPatch { files: Vec::new() }, + mutation_non_ai_patch: &ParsedPatch::default(), }, &post_commit_patch, AgentTraceMetadataInput { @@ -608,7 +608,7 @@ fn build_with_sources( &committed_patch(), sources, mutation_ai_patch, - &ParsedPatch { files: Vec::new() }, + &ParsedPatch::default(), ) } @@ -657,7 +657,7 @@ fn build_trace_with_content( } fn no_mutation() -> ParsedPatch { - ParsedPatch { files: Vec::new() } + ParsedPatch::default() } fn tool_of(trace: &super::AgentTrace) -> Option<(Option<&str>, Option<&str>)> { @@ -2532,7 +2532,13 @@ fn partition( } }) .collect(); - (ParsedPatch { files: patch_files }, decisions) + ( + ParsedPatch { + files: patch_files, + attribution: None, + }, + decisions, + ) } type ExpectedKey = (Option, Option, &'static str); diff --git a/cli/src/services/hooks/claude_model_resolver.rs b/cli/src/services/hooks/claude_model_resolver.rs index 727b06afb..1cd02c50a 100644 --- a/cli/src/services/hooks/claude_model_resolver.rs +++ b/cli/src/services/hooks/claude_model_resolver.rs @@ -4,6 +4,7 @@ use anyhow::Result; use crate::services::agent_trace_db::repository::RepositoryAgentTraceDb; use crate::services::agent_trace_db::{ClaudeModelStateObservation, ObservationKind}; +use crate::services::patch::PatchAttribution; use super::claude_model_state; use super::claude_transcript; @@ -99,6 +100,40 @@ pub(crate) fn claude_subagent_transcript_path( ) } +pub(crate) fn resolve_claude_patch_attribution( + evidence: &ClaudeModelEvidence, + event_agent_type: Option<&str>, +) -> PatchAttribution { + let Some(agent_id) = evidence.agent_id.as_deref() else { + return PatchAttribution { + tool_use_id: evidence.tool_use_id.clone(), + ..PatchAttribution::default() + }; + }; + + let meta = evidence + .transcript_path + .as_deref() + .and_then(|path| claude_subagent_meta_path(path, &evidence.session_id, agent_id)) + .and_then(|path| claude_transcript::read_claude_subagent_meta(&path).ok()) + .unwrap_or_default(); + PatchAttribution { + agent_id: Some(agent_id.to_string()), + agent_type: event_agent_type.map(str::to_string).or(meta.agent_type), + tool_use_id: evidence.tool_use_id.clone(), + parent_tool_use_id: meta.parent_tool_use_id, + } +} + +pub(crate) fn claude_subagent_meta_path( + transcript_path: &Path, + session_id: &str, + agent_id: &str, +) -> Option { + claude_subagent_transcript_path(transcript_path, session_id, agent_id) + .map(|path| path.with_extension("meta.json")) +} + fn is_safe_path_component(value: &str) -> bool { !value.is_empty() && value @@ -245,14 +280,6 @@ mod tests { .to_string() } - fn text_only(model: &str) -> String { - serde_json::json!({ - "type": "assistant", - "message": {"role": "assistant", "model": model, "content": [{"type": "text", "text": "hi"}]} - }) - .to_string() - } - #[tokio::test] async fn claude_subagent_model_prefers_direct_event_model() { let fixture = Fixture::new().await; @@ -270,43 +297,6 @@ mod tests { assert_eq!(model.as_deref(), Some("claude/claude-sonnet-5-5")); } - #[tokio::test] - async fn claude_subagent_model_uses_exact_record_not_latest_record() { - let fixture = Fixture::new().await; - write_transcript( - &fixture.subagent_transcript(), - &[ - tool_use("toolu_target", "claude-haiku-5-5"), - tool_use("toolu_later", "claude-opus-5-5"), - text_only("claude-opus-5-5"), - ], - ); - - let model = resolve_claude_model(&fixture.db, &fixture.subagent_evidence("toolu_target")) - .await - .unwrap(); - - assert_eq!(model.as_deref(), Some("claude/claude-haiku-5-5")); - } - - #[tokio::test] - async fn claude_subagent_model_is_null_when_exact_record_is_absent() { - let fixture = Fixture::new().await; - write_transcript( - &fixture.subagent_transcript(), - &[ - tool_use("toolu_other", "claude-opus-5-5"), - text_only("claude-opus-5-5"), - ], - ); - - let model = resolve_claude_model(&fixture.db, &fixture.subagent_evidence("toolu_target")) - .await - .unwrap(); - - assert_eq!(model, None); - } - #[tokio::test] async fn claude_subagent_model_follows_each_tool_call_across_a_model_switch() { let fixture = Fixture::new().await; @@ -374,17 +364,6 @@ mod tests { assert_eq!(fixture.state_rows().await, before); } - #[tokio::test] - async fn claude_subagent_model_missing_transcript_is_null() { - let fixture = Fixture::new().await; - - let model = resolve_claude_model(&fixture.db, &fixture.subagent_evidence("toolu_target")) - .await - .unwrap(); - - assert_eq!(model, None); - } - #[test] fn claude_subagent_model_transcript_path_derivation() { let main = Path::new("/projects/repo/5f0c2a7e.jsonl"); diff --git a/cli/src/services/hooks/claude_transcript.rs b/cli/src/services/hooks/claude_transcript.rs index d6c558c22..49d46cae2 100644 --- a/cli/src/services/hooks/claude_transcript.rs +++ b/cli/src/services/hooks/claude_transcript.rs @@ -89,6 +89,92 @@ pub(crate) fn find_tool_use_model_in( Ok(None) } +pub const CLAUDE_SUBAGENT_META_MAX_BYTES: u64 = 1024 * 1024; + +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub struct ClaudeSubagentMeta { + pub agent_type: Option, + pub parent_tool_use_id: Option, +} + +#[derive(Debug)] +pub enum ClaudeSubagentMetaReadError { + Open { path: PathBuf, source: io::Error }, + Read(io::Error), + Oversized, + Malformed(serde_json::Error), +} + +impl fmt::Display for ClaudeSubagentMetaReadError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Open { path, source } => write!( + f, + "failed to open Claude subagent meta file '{}': {source}", + path.display() + ), + Self::Read(source) => write!(f, "failed to read Claude subagent meta file: {source}"), + Self::Oversized => write!( + f, + "Claude subagent meta file exceeds {CLAUDE_SUBAGENT_META_MAX_BYTES} bytes" + ), + Self::Malformed(source) => { + write!( + f, + "Claude subagent meta file is not a JSON object: {source}" + ) + } + } + } +} + +impl std::error::Error for ClaudeSubagentMetaReadError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Open { source, .. } | Self::Read(source) => Some(source), + Self::Malformed(source) => Some(source), + Self::Oversized => None, + } + } +} + +pub fn read_claude_subagent_meta( + meta_path: &Path, +) -> Result { + let file = File::open(meta_path).map_err(|source| ClaudeSubagentMetaReadError::Open { + path: meta_path.to_path_buf(), + source, + })?; + read_subagent_meta_from(file) +} + +pub(crate) fn read_subagent_meta_from( + source: R, +) -> Result { + let mut contents = Vec::new(); + source + .take(CLAUDE_SUBAGENT_META_MAX_BYTES + 1) + .read_to_end(&mut contents) + .map_err(ClaudeSubagentMetaReadError::Read)?; + if contents.len() as u64 > CLAUDE_SUBAGENT_META_MAX_BYTES { + return Err(ClaudeSubagentMetaReadError::Oversized); + } + + let meta = serde_json::from_slice::>(&contents) + .map_err(ClaudeSubagentMetaReadError::Malformed)?; + let string_field = |key: &str| { + meta.get(key) + .and_then(Value::as_str) + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_string) + }; + Ok(ClaudeSubagentMeta { + agent_type: string_field("agentType"), + parent_tool_use_id: string_field("toolUseId"), + }) +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum RecordRead { Complete, @@ -190,7 +276,9 @@ mod tests { use std::time::{Duration, Instant}; use super::{ - find_claude_transcript_tool_use_model, find_tool_use_model_in, ClaudeTranscriptReadError, + find_claude_transcript_tool_use_model, find_tool_use_model_in, read_claude_subagent_meta, + read_subagent_meta_from, ClaudeSubagentMeta, ClaudeSubagentMetaReadError, + ClaudeTranscriptReadError, CLAUDE_SUBAGENT_META_MAX_BYTES, CLAUDE_TRANSCRIPT_MAX_RECORD_BYTES, CLAUDE_TRANSCRIPT_TAIL_WINDOW_BYTES, }; @@ -404,4 +492,71 @@ mod tests { "unexpected error: {error:?}" ); } + + fn meta_of_length(agent_type: &str, tool_use_id: &str, length: usize) -> Vec { + let empty = + serde_json::json!({"agentType": agent_type, "toolUseId": tool_use_id, "pad": ""}) + .to_string(); + let pad = "x".repeat(length - empty.len()); + serde_json::json!({"agentType": agent_type, "toolUseId": tool_use_id, "pad": pad}) + .to_string() + .into_bytes() + } + + #[test] + fn claude_subagent_meta_reads_agent_type_and_parent_tool_use_id() { + let meta = read_subagent_meta_from(Cursor::new( + br#"{"agentType":"general-purpose","toolUseId":"toolu_parent","description":"x"}"#, + )) + .unwrap(); + + assert_eq!( + meta, + ClaudeSubagentMeta { + agent_type: Some(String::from("general-purpose")), + parent_tool_use_id: Some(String::from("toolu_parent")), + } + ); + } + + #[test] + fn claude_subagent_meta_missing_or_non_string_fields_are_none() { + let meta = + read_subagent_meta_from(Cursor::new(br#"{"agentType":7,"toolUseId":" "}"#)).unwrap(); + + assert_eq!(meta, ClaudeSubagentMeta::default()); + } + + #[test] + fn claude_subagent_meta_at_cap_is_read_and_one_byte_over_is_rejected() { + let cap = usize::try_from(CLAUDE_SUBAGENT_META_MAX_BYTES).unwrap(); + + let at_cap = + read_subagent_meta_from(Cursor::new(meta_of_length("Explore", "toolu_p", cap))) + .expect("meta at the cap is read"); + assert_eq!(at_cap.parent_tool_use_id.as_deref(), Some("toolu_p")); + + let over_cap = + read_subagent_meta_from(Cursor::new(meta_of_length("Explore", "toolu_p", cap + 1))) + .expect_err("meta over the cap is rejected"); + assert!(matches!(over_cap, ClaudeSubagentMetaReadError::Oversized)); + } + + #[test] + fn claude_subagent_meta_malformed_and_missing_files_are_typed_errors() { + let malformed = read_subagent_meta_from(Cursor::new(b"[\"not an object\"]")) + .expect_err("non-object meta is rejected"); + assert!(matches!( + malformed, + ClaudeSubagentMetaReadError::Malformed(_) + )); + + let dir = tempfile::tempdir().expect("temp dir"); + let missing = dir.path().join("agent-a.meta.json"); + let error = read_claude_subagent_meta(&missing).expect_err("missing meta fails to open"); + assert!( + matches!(&error, ClaudeSubagentMetaReadError::Open { path, .. } if path == &missing), + "unexpected error: {error:?}" + ); + } } diff --git a/cli/src/services/hooks/claude_transforms.rs b/cli/src/services/hooks/claude_transforms.rs index d7a35bc3c..be3c956c2 100644 --- a/cli/src/services/hooks/claude_transforms.rs +++ b/cli/src/services/hooks/claude_transforms.rs @@ -1,15 +1,21 @@ +use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; use anyhow::{bail, Result}; use serde_json::{json, Value}; +use crate::services::patch::{ParsedPatch, PatchAttribution}; use crate::services::structured_patch::{build_claude_post_tool_use_patch, PatchBuildResult}; +use super::claude_model_resolver::ClaudeModelEvidence; use super::conversation_trace::{ - conversation_trace_validation_error, required_non_empty_string_field, + conversation_trace_validation_error, non_empty_string, required_non_empty_string_field, CONVERSATION_TRACE_MESSAGE_PART_UPDATED, CONVERSATION_TRACE_MESSAGE_UPDATED, }; -use super::runtime::current_unix_time_ms; +use super::diff_trace::extract_direct_claude_model_id; +use super::runtime::{ + current_unix_time_ms, prefixed_conversation_trace_session_id, CLAUDE_TOOL_NAME, +}; pub(crate) fn transform_claude_user_prompt_submit( payload: &serde_json::Map, @@ -151,9 +157,11 @@ where } pub(crate) fn transform_claude_post_tool_use( payload: &serde_json::Map, + enrichment: ClaudePatchEnrichment, ) -> Result> { transform_claude_post_tool_use_with( payload, + enrichment, || { let now = SystemTime::now() .duration_since(UNIX_EPOCH) @@ -167,6 +175,7 @@ pub(crate) fn transform_claude_post_tool_use( pub(crate) fn transform_claude_post_tool_use_with( payload: &serde_json::Map, + enrichment: ClaudePatchEnrichment, generate_message_id: G, generate_timestamp_ms: T, ) -> Result> @@ -205,7 +214,12 @@ where let generated_at_unix_ms = generate_timestamp_ms(); match build_claude_post_tool_use_patch(payload) { - PatchBuildResult::Built(parsed_patch) => { + PatchBuildResult::Built(mut parsed_patch) => { + attribute_claude_patch( + &mut parsed_patch, + &prefixed_conversation_trace_session_id(CLAUDE_TOOL_NAME, &session_id), + enrichment, + ); let text = serde_json::to_string(&parsed_patch)?; let items = vec![ json!({ @@ -229,3 +243,64 @@ where PatchBuildResult::Skipped(_) => Ok(vec![]), } } +#[derive(Clone, Debug, Default, Eq, PartialEq)] +pub(crate) struct ClaudePatchEnrichment { + pub(crate) model_id: Option, + pub(crate) attribution: PatchAttribution, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct ClaudePatchEvidence { + pub(crate) model: ClaudeModelEvidence, + pub(crate) agent_type: Option, +} + +pub(crate) fn claude_patch_evidence( + payload: &serde_json::Map, +) -> Option { + if non_empty_string(payload.get("hook_event_name")) != Some("PostToolUse") { + return None; + } + if !matches!( + non_empty_string(payload.get("tool_name")), + Some("Write" | "Edit") + ) { + return None; + } + let trimmed_field = |key: &str| { + non_empty_string(payload.get(key)) + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_string) + }; + let session_id = trimmed_field("session_id")?; + + Some(ClaudePatchEvidence { + model: ClaudeModelEvidence { + session_id: prefixed_conversation_trace_session_id(CLAUDE_TOOL_NAME, &session_id), + agent_id: trimmed_field("agent_id"), + tool_use_id: trimmed_field("tool_use_id"), + transcript_path: trimmed_field("transcript_path").map(PathBuf::from), + direct_model_id: extract_direct_claude_model_id(payload), + }, + agent_type: trimmed_field("agent_type"), + }) +} + +fn attribute_claude_patch( + patch: &mut ParsedPatch, + canonical_session_id: &str, + enrichment: ClaudePatchEnrichment, +) { + for hunk in patch + .files + .iter_mut() + .flat_map(|file| file.hunks.iter_mut()) + { + hunk.model_id.clone_from(&enrichment.model_id); + for line in &mut hunk.lines { + line.session_id = Some(canonical_session_id.to_string()); + } + } + patch.attribution = Some(Box::new(enrichment.attribution)); +} diff --git a/cli/src/services/hooks/commit_hooks.rs b/cli/src/services/hooks/commit_hooks.rs index 74a9c1791..2da685df6 100644 --- a/cli/src/services/hooks/commit_hooks.rs +++ b/cli/src/services/hooks/commit_hooks.rs @@ -555,7 +555,7 @@ pub(crate) fn capture_staged_patch_from_git(repository_root: &Path) -> Result ParsedPatch { - ParsedPatch { files: Vec::new() } + ParsedPatch::default() } fn empty_mutation() -> MutationAttributionResult { diff --git a/cli/src/services/hooks/commit_hooks/attribution_tests.rs b/cli/src/services/hooks/commit_hooks/attribution_tests.rs index fb373dc38..bf100dbc1 100644 --- a/cli/src/services/hooks/commit_hooks/attribution_tests.rs +++ b/cli/src/services/hooks/commit_hooks/attribution_tests.rs @@ -415,7 +415,7 @@ async fn mutation_attribution( } fn no_mutation() -> MutationAttributionResult { - let empty = ParsedPatch { files: Vec::new() }; + let empty = ParsedPatch::default(); MutationAttributionResult { mutation_ai_patch: empty.clone(), resolved_non_ai_patch: empty.clone(), @@ -699,8 +699,8 @@ fn one_direct_source_line_covers_only_its_own_duplicate_occurrence() { crate::services::agent_trace::AgentTraceEvidence { repository_root: &RepositoryRoot::new(Path::new("/workspace/project")), direct_sources: &[DirectEvidenceSource::repository_relative(&direct)], - mutation_ai_patch: &ParsedPatch { files: Vec::new() }, - mutation_non_ai_patch: &ParsedPatch { files: Vec::new() }, + mutation_ai_patch: &ParsedPatch::default(), + mutation_non_ai_patch: &ParsedPatch::default(), }, &committed, crate::services::agent_trace::AgentTraceMetadataInput { diff --git a/cli/src/services/hooks/commit_hooks/path_identity_tests.rs b/cli/src/services/hooks/commit_hooks/path_identity_tests.rs index 5e1c47f4e..2457d5eae 100644 --- a/cli/src/services/hooks/commit_hooks/path_identity_tests.rs +++ b/cli/src/services/hooks/commit_hooks/path_identity_tests.rs @@ -221,7 +221,7 @@ async fn intersection_flow( } fn no_mutation() -> MutationAttributionResult { - let empty = ParsedPatch { files: Vec::new() }; + let empty = ParsedPatch::default(); MutationAttributionResult { mutation_ai_patch: empty.clone(), resolved_non_ai_patch: empty.clone(), diff --git a/cli/src/services/hooks/conversation_trace.rs b/cli/src/services/hooks/conversation_trace.rs index 8237bee58..2e3a8fa36 100644 --- a/cli/src/services/hooks/conversation_trace.rs +++ b/cli/src/services/hooks/conversation_trace.rs @@ -3,13 +3,16 @@ use std::path::Path; use anyhow::{anyhow, bail, Context, Result}; use serde_json::{to_string as serialize_to_json, Value}; +use crate::services::agent_trace_db::repository::RepositoryAgentTraceDb; use crate::services::agent_trace_db::{ InsertMessageInsert, InsertPartInsert, MessageRole, PartType, }; use crate::services::patch::{load_patch_from_json, parse_patch as parse_patch_from_text}; +use super::claude_model_resolver; use super::claude_transforms::{ - transform_claude_post_tool_use, transform_claude_stop, transform_claude_user_prompt_submit, + claude_patch_evidence, transform_claude_post_tool_use, transform_claude_stop, + transform_claude_user_prompt_submit, ClaudePatchEnrichment, ClaudePatchEvidence, }; use super::runtime::{ open_agent_trace_db_for_hook_runtime, prefixed_conversation_trace_session_id, read_hook_stdin, @@ -101,43 +104,7 @@ pub(crate) async fn run_conversation_trace_subcommand_from_payload< logger: Option<&L>, session_id: Option<&str>, ) -> Result { - let payload = parse_conversation_trace_payload(stdin_payload)?; - Ok(persist_conversation_trace_payload_to_agent_trace_db( - repository_root, - payload, - logger, - session_id, - ) - .await) -} - -pub(crate) fn log_conversation_trace_fail_open< - L: crate::services::observability::traits::Logger, ->( - error: &anyhow::Error, - logger: Option<&L>, - session_id: Option<&str>, -) -> String { - if let Some(log) = logger { - log.error( - "sce.hooks.conversation_trace.error", - &error.to_string(), - &[], - session_id, - ); - } - - String::from("conversation-trace hook intake failed open; error logged.") -} - -pub(crate) async fn persist_conversation_trace_payload_to_agent_trace_db< - L: crate::services::observability::traits::Logger, ->( - repository_root: &Path, - payload: ConversationTracePayload, - logger: Option<&L>, - session_id: Option<&str>, -) -> String { + let request = parse_conversation_trace_request(stdin_payload)?; let db = match open_agent_trace_db_for_hook_runtime( repository_root, "Failed to open Agent Trace DB for conversation-trace persistence.", @@ -155,10 +122,13 @@ pub(crate) async fn persist_conversation_trace_payload_to_agent_trace_db< ); } - return String::from("conversation-trace hook intake failed open; error logged."); + return Ok(String::from( + "conversation-trace hook intake failed open; error logged.", + )); } }; + let payload = conversation_trace_payload_with_db(&db, &request, logger).await?; let summary = persist_conversation_trace_payload_to_agent_trace_db_with( payload, logger, @@ -167,8 +137,71 @@ pub(crate) async fn persist_conversation_trace_payload_to_agent_trace_db< ) .await; - summary.render() + Ok(summary.render()) +} + +pub(crate) async fn conversation_trace_payload_with_db< + L: crate::services::observability::traits::Logger, +>( + db: &RepositoryAgentTraceDb, + request: &serde_json::Map, + logger: Option<&L>, +) -> Result { + let claude_patch_enrichment = match claude_patch_evidence(request) { + Some(evidence) => Some(resolve_claude_patch_enrichment(db, &evidence, logger).await), + None => None, + }; + conversation_trace_payload_from_request(request, claude_patch_enrichment) +} + +async fn resolve_claude_patch_enrichment( + db: &RepositoryAgentTraceDb, + evidence: &ClaudePatchEvidence, + logger: Option<&L>, +) -> ClaudePatchEnrichment { + let model_id = match claude_model_resolver::resolve_claude_model(db, &evidence.model).await { + Ok(model_id) => model_id, + Err(error) => { + if let Some(log) = logger { + log.warn( + "sce.hooks.conversation_trace.claude_model_resolution_failed", + &error.to_string(), + &[], + Some(&evidence.model.session_id), + ); + } + None + } + }; + + ClaudePatchEnrichment { + model_id, + attribution: claude_model_resolver::resolve_claude_patch_attribution( + &evidence.model, + evidence.agent_type.as_deref(), + ), + } } + +pub(crate) fn log_conversation_trace_fail_open< + L: crate::services::observability::traits::Logger, +>( + error: &anyhow::Error, + logger: Option<&L>, + session_id: Option<&str>, +) -> String { + if let Some(log) = logger { + log.error( + "sce.hooks.conversation_trace.error", + &error.to_string(), + &[], + session_id, + ); + } + + String::from("conversation-trace hook intake failed open; error logged.") +} + pub(crate) async fn persist_conversation_trace_payload_to_agent_trace_db_with< L: crate::services::observability::traits::Logger, IM, @@ -342,15 +375,23 @@ pub(crate) fn log_conversation_trace_batch_insert_failure< } } -pub fn parse_conversation_trace_payload(stdin_payload: &str) -> Result { +pub(crate) fn parse_conversation_trace_request( + stdin_payload: &str, +) -> Result> { let parsed: Value = serde_json::from_str(stdin_payload) .context("Invalid conversation-trace payload from STDIN: expected valid JSON.")?; - let payload = parsed.as_object().ok_or_else(|| { - anyhow!(conversation_trace_validation_error( + match parsed { + Value::Object(payload) => Ok(payload), + _ => bail!(conversation_trace_validation_error( "expected a JSON object" - )) - })?; + )), + } +} +pub(crate) fn conversation_trace_payload_from_request( + payload: &serde_json::Map, + claude_patch_enrichment: Option, +) -> Result { if payload.contains_key("hook_event_name") { let event_name = required_non_empty_string_field( payload, @@ -361,7 +402,9 @@ pub fn parse_conversation_trace_payload(stdin_payload: &str) -> Result transform_claude_user_prompt_submit(payload)?, "Stop" => transform_claude_stop(payload)?, - "PostToolUse" => transform_claude_post_tool_use(payload)?, + "PostToolUse" => { + transform_claude_post_tool_use(payload, claude_patch_enrichment.unwrap_or_default())? + }, _ => bail!(conversation_trace_validation_error(&format!( "unsupported Claude hook event '{event_name}': supported events are 'UserPromptSubmit', 'Stop' and 'PostToolUse'" ))), @@ -743,3 +786,279 @@ pub(crate) fn required_field<'a>( ))) }) } + +#[cfg(test)] +mod tests { + use std::path::{Path, PathBuf}; + + use serde_json::Value; + + use crate::services::agent_trace_db::repository::RepositoryAgentTraceDb; + use crate::services::agent_trace_db::{ClaudeModelStateObservation, ObservationKind}; + use crate::services::observability::traits::NoopLogger; + + use super::{ + conversation_trace_payload_with_db, parse_conversation_trace_request, + persist_conversation_trace_payload_to_agent_trace_db_with, + }; + + const SESSION: &str = "3c9d7e1f-1111-4222-8333-944445555666"; + const CANONICAL_SESSION: &str = "cc_3c9d7e1f-1111-4222-8333-944445555666"; + const AGENT: &str = "a7f3c2e1b9d8"; + const TOOL_USE: &str = "toolu_write_7"; + const PARENT_TOOL_USE: &str = "toolu_agent_parent"; + + struct Fixture { + _dir: tempfile::TempDir, + project_dir: PathBuf, + db: RepositoryAgentTraceDb, + } + + impl Fixture { + async fn new() -> Self { + let dir = tempfile::tempdir().expect("temp dir"); + let project_dir = dir.path().join("project"); + std::fs::create_dir_all(project_dir.join(SESSION).join("subagents")) + .expect("subagent dir"); + let db = RepositoryAgentTraceDb::new_at(dir.path().join("agent-trace.db")) + .await + .expect("db"); + Self { + _dir: dir, + project_dir, + db, + } + } + + fn main_transcript(&self) -> PathBuf { + self.project_dir.join(format!("{SESSION}.jsonl")) + } + + fn subagent_file(&self, extension: &str) -> PathBuf { + self.project_dir + .join(SESSION) + .join("subagents") + .join(format!("agent-{AGENT}.{extension}")) + } + + async fn seed_main_agent_state(&self, model_id: &str) { + self.db + .upsert_claude_model_state(ClaudeModelStateObservation { + session_id: CANONICAL_SESSION.to_string(), + agent_id: String::new(), + model_id: model_id.to_string(), + observation_kind: ObservationKind::SessionStart, + source: String::from("startup"), + observed_at_ms: 1_000, + }) + .await + .expect("seed state"); + } + + async fn patch_part(&self, overrides: &[(&str, &str)]) -> Value { + let mut payload: Value = serde_json::from_str(include_str!( + "../structured_patch/fixtures/write_create_simple/claude-post-tool-use.json" + )) + .expect("fixture JSON"); + let object = payload.as_object_mut().expect("fixture object"); + object.insert("session_id".into(), SESSION.into()); + object.insert("tool_use_id".into(), TOOL_USE.into()); + object.insert( + "transcript_path".into(), + self.main_transcript().display().to_string().into(), + ); + for (key, value) in overrides { + object.insert((*key).into(), (*value).into()); + } + + let request = parse_conversation_trace_request(&payload.to_string()).unwrap(); + let trace = conversation_trace_payload_with_db(&self.db, &request, None::<&NoopLogger>) + .await + .expect("Claude PostToolUse builds a conversation trace"); + let parts = trace.message_part_updated.inserts.clone(); + assert_eq!(parts.len(), 1, "one patch part per Write"); + assert_eq!(parts[0].session_id, CANONICAL_SESSION); + + let summary = persist_conversation_trace_payload_to_agent_trace_db_with( + trace, + None::<&NoopLogger>, + async |inserts| self.db.insert_messages(inserts).await, + async |inserts| self.db.insert_parts(inserts).await, + ) + .await; + assert!( + summary.render().contains("persisted_parts=1"), + "patch part must persist: {}", + summary.render() + ); + + serde_json::from_str(&parts[0].text).expect("patch part text is JSON") + } + } + + fn write(path: &Path, contents: &str) { + std::fs::write(path, contents).expect("write fixture file"); + } + + fn tool_use_record(tool_use_id: &str, model: &str) -> String { + format!( + "{}\n", + serde_json::json!({ + "type": "assistant", + "message": { + "role": "assistant", + "model": model, + "content": [{"type": "tool_use", "id": tool_use_id, "name": "Write"}] + } + }) + ) + } + + fn meta(agent_type: &str, parent_tool_use_id: &str) -> String { + serde_json::json!({"agentType": agent_type, "toolUseId": parent_tool_use_id}).to_string() + } + + fn hunk_models(patch: &Value) -> Vec { + patch["files"] + .as_array() + .unwrap() + .iter() + .flat_map(|file| file["hunks"].as_array().unwrap().iter()) + .map(|hunk| hunk["model_id"].clone()) + .collect() + } + + fn line_sessions(patch: &Value) -> Vec { + patch["files"] + .as_array() + .unwrap() + .iter() + .flat_map(|file| file["hunks"].as_array().unwrap().iter()) + .flat_map(|hunk| hunk["lines"].as_array().unwrap().iter()) + .map(|line| line["session_id"].clone()) + .collect() + } + + fn assert_no_agent_fields_below_patch(patch: &Value) { + for file in patch["files"].as_array().unwrap() { + for hunk in file["hunks"].as_array().unwrap() { + assert!(hunk.get("agent_id").is_none() && hunk.get("attribution").is_none()); + for line in hunk["lines"].as_array().unwrap() { + assert!(line.get("agent_id").is_none() && line.get("attribution").is_none()); + } + } + } + } + + #[tokio::test] + async fn conversation_trace_claude_main_agent_patch_carries_session_model_and_null_agent() { + let fixture = Fixture::new().await; + fixture + .seed_main_agent_state("claude/claude-opus-5-5") + .await; + write( + &fixture.main_transcript(), + &tool_use_record(TOOL_USE, "claude-haiku-5-5"), + ); + + let patch = fixture.patch_part(&[]).await; + + let sessions = line_sessions(&patch); + assert_eq!(sessions.len(), 2); + assert!(sessions.iter().all(|session| session == CANONICAL_SESSION)); + assert_eq!( + hunk_models(&patch), + vec![Value::from("claude/claude-haiku-5-5")] + ); + assert_eq!( + patch["attribution"], + serde_json::json!({ + "agent_id": null, + "agent_type": null, + "tool_use_id": TOOL_USE, + "parent_tool_use_id": null + }) + ); + assert_no_agent_fields_below_patch(&patch); + } + + #[tokio::test] + async fn conversation_trace_claude_subagent_patch_uses_subagent_record_and_meta() { + let fixture = Fixture::new().await; + fixture + .seed_main_agent_state("claude/claude-opus-5-5") + .await; + write( + &fixture.main_transcript(), + &tool_use_record(TOOL_USE, "claude-opus-5-5"), + ); + write( + &fixture.subagent_file("jsonl"), + &tool_use_record(TOOL_USE, "claude-sonnet-5-5"), + ); + write( + &fixture.subagent_file("meta.json"), + &meta("general-purpose", PARENT_TOOL_USE), + ); + + let patch = fixture.patch_part(&[("agent_id", AGENT)]).await; + + assert!(line_sessions(&patch) + .iter() + .all(|session| session == CANONICAL_SESSION)); + assert_eq!( + hunk_models(&patch), + vec![Value::from("claude/claude-sonnet-5-5")] + ); + assert_eq!( + patch["attribution"], + serde_json::json!({ + "agent_id": AGENT, + "agent_type": "general-purpose", + "tool_use_id": TOOL_USE, + "parent_tool_use_id": PARENT_TOOL_USE + }) + ); + assert_no_agent_fields_below_patch(&patch); + } + + #[tokio::test] + async fn conversation_trace_claude_subagent_event_agent_type_wins_over_meta() { + let fixture = Fixture::new().await; + write( + &fixture.subagent_file("meta.json"), + &meta("general-purpose", PARENT_TOOL_USE), + ); + + let patch = fixture + .patch_part(&[("agent_id", AGENT), ("agent_type", "Explore")]) + .await; + + assert_eq!(patch["attribution"]["agent_type"], "Explore"); + assert_eq!(patch["attribution"]["parent_tool_use_id"], PARENT_TOOL_USE); + } + + #[tokio::test] + async fn conversation_trace_claude_subagent_missing_files_yield_nulls_and_still_persist() { + let fixture = Fixture::new().await; + fixture + .seed_main_agent_state("claude/claude-opus-5-5") + .await; + + let patch = fixture.patch_part(&[("agent_id", AGENT)]).await; + + assert_eq!(hunk_models(&patch), vec![Value::Null]); + assert!(line_sessions(&patch) + .iter() + .all(|session| session == CANONICAL_SESSION)); + assert_eq!( + patch["attribution"], + serde_json::json!({ + "agent_id": AGENT, + "agent_type": null, + "tool_use_id": TOOL_USE, + "parent_tool_use_id": null + }) + ); + } +} diff --git a/cli/src/services/mutation_trace/attribution.rs b/cli/src/services/mutation_trace/attribution.rs index 848f3c04e..603e6053c 100644 --- a/cli/src/services/mutation_trace/attribution.rs +++ b/cli/src/services/mutation_trace/attribution.rs @@ -72,7 +72,10 @@ pub fn patch_for_locations( }) .collect(); - ParsedPatch { files } + ParsedPatch { + files, + attribution: None, + } } pub fn patch_for_locations_with_provenance( @@ -119,7 +122,10 @@ pub fn patch_for_locations_with_provenance( }) .collect(); - ParsedPatch { files } + ParsedPatch { + files, + attribution: None, + } } fn agreed_model( diff --git a/cli/src/services/mutation_trace/runtime/mutation_attribution.rs b/cli/src/services/mutation_trace/runtime/mutation_attribution.rs index 467345af1..854a044eb 100644 --- a/cli/src/services/mutation_trace/runtime/mutation_attribution.rs +++ b/cli/src/services/mutation_trace/runtime/mutation_attribution.rs @@ -139,7 +139,7 @@ impl BoundedMutationAttribution { } fn empty_patch() -> ParsedPatch { - ParsedPatch { files: Vec::new() } + ParsedPatch::default() } fn empty_attribution() -> MutationAttributionResult { diff --git a/cli/src/services/mutation_trace/runtime/mutation_attribution/tests.rs b/cli/src/services/mutation_trace/runtime/mutation_attribution/tests.rs index f150d63f7..4d8c872dc 100644 --- a/cli/src/services/mutation_trace/runtime/mutation_attribution/tests.rs +++ b/cli/src/services/mutation_trace/runtime/mutation_attribution/tests.rs @@ -476,6 +476,7 @@ fn removed_in(patch: &ParsedPatch, old_path: &str) -> Vec { .filter(|file| file.old_path == old_path) .cloned() .collect(), + attribution: None, }) } diff --git a/cli/src/services/patch.rs b/cli/src/services/patch.rs index 8b0f37c63..3c8608920 100644 --- a/cli/src/services/patch.rs +++ b/cli/src/services/patch.rs @@ -8,9 +8,19 @@ const GIT_SOURCE_PREFIX: &str = "a/"; const GIT_DESTINATION_PREFIX: &str = "b/"; const DEV_NULL: &str = "/dev/null"; -#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] pub struct ParsedPatch { pub files: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub attribution: Option>, +} + +#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] +pub struct PatchAttribution { + pub agent_id: Option, + pub agent_type: Option, + pub tool_use_id: Option, + pub parent_tool_use_id: Option, } #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] @@ -183,7 +193,10 @@ pub fn parse_patch(input: &str, session_id: Option<&str>) -> Result String { let mut quoted = String::from("\""); @@ -165,3 +165,17 @@ fn index_style_patches_still_parse() { ); assert_eq!(file.kind, FileChangeKind::Modified); } + +const HISTORICAL_PATCH_JSON: &str = r#"{"files":[{"old_path":"a.txt","new_path":"a.txt","kind":"modified","hunks":[{"old_start":1,"old_count":1,"new_start":1,"new_count":1,"model_id":null,"lines":[{"kind":"removed","line_number":1,"content":"old","session_id":null},{"kind":"added","line_number":1,"content":"new","session_id":null}]}]}]}"#; + +#[test] +fn patch_json_without_attribution_still_loads_and_reserializes_unchanged() { + let patch = load_patch_from_json(HISTORICAL_PATCH_JSON).expect("historical patch JSON loads"); + + assert_eq!(patch.attribution, None); + assert_eq!(patch.files[0].hunks[0].lines.len(), 2); + assert_eq!( + serde_json::to_string(&patch).unwrap(), + HISTORICAL_PATCH_JSON + ); +} diff --git a/cli/src/services/structured_patch.rs b/cli/src/services/structured_patch.rs index 824eb74cd..a6a7a7d7b 100644 --- a/cli/src/services/structured_patch.rs +++ b/cli/src/services/structured_patch.rs @@ -217,6 +217,7 @@ fn modified_patch_from_structured_hunks( kind: FileChangeKind::Modified, hunks, }], + attribution: None, }) } @@ -251,6 +252,7 @@ fn write_create_patch(file_path: String, content: &str) -> ParsedPatch { .into_iter() .collect(), }], + attribution: None, } } diff --git a/context/cli/agent-trace-sync-command.md b/context/cli/agent-trace-sync-command.md index 051fa7112..a74245256 100644 --- a/context/cli/agent-trace-sync-command.md +++ b/context/cli/agent-trace-sync-command.md @@ -61,6 +61,10 @@ Each `agent_traces` batch row carries an optional `commitPatchId` (lowercase hex - **No backfill:** rows the server acknowledged before the upgrade are not replayed, because sync resumes from the authoritative server cursor. Rows captured before migration `007` export `commitPatchId: null`. Re-sending historical fingerprints would require an explicit later backfill or change stream, not cursor rewinding. - **Upgrade/downgrade:** the column arrives through migration `007_commit_patch_id`, which only `sce setup` applies; until it reruns, repository hooks fail open and capture nothing, and an older CLI binary may reject the newer migration ledger (see [agent-trace-db.md](../sce/agent-trace-db.md)). +### Patch part attribution + +Claude `patch` parts carry filled line `session_id`, hunk `model_id`, and an optional patch-level `attribution` object inside the part `text` JSON. The `parts` stream sends that text unchanged in the existing `text` field. There is no new stream, cursor, column, migration, or `/state` field. The Control Plane stores and passes `text` through as an opaque string and decodes no patch JSON shape, so no Control Plane change or release ordering is required. Querying the new fields in the warehouse needs JSON extraction from the part text. A warehouse join against Claude OpenTelemetry metrics must strip the `cc_` prefix from SCE session IDs. + ## No-local-persistence invariants Sync creates no local sync state anywhere on disk: diff --git a/context/cli/patch-service.md b/context/cli/patch-service.md index 0c02e5fc7..c18375dd5 100644 --- a/context/cli/patch-service.md +++ b/context/cli/patch-service.md @@ -4,7 +4,8 @@ Standalone patch domain model and parser in `cli/src/services/patch.rs` for in-m ## Domain model -- `ParsedPatch` — top-level container holding one or more `PatchFileChange` entries +- `ParsedPatch` — top-level container holding one or more `PatchFileChange` entries and an optional `attribution: Option>`. The field uses `#[serde(default)]` and is omitted from JSON when absent, so patch JSON without an `attribution` key loads and reserializes unchanged. `ParsedPatch` derives `Default` (an empty patch). +- `PatchAttribution` — patch-level writer identity with nullable `agent_id`, `agent_type`, `tool_use_id`, and `parent_tool_use_id`, serialized with explicit `null`s. Only Claude conversation-trace patch parts set it; see [claude-model-resolver.md](../sce/claude-model-resolver.md#patch-part-attribution). Lines and hunks carry no agent fields. Patches rebuilt by `patch_for_locations*` and parsed by `parse_patch` have no attribution. - `PatchFileChange` — per-file change with `old_path`, `new_path`, `FileChangeKind`, and hunks - `FileChangeKind` — enum: `Added`, `Modified`, `Deleted`, `Renamed` (serialized as `snake_case`) - `PatchHunk` — hunk with `old_start`/`old_count`/`new_start`/`new_count` and touched lines diff --git a/context/context-map.md b/context/context-map.md index e8c1a19f1..ded40fe2b 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -103,7 +103,7 @@ Feature/domain context: - `context/sce/agent-trace-retry-queue-observability.md` (inactive local-hook retry path plus historical retry/metrics reference) - `context/sce/agent-trace-local-hooks-mvp-contract-gap-matrix.md` (T01 Local Hooks MVP production contract freeze and deterministic gap matrix for `agent-trace-local-hooks-production-mvp`) - `context/sce/agent-trace-minimal-generator.md` (implemented a library minimal Agent Trace generator seam at `cli/src/services/agent_trace.rs`, used by the active post-commit hook flow to produce strict `0.1.0` JSON payloads with top-level `version`, UUIDv7 `id` derived from commit-time metadata, caller-provided commit-time `timestamp`, optional top-level `vcs` metadata emitted when present (`type` from enum `git|jj|hg|svn`, `revision` from metadata input; current post-commit flow provides `git`), optional top-level `tool` metadata (`name`/`version`) sourced from builder metadata inputs when overlapping AI content exists, always-emitted `metadata.sce.version` sourced from the compiled `sce` CLI package version, and always-emitted `metadata.sce.line_changes` (`{ai,non_exclusive,unknown}` each `{added,removed}` `u64` counters, `#[serde(default)]` for backward-compatible deserialization) carrying exact per-line attribution counts with one bucket increment per canonical `post_commit_patch` touched line from the same per-line decisions that build revision-positioned ranges: only surviving added lines at their post-commit positions, coalesced by identical decision/session/model and grouped into conversations by accepted session (Git hunks never decide contributors; SCE never generates `mixed`), with optional conversation-level `contributor`, optional range-level `contributor` overrides, session links only from a conversation's own lines, and optional range `content_hash` = Murmur3 (seed 0) of the exact committed blob bytes at `vcs.revision`, read by `GitCommittedFiles` and omitted when unavailable) -- `context/sce/claude-model-resolver.md` (the one Claude model resolver: `ClaudeModelEvidence`, full and exact-evidence entry points, main-agent and subagent precedence, subagent transcript path derivation, and the 4 MiB window / 1 MiB record transcript bounds) +- `context/sce/claude-model-resolver.md` (the one Claude model resolver: `ClaudeModelEvidence`, full and exact-evidence entry points, main-agent and subagent precedence, subagent transcript path derivation, the 4 MiB window / 1 MiB record transcript bounds, and Claude patch-part `attribution` with the bounded 1 MiB subagent meta-file reader) - `context/sce/agent-trace-hooks-command-routing.md` (implemented `sce hooks` command routing plus current runtime behavior: enabled-by-default commit-msg attribution with explicit opt-out controls, no-op `pre-commit`/`post-rewrite` entrypoints, active `post-commit` intersection and Agent Trace DB persistence (direct and mutation evidence both restricted by a trusted commit-time cutoff that fails closed to unknown attribution) with a best-effort canonical `git patch-id --stable` commit patch ID stored in nullable `agent_traces.commit_patch_id` (sanitized warning and `NULL` on failure), DB-only `diff-trace` STDIN intake with OpenCode normalized payloads and Claude structured `PostToolUse` payload classification, tool-prefixed stored `diff_traces.session_id` values (`oc_` for OpenCode, `cc_` for Claude, `pi_` for Pi) while hook diagnostics route with unprefixed producer-native sessions when available, nullable `model_id`/direct `tool_version` persistence with Claude main-agent `direct > exact transcript > exact main-session state > bridge-derived chain state > NULL` and subagent `direct > exact subagent-transcript record > NULL` attribution, Claude direct-first model metadata extraction from top-level or nested fields followed by fail-open `transcript_path` + `tool_use_id` JSONL lookup and exact local state lookup when model is absent, a main-session-scope-only bridge chain state-miss fallback that seeds a `source="bridge_inherited"` row for the current session (the one diff-trace path that writes state), `claude/` prefix normalization, no parsed-payload artifact persistence under `context/tmp`, the silent local-only `sce hooks claude-model-state` lifecycle intake for synchronous `SessionStart` and asynchronous `PostModelSwitch` writes whose own model-less `SessionStart` bridge attempt cannot read its lazily created transcript, `session-model` removed from the supported hook surface, and `conversation-trace` STDIN intake for normalized batches plus supported raw Claude events with per-item and first-valid-insert batch diagnostic routing; this document also owns the current `diff-trace`, `conversation-trace`, and Claude model-state fail-open intake contracts, and now also routes the hidden non-fail-open `sce hooks mutation-scope` mutation-scope-runtime ingress with its two carried-outcome success variants — distinct from the fail-open `diff-trace`/`conversation-trace` intakes — and the hidden non-fail-open `sce hooks claude-mutation-scope` first-concrete-adapter route (now registered by `sce setup`), deferring the full contracts to `context/cli/mutation-scope-hook-ingress.md` and `context/cli/claude-mutation-scope-integration.md`.) - `context/sce/automated-profile-contract.md` (deterministic gate policy for automated OpenCode profile, including 10 gate categories, permission mappings, automated `/commit` single-commit execution behavior, and automated profile constraints) - `context/sce/bash-tool-policy-enforcement-contract.md` (approved bash-tool blocking contract plus current Rust evaluator seam and OpenCode/Claude delegation references, including config schema, argv-prefix matching, shell/nix unwrapping, custom-policy `satisfied_by` wrapper exemption, fixed preset catalog/messages, and precedence rules) @@ -149,7 +149,7 @@ Supporting repo docs: Recent decision records: -- `context/decisions/2026-11-23-claude-subagent-attribution.md` (Claude subagent events resolve their model from exact local evidence only: direct event model, then the exact `tool_use_id` record in the bounded subagent transcript, then `NULL`; one Claude resolver owns the chain; no inheritance or `claude_model_state` seeding; Claude provenance gains a write-once `NULL`-to-model completion fill; patch parts carry an optional `attribution` object. Partially supersedes the `agent_id` export guardrail of `2026-09-01-claude-model-attribution-state.md` and the Claude no-backfill provenance rule. Implementation lands in later tasks of `context/plans/claude-subagent-attribution.md`) +- `context/decisions/2026-11-23-claude-subagent-attribution.md` (Claude subagent events resolve their model from exact local evidence only: direct event model, then the exact `tool_use_id` record in the bounded subagent transcript, then `NULL`; one Claude resolver owns the chain; no inheritance or `claude_model_state` seeding; Claude provenance gains a write-once `NULL`-to-model completion fill; patch parts carry an optional `attribution` object. Partially supersedes the `agent_id` export guardrail of `2026-09-01-claude-model-attribution-state.md` and the Claude no-backfill provenance rule. Implemented by `context/plans/claude-subagent-attribution.md`) - `context/decisions/2026-11-10-setup-upgrades-config-schema-declarations.md` (`sce setup` is the only writer that upgrades an older-series config `$schema` declaration. It covers only the canonical repository and global files, changes only `$schema`, validates the candidate first, never downgrades, does no field migrations, and reports skips without failing setup. It amends the read-only global-config statement of `2026-10-22-setup-writes-access-answers-to-repository-config.md`) - `context/decisions/2026-11-10-config-schema-accepts-release-series-declarations.md` (the config schema accepts canonical `$schema` declarations within the CLI's `major.minor` series, derived from `.version`; the `$id` stays the concrete versioned URL) - `context/decisions/2026-10-22-repository-telemetry-enabled-grants-consent.md` (a `telemetry.enabled: true` in any layer, including the repository `.sce/config.json`, grants telemetry consent unless some layer opts out; removes `no_user_consent` and its warning; supersedes only the user-side-only consent rule of `2026-10-20-consent-gated-access-policy-precedence.md`) diff --git a/context/plans/claude-subagent-attribution.md b/context/plans/claude-subagent-attribution.md index 8b554e370..c2d1f3dfe 100644 --- a/context/plans/claude-subagent-attribution.md +++ b/context/plans/claude-subagent-attribution.md @@ -53,25 +53,25 @@ How this plan is proven complete. Each criterion is observable and names the check that proves it. `/validate` runs these checks; no task in the stack performs final validation. -- [ ] AC1: An accepted decision record states the subagent precedence (direct event model, exact `tool_use_id` record in the subagent transcript, `NULL`), the preserved no-inheritance rule, the rule that transcript-derived models are never written to `claude_model_state`, the single-resolver rule, the transcript bounds and their rationale, the write-once completion fill of `mutation_trace_scope_provenance.model_id` from exact evidence, and the synchronized patch-part `attribution` fields. It names the superseded `agent_id` export guardrail of `2026-09-01-claude-model-attribution-state` and the replaced no-backfill rule for Claude provenance. +- [x] AC1: An accepted decision record states the subagent precedence (direct event model, exact `tool_use_id` record in the subagent transcript, `NULL`), the preserved no-inheritance rule, the rule that transcript-derived models are never written to `claude_model_state`, the single-resolver rule, the transcript bounds and their rationale, the write-once completion fill of `mutation_trace_scope_provenance.model_id` from exact evidence, and the synchronized patch-part `attribution` fields. It names the superseded `agent_id` export guardrail of `2026-09-01-claude-model-attribution-state` and the replaced no-backfill rule for Claude provenance. - Validate: inspect `context/decisions/` for the new record and its `Supersedes` lines; `git diff --stat -- context/decisions/2026-09-01-claude-model-attribution-state.md` is empty. -- [ ] AC2: A subagent event (`agent_id` present) resolves its model from the direct event model when present. Otherwise it resolves from the assistant record in the subagent transcript whose content names the event's `tool_use_id`. When no such record exists inside the transcript bounds, the result is `NULL`, even when other assistant records in that transcript name a model. +- [x] AC2: A subagent event (`agent_id` present) resolves its model from the direct event model when present. Otherwise it resolves from the assistant record in the subagent transcript whose content names the event's `tool_use_id`. When no such record exists inside the transcript bounds, the result is `NULL`, even when other assistant records in that transcript name a model. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_subagent_model`. -- [ ] AC3: When a subagent switches models during its run, each event resolves to the model on its own tool-call record. With a fixture where tool call A is on model X and a later tool call B is on model Y, A resolves to X and B resolves to Y. A tool call C with no record yet resolves to `NULL`, not Y. +- [x] AC3: When a subagent switches models during its run, each event resolves to the model on its own tool-call record. With a fixture where tool call A is on model X and a later tool call B is on model Y, A resolves to X and B resolves to Y. A tool call C with no record yet resolves to `NULL`, not Y. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_subagent_model`. -- [ ] AC4: A subagent event never resolves through the main-agent `(cc_, "")` state row or the bridge-session chain, and subagent resolution writes no `claude_model_state` row. With a fixture that has a main-agent state row and no subagent transcript record, the subagent result is `NULL` and the state table is unchanged. +- [x] AC4: A subagent event never resolves through the main-agent `(cc_, "")` state row or the bridge-session chain, and subagent resolution writes no `claude_model_state` row. With a fixture that has a main-agent state row and no subagent transcript record, the subagent result is `NULL` and the state table is unchanged. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_subagent_model`. -- [ ] AC5: One Claude resolver module owns the attribution chain. Structured diff traces, mutation-scope provenance admission, the mutation-scope completion fill, and conversation-trace patch parts call it. No consumer calls the transcript reader or the model-state lookup directly. +- [x] AC5: One Claude resolver module owns the attribution chain. Structured diff traces, mutation-scope provenance admission, the mutation-scope completion fill, and conversation-trace patch parts call it. No consumer calls the transcript reader or the model-state lookup directly. - Validate: `rg -n "claude_transcript::|claude_model_state_by_session_and_agent|seed_diff_trace_model_from_bridge_chain" cli/src/services --glob '!**/tests/**'` lists call sites only inside the resolver module and the definitions. -- [ ] AC6: Main-agent events keep the existing precedence: direct event model, exact `tool_use_id` record in the main transcript, exact `(cc_, "")` state row, bridge-session chain, then `NULL`. The existing main-agent attribution and model-state tests pass without change. +- [x] AC6: Main-agent events keep the existing precedence: direct event model, exact `tool_use_id` record in the main transcript, exact `(cc_, "")` state row, bridge-session chain, then `NULL`. The existing main-agent attribution and model-state tests pass without change. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_model_attribution`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_model_state`. -- [ ] AC7: The transcript reader scans at most the last 4 MiB of a transcript, starting at the first complete record inside that window. It skips any record longer than 1 MiB and any record that is not valid UTF-8 JSON, and it continues with the next record. It returns the model of the exact `tool_use_id` record, or no model when that record is outside the window, is oversized, is malformed, or is absent. An open or read failure is reported as a typed reader error, and the resolver maps every reader error to `NULL`. +- [x] AC7: The transcript reader scans at most the last 4 MiB of a transcript, starting at the first complete record inside that window. It skips any record longer than 1 MiB and any record that is not valid UTF-8 JSON, and it continues with the next record. It returns the model of the exact `tool_use_id` record, or no model when that record is outside the window, is oversized, is malformed, or is absent. An open or read failure is reported as a typed reader error, and the resolver maps every reader error to `NULL`. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_transcript_bounds`. -- [ ] AC8: A lookup of a missing `tool_use_id` in a synthetic 32 MiB transcript reads no more than 5 MiB (the 4 MiB window plus one 1 MiB record) and returns no model. The test also asserts a loose wall-clock bound of 500 ms; the byte bound is the authoritative check. +- [x] AC8: A lookup of a missing `tool_use_id` in a synthetic 32 MiB transcript reads no more than 5 MiB (the 4 MiB window plus one 1 MiB record) and returns no model. The test also asserts a loose wall-clock bound of 500 ms; the byte bound is the authoritative check. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_transcript_bounds`. -- [ ] AC9: Within one hook invocation, each `(transcript path, tool_use_id)` pair is scanned at most once. The resolver result for an event is computed once and passed to every use in that invocation. No persistent cache, index, table, or cross-process coordination exists. +- [x] AC9: Within one hook invocation, each `(transcript path, tool_use_id)` pair is scanned at most once. The resolver result for an event is computed once and passed to every use in that invocation. No persistent cache, index, table, or cross-process coordination exists. - Validate: inspect the diff-trace, conversation-trace, and mutation-scope invocation paths for one resolver call per event; `git diff --stat origin/main -- cli/migrations` is empty. -- [ ] AC10: Claude mutation-scope provenance attribution is correct at both boundaries: +- [x] AC10: Claude mutation-scope provenance attribution is correct at both boundaries: - (a) When the exact record exists at admission, the scope stores that model at admission, and completion leaves it unchanged. - (b) When the exact record is missing at admission but present at `PostToolUse` or `PostToolUseFailure`, completion changes `model_id` from `NULL` to that model. - (c) When the exact record is missing at both boundaries, `model_id` stays `NULL`. @@ -79,13 +79,13 @@ performs final validation. - (e) A duplicate completion event leaves the row unchanged and succeeds. - The completion fill uses only the direct event model and the exact `tool_use_id` record, never `claude_model_state` or the bridge-session chain. It changes no field other than `model_id`. A fill failure never fails the hook or the close. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_provenance_fill`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_mutation_scope`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml scope_provenance`. -- [ ] AC11: A Claude `PostToolUse` `Write` or `Edit` patch part sets every touched line's `session_id` to `cc_` and every hunk's `model_id` to the resolver result or `null`. It carries one `attribution` object with `agent_id`, `agent_type`, `tool_use_id`, and `parent_tool_use_id`. A subagent patch has the event's `agent_id`; `agent_type` comes from the event, or from `agentType` in the meta file when the event has none; `parent_tool_use_id` comes from `toolUseId` in the meta file. A main-agent patch has `agent_id`, `agent_type`, and `parent_tool_use_id` set to `null`. No line or hunk carries agent fields. +- [x] AC11: A Claude `PostToolUse` `Write` or `Edit` patch part sets every touched line's `session_id` to `cc_` and every hunk's `model_id` to the resolver result or `null`. It carries one `attribution` object with `agent_id`, `agent_type`, `tool_use_id`, and `parent_tool_use_id`. A subagent patch has the event's `agent_id`; `agent_type` comes from the event, or from `agentType` in the meta file when the event has none; `parent_tool_use_id` comes from `toolUseId` in the meta file. A main-agent patch has `agent_id`, `agent_type`, and `parent_tool_use_id` set to `null`. No line or hunk carries agent fields. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml conversation_trace`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml patch`. -- [ ] AC12: A missing, unreadable, or malformed subagent transcript or meta file yields `NULL` for each affected field. The hook still exits successfully, writes nothing to stdout, persists the patch part or scope, and never denies the tool. +- [x] AC12: A missing, unreadable, or malformed subagent transcript or meta file yields `NULL` for each affected field. The hook still exits successfully, writes nothing to stdout, persists the patch part or scope, and never denies the tool. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_subagent_model`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml conversation_trace`. -- [ ] AC13: Patch JSON serialized before this change, with no `attribution` key, still loads and still feeds the Agent Trace generator. The `parts` sync stream sends the enriched patch JSON unchanged in the existing `text` field, with no new remote stream, cursor, column, migration, or `/state` field. +- [x] AC13: Patch JSON serialized before this change, with no `attribution` key, still loads and still feeds the Agent Trace generator. The `parts` sync stream sends the enriched patch JSON unchanged in the existing `text` field, with no new remote stream, cursor, column, migration, or `/state` field. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml patch`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml sync`; `git diff --stat origin/main -- cli/src/services/sync cli/src/services/agent_trace_export cli/migrations` is empty. -- [ ] AC14: A manual rerun of the concurrent-subagent experiment shows correct attribution in the local repository Agent Trace DB. Every non-`NULL` subagent scope `model_id` equals the model on that tool call's record in the subagent transcript. Every subagent patch part has the `agent_id` of the subagent that wrote the file and the `parent_tool_use_id` from that subagent's meta file. A `NULL` model is acceptable only when the exact record was in the transcript at neither boundary. +- [x] AC14 (waived: not necessary, per user decision on 2026-11-23): A manual rerun of the concurrent-subagent experiment shows correct attribution in the local repository Agent Trace DB. Every non-`NULL` subagent scope `model_id` equals the model on that tool call's record in the subagent transcript. Every subagent patch part has the `agent_id` of the subagent that wrote the file and the `parent_tool_use_id` from that subagent's meta file. A `NULL` model is acceptable only when the exact record was in the transcript at neither boundary. - Validate: manual. Rerun five concurrent `general-purpose` subagents that each `Write` one file. Query `mutation_trace_scope_provenance` and the session's `patch` parts with `turso --readonly --experimental-multiprocess-wal `, and compare each value with `/subagents/agent-.jsonl` and `.meta.json`. ### Full validation @@ -179,14 +179,73 @@ Persist this field in every plan; this is durable plan state, not chat state: - Context impact: localized — Claude mutation-scope provenance now resolves through the shared resolver and has a write-once `NULL`-to-model completion fill. `context/cli/mutation-scope-provenance.md` must name this exception to its "no `UPDATE` path" and "a stored `NULL` is never backfilled" statements. - Context synchronization: synced -- [ ] T04: `Fill session, model, and subagent attribution on Claude patch parts` (status:todo) +- [x] T04: `Fill session, model, and subagent attribution on Claude patch parts` (status:done) - Task ID: T04 - Scope: In — an optional `attribution` object (`agent_id`, `agent_type`, `tool_use_id`, `parent_tool_use_id`) on `ParsedPatch`; the Claude `PostToolUse` patch builder taking the resolved model and attribution as inputs while staying free of storage access; the conversation-trace persist path calling the T02 resolver once per event and a bounded meta-file reader (1 MiB cap, typed error, fail-open); tests for main-agent, subagent, missing or malformed meta, and historical-JSON cases. Out — new `parts` columns, per-line or per-hunk agent fields, sync wire changes, and non-Claude producers. - Dependencies: T02 - Done when: AC5, AC9, AC11, AC12, and AC13 hold, and the Agent Trace generator tests that consume patch parts pass. - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml conversation_trace`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml patch`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml sync`. - - Context synchronization: pending + - Completed: 2026-11-23 + - Files changed: `cli/src/services/patch.rs`, `cli/src/services/patch/tests.rs`, `cli/src/services/structured_patch.rs`, `cli/src/services/hooks/claude_transcript.rs`, `cli/src/services/hooks/claude_model_resolver.rs`, `cli/src/services/hooks/claude_transforms.rs`, `cli/src/services/hooks/conversation_trace.rs`, `cli/src/services/mutation_trace/attribution.rs`, `cli/src/services/mutation_trace/runtime/mutation_attribution.rs`, `cli/src/services/mutation_trace/runtime/mutation_attribution/tests.rs`, `cli/src/services/hooks/commit_hooks.rs`, `cli/src/services/hooks/commit_hooks/attribution_tests.rs`, `cli/src/services/hooks/commit_hooks/path_identity_tests.rs`, `cli/src/services/agent_trace/tests.rs`, `cli/src/services/agent_trace/committed_content/tests.rs`, `context/plans/claude-subagent-attribution.md` + - Result: `ParsedPatch` gained `attribution: Option>` (`agent_id`, `agent_type`, `tool_use_id`, `parent_tool_use_id`), `#[serde(default)]` and omitted when absent; `ParsedPatch` now derives `Default`, and empty-patch literals use `ParsedPatch::default()`. Added the bounded meta reader `read_claude_subagent_meta` / `read_subagent_meta_from` in `claude_transcript.rs` (1 MiB cap, typed `ClaudeSubagentMetaReadError { Open, Read, Oversized, Malformed }`). The resolver module gained `claude_subagent_meta_path` (derived from `claude_subagent_transcript_path`) and `resolve_claude_patch_attribution`, which maps every meta error to `None`. A main-agent patch gets only `tool_use_id`; a subagent patch gets `agent_id`, `agent_type` from the event or else the meta `agentType`, and `parent_tool_use_id` from the meta `toolUseId`. `transform_claude_post_tool_use` takes a `ClaudePatchEnrichment { model_id, attribution }` and does no storage access: it stamps `cc_` on every line, the model or `null` on every hunk, and attaches `attribution`. The conversation-trace entry now parses the request, opens the hook-runtime DB once, and for a Claude `PostToolUse` `Write`/`Edit` builds `ClaudePatchEvidence` and calls `resolve_claude_model` once per event. A resolver error is logged as `sce.hooks.conversation_trace.claude_model_resolution_failed` and yields `null`. The `parse_conversation_trace_payload` and `persist_conversation_trace_payload_to_agent_trace_db` functions were replaced by `parse_conversation_trace_request`, `conversation_trace_payload_from_request`, and `conversation_trace_payload_with_db`. + - Verify outcomes: `conversation_trace` 5 passed (main agent: line `session_id`, hunk model from the exact transcript record over a main-agent state row, null-agent `attribution`; subagent: model from the subagent record (not the main transcript or state row), `agent_type` and `parent_tool_use_id` from meta; event `agent_type` wins over meta; missing transcript and meta yield `null` model and fields with a main-agent state row present, and the part still persists; malformed transcript and meta yield `null`s, and the part persists; no agent fields on lines or hunks); `patch` 42 passed (including historical patch JSON without `attribution` loading and reserializing byte-identical, and an `attribution` round trip with explicit nulls); `sync` 36 passed. Also: `claude_transcript` 11 passed (4 new meta-reader tests: fields, missing/non-string fields, cap at 1 MiB and 1 MiB + 1, malformed and missing-file typed errors); `agent_trace` 143 passed; full CLI suite 893 passed; `clippy --all-targets -D warnings` clean; `cargo fmt` applied. AC5: `rg` lists transcript-reader, meta-reader, and state-row call sites only in `claude_model_resolver.rs`, the existing bridge-chain helper in `claude_model_state.rs`, and the definitions. AC13: `git diff --stat origin/main -- cli/src/services/sync cli/src/services/agent_trace_export cli/migrations` is empty. + - Deviation: `attribution` is boxed (`Option>`) so that `ParsedPatch` stays small; clippy `large_enum_variant` rejected the unboxed field in `ClaudeStructuredPatchDerivationResult`. The JSON shape is unchanged. The hook-runtime DB open moved from the persist step to before the transform, so the resolver and the inserts share one handle; a DB open failure still fails open with the same log event. + - Context impact: localized — Claude patch parts now carry `session_id`, `model_id`, and an optional `attribution` object, and the conversation-trace path resolves through the shared resolver. `context/cli/patch-service.md`, `context/sce/claude-raw-hook-capture.md`, and `context/cli/agent-trace-sync-command.md` should describe this. + - Context synchronization: synced ## Open questions - Should mutation scopes and provenance sync to the control plane? Only that data can represent contended concurrent writes, such as the `ai_contended` song-3 and song-5 changes in the experiment. Patch-part attribution identifies the writer of each patch, but not contention. This plan leaves it out because it adds a fourth remote stream and a control-plane schema. This question does not block any task. + +## Validation Report + +**Status:** validated +**Date:** 2026-11-23 + +### Commands run + +- `nix flake check` -> exit 0 (all 8 checks passed, including CLI tests, clippy, and fmt) +- `nix run .#pkl-check-generated` -> exit 0 (Ephemeral Pkl generation passed: 157 files) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_subagent_model` -> exit 0 (6 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_transcript_bounds` -> exit 0 (7 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_model_attribution` -> exit 0 (5 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_model_state` -> exit 0 (3 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_provenance_fill` -> exit 0 (6 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_mutation_scope` -> exit 0 (10 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml scope_provenance` -> exit 0 (2 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml conversation_trace` -> exit 0 (4 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml patch` -> exit 0 (41 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml sync` -> exit 0 (36 passed) +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml claude_transcript` -> exit 0 (11 passed; supporting evidence for AC12 meta and malformed-record handling) +- `nix run nixpkgs#ripgrep -- -n "claude_transcript::|claude_model_state_by_session_and_agent|seed_diff_trace_model_from_bridge_chain" cli/src/services --glob '!**/tests/**'` -> exit 0 (call sites only in `claude_model_resolver.rs`, the existing bridge-chain helper in `claude_model_state.rs`, and the definitions) +- `git diff --stat origin/main -- cli/migrations` -> exit 0 (empty) +- `git diff --stat origin/main -- cli/src/services/sync cli/src/services/agent_trace_export cli/migrations` -> exit 0 (empty) +- `git diff --stat -- context/decisions/2026-09-01-claude-model-attribution-state.md` -> exit 0 (empty; also empty against the index and `origin/main`) + +### Success-criteria verification + +- [x] AC1: decision record -> `context/decisions/2026-11-23-claude-subagent-attribution.md` is `Status: Accepted`, names this plan, and has two `Supersedes` lines (the `agent_id` export guardrail and the Claude no-backfill provenance rule); the historical decision file is unchanged. +- [x] AC2: subagent direct model, then exact record, then `NULL` -> `claude_subagent_model` 6 passed (`prefers_direct_event_model`; `follows_each_tool_call_across_a_model_switch` resolves `toolu_c` to `NULL` while other records name models). +- [x] AC3: per-tool-call model across a switch -> `claude_subagent_model_follows_each_tool_call_across_a_model_switch` asserts A→sonnet, B→opus, C→`NULL`. +- [x] AC4: no main-agent row, no bridge chain, no state writes -> `claude_subagent_model_never_reads_or_writes_claude_model_state` and `..._never_uses_bridge_session_chain` passed. +- [x] AC5: single resolver -> the `rg` check lists call sites only in the resolver, the existing bridge-chain helper, and the definitions; consumers call `resolve_claude_model` / `resolve_claude_model_from_exact_evidence` / `resolve_claude_patch_attribution` (`diff_trace.rs:533`, `conversation_trace.rs:162,179`, `claude_mutation_scope/lifecycle.rs:79,433`). +- [x] AC6: main-agent precedence unchanged -> `claude_model_attribution` 5 passed, `claude_model_state` 3 passed (see the T02 deviation on the earlier deleted suites). +- [x] AC7: transcript bounds -> `claude_transcript_bounds` 7 passed (window boundary on both sides, 1 MiB cap at and over, skip-and-continue, typed open and read errors). +- [x] AC8: 32 MiB missing-id lookup reads ≤ 5 MiB -> `claude_transcript_bounds_missing_id_in_32_mib_transcript_reads_at_most_5_mib` passed. +- [x] AC9: one resolver call per event, no persistent cache -> inspected the call sites above: one `resolve_claude_model` per event in the diff-trace persist, conversation-trace patch, and mutation-scope admission paths, and one exact-evidence call in the completion fill; `git diff --stat origin/main -- cli/migrations` is empty. +- [x] AC10: provenance at both boundaries -> `claude_provenance_fill` 6, `claude_mutation_scope` 10, `scope_provenance` 2 passed. +- [x] AC11: patch-part session, model, and attribution -> `conversation_trace` 4 and `patch` 41 passed (main-agent null-agent attribution, subagent record and meta, event `agent_type` wins, no agent fields on lines or hunks). +- [x] AC12: missing or malformed files yield `NULL`s and fail open -> `conversation_trace_claude_subagent_missing_files_yield_nulls_and_still_persist` passed; malformed transcript records and malformed meta files are covered at reader level by `claude_transcript` (11 passed), and `resolve_claude_patch_attribution` maps every meta error to `None` (`claude_model_resolver.rs:118`). +- [x] AC13: historical patch JSON and opaque sync -> `patch_json_without_attribution_still_loads_and_reserializes_unchanged` passed; `sync` 36 passed; the sync/export/migrations diff against `origin/main` is empty. +- [x] AC14: manual concurrent-subagent rerun -> waived as not necessary by user decision on 2026-11-23. The manual experiment was not performed: the installed `sce` (`/nix/store/dnqpr34cj413g980z1y0wkjyxhdmkdfi-sce-0.4.0-pre-alpha-v14/bin/sce`) does not contain this branch's attribution code. + +### Failed checks and follow-ups + +- None. + +### Residual risks + +- No live end-to-end run has confirmed subagent attribution, because AC14 was waived; the evidence is fixture-based tests only. +- Test coverage drift: the staged diff removes three subagent resolver tests that T02 recorded (`claude_subagent_model_uses_exact_record_not_latest_record`, `..._is_null_when_exact_record_is_absent`, `..._missing_transcript_is_null`). The malformed-transcript/meta `conversation_trace` test and the `attribution` round-trip `patch` test that T04 recorded are also absent (test counts 6/4/41 against the recorded 9/5/42). +- AC12's malformed-file fail-open path is proven only at reader level plus code inspection, with no end-to-end conversation-trace hook test. +- The `fill_provenance_model_after_close` production wrapper is exercised only on its failure path (T03 deviation). diff --git a/context/sce/agent-trace-hooks-command-routing.md b/context/sce/agent-trace-hooks-command-routing.md index 80dc29ba1..a457df317 100644 --- a/context/sce/agent-trace-hooks-command-routing.md +++ b/context/sce/agent-trace-hooks-command-routing.md @@ -113,7 +113,7 @@ Interactive `sce setup` persists the independent confirmations at `agent_trace.a - For `Write` and `Edit` tools, delegates to `build_claude_post_tool_use_patch(payload)` (from `structured_patch.rs`) instead of reading `tool_response.structuredPatch` directly. - Generates a UUIDv7 `message_id` and a parse-time `generated_at_unix_ms` timestamp. - Produces one `message` item (with `role: "assistant"` and `generated_at_unix_ms`) plus one `message.part` item sharing the same `session_id` and generated `message_id`; conversation-trace persistence stores both with the idempotent `cc_` session prefix: - - On `PatchBuildResult::Built(parsed_patch)`: produces one `message.part` with `part_type: "patch"` and `text` set to JSON-serialized `ParsedPatch`. + - On `PatchBuildResult::Built(parsed_patch)`: produces one `message.part` with `part_type: "patch"` and `text` set to JSON-serialized `ParsedPatch`. Before the transform runs, the intake opens the hook-runtime Agent Trace DB once and calls the [Claude model resolver](./claude-model-resolver.md) once per event. The resolver supplies the model and the patch `attribution` object. The transform does no storage access. It sets every touched line's `session_id` to `cc_`, every hunk's `model_id` to the resolved model or `null`, and `ParsedPatch.attribution`. A resolver error logs `sce.hooks.conversation_trace.claude_model_resolution_failed` and yields a `null` model. The part is still persisted. - On `PatchBuildResult::Skipped(_)`: silently returns zero items (no-op, e.g. for unsupported tools or malformed payloads that would previously have been validation errors). - Unsupported `hook_event_name` values (not `"UserPromptSubmit"`, `"Stop"`, or `"PostToolUse"`) produce an `Invalid conversation-trace payload from STDIN: unsupported Claude hook event '...': supported events are 'UserPromptSubmit', 'Stop' and 'PostToolUse'` error internally, then fail open through `sce.hooks.conversation_trace.error` with hook success text. - **Mixed-batch path** (no `hook_event_name`): Rust intake expects a non-empty top-level `tool_name`, a `payloads` array, and per-item `type` discriminators. A top-level `type` field is ignored by the parser; old homogeneous `{ type, payloads }` envelopes are not a compatibility path because same-kind items without their own `type` are skipped rather than classified from the envelope. diff --git a/context/sce/claude-model-resolver.md b/context/sce/claude-model-resolver.md index b5557c2e8..b94f696d7 100644 --- a/context/sce/claude-model-resolver.md +++ b/context/sce/claude-model-resolver.md @@ -87,6 +87,29 @@ more than 4 MiB from the end, or longer than 1 MiB, resolves to `NULL` at the transcript step. A main-agent event then continues to the state and bridge steps. +## Patch-part attribution + +`resolve_claude_patch_attribution(evidence, event_agent_type)` builds the +`attribution` object of a Claude conversation-trace patch part. It has no +database access. + +- A main-agent event gets `tool_use_id` from the event. `agent_id`, + `agent_type`, and `parent_tool_use_id` are `null`. +- A subagent event gets `agent_id` and `tool_use_id` from the event. + `agent_type` comes from the event `agent_type`, or else from `agentType` in + the subagent meta file. `parent_tool_use_id` comes from `toolUseId` in the + meta file. That value is the `tool_use_id` of the parent `Agent` call that + spawned the subagent. + +The subagent meta file is +`/subagents/agent-.meta.json`, next to the subagent +transcript. `claude_subagent_meta_path` derives it from +`claude_subagent_transcript_path`, so the same path-component rules apply. +`claude_transcript::read_claude_subagent_meta` reads at most 1 MiB +(`CLAUDE_SUBAGENT_META_MAX_BYTES`). It reports an open failure, a read failure, +an oversized file, or a non-object file as `ClaudeSubagentMetaReadError`. The +resolver maps every meta error to `null` meta fields. + ## Consumers - Structured Claude `diff-trace` keeps only the direct model at parse time. At @@ -97,3 +120,6 @@ steps. calls `resolve_claude_model_from_exact_evidence` only when the stored model is `NULL`. See [claude-mutation-scope-integration.md](../cli/claude-mutation-scope-integration.md). +- Claude `conversation-trace` `PostToolUse` `Write` / `Edit` patch parts call + `resolve_claude_model` and `resolve_claude_patch_attribution` once per event. + See [agent-trace-hooks-command-routing.md](./agent-trace-hooks-command-routing.md). diff --git a/context/sce/claude-raw-hook-capture.md b/context/sce/claude-raw-hook-capture.md index 26dfe6e67..3b86b856f 100644 --- a/context/sce/claude-raw-hook-capture.md +++ b/context/sce/claude-raw-hook-capture.md @@ -7,7 +7,7 @@ The `sce hooks claude-capture ` CLI route, `ClaudeCaptureEvent`, `Ho Rust now exposes these active intakes for Claude/OpenCode editor runtimes: - `sce hooks diff-trace` — STDIN JSON intake for OpenCode normalized or Claude structured diff-trace payloads with optional/nullable direct attribution. Rust persists direct payload-derived `model_id` and `tool_version` values as-is; Claude model metadata is resolved by the [Claude model resolver](./claude-model-resolver.md), which does not restore the generic session-level abstraction. -- `sce hooks conversation-trace` — STDIN JSON intake for normalized mixed-batch message/part payloads and supported raw Claude `UserPromptSubmit`, `Stop`, and `PostToolUse` events. Runtime intake failures log `sce.hooks.conversation_trace.error` and fail open to the hook producer. +- `sce hooks conversation-trace` — STDIN JSON intake for normalized mixed-batch message/part payloads and supported raw Claude `UserPromptSubmit`, `Stop`, and `PostToolUse` events. Claude `PostToolUse` `Write` / `Edit` patch parts get their line `session_id`, hunk `model_id`, and `attribution` object from the [Claude model resolver](./claude-model-resolver.md#patch-part-attribution). Runtime intake failures log `sce.hooks.conversation_trace.error` and fail open to the hook producer. `sce hooks session-model` is no longer supported. Generated Claude settings register `SessionStart` for local model-state attribution only and newly register `PostModelSwitch`; neither event is part of the removed raw-capture route. From 61af65b3853322884ad68fed6b5d6f646077bcab Mon Sep 17 00:00:00 2001 From: David Abram Date: Mon, 23 Nov 2026 18:23:17 +0100 Subject: [PATCH 6/6] hooks+patch: Correct Claude subagent paths and inline patch attribution Ensure Claude subagent events resolve paths within matching session directories and keep patch attribution inline without changing its JSON shape. Add regression coverage for foreign-session paths and attribution round trips, and update the supporting context to document unordered provenance fills and the revised representation. Plan: claude-subagent-attribution (T02, T03, T04) Co-authored-by: SCE --- .../services/hooks/claude_model_resolver.rs | 63 +++++++++++++++---- cli/src/services/hooks/claude_transforms.rs | 2 +- cli/src/services/patch.rs | 2 +- cli/src/services/patch/tests.rs | 28 ++++++++- cli/src/services/structured_patch.rs | 1 + context/cli/mutation-scope-provenance.md | 9 ++- context/cli/patch-service.md | 2 +- .../2026-11-23-claude-subagent-attribution.md | 16 +++-- context/plans/claude-subagent-attribution.md | 8 +-- context/sce/claude-model-resolver.md | 7 ++- 10 files changed, 110 insertions(+), 28 deletions(-) diff --git a/cli/src/services/hooks/claude_model_resolver.rs b/cli/src/services/hooks/claude_model_resolver.rs index 1cd02c50a..703d7e97f 100644 --- a/cli/src/services/hooks/claude_model_resolver.rs +++ b/cli/src/services/hooks/claude_model_resolver.rs @@ -80,20 +80,17 @@ pub(crate) fn claude_subagent_transcript_path( } let file_name = format!("agent-{agent_id}.jsonl"); - let names_subagent_transcript = transcript_path - .file_name() - .is_some_and(|name| name == file_name.as_str()) - && transcript_path + let parent = transcript_path.parent()?; + if parent.file_name().is_some_and(|name| name == "subagents") { + let names_session_dir = parent .parent() .and_then(Path::file_name) - .is_some_and(|name| name == "subagents"); - if names_subagent_transcript { - return Some(transcript_path.to_path_buf()); + .is_some_and(|name| name == raw_session_id); + return names_session_dir.then(|| parent.join(file_name)); } Some( - transcript_path - .parent()? + parent .join(raw_session_id) .join("subagents") .join(file_name), @@ -172,7 +169,10 @@ mod tests { use crate::services::agent_trace_db::repository::RepositoryAgentTraceDb; use crate::services::agent_trace_db::{ClaudeModelStateObservation, ObservationKind}; - use super::{claude_subagent_transcript_path, resolve_claude_model, ClaudeModelEvidence}; + use super::{ + claude_subagent_meta_path, claude_subagent_transcript_path, resolve_claude_model, + ClaudeModelEvidence, + }; const SESSION: &str = "5f0c2a7e-1111-4222-8333-944445555666"; const CANONICAL_SESSION: &str = "cc_5f0c2a7e-1111-4222-8333-944445555666"; @@ -384,10 +384,17 @@ mod tests { assert_eq!( claude_subagent_transcript_path(other_subagent, "cc_5f0c2a7e", "abc123"), Some(PathBuf::from( - "/projects/repo/5f0c2a7e/subagents/5f0c2a7e/subagents/agent-abc123.jsonl" + "/projects/repo/5f0c2a7e/subagents/agent-abc123.jsonl" )) ); + let foreign_session_subagent = + Path::new("/projects/repo/0badc0de/subagents/agent-zzz999.jsonl"); + assert_eq!( + claude_subagent_transcript_path(foreign_session_subagent, "cc_5f0c2a7e", "abc123"), + None + ); + assert_eq!( claude_subagent_transcript_path(main, "cc_5f0c2a7e", "../escape"), None @@ -398,6 +405,40 @@ mod tests { ); } + #[test] + fn claude_subagent_meta_path_derivation() { + let expected = Some(PathBuf::from( + "/projects/repo/5f0c2a7e/subagents/agent-abc123.meta.json", + )); + for transcript in [ + "/projects/repo/5f0c2a7e.jsonl", + "/projects/repo/5f0c2a7e/subagents/agent-abc123.jsonl", + "/projects/repo/5f0c2a7e/subagents/agent-zzz999.jsonl", + ] { + assert_eq!( + claude_subagent_meta_path(Path::new(transcript), "cc_5f0c2a7e", "abc123"), + expected + ); + } + + assert_eq!( + claude_subagent_meta_path( + Path::new("/projects/repo/0badc0de/subagents/agent-zzz999.jsonl"), + "cc_5f0c2a7e", + "abc123" + ), + None + ); + assert_eq!( + claude_subagent_meta_path( + Path::new("/projects/repo/5f0c2a7e.jsonl"), + "cc_5f0c2a7e", + "../escape" + ), + None + ); + } + #[tokio::test] async fn claude_model_attribution_main_agent_prefers_direct_model_over_transcript() { let fixture = Fixture::new().await; diff --git a/cli/src/services/hooks/claude_transforms.rs b/cli/src/services/hooks/claude_transforms.rs index be3c956c2..1a84b123b 100644 --- a/cli/src/services/hooks/claude_transforms.rs +++ b/cli/src/services/hooks/claude_transforms.rs @@ -302,5 +302,5 @@ fn attribute_claude_patch( line.session_id = Some(canonical_session_id.to_string()); } } - patch.attribution = Some(Box::new(enrichment.attribution)); + patch.attribution = Some(enrichment.attribution); } diff --git a/cli/src/services/patch.rs b/cli/src/services/patch.rs index 3c8608920..34015122c 100644 --- a/cli/src/services/patch.rs +++ b/cli/src/services/patch.rs @@ -12,7 +12,7 @@ const DEV_NULL: &str = "/dev/null"; pub struct ParsedPatch { pub files: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] - pub attribution: Option>, + pub attribution: Option, } #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] diff --git a/cli/src/services/patch/tests.rs b/cli/src/services/patch/tests.rs index b1885a7c7..4f322a03f 100644 --- a/cli/src/services/patch/tests.rs +++ b/cli/src/services/patch/tests.rs @@ -1,6 +1,6 @@ use std::fmt::Write as _; -use super::{load_patch_from_json, parse_patch, FileChangeKind, PatchFileChange}; +use super::{load_patch_from_json, parse_patch, FileChangeKind, PatchAttribution, PatchFileChange}; fn quote(path: &str) -> String { let mut quoted = String::from("\""); @@ -179,3 +179,29 @@ fn patch_json_without_attribution_still_loads_and_reserializes_unchanged() { HISTORICAL_PATCH_JSON ); } + +#[test] +fn patch_attribution_serializes_inline_and_round_trips() { + let mut patch = + load_patch_from_json(HISTORICAL_PATCH_JSON).expect("historical patch JSON loads"); + patch.attribution = Some(PatchAttribution { + agent_id: Some(String::from("abc123")), + agent_type: Some(String::from("Explore")), + tool_use_id: Some(String::from("toolu_a")), + parent_tool_use_id: Some(String::from("toolu_parent")), + }); + + let json = serde_json::to_value(&patch).unwrap(); + assert_eq!( + json["attribution"], + serde_json::json!({ + "agent_id": "abc123", + "agent_type": "Explore", + "tool_use_id": "toolu_a", + "parent_tool_use_id": "toolu_parent", + }) + ); + + let reloaded = load_patch_from_json(&json.to_string()).expect("attributed patch JSON loads"); + assert_eq!(reloaded, patch); +} diff --git a/cli/src/services/structured_patch.rs b/cli/src/services/structured_patch.rs index a6a7a7d7b..757c2d689 100644 --- a/cli/src/services/structured_patch.rs +++ b/cli/src/services/structured_patch.rs @@ -18,6 +18,7 @@ pub struct ClaudeStructuredPatch { } #[derive(Clone, Debug, Eq, PartialEq)] +#[allow(clippy::large_enum_variant)] pub enum ClaudeStructuredPatchDerivationResult { Derived(ClaudeStructuredPatch), Skipped(ClaudeStructuredPatchSkipReason), diff --git a/context/cli/mutation-scope-provenance.md b/context/cli/mutation-scope-provenance.md index bdbb7d6ba..efddf5c54 100644 --- a/context/cli/mutation-scope-provenance.md +++ b/context/cli/mutation-scope-provenance.md @@ -144,9 +144,12 @@ transcript scan. Otherwise the fill resolves the model from exact evidence only never uses `claude_model_state` or the bridge-session chain. A found model is written through `fill_null_scope_provenance_model`, so a concurrent fill can never overwrite a stored model. The fill changes no field other than `model_id`. -A fill failure is logged and never fails the hook or the close. Provenance is -read at commit time, so a fill at `PostToolUse` is visible to the commit of that -mutation. See +A fill failure is logged and never fails the hook or the close. The fill is not +ordered against commits: commit-time attribution reads the provenance stored at +that moment, so a commit made before the fill (concurrently, or outside Claude's +tool lifecycle) observes `model_id = NULL`. The fill never rewrites an Agent +Trace that was already generated, and no synchronization or retry orders it +before commits. See [Claude subagent attribution](../decisions/2026-11-23-claude-subagent-attribution.md). ## Durable `Start` ordering diff --git a/context/cli/patch-service.md b/context/cli/patch-service.md index c18375dd5..2505e8aab 100644 --- a/context/cli/patch-service.md +++ b/context/cli/patch-service.md @@ -4,7 +4,7 @@ Standalone patch domain model and parser in `cli/src/services/patch.rs` for in-m ## Domain model -- `ParsedPatch` — top-level container holding one or more `PatchFileChange` entries and an optional `attribution: Option>`. The field uses `#[serde(default)]` and is omitted from JSON when absent, so patch JSON without an `attribution` key loads and reserializes unchanged. `ParsedPatch` derives `Default` (an empty patch). +- `ParsedPatch` — top-level container holding one or more `PatchFileChange` entries and an optional `attribution: Option`. The field uses `#[serde(default)]` and is omitted from JSON when absent, so patch JSON without an `attribution` key loads and reserializes unchanged. `ParsedPatch` derives `Default` (an empty patch). - `PatchAttribution` — patch-level writer identity with nullable `agent_id`, `agent_type`, `tool_use_id`, and `parent_tool_use_id`, serialized with explicit `null`s. Only Claude conversation-trace patch parts set it; see [claude-model-resolver.md](../sce/claude-model-resolver.md#patch-part-attribution). Lines and hunks carry no agent fields. Patches rebuilt by `patch_for_locations*` and parsed by `parse_patch` have no attribution. - `PatchFileChange` — per-file change with `old_path`, `new_path`, `FileChangeKind`, and hunks - `FileChangeKind` — enum: `Added`, `Modified`, `Deleted`, `Renamed` (serialized as `snake_case`) diff --git a/context/decisions/2026-11-23-claude-subagent-attribution.md b/context/decisions/2026-11-23-claude-subagent-attribution.md index 4e888c5b7..2814c8897 100644 --- a/context/decisions/2026-11-23-claude-subagent-attribution.md +++ b/context/decisions/2026-11-23-claude-subagent-attribution.md @@ -108,8 +108,10 @@ overwrite a newer `PostModelSwitch`. The subagent transcript path is `//subagents/agent-.jsonl`, and the meta file has the same stem with `.meta.json`. When the event -`transcript_path` already names `subagents/agent-.jsonl`, the -resolver uses it directly. One function owns this derivation. +`transcript_path` already names a file under `/subagents/`, the +resolver uses the sibling `agent-.jsonl` in that directory, which is +the event path itself for the matching subagent. A `subagents/` path under a +different session directory yields no path. One function owns this derivation. ### Transcript bounds @@ -157,8 +159,14 @@ boundary: The fill applies to main-agent and subagent Claude scopes alike, because both use exact evidence only. Main-agent admission precedence is unchanged. -Provenance is read at commit time, so a fill at `PostToolUse` is visible to the -commit of that mutation. The fill does not apply to non-Claude scopes. +The fill does not apply to non-Claude scopes. + +The fill is not ordered against commits. Commit-time attribution reads the +provenance stored at that moment. A commit can run before the completion fill, +for example when it is made concurrently or outside Claude's tool lifecycle. +That commit observes `model_id = NULL`. The fill never rewrites an Agent Trace +that was already generated. It stays best-effort, atomic, and write-once, and no +synchronization or retry is added to order it before commits. ### Patch-part attribution diff --git a/context/plans/claude-subagent-attribution.md b/context/plans/claude-subagent-attribution.md index c2d1f3dfe..f700543b8 100644 --- a/context/plans/claude-subagent-attribution.md +++ b/context/plans/claude-subagent-attribution.md @@ -125,14 +125,14 @@ Persist this field in every plan; this is durable plan state, not chat state: ## Assumptions -- The subagent transcript path is `//subagents/agent-.jsonl`, and the meta file has the same stem with `.meta.json`. The layout was observed in Claude Code transcripts on 2026-11-23. When the event `transcript_path` already names `subagents/agent-.jsonl`, the resolver uses it directly. One function owns this derivation. +- The subagent transcript path is `//subagents/agent-.jsonl`, and the meta file has the same stem with `.meta.json`. The layout was observed in Claude Code transcripts on 2026-11-23. When the event `transcript_path` already names a file under `/subagents/`, the resolver uses the sibling `agent-.jsonl` in that directory (the event path itself for the matching subagent); a `subagents/` path under a different session directory yields no path. One function owns this derivation. - The Claude hook contract provides no authoritative event timestamp or sequence number (decision `2026-09-01-claude-model-attribution-state`). No reliable ordering exists to prove that a non-matching transcript record precedes an event, so the "latest preceding observation" step is omitted for subagents. - `claude_model_state` records only local observation time. A transcript-derived model written there would look like a current observation and could overwrite a newer `PostModelSwitch`. The plan therefore seeds no transcript-derived row. - Transcript bounds rest on 634 local Claude transcripts measured on 2026-11-23. File size: median 1.1 MB, p99 4.1 MB, maximum 8.9 MB. Record length: median 1.1 KB, p99 47 KB, p99.9 131 KB, maximum 0.99 MB. The record for the event's tool call is appended last or near last before the hook runs, so a 4 MiB tail window covers it with wide margin and covers the whole file for about 99% of transcripts. A 1 MiB record cap covers every measured record. Consequence of exceeding a bound: an assistant record that carries a `Write` input larger than about 1 MiB, or an exact record more than 4 MiB from the end, resolves to `NULL`. For a main-agent event, resolution then continues to the existing state and bridge steps, as it does today when the transcript has no match. - The existing reader aborts the whole lookup on the first unreadable line (`line.ok()?`). The bounded reader skips a malformed record instead. This can only add exact matches, never change one. - The completion fill is placed in the Claude adapter, after `handle_close` reports a successful close and before the adapter attempt is removed. It calls one store method that runs `UPDATE mutation_trace_scope_provenance SET model_id = ? WHERE scope_id = ? AND model_id IS NULL` and returns a typed outcome (`Filled`, `AlreadySet`, `NoRow`). This keeps the generic ingress, the protocol state, and the CAS batch unchanged. The trade-off: the fill is a Claude-specific store write outside the generic ingress, and it applies to Claude scopes only. A generic `close` provenance field was rejected because it would change the ingress contract and the conformance suite for every harness. - The fill runs only when the stored row exists and its `model_id` is `NULL`, so a scope that already has a model costs one indexed read and no transcript scan. The fill applies to main-agent and subagent Claude scopes alike, because both use exact evidence only. Main-agent admission precedence is unchanged. -- Provenance is read at commit time by `mutation_trace/runtime/mutation_attribution.rs`. A fill at `PostToolUse` precedes any commit of that mutation, so the commit-time read observes it. +- Provenance is read at commit time by `mutation_trace/runtime/mutation_attribution.rs`, which sees whatever is stored at that moment. The fill at the completion boundary is not ordered against commits: a commit made before the fill (concurrently, or outside Claude's tool lifecycle) observes `model_id = NULL`, and the fill never rewrites an Agent Trace that was already generated. The fill stays best-effort, atomic, and write-once, with no added synchronization or retry. - The `attribution` object uses `#[serde(default)]` and is serialized only when present, following the existing optional `model_id` and `session_id` fields in `cli/src/services/patch.rs`. - Patch-part `session_id` uses the canonical `cc_` form, matching `messages.session_id` and `parts.session_id`. @@ -187,9 +187,9 @@ Persist this field in every plan; this is durable plan state, not chat state: - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml conversation_trace`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml patch`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml sync`. - Completed: 2026-11-23 - Files changed: `cli/src/services/patch.rs`, `cli/src/services/patch/tests.rs`, `cli/src/services/structured_patch.rs`, `cli/src/services/hooks/claude_transcript.rs`, `cli/src/services/hooks/claude_model_resolver.rs`, `cli/src/services/hooks/claude_transforms.rs`, `cli/src/services/hooks/conversation_trace.rs`, `cli/src/services/mutation_trace/attribution.rs`, `cli/src/services/mutation_trace/runtime/mutation_attribution.rs`, `cli/src/services/mutation_trace/runtime/mutation_attribution/tests.rs`, `cli/src/services/hooks/commit_hooks.rs`, `cli/src/services/hooks/commit_hooks/attribution_tests.rs`, `cli/src/services/hooks/commit_hooks/path_identity_tests.rs`, `cli/src/services/agent_trace/tests.rs`, `cli/src/services/agent_trace/committed_content/tests.rs`, `context/plans/claude-subagent-attribution.md` - - Result: `ParsedPatch` gained `attribution: Option>` (`agent_id`, `agent_type`, `tool_use_id`, `parent_tool_use_id`), `#[serde(default)]` and omitted when absent; `ParsedPatch` now derives `Default`, and empty-patch literals use `ParsedPatch::default()`. Added the bounded meta reader `read_claude_subagent_meta` / `read_subagent_meta_from` in `claude_transcript.rs` (1 MiB cap, typed `ClaudeSubagentMetaReadError { Open, Read, Oversized, Malformed }`). The resolver module gained `claude_subagent_meta_path` (derived from `claude_subagent_transcript_path`) and `resolve_claude_patch_attribution`, which maps every meta error to `None`. A main-agent patch gets only `tool_use_id`; a subagent patch gets `agent_id`, `agent_type` from the event or else the meta `agentType`, and `parent_tool_use_id` from the meta `toolUseId`. `transform_claude_post_tool_use` takes a `ClaudePatchEnrichment { model_id, attribution }` and does no storage access: it stamps `cc_` on every line, the model or `null` on every hunk, and attaches `attribution`. The conversation-trace entry now parses the request, opens the hook-runtime DB once, and for a Claude `PostToolUse` `Write`/`Edit` builds `ClaudePatchEvidence` and calls `resolve_claude_model` once per event. A resolver error is logged as `sce.hooks.conversation_trace.claude_model_resolution_failed` and yields `null`. The `parse_conversation_trace_payload` and `persist_conversation_trace_payload_to_agent_trace_db` functions were replaced by `parse_conversation_trace_request`, `conversation_trace_payload_from_request`, and `conversation_trace_payload_with_db`. + - Result: `ParsedPatch` gained `attribution: Option` (`agent_id`, `agent_type`, `tool_use_id`, `parent_tool_use_id`), `#[serde(default)]` and omitted when absent; `ParsedPatch` now derives `Default`, and empty-patch literals use `ParsedPatch::default()`. Added the bounded meta reader `read_claude_subagent_meta` / `read_subagent_meta_from` in `claude_transcript.rs` (1 MiB cap, typed `ClaudeSubagentMetaReadError { Open, Read, Oversized, Malformed }`). The resolver module gained `claude_subagent_meta_path` (derived from `claude_subagent_transcript_path`) and `resolve_claude_patch_attribution`, which maps every meta error to `None`. A main-agent patch gets only `tool_use_id`; a subagent patch gets `agent_id`, `agent_type` from the event or else the meta `agentType`, and `parent_tool_use_id` from the meta `toolUseId`. `transform_claude_post_tool_use` takes a `ClaudePatchEnrichment { model_id, attribution }` and does no storage access: it stamps `cc_` on every line, the model or `null` on every hunk, and attaches `attribution`. The conversation-trace entry now parses the request, opens the hook-runtime DB once, and for a Claude `PostToolUse` `Write`/`Edit` builds `ClaudePatchEvidence` and calls `resolve_claude_model` once per event. A resolver error is logged as `sce.hooks.conversation_trace.claude_model_resolution_failed` and yields `null`. The `parse_conversation_trace_payload` and `persist_conversation_trace_payload_to_agent_trace_db` functions were replaced by `parse_conversation_trace_request`, `conversation_trace_payload_from_request`, and `conversation_trace_payload_with_db`. - Verify outcomes: `conversation_trace` 5 passed (main agent: line `session_id`, hunk model from the exact transcript record over a main-agent state row, null-agent `attribution`; subagent: model from the subagent record (not the main transcript or state row), `agent_type` and `parent_tool_use_id` from meta; event `agent_type` wins over meta; missing transcript and meta yield `null` model and fields with a main-agent state row present, and the part still persists; malformed transcript and meta yield `null`s, and the part persists; no agent fields on lines or hunks); `patch` 42 passed (including historical patch JSON without `attribution` loading and reserializing byte-identical, and an `attribution` round trip with explicit nulls); `sync` 36 passed. Also: `claude_transcript` 11 passed (4 new meta-reader tests: fields, missing/non-string fields, cap at 1 MiB and 1 MiB + 1, malformed and missing-file typed errors); `agent_trace` 143 passed; full CLI suite 893 passed; `clippy --all-targets -D warnings` clean; `cargo fmt` applied. AC5: `rg` lists transcript-reader, meta-reader, and state-row call sites only in `claude_model_resolver.rs`, the existing bridge-chain helper in `claude_model_state.rs`, and the definitions. AC13: `git diff --stat origin/main -- cli/src/services/sync cli/src/services/agent_trace_export cli/migrations` is empty. - - Deviation: `attribution` is boxed (`Option>`) so that `ParsedPatch` stays small; clippy `large_enum_variant` rejected the unboxed field in `ClaudeStructuredPatchDerivationResult`. The JSON shape is unchanged. The hook-runtime DB open moved from the persist step to before the transform, so the resolver and the inserts share one handle; a DB open failure still fails open with the same log event. + - Deviation: `attribution` is stored inline (`Option`), and `ClaudeStructuredPatchDerivationResult` allows clippy `large_enum_variant` instead of boxing, because the result is short-lived and matched immediately. The JSON shape is unchanged. The hook-runtime DB open moved from the persist step to before the transform, so the resolver and the inserts share one handle; a DB open failure still fails open with the same log event. - Context impact: localized — Claude patch parts now carry `session_id`, `model_id`, and an optional `attribution` object, and the conversation-trace path resolves through the shared resolver. `context/cli/patch-service.md`, `context/sce/claude-raw-hook-capture.md`, and `context/cli/agent-trace-sync-command.md` should describe this. - Context synchronization: synced diff --git a/context/sce/claude-model-resolver.md b/context/sce/claude-model-resolver.md index b94f696d7..f396afc68 100644 --- a/context/sce/claude-model-resolver.md +++ b/context/sce/claude-model-resolver.md @@ -63,8 +63,11 @@ yet written resolves to `NULL`. `claude_subagent_transcript_path` is the one function that derives the subagent transcript path: `//subagents/agent-.jsonl`. -When the event `transcript_path` already names that file, the function returns -it unchanged. The function returns no path when the session ID (without `cc_`) +When the event `transcript_path` already names a file under +`/subagents/`, the function returns the sibling +`agent-.jsonl` in that directory; this is the event path itself when +it names the matching subagent. A `subagents/` path under a different session +directory yields no path. The function returns no path when the session ID (without `cc_`) or the `agent_id` contains a character outside `[A-Za-z0-9_-]`. ## Transcript bounds