From a0562c0be29bc10e9e7041e69e10d5ac9abac6d1 Mon Sep 17 00:00:00 2001 From: David Abram Date: Tue, 24 Nov 2026 14:34:50 +0100 Subject: [PATCH 1/4] context: Define Codex native telemetry instrumentation plan Codex currently lacks managed native telemetry, while existing SCE infrastructure supports Claude telemetry and hook spans. Define the evidence-driven work to establish the Codex 0.172.0 contract, ship repository-safe native export and hook spans, and record live verification without changing credential lifecycle or privacy boundaries. Plan: codex-native-otel-instrumentation Co-authored-by: SCE --- .../codex-native-otel-instrumentation.md | 118 ++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 context/plans/codex-native-otel-instrumentation.md diff --git a/context/plans/codex-native-otel-instrumentation.md b/context/plans/codex-native-otel-instrumentation.md new file mode 100644 index 000000000..b7729ee65 --- /dev/null +++ b/context/plans/codex-native-otel-instrumentation.md @@ -0,0 +1,118 @@ +# Plan: codex-native-otel-instrumentation + +## Change summary + +Codex CLI exports no telemetry to the SCE managed collector today. Claude Code does: `sce setup` installs Claude-native OTLP settings with `otelHeadersHelper = "sce auth telemetry-headers"`, and Claude-invoked SCE hooks export `sce.hook` spans through the managed exporter. This plan brings Codex to the closest parity that Codex 0.172.0 supports. It reuses the existing managed telemetry infrastructure and adds no second telemetry architecture. + +The plan extends three existing surfaces: + +- The hidden helper `sce auth telemetry-headers` (`cli/src/services/auth_command/mod.rs`). Today `run_telemetry_headers` derives the repository from `std::env::current_dir()`. Codex runs `otel.headers_helper` from `CODEX_HOME`, so the working directory cannot identify the repository. The helper may need explicit repository context. Its no-argument Claude behavior must stay byte-identical. +- Codex launch configuration. Repository-local Codex config cannot set `otel.*`. Codex accepts process-local `-c` overrides. T01 decides with evidence whether a thin `sce codex` launcher is required, or whether a smaller mechanism is safe. +- Managed hook telemetry (`cli/src/app.rs::managed_span_kind`, `cli/src/services/managed_telemetry/trace_export.rs`). Today `ManagedSpanKind` is `{ Command, ClaudeHook }`, and every `sce hooks codex` and `sce hooks codex-mutation-scope` process resolves `NoopTelemetry`. This plan admits those two Codex hook commands to the same `sce.hook` / `sce.mutation_scope` / `sce.git_snapshot` / `sce.persistence` span contract. `TRACEPARENT` parenting applies only when T01 proves that Codex passes valid current-span context to command hooks. + +Credential provisioning, the encrypted `auth.db`, repository enrollment, the effective access policy, non-interactive lookup, fail-closed helper behavior, Claude telemetry, and Codex hook behavior are preserved. + +## 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: Durable context records evidence from real Codex 0.172.0 runs against a local OTLP receiver with dummy credentials. The evidence covers: the header-helper invocation contract (argv form, working directory, environment, stdout format, refresh cadence, failure recovery, header caching); configuration precedence across `-c`, profiles, user `config.toml`, and enterprise requirements; whether a helper-authorized header can reach a non-canonical exporter; attribution behavior for interactive, `exec`, `resume`, `fork`, working-directory changes, and multiple threads; whether command hooks receive `TRACEPARENT`/`TRACESTATE` that names an exported Codex span (distinguished from inherited process environment); the mapping between native session identifiers and SCE `cx_` session identities; the exported token, cost, cache, tool, duration, model, repository, and subagent attributes with their observed semantics; and which config options control prompt, response, and tool-argument content in native logs. The record ends with one implementation decision and a Claude/Codex parity matrix. + - Validate: Inspect `context/sce/codex-native-telemetry-contract.md` for the evidence tables, the Codex version, the decision, and the parity matrix. `git ls-files` shows no probe script or receiver fixture. `rg -n 'Bearer [A-Za-z0-9._-]{12,}|hvs\.|s\.[A-Za-z0-9]{20,}' context/sce/codex-native-telemetry-contract.md` returns no match. +- [ ] AC2: `sce auth telemetry-headers` with no arguments behaves exactly as before for Claude. When the T01 decision requires explicit repository context, the helper accepts it, applies the same access-policy gate, destination tripwire, `auth.db` presence check, repository-binding lookup, and `CREDENTIAL_LOOKUP_DEADLINE` to that repository, and fails closed with the fixed diagnostic `Telemetry credential is unavailable.` and empty stdout for a missing, non-Git, unenrolled, opted-out, or otherwise unauthorized repository. The helper never initializes managed telemetry. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml telemetry_headers`; the existing no-argument tests in `cli/src/services/auth_command/mod.rs` and `cli/src/services/telemetry_credential_storage.rs` pass unchanged; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_span_kind`. +- [ ] AC3: Native Codex telemetry is enabled only through the mechanism the T01 decision selects, and only for invocation modes that T01 proved repository-safe. When the decision selects a `sce codex` launcher, it resolves the effective repository and access policy before launch, supplies native OTEL settings only as process-local `-c` overrides that pin `MANAGED_OTLP_ENDPOINT` / `MANAGED_OTLP_PROTOCOL` and the helper with explicit repository context, forwards supported Codex arguments unchanged, preserves the terminal, signal delivery, and the Codex exit code, and refuses or launches without SCE telemetry for unproven modes. No credential is written to any file, and no global Codex config is changed unless T01 proves it necessary. + - Validate: Targeted Rust tests for the launch argument builder and mode classification (`nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml codex_telemetry`); `rg -n 'Bearer|OTEL_EXPORTER_OTLP_HEADERS' cli/src/services` shows no credential in launch arguments or written config; inspection of the T02 completion record for the exit-code and signal checks. +- [ ] AC4: SCE credentials cannot be sent to an exporter that targets an unrelated endpoint through any path T01 identified. User-owned or enterprise-managed Codex OTEL configuration that conflicts with the managed endpoint causes SCE to skip native telemetry and report the reason; it is never overwritten. + - Validate: Targeted Rust tests per conflict class identified in T01; inspection of the residual-risk statement in `context/sce/telemetry-credential.md`. +- [ ] AC5: With a valid stored credential, each `sce hooks codex` and `sce hooks codex-mutation-scope` process exports exactly one `sce.hook` span with `service.name=sce`, `sce.agent=codex`, `sce.hook.command`, `sce.hook.event`, `sce.hook.tool` when present, `sce.outcome`, and only the Codex session, turn, tool-use, and model identifiers that T01 verified. `sce.mutation_scope`, `sce.git_snapshot`, and `sce.persistence` child spans appear only when that operation executed in the process. Claude hook spans keep their current names and `sce.claude.*` attributes. + - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_telemetry`, including loopback-receiver tests over Codex `PostToolUse(apply_patch)` and non-tracked fixtures that decode the OTLP payload and assert span name, count, parent links, and attributes; existing Claude loopback tests pass unchanged. +- [ ] AC6: A Codex hook `sce.hook` span is parented on upstream `TRACEPARENT` only when T01 proved that Codex supplies valid current-span context for that hook execution. Otherwise the span is an independent root with correlation attributes. No trace ID or parent span ID is ever derived from a session, turn, or tool-use identifier. + - Validate: Loopback-receiver tests for valid, invalid, all-zero, and missing traceparent when parenting ships; otherwise `rg -n 'extract_parent_context' cli/src/services/managed_telemetry` shows extraction gated to the proven agent only, and `context/sce/codex-native-telemetry-contract.md` states the verdict. +- [ ] AC7: Telemetry cannot change Codex hook behavior. With credential lookup failure, an expired credential, a refused or stalled receiver, or exporter timeout, hook stdout, stderr, exit code, permission decisions, Agent Trace DB rows, and mutation-trace state match the telemetry-disabled run, and process lifetime stays within `CREDENTIAL_LOOKUP_DEADLINE` + `SHUTDOWN_TIMEOUT`. + - Validate: Parity tests running the same Codex hook fixtures with Noop and with failing managed telemetry, comparing outputs and persisted state and asserting elapsed-time bounds. +- [ ] AC8: Live verification is recorded. A real Codex session in an enrolled repository delivers native traces, metrics, and logs, plus SCE Codex hook spans, to the correct Dash0 dataset with correct session and repository attribution. The record covers token, cache, model, cost, and tool telemetry; hook-span correlation with native Codex telemetry; subagent attribution where upstream provides identity; credential replacement, expiry, logout, and failed authorization; repository opt-out and global consent withdrawal; two repositories in different workspaces; preservation of user-owned and managed Codex config; an unchanged Claude session; and the absence of prompt, response, and tool content. A collector 2xx alone is not recorded as delivery. + - Validate: Inspect the live-verification section of `context/sce/codex-native-telemetry-contract.md` and the T03 completion record. +- [ ] AC9: Current-state context describes the shipped Codex telemetry mechanism, the helper repository-context contract, hook admission and span attributes, the trace-context verdict, privacy controls, the final Claude/Codex parity matrix, remaining upstream limitations, the minimum verified Codex version, and required control-plane follow-ups. The hidden helper and any hidden flags stay absent from the public command reference. + - Validate: Inspect the files listed under Context sync against the implemented code; `rg -n 'telemetry-headers' context/cli/cli-command-surface.md` shows no public listing. + +### 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` +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_telemetry` +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml telemetry` +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml codex` +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml auth` + +### Context sync + +- `context/sce/codex-native-telemetry-contract.md` (new: T01 evidence, decision, parity matrix, live verification, smoke procedure) +- `context/sce/telemetry-credential.md` (helper repository context, Codex launch context, endpoint residual risk) +- `context/sce/cli-observability-contract.md` (Codex hook admission and span attributes) +- `context/sce/codex-integration-runtime.md` and `context/cli/codex-mutation-scope-integration.md` (span boundaries over the Codex hooks) +- `context/cli/access-policy.md` (helper and launcher enforcement points) +- `context/cli/cli-command-surface.md` (only if a public `sce codex` command ships) +- `context/sce/doctor-human-text-contract.md` (only if a doctor row changes) +- `context/architecture.md`, `context/overview.md`, `context/glossary.md`, `context/context-map.md` +- `context/decisions/` (one ADR only if T02 introduces a launcher or another substantive architectural choice) + +## 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/auth_command/` (helper repository context); `cli/src/cli_schema.rs` and `cli/src/services/parse/command_runtime.rs` (hidden helper flag, optional `sce codex`); a launcher module under `cli/src/services/` only if T01 requires it; `cli/src/app.rs` (`managed_span_kind` admission, helper bypass); `cli/src/services/managed_telemetry.rs` and `managed_telemetry/trace_export.rs` (hook-agent span kind, Codex attributes, gated parent extraction); span boundaries at existing call sites in `cli/src/services/hooks/codex/` and `cli/src/services/hooks/codex_mutation_scope/`; Codex setup and doctor code only where the T01 decision requires it; focused tests; the context files listed above. +- **Out of scope:** Control Plane, Collector, Dash0 dataset, or warehouse changes; credential issuance, storage schema, or lifecycle changes; OpenCode and Pi telemetry; Pkl-generated `.codex/hooks.json` contract changes; changes to Claude settings, Claude span names, or Claude attributes; a public telemetry command. +- **Constraints:** static dispatch and concrete types (`AGENTS.md`); typed errors over `anyhow` where a caller branches on the cause; reuse `MANAGED_OTLP_ENDPOINT`, `MANAGED_OTLP_PROTOCOL`, `authorized_repository_credential_with`, `load_repository_telemetry_credential`, and the existing exporter; no comments that narrate changes; Nix-wrapped Cargo only; automated tests never contact the production collector or use real credentials; probes use dummy credentials and never log real tokens; telemetry stays fail-open for hooks and fail-closed for authentication; repository authorization and consent enforcement are never weakened. +- **Non-goal:** a telemetry proxy, local collector, sidecar, or daemon; a new database, credential lifecycle, or readiness marker; a generic agent-telemetry plugin framework; a second credential-authorization implementation; JSONL-based reconstruction of native telemetry unless T01 proves essential metrics are unavailable through OTEL. + +## Assumptions + +- The plan name is `codex-native-otel-instrumentation`, mirroring `claude-native-otel-instrumentation`. +- The locally installed `codex-cli 0.172.0` is the released binary T01 probes; upstream source at `rust-v0.172.0` is the reference for behavior the probe cannot observe directly. +- Codex hook spans use a `sce.codex.*` attribute namespace that mirrors `sce.claude.*`. Claude attribute names stay unchanged. +- `sce hooks codex` and `sce hooks codex-mutation-scope` are Codex-only subcommands, so admission needs no caller environment marker, as with `CLAUDE_ONLY_HOOK_SUBCOMMANDS`. Shared `diff-trace` and `conversation-trace` admission stays Claude-only. +- `ManagedSpanKind::ClaudeHook` becomes a hook variant carrying a statically dispatched agent enum (`Claude | Codex`) only if that keeps the Claude export byte-identical; otherwise a sibling `CodexHook` variant is used. This is a reversible local choice for T02. +- The T03 executor has a Dash0 account and an enrolled repository, as the `claude-hook-trace-propagation` T05 executor did. +- T03 is an evidence-and-context task, not a validation-only task. It produces the live-verification record and the current-state parity documentation that the change itself requires. + +## Task stack + +- [ ] T01: `Establish the Codex 0.172.0 native telemetry contract by probe` (status:todo) + - Task ID: T01 + - Scope: In — probes with the released Codex 0.172.0 binary, a scratchpad loopback OTLP/HTTP receiver, dummy credentials, and a scratchpad stub header helper; reading `rust-v0.172.0` source for `otel.*` config, header-helper execution, hook spawning, and requirements layering; recording every item listed in AC1; writing `context/sce/codex-native-telemetry-contract.md` with evidence tables, the implementation decision (helper-argument mechanism, launcher or no launcher, safe invocation modes, setup/doctor needs, trace-parenting verdict, identifier mapping, privacy config), and the parity matrix. Out — any change under `cli/`; real credentials; contact with the production collector; probe code left in the repository. + - Dependencies: none + - Done when: the contract file answers every AC1 question with recorded evidence or an explicit "not observable" verdict and its reason; similarly named Claude and Codex metrics are compared by observed semantics, not by name; the decision names the smallest safe T02 mechanism; `git status` shows only the new context file and this plan's status update. + - Verify: inspection of the contract file against the AC1 list; `git ls-files | rg -i 'probe|otlp-receiver'` returns nothing new; `rg -n 'Bearer [A-Za-z0-9._-]{12,}' context/sce/codex-native-telemetry-contract.md` returns no match. + - Context synchronization: pending + +- [ ] T02: `Ship native Codex telemetry and Codex hook spans on the managed infrastructure` (status:todo) + - Task ID: T02 + - Scope: In — the T01-selected mechanism only: explicit repository context on the hidden helper (no-argument behavior unchanged), a thin `sce codex` launcher if and only if T01 requires it, and conflict detection for user-owned and enterprise Codex OTEL config; hook admission for `sce hooks codex` and `sce hooks codex-mutation-scope` in `managed_span_kind`; the hook-agent span kind and verified `sce.codex.*` attributes; reuse of `sce.mutation_scope`, `sce.git_snapshot`, and `sce.persistence` at existing Codex call sites; `TRACEPARENT` extraction for Codex only if T01 proved current-span propagation; setup and doctor changes only where T01 requires them, keeping configuration availability, credential authorization, and delivery as distinct states; focused unit and loopback-receiver tests; one ADR if a launcher ships. Out — live Dash0 verification; Claude span or settings changes; credential lifecycle changes; Pkl hook contract changes; unproven invocation modes. + - Dependencies: T01 + - Done when: AC2 through AC7 hold in tests; the helper bypass in `managed_span_kind` still returns no span kind for `sce auth telemetry-headers` in all argument forms; every existing Claude telemetry, helper, and Codex hook test passes unchanged; no credential appears in launch arguments, written config, output, or diagnostics. + - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_telemetry`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml telemetry_headers`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml codex`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_span_kind`; `nix develop -c ./scripts/run-cli-cargo.sh clippy --manifest-path cli/Cargo.toml --all-targets -- -D warnings`. + - Context synchronization: pending + +- [ ] T03: `Record live Codex telemetry verification and the Claude/Codex parity contract in durable context` (status:todo) + - Task ID: T03 + - Scope: In — real Codex sessions through the shipped mechanism against `https://otel.crocoderlab.dev` with existing managed credentials; Dash0 observation of every AC8 item; a Claude regression session; the live-verification section, final parity matrix, upstream limitations, minimum verified Codex version, and control-plane follow-up list in `context/sce/codex-native-telemetry-contract.md`; synchronization of every file under Context sync. Out — code changes (a defect found here is recorded with its evidence and fixed in a new task appended to this plan); Control Plane or warehouse changes; recording real tokens, prompts, or tool content. + - Dependencies: T02 + - Done when: every AC8 item is recorded as observed in the correct Dash0 dataset with trace IDs, or recorded as not verifiable with the exact reason; AC9 context matches the shipped code; the minimum verified Codex version is stated. + - Verify: inspection of the live-verification section and the Context sync files against the code; `rg -n 'telemetry-headers' context/cli/cli-command-surface.md` shows no public listing; `rg -n 'Bearer [A-Za-z0-9._-]{12,}' context/` returns no match. + - Context synchronization: pending + +## Open questions + +- Is launcher-only coverage worth its cost? If T01 proves that `CODEX_HOME` execution makes a user-level `config.toml` install unable to identify the repository, only `sce codex` launches will export native telemetry, and every plain `codex` launch stays dark. That is weaker than Claude parity, where a user-level install covers every launch. A smaller alternative is to ship only the T02 Codex hook spans, which need no launcher, and defer native export until upstream passes a working directory or repository context to the helper. +- Will Codex native metrics be usable without control-plane work? Codex metric names and units differ from `claude_code.*`, and this plan excludes warehouse and dashboard changes. Delivered Codex metrics may not appear in existing SCE views until the follow-ups T03 records are done. From 87282887bca6bee3a1c88350507370529e55a39d Mon Sep 17 00:00:00 2001 From: David Abram Date: Tue, 24 Nov 2026 14:58:02 +0100 Subject: [PATCH 2/4] context: Record Codex native telemetry contract MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Capture Codex 0.172.0 probe evidence for header-helper invocation, configuration precedence, attribution, hook context, identifiers, telemetry semantics, privacy controls, and the launcher-plus-hook-span decision. Mark T01 complete with verification evidence and link the new durable contract so T02 can implement the selected mechanism without shipping behavior here. Plan: `codex-native-otel-instrumentation` — T01 Co-authored-by: SCE --- context/context-map.md | 1 + .../codex-native-otel-instrumentation.md | 10 +- .../sce/codex-native-telemetry-contract.md | 180 ++++++++++++++++++ 3 files changed, 189 insertions(+), 2 deletions(-) create mode 100644 context/sce/codex-native-telemetry-contract.md diff --git a/context/context-map.md b/context/context-map.md index ded40fe2b..64fa113a4 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -58,6 +58,7 @@ Feature/domain context: - `context/sce/cli-shell-completion-contract.md` (implemented `sce completion` contract for deterministic Bash/Zsh/Fish completion script generation) - `context/sce/claude-raw-hook-capture.md` (removed feature: the former `sce hooks claude-capture` raw-capture route and its supporting types, replaced by the active `diff-trace` and `conversation-trace` intakes) - `context/sce/claude-hook-trace-propagation.md` (probe evidence for Claude Code 2.1.301 command-hook trace context: `TRACEPARENT` names the `claude_code.interaction` span, not the tool span, and only when Claude tracing is active; hook-to-tool correlation by `tool_use_id`; `CLAUDECODE` + `CLAUDE_PROJECT_DIR` presence as the Claude hook-caller signal; T05 live Dash0 verification (doctor and session-boundary hook spans observed, parented tool-hook hierarchy unverified) and the opt-in live smoke procedure; the shipped `sce.hook` contract lives in `cli-observability-contract.md`, admission decision `context/decisions/2026-10-17-claude-hook-managed-trace-admission.md`) +- `context/sce/codex-native-telemetry-contract.md` (probe evidence for Codex CLI 0.172.0 native OTEL export: the `otel.headers_helper` invocation contract (runs from `CODEX_HOME` without repository context, timer-only refresh, export suspended on failure), `-c`/profile/user/requirements precedence and credential reach to unpinned exporters, attribution per invocation mode (`resume` without `-C` uses the stored session cwd), no current-span `TRACEPARENT` for command hooks, hook-to-native identifier mapping, observed token/cache/tool semantics and privacy controls, the decided launcher-plus-hook-span mechanism, and the Claude/Codex parity matrix; this is evidence and a decision, not shipped behavior) - `context/sce/cli-observability-contract.md` (implemented config-backed runtime observability contract for the flat logging config-file shape with explicit config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` env-over-config-over-`/sce/logs` fallback, append-only local-date/session log file routing with a one-time complete-record `-v2.log` fallback on primary open/append/flush failure, creation-triggered retention of direct regular `*.log` files to 10 entries, reliable producer-native diff-trace/conversation-trace session routing and hook-specific non-duplicated Agent Trace DB-open error events, deterministic session filename sanitization, concrete `Logger` behavior plus the `NoopTelemetry`-backed telemetry capability boundary, logger and deliberately non-object-safe generic async telemetry boundaries with static capability dispatch and future-aware polling scope, AppContext observability wiring, generic `RunOutcome` final rendering, runtime-classified repeated telemetry action protection, operator-facing `sce config show` observability reporting, managed OTLP trace/log export (credential-gated, hardcoded canonical collector, Claude-only hook admission with one `sce.hook` span and correlation-only session/tool-use IDs, its `sce.mutation_scope`/`sce.git_snapshot`/`sce.persistence` operation child spans with a span-kind-specific export filter, allowlisted fields, bounded fail-open lifecycle, reserved metrics endpoint), and the trimmed `sce config validate` status-only validation surface) - `context/sce/shared-context-code-workflow.md` (canonical `/next-task` task-synchronization lifecycle and validation-only `/validate` lifecycle, package-local phase references with single-skill control flow, and the task-synchronization-scoped `sce-decision` sibling invocation with ADR reuse/blocker propagation) - `context/sce/shared-context-plan-workflow.md` (canonical `/change-to-plan` workflow, package-local context-load/plan-authoring/template references, clarification/readiness gate contract, and one-task/one-atomic-commit task slicing) diff --git a/context/plans/codex-native-otel-instrumentation.md b/context/plans/codex-native-otel-instrumentation.md index b7729ee65..2d733a153 100644 --- a/context/plans/codex-native-otel-instrumentation.md +++ b/context/plans/codex-native-otel-instrumentation.md @@ -88,13 +88,19 @@ Persist this field in every plan; this is durable plan state, not chat state: ## Task stack -- [ ] T01: `Establish the Codex 0.172.0 native telemetry contract by probe` (status:todo) +- [x] T01: `Establish the Codex 0.172.0 native telemetry contract by probe` (status:done) - Task ID: T01 - Scope: In — probes with the released Codex 0.172.0 binary, a scratchpad loopback OTLP/HTTP receiver, dummy credentials, and a scratchpad stub header helper; reading `rust-v0.172.0` source for `otel.*` config, header-helper execution, hook spawning, and requirements layering; recording every item listed in AC1; writing `context/sce/codex-native-telemetry-contract.md` with evidence tables, the implementation decision (helper-argument mechanism, launcher or no launcher, safe invocation modes, setup/doctor needs, trace-parenting verdict, identifier mapping, privacy config), and the parity matrix. Out — any change under `cli/`; real credentials; contact with the production collector; probe code left in the repository. - Dependencies: none - Done when: the contract file answers every AC1 question with recorded evidence or an explicit "not observable" verdict and its reason; similarly named Claude and Codex metrics are compared by observed semantics, not by name; the decision names the smallest safe T02 mechanism; `git status` shows only the new context file and this plan's status update. - Verify: inspection of the contract file against the AC1 list; `git ls-files | rg -i 'probe|otlp-receiver'` returns nothing new; `rg -n 'Bearer [A-Za-z0-9._-]{12,}' context/sce/codex-native-telemetry-contract.md` returns no match. - - Context synchronization: pending + - Completed: 2026-11-24 + - Files changed: `context/sce/codex-native-telemetry-contract.md` (new); `context/plans/codex-native-otel-instrumentation.md` (T01 record) + - Result: Probed Codex 0.172.0 (`rust-v0.172.0`, commit `3d86e43b`) with `exec`, `exec resume`, `exec fork`, pty-interactive start, subagent spawn, helper failure/refresh, and scratch-`CODEX_HOME` precedence runs against a loopback OTLP/HTTP JSON receiver with a dummy-header stub helper. Findings: the helper runs as `sh -c` from `CODEX_HOME` with the inherited Codex environment and no repository context, and argv arguments are delivered; refresh is timer-only (default 29 min), and helper failure suspends export without replay; a helper reaches every unpinned `otlp-http` exporter (user config and profile observed), so all exporter keys must be pinned by `-c`; `exec resume` without `-C` runs in the stored session cwd (attribution hazard); hooks never receive current-span `TRACEPARENT`, only inherited environment; hook `session_id` = `conversation.id`, `turn_id` = `turn.id`, `tool_use_id` = `call_id`, subagent `agent_id` = child `conversation.id`; `codex.turn.token_usage` `input` includes cached input; no cost signal; metrics carry no session id; logs carry unredactable tool arguments and `user.email`. Decision: hook spans ship as independent roots with no Codex `TRACEPARENT` extraction; native export only via a thin `sce codex` launcher that pins the helper with an explicit repository argument, traces and metrics to `MANAGED_OTLP_ENDPOINT` per-signal paths (`binary`), logs `none`, content flags false; safe modes are new interactive, `exec`, and `exec fork`, plus resume only with `-C`; conflict skip on user, profile, or readable system/requirements `otel.*`; no setup change; one ADR in T02. + - Verify results: contract inspected against every AC1 item (helper argv/cwd/env/stdout/refresh/failure/caching, precedence across `-c`/profile/user/requirements, non-canonical reach, interactive/exec/resume/fork/cwd/threads attribution, TRACEPARENT verdict, identifier mapping, token/cost/cache/tool/duration/model/repository/subagent semantics, privacy config, decision, parity matrix) — passed; `git ls-files | rg -i 'probe|otlp-receiver'` lists only pre-existing tracked fixtures and no new path (`git status` shows only the new contract file and this plan) — passed; `rg -n 'Bearer [A-Za-z0-9._-]{12,}|hvs\.|s\.[A-Za-z0-9]{20,}'` on the contract — no match, passed. + - Context impact: localized-new-contract — adds `context/sce/codex-native-telemetry-contract.md`; no shipped behavior changed; root context unaffected until T02 ships the mechanism. + - Deviations: enterprise requirements, MDM, cloud, and `app-server` layering were not probed live (root required or out of scope) and are recorded as source-only or unproven; Claude metric semantics in the parity matrix come from existing context and documentation and are deferred to T03 for live confirmation; probe runs created Codex session rollouts under the user's `~/.codex/sessions` (no config change). + - Context synchronization: synced - [ ] T02: `Ship native Codex telemetry and Codex hook spans on the managed infrastructure` (status:todo) - Task ID: T02 diff --git a/context/sce/codex-native-telemetry-contract.md b/context/sce/codex-native-telemetry-contract.md new file mode 100644 index 000000000..8cbc31a69 --- /dev/null +++ b/context/sce/codex-native-telemetry-contract.md @@ -0,0 +1,180 @@ +# Codex native telemetry contract + +Probe evidence for Codex CLI 0.172.0 native OpenTelemetry export, the `otel.headers_helper` invocation contract, configuration precedence, command-hook trace context, and identifier mapping. This file records the implementation decision for native Codex telemetry and Codex hook spans, and the Claude/Codex parity matrix. + +## Provenance + +- Binary: `codex-cli 0.172.0` (npm/bun distribution), Linux. +- Source reference: `openai/codex` tag `rust-v0.172.0`, commit `3d86e43b075adeba2193ec5c22ac92f55afd82e6`. The relevant files are `codex-rs/otel/src/headers_helper.rs`, `codex-rs/http-headers-helper/src/lib.rs`, `codex-rs/core/src/otel_init.rs`, `codex-rs/otel/src/provider.rs`, `codex-rs/otel/src/otlp.rs`, `codex-rs/config/src/types.rs`, `codex-rs/config/src/config_requirements.rs`, `codex-rs/config/src/loader/mod.rs`, `codex-rs/config/src/requirements_layers/layer.rs`, `codex-rs/hooks/src/engine/command_runner.rs`, `codex-rs/hooks/src/registry.rs`, `codex-rs/otel/src/trace_context.rs`, and `codex-rs/tui/src/cwd_prompt.rs`. +- Method: real `codex exec` runs, `exec resume`, `exec fork`, and a pseudo-terminal interactive start. Each run used process-local `-c` overrides that pointed all three exporters at a loopback OTLP/HTTP JSON receiver. A stub header helper printed a dummy `authorization` header and an `x-probe-repo` header that echoed its argv. A probe command hook was supplied through `-c hooks.=[...]` with `--dangerously-bypass-hook-trust`. The probe repositories, receiver, helper, and hook lived only in a session scratch directory. The user's `~/.codex/config.toml` was never modified. Model turns used the existing Codex login. No SCE credential was used and the production collector was never contacted. +- Config-precedence runs used a scratch `CODEX_HOME` without Codex authentication. Codex exported startup traces and logs before the model request failed. +- `TRACEPARENT` was unset for every run except the inherited-context probe, because the invoking shell carried a parent agent's `TRACEPARENT`. + +## Header-helper invocation contract + +| Question | Evidence | Verdict | +|---|---|---| +| Config keys | `otel.headers_helper` (string) and `otel.headers_helper_refresh_interval_ms` (non-zero integer). Source: `OtelConfigToml`. | Observed and source. | +| Argv form | A user-configured helper runs as `sh -c ""` unless `CODEX_HOME/` is an existing file, in which case that file runs directly with no arguments. Observed: `-c 'otel.headers_helper="/helper.sh "'` delivered `` as `$1`. | Arguments work. The command is shell text, so the repository path must be shell-quoted. | +| Working directory | `cwd=$CODEX_HOME` (`~/.codex` in the observed run); `PWD=$CODEX_HOME`. Source: `HeadersHelper::start(config, &settings.codex_home, …)`. A helper from managed requirements must be an absolute path and runs from its own parent directory. | The working directory can never identify the repository. | +| Environment | The helper inherits the full Codex process environment, including an inherited `TRACEPARENT`. Codex adds no `CODEX_THREAD_ID`, `CODEX_SESSION_ID`, or repository variable. Stdin is `/dev/null`; stderr is discarded. | No repository or session context is supplied. | +| Stdout format | One JSON object of string header names and values. Header names are case-insensitive. Duplicates, non-UTF-8 output, output over 64 KiB, or a non-object fail the run. Source: `http-headers-helper::parse_headers`. | `{"Authorization":"Bearer "}`, the current SCE output, is accepted. | +| Timeout | 10 s, after which the process group is killed. Source: `HELPER_TIMEOUT`. | Larger than `CREDENTIAL_LOOKUP_DEADLINE`, so the SCE deadline governs. | +| Refresh cadence | The default interval is 29 minutes (`DEFAULT_HEADERS_HELPER_REFRESH_INTERVAL_MS = 1_740_000`). Observed with `refresh_interval_ms=3000`: 17 runs at 3.01 s intervals over a 50 s session. The helper runs once at provider start. Exports wait for the first result. | Refresh is time-based only. A collector `401` does not trigger a refresh (no status handling in `otel/src/otlp.rs`). | +| Header caching | One worker per process serves every signal that has an explicit HTTP exporter. Each export uses the most recent helper result. Observed: each request's header carried the timestamp of the latest preceding helper run. | Cached between refreshes. | +| Failure recovery | Observed: while the helper exited `1` (about 12 s), no OTLP request reached the receiver and nothing was replayed afterwards. The first successful refresh restored export. Codex printed `WARNING: OTel headers helper failed; telemetry is not being exported: headers helper exited with status exit status: 1` to stderr once per process, and the session itself completed with exit 0. | Export is suspended and data is lost. Codex never falls back to stale or static headers. The session is not affected. | +| Precedence over static headers | Observed: with `OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer envtok,x-env=1"`, requests carried the helper's `authorization` and the environment's `x-env`. | Helper headers override static and environment headers. Other environment headers are merged in. | +| Redirects | `without_redirects()` whenever a helper is attached. Source: `otel/src/otlp.rs`. | Credentials do not follow collector redirects. | +| gRPC | The helper applies only to `otlp-http` exporters. | The managed path must use `otlp-http`. | + +## Configuration precedence + +The config layers in ascending precedence are: package, MDM admin, system `/etc/codex/config.toml`, cloud bundle, user `$CODEX_HOME/config.toml`, profile `$CODEX_HOME/.config.toml`, cwd/tree/repo `.codex/config.toml`, and runtime (`-c`, UI). Requirements (`/etc/codex/requirements.toml`, `/etc/codex/managed_config.toml`, cloud requirements, MDM) are applied after the config layers and override them. Source: `config/src/loader/mod.rs`, `core/src/config/requirements.rs`. + +| Case | Evidence | Verdict | +|---|---|---| +| Repository-local `otel` | `otel` is in `PROJECT_LOCAL_CONFIG_DENYLIST`. | A repository cannot set `otel.*`. | +| User `config.toml` exporters, helper only via `-c` | Observed (5a): every log and trace request, with the helper's header, went to the user-owned endpoint. | **Credential leak path.** Supplying only the helper hands the credential to any user-configured `otlp-http` exporter. | +| `-c` pins all three exporters over user config and profile | Observed (5b, 5e): every request went to the pinned endpoint and the user-owned receiver got nothing. Observed (5d): a profile-owned logs exporter that `-c` did not pin received the helper header. | `-c` beats user and profile layers per key. Every exporter key must be pinned, including `none` for a signal SCE does not export. | +| `OTEL_EXPORTER_OTLP_*_ENDPOINT` environment | Observed (5c): with `OTEL_EXPORTER_OTLP_ENDPOINT` and `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` set to another port, requests still went to the explicit `-c` endpoint. An empty explicit endpoint falls back to the environment (source comment in `OtelHeadersHelperTargets::merge_layer`). | A non-empty explicit endpoint is authoritative. `OTEL_EXPORTER_OTLP_HEADERS` is still merged (see above). | +| Endpoint path | Observed: requests were posted to the configured endpoint string verbatim (`…/v1/traces`, `…/v1/logs`, `…/v1/metrics`). | Per-signal paths must be supplied explicitly. | +| Requirements override `-c` | `apply_otel_requirements` overwrites every set field and records a startup warning. A requirements-layer helper must be an absolute executable path from local system or MDM requirements, never cloud requirements. Source. | Enterprise OTEL settings win over SCE `-c` overrides. | +| Requirements exporter with a user helper | `headers_helper_targets()`: when requirements carry OTEL settings but no helper, a user helper applies only to signals whose requirements exporter is unset. When requirements carry a helper, that helper serves only that layer's non-empty HTTP exporters. Source. | Upstream already blocks a user-supplied helper from reaching a managed exporter. | +| Requirements forcing content logging | `log_user_prompt`, `log_agent_responses`, `log_guardian_assessments`, and `tool_result` are requirements fields. Source. | A requirements layer can force content into logs. `-c` cannot undo it. | +| Enterprise requirements observed live | Not observable. Writing `/etc/codex/requirements.toml` needs root and was out of scope. MDM and cloud requirements are not readable from the CLI. | Source-only. | + +## Credential reach to non-canonical exporters + +A helper header reaches every explicit `otlp-http` exporter in the effective config, whatever its endpoint (`provider.rs` gates only on the exporter kind). Three paths were identified: + +1. A user or profile exporter for a signal that the launch arguments did not pin (observed, 5a and 5d). +2. An empty explicit endpoint falling back to `OTEL_EXPORTER_OTLP_*_ENDPOINT` (source). +3. A requirements-layer exporter. Upstream blocks this for a user helper (source). If requirements also set a helper, the requirements helper replaces SCE's and no SCE credential is involved. + +## Attribution by invocation mode + +| Mode | Evidence | Repository-safe when the helper repository is resolved from the launch directory | +|---|---|---| +| `codex` interactive, new session | Observed under a pty: `service.name=codex_cli_rs`. The helper got the launch-time argv and ran from `CODEX_HOME`. | Yes, for the first thread. | +| `codex exec` | Observed: `service.name=codex_exec`. The thread and hook `cwd` equal the launch directory. | Yes. | +| `codex exec resume ` without `-C` | Observed: launched from repository B, the session and every hook ran in repository A (the stored session cwd). | **No.** The launch directory does not identify the working repository. | +| `codex exec resume -C ` | Observed: the session ran in ``. | Yes, when the repository is resolved from `-C`. | +| `codex exec fork ` | Observed: the new session id ran in the launch directory, not in the source session's cwd. | Yes. | +| `codex resume` / `codex fork` (interactive) | Source: `tui/src/cwd_prompt.rs` asks the user to choose between the session directory and the current one, and defaults to the session directory. | No. The choice is made after launch. | +| `-C ` | Observed with resume. The process working directory is irrelevant to the helper. | Resolve the repository from `-C` when present. | +| In-process directory change or multiple threads | Source and observed: the helper command is fixed per process, while threads (subagents, `/new`, in-TUI resume, app-server) each carry their own cwd. Subagents inherit the parent's cwd (observed). | Not safe for a thread whose cwd leaves the launch repository. This is a residual risk; Codex exposes no per-thread hook into the helper. | +| `codex app-server` / remote | Not probed. Multi-client and multi-thread by design. | Unproven. | + +## Hook trace context + +| Probe | Evidence | Verdict | +|---|---|---| +| `TRACEPARENT` unset in the Codex process | All 8 hook runs (`SessionStart`, `UserPromptSubmit`, `PreToolUse` ×2, `PostToolUse` ×2, `Stop`, `SessionEnd`) saw an empty `TRACEPARENT` and `TRACESTATE`. | Codex does not inject trace context into command hooks. | +| `TRACEPARENT=00-aaaa…aaaa-bbbbbbbbbbbbbbbb-01` inherited | All 12 hook runs, including subagent runs, saw exactly the inherited value. `bbbbbbbbbbbbbbbb` was not an exported Codex span. Codex parented 8 of its own root spans on it, and 2,236 of 2,522 spans carried trace ID `aaaa…`. | A hook `TRACEPARENT` is inherited process environment, never the current Codex span. | +| Source | `hooks/src/registry.rs` snapshots `std::env::vars_os()` when the session starts. `command_runner::build_command` replays that snapshot plus the handler's configured `env`. No code path writes `TRACEPARENT`. `otel/src/trace_context.rs` reads `TRACEPARENT` only as the inbound parent of Codex's own spans. Codex does export a `codex.hooks.command` span per hook run, but it is not propagated. | Confirmed. | + +**Verdict:** SCE Codex hook spans must not be parented on `TRACEPARENT`. A `sce.hook` span from a Codex hook is an independent root with correlation attributes. Parenting on the inherited value would attach SCE spans to whatever trace launched Codex. + +## Identifier mapping + +| Hook stdin field | Native telemetry equivalent | Observed relationship | +|---|---|---| +| `session_id` | `conversation.id` on logs and spans; `thread.id`/`thread_id` (string) on some spans | Equal (for example `01a20dc9-9a1a-…`). The SCE identity is `cx_` (`DIFF_TRACE_CODEX_SESSION_ID_PREFIX`). | +| `turn_id` | `turn.id` / `turn_id` span attributes | Equal. | +| `tool_use_id` | `call_id` on spans and the `codex.tool_result`/`codex.tool_decision` logs | Equal for `exec-…` ids. Model `call_…` ids appear on other spans. | +| `model` | `model` on metrics, logs, and the `session_task.turn` span | Equal. | +| `agent_id` (subagent hooks only), `agent_type` | Child thread `conversation.id`; `agent_name` (`/root/`) on `codex.tool_result`; `session_source=subagent_thread_spawn__d` on metrics | `agent_id` equals the child `conversation.id`. Hook `session_id` stays the parent's. | +| `transcript_path` | none | `~/.codex/sessions/…/rollout-…-.jsonl`. | +| — | `thread.id` as an integer | The OS thread number from `tracing`, unrelated to the Codex thread. Do not join on it. | +| — | `session.id` on `code_mode.grpc.*` spans | A code-mode runtime id. Not the conversation. | + +Hooks get no `CODEX_THREAD_ID`, `CODEX_SESSION_ID`, or `CODEX_TOOL_CALL_ID` in their environment (observed empty). Identifiers come only from stdin. + +## Exported data and observed semantics + +Resource attributes on all signals: `service.name` (`codex_exec` | `codex_cli_rs`), `service.version=0.172.0`, `env` (from `otel.environment`, default `dev`), `telemetry.sdk.*`. Logs add `host.name`; metrics add `os`, `os_version`. No repository attribute exists. + +| Data | Where | Observed semantics | +|---|---|---| +| Tokens per turn | Metric `codex.turn.token_usage` (histogram, delta temporality, one point per turn, attributes `token_type` ∈ {`input`, `cached_input`, `cache_write_input`, `output`, `reasoning_output`, `total`}, `model`, `session_source`, `originator`, `auth_mode`, `app.version`). Span `session_task.turn` attributes `codex.turn.token_usage.*` including `non_cached_input_tokens`. | `input` **includes** cached input: 69,087 = 50,816 cached + 18,271 non-cached; `total` = input + output (69,201). | +| Tokens per request | Span `handle_responses`: `gen_ai.usage.input_tokens`, `gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.cache_write.input_tokens`, `gen_ai.usage.output_tokens`, `codex.usage.reasoning_output_tokens`, `codex.usage.total_tokens`. Log `codex.sse_event` (`response.completed`) token counts. | Per model request. | +| Cost | none | **Not exported.** There is no cost attribute or metric in any signal. | +| Cache | See tokens. | `cached_input` / `cache_read` = prompt-cache reads; `cache_write_input` = cache writes (0 in every observed run). | +| Tools | Metrics `codex.tool.call` (counter, `tool`, `success`, `sandbox`, `command_category`), `codex.tool.call.duration_ms`, `codex.exec_command.calls`, `codex.turn.tool.call` (per-turn count). Logs `codex.tool_decision`, `codex.tool_result`. Span `codex.hooks.command`. | Tool names are `exec`, `exec_command`, `apply_patch`, and so on. | +| Durations | `codex.turn.e2e_duration_ms`, `codex.turn.ttft.duration_ms`, `codex.turn.ttfm.duration_ms`, `codex.hooks.run.duration_ms`, many startup metrics. | Milliseconds. | +| Model | `model` attribute on metrics, logs, and turn spans. | — | +| Session or conversation on metrics | none | **Metric points carry no conversation or session id.** Only logs and spans carry `conversation.id`. | +| Repository | `cwd` on 2–3 spans per session (absolute path). | Repository attribution must come from the credential binding (collector dataset) or from `otel.span_attributes` (traces only). | +| Subagents | See Identifier mapping. | Attributable through `session_source` and the child `conversation.id`. | +| Volume | A trivial `exec` session exported about 1,800 spans in about 4 MB of OTLP JSON across 77 traces, mostly `fs.*` and `append_items`. Metrics are exported once at process shutdown for `exec`. | There is no trace-volume filter in `otel.*`. Recorded as a control-plane cost follow-up. | + +### Privacy controls + +| Content | Default | Control | +|---|---|---| +| User prompt (`codex.user_prompt` log `prompt`) | `[REDACTED]` (observed) | `otel.log_user_prompt` (default false). | +| Agent responses | Not logged | `otel.log_agent_responses` (default false; needs a log exporter). | +| Guardian rationales | Not logged | `otel.log_guardian_assessments` (default false). | +| Tool arguments (`codex.tool_result` `arguments`) | **Logged in full** (observed `{"cmd":"cat a.txt"}`) | **No config control** in 0.172.0. | +| Tool output (`codex.tool_result` `output`) | **Logged, capped at 2,048 bytes** (observed command output) | `otel.tool_result.max_bytes`. | +| Personal identifiers | `user.email` and `user.account_id` on every Codex log event (observed) | No config control. | +| Spans and metrics | No prompt, response, tool-argument, or output attributes observed. `cwd` paths appear on a few spans. | — | + +Every content-bearing field is on the log signal. Spans and metrics carry identifiers, counts, and durations only. + +## Implementation decision + +1. **Hook spans ship without a launcher.** `sce hooks codex` and `sce hooks codex-mutation-scope` are admitted to managed telemetry as Codex-only hook subcommands. Each exports one `sce.hook` span (`sce.agent=codex`). Verified correlation attributes are `sce.codex.session_id` (the raw stdin `session_id`), `sce.codex.turn_id`, `sce.codex.tool_use_id`, `sce.codex.model`, and, for subagent hook runs, `sce.codex.agent_id`/`sce.codex.agent_type`. Every span is an independent root, with **no `TRACEPARENT` extraction** for Codex. `sce.mutation_scope`, `sce.git_snapshot`, and `sce.persistence` children reuse the existing contract. +2. **Native export requires a thin `sce codex` launcher.** A user-level `config.toml` install cannot identify the repository: the helper runs from `CODEX_HOME` with no repository context, and a fixed user-level command would attribute every repository to one credential. The launcher resolves the repository and effective access policy first, then `exec`s `codex` with process-local overrides only: + - `otel.headers_helper` set to `"" auth telemetry-headers --repo ''`, under the hidden flag name T02 chooses; + - `otel.headers_helper_refresh_interval_ms=300000`, matching the Claude 5-minute debounce; + - `otel.trace_exporter` and `otel.metrics_exporter` = `otlp-http` with `endpoint = MANAGED_OTLP_ENDPOINT + "/v1/traces"` / `"/v1/metrics"` and `protocol = "binary"` (`MANAGED_OTLP_PROTOCOL = http/protobuf`); + - **`otel.exporter = "none"`**: native log export stays off, because 0.172.0 cannot redact tool arguments or the user email from logs. Tokens, cache, model, tool counts, and durations remain available from metrics and spans. + - `otel.log_user_prompt=false`, `otel.log_agent_responses=false`, and `otel.log_guardian_assessments=false`, pinned explicitly; + - optionally `otel.span_attributes.sce.repository.id=` for trace-side repository attribution. This is a T02 local choice, traces only. + No credential appears in arguments or files, and no global Codex config is written. +3. **Safe modes.** The launcher enables native telemetry for new interactive sessions, `exec`, `exec fork`, and `resume`/`exec resume` **only with an explicit `-C`** (the repository is resolved from `-C` when present). It launches **without SCE telemetry**, with a one-line notice, for `resume` without `-C`, interactive `fork`, `app-server`, `exec-server`, `remote-control`, `cloud`, `mcp`, and unknown subcommands. In-process thread switching to another repository is a recorded residual risk. +4. **Conflict detection.** The launcher skips native telemetry and reports the reason, never overwriting anything, when any of the following holds: + - `$CODEX_HOME/config.toml` or the selected profile file defines `otel.exporter`, `otel.trace_exporter`, `otel.metrics_exporter`, or `otel.headers_helper`, because the user owns an OTEL destination; + - a readable `/etc/codex/requirements.toml`, `/etc/codex/managed_config.toml`, or `/etc/codex/config.toml` defines any `otel.*` key, because enterprise settings would override the pins or force content logging; + - the caller's arguments include an `otel.*` `-c` override or `--profile` in an unreadable form. + MDM and cloud requirements cannot be read and are a residual risk. Upstream still prevents a user helper from reaching a managed exporter (`headers_helper_targets`). +5. **Helper repository context.** The hidden `sce auth telemetry-headers` gains an explicit repository argument. With it, the policy gate, destination tripwire, `auth.db` presence check, repository-binding lookup, and `CREDENTIAL_LOOKUP_DEADLINE` apply to that path instead of `current_dir()`. The no-argument form stays byte-identical for Claude. The tripwire stays meaningful, because Codex passes its environment to the helper. +6. **Setup and doctor.** No `sce setup` change is needed: no Codex config is written. Doctor changes are optional and out of the minimum T02 scope. +7. **ADR.** The launcher is a substantive architectural choice, so T02 records one ADR. + +The open question "is launcher-only coverage worth its cost" is answered by evidence: plain `codex` launches cannot be attributed safely. T02 ships the launcher together with the hook spans, and a plain `codex` launch keeps only the SCE hook spans. + +## Claude/Codex parity matrix + +Claude semantics come from existing SCE context (`telemetry-credential.md`, `claude-hook-trace-propagation.md`) and Claude Code monitoring documentation. They were not re-probed in T01, and T03 confirms them in Dash0. + +| Capability | Claude Code (SCE install) | Codex 0.172.0 (decided mechanism) | +|---|---|---| +| Activation | User-level settings; every launch | `sce codex` launches only; plain `codex` exports nothing natively | +| Repository attribution | Helper uses the launch cwd; `vcs.*` on metrics and logs via `OTEL_METRICS_INCLUDE_REPOSITORY` | Helper gets an explicit repository argument; no native repository attribute; optional `span_attributes` on traces | +| Helper refresh | Debounce 300 s; on demand | Fixed timer (300 s via launcher); start-up run; no refresh on 401 | +| Helper failure | Export unauthenticated or failing | Export suspended and data dropped; one stderr warning | +| Token usage | `claude_code.token.usage` counter; `input` excludes cache reads; separate `cacheRead`/`cacheCreation` | `codex.turn.token_usage` histogram per turn; `input` **includes** `cached_input`; also `cache_write_input`, `reasoning_output`, `total`. Not summable against Claude `input` without subtracting `cached_input` | +| Cost | `claude_code.cost.usage` (USD) | **None**; must be derived server-side from tokens and model | +| Session id on metrics | `session.id` attribute | **None** on metrics; `conversation.id` on spans only (logs off) | +| Model | `model` | `model` | +| Tool telemetry | Tool events and spans; `OTEL_LOG_TOOL_DETAILS=1` exports tool input | `codex.tool.call` counters and durations, tool spans; tool input not exported (logs off) | +| Prompt and response content | Prompts redacted by default | Prompts redacted; responses off; tool arguments and output excluded by disabling logs | +| Native log events | Exported | Disabled (privacy) | +| Native traces | Enhanced beta tracing | Exported; high volume | +| Subagent attribution | Agent names with tool details | `session_source=subagent_thread_spawn__dN`; child `conversation.id`; hook `agent_id` | +| SCE hook spans | `sce.hook`, `sce.agent=claude`, `sce.claude.*` | `sce.hook`, `sce.agent=codex`, `sce.codex.*` | +| Hook span parenting | `TRACEPARENT` → `claude_code.interaction` span | Independent root; Codex never propagates current-span context | +| Hook-to-native join | `tool_use_id` ↔ `claude_code.tool` | `session_id` ↔ `conversation.id`, `turn_id` ↔ `turn.id`, `tool_use_id` ↔ `call_id` | + +## Upstream limitations + +- The helper runs from `CODEX_HOME` with no repository or thread context. +- Command hooks receive no current-span context. +- Tool arguments and the user email in logs have no redaction control. +- Metrics carry no session or conversation id. +- There is no cost signal. +- There is no trace-volume or target filter configuration. +- Refresh is timer-only, with no refresh on authentication failure. +- Requirements-layer OTEL settings override runtime `-c`. From 977ac744d88dee823a3fc92a18fc2ca321bdac94 Mon Sep 17 00:00:00 2001 From: David Abram Date: Tue, 24 Nov 2026 15:32:20 +0100 Subject: [PATCH 3/4] runtime: Add Codex native telemetry and hook tracing Enable repository-scoped Codex traces and metrics through `sce codex`, pinning managed endpoints and skipping conflicting or unauthorized environments without writing Codex config. Admit Codex hooks to managed `sce.hook` telemetry with verified identifiers and mutation-scope child spans, and extend telemetry-header lookup with explicit repository resolution for Codex launches. Document the launcher, credential, observability, command-surface, and integration contracts, including the launcher ADR and verified test/manual results. Plan: codex-native-otel-instrumentation (T02) Co-authored-by: SCE --- cli/context/tmp/sce-24_11_2026.log | 9 + cli/src/app.rs | 70 ++ cli/src/cli_schema.rs | 25 +- cli/src/command_surface.rs | 7 + cli/src/services/auth_command/command.rs | 2 +- cli/src/services/auth_command/mod.rs | 86 ++- cli/src/services/codex_telemetry/command.rs | 69 ++ cli/src/services/codex_telemetry/mod.rs | 558 +++++++++++++++ cli/src/services/codex_telemetry/tests.rs | 659 ++++++++++++++++++ cli/src/services/command_registry.rs | 3 + cli/src/services/hooks/codex/mod.rs | 3 + .../hooks/codex_mutation_scope/lifecycle.rs | 21 +- .../hooks/codex_mutation_scope/mod.rs | 3 + .../codex_mutation_scope/telemetry_tests.rs | 313 +++++++++ .../managed_telemetry/trace_export.rs | 217 +++++- cli/src/services/mod.rs | 1 + cli/src/services/parse/command_runtime.rs | 27 +- context/architecture.md | 5 +- context/cli/access-policy.md | 7 +- context/cli/cli-command-surface.md | 4 +- context/cli/execution-glossary.md | 2 + context/context-map.md | 4 +- ...native-telemetry-via-sce-codex-launcher.md | 83 +++ context/glossary.md | 2 +- context/overview.md | 1 + .../codex-native-otel-instrumentation.md | 10 +- context/sce/cli-observability-contract.md | 8 +- context/sce/codex-integration-runtime.md | 11 + .../sce/codex-native-telemetry-launcher.md | 80 +++ context/sce/telemetry-credential.md | 10 +- 30 files changed, 2265 insertions(+), 35 deletions(-) create mode 100644 cli/context/tmp/sce-24_11_2026.log create mode 100644 cli/src/services/codex_telemetry/command.rs create mode 100644 cli/src/services/codex_telemetry/mod.rs create mode 100644 cli/src/services/codex_telemetry/tests.rs create mode 100644 cli/src/services/hooks/codex_mutation_scope/telemetry_tests.rs create mode 100644 context/decisions/2026-11-24-codex-native-telemetry-via-sce-codex-launcher.md create mode 100644 context/sce/codex-native-telemetry-launcher.md diff --git a/cli/context/tmp/sce-24_11_2026.log b/cli/context/tmp/sce-24_11_2026.log new file mode 100644 index 000000000..bec8c3e66 --- /dev/null +++ b/cli/context/tmp/sce-24_11_2026.log @@ -0,0 +1,9 @@ +timestamp=2026-11-24T14:00:57.147Z log_format=text level=warn event_id=sce.hooks.claude_mutation_scope.pre_tool_use_fail_closed message=mutation-scope runtime boundary failed before durable completion: Operation 'execute repository Agent Trace DB database query' failed after 2 attempt(s) under write contention (db_name=repository Agent Trace DB, operation=execute repository Agent Trace DB database query, attempts=2, busy_timeout_ms=1000, contention_deadline_ms=2250 [no retry is scheduled past this cutoff], elapsed_ms=2035, cause=database busy (busy timeout exhausted)). Last error: repository Agent Trace DB execute failed: INSERT INTO mutation_trace_worktrees + (worktree_id, cursor_tree, revision, tainted, failure_kind, needs_rebaseline) + VALUES (?1, ?2, ?3, 0, 'healthy', 0) + ON CONFLICT (worktree_id) DO NOTHING: database is locked. Try: retry after the database lock clears; if the issue persists, stop other SCE processes using this database and rerun the command context=establish_start +timestamp=2026-11-24T14:01:02.164Z log_format=text level=warn event_id=sce.telemetry.fallback message=Managed telemetry disabled for this invocation; continuing without export reason=lookup_timeout +timestamp=2026-11-24T14:01:02.165Z log_format=text level=warn event_id=sce.telemetry.fallback message=Managed telemetry disabled for this invocation; continuing without export reason=lookup_timeout +timestamp=2026-11-24T14:12:42.500Z log_format=text level=warn event_id=sce.telemetry.fallback message=Managed telemetry disabled for this invocation; continuing without export reason=lookup_timeout +timestamp=2026-11-24T14:12:42.501Z log_format=text level=warn event_id=sce.telemetry.fallback message=Managed telemetry disabled for this invocation; continuing without export reason=lookup_timeout +timestamp=2026-11-24T14:25:24.748Z log_format=text level=error event_id=sce.error.SCE-ERR-RUNTIME message=Telemetry credential is unavailable. error_code=SCE-ERR-RUNTIME error_class=runtime error_surface=internal error_source=Telemetry credential is unavailable. diff --git a/cli/src/app.rs b/cli/src/app.rs index f6b62be50..45a1f5717 100644 --- a/cli/src/app.rs +++ b/cli/src/app.rs @@ -17,6 +17,7 @@ const RUNTIME_SHUTDOWN_GRACE: Duration = Duration::from_millis(500); const REPEATED_COMMAND_DISPATCH_ERROR: &str = "Command lifecycle telemetry attempted to execute command dispatch more than once"; const CLAUDE_ONLY_HOOK_SUBCOMMANDS: [&str; 2] = ["claude-mutation-scope", "claude-model-state"]; +const CODEX_HOOK_SUBCOMMANDS: [&str; 2] = ["codex", "codex-mutation-scope"]; const SHARED_CLAUDE_HOOK_SUBCOMMANDS: [&str; 2] = ["diff-trace", "conversation-trace"]; const CLAUDE_HOOK_CALLER_MARKERS: [&str; 2] = ["CLAUDECODE", "CLAUDE_PROJECT_DIR"]; @@ -317,12 +318,18 @@ fn managed_span_kind(args: &[String], claude_hook_caller: bool) -> Option + { + return Some(ManagedSpanKind::CodexHook); + } (Some(first), Some(subcommand)) if first == services::hooks::NAME => { CLAUDE_ONLY_HOOK_SUBCOMMANDS.contains(&subcommand) || (claude_hook_caller && SHARED_CLAUDE_HOOK_SUBCOMMANDS.contains(&subcommand)) } (Some(first), _) if first == services::hooks::NAME => false, (Some(first), _) if first == services::setup::NAME => false, + (Some(first), _) if first == services::codex_telemetry::NAME => false, (Some(first), Some("bash")) if first == services::bash_policy::NAME => claude_hook_caller, (Some(first), Some("telemetry-headers")) if first == services::auth_command::NAME => false, _ => return Some(ManagedSpanKind::Command), @@ -1130,4 +1137,67 @@ pub(crate) mod tests { .await; assert!(matches!(telemetry, RuntimeTelemetry::Noop(_))); } + + fn span_kind_for(command_line: &[&str], claude_hook_caller: bool) -> Option { + let args = command_line + .iter() + .map(|arg| (*arg).to_string()) + .collect::>(); + managed_span_kind(&args, claude_hook_caller) + } + + #[test] + fn managed_span_kind_admits_codex_hook_subcommands_without_caller_marker() { + for caller in [false, true] { + for argv in [ + ["sce", "hooks", "codex"].as_slice(), + ["sce", "hooks", "codex-mutation-scope"].as_slice(), + ] { + assert_eq!( + span_kind_for(argv, caller), + Some(ManagedSpanKind::CodexHook), + "{argv:?} caller={caller}" + ); + } + } + } + + #[test] + fn managed_span_kind_keeps_claude_and_shared_hook_admission() { + assert_eq!( + span_kind_for(&["sce", "hooks", "claude-mutation-scope"], false), + Some(ManagedSpanKind::ClaudeHook) + ); + assert_eq!( + span_kind_for(&["sce", "hooks", "diff-trace"], true), + Some(ManagedSpanKind::ClaudeHook) + ); + assert_eq!(span_kind_for(&["sce", "hooks", "diff-trace"], false), None); + assert_eq!(span_kind_for(&["sce", "hooks", "pre-commit"], true), None); + assert_eq!( + span_kind_for(&["sce", "config", "show"], false), + Some(ManagedSpanKind::Command) + ); + } + + #[test] + fn managed_span_kind_never_instruments_the_header_helper_or_codex_launcher() { + for argv in [ + ["sce", "auth", "telemetry-headers"].as_slice(), + ["sce", "auth", "telemetry-headers", "--repo", "/work/repo"].as_slice(), + ["sce", "auth", "telemetry-headers", "--repo=/work/repo"].as_slice(), + ["sce", "auth", "--repo", "telemetry-headers"].as_slice(), + ["sce", "codex"].as_slice(), + ["sce", "codex", "exec", "prompt"].as_slice(), + ["sce", "codex", "hooks", "codex"].as_slice(), + ] { + for caller in [false, true] { + assert_eq!( + span_kind_for(argv, caller), + None, + "{argv:?} caller={caller}" + ); + } + } + } } diff --git a/cli/src/cli_schema.rs b/cli/src/cli_schema.rs index 40e86d0d7..4da67a008 100644 --- a/cli/src/cli_schema.rs +++ b/cli/src/cli_schema.rs @@ -53,6 +53,11 @@ pub const SYNC_TOP_LEVEL_PURPOSE: &str = "Synchronize the current repository's Agent Trace database"; pub const SYNC_SHOW_IN_TOP_LEVEL_HELP: bool = true; +pub const CODEX_CLAP_ABOUT: &str = + "Launch Codex with SCE native telemetry for the current repository"; +pub const CODEX_TOP_LEVEL_PURPOSE: &str = "Launch Codex with SCE native telemetry"; +pub const CODEX_SHOW_IN_TOP_LEVEL_HELP: bool = true; + pub const TOP_LEVEL_COMMANDS: &[TopLevelCommandMetadata] = &[ TopLevelCommandMetadata { name: crate::services::auth_command::NAME, @@ -99,6 +104,11 @@ pub const TOP_LEVEL_COMMANDS: &[TopLevelCommandMetadata] = &[ purpose: SYNC_TOP_LEVEL_PURPOSE, show_in_top_level_help: SYNC_SHOW_IN_TOP_LEVEL_HELP, }, + TopLevelCommandMetadata { + name: crate::services::codex_telemetry::NAME, + purpose: CODEX_TOP_LEVEL_PURPOSE, + show_in_top_level_help: CODEX_SHOW_IN_TOP_LEVEL_HELP, + }, ]; #[derive(Parser, Debug)] @@ -241,6 +251,16 @@ pub enum Commands { #[arg(long, value_enum, default_value_t = OutputFormat::Text)] format: OutputFormat, }, + + #[command( + about = CODEX_CLAP_ABOUT, + hide = !CODEX_SHOW_IN_TOP_LEVEL_HELP, + disable_help_flag = true + )] + Codex { + #[arg(trailing_var_arg = true, allow_hyphen_values = true, num_args = 0..)] + args: Vec, + }, } #[derive(Subcommand, Debug, Clone, PartialEq, Eq)] @@ -264,7 +284,10 @@ pub enum AuthSubcommand { }, #[command(hide = true, about = "Print telemetry authorization headers")] - TelemetryHeaders, + TelemetryHeaders { + #[arg(long, hide = true)] + repo: Option, + }, } #[derive(Subcommand, Debug, Clone, PartialEq, Eq)] diff --git a/cli/src/command_surface.rs b/cli/src/command_surface.rs index 13682865d..3fa1892a4 100644 --- a/cli/src/command_surface.rs +++ b/cli/src/command_surface.rs @@ -59,6 +59,13 @@ const HELP_SECTIONS: &[HelpSection] = &[ suffix: " [--fix] [--format ]", }], }, + HelpSection { + title: "Codex Usage:", + body: &[HelpSectionBodyLine::Command { + cmd: " sce codex", + suffix: " [codex arguments...]", + }], + }, HelpSection { title: "Version Usage:", body: &[HelpSectionBodyLine::Command { diff --git a/cli/src/services/auth_command/command.rs b/cli/src/services/auth_command/command.rs index 2ce5e0448..0b6017c18 100644 --- a/cli/src/services/auth_command/command.rs +++ b/cli/src/services/auth_command/command.rs @@ -7,6 +7,6 @@ pub struct AuthCommand { impl AuthCommand { pub async fn execute(&self, _context: &C) -> Result { - auth_command::run_auth_subcommand(self.request).await + auth_command::run_auth_subcommand(self.request.clone()).await } } diff --git a/cli/src/services/auth_command/mod.rs b/cli/src/services/auth_command/mod.rs index 8b02aeb15..6217ca219 100644 --- a/cli/src/services/auth_command/mod.rs +++ b/cli/src/services/auth_command/mod.rs @@ -64,15 +64,16 @@ pub(crate) struct LoginReport { pub(crate) telemetry: TelemetryProvisioningResult, } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq)] pub enum AuthSubcommand { Login { format: AuthFormat }, Logout { format: AuthFormat }, Whoami { format: AuthFormat }, TelemetryHeaders, + TelemetryHeadersForRepository { repository: PathBuf }, } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[derive(Clone, Debug, Eq, PartialEq)] pub struct AuthRequest { pub subcommand: AuthSubcommand, } @@ -96,7 +97,7 @@ async fn run_auth_subcommand_with( telemetry_headers: H, ) -> Result where - H: FnOnce() -> HF, + H: FnOnce(Option) -> HF, HF: Future>, L: FnOnce(AuthFormat) -> LF, LF: Future>, @@ -109,12 +110,15 @@ where AuthSubcommand::Login { format } => login(format).await, AuthSubcommand::Logout { format } => logout(format).await, AuthSubcommand::Whoami { format } => whoami(format).await, - AuthSubcommand::TelemetryHeaders => telemetry_headers().await, + AuthSubcommand::TelemetryHeaders => telemetry_headers(None).await, + AuthSubcommand::TelemetryHeadersForRepository { repository } => { + telemetry_headers(Some(repository)).await + } } } -async fn run_telemetry_headers() -> Result { - let working_dir = std::env::current_dir().ok(); +async fn run_telemetry_headers(repository: Option) -> Result { + let working_dir = repository.or_else(|| std::env::current_dir().ok()); let telemetry_enabled = working_dir.as_deref().is_some_and(telemetry_enabled_for); telemetry_headers_with( working_dir, @@ -127,7 +131,7 @@ async fn run_telemetry_headers() -> Result { .await } -fn telemetry_enabled_for(working_dir: &Path) -> bool { +pub(crate) fn telemetry_enabled_for(working_dir: &Path) -> bool { config::resolve_auth_runtime_config(working_dir) .is_ok_and(|config| config.access_policy.telemetry_enabled()) } @@ -1096,6 +1100,74 @@ mod tests { assert_eq!(headers, r#"{"Authorization":"Bearer tok-scoped"}"#); } + #[tokio::test] + async fn telemetry_headers_route_repository_argument_and_keep_no_argument_form() { + let unexpected = |_: AuthFormat| async { panic!("unexpected auth subcommand") }; + let routed = |subcommand: AuthSubcommand| { + run_auth_subcommand_with( + AuthRequest { subcommand }, + unexpected, + unexpected, + unexpected, + |repository: Option| async move { Ok(format!("{repository:?}")) }, + ) + }; + + assert_eq!( + routed(AuthSubcommand::TelemetryHeaders).await.unwrap(), + "None" + ); + assert_eq!( + routed(AuthSubcommand::TelemetryHeadersForRepository { + repository: PathBuf::from("/work/b"), + }) + .await + .unwrap(), + r#"Some("/work/b")"# + ); + } + + #[tokio::test] + async fn telemetry_headers_bind_the_explicit_repository_and_fail_closed_elsewhere() { + use crate::services::managed_telemetry::claude_helper::tests::git_repository_with_remote; + + let dir = tempfile::tempdir().unwrap(); + let enrolled = git_repository_with_remote(dir.path(), "a", "git@github.com:acme/a.git"); + let unenrolled = git_repository_with_remote(dir.path(), "b", "git@github.com:acme/b.git"); + let not_git = dir.path().join("plain"); + std::fs::create_dir_all(¬_git).unwrap(); + let enrolled_id = repository_id_for(&enrolled).expect("enrolled repository identity"); + + let headers_for = |repository: PathBuf| { + let enrolled_id = enrolled_id.clone(); + telemetry_headers_with( + Some(repository), + true, + false, + || true, + repository_id_for, + move |repository_id: String| async move { + Ok((repository_id == enrolled_id).then(|| telemetry_credential("tok-a"))) + }, + ) + }; + + assert_eq!( + headers_for(enrolled.join("src").join("module")) + .await + .unwrap(), + r#"{"Authorization":"Bearer tok-a"}"# + ); + for (case, repository) in [ + ("unenrolled", unenrolled), + ("not git", not_git), + ("missing", dir.path().join("missing")), + ] { + let error = headers_for(repository).await.expect_err(case); + assert_eq!(error.to_string(), TELEMETRY_HEADERS_UNAVAILABLE, "{case}"); + } + } + #[test] fn telemetry_headers_failures_use_fixed_secret_free_diagnostic() { let missing = render_telemetry_headers(Ok(None)).expect_err("missing should fail"); diff --git a/cli/src/services/codex_telemetry/command.rs b/cli/src/services/codex_telemetry/command.rs new file mode 100644 index 000000000..95c0c3b5f --- /dev/null +++ b/cli/src/services/codex_telemetry/command.rs @@ -0,0 +1,69 @@ +use std::io::Write; + +use anyhow::anyhow; + +use super::{ + plan_launch_with, read_config_file, repository_root_for, LaunchContext, LaunchPlan, + CODEX_PROGRAM, +}; +use crate::services::auth_command::{repository_telemetry_authorized, telemetry_enabled_for}; +use crate::services::error::CliError; + +pub struct CodexCommand { + pub args: Vec, +} + +impl CodexCommand { + pub async fn execute_with_stderr( + &self, + _context: &C, + stderr: &mut W, + ) -> Result + where + W: Write, + { + let context = LaunchContext::from_process().map_err(|error| { + CliError::runtime(anyhow!( + "Failed to determine the Codex launch directory: {error}" + )) + })?; + let plan = plan_launch_with( + self.args.clone(), + &context, + read_config_file, + |key| std::env::var(key).ok(), + repository_root_for, + telemetry_enabled_for, + async |repository_root| repository_telemetry_authorized(&repository_root).await, + ) + .await; + if let Some(notice) = &plan.notice { + let _ = writeln!(stderr, "{notice}"); + } + let _ = stderr.flush(); + launch(plan) + } +} + +#[cfg(unix)] +fn launch(plan: LaunchPlan) -> Result { + use std::os::unix::process::CommandExt; + + let error = std::process::Command::new(CODEX_PROGRAM) + .args(plan.argv) + .exec(); + Err(launch_failure(&error)) +} + +#[cfg(not(unix))] +fn launch(plan: LaunchPlan) -> Result { + let status = std::process::Command::new(CODEX_PROGRAM) + .args(plan.argv) + .status() + .map_err(|error| launch_failure(&error))?; + std::process::exit(status.code().unwrap_or(1)); +} + +fn launch_failure(error: &std::io::Error) -> CliError { + CliError::runtime(anyhow!("Failed to launch `{CODEX_PROGRAM}`: {error}")) +} diff --git a/cli/src/services/codex_telemetry/mod.rs b/cli/src/services/codex_telemetry/mod.rs new file mode 100644 index 000000000..66de70413 --- /dev/null +++ b/cli/src/services/codex_telemetry/mod.rs @@ -0,0 +1,558 @@ +pub mod command; + +use std::fmt; +use std::future::Future; +use std::io; +use std::path::{Path, PathBuf}; + +use crate::services::default_paths::enclosing_repository_root; +use crate::services::managed_telemetry::claude_helper::visible_destination_conflict; +use crate::services::managed_telemetry::{ + MANAGED_OTLP_METRICS_ENDPOINT, MANAGED_OTLP_TRACES_ENDPOINT, +}; + +pub const NAME: &str = "codex"; + +const CODEX_PROGRAM: &str = "codex"; +const CODEX_HOME_ENV: &str = "CODEX_HOME"; +const HEADERS_HELPER_REFRESH_INTERVAL_MS: u32 = 300_000; +const OTLP_HTTP_BINARY_PROTOCOL: &str = "binary"; +const NOTICE_PREFIX: &str = "sce: launching Codex without SCE native telemetry"; + +const SYSTEM_CONFIG_PATHS: [&str; 3] = [ + "/etc/codex/requirements.toml", + "/etc/codex/managed_config.toml", + "/etc/codex/config.toml", +]; +const USER_OWNED_OTEL_KEYS: [&str; 4] = [ + "exporter", + "trace_exporter", + "metrics_exporter", + "headers_helper", +]; + +const CONFIG_OPTIONS: [&str; 2] = ["-c", "--config"]; +const PROFILE_OPTIONS: [&str; 2] = ["-p", "--profile"]; +const DIRECTORY_OPTIONS: [&str; 2] = ["-C", "--cd"]; +const OTHER_VALUE_OPTIONS: [&str; 16] = [ + "-m", + "--model", + "-s", + "--sandbox", + "-a", + "--ask-for-approval", + "-i", + "--image", + "--enable", + "--disable", + "--local-provider", + "--add-dir", + "--output-schema", + "-o", + "--output-last-message", + "--color", +]; +const FLAG_OPTIONS: [&str; 10] = [ + "--oss", + "--search", + "--full-auto", + "--dangerously-bypass-approvals-and-sandbox", + "--yolo", + "--skip-git-repo-check", + "--json", + "--ephemeral", + "--no-alt-screen", + "--dangerously-bypass-hook-trust", +]; +const HELP_OR_VERSION_OPTIONS: [&str; 4] = ["-h", "--help", "-V", "--version"]; + +const EXEC_SUBCOMMANDS: [&str; 2] = ["exec", "e"]; +const RESUME_SUBCOMMAND: &str = "resume"; +const FORK_SUBCOMMAND: &str = "fork"; +const SESSIONLESS_SUBCOMMANDS: [&str; 9] = [ + "login", + "logout", + "completion", + "features", + "apply", + "a", + "sandbox", + "debug", + "help", +]; +const UNSUPPORTED_SUBCOMMANDS: [&str; 7] = [ + "app-server", + "exec-server", + "remote-control", + "cloud", + "mcp", + "mcp-server", + "review", +]; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum LaunchMode { + Telemetry { directory: Option }, + Plain(PlainLaunchReason), +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum PlainLaunchReason { + Sessionless, + ResumeWithoutDirectory, + InteractiveFork, + UnsupportedSubcommand(String), + UnrecognizedOption(String), + NotRepository, + TelemetryDisabled, + Conflict(OtelConflict), + CredentialUnavailable, + ExecutableUnavailable, +} + +impl PlainLaunchReason { + fn notice(&self) -> Option { + let reason = match self { + Self::Sessionless | Self::TelemetryDisabled => return None, + Self::ResumeWithoutDirectory => { + "resume needs an explicit `-C ` to attribute the session to a repository" + .to_string() + } + Self::InteractiveFork => { + "interactive fork chooses its working directory after launch".to_string() + } + Self::UnsupportedSubcommand(subcommand) => { + format!("`{subcommand}` is not a supported telemetry launch mode") + } + Self::UnrecognizedOption(option) => { + format!("unrecognized Codex option `{option}`") + } + Self::NotRepository => { + "the launch directory is not inside a Git repository".to_string() + } + Self::Conflict(conflict) => conflict.to_string(), + Self::CredentialUnavailable => { + "no telemetry credential is authorized for this repository".to_string() + } + Self::ExecutableUnavailable => { + "the sce executable path could not be determined".to_string() + } + }; + Some(format!("{NOTICE_PREFIX}: {reason}.")) + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum OtelConflict { + DestinationEnvironment, + CallerOverride, + UnknownCodexHome, + UserConfig(PathBuf), + ProfileConfig(PathBuf), + SystemConfig(PathBuf), + UnreadableConfig(PathBuf), +} + +impl fmt::Display for OtelConflict { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::DestinationEnvironment => { + write!( + f, + "OTEL_EXPORTER_OTLP_* environment variables name another destination" + ) + } + Self::CallerOverride => write!(f, "the launch arguments override `otel.*` settings"), + Self::UnknownCodexHome => write!(f, "the Codex home directory could not be determined"), + Self::UserConfig(path) => { + write!(f, "{} defines a user-owned OTEL exporter", path.display()) + } + Self::ProfileConfig(path) => { + write!( + f, + "the selected profile in {} defines OTEL settings", + path.display() + ) + } + Self::SystemConfig(path) => { + write!(f, "{} defines managed OTEL settings", path.display()) + } + Self::UnreadableConfig(path) => { + write!(f, "{} could not be read as Codex config", path.display()) + } + } + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct LaunchPlan { + pub(crate) argv: Vec, + pub(crate) notice: Option, +} + +impl LaunchPlan { + fn plain(args: Vec, reason: &PlainLaunchReason) -> Self { + Self { + argv: args, + notice: reason.notice(), + } + } +} + +pub(crate) struct LaunchContext { + pub(crate) working_dir: PathBuf, + pub(crate) codex_home: Option, + pub(crate) sce_executable: Option, +} + +impl LaunchContext { + fn from_process() -> io::Result { + Ok(Self { + working_dir: std::env::current_dir()?, + codex_home: std::env::var_os(CODEX_HOME_ENV) + .map(PathBuf::from) + .or_else(|| dirs::home_dir().map(|home| home.join(".codex"))), + sce_executable: std::env::current_exe().ok(), + }) + } +} + +pub(crate) fn classify_launch(args: &[String]) -> LaunchMode { + let mut tokens = args.iter().map(String::as_str); + let mut directory = None; + let mut in_exec = false; + while let Some(token) = tokens.next() { + if token == "--" { + break; + } + match read_option(token, &mut tokens) { + OptionToken::Directory(value) => directory = Some(PathBuf::from(value)), + OptionToken::Other => {} + OptionToken::HelpOrVersion => return LaunchMode::Plain(PlainLaunchReason::Sessionless), + OptionToken::Unrecognized => { + return LaunchMode::Plain(PlainLaunchReason::UnrecognizedOption(token.to_string())) + } + OptionToken::Positional => { + let subcommand = if in_exec { + format!("exec {token}") + } else { + token.to_string() + }; + match (in_exec, token) { + (false, _) if EXEC_SUBCOMMANDS.contains(&token) => in_exec = true, + (_, RESUME_SUBCOMMAND) => return classify_resume(directory, tokens), + (false, FORK_SUBCOMMAND) => { + return LaunchMode::Plain(PlainLaunchReason::InteractiveFork) + } + (_, "help") => return LaunchMode::Plain(PlainLaunchReason::Sessionless), + (false, _) if SESSIONLESS_SUBCOMMANDS.contains(&token) => { + return LaunchMode::Plain(PlainLaunchReason::Sessionless) + } + (_, _) if UNSUPPORTED_SUBCOMMANDS.contains(&token) => { + return LaunchMode::Plain(PlainLaunchReason::UnsupportedSubcommand( + subcommand, + )) + } + _ => return LaunchMode::Telemetry { directory }, + } + } + } + } + LaunchMode::Telemetry { directory } +} + +fn classify_resume<'a>( + mut directory: Option, + mut tokens: impl Iterator, +) -> LaunchMode { + while let Some(token) = tokens.next() { + if let OptionToken::Directory(value) = read_option(token, &mut tokens) { + directory = Some(PathBuf::from(value)); + } + } + match directory { + Some(directory) => LaunchMode::Telemetry { + directory: Some(directory), + }, + None => LaunchMode::Plain(PlainLaunchReason::ResumeWithoutDirectory), + } +} + +enum OptionToken<'a> { + Directory(&'a str), + Other, + HelpOrVersion, + Unrecognized, + Positional, +} + +fn read_option<'a>(token: &'a str, rest: &mut impl Iterator) -> OptionToken<'a> { + if token == "-" || !token.starts_with('-') { + return OptionToken::Positional; + } + if HELP_OR_VERSION_OPTIONS.contains(&token) { + return OptionToken::HelpOrVersion; + } + if FLAG_OPTIONS.contains(&token) { + return OptionToken::Other; + } + let Some((name, value)) = split_option(token, rest) else { + return OptionToken::Unrecognized; + }; + if DIRECTORY_OPTIONS.contains(&name) { + value.map_or(OptionToken::Other, OptionToken::Directory) + } else { + OptionToken::Other + } +} + +fn split_option<'a>( + token: &'a str, + rest: &mut impl Iterator, +) -> Option<(&'a str, Option<&'a str>)> { + let is_value_option = |name: &str| { + CONFIG_OPTIONS.contains(&name) + || PROFILE_OPTIONS.contains(&name) + || DIRECTORY_OPTIONS.contains(&name) + || OTHER_VALUE_OPTIONS.contains(&name) + }; + if is_value_option(token) { + return Some((token, rest.next())); + } + if !token.starts_with("--") && token.len() > 2 && token.is_char_boundary(2) { + let (name, value) = token.split_at(2); + let value = value.strip_prefix('=').unwrap_or(value); + return is_value_option(name).then_some((name, Some(value))); + } + let (name, value) = token.split_once('=')?; + is_value_option(name).then_some((name, Some(value))) +} + +fn option_values<'a>(args: &'a [String], names: &[&str]) -> Vec<&'a str> { + let mut values = Vec::new(); + let mut tokens = args.iter().map(String::as_str); + while let Some(token) = tokens.next() { + if token == "--" { + break; + } + if let Some((name, Some(value))) = split_option(token, &mut tokens) { + if names.contains(&name) { + values.push(value); + } + } + } + values +} + +pub(crate) fn detect_otel_conflict( + args: &[String], + codex_home: Option<&Path>, + read_config: R, + environment: E, +) -> Option +where + R: Fn(&Path) -> io::Result>, + E: Fn(&str) -> Option, +{ + if visible_destination_conflict(environment) { + return Some(OtelConflict::DestinationEnvironment); + } + if option_values(args, &CONFIG_OPTIONS) + .iter() + .any(|value| is_otel_key(value.split_once('=').map_or(*value, |(key, _)| key))) + { + return Some(OtelConflict::CallerOverride); + } + let Some(codex_home) = codex_home else { + return Some(OtelConflict::UnknownCodexHome); + }; + + let user_path = codex_home.join("config.toml"); + let user_config = match load_toml(&user_path, &read_config) { + Ok(config) => config.unwrap_or_default(), + Err(()) => return Some(OtelConflict::UnreadableConfig(user_path)), + }; + if defines_user_owned_otel(&user_config) { + return Some(OtelConflict::UserConfig(user_path)); + } + + let profile = option_values(args, &PROFILE_OPTIONS) + .last() + .map(|name| (*name).to_string()) + .or_else(|| { + user_config + .get("profile") + .and_then(toml::Value::as_str) + .map(str::to_string) + }); + if let Some(profile) = profile { + let inline_profile = user_config + .get("profiles") + .and_then(|profiles| profiles.get(&profile)) + .and_then(toml::Value::as_table); + if inline_profile.is_some_and(defines_user_owned_otel) { + return Some(OtelConflict::ProfileConfig(user_path)); + } + let profile_path = codex_home.join(format!("{profile}.config.toml")); + match load_toml(&profile_path, &read_config) { + Ok(Some(config)) if defines_user_owned_otel(&config) => { + return Some(OtelConflict::ProfileConfig(profile_path)) + } + Ok(_) => {} + Err(()) => return Some(OtelConflict::UnreadableConfig(profile_path)), + } + } + + SYSTEM_CONFIG_PATHS + .iter() + .map(Path::new) + .find_map(|path| match read_config(path) { + Ok(Some(contents)) => match contents.parse::() { + Ok(config) if !config.contains_key("otel") => None, + _ => Some(OtelConflict::SystemConfig(path.to_path_buf())), + }, + Ok(None) | Err(_) => None, + }) +} + +fn is_otel_key(key: &str) -> bool { + let key = key.trim(); + key == "otel" || key.starts_with("otel.") +} + +fn load_toml(path: &Path, read_config: &R) -> Result, ()> +where + R: Fn(&Path) -> io::Result>, +{ + match read_config(path) { + Ok(Some(contents)) => contents.parse::().map(Some).map_err(|_| ()), + Ok(None) => Ok(None), + Err(_) => Err(()), + } +} + +fn defines_user_owned_otel(config: &toml::Table) -> bool { + config + .get("otel") + .and_then(toml::Value::as_table) + .is_some_and(|otel| { + USER_OWNED_OTEL_KEYS + .iter() + .any(|key| otel.contains_key(*key)) + }) +} + +pub(crate) fn read_config_file(path: &Path) -> io::Result> { + match std::fs::read_to_string(path) { + Ok(contents) => Ok(Some(contents)), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error), + } +} + +pub(crate) fn telemetry_overrides(sce_executable: &Path, repository_root: &Path) -> Vec { + let helper = format!( + "{} auth telemetry-headers --repo {}", + shell_quote(&sce_executable.to_string_lossy()), + shell_quote(&repository_root.to_string_lossy()), + ); + let exporter = |endpoint: &str| { + format!( + "{{otlp-http={{endpoint={},protocol={}}}}}", + toml_string(endpoint), + toml_string(OTLP_HTTP_BINARY_PROTOCOL) + ) + }; + [ + ("otel.headers_helper", toml_string(&helper)), + ( + "otel.headers_helper_refresh_interval_ms", + HEADERS_HELPER_REFRESH_INTERVAL_MS.to_string(), + ), + ("otel.exporter", toml_string("none")), + ( + "otel.trace_exporter", + exporter(MANAGED_OTLP_TRACES_ENDPOINT), + ), + ( + "otel.metrics_exporter", + exporter(MANAGED_OTLP_METRICS_ENDPOINT), + ), + ("otel.log_user_prompt", "false".to_string()), + ("otel.log_agent_responses", "false".to_string()), + ("otel.log_guardian_assessments", "false".to_string()), + ] + .into_iter() + .flat_map(|(key, value)| ["-c".to_string(), format!("{key}={value}")]) + .collect() +} + +fn toml_string(value: &str) -> String { + toml::Value::String(value.to_string()).to_string() +} + +fn shell_quote(value: &str) -> String { + format!("'{}'", value.replace('\'', r"'\''")) +} + +pub(crate) fn repository_root_for(launch_dir: &Path) -> Option { + let launch_dir = std::fs::canonicalize(launch_dir).ok()?; + enclosing_repository_root(&launch_dir).map(Path::to_path_buf) +} + +pub(crate) async fn plan_launch_with( + args: Vec, + context: &LaunchContext, + read_config: R, + environment: E, + resolve_repository_root: G, + telemetry_enabled: P, + authorized: A, +) -> LaunchPlan +where + R: Fn(&Path) -> io::Result>, + E: Fn(&str) -> Option, + G: FnOnce(&Path) -> Option, + P: FnOnce(&Path) -> bool, + A: FnOnce(PathBuf) -> AF, + AF: Future, +{ + let directory = match classify_launch(&args) { + LaunchMode::Plain(reason) => return LaunchPlan::plain(args, &reason), + LaunchMode::Telemetry { directory } => directory, + }; + let launch_dir = directory.map_or_else( + || context.working_dir.clone(), + |directory| context.working_dir.join(directory), + ); + let Some(repository_root) = resolve_repository_root(&launch_dir) else { + return LaunchPlan::plain(args, &PlainLaunchReason::NotRepository); + }; + if !telemetry_enabled(&repository_root) { + return LaunchPlan::plain(args, &PlainLaunchReason::TelemetryDisabled); + } + if let Some(conflict) = detect_otel_conflict( + &args, + context.codex_home.as_deref(), + read_config, + environment, + ) { + return LaunchPlan::plain(args, &PlainLaunchReason::Conflict(conflict)); + } + let Some(sce_executable) = context.sce_executable.as_deref() else { + return LaunchPlan::plain(args, &PlainLaunchReason::ExecutableUnavailable); + }; + let overrides = telemetry_overrides(sce_executable, &repository_root); + if !authorized(repository_root).await { + return LaunchPlan::plain(args, &PlainLaunchReason::CredentialUnavailable); + } + let mut launch_argv = overrides; + launch_argv.extend(args); + LaunchPlan { + argv: launch_argv, + notice: None, + } +} + +#[cfg(test)] +mod tests; diff --git a/cli/src/services/codex_telemetry/tests.rs b/cli/src/services/codex_telemetry/tests.rs new file mode 100644 index 000000000..00bf2f927 --- /dev/null +++ b/cli/src/services/codex_telemetry/tests.rs @@ -0,0 +1,659 @@ +use std::cell::RefCell; +use std::collections::HashMap; +use std::process::Command; + +use super::*; + +fn args(values: &[&str]) -> Vec { + values.iter().map(|value| (*value).to_string()).collect() +} + +fn telemetry(directory: Option<&str>) -> LaunchMode { + LaunchMode::Telemetry { + directory: directory.map(PathBuf::from), + } +} + +fn plain(reason: PlainLaunchReason) -> LaunchMode { + LaunchMode::Plain(reason) +} + +#[test] +fn codex_telemetry_classifies_new_sessions_exec_and_exec_fork_as_telemetry_modes() { + for (argv, expected) in [ + (vec![], telemetry(None)), + (vec!["fix the failing test"], telemetry(None)), + ( + vec!["-m", "gpt-5", "--full-auto", "prompt"], + telemetry(None), + ), + (vec!["exec", "prompt"], telemetry(None)), + (vec!["e", "--json", "prompt"], telemetry(None)), + (vec!["exec"], telemetry(None)), + (vec!["exec", "fork", "019a-session"], telemetry(None)), + ( + vec!["-C", "../other", "exec", "prompt"], + telemetry(Some("../other")), + ), + (vec!["--cd=/work/b"], telemetry(Some("/work/b"))), + (vec!["-C/work/b", "prompt"], telemetry(Some("/work/b"))), + (vec!["-m", "resume"], telemetry(None)), + (vec!["-c", "model=fork", "prompt"], telemetry(None)), + (vec!["--", "--help"], telemetry(None)), + ] { + assert_eq!(classify_launch(&args(&argv)), expected, "{argv:?}"); + } +} + +#[test] +fn codex_telemetry_requires_explicit_directory_for_resume() { + for (argv, expected) in [ + ( + vec!["resume", "019a-session"], + plain(PlainLaunchReason::ResumeWithoutDirectory), + ), + ( + vec!["resume", "--last"], + plain(PlainLaunchReason::ResumeWithoutDirectory), + ), + ( + vec!["exec", "resume", "019a-session", "prompt"], + plain(PlainLaunchReason::ResumeWithoutDirectory), + ), + ( + vec!["resume", "019a-session", "-C", "/work/a"], + telemetry(Some("/work/a")), + ), + ( + vec!["-C", "/work/a", "resume", "019a-session"], + telemetry(Some("/work/a")), + ), + ( + vec!["exec", "resume", "--cd", "/work/a", "019a-session"], + telemetry(Some("/work/a")), + ), + ] { + assert_eq!(classify_launch(&args(&argv)), expected, "{argv:?}"); + } +} + +#[test] +fn codex_telemetry_launches_unproven_and_sessionless_modes_without_telemetry() { + for (argv, expected) in [ + ( + vec!["fork", "019a-session"], + plain(PlainLaunchReason::InteractiveFork), + ), + ( + vec!["-c", "model=o3", "fork"], + plain(PlainLaunchReason::InteractiveFork), + ), + ( + vec!["app-server"], + plain(PlainLaunchReason::UnsupportedSubcommand( + "app-server".into(), + )), + ), + ( + vec!["exec", "review"], + plain(PlainLaunchReason::UnsupportedSubcommand( + "exec review".into(), + )), + ), + ( + vec!["mcp", "list"], + plain(PlainLaunchReason::UnsupportedSubcommand("mcp".into())), + ), + ( + vec!["--brand-new-flag", "resume"], + plain(PlainLaunchReason::UnrecognizedOption( + "--brand-new-flag".into(), + )), + ), + ( + vec!["--brand-new=value"], + plain(PlainLaunchReason::UnrecognizedOption( + "--brand-new=value".into(), + )), + ), + (vec!["login"], plain(PlainLaunchReason::Sessionless)), + (vec!["--help"], plain(PlainLaunchReason::Sessionless)), + (vec!["exec", "-h"], plain(PlainLaunchReason::Sessionless)), + (vec!["--version"], plain(PlainLaunchReason::Sessionless)), + ] { + assert_eq!(classify_launch(&args(&argv)), expected, "{argv:?}"); + } +} + +struct ConfigFiles(HashMap>); + +impl ConfigFiles { + fn new(entries: Vec<(&str, io::Result<&str>)>) -> Self { + Self( + entries + .into_iter() + .map(|(path, contents)| (PathBuf::from(path), contents.map(str::to_string))) + .collect(), + ) + } + + fn read(&self, path: &Path) -> io::Result> { + match self.0.get(path) { + None => Ok(None), + Some(Ok(contents)) => Ok(Some(contents.clone())), + Some(Err(error)) => Err(io::Error::new(error.kind(), "denied")), + } + } +} + +fn no_environment(_: &str) -> Option { + None +} + +fn conflict_for( + argv: &[&str], + files: &ConfigFiles, + environment: impl Fn(&str) -> Option, +) -> Option { + detect_otel_conflict( + &args(argv), + Some(Path::new("/home/u/.codex")), + |path| files.read(path), + environment, + ) +} + +fn denied() -> io::Result<&'static str> { + Err(io::Error::from(io::ErrorKind::PermissionDenied)) +} + +type ConflictCase = ( + &'static str, + Vec<&'static str>, + Vec<(&'static str, io::Result<&'static str>)>, + OtelConflict, +); + +const USER_CONFIG: &str = "/home/u/.codex/config.toml"; + +fn assert_conflicts(cases: Vec) { + for (case, argv, files, expected) in cases { + assert_eq!( + conflict_for(&argv, &ConfigFiles::new(files), no_environment), + Some(expected), + "{case}" + ); + } +} + +#[test] +fn codex_telemetry_conflict_detection_skips_for_caller_user_and_profile_otel() { + let user = USER_CONFIG; + assert_conflicts(vec![ + ( + "caller override", + vec!["-c", "otel.trace_exporter=none"], + vec![], + OtelConflict::CallerOverride, + ), + ( + "caller override attached", + vec!["--config=otel.environment=\"prod\"", "exec"], + vec![], + OtelConflict::CallerOverride, + ), + ( + "caller otel table", + vec!["-cotel={exporter=\"none\"}"], + vec![], + OtelConflict::CallerOverride, + ), + ( + "user exporter", + vec![], + vec![(user, Ok("[otel]\nexporter = { otlp-http = { endpoint = \"https://mine/v1/logs\", protocol = \"json\" } }\n"))], + OtelConflict::UserConfig(PathBuf::from(user)), + ), + ( + "user helper", + vec![], + vec![(user, Ok("otel.headers_helper = \"my-helper\"\n"))], + OtelConflict::UserConfig(PathBuf::from(user)), + ), + ( + "profile file from argument", + vec!["--profile", "work"], + vec![( + "/home/u/.codex/work.config.toml", + Ok("[otel]\nmetrics_exporter = \"statsig\"\n"), + )], + OtelConflict::ProfileConfig(PathBuf::from("/home/u/.codex/work.config.toml")), + ), + ( + "default inline profile", + vec![], + vec![( + user, + Ok("profile = \"work\"\n[profiles.work.otel]\ntrace_exporter = \"none\"\n"), + )], + OtelConflict::ProfileConfig(PathBuf::from(user)), + ), + ( + "unreadable user config", + vec![], + vec![(user, denied())], + OtelConflict::UnreadableConfig(PathBuf::from(user)), + ), + ( + "invalid user config", + vec![], + vec![(user, Ok("otel = [unterminated"))], + OtelConflict::UnreadableConfig(PathBuf::from(user)), + ), + ( + "invalid profile file", + vec!["-p", "work"], + vec![("/home/u/.codex/work.config.toml", Ok("[[["))], + OtelConflict::UnreadableConfig(PathBuf::from("/home/u/.codex/work.config.toml")), + ), + ]); +} + +#[test] +fn codex_telemetry_conflict_detection_skips_for_managed_system_otel() { + assert_conflicts(vec![ + ( + "requirements", + vec![], + vec![( + "/etc/codex/requirements.toml", + Ok("[otel]\nlog_user_prompt = true\n"), + )], + OtelConflict::SystemConfig(PathBuf::from("/etc/codex/requirements.toml")), + ), + ( + "managed config", + vec![], + vec![( + "/etc/codex/managed_config.toml", + Ok("otel.environment = \"corp\"\n"), + )], + OtelConflict::SystemConfig(PathBuf::from("/etc/codex/managed_config.toml")), + ), + ( + "system config", + vec![], + vec![("/etc/codex/config.toml", Ok("[otel]\n"))], + OtelConflict::SystemConfig(PathBuf::from("/etc/codex/config.toml")), + ), + ]); +} + +#[test] +fn codex_telemetry_conflict_detection_allows_unrelated_settings() { + let files = ConfigFiles::new(vec![ + ( + "/home/u/.codex/config.toml", + Ok("model = \"o3\"\nprofile = \"work\"\n[otel]\nenvironment = \"dev\"\nlog_user_prompt = false\n[profiles.work]\nmodel = \"gpt-5\"\n"), + ), + ("/home/u/.codex/work.config.toml", Ok("model = \"gpt-5\"\n")), + ("/etc/codex/config.toml", Ok("model = \"o3\"\n")), + ("/etc/codex/requirements.toml", denied()), + ]); + assert_eq!( + conflict_for( + &["-c", "model=o3", "-c", "hotel.x=1", "exec"], + &files, + no_environment + ), + None + ); + assert_eq!( + conflict_for(&[], &ConfigFiles::new(vec![]), no_environment), + None + ); +} + +#[test] +fn codex_telemetry_conflict_detection_refuses_foreign_destination_environment_and_unknown_home() { + let foreign = |key: &str| { + (key == "OTEL_EXPORTER_OTLP_ENDPOINT").then(|| "http://localhost:4318".to_string()) + }; + assert_eq!( + conflict_for(&[], &ConfigFiles::new(vec![]), foreign), + Some(OtelConflict::DestinationEnvironment) + ); + let managed = |key: &str| { + (key == "OTEL_EXPORTER_OTLP_ENDPOINT").then(|| "https://otel.crocoderlab.dev".to_string()) + }; + assert_eq!(conflict_for(&[], &ConfigFiles::new(vec![]), managed), None); + assert_eq!( + detect_otel_conflict(&[], None, |_| Ok(None), no_environment), + Some(OtelConflict::UnknownCodexHome) + ); +} + +fn overrides_as_toml(overrides: &[String]) -> toml::Table { + assert_eq!(overrides.len() % 2, 0); + let document = overrides + .chunks(2) + .map(|pair| { + assert_eq!(pair[0], "-c"); + let (key, value) = pair[1].split_once('=').expect("key=value override"); + format!("{key} = {value}") + }) + .collect::>() + .join("\n"); + document + .parse::() + .expect("overrides are valid TOML") +} + +#[test] +fn codex_telemetry_overrides_pin_every_exporter_and_disable_content() { + let overrides = telemetry_overrides(Path::new("/opt/sce/bin/sce"), Path::new("/work/repo")); + let parsed = overrides_as_toml(&overrides); + let otel = parsed["otel"].as_table().expect("otel table"); + + assert_eq!(otel["exporter"].as_str(), Some("none")); + for (key, endpoint) in [ + ("trace_exporter", "https://otel.crocoderlab.dev/v1/traces"), + ( + "metrics_exporter", + "https://otel.crocoderlab.dev/v1/metrics", + ), + ] { + let exporter = otel[key]["otlp-http"].as_table().expect(key); + assert_eq!(exporter["endpoint"].as_str(), Some(endpoint), "{key}"); + assert_eq!(exporter["protocol"].as_str(), Some("binary"), "{key}"); + assert!( + !exporter.contains_key("headers"), + "{key} has static headers" + ); + } + assert_eq!( + otel["headers_helper_refresh_interval_ms"].as_integer(), + Some(300_000) + ); + for key in [ + "log_user_prompt", + "log_agent_responses", + "log_guardian_assessments", + ] { + assert_eq!(otel[key].as_bool(), Some(false), "{key}"); + } + for override_value in &overrides { + assert!(!override_value.contains("Bearer"), "{override_value}"); + assert!( + !override_value.contains("authorization"), + "{override_value}" + ); + } +} + +#[test] +fn codex_telemetry_helper_command_round_trips_through_the_shell() { + let repository = "/work/it's a $HOME `repo`\\ \"x\""; + let executable = "/opt/s ce/sce"; + let overrides = telemetry_overrides(Path::new(executable), Path::new(repository)); + let parsed = overrides_as_toml(&overrides); + let helper = parsed["otel"]["headers_helper"] + .as_str() + .expect("helper command"); + + let output = Command::new("sh") + .arg("-c") + .arg(format!("set -- {helper}; printf '%s\\0' \"$@\"")) + .output() + .expect("run sh"); + assert!(output.status.success()); + let words = String::from_utf8(output.stdout).unwrap(); + let words = words.trim_end_matches('\0').split('\0').collect::>(); + assert_eq!( + words, + [ + executable, + "auth", + "telemetry-headers", + "--repo", + repository + ] + ); +} + +struct Repositories { + _dir: tempfile::TempDir, + root: PathBuf, + first: PathBuf, + second: PathBuf, + plain: PathBuf, +} + +fn repositories() -> Repositories { + let dir = tempfile::tempdir().unwrap(); + let root = std::fs::canonicalize(dir.path()).unwrap(); + let first = root.join("first"); + let second = root.join("second"); + let plain = root.join("plain"); + for repository in [&first, &second] { + std::fs::create_dir_all(repository.join(".git")).unwrap(); + std::fs::create_dir_all(repository.join("src")).unwrap(); + } + std::fs::create_dir_all(&plain).unwrap(); + Repositories { + _dir: dir, + root, + first, + second, + plain, + } +} + +fn context_in(working_dir: &Path) -> LaunchContext { + LaunchContext { + working_dir: working_dir.to_path_buf(), + codex_home: Some(PathBuf::from("/home/u/.codex")), + sce_executable: Some(PathBuf::from("/opt/sce/bin/sce")), + } +} + +fn repository_root_within(sandbox: &Path) -> impl FnOnce(&Path) -> Option + '_ { + move |launch_dir| repository_root_for(launch_dir).filter(|root| root.starts_with(sandbox)) +} + +struct Outcome { + plan: LaunchPlan, + policy_checked: Option, + authorized_for: Option, +} + +fn plan( + argv: &[&str], + sandbox: &Path, + context: &LaunchContext, + files: &ConfigFiles, + telemetry_enabled: bool, + authorized: bool, +) -> Outcome { + let policy_checked = RefCell::new(None); + let authorized_for = RefCell::new(None); + let runtime = tokio::runtime::Builder::new_current_thread() + .build() + .unwrap(); + let plan = runtime.block_on(plan_launch_with( + args(argv), + context, + |path| files.read(path), + no_environment, + repository_root_within(sandbox), + |root: &Path| { + *policy_checked.borrow_mut() = Some(root.to_path_buf()); + telemetry_enabled + }, + |root: PathBuf| { + *authorized_for.borrow_mut() = Some(root); + async move { authorized } + }, + )); + Outcome { + plan, + policy_checked: policy_checked.into_inner(), + authorized_for: authorized_for.into_inner(), + } +} + +fn helper_repository(argv: &[String]) -> String { + let parsed = overrides_as_toml(&argv[..16]); + parsed["otel"]["headers_helper"] + .as_str() + .unwrap() + .rsplit_once(" --repo ") + .unwrap() + .1 + .trim_matches('\'') + .to_string() +} + +#[test] +fn codex_telemetry_plan_prepends_overrides_for_the_resolved_repository() { + let repos = repositories(); + let files = ConfigFiles::new(vec![]); + + let outcome = plan( + &["exec", "--json", "prompt"], + &repos.root, + &context_in(&repos.first.join("src")), + &files, + true, + true, + ); + assert_eq!(outcome.plan.notice, None); + assert_eq!( + outcome.policy_checked.as_deref(), + Some(repos.first.as_path()) + ); + assert_eq!( + outcome.authorized_for.as_deref(), + Some(repos.first.as_path()) + ); + assert_eq!(outcome.plan.argv[16..], args(&["exec", "--json", "prompt"])); + assert_eq!( + helper_repository(&outcome.plan.argv), + repos.first.to_string_lossy() + ); + + let resumed = plan( + &["resume", "019a-session", "-C", "../second"], + &repos.root, + &context_in(&repos.first), + &files, + true, + true, + ); + assert_eq!(resumed.plan.notice, None); + assert_eq!( + resumed.authorized_for.as_deref(), + Some(repos.second.as_path()) + ); + assert_eq!( + helper_repository(&resumed.plan.argv), + repos.second.to_string_lossy() + ); +} + +#[test] +fn codex_telemetry_plan_forwards_arguments_unchanged_when_telemetry_is_skipped() { + let repos = repositories(); + let conflicting = ConfigFiles::new(vec![( + "/home/u/.codex/config.toml", + Ok("[otel]\ntrace_exporter = \"none\"\n"), + )]); + let clean = ConfigFiles::new(vec![]); + let argv = ["-m", "o3", "exec", "prompt"]; + + let cases = [ + ( + "not a repository", + context_in(&repos.plain), + &clean, + true, + true, + true, + false, + ), + ( + "policy disabled", + context_in(&repos.first), + &clean, + false, + true, + false, + false, + ), + ( + "conflict", + context_in(&repos.first), + &conflicting, + true, + true, + true, + false, + ), + ( + "unauthorized", + context_in(&repos.first), + &clean, + true, + false, + true, + true, + ), + ]; + for (case, context, files, enabled, authorized, expect_notice, expect_lookup) in cases { + let outcome = plan(&argv, &repos.root, &context, files, enabled, authorized); + assert_eq!(outcome.plan.argv, args(&argv), "{case}"); + assert_eq!(outcome.plan.notice.is_some(), expect_notice, "{case}"); + assert_eq!(outcome.authorized_for.is_some(), expect_lookup, "{case}"); + } + + let conflict = plan( + &argv, + &repos.root, + &context_in(&repos.first), + &conflicting, + true, + true, + ); + assert_eq!( + conflict.plan.notice.as_deref(), + Some("sce: launching Codex without SCE native telemetry: /home/u/.codex/config.toml defines a user-owned OTEL exporter.") + ); + + let resume = plan( + &["resume", "--last"], + &repos.root, + &context_in(&repos.first), + &clean, + true, + true, + ); + assert_eq!(resume.plan.argv, args(&["resume", "--last"])); + assert!(resume.plan.notice.is_some()); + assert_eq!(resume.policy_checked, None); + + let help = plan( + &["--help"], + &repos.root, + &context_in(&repos.first), + &clean, + true, + true, + ); + assert_eq!( + help.plan, + LaunchPlan { + argv: args(&["--help"]), + notice: None + } + ); +} diff --git a/cli/src/services/command_registry.rs b/cli/src/services/command_registry.rs index c9ff67541..a573c2c8e 100644 --- a/cli/src/services/command_registry.rs +++ b/cli/src/services/command_registry.rs @@ -17,6 +17,7 @@ pub enum RuntimeCommand { Version(services::version::command::VersionCommand), Completion(services::completion::command::CompletionCommand), Sync(services::sync::command::SyncCommand), + Codex(services::codex_telemetry::command::CodexCommand), } impl RuntimeCommand { @@ -33,6 +34,7 @@ impl RuntimeCommand { Self::Version(_) => Cow::Borrowed(services::version::NAME), Self::Completion(_) => Cow::Borrowed(services::completion::NAME), Self::Sync(_) => Cow::Borrowed(services::sync::NAME), + Self::Codex(_) => Cow::Borrowed(services::codex_telemetry::NAME), } } @@ -57,6 +59,7 @@ impl RuntimeCommand { Self::Version(command) => command.execute(context), Self::Completion(command) => Ok(command.execute(context)), Self::Sync(command) => command.execute_with_stderr(context, stderr).await, + Self::Codex(command) => command.execute_with_stderr(context, stderr).await, } } } diff --git a/cli/src/services/hooks/codex/mod.rs b/cli/src/services/hooks/codex/mod.rs index 3f9d5b9a3..71f953d7a 100644 --- a/cli/src/services/hooks/codex/mod.rs +++ b/cli/src/services/hooks/codex/mod.rs @@ -5,6 +5,7 @@ use serde::{Deserialize, Deserializer}; use serde_json::Value; use super::read_hook_stdin; +use crate::services::managed_telemetry::trace_export; mod apply_patch; pub(crate) mod bash_policy; @@ -91,10 +92,12 @@ pub(super) async fn run_codex_subcommand, ) -> String { + trace_export::record_codex_hook_command(trace_export::CodexHookCommand::Codex); let stdin_payload = match read_hook_stdin() { Ok(payload) => payload, Err(error) => return log_codex_fail_open(&error, logger), }; + trace_export::record_codex_hook_payload(&stdin_payload); match run_codex_subcommand_from_payload(repository_root, &stdin_payload, logger).await { Ok(output) => output, diff --git a/cli/src/services/hooks/codex_mutation_scope/lifecycle.rs b/cli/src/services/hooks/codex_mutation_scope/lifecycle.rs index 49508938a..a35681e6d 100644 --- a/cli/src/services/hooks/codex_mutation_scope/lifecycle.rs +++ b/cli/src/services/hooks/codex_mutation_scope/lifecycle.rs @@ -9,6 +9,9 @@ use crate::services::hooks::codex::bash_policy::{ use crate::services::hooks::{ normalize_codex_model_id, prefixed_diff_trace_session_id, CODEX_TOOL_NAME, }; +use crate::services::managed_telemetry::trace_export::{ + self, in_child_span, CodexHookCommand, ManagedChildSpan, +}; use crate::services::mutation_trace::runtime::resolve_git_dir; use super::events::CODEX_TRACKED_TOOL_BASH; @@ -63,7 +66,9 @@ pub(crate) async fn run_codex_mutation_scope_subcommand< >( logger: Option<&L>, ) -> Result { + trace_export::record_codex_hook_command(CodexHookCommand::CodexMutationScope); let stdin_payload = hooks::read_hook_stdin()?; + trace_export::record_codex_hook_payload(&stdin_payload); run_codex_mutation_scope_from_payload(&stdin_payload, logger).await } @@ -102,7 +107,21 @@ pub(super) async fn run_codex_mutation_scope_from_payload_with_seams< evaluate_bash_policy: &impl Fn(&Path, &str) -> Result, ) -> Result { let event = parse_codex_hook_event(stdin_payload)?; - dispatch_codex_hook_event(event, logger, resolve_git_dir, seam, evaluate_bash_policy).await + let traced_seam = async |repository_root: &Path, payload: &str, logger: Option<&L>| { + in_child_span( + ManagedChildSpan::MutationScope, + seam(repository_root, payload, logger), + ) + .await + }; + dispatch_codex_hook_event( + event, + logger, + resolve_git_dir, + &traced_seam, + evaluate_bash_policy, + ) + .await } pub(super) async fn dispatch_codex_hook_event( diff --git a/cli/src/services/hooks/codex_mutation_scope/mod.rs b/cli/src/services/hooks/codex_mutation_scope/mod.rs index e29e38078..eecfce336 100644 --- a/cli/src/services/hooks/codex_mutation_scope/mod.rs +++ b/cli/src/services/hooks/codex_mutation_scope/mod.rs @@ -50,3 +50,6 @@ use payload::{ abandon_payload, flush_payload, pre_tool_use_deny_json, scope_boundary_payload, scope_start_payload, }; + +#[cfg(test)] +mod telemetry_tests; diff --git a/cli/src/services/hooks/codex_mutation_scope/telemetry_tests.rs b/cli/src/services/hooks/codex_mutation_scope/telemetry_tests.rs new file mode 100644 index 000000000..e56dfd1d3 --- /dev/null +++ b/cli/src/services/hooks/codex_mutation_scope/telemetry_tests.rs @@ -0,0 +1,313 @@ +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use anyhow::Result; +use serde_json::Value; +use tokio::net::TcpListener; + +use crate::services::error::CliError; +use crate::services::managed_telemetry::trace_export::tests::{ + capture_requests_until, loopback_telemetry_of_kind, trace_spans, DecodedSpan, +}; +use crate::services::managed_telemetry::trace_export::{ + record_codex_hook_command, record_codex_hook_payload, CodexHookCommand, ManagedSpanKind, + ManagedTraceTelemetry, SHUTDOWN_TIMEOUT, +}; +use crate::services::observability::traits::{NoopLogger, NoopTelemetry, Telemetry}; + +use super::{run_codex_mutation_scope_from_payload_with_seams, CodexBashPolicyDecision}; + +const PRE_APPLY_PATCH: &str = + include_str!("fixtures/probe01-apply-patch-and-shell-success.apply_patch.pre_tool_use.json"); +const POST_APPLY_PATCH: &str = + include_str!("fixtures/probe01-apply-patch-and-shell-success.apply_patch.post_tool_use.json"); + +struct Workspace { + _dir: tempfile::TempDir, + project: PathBuf, + git_dir: PathBuf, +} + +fn workspace() -> Workspace { + let dir = tempfile::tempdir().expect("temp dir"); + let project = dir.path().join("project"); + let git_dir = dir.path().join("git"); + std::fs::create_dir_all(&project).expect("project dir"); + std::fs::create_dir_all(&git_dir).expect("git dir"); + Workspace { + _dir: dir, + project, + git_dir, + } +} + +fn payload(fixture: &str, project: &Path, overrides: &[(&str, &str)]) -> String { + let mut value: Value = serde_json::from_str(fixture).expect("fixture JSON"); + value["cwd"] = Value::String(project.to_string_lossy().into_owned()); + for (key, field) in overrides { + value[*key] = Value::String((*field).to_string()); + } + value.to_string() +} + +async fn run_hook( + stdin: &str, + git_dir: &Path, + seam_payloads: &Mutex>, +) -> Result { + record_codex_hook_command(CodexHookCommand::CodexMutationScope); + record_codex_hook_payload(stdin); + let resolve_git_dir = async |_: &str| -> Result { Ok(git_dir.to_path_buf()) }; + let seam = async |_: &Path, payload: &str, _: Option<&NoopLogger>| -> Result { + seam_payloads.lock().unwrap().push(payload.to_string()); + Ok(String::new()) + }; + let bash_policy = |_: &Path, _: &str| -> Result { + panic!("apply_patch fixtures never evaluate bash policy") + }; + run_codex_mutation_scope_from_payload_with_seams( + stdin, + None::<&NoopLogger>, + &resolve_git_dir, + &seam, + &bash_policy, + ) + .await + .map_err(CliError::runtime) +} + +async fn run_with( + telemetry: &T, + stdin: &str, + git_dir: &Path, + seam_payloads: &Mutex>, +) -> String { + telemetry + .with_default_subscriber(&mut || run_hook(stdin, git_dir, seam_payloads)) + .await + .expect("hook result") +} + +async fn exported_spans_for(stdin: &str, workspace: &Workspace) -> Vec { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let address = listener.local_addr().expect("addr"); + let (stop, stopped) = tokio::sync::oneshot::channel(); + let receiver = tokio::spawn(capture_requests_until(listener, stopped)); + let telemetry = + loopback_telemetry_of_kind(address, "bao-token-value", ManagedSpanKind::CodexHook); + let seam_payloads = Mutex::new(Vec::new()); + run_with(&telemetry, stdin, &workspace.git_dir, &seam_payloads).await; + telemetry.shutdown().await; + stop.send(()).expect("stop receiver"); + trace_spans(&receiver.await.expect("receiver join")) +} + +fn attribute<'a>(span: &'a DecodedSpan, key: &str) -> Option<&'a str> { + span.attributes + .iter() + .find(|(name, _)| name == key) + .map(|(_, value)| value.as_str()) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn codex_mutation_scope_apply_patch_exports_one_hook_root_with_mutation_scope_children() { + let workspace = workspace(); + for (fixture, event) in [ + (PRE_APPLY_PATCH, "PreToolUse"), + (POST_APPLY_PATCH, "PostToolUse"), + ] { + let stdin = payload(fixture, &workspace.project, &[]); + let spans = exported_spans_for(&stdin, &workspace).await; + + let hooks = spans + .iter() + .filter(|span| span.name == "sce.hook") + .collect::>(); + assert_eq!(hooks.len(), 1, "{event}: {spans:?}"); + let hook = hooks[0]; + assert!( + hook.parent_span_id.is_empty(), + "{event}: hook must be a root" + ); + for (key, value) in [ + ("sce.agent", "codex"), + ("sce.hook.command", "codex-mutation-scope"), + ("sce.hook.event", event), + ("sce.hook.tool", "apply_patch"), + ( + "sce.codex.session_id", + "01a07c1e-e08e-7172-8032-cb9d62af21d9", + ), + ("sce.codex.turn_id", "01a07c1e-e0cc-75f1-a566-e790c06cb033"), + ( + "sce.codex.tool_use_id", + "exec-1af8025d-ad98-415e-ab60-9eff31a15b73", + ), + ("sce.codex.model", "gpt-5.6-sol"), + ("sce.outcome", "success"), + ] { + assert_eq!(attribute(hook, key), Some(value), "{event}: {key}"); + } + assert_eq!(attribute(hook, "sce.codex.agent_id"), None, "{event}"); + + let children = spans + .iter() + .filter(|span| span.name != "sce.hook") + .collect::>(); + assert!( + !children.is_empty(), + "{event}: expected a mutation-scope child" + ); + for child in children { + assert_eq!(child.name, "sce.mutation_scope", "{event}"); + assert_eq!(child.trace_id, hook.trace_id, "{event}"); + assert_eq!(child.parent_span_id, hook.span_id, "{event}"); + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn codex_mutation_scope_untracked_tool_exports_only_the_hook_span() { + let workspace = workspace(); + let stdin = payload( + POST_APPLY_PATCH, + &workspace.project, + &[ + ("tool_name", "web_search"), + ("agent_id", "019a-child"), + ("agent_type", "explorer"), + ], + ); + let spans = exported_spans_for(&stdin, &workspace).await; + + assert_eq!(spans.len(), 1, "{spans:?}"); + assert_eq!(spans[0].name, "sce.hook"); + assert_eq!(attribute(&spans[0], "sce.hook.tool"), Some("web_search")); + assert_eq!( + attribute(&spans[0], "sce.codex.agent_id"), + Some("019a-child") + ); + assert_eq!( + attribute(&spans[0], "sce.codex.agent_type"), + Some("explorer") + ); +} + +struct Observed { + outputs: Vec, + seam_payloads: Vec, + state_files: Vec<(String, Vec)>, +} + +fn state_files(git_dir: &Path) -> Vec<(String, Vec)> { + let mut files = Vec::new(); + let mut pending = vec![git_dir.to_path_buf()]; + while let Some(dir) = pending.pop() { + for entry in std::fs::read_dir(&dir).expect("read state dir") { + let path = entry.expect("state entry").path(); + if path.is_dir() { + pending.push(path); + } else { + let relative = path + .strip_prefix(git_dir) + .unwrap() + .to_string_lossy() + .into_owned(); + files.push((relative, std::fs::read(&path).expect("read state file"))); + } + } + } + files.sort(); + files +} + +async fn observe(telemetry: &T) -> Observed { + let workspace = workspace(); + let seam_payloads = Mutex::new(Vec::new()); + let mut outputs = Vec::new(); + for fixture in [PRE_APPLY_PATCH, POST_APPLY_PATCH] { + let stdin = payload(fixture, &workspace.project, &[]); + outputs.push(run_with(telemetry, &stdin, &workspace.git_dir, &seam_payloads).await); + } + Observed { + outputs, + seam_payloads: seam_payloads.into_inner().unwrap(), + state_files: state_files(&workspace.git_dir), + } +} + +fn normalize_paths(observed: &Observed) -> Vec { + observed + .seam_payloads + .iter() + .map(|payload| { + let mut value: Value = + serde_json::from_str(payload).unwrap_or(Value::String(payload.clone())); + if let Some(object) = value.as_object_mut() { + object.remove("cwd"); + } + value.to_string() + }) + .collect() +} + +async fn assert_failing_exporter_matches_noop(failing: ManagedTraceTelemetry) { + let baseline = observe(&NoopTelemetry).await; + let started = Instant::now(); + let observed = observe(&failing).await; + assert!( + started.elapsed() < Duration::from_secs(2), + "hooks waited on export" + ); + let shutdown_started = Instant::now(); + failing.shutdown().await; + assert!(shutdown_started.elapsed() < SHUTDOWN_TIMEOUT + Duration::from_millis(500)); + + assert_eq!(observed.outputs, baseline.outputs); + assert_eq!(normalize_paths(&observed), normalize_paths(&baseline)); + assert_eq!( + observed + .state_files + .iter() + .map(|(path, _)| path) + .collect::>(), + baseline + .state_files + .iter() + .map(|(path, _)| path) + .collect::>() + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn codex_mutation_scope_refused_receiver_matches_telemetry_disabled_run() { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let address = listener.local_addr().expect("addr"); + drop(listener); + assert_failing_exporter_matches_noop(loopback_telemetry_of_kind( + address, + "bao-token-value", + ManagedSpanKind::CodexHook, + )) + .await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn codex_mutation_scope_stalled_receiver_matches_telemetry_disabled_run() { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let address = listener.local_addr().expect("addr"); + let holder = tokio::spawn(async move { + let mut held = Vec::new(); + while let Ok((stream, _)) = listener.accept().await { + held.push(stream); + } + }); + assert_failing_exporter_matches_noop(loopback_telemetry_of_kind( + address, + "bao-token-value", + ManagedSpanKind::CodexHook, + )) + .await; + holder.abort(); +} diff --git a/cli/src/services/managed_telemetry/trace_export.rs b/cli/src/services/managed_telemetry/trace_export.rs index ba8a30de0..5112fb877 100644 --- a/cli/src/services/managed_telemetry/trace_export.rs +++ b/cli/src/services/managed_telemetry/trace_export.rs @@ -43,6 +43,7 @@ const HOOK_EXPORTED_SPAN_NAMES: [&str; 4] = [ ]; pub const COMMAND_NAME_FIELD: &str = "sce.command.name"; const AGENT_CLAUDE: &str = "claude"; +const AGENT_CODEX: &str = "codex"; const HOOK_EVENT_FIELD: &str = "sce.hook.event"; const HOOK_TOOL_FIELD: &str = "sce.hook.tool"; const HOOK_COMMAND_FIELD: &str = "sce.hook.command"; @@ -54,6 +55,22 @@ const CLAUDE_PAYLOAD_FIELDS: [(&str, &str); 4] = [ ("session_id", CLAUDE_SESSION_ID_FIELD), ("tool_use_id", CLAUDE_TOOL_USE_ID_FIELD), ]; +const CODEX_SESSION_ID_FIELD: &str = "sce.codex.session_id"; +const CODEX_TURN_ID_FIELD: &str = "sce.codex.turn_id"; +const CODEX_TOOL_USE_ID_FIELD: &str = "sce.codex.tool_use_id"; +const CODEX_MODEL_FIELD: &str = "sce.codex.model"; +const CODEX_AGENT_ID_FIELD: &str = "sce.codex.agent_id"; +const CODEX_AGENT_TYPE_FIELD: &str = "sce.codex.agent_type"; +const CODEX_PAYLOAD_FIELDS: [(&str, &str); 8] = [ + ("hook_event_name", HOOK_EVENT_FIELD), + ("tool_name", HOOK_TOOL_FIELD), + ("session_id", CODEX_SESSION_ID_FIELD), + ("turn_id", CODEX_TURN_ID_FIELD), + ("tool_use_id", CODEX_TOOL_USE_ID_FIELD), + ("model", CODEX_MODEL_FIELD), + ("agent_id", CODEX_AGENT_ID_FIELD), + ("agent_type", CODEX_AGENT_TYPE_FIELD), +]; const TRACEPARENT_ENV: &str = "TRACEPARENT"; const TRACESTATE_ENV: &str = "TRACESTATE"; const TRACEPARENT_HEADER: &str = "traceparent"; @@ -115,6 +132,7 @@ fn is_hook_span(metadata: &tracing::Metadata<'_>) -> bool { pub enum ManagedSpanKind { Command, ClaudeHook, + CodexHook, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -138,6 +156,21 @@ impl ClaudeHookCommand { } } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum CodexHookCommand { + Codex, + CodexMutationScope, +} + +impl CodexHookCommand { + pub const fn as_str(self) -> &'static str { + match self { + Self::Codex => "codex", + Self::CodexMutationScope => "codex-mutation-scope", + } + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ManagedChildSpan { MutationScope, @@ -166,12 +199,11 @@ impl ManagedTraceTelemetry { .timeout(REQUEST_TIMEOUT) .build()?; let mut telemetry = Self::with_client(bearer, endpoints, runtime, client, span_kind)?; - if span_kind == ManagedSpanKind::ClaudeHook { - telemetry.parent_context = extract_parent_context( - std::env::var(TRACEPARENT_ENV).ok(), - std::env::var(TRACESTATE_ENV).ok(), - ); - } + telemetry.parent_context = upstream_parent_context( + span_kind, + std::env::var(TRACEPARENT_ENV).ok(), + std::env::var(TRACESTATE_ENV).ok(), + ); Ok(telemetry) } @@ -242,7 +274,7 @@ impl ManagedTraceTelemetry { .build(); let span_filter: fn(&tracing::Metadata<'_>) -> bool = match span_kind { ManagedSpanKind::Command => is_command_span, - ManagedSpanKind::ClaudeHook => is_hook_span, + ManagedSpanKind::ClaudeHook | ManagedSpanKind::CodexHook => is_hook_span, }; let span_layer = tracing_opentelemetry::layer() .with_tracer(provider.tracer(TRACER_NAME)) @@ -310,6 +342,22 @@ impl ManagedTraceTelemetry { sce.outcome = field::Empty, sce.error.class = field::Empty, ), + ManagedSpanKind::CodexHook => tracing::info_span!( + target: COMMAND_SPAN_TARGET, + HOOK_SPAN_NAME, + sce.agent = AGENT_CODEX, + sce.hook.command = field::Empty, + sce.hook.event = field::Empty, + sce.hook.tool = field::Empty, + sce.codex.session_id = field::Empty, + sce.codex.turn_id = field::Empty, + sce.codex.tool_use_id = field::Empty, + sce.codex.model = field::Empty, + sce.codex.agent_id = field::Empty, + sce.codex.agent_type = field::Empty, + sce.outcome = field::Empty, + sce.error.class = field::Empty, + ), }) } } @@ -339,6 +387,19 @@ impl Telemetry for ManagedTraceTelemetry { } } +/// Codex command hooks inherit `TRACEPARENT` from the process that launched Codex, never the +/// current Codex span, so only Claude hook spans adopt an upstream parent. +fn upstream_parent_context( + span_kind: ManagedSpanKind, + traceparent: Option, + tracestate: Option, +) -> Option { + match span_kind { + ManagedSpanKind::ClaudeHook => extract_parent_context(traceparent, tracestate), + ManagedSpanKind::Command | ManagedSpanKind::CodexHook => None, + } +} + fn extract_parent_context( traceparent: Option, tracestate: Option, @@ -396,6 +457,18 @@ pub fn record_claude_hook_command(command: ClaudeHookCommand) { } pub fn record_claude_hook_payload(stdin_payload: &str) { + record_hook_payload(stdin_payload, &CLAUDE_PAYLOAD_FIELDS); +} + +pub fn record_codex_hook_command(command: CodexHookCommand) { + Span::current().record(HOOK_COMMAND_FIELD, command.as_str()); +} + +pub fn record_codex_hook_payload(stdin_payload: &str) { + record_hook_payload(stdin_payload, &CODEX_PAYLOAD_FIELDS); +} + +fn record_hook_payload(stdin_payload: &str, fields: &[(&str, &str)]) { let span = Span::current(); if span.is_disabled() { return; @@ -403,7 +476,7 @@ pub fn record_claude_hook_payload(stdin_payload: &str) { let Ok(serde_json::Value::Object(payload)) = serde_json::from_str(stdin_payload) else { return; }; - for (payload_key, span_field) in CLAUDE_PAYLOAD_FIELDS { + for &(payload_key, span_field) in fields { if let Some(value) = payload .get(payload_key) .and_then(serde_json::Value::as_str) @@ -634,7 +707,7 @@ pub(crate) mod tests { loopback_telemetry_of_kind(address, token, ManagedSpanKind::Command) } - fn loopback_telemetry_of_kind( + pub(crate) fn loopback_telemetry_of_kind( address: std::net::SocketAddr, token: &str, span_kind: ManagedSpanKind, @@ -1052,4 +1125,130 @@ pub(crate) mod tests { }); crate::app::finish_runtime(runtime); } + + const VALID_TRACEPARENT: &str = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"; + + #[test] + fn upstream_parent_context_is_adopted_only_for_claude_hooks() { + let parent = |span_kind, traceparent: &str| { + upstream_parent_context( + span_kind, + Some(traceparent.to_string()), + Some("vendor=value".to_string()), + ) + }; + assert!(parent(ManagedSpanKind::ClaudeHook, VALID_TRACEPARENT).is_some()); + for traceparent in [ + VALID_TRACEPARENT, + "00-00000000000000000000000000000000-0000000000000000-01", + "garbage", + ] { + assert!(parent(ManagedSpanKind::CodexHook, traceparent).is_none()); + assert!(parent(ManagedSpanKind::Command, traceparent).is_none()); + } + assert!(upstream_parent_context(ManagedSpanKind::CodexHook, None, None).is_none()); + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn codex_hook_span_exports_codex_attributes_without_claude_fields() { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let address = listener.local_addr().expect("addr"); + let (stop, stopped) = tokio::sync::oneshot::channel(); + let receiver = tokio::spawn(capture_requests_until(listener, stopped)); + let telemetry = + loopback_telemetry_of_kind(address, "bao-token-value", ManagedSpanKind::CodexHook); + let payload = r#"{"hook_event_name":"PostToolUse","tool_name":"apply_patch","session_id":"019a-s","turn_id":"019a-t","tool_use_id":"call_1","model":"gpt-5","agent_id":"019a-child","agent_type":"worker","cwd":"/home/u/secret-repo","tool_input":{"command":"*** Begin Patch"},"prompt":"private prompt","transcript_path":"/home/u/.codex/sessions/x.jsonl"}"#; + + let result = telemetry + .with_default_subscriber(&mut || async { + record_codex_hook_command(CodexHookCommand::Codex); + record_codex_hook_payload(payload); + Ok(String::new()) + }) + .await; + assert_eq!(result.expect("hook result"), ""); + telemetry.shutdown().await; + stop.send(()).expect("stop receiver"); + + let requests = receiver.await.expect("receiver join"); + let spans = trace_spans(&requests); + assert_eq!(spans.len(), 1, "{spans:?}"); + assert_eq!(spans[0].name, "sce.hook"); + assert!(spans[0].parent_span_id.is_empty()); + assert_eq!( + spans[0].sce_attributes(), + [ + ("sce.agent", "codex"), + ("sce.codex.agent_id", "019a-child"), + ("sce.codex.agent_type", "worker"), + ("sce.codex.model", "gpt-5"), + ("sce.codex.session_id", "019a-s"), + ("sce.codex.tool_use_id", "call_1"), + ("sce.codex.turn_id", "019a-t"), + ("sce.hook.command", "codex"), + ("sce.hook.event", "PostToolUse"), + ("sce.hook.tool", "apply_patch"), + ("sce.outcome", "success"), + ] + .map(|(key, value)| (key.to_string(), value.to_string())) + ); + assert!(spans[0] + .resource_attributes + .contains(&("service.name".to_string(), "sce".to_string()))); + for request in requests.iter().filter(|request| { + request + .head + .to_ascii_lowercase() + .starts_with("post /v1/traces ") + }) { + let body = String::from_utf8_lossy(&request.body); + for leaked in [ + "secret-repo", + "private prompt", + "Begin Patch", + "sessions/x.jsonl", + ] { + assert!(!body.contains(leaked), "leaked {leaked}"); + } + } + } + + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] + async fn claude_hook_span_shape_is_unchanged_by_codex_admission() { + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let address = listener.local_addr().expect("addr"); + let (stop, stopped) = tokio::sync::oneshot::channel(); + let receiver = tokio::spawn(capture_requests_until(listener, stopped)); + let telemetry = + loopback_telemetry_of_kind(address, "bao-token-value", ManagedSpanKind::ClaudeHook); + let payload = r#"{"hook_event_name":"PreToolUse","tool_name":"Write","session_id":"sess-1","tool_use_id":"toolu_1","turn_id":"ignored","model":"ignored"}"#; + + telemetry + .with_default_subscriber(&mut || async { + record_claude_hook_command(ClaudeHookCommand::ClaudeMutationScope); + record_claude_hook_payload(payload); + Ok(String::new()) + }) + .await + .expect("hook result"); + telemetry.shutdown().await; + stop.send(()).expect("stop receiver"); + + let spans = trace_spans(&receiver.await.expect("receiver join")); + assert_eq!(spans.len(), 1, "{spans:?}"); + assert_eq!(spans[0].name, "sce.hook"); + assert_eq!( + spans[0].sce_attributes(), + [ + ("sce.agent", "claude"), + ("sce.claude.session_id", "sess-1"), + ("sce.claude.tool_use_id", "toolu_1"), + ("sce.hook.command", "claude-mutation-scope"), + ("sce.hook.event", "PreToolUse"), + ("sce.hook.tool", "Write"), + ("sce.outcome", "success"), + ] + .map(|(key, value)| (key.to_string(), value.to_string())) + ); + } } diff --git a/cli/src/services/mod.rs b/cli/src/services/mod.rs index 2612c646b..74178c3dd 100644 --- a/cli/src/services/mod.rs +++ b/cli/src/services/mod.rs @@ -12,6 +12,7 @@ pub mod capabilities; pub(crate) mod codex_hook_config; pub(crate) mod codex_hook_policy; pub(crate) mod codex_hook_trust; +pub mod codex_telemetry; pub mod command_registry; pub mod completion; pub mod config; diff --git a/cli/src/services/parse/command_runtime.rs b/cli/src/services/parse/command_runtime.rs index 929ab295c..6f9db1bdc 100644 --- a/cli/src/services/parse/command_runtime.rs +++ b/cli/src/services/parse/command_runtime.rs @@ -321,6 +321,9 @@ fn convert_clap_command(command: cli_schema::Commands) -> Result Ok(RuntimeCommand::Codex( + services::codex_telemetry::command::CodexCommand { args }, + )), } } @@ -391,9 +394,12 @@ fn convert_auth_subcommand( cli_schema::AuthSubcommand::Whoami { format } => { services::auth_command::AuthSubcommand::Whoami { format } } - cli_schema::AuthSubcommand::TelemetryHeaders => { + cli_schema::AuthSubcommand::TelemetryHeaders { repo: None } => { services::auth_command::AuthSubcommand::TelemetryHeaders } + cli_schema::AuthSubcommand::TelemetryHeaders { + repo: Some(repository), + } => services::auth_command::AuthSubcommand::TelemetryHeadersForRepository { repository }, }; Ok(RuntimeCommand::Auth( @@ -856,6 +862,25 @@ mod tests { assert!(!services::help::help_text().contains("telemetry-headers")); } + #[test] + fn telemetry_headers_repo_flag_parses_and_is_hidden_from_help() { + let command = parse(&["sce", "auth", "telemetry-headers", "--repo", "/work/repo a"]); + + let RuntimeCommand::Auth(command) = command else { + panic!("expected auth command"); + }; + assert_eq!( + command.request.subcommand, + services::auth_command::AuthSubcommand::TelemetryHeadersForRepository { + repository: std::path::PathBuf::from("/work/repo a"), + } + ); + + let help = cli_schema::render_help_for_path(&["auth", "telemetry-headers"]) + .expect("hidden command help renders"); + assert!(!help.contains("--repo")); + } + #[test] fn removed_auth_renew_command_routes_to_auth_help() { assert_eq!( diff --git a/context/architecture.md b/context/architecture.md index 1bdd870d6..4377f14ab 100644 --- a/context/architecture.md +++ b/context/architecture.md @@ -53,7 +53,8 @@ The repository includes a new placeholder Rust binary crate at `cli/`. - Command parse-time conversion and run-time handling are separated by an internal static `RuntimeCommand` seam. `cli/src/services/command_registry.rs` defines the `RuntimeCommand` enum with variants for help/help-text, version, completion, auth, config, setup, doctor, hooks, policy, and sync, with no additional command registry or default-command catalog. `parse_command_phase` in `cli/src/app.rs` delegates clap-output conversion to `cli/src/services/parse/command_runtime.rs`, which owns clap error classification, help rendering bridges, longest-valid-parent traversal for unknown command paths, and parsed-request-to-enum conversion while returning concrete enum values. Service-owned `command.rs` modules define command payload structs and generic execution methods with narrow context requirements: context-free commands accept any context, hooks requires logger access, setup/doctor require repo-root scoping, and central dispatch requires the union of logger plus repo-root-scoping capabilities. `services::app_support::execute_command_phase` emits lifecycle logs around `RuntimeCommand::execute_with_stderr(...)`; the enum performs the only central dispatch match and delegates business behavior to the service-owned command structs, with sync receiving the app-owned stderr writer for format-gated progress. - Startup observability bootstrapping in `cli/src/app.rs` still tolerates invalid default-discovered config files by continuing with degraded defaults plus `sce.config.invalid_config` warn-level logs, but the warning/logging work is now isolated behind the startup-context and runtime-initialization phases rather than one inline startup function. - `cli/src/services/observability.rs` provides deterministic runtime observability controls and rendering for app lifecycle logs, including shared config-resolved threshold/format, explicit config-file/default `log_to_file`, and `log_dir` inputs with precedence `env > config file > defaults` for non-flag observability keys, stable event identifiers, severity filtering, the forced-emission warning path used for invalid discovered config startup diagnostics, error-specific stderr suppression when file logging is enabled while non-error records and file-write diagnostics remain on stderr, redaction-safe emission through the shared security helper, and log-directory writes with bounded retention. Config resolution also carries a positive config-file/default-only `log_file_retention_limit` (`10` by default) into startup observability config and `sce config show`; the concrete logger stores that resolved value and threads it through primary and v2 cleanup. When `log_dir` resolves from `SCE_LOG_DIR`, config, or the `/sce/logs` default, each enabled or forced log operation selects `/sce-.log` or `/sce--.log` using the machine-local date and optional logger session context, with deterministic percent-encoding for unsafe session filename bytes; after successfully writing a newly created selected file, retention keeps the configured number of newest direct regular `*.log` files by mtime plus path/name tie-break and fails open on cleanup errors. Its `observability::traits` submodule exposes the current `Logger` API with `Option<&str>` session context plus the generic async, deliberately non-object-safe `Telemetry` capability and `NoopLogger`; the concrete observability `Logger` and `NoopTelemetry` implement those capability traits; `NoopTelemetry` installs no tracing subscriber. `services::app_support::render_run_outcome` consumes the logger through that trait boundary when logging classified errors and stdout-write failures. -- `cli/src/services/managed_telemetry.rs` (+ `managed_telemetry/trace_export.rs`, `managed_telemetry/log_export.rs`) owns hardcoded managed OTLP defaults, credential-backed runtime telemetry selection from the encrypted auth DB, and bounded fail-open OTLP/HTTP protobuf export of `sce.command` spans (or one `sce.hook` span, with `sce.mutation_scope`/`sce.git_snapshot`/`sce.persistence` operation children opened through `trace_export::in_child_span` at the Claude adapter seam and in `mutation_trace::runtime`, for Claude-invoked hooks admitted by `managed_span_kind` in `cli/src/app.rs`) and allowlisted `Logger` events to the pinned canonical collector (metrics endpoint reserved, not exported); see `context/sce/cli-observability-contract.md`. +- `cli/src/services/managed_telemetry.rs` (+ `managed_telemetry/trace_export.rs`, `managed_telemetry/log_export.rs`) owns hardcoded managed OTLP defaults, credential-backed runtime telemetry selection from the encrypted auth DB, and bounded fail-open OTLP/HTTP protobuf export of `sce.command` spans (or one `sce.hook` span, with `sce.mutation_scope`/`sce.git_snapshot`/`sce.persistence` operation children opened through `trace_export::in_child_span` at the Claude and Codex adapter seams and in `mutation_trace::runtime`, for Claude-invoked hooks and the two Codex hook subcommands admitted by `managed_span_kind` in `cli/src/app.rs`; Codex hook spans are always roots) and allowlisted `Logger` events to the pinned canonical collector (metrics endpoint reserved, not exported); see `context/sce/cli-observability-contract.md`. +- `cli/src/services/codex_telemetry/` owns the public `sce codex` launcher: invocation-mode classification, Codex OTEL conflict detection, and process-local `-c` overrides that run the hidden header helper with `--repo` and pin Codex traces and metrics to the managed endpoint before it `exec`s `codex`; it never writes Codex config or initializes managed exporter telemetry. See `context/sce/codex-native-telemetry-launcher.md`. - `cli/src/services/observability.rs` no longer owns duplicate log enums or parsing helpers; it consumes the canonical primitive seam from `cli/src/services/config/mod.rs` and stays focused on concrete `Logger` behavior plus the `NoopTelemetry`-backed telemetry capability boundary. - `cli/src/cli_schema.rs` is now the canonical owner for top-level command metadata for the real clap-backed command set (`auth`, `config`, `setup`, `doctor`, `hooks`, `policy`, `sync`, `version`, `completion`), including the slim top-level help purpose text and per-command visibility on `sce`, `sce help`, and `sce --help`; `cli/src/command_surface.rs` remains the custom top-level help renderer and known-command classifier, adding the synthetic `help` row plus the ASCII banner while consuming that shared metadata instead of maintaining a parallel command catalog. - `cli/src/services/default_paths.rs` is the canonical production path catalog for the CLI: it resolves config/state/cache roots with platform-aware XDG or `dirs` fallbacks through an internal `roots` seam, exposes named default paths for current persisted artifacts and database/log files (global config, auth tokens, auth DB, local DB, default observability log directory, and the sole Agent Trace DB path helper `agent_trace_db_path_for_repository` under `repos//agent-trace.db`; the former global-sentinel and per-checkout Agent Trace path helpers were removed by the `retire-legacy-agent-trace-db` plan), and owns canonical repo-relative, embedded-asset, install, hook, and context-path accessors so non-test production path definitions have one shared owner. Compile-time generated payload paths are owned by `build.rs` under `OUT_DIR`, not by the default-path catalog. Current production consumers such as config discovery, observability config resolution, doctor reporting, setup/install flows, database adapters, checkout identity, Agent Trace storage resolution, and local hook runtime path resolution consume this shared catalog rather than defining owned path literals in their own modules. @@ -85,7 +86,7 @@ The repository includes a new placeholder Rust binary crate at `cli/`. - `sce sync [--format text|json]` is implemented: `cli/src/services/sync/sync.rs` first rejects an effective `auth.mode: disabled` (`auth.disabled_by_config`, see `context/cli/access-policy.md`), then resolves repository-scoped Agent Trace storage, authenticates against the control plane with stored WorkOS credentials, uses the config-resolved `control_plane_base_url` with baked default `https://sce.crocoderlab.dev`, calls the ingestion `/state` endpoint once, then starts the three remote `messages`/`parts`/`agent_traces` stream state machines concurrently (`diff_traces` remains a local-only compatibility report) via `AgentTraceExportReader` and a shared per-stream reconciliation engine. Batches and cursor refreshes remain sequential within each stream, while fixed stream order is retained for final and stream-completion reporting; `cli/src/services/sync/render_sync.rs` renders the converged `AgentTraceSyncReport` as concise per-stream text or `camelCase` JSON without a nested subcommand field (see `context/cli/sync-command.md`). Local DB bootstrap and setup-time repository-scoped Agent Trace DB initialization otherwise still flow through lifecycle providers aggregated by setup, while repository-scoped DB health/repair flows through the doctor surface. The former trace database inspection and nested sync surfaces are unavailable. - `cli/src/services/patch.rs` defines the standalone patch domain model (`ParsedPatch`, `PatchFileChange`, `FileChangeKind`, `PatchHunk`, `TouchedLine`, `TouchedLineKind`) for in-memory parsed unified-diff representation, capturing only touched lines (added/removed) plus minimal per-file/per-hunk metadata while excluding non-hunk headers and unchanged context lines. All types are `serde`-serializable/deserializable with `snake_case` JSON field naming. The module also provides `parse_patch`, a public parser function that converts raw unified-diff text (both `Index:` SVN-style and `diff --git` git-style formats) into `ParsedPatch` structs, with `ParseError` for actionable malformed-input diagnostics. Storage-agnostic JSON load helper (`load_patch_from_json` for string input) reconstruct `ParsedPatch` from serialized JSON content with `PatchLoadError` for actionable deserialization diagnostics. The former `combine_patches`/`intersect_patches` set operations and the suffix-equivalence path helper were removed; attribution-grade file identity lives in `cli/src/services/agent_trace/repository_path.rs`, and `parse_patch` is consumed by the active post-commit hook runtime. - `cli/src/services/structured_patch.rs` defines the synchronous structured editor-hook derivation seam. It derives Claude `PostToolUse` `Write` structured-update hunks, `Write` `tool_input.content` create fallback, and `Edit` structured-patch payloads into canonical `ParsedPatch` values plus Claude session/tool metadata, returning deterministic skip reasons for unsupported events/tools/payload shapes. The module is pure and side-effect-free. It is wired into `sce hooks diff-trace` for Claude payload classification at intake (T04) and into `RepositoryAgentTraceDb::recent_diff_trace_patches` for post-commit structured payload parsing dispatch at read time (T05). -- `cli/src/services/` contains module boundaries for command_registry, lifecycle, auth_command, config, setup, doctor, hooks, bash_policy, version, completion, help, patch, sync, SCE web URL helpers, shared database infrastructure, local DB adapters, encrypted auth DB adapters, and Agent Trace DB adapters with explicit trait seams for future implementations. The former `cli/src/services/checkout/` checkout-identity module was removed by the `remove-checkout-id` plan (see `context/cli/checkout-identity.md`); there is no per-clone identity, worktrees are identified by Git topology (`resolve_worktree_id`), active setup/hooks use `agent_trace_storage` to initialize/open the repository-scoped DB, and `sce doctor` surfaces credential-safe repository Agent Trace DB metadata. There is no checkout-scoped discovery or former trace inspection surface; any pre-migration `agent-trace-*.db` files on disk are never touched and no longer inspectable via the CLI. `cli/src/services/bash_policy.rs` owns both the CLI-agnostic evaluator logic and the hidden `sce policy bash` command adapter used by OpenCode, Claude, and Pi callers; Codex delegates in-process to the same evaluator for its native `PreToolUse(Bash)` response. `cli/src/services/command_registry.rs` defines the static `RuntimeCommand` enum for command dispatch metadata. Service-owned command modules own the runtime command payload structs for help/help-text, version, completion, auth, config, setup, doctor, hooks, policy, and sync. +- `cli/src/services/` contains module boundaries for command_registry, lifecycle, auth_command, codex_telemetry, config, setup, doctor, hooks, bash_policy, version, completion, help, patch, sync, SCE web URL helpers, shared database infrastructure, local DB adapters, encrypted auth DB adapters, and Agent Trace DB adapters with explicit trait seams for future implementations. The former `cli/src/services/checkout/` checkout-identity module was removed by the `remove-checkout-id` plan (see `context/cli/checkout-identity.md`); there is no per-clone identity, worktrees are identified by Git topology (`resolve_worktree_id`), active setup/hooks use `agent_trace_storage` to initialize/open the repository-scoped DB, and `sce doctor` surfaces credential-safe repository Agent Trace DB metadata. There is no checkout-scoped discovery or former trace inspection surface; any pre-migration `agent-trace-*.db` files on disk are never touched and no longer inspectable via the CLI. `cli/src/services/bash_policy.rs` owns both the CLI-agnostic evaluator logic and the hidden `sce policy bash` command adapter used by OpenCode, Claude, and Pi callers; Codex delegates in-process to the same evaluator for its native `PreToolUse(Bash)` response. `cli/src/services/command_registry.rs` defines the static `RuntimeCommand` enum for command dispatch metadata. Service-owned command modules own the runtime command payload structs for help/help-text, version, completion, auth, config, setup, doctor, hooks, policy, and sync. - `cli/README.md` is the crate-local onboarding and usage source of truth for placeholder behavior, safety limitations, and roadmap mapping back to service contracts. - `flake.nix` applies `rust-overlay` (`oxalica/rust-overlay`) to nixpkgs, pins `rust-bin.stable.1.95.0.default` with `rustfmt` + `clippy`, and reads package/check version from repo-root `.version`. Its `cliGeneratedInput` derivation invokes the shared generated-input producer from a declarative source containing the producer and canonical inputs, then publishes the producer-validated handoff as its store output. Native, release, test, and Clippy Cargo derivations receive that same store path through `SCE_CLI_GENERATED_INPUT_DIR`; their Cargo environments exclude Pkl and assert that it is unavailable. Repository-mode `cli/build.rs` validates the handoff before copying it into `OUT_DIR`; published crates use the validated packaging-only fallback. The build script stages SQL under `OUT_DIR/static/migrations` and writes `OUT_DIR/generated_migrations.rs` with deterministic migration constants sorted by numeric filename prefix. - Crane dependency-only derivations and `cli-fmt` intentionally do not receive `SCE_CLI_GENERATED_INPUT_DIR`, so canonical generation changes invalidate the producer and compiling derivations while preserving host/musl dependency artifacts and formatting. The root flake runs `cli-tests`, `cli-clippy`, and `cli-fmt` through Crane-backed paths and exposes `cli-generated-input` as the focused payload/inventory integrity check. It also exposes directory-scoped JS validation derivations for `npm/` and `config/lib/`, while `pkl-generated` uses a narrow canonical-input source set plus maybe-missing forbidden paths so reintroduced generated repository artifacts fail the check. diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index 538648492..cb372fdf2 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -4,7 +4,7 @@ This file describes how the CLI turns the per-layer `auth.mode` and `telemetry.enabled` config values into one effective access policy (`ResolvedAccessPolicy`). Key syntax and schema validation are in [config precedence contract](config-precedence-contract.md). The precedence model is recorded in [ADR: consent-gated access policy precedence](../decisions/2026-10-20-consent-gated-access-policy-precedence.md); its user-side-only consent rule is superseded by [ADR: repository telemetry.enabled grants consent](../decisions/2026-10-22-repository-telemetry-enabled-grants-consent.md). -Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Managed telemetry startup, `sce doctor`'s managed-telemetry and auto-sync health, the hidden `sce auth telemetry-headers` helper, `sce auth login` / `whoami`, `sce sync`, post-commit auto-sync, and the Claude `SessionStart` login notice enforce the policy (see [Enforcement](#enforcement)). Interactive `sce setup` is the writer for the repository layer's access keys (see [Setup](#setup)). +Status: the resolver computes and exposes the policy, and `sce config show` / `validate` report it (see [Reporting](#reporting)). Managed telemetry startup, `sce doctor`'s managed-telemetry and auto-sync health, the hidden `sce auth telemetry-headers` helper, the `sce codex` launcher, `sce auth login` / `whoami`, `sce sync`, post-commit auto-sync, and the Claude `SessionStart` login notice enforce the policy (see [Enforcement](#enforcement)). Interactive `sce setup` is the writer for the repository layer's access keys (see [Setup](#setup)). ## Terms @@ -27,7 +27,7 @@ Status: the resolver computes and exposes the policy, and `sce config show` / `v `resolve_config_paths` locates the repository layer at `enclosing_repository_root_with(cwd, path_exists)` (`cli/src/services/default_paths.rs`): the nearest ancestor of the working directory, inclusive, that contains a `.git` entry (directory or file). That is the worktree root for ordinary repositories, linked worktrees, and submodules; in a nested repository it is the innermost repository. Outside a Git repository it falls back to the working directory. The walk only probes the filesystem, so no Git subprocess runs on hook paths. `GIT_DIR` / `GIT_WORK_TREE` are not consulted. `repository_id_for` (the headers helper's repository identity) uses the same helper, so policy and repository identity always describe the same root. -Every consumer goes through this one resolver, so running from the repository root or any subdirectory yields the same effective policy: startup and managed telemetry, `sce auth login` / `whoami`, `sce auth telemetry-headers`, `sce sync`, post-commit auto-sync, `sce doctor`, and `sce config show` / `validate`. +Every consumer goes through this one resolver, so running from the repository root or any subdirectory yields the same effective policy: startup and managed telemetry, `sce auth login` / `whoami`, `sce auth telemetry-headers`, `sce codex`, `sce sync`, post-commit auto-sync, `sce doctor`, and `sce config show` / `validate`. ## Explicit config files @@ -131,7 +131,8 @@ Setup then enforces the re-resolved mode with a login step: it never logs in und - **`sce doctor` managed-telemetry health:** doctor resolves the policy for the inspected repository root once. A resolution failure counts as `invalid_config`. The row reports the effective state (`Managed telemetry: enabled for this repository` or `Managed telemetry: disabled (reason: )`) and the deciding layer, and JSON adds `managed_telemetry.policy`. When telemetry is not `Enabled`, the health is `disabled_by_config`. Doctor may then check whether `auth.db` exists (for the opt-in note), but never opens it or touches the credential store. See [telemetry credential: doctor health check](../sce/telemetry-credential.md#doctor-health-check). - **`sce doctor` SCE login row:** under effective `mandatory`, doctor confirms the saved WorkOS session non-interactively with a deadline and without creating or migrating `auth.db`. A current access token counts as logged in. An expired one is refreshed against WorkOS (the only case where doctor makes a network request) and the refreshed tokens are saved. A rejected refresh fails, and its problem summary names the WorkOS reason. WorkOS unreachable keeps the session logged in for 24h after its last confirmation. Login status is independent of telemetry credentials and repository bindings. Unreadable storage, outdated schema, lookup failures, and WorkOS unreachable past the grace report `unavailable` with a warning and a reason instead of claiming logout. A missing login is a blocking `[FAIL] SCE login` that names the deciding config file, with the fix `Run 'sce auth login'.`. Other modes skip the lookup. Local SCE features are never blocked. See [doctor human text: SCE login row](../sce/doctor-human-text-contract.md#sce-login-row). - **Claude session login notice:** the Claude-only `sce-info` hooks module (`config/lib/sce-info/hooks/register.ts`) owns it. On an interactive `session.start`, after Claude's own start step, it first probes `sce --version` (5 s timeout); when that cannot start, it logs the install guidance described in [patterns](../patterns.md) and skips doctor. Otherwise it runs `sce doctor --format json` in the session's working directory. When `sce_login.state` is `not_logged_in` (effective `mandatory` without a saved usable or renewable WorkOS session), it writes the single transcript line `Login required for this repository. Run 'sce auth login'.` through `$.ui.log`. A doctor command that cannot run, unparseable output, any other login state, or a non-interactive session shows nothing. The notice never fails or blocks the session. `sce hooks claude-model-state` emits no notice. OpenCode, Pi, and Codex sessions get no notice. -- **`sce auth telemetry-headers`** (Claude's `otelHeadersHelper`): the helper resolves the policy from its working directory through `resolve_auth_runtime_config`. A missing working directory or a resolution failure counts as not enabled. When telemetry is not `Enabled`, it fails closed with the existing fixed `Telemetry credential is unavailable.` diagnostic and empty stdout. This happens before the destination tripwire, the `auth.db` existence check, repository resolution, and the `auth.db` lookup. See [telemetry credential: hidden header helper](../sce/telemetry-credential.md#hidden-header-helper). +- **`sce auth telemetry-headers`** (Claude's `otelHeadersHelper`, and Codex's `otel.headers_helper` through `sce codex`): the helper resolves the policy from its working directory through `resolve_auth_runtime_config`, or from the hidden `--repo ` repository when supplied. A missing working directory or a resolution failure counts as not enabled. When telemetry is not `Enabled`, it fails closed with the existing fixed `Telemetry credential is unavailable.` diagnostic and empty stdout. This happens before the destination tripwire, the `auth.db` existence check, repository resolution, and the `auth.db` lookup. See [telemetry credential: hidden header helper](../sce/telemetry-credential.md#hidden-header-helper). +- **`sce codex` launcher:** the launcher resolves the policy for the launch repository root (the `-C` directory or the working directory) through `resolve_auth_runtime_config`. A resolution failure counts as not enabled. When telemetry is not `Enabled`, it launches Codex without native telemetry overrides and without a notice. This happens before conflict detection and the credential lookup. See [Codex native telemetry launcher](../sce/codex-native-telemetry-launcher.md). - **`sce setup` Claude telemetry install:** with the Claude target selected, setup resolves the policy for the setup repository root through `resolve_auth_runtime_config`. A resolution failure counts as not enabled. When telemetry is not `Enabled`, it skips the Claude-native install with the fixed line `Claude telemetry: skipped; SCE telemetry is disabled by config.` and leaves user Claude settings unchanged. The exception is a withdrawal in the global user config itself (`telemetry.enabled: false` or `auth.mode: disabled`, read with `read_global_access_preferences`, never the effective reason): setup then removes the SCE-owned Claude settings, in every interactive run and in non-interactive runs with Claude selected. See [telemetry credential: Claude-native telemetry](../sce/telemetry-credential.md#claude-native-telemetry). - **`sce auth login` / `sce auth whoami`:** both resolve the policy from the working directory through `resolve_auth_runtime_config` and check `auth_allowed()` before any `token_storage` call. A resolution failure is a command error. - Under `disabled`, both fail with `UserError::AuthDisabledByConfig` (key `auth.disabled_by_config`, runtime class, exit code 4) before `auth.db` or the credential store is touched. The fixed message names `auth.mode: disabled` and the config file of the deciding layer: the global SCE config, the repository `.sce/config.json`, the `--config` file, or the `SCE_CONFIG_FILE` file (`AuthPolicyConfigFile`). It tells the user to set `auth.mode` to `optional` or `mandatory` there. diff --git a/context/cli/cli-command-surface.md b/context/cli/cli-command-surface.md index ac439b87c..d655adf14 100644 --- a/context/cli/cli-command-surface.md +++ b/context/cli/cli-command-surface.md @@ -11,7 +11,7 @@ Operator onboarding currently comes from `sce --help`, command-local `--help` ou - Top-level command metadata catalog: `cli/src/cli_schema.rs` - Custom top-level help renderer and known-command classifier: `cli/src/command_surface.rs` - Turso adapters: `cli/src/services/auth_db/mod.rs`, `cli/src/services/local_db/mod.rs`, `cli/src/services/agent_trace_db/mod.rs`, and shared infrastructure in `cli/src/services/db/mod.rs` -- Service domains: `cli/src/services/{agent_trace,agent_trace_db,auth,auth_command,auth_db,completion,config,db,default_paths,hooks,local_db,observability,output_format,resilience,security,setup,style,sync,token_storage,version}` plus the split doctor module at `cli/src/services/doctor/{mod,command,inspect,render,fixes,types}.rs`; service-owned `command.rs` files own command payload structs for help/version/completion/auth/config/setup/doctor/hooks/policy/sync, and `cli/src/services/command_registry.rs` owns the static `RuntimeCommand` enum that dispatches them +- Service domains: `cli/src/services/{agent_trace,agent_trace_db,auth,auth_command,auth_db,codex_telemetry,completion,config,db,default_paths,hooks,local_db,observability,output_format,resilience,security,setup,style,sync,token_storage,version}` plus the split doctor module at `cli/src/services/doctor/{mod,command,inspect,render,fixes,types}.rs`; service-owned `command.rs` files own command payload structs for help/version/completion/auth/config/setup/doctor/hooks/policy/sync, and `cli/src/services/command_registry.rs` owns the static `RuntimeCommand` enum that dispatches them - Service lifecycle: `cli/src/services/lifecycle.rs` defines lifecycle-owned health/setup result types, the `ServiceLifecycle` trait with `diagnose`, `fix`, and `setup` methods for concrete providers, and the static `LifecycleProvider` enum used by `doctor`/`setup` to dispatch across `config`, `local_db`, `auth_db`, `agent_trace_db`, and `hooks` without boxed provider aggregation ## Application runtime dispatch @@ -111,6 +111,8 @@ An interactive `setup` run instead resolves the selection through an `inquire` m `setup` now executes end-to-end and prints deterministic completion details including selected target(s) and per-target install count. `setup` with a selected Claude target also merges Claude-native OpenTelemetry settings into user-level Claude `settings.json` (`$CLAUDE_CONFIG_DIR` else `~/.claude`) and prints a fixed telemetry line (configured, configured but not ready for this repository when interactive setup finds no valid credential bound to it, configured with repository authorization not checked for non-interactive and target-flag runs, which never read authentication storage, skipped on conflict/malformed JSON, or skipped because the effective access policy does not enable telemetry, in which case settings are untouched) without failing repository setup; see [telemetry credential](../sce/telemetry-credential.md). The hidden auth helper is intentionally not part of the public command listing. `doctor` now executes end-to-end with explicit diagnosis and repair-intent surfaces: `sce doctor` stays read-only and `sce doctor --fix` selects repair-intent mode. The former Agent Trace database inspection routes are unavailable; doctor owns repository-scoped Agent Trace DB health (checkout-identity diagnostics were removed by the `remove-checkout-id` plan; see `context/cli/checkout-identity.md`). The current `doctor` runtime aggregates `ServiceLifecycle::diagnose` and `ServiceLifecycle::fix` calls across all registered service providers (`config`, `local_db`, `auth_db`, `agent_trace_db`, `hooks`) plus integration checks, covering state-root resolution, global and repo-local `sce/config.json` readability/schema validation, local DB and repository-scoped Agent Trace DB path/health, DB-parent readiness barriers, the repo hook rollout slice when a repository target is detected, and post-commit Agent Trace auto-sync readiness derived from canonical managed-block currency plus resolved configuration. The readiness fact reports enabled/current, explicit disabled, not-ready, and not-applicable states in text and JSON without launching synchronization; Claude's inventory is only `Plugins`, `Commands`, and `Skills`, while OpenCode retains `Agents`. Fix mode delegates to each provider's `fix` implementation, which reuses the canonical setup hook install flow to repair missing/stale/non-executable required hooks and missing hooks directories, and it can bootstrap missing canonical database parent directories when the resolved paths match canonical owned locations. +`sce codex [codex arguments...]` is a public launcher that runs Codex CLI with Codex-native OpenTelemetry export pointed at the managed collector for the launch repository. It forwards every argument to `codex` verbatim (including `--help`), prepends process-local `-c` overrides only for repository-safe invocation modes when telemetry is enabled, authorized, and unconflicted, and otherwise launches Codex unchanged with a one-line stderr reason. See [Codex native telemetry launcher](../sce/codex-native-telemetry-launcher.md). The hidden `sce auth telemetry-headers` helper and its hidden `--repo` flag stay absent from public help. + `sce sync [--format text|json]` is the implemented user-invocable synchronization command: it synchronizes the current repository's Agent Trace DB with the control-plane ingestion API; local DB and Agent Trace DB bootstrap continue to happen through `setup`, and DB health/repair continues to happen through `doctor`. Under `auth.mode: disabled`, `sce sync` fails with `auth.disabled_by_config` before storage or credential access (see [effective access policy](access-policy.md#enforcement)). See [agent-trace-sync-command.md](agent-trace-sync-command.md) and [sync-command.md](sync-command.md). ## Command loop and error model diff --git a/context/cli/execution-glossary.md b/context/cli/execution-glossary.md index d629bca91..26727cea7 100644 --- a/context/cli/execution-glossary.md +++ b/context/cli/execution-glossary.md @@ -4,6 +4,8 @@ - `RuntimeCommand seam`: Internal static command-execution abstraction in `cli/src/services/command_registry.rs` where clap-parsed commands are represented as a `RuntimeCommand` enum with variants for `Help`, `HelpText`, `Version`, `Completion`, `Auth`, `Config`, `Setup`, `Doctor`, `Hooks`, `Policy`, and `Sync`. The enum owns `name()` and async `execute(...)` dispatch, directly awaited under the application-level multi-thread Tokio runtime (distinct from retained DB-owned runtimes), delegating behavior to service-owned command payload structs while avoiding boxed `dyn RuntimeCommand` handles. Parsed request construction lives in `cli/src/services/parse/command_runtime.rs` when user-provided options or subcommands are required. - `logger trait boundary`: `services::observability::traits::Logger` mirrors the current observability logger API (`info`, `debug`, `warn`, `error`, `log_cli_error`) for generic command/runtime bounds and tests, with each method accepting `Option<&str>` session context for file routing; the concrete `services::observability::Logger` implements it and `NoopLogger` remains available for side-effect-free tests. - `telemetry trait boundary`: `services::observability::traits::Telemetry` defines the `with_default_subscriber` command-lifecycle capability used by generic app-runtime bounds and tests. The generic async callback deliberately makes this capability non-object-safe and statically selected through `HasTelemetry::Telemetry`. `NoopTelemetry` awaits the action once and installs no subscriber; production `RuntimeTelemetry` selects it unless a valid unexpired telemetry credential is stored, in which case managed telemetry attaches its subscriber to the command future so every poll is scoped (a thread-local guard across await is insufficient). Managed telemetry exports OTLP/HTTP protobuf traces and logs to the hardcoded canonical collector, fail-open and with bounded shutdown after command output; hook invocations, `sce policy bash`, and `sce auth telemetry-headers` always use `NoopTelemetry`. +- `sce codex` launcher: The public command in `cli/src/services/codex_telemetry/` that `exec`s Codex CLI with process-local `-c` OTEL overrides for repository-safe invocation modes, or unchanged with a one-line reason otherwise ([launcher](../sce/codex-native-telemetry-launcher.md)). +- `Codex hook span kind`: `ManagedSpanKind::CodexHook`, the managed-trace kind for `sce hooks codex` and `sce hooks codex-mutation-scope`; it exports one root `sce.hook` span with `sce.agent=codex` and `sce.codex.*` correlation attributes and never adopts `TRACEPARENT` ([observability](../sce/cli-observability-contract.md#managed-trace-export)). - `AppContext`: Generic borrowed dependency view in `cli/src/app.rs` passed through static command dispatch. `AppRuntime` owns the concrete production logger, `RuntimeTelemetry` (`NoopTelemetry` or managed export), filesystem, and git implementations; `AppContext` stores references to those dependencies plus an optional `repo_root: Option`, not owned `Arc` trait objects. Because it borrows from `AppRuntime`, `AppContext` is command-scoped: borrowing across directly awaited execution is safe while the owner lives, but detached work cannot retain that borrowed view. No new `Send`, `Sync`, or `'static` command bounds are required. The `repo_root` field is `None` at startup and command paths can derive a repo-root-scoped context with `AppContext::with_repo_root(...)` / `ContextWithRepoRoot`, preserving the borrowed runtime dependencies while attaching the resolved root. Narrow accessor traits (`HasLogger`, `HasTelemetry`, `HasFs`, `HasGit`, `HasRepoRoot`) let command and lifecycle call sites express capability requirements without depending on the full production context type; logger/telemetry/fs/git accessors use associated concrete capability types and return `&Self::{Capability}` rather than object-erased `&dyn ...` values. See [application execution runtime](../architecture.md#application-execution-runtime), [capability traits](capability-traits.md), and [observability](../sce/cli-observability-contract.md). diff --git a/context/context-map.md b/context/context-map.md index 64fa113a4..1c383bfa3 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -58,7 +58,8 @@ Feature/domain context: - `context/sce/cli-shell-completion-contract.md` (implemented `sce completion` contract for deterministic Bash/Zsh/Fish completion script generation) - `context/sce/claude-raw-hook-capture.md` (removed feature: the former `sce hooks claude-capture` raw-capture route and its supporting types, replaced by the active `diff-trace` and `conversation-trace` intakes) - `context/sce/claude-hook-trace-propagation.md` (probe evidence for Claude Code 2.1.301 command-hook trace context: `TRACEPARENT` names the `claude_code.interaction` span, not the tool span, and only when Claude tracing is active; hook-to-tool correlation by `tool_use_id`; `CLAUDECODE` + `CLAUDE_PROJECT_DIR` presence as the Claude hook-caller signal; T05 live Dash0 verification (doctor and session-boundary hook spans observed, parented tool-hook hierarchy unverified) and the opt-in live smoke procedure; the shipped `sce.hook` contract lives in `cli-observability-contract.md`, admission decision `context/decisions/2026-10-17-claude-hook-managed-trace-admission.md`) -- `context/sce/codex-native-telemetry-contract.md` (probe evidence for Codex CLI 0.172.0 native OTEL export: the `otel.headers_helper` invocation contract (runs from `CODEX_HOME` without repository context, timer-only refresh, export suspended on failure), `-c`/profile/user/requirements precedence and credential reach to unpinned exporters, attribution per invocation mode (`resume` without `-C` uses the stored session cwd), no current-span `TRACEPARENT` for command hooks, hook-to-native identifier mapping, observed token/cache/tool semantics and privacy controls, the decided launcher-plus-hook-span mechanism, and the Claude/Codex parity matrix; this is evidence and a decision, not shipped behavior) +- `context/sce/codex-native-telemetry-contract.md` (probe evidence for Codex CLI 0.172.0 native OTEL export: the `otel.headers_helper` invocation contract (runs from `CODEX_HOME` without repository context, timer-only refresh, export suspended on failure), `-c`/profile/user/requirements precedence and credential reach to unpinned exporters, attribution per invocation mode (`resume` without `-C` uses the stored session cwd), no current-span `TRACEPARENT` for command hooks, hook-to-native identifier mapping, observed token/cache/tool semantics and privacy controls, the decided launcher-plus-hook-span mechanism, and the Claude/Codex parity matrix; this is probe evidence and the decision record; shipped behavior is in `context/sce/codex-native-telemetry-launcher.md`) +- `context/sce/codex-native-telemetry-launcher.md` (shipped `sce codex` launcher: invocation-mode classification (new interactive, `exec`, `exec fork`, resume only with `-C`), conflict detection over environment, caller `-c otel.*`, user, profile, and readable `/etc/codex` OTEL settings, process-local `-c` overrides that run `sce auth telemetry-headers --repo ` and pin traces and metrics to the managed endpoint with logs off, Unix `exec` preserving terminal, signals, and exit code, and residual limits) - `context/sce/cli-observability-contract.md` (implemented config-backed runtime observability contract for the flat logging config-file shape with explicit config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` env-over-config-over-`/sce/logs` fallback, append-only local-date/session log file routing with a one-time complete-record `-v2.log` fallback on primary open/append/flush failure, creation-triggered retention of direct regular `*.log` files to 10 entries, reliable producer-native diff-trace/conversation-trace session routing and hook-specific non-duplicated Agent Trace DB-open error events, deterministic session filename sanitization, concrete `Logger` behavior plus the `NoopTelemetry`-backed telemetry capability boundary, logger and deliberately non-object-safe generic async telemetry boundaries with static capability dispatch and future-aware polling scope, AppContext observability wiring, generic `RunOutcome` final rendering, runtime-classified repeated telemetry action protection, operator-facing `sce config show` observability reporting, managed OTLP trace/log export (credential-gated, hardcoded canonical collector, Claude-only hook admission with one `sce.hook` span and correlation-only session/tool-use IDs, its `sce.mutation_scope`/`sce.git_snapshot`/`sce.persistence` operation child spans with a span-kind-specific export filter, allowlisted fields, bounded fail-open lifecycle, reserved metrics endpoint), and the trimmed `sce config validate` status-only validation surface) - `context/sce/shared-context-code-workflow.md` (canonical `/next-task` task-synchronization lifecycle and validation-only `/validate` lifecycle, package-local phase references with single-skill control flow, and the task-synchronization-scoped `sce-decision` sibling invocation with ADR reuse/blocker propagation) - `context/sce/shared-context-plan-workflow.md` (canonical `/change-to-plan` workflow, package-local context-load/plan-authoring/template references, clarification/readiness gate contract, and one-task/one-atomic-commit task slicing) @@ -150,6 +151,7 @@ Supporting repo docs: Recent decision records: +- `context/decisions/2026-11-24-codex-native-telemetry-via-sce-codex-launcher.md` (native Codex OTEL export is enabled only by the `sce codex` launcher with process-local overrides that pin every exporter and pass the helper an explicit repository; native logs stay off; plain `codex` exports only SCE Codex hook spans, which are independent roots) - `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) diff --git a/context/decisions/2026-11-24-codex-native-telemetry-via-sce-codex-launcher.md b/context/decisions/2026-11-24-codex-native-telemetry-via-sce-codex-launcher.md new file mode 100644 index 000000000..89bbc8369 --- /dev/null +++ b/context/decisions/2026-11-24-codex-native-telemetry-via-sce-codex-launcher.md @@ -0,0 +1,83 @@ +# Decision: Enable native Codex telemetry only through the `sce codex` launcher + +Date: 2026-11-24 +Status: Accepted +Plan: `context/plans/codex-native-otel-instrumentation.md` +Task: `T02` + +## Context + +Codex CLI 0.172.0 runs `otel.headers_helper` from `CODEX_HOME` and gives it no repository or thread context. A helper command fixed in user-level Codex config therefore cannot identify the repository, and every repository would be attributed to one credential. Repository-local Codex config cannot set `otel.*`. Codex attaches a helper header to every `otlp-http` exporter that is not pinned, including user-owned and profile exporters, so supplying only the helper hands the credential to those destinations. Codex command hooks receive only the `TRACEPARENT` inherited from the process that launched Codex, never the current Codex span. The probe evidence is in [codex-native-telemetry-contract.md](../sce/codex-native-telemetry-contract.md). + +## Decision + +Native Codex OpenTelemetry export is enabled only through the public `sce codex` launcher. The launcher resolves the repository and the effective access policy before launch. It then `exec`s `codex` with process-local `-c` overrides only: + +- `otel.headers_helper` set to the shell-quoted ` auth telemetry-headers --repo `; +- `otel.headers_helper_refresh_interval_ms=300000`; +- `otel.exporter="none"`, so native log export stays off; +- `otel.trace_exporter` and `otel.metrics_exporter` as `otlp-http` with protocol `binary`, pinned to the managed endpoint's per-signal paths; +- `otel.log_user_prompt`, `otel.log_agent_responses`, and `otel.log_guardian_assessments` set to `false`. + +The launcher launches Codex unchanged, without these overrides, and prints a one-line stderr reason in these cases: + +- user, profile, or readable system Codex config defines OTEL settings; +- a non-canonical `OTEL_EXPORTER_OTLP_*` destination is visible; +- the caller passes a `-c otel.*` override; +- the invocation mode is unproven: resume without `-C`, interactive fork, or `app-server`, `exec-server`, `remote-control`, `cloud`, `mcp`, or `review`; +- the repository has no authorized telemetry credential. + +When the access policy disables telemetry, the launcher launches Codex unchanged without a notice. No Codex config file is written, and no credential appears in arguments. A plain `codex` launch exports no native telemetry. Codex hook spans (`sce.hook`, `sce.agent=codex`) export independently of the launcher as independent roots, with no `TRACEPARENT` extraction. + +## Rationale + +- Only a launch-time wrapper knows the repository before Codex starts, so only it can pass explicit repository context to the helper. +- Pinning every exporter key with `-c` overrides user and profile layers per key, which closes the observed credential leak path. +- Process-local overrides leave user-owned and enterprise Codex config untouched. +- Native logs carry tool arguments and the user email without a redaction control, so disabling them keeps content off the wire. Metrics and spans still carry tokens, cache, model, tool counts, and durations. +- Inherited `TRACEPARENT` would attach SCE hook spans to whatever trace launched Codex, so Codex hook spans stay roots. + +## Alternatives considered + +- **User-level Codex config install, like Claude** — rejected because the helper cannot identify the repository from `CODEX_HOME`. +- **Hook spans only, native export deferred** — rejected because the launcher delivers token, model, and tool telemetry now for repository-safe modes. +- **Supplying only the helper override** — rejected because the helper header reaches unpinned user and profile exporters. +- **Exporting native logs** — rejected because tool arguments and `user.email` cannot be redacted in Codex 0.172.0. + +## Compatibility and risks + +- Coverage is limited to `sce codex` launches. Plain `codex` launches keep only SCE hook spans. +- In-process thread switches to another repository (subagents, `/new`, in-TUI resume) remain attributed to the launch repository. +- MDM and cloud requirements cannot be read by the launcher. Upstream still prevents a user helper from reaching a requirements-layer exporter. +- Codex helper failure suspends export without replay. The Codex session itself is not affected. +- Unrecognized Codex options launch without telemetry, so a new Codex option disables telemetry until the launcher learns it. + +## Guardrails + +- The launcher never writes Codex config files and never places a credential in arguments, files, or output. +- Every OTEL exporter key is pinned whenever the helper override is supplied. +- The no-argument `sce auth telemetry-headers` form keeps its Claude behavior. The `--repo` form applies the same policy gate, destination tripwire, `auth.db` check, repository binding, and deadline to the named repository. +- Codex hook spans never derive a parent from `TRACEPARENT` or from session, turn, or tool-use identifiers. +- The launcher and the header helper never initialize managed exporter telemetry. + +## Consequences + +- Native Codex traces and metrics reach the managed collector with repository-scoped credentials for new interactive sessions, `exec`, `exec fork`, and resume with `-C`. +- Codex hook processes are admitted to managed trace export. This narrows the "never admitted" list in the Claude hook admission decision. +- Codex metric names and semantics differ from Claude's. Existing dashboards may need control-plane work to use them. + +## Follow-up + +- Live Dash0 verification of delivery, attribution, and privacy is recorded by plan task T03. + +## References + +- Plan: [`codex-native-otel-instrumentation`](../plans/codex-native-otel-instrumentation.md) +- Task: `T02` +- Current-state context: [`telemetry-credential.md`](../sce/telemetry-credential.md) +- Current-state context: [`cli-observability-contract.md`](../sce/cli-observability-contract.md) +- Current-state context: [`access-policy.md`](../cli/access-policy.md) +- Current-state context: [`cli-command-surface.md`](../cli/cli-command-surface.md) +- Evidence: [`codex-native-telemetry-contract.md`](../sce/codex-native-telemetry-contract.md) +- Related decision: [Admit Claude-invoked SCE hooks to managed trace export](2026-10-17-claude-hook-managed-trace-admission.md) +- Related decision: [Claude telemetry removal on global withdrawal](2026-10-21-claude-telemetry-removal-on-global-withdrawal.md) diff --git a/context/glossary.md b/context/glossary.md index c5d42df30..899bf14a1 100644 --- a/context/glossary.md +++ b/context/glossary.md @@ -1,5 +1,5 @@ # Glossary -- CLI execution terminology: [command dispatch, runtime dependencies and telemetry](cli/execution-glossary.md). Auth mode, policy layer (user/repository), effective access policy, setup repository access preferences, and the `auth.disabled_by_config` rejection: [effective access policy](cli/access-policy.md). Setup login step and `auth.setup_login_required`: [setup login](sce/setup-repo-local-config-bootstrap.md#setup-login). +- CLI execution terminology: [command dispatch, runtime dependencies, telemetry, the `sce codex` launcher, and the Codex hook span kind](cli/execution-glossary.md). Auth mode, policy layer (user/repository), effective access policy, setup repository access preferences, and the `auth.disabled_by_config` rejection: [effective access policy](cli/access-policy.md). Setup login step and `auth.setup_login_required`: [setup login](sce/setup-repo-local-config-bootstrap.md#setup-login). - `pkl-check-generated`: Flake app exposed as `nix run .#pkl-check-generated`; canonical ephemeral-generation check that rejects committed target/schema/mirror outputs, evaluates exact workflow metadata, the generated artifact contract, semantic layout/path/inventory/content/parity/observational checks, and the optional-workflow manifest's content against the catalog, requires the shared helper-composition rule and SCE-scoped workflow prohibitions, enforces ordered catalog-derived OpenCode skill permissions plus explicit-permission artifact integrity, rejects stale sibling-package references or unresolved internalization tokens in workflow entrypoint `SKILL.md` documents, proves contract failures through checked-in negative fixtures, and delegates deterministic generation plus payload/input inventories to the generated-input producer while preserving its established inventory report. - `repo-level verification preference`: Current repository guidance that contributor-facing validation/check flows should prefer `nix flake check`; direct Cargo verification commands are secondary and used only when explicitly requested or for narrow targeted debugging, while `cargo fmt` remains the explicit autofix path. Required quick checks after each completed task in this repo are `nix run .#pkl-check-generated` and `nix flake check`. - disposable plan lifecycle: Policy where `context/plans/` holds active execution artifacts only; completed plans are disposable and durable outcomes must be reflected in current-state context files and/or `context/decisions/`. diff --git a/context/overview.md b/context/overview.md index ae12d8e99..b720946e9 100644 --- a/context/overview.md +++ b/context/overview.md @@ -56,6 +56,7 @@ The generated `/next-task` workflow persists task-level context-synchronization - **Stdout/stderr:** command payloads on stdout only; redacted diagnostics and text-mode `sce sync` progress on stderr, while JSON sync remains silent (see `context/sce/cli-stdout-stderr-contract.md`). - **Observability:** config-resolved logging with tracing, explicit config-file/default `log_to_file` control, suppression of normal logger records on `stderr` when file logging is enabled, error-only logger routing to `stderr` when file logging is disabled, and optional dated/session-partitioned `log_dir` / `SCE_LOG_DIR` files with retention (see `context/sce/cli-observability-contract.md`). - **Config precedence:** `flags > env > config file > defaults` (see `context/cli/config-precedence-contract.md`); invalid default-discovered config remains degradable for ordinary startup, while setup and Agent Trace storage fail closed before side effects or fallback identity selection. The config-file-only `agent_trace.auto_sync` setting resolves omitted values to `false`, while setup explicitly writes `true` into a newly created repo-local config; source metadata feeds the post-commit trigger and doctor readiness boundaries. Its asynchronous post-commit behavior and doctor capability reporting are documented in `context/cli/agent-trace-auto-sync.md`. +- **Codex native telemetry:** `sce codex` launches Codex with Codex traces and metrics exported to the managed collector under a repository-scoped credential, for repository-safe invocation modes only; plain `codex` launches export only SCE Codex hook spans (see `context/sce/codex-native-telemetry-launcher.md`). - **Attribution hooks:** enabled by default, gated by staged-diff AI-overlap preflight; `SCE_ATTRIBUTION_HOOKS_DISABLED` opt-out (see `context/sce/agent-trace-commit-msg-coauthor-policy.md`). - **Setup behavior choices:** interactive setup asks independent Yes-default confirmations for post-commit Agent Trace auto-sync and commit-attribution trailers, persists the answers under `agent_trace.auto_sync` and `policies.attribution_hooks.enabled`, and leaves existing behavior keys/omissions untouched during non-interactive setup. Interactive setup also asks for the SCE auth mode and telemetry consent, saves those answers only to the repository `.sce/config.json` before the target install, so they apply only to that repository, and reports the re-resolved effective access policy in an `SCE access` section. It then runs `sce auth login` from the repository root when the effective mode is `mandatory` or the user accepted the `optional` login offer, never under `disabled`; a failed mandatory login exits with `auth.setup_login_required`. Saved answers skip their prompts on reruns; interactive-only `sce setup --reconfigure` asks them all again with the saved values as defaults. The runtime resolver and hook contracts remain authoritative (see `context/sce/setup-repo-local-config-bootstrap.md`). - **Install channels:** repo-flake Nix, Cargo, npm, and source-built Flatpak (`dev.crocoder.sce`); Homebrew deferred (see `context/sce/cli-first-install-channels-contract.md`). diff --git a/context/plans/codex-native-otel-instrumentation.md b/context/plans/codex-native-otel-instrumentation.md index 2d733a153..7643d4b58 100644 --- a/context/plans/codex-native-otel-instrumentation.md +++ b/context/plans/codex-native-otel-instrumentation.md @@ -102,13 +102,19 @@ Persist this field in every plan; this is durable plan state, not chat state: - Deviations: enterprise requirements, MDM, cloud, and `app-server` layering were not probed live (root required or out of scope) and are recorded as source-only or unproven; Claude metric semantics in the parity matrix come from existing context and documentation and are deferred to T03 for live confirmation; probe runs created Codex session rollouts under the user's `~/.codex/sessions` (no config change). - Context synchronization: synced -- [ ] T02: `Ship native Codex telemetry and Codex hook spans on the managed infrastructure` (status:todo) +- [x] T02: `Ship native Codex telemetry and Codex hook spans on the managed infrastructure` (status:done) - Task ID: T02 - Scope: In — the T01-selected mechanism only: explicit repository context on the hidden helper (no-argument behavior unchanged), a thin `sce codex` launcher if and only if T01 requires it, and conflict detection for user-owned and enterprise Codex OTEL config; hook admission for `sce hooks codex` and `sce hooks codex-mutation-scope` in `managed_span_kind`; the hook-agent span kind and verified `sce.codex.*` attributes; reuse of `sce.mutation_scope`, `sce.git_snapshot`, and `sce.persistence` at existing Codex call sites; `TRACEPARENT` extraction for Codex only if T01 proved current-span propagation; setup and doctor changes only where T01 requires them, keeping configuration availability, credential authorization, and delivery as distinct states; focused unit and loopback-receiver tests; one ADR if a launcher ships. Out — live Dash0 verification; Claude span or settings changes; credential lifecycle changes; Pkl hook contract changes; unproven invocation modes. - Dependencies: T01 - Done when: AC2 through AC7 hold in tests; the helper bypass in `managed_span_kind` still returns no span kind for `sce auth telemetry-headers` in all argument forms; every existing Claude telemetry, helper, and Codex hook test passes unchanged; no credential appears in launch arguments, written config, output, or diagnostics. - Verify: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_telemetry`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml telemetry_headers`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml codex`; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_span_kind`; `nix develop -c ./scripts/run-cli-cargo.sh clippy --manifest-path cli/Cargo.toml --all-targets -- -D warnings`. - - Context synchronization: pending + - Completed: 2026-11-24 + - Files changed: `cli/src/app.rs`; `cli/src/cli_schema.rs`; `cli/src/command_surface.rs`; `cli/src/services/mod.rs`; `cli/src/services/command_registry.rs`; `cli/src/services/parse/command_runtime.rs`; `cli/src/services/auth_command/mod.rs`; `cli/src/services/auth_command/command.rs`; `cli/src/services/managed_telemetry/trace_export.rs`; `cli/src/services/hooks/codex/mod.rs`; `cli/src/services/hooks/codex_mutation_scope/lifecycle.rs`; `cli/src/services/hooks/codex_mutation_scope/mod.rs`; `cli/src/services/hooks/codex_mutation_scope/telemetry_tests.rs` (new); `cli/src/services/codex_telemetry/mod.rs` (new); `cli/src/services/codex_telemetry/command.rs` (new); `cli/src/services/codex_telemetry/tests.rs` (new); `context/plans/codex-native-otel-instrumentation.md` (T02 record) + - Result: Added a sibling `ManagedSpanKind::CodexHook`; `sce hooks codex` and `sce hooks codex-mutation-scope` are admitted without a caller marker and export one root `sce.hook` span with `sce.agent=codex`, `sce.hook.command`/`event`/`tool`, and `sce.codex.session_id`/`turn_id`/`tool_use_id`/`model`/`agent_id`/`agent_type` from stdin; `upstream_parent_context` adopts `TRACEPARENT` only for `ClaudeHook`. The Codex mutation-scope seam runs inside `sce.mutation_scope`, and the existing coordinator supplies `sce.git_snapshot`/`sce.persistence`. The hidden helper accepts a hidden `--repo ` (`AuthSubcommand::TelemetryHeadersForRepository`), routing the same policy gate, destination tripwire, `auth.db` probe, repository binding, and deadline to that path; the no-argument variant and code path are unchanged. A public `sce codex [codex arguments...]` launcher (`services::codex_telemetry`) classifies the invocation (new interactive, `exec`, `exec fork`, and resume only with `-C`; everything else launches plainly), resolves the repository and access policy, skips with a one-line stderr reason on destination-environment, caller `-c otel.*`, user, profile, readable `/etc/codex/*` OTEL settings, unreadable config, or an unauthorized repository, and otherwise prepends process-local `-c` overrides (shell-quoted helper with `--repo`, 300 s refresh, `otel.exporter="none"`, traces and metrics `otlp-http` binary to the managed per-signal endpoints, three content flags false), then `exec`s `codex` (spawn-and-exit on non-Unix). `managed_span_kind` returns no span kind for `sce codex` and for every `sce auth telemetry-headers` argument form. + - Verify results: `test … managed_telemetry` — 23 passed; `test … telemetry_headers` — 11 passed; `test … codex` — 59 passed; `test … managed_span_kind` — 3 passed; `clippy … --all-targets -- -D warnings` — clean; full `test --manifest-path cli/Cargo.toml` — 915 passed, 0 failed (existing Claude telemetry, helper, and Codex hook tests unchanged and passing). Manual launcher check with the built binary and a stub `codex` on `PATH`: stub `exit 7` → `sce codex` status 7; stub self-`SIGTERM` → status 143; arguments (including `--help`) forwarded verbatim; resume without `-C`, user `[otel]` exporter, foreign `OTEL_EXPORTER_OTLP_ENDPOINT`, caller `-c otel.*`, and an unauthorized repository each printed the expected one-line reason and launched without overrides; a missing `codex` binary returned `Failed to launch \`codex\``; `sce auth telemetry-headers [--repo ]` without a credential failed closed with `Telemetry credential is unavailable.` and empty stdout. No credential appears in overrides (asserted by `codex_telemetry_overrides_pin_every_exporter_and_disable_content`). + - Context impact: cross-domain — adds the public `sce codex` command and the hidden helper `--repo` flag, the `CodexHook` span kind and `sce.codex.*` attributes, and Codex-only trace-parent gating; affects `context/cli/cli-command-surface.md`, `context/sce/telemetry-credential.md`, `context/sce/cli-observability-contract.md`, `context/sce/codex-integration-runtime.md`, `context/cli/codex-mutation-scope-integration.md`, `context/cli/access-policy.md`, and root architecture/overview/glossary; the launcher is the ADR-worthy architectural choice. + - Deviations: the helper repository argument ships as a separate `TelemetryHeadersForRepository` variant so the existing no-argument parse test and code path stay unchanged, which drops `Copy` from `AuthSubcommand`/`AuthRequest`; `otel.span_attributes` repository attribution was not added (T01 local choice); `plan_launch_with` takes an injected repository-root resolver because this machine has a stray `/tmp/.git` directory that made a temp-dir "not a repository" test non-hermetic; the ADR is left to the context-synchronization decision gate; SCE hook runs during the session wrote an untracked `cli/context/tmp/` log (not part of this change). + - Context synchronization: synced - [ ] T03: `Record live Codex telemetry verification and the Claude/Codex parity contract in durable context` (status:todo) - Task ID: T03 diff --git a/context/sce/cli-observability-contract.md b/context/sce/cli-observability-contract.md index 42c4f60ff..6d9523666 100644 --- a/context/sce/cli-observability-contract.md +++ b/context/sce/cli-observability-contract.md @@ -96,11 +96,12 @@ Runtime observability consumes the shared resolved observability config from `cl ## Managed trace export - Defined in `cli/src/services/managed_telemetry.rs` and `cli/src/services/managed_telemetry/trace_export.rs` (plus `log_export.rs`). After startup, `RuntimeTelemetry::resolve` returns Noop (`disabled_by_config`) before any auth DB access when the effective access policy's telemetry state is not `Enabled` ([access-policy.md](../cli/access-policy.md)); otherwise a missing `auth.db` returns Noop (`not_configured`) without resolving a key ([telemetry-credential.md](telemetry-credential.md)). Otherwise it loads the stored telemetry credential from the encrypted auth DB, with non-interactive credential-store access, in a spawned task bounded by `CREDENTIAL_LOOKUP_DEADLINE` (2s); absent, expired, malformed, unavailable, ownerless (no stored WorkOS session), or timed-out credentials select `NoopTelemetry`. Startup never issues or refreshes a credential. The fallback is not silent: `RuntimeTelemetry::resolve` logs one `sce.telemetry.fallback` record with `reason` = `disabled_by_config`, `not_configured`, `credential_inaccessible`, `credential_unavailable`, `credential_expired`, `lookup_timeout`, `database_error`, `path_resolution_error`, or `exporter_init_failed`, at forced `warn` for failures and `debug` otherwise. Database and path errors add the redacted storage error text as `error`; no credential, bearer, key, or payload is logged, and the record never reaches stdout or, with `log_to_file=true`, stderr. -- Admission (`managed_span_kind` in `cli/src/app.rs`, decided from argv before credential lookup): Claude-invoked SCE hooks resolve the `sce.hook` span kind, every other hook and the hidden `sce auth telemetry-headers` helper use `NoopTelemetry` without a credential lookup, and all remaining commands use the `sce.command` span kind. `sce hooks claude-mutation-scope` and `sce hooks claude-model-state` are admitted from argv alone. The shared `sce hooks diff-trace`, `sce hooks conversation-trace`, and `sce policy bash` are admitted only when both `CLAUDECODE` and `CLAUDE_PROJECT_DIR` are present in the environment (checked for presence only; values never read); `CLAUDE_PROJECT_DIR` is set for Claude command hooks but not for the Claude Bash tool (evidence: [claude-hook-trace-propagation.md](claude-hook-trace-propagation.md)). Other hooks (commit hooks, Codex, OpenCode, Pi) stay Noop. Admitted hooks use the same `CREDENTIAL_LOOKUP_DEADLINE`, `SHUTDOWN_TIMEOUT`, and runtime grace bounds as commands. Decision record: [2026-10-17-claude-hook-managed-trace-admission.md](../decisions/2026-10-17-claude-hook-managed-trace-admission.md). +- Admission (`managed_span_kind` in `cli/src/app.rs`, decided from argv before credential lookup): Claude-invoked SCE hooks resolve the Claude `sce.hook` span kind, `sce hooks codex` and `sce hooks codex-mutation-scope` resolve the Codex `sce.hook` span kind (`ManagedSpanKind::CodexHook`) from argv alone, every other hook, the hidden `sce auth telemetry-headers` helper (in every argument form), and the `sce codex` launcher use `NoopTelemetry` without a credential lookup, and all remaining commands use the `sce.command` span kind. `sce hooks claude-mutation-scope` and `sce hooks claude-model-state` are admitted from argv alone. The shared `sce hooks diff-trace`, `sce hooks conversation-trace`, and `sce policy bash` are admitted only when both `CLAUDECODE` and `CLAUDE_PROJECT_DIR` are present in the environment (checked for presence only; values never read); `CLAUDE_PROJECT_DIR` is set for Claude command hooks but not for the Claude Bash tool (evidence: [claude-hook-trace-propagation.md](claude-hook-trace-propagation.md)). Other hooks (commit hooks, OpenCode, Pi) stay Noop. Admitted hooks use the same `CREDENTIAL_LOOKUP_DEADLINE`, `SHUTDOWN_TIMEOUT`, and runtime grace bounds as commands. Decision record: [2026-10-17-claude-hook-managed-trace-admission.md](../decisions/2026-10-17-claude-hook-managed-trace-admission.md). - Export is OTLP/HTTP protobuf to the hardcoded `https://otel.crocoderlab.dev/v1/traces`. A pinned HTTP client sets `Authorization: Bearer ` (token only, never the accessor), disables redirects, rebuilds the request to the fixed endpoint, and bounds requests to 3s. Ambient `OTEL_EXPORTER_OTLP_*` values cannot redirect it. - Each command emits one `sce.command` span with `sce.command.name`, `sce.outcome` (`success`/`failure`), and `sce.error.class` (the `SCE-ERR-*` code on failure); resource attributes are `service.name=sce` and `service.version`. Raw arguments, paths, and error chains are not exported. -- An admitted Claude hook process emits exactly one `sce.hook` span instead (no `sce.command` span), with `sce.agent=claude`, `sce.hook.command`, `sce.outcome`, `sce.error.class`, and, when present as non-empty strings in the Claude hook stdin payload, `sce.hook.event` (`hook_event_name`), `sce.hook.tool` (`tool_name`), `sce.claude.session_id`, and `sce.claude.tool_use_id`. `sce.hook.command` is the stable SCE entry point (`ClaudeHookCommand`: `diff-trace`, `conversation-trace`, `claude-mutation-scope`, `claude-model-state`, `policy-bash`), so the several SCE hooks that one Claude event runs produce distinguishable spans; each Claude hook entry point records it with `trace_export::record_claude_hook_command` as its first step, before reading stdin, so the span carries it even when stdin is empty, cannot be read, or is not JSON, and when the hook then fails. `trace_export::record_claude_hook_payload(stdin)` is the only payload reader: each entry point passes its stdin to it once after a successful read, it returns immediately when the current span is disabled (Noop), and it copies only those four fields. Session and tool-use IDs are opaque correlation identifiers: span attributes only, never metric attributes, never used to derive a trace ID. Tool input and response, prompts, `cwd`, transcript paths, file contents, and the raw payload are never exported. Parent context: for the `sce.hook` kind only, `ManagedTraceTelemetry::new` reads `TRACEPARENT` (and `TRACESTATE` when present) from the process environment, extracts it with `TraceContextPropagator`, and keeps it only when the remote span context is valid; `root_span` then attaches it with `set_parent`, so `sce.hook` shares Claude Code's trace ID, its parent is the upstream span (Claude Code 2.1.301 supplies `claude_code.interaction`, making `sce.hook` a sibling of `claude_code.tool`), and its own span ID is freshly generated. Child spans created inside the instrumented hook future inherit that trace across `.await` points and worker migration. No global propagator is registered and `sce.command` never reads the variables. A missing, malformed, or all-zero traceparent (the normal case when Claude tracing is off) yields an independent SCE root. Claude `SessionStart` and `SessionEnd` hooks run outside any interaction span, so their `sce.hook` is always a root. Live status: Dash0 (dataset `sce-crocoder`) shows `sce doctor`, Claude session-boundary `sce.hook` spans, and parented tool-hook `sce.hook` spans with operation children under `claude_code.interaction`. Concurrent hook processes previously lost spans because the auth DB credential lookup failed with `LockingError` and fell back to Noop; that is fixed, and the fix is verified by multiprocess regression tests but not yet re-verified live in Dash0. The evidence and the opt-in smoke procedure are in [claude-hook-trace-propagation.md](claude-hook-trace-propagation.md). Telemetry failures never change hook stdout, permission decisions, persisted state, or exit codes. -- Operation child spans: `trace_export::in_child_span(ManagedChildSpan, future)` wraps an existing operation in one of three named spans, each carrying only `sce.outcome` (`success`/`failure` from the operation's `Result`): `sce.mutation_scope` around every Claude adapter seam call (one coordinate or abandon boundary), `sce.git_snapshot` around the coordinator's tree capture and pin, and `sce.persistence` around the mutation-store phase of a coordinate boundary (initialize, scope/provenance registration, CAS commit loop) and of an abandon. The hierarchy is `sce.hook → sce.mutation_scope → {sce.git_snapshot, sce.persistence}`. A child span exists only when its operation runs: a read-only tool, an untracked background shell, or a close with no matching attempt exports `sce.hook` alone. Snapshot-failure taint persistence and conversation/diff-trace Agent Trace DB writes have no span. The span filter depends on the span kind: a `sce.command` dispatch exports only `sce.command` (ordinary commands that reach the coordinator, such as ref maintenance, still export one span), and a `sce.hook` dispatch exports only `sce.hook` and the three child names. Without a managed hook dispatch the child spans are disabled, and they never change ordering, locking, or errors. +- An admitted Claude hook process emits exactly one `sce.hook` span instead (no `sce.command` span), with `sce.agent=claude`, `sce.hook.command`, `sce.outcome`, `sce.error.class`, and, when present as non-empty strings in the Claude hook stdin payload, `sce.hook.event` (`hook_event_name`), `sce.hook.tool` (`tool_name`), `sce.claude.session_id`, and `sce.claude.tool_use_id`. `sce.hook.command` is the stable SCE entry point (`ClaudeHookCommand`: `diff-trace`, `conversation-trace`, `claude-mutation-scope`, `claude-model-state`, `policy-bash`), so the several SCE hooks that one Claude event runs produce distinguishable spans; each Claude hook entry point records it with `trace_export::record_claude_hook_command` as its first step, before reading stdin, so the span carries it even when stdin is empty, cannot be read, or is not JSON, and when the hook then fails. `trace_export::record_claude_hook_payload(stdin)` is the only payload reader: each entry point passes its stdin to it once after a successful read, it returns immediately when the current span is disabled (Noop), and it copies only those four fields. Session and tool-use IDs are opaque correlation identifiers: span attributes only, never metric attributes, never used to derive a trace ID. Tool input and response, prompts, `cwd`, transcript paths, file contents, and the raw payload are never exported. Parent context: for the Claude `sce.hook` kind only, `ManagedTraceTelemetry::new` reads `TRACEPARENT` (and `TRACESTATE` when present) from the process environment, extracts it with `TraceContextPropagator`, and keeps it only when the remote span context is valid; `root_span` then attaches it with `set_parent`, so `sce.hook` shares Claude Code's trace ID, its parent is the upstream span (Claude Code 2.1.301 supplies `claude_code.interaction`, making `sce.hook` a sibling of `claude_code.tool`), and its own span ID is freshly generated. Child spans created inside the instrumented hook future inherit that trace across `.await` points and worker migration. No global propagator is registered and `sce.command` never reads the variables. A missing, malformed, or all-zero traceparent (the normal case when Claude tracing is off) yields an independent SCE root. Claude `SessionStart` and `SessionEnd` hooks run outside any interaction span, so their `sce.hook` is always a root. Live status: Dash0 (dataset `sce-crocoder`) shows `sce doctor`, Claude session-boundary `sce.hook` spans, and parented tool-hook `sce.hook` spans with operation children under `claude_code.interaction`. Concurrent hook processes previously lost spans because the auth DB credential lookup failed with `LockingError` and fell back to Noop; that is fixed, and the fix is verified by multiprocess regression tests but not yet re-verified live in Dash0. The evidence and the opt-in smoke procedure are in [claude-hook-trace-propagation.md](claude-hook-trace-propagation.md). Telemetry failures never change hook stdout, permission decisions, persisted state, or exit codes. +- An admitted Codex hook process emits exactly one `sce.hook` span with `sce.agent=codex`, `sce.hook.command` (`CodexHookCommand`: `codex`, `codex-mutation-scope`), `sce.outcome`, `sce.error.class`, and, when present as non-empty strings in the Codex hook stdin payload, `sce.hook.event` (`hook_event_name`), `sce.hook.tool` (`tool_name`), `sce.codex.session_id`, `sce.codex.turn_id`, `sce.codex.tool_use_id`, `sce.codex.model`, `sce.codex.agent_id`, and `sce.codex.agent_type`. Each Codex entry point records the command with `trace_export::record_codex_hook_command` before reading stdin and passes stdin once to `trace_export::record_codex_hook_payload`, which copies only those fields. The identifiers join to native Codex telemetry: `session_id` equals `conversation.id`, `turn_id` equals `turn.id`, `tool_use_id` equals `call_id`, and a subagent `agent_id` equals the child `conversation.id` ([codex-native-telemetry-contract.md](codex-native-telemetry-contract.md#identifier-mapping)). Codex hook spans are always independent roots: `upstream_parent_context` adopts `TRACEPARENT` only for the Claude hook kind, because Codex hooks inherit `TRACEPARENT` from the process that launched Codex, never the current Codex span. No trace or parent span ID is derived from a session, turn, or tool-use identifier. Codex hooks keep their fail-open behavior; telemetry failures never change their stdout, permission decisions, persisted state, or exit codes. +- Operation child spans: `trace_export::in_child_span(ManagedChildSpan, future)` wraps an existing operation in one of three named spans, each carrying only `sce.outcome` (`success`/`failure` from the operation's `Result`): `sce.mutation_scope` around every Claude and Codex adapter seam call (one coordinate or abandon boundary), `sce.git_snapshot` around the coordinator's tree capture and pin, and `sce.persistence` around the mutation-store phase of a coordinate boundary (initialize, scope/provenance registration, CAS commit loop) and of an abandon. The hierarchy is `sce.hook → sce.mutation_scope → {sce.git_snapshot, sce.persistence}`. A child span exists only when its operation runs: a read-only tool, an untracked background shell, or a close with no matching attempt exports `sce.hook` alone. Snapshot-failure taint persistence and conversation/diff-trace Agent Trace DB writes have no span. The span filter depends on the span kind: a `sce.command` dispatch exports only `sce.command` (ordinary commands that reach the coordinator, such as ref maintenance, still export one span), and a `sce.hook` dispatch exports only `sce.hook` and the three child names. Without a managed hook dispatch the child spans are disabled, and they never change ordering, locking, or errors. - The exporter uses a bounded batch queue on a dedicated thread. Final stdout/stderr rendering and classified-error logging run inside the command span (`run_command_lifecycle_with_context`), so `sce.outcome` reflects the rendered result (a stdout write failure is `failure`) and the final `sce.error.*` log is exported. Trace and log providers shut down concurrently under one shared `SHUTDOWN_TIMEOUT` (3s) deadline after rendering; failures never change command results or exit codes. - Process lifetime: `app::run_process` owns the Tokio runtime (at least two workers) and ends it with `shutdown_timeout(RUNTIME_SHUTDOWN_GRACE)` (500ms), so a stalled keychain, database, or exporter worker cannot keep the process alive. The async deadlines bound when the command proceeds; the runtime grace is the hard process-level bound. Abandoned workers are not cancelled, only no longer awaited. - Logs: `managed_telemetry/log_export.rs` bridges `target: "sce"` tracing events and their `enabled!` hints (emitted by `Logger` only when the local level is enabled) to OTLP/HTTP protobuf log records at the hardcoded `/v1/logs`, using the same pinned bearer client, batch bounds, and shutdown as traces. Records carry severity, `sce.event_id`, a body limited to path- and secret-free messages (falling back to the event ID), and only allowlisted fields (`command`, `component`, `failure_class`, `error_code`, `error_class`, `error_surface`, `user_error`) with bounded, redacted values; `error_source`, arguments, paths, and hook payloads are never exported. Local file/stderr logging is unchanged. @@ -111,3 +112,4 @@ Runtime observability consumes the shared resolved observability config from `cl - The managed exporter above covers only the Rust `sce` process. Claude Code's native OpenTelemetry export is a separate pipeline configured in Claude's user-level `settings.json` by `sce setup` for Claude targets; SCE does not proxy, wrap, or cache it. - Both pipelines target the same managed OTLP endpoint and authenticate with the same stored telemetry credential, but Claude obtains the bearer by running the hidden `sce auth telemetry-headers` helper (re-run every five minutes), which never initializes managed exporter telemetry and returns the bearer only for a repository enrolled under the credential's workspace. The helper cannot observe Claude's effective exporter endpoint, so endpoint pinning is not claimed. - Setup skips the Claude install on conflicting user-owned or managed settings and never writes a token. Details, rotation, logout, failure handling, and override limits: [telemetry-credential.md](telemetry-credential.md). +- Codex's native export is a third pipeline, enabled only by `sce codex` with process-local overrides that run the helper with `--repo `. It exports Codex traces and metrics, not logs. See [codex-native-telemetry-launcher.md](codex-native-telemetry-launcher.md). diff --git a/context/sce/codex-integration-runtime.md b/context/sce/codex-integration-runtime.md index 15a833c28..941f06e80 100644 --- a/context/sce/codex-integration-runtime.md +++ b/context/sce/codex-integration-runtime.md @@ -201,6 +201,17 @@ mutation-scope `PreToolUse` registration matched by `^(Bash|apply_patch)$` and routed to `sce hooks codex-mutation-scope` is a separate concern handled by that command. +## Managed trace spans + +`sce hooks codex` and `sce hooks codex-mutation-scope` are admitted to managed +trace export. With a valid stored credential, each process exports one root +`sce.hook` span with `sce.agent=codex` and the verified `sce.codex.*` +identifiers. The mutation-scope seam runs inside `sce.mutation_scope`, with +`sce.git_snapshot` and `sce.persistence` children when the coordinator runs. +Codex hook spans never adopt `TRACEPARENT`. Telemetry never changes hook output +or persisted state. Contract: +[cli-observability-contract.md](cli-observability-contract.md#managed-trace-export). + ## Verification - `nix develop -c sh -c './scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml hooks::codex'` diff --git a/context/sce/codex-native-telemetry-launcher.md b/context/sce/codex-native-telemetry-launcher.md new file mode 100644 index 000000000..227d09cce --- /dev/null +++ b/context/sce/codex-native-telemetry-launcher.md @@ -0,0 +1,80 @@ +# Codex native telemetry launcher + +`sce codex [codex arguments...]` launches Codex CLI with Codex's own OpenTelemetry export pointed at the managed collector. The export uses a repository-scoped telemetry credential. A plain `codex` launch exports no native telemetry. SCE Codex hook spans are independent of the launcher (see [cli-observability-contract.md](cli-observability-contract.md#managed-trace-export)). + +Code: `cli/src/services/codex_telemetry/` (`mod.rs` for classification, conflict detection, and overrides; `command.rs` for execution). Decision: [ADR](../decisions/2026-11-24-codex-native-telemetry-via-sce-codex-launcher.md). Probe evidence for Codex 0.172.0: [codex-native-telemetry-contract.md](codex-native-telemetry-contract.md). + +## Launch flow + +```mermaid +flowchart TD + A[sce codex args] --> B{classify_launch} + B -- sessionless or unproven mode --> P[exec codex args unchanged] + B -- telemetry mode --> C{repository root of -C dir or cwd} + C -- none --> P + C -- found --> D{access policy enables telemetry} + D -- no --> P + D -- yes --> E{detect_otel_conflict} + E -- conflict --> P + E -- none --> F{repository credential authorized} + F -- no --> P + F -- yes --> G[exec codex with -c overrides, then args] +``` + +- Every plain launch except the sessionless and policy-disabled cases prints one stderr line: `sce: launching Codex without SCE native telemetry: .` +- The launcher must not change the caller's arguments. Overrides are prepended. Arguments, including `--help`, reach Codex verbatim. +- On Unix the launcher replaces itself with `codex` (`exec`), so the terminal, signal delivery, and the Codex exit code are Codex's own. On other platforms it waits for `codex` and exits with its status. A missing `codex` binary fails with `Failed to launch `codex``. +- The launcher never initializes managed exporter telemetry (`managed_span_kind` returns no span kind for `sce codex`). + +## Invocation modes + +| Mode | Native telemetry | +| --- | --- | +| New interactive session, with or without a prompt | Yes | +| `exec`, `e`, `exec fork` | Yes | +| `resume`, `exec resume` with `-C ` (before or after the subcommand) | Yes; the repository comes from `` | +| `resume`, `exec resume` without `-C` | No; the session runs in its stored directory | +| Interactive `fork` | No; the directory is chosen after launch | +| `app-server`, `exec-server`, `remote-control`, `cloud`, `mcp`, `mcp-server`, `review`, `exec review` | No; unproven | +| `login`, `logout`, `completion`, `features`, `apply`, `sandbox`, `debug`, `help`, `-h`, `--help`, `-V`, `--version` | No; sessionless, without a notice | +| An option the launcher does not recognize | No; the value boundary is unknown | + +`-C`/`--cd` sets the launch directory, resolved against the process working directory. The repository root is the nearest ancestor with a `.git` entry. + +## Conflict detection + +The launcher skips native telemetry when any of the following holds. It never overwrites the conflicting source. + +- A non-canonical `OTEL_EXPORTER_OTLP_ENDPOINT`, per-signal endpoint, or `BETA_TRACING_ENDPOINT` is set (the same tripwire as the header helper). +- A caller `-c`/`--config` override has the key `otel` or `otel.*`. +- `CODEX_HOME` (else `~/.codex`) cannot be determined. +- `$CODEX_HOME/config.toml` defines `otel.exporter`, `otel.trace_exporter`, `otel.metrics_exporter`, or `otel.headers_helper`. +- The selected profile defines one of those keys. The profile comes from `--profile`/`-p`, else the config `profile` key. The launcher checks `[profiles..otel]` in `config.toml` and `$CODEX_HOME/.config.toml`. +- The user config or the selected profile file cannot be read or parsed. +- A readable `/etc/codex/requirements.toml`, `/etc/codex/managed_config.toml`, or `/etc/codex/config.toml` has an `otel` key, or cannot be parsed. An unreadable system file is not a conflict. + +## Overrides + +When telemetry is enabled, the launcher passes these process-local `-c` overrides before the caller's arguments: + +| Key | Value | +| --- | --- | +| `otel.headers_helper` | `'' auth telemetry-headers --repo ''` (single-quoted for `sh -c`) | +| `otel.headers_helper_refresh_interval_ms` | `300000` | +| `otel.exporter` | `"none"`: native logs stay off | +| `otel.trace_exporter` | `{otlp-http={endpoint="https://otel.crocoderlab.dev/v1/traces",protocol="binary"}}` | +| `otel.metrics_exporter` | `{otlp-http={endpoint="https://otel.crocoderlab.dev/v1/metrics",protocol="binary"}}` | +| `otel.log_user_prompt`, `otel.log_agent_responses`, `otel.log_guardian_assessments` | `false` | + +- No override carries a credential or static headers. Codex obtains the bearer from the helper ([telemetry-credential.md](telemetry-credential.md#hidden-header-helper)). +- No Codex config file is written. + +## Limits + +- Coverage is limited to `sce codex` launches. +- Threads that change directory inside one Codex process (subagents, `/new`, in-TUI resume) stay attributed to the launch repository. +- MDM and cloud requirements are not readable by the launcher. A requirements layer can override the pins or force content logging. +- If the helper fails, Codex suspends export and drops data until the next successful refresh. The session itself continues. +- Codex native metrics have no session identifier and no cost signal. Token `input` includes cached input. + +See also: [codex-native-telemetry-contract.md](codex-native-telemetry-contract.md), [telemetry-credential.md](telemetry-credential.md), [../context-map.md](../context-map.md) diff --git a/context/sce/telemetry-credential.md b/context/sce/telemetry-credential.md index 1a75254e4..d869f1b9b 100644 --- a/context/sce/telemetry-credential.md +++ b/context/sce/telemetry-credential.md @@ -35,7 +35,7 @@ flowchart LR ## Runtime use -- `managed_telemetry::RuntimeTelemetry::resolve` first checks the effective access policy ([access-policy.md](../cli/access-policy.md)). When telemetry is not `Enabled`, the result is Noop with reason `disabled_by_config` (logged at `debug`), and neither `auth.db` nor the credential store is touched. Otherwise it runs the typed lookup through the non-interactive credential-store path at CLI startup (never issuing one). A missing `auth.db` is `Missing`, so the result is Noop with reason `not_configured` (logged at `debug`) without resolving a key; an existing `auth.db` resolves its key non-interactively and is opened without migrating ([auth-db.md](auth-db.md)). If the store refuses silent access, the reason is `credential_inaccessible` (logged at `debug`, so a denied Keychain does not flood the log). `sce setup` is excluded from managed telemetry so that it never reaches the credential store. a valid unexpired `token` is used only as the `Authorization: Bearer` credential for managed OTLP trace and log export; the `accessor` is never transmitted. Absent, expired, malformed, or unavailable rows select `NoopTelemetry`. Every Noop fallback is classified (`disabled_by_config`, `not_configured`, `credential_inaccessible`, `credential_unavailable`, `credential_expired`, `lookup_timeout`, `database_error`, `path_resolution_error`, `exporter_init_failed`) and logged locally as `sce.telemetry.fallback`; failures log at `warn` (forced, so they reach the log file at the default `error` level, never stderr while `log_to_file=true`), with the redacted `TokenStorageError` text for database and path errors, and policy-disabled telemetry, a missing `auth.db` or telemetry row, an inaccessible credential store, or missing or expired credentials log at `debug`. Concurrent lookups from many hook processes are supported by the auth DB's multiprocess WAL and migration-free current-schema open ([auth-db.md](auth-db.md)). Both this lookup and the header helper's repository lookup are existing-DB reads: a missing `auth.db` yields no credential and creates no DB file or encryption key. Claude-invoked SCE hooks are admitted to this lookup and export one `sce.hook` span. Every other hook and this hidden header helper skip the lookup and stay Noop. See [cli-observability-contract.md](cli-observability-contract.md). +- `managed_telemetry::RuntimeTelemetry::resolve` first checks the effective access policy ([access-policy.md](../cli/access-policy.md)). When telemetry is not `Enabled`, the result is Noop with reason `disabled_by_config` (logged at `debug`), and neither `auth.db` nor the credential store is touched. Otherwise it runs the typed lookup through the non-interactive credential-store path at CLI startup (never issuing one). A missing `auth.db` is `Missing`, so the result is Noop with reason `not_configured` (logged at `debug`) without resolving a key; an existing `auth.db` resolves its key non-interactively and is opened without migrating ([auth-db.md](auth-db.md)). If the store refuses silent access, the reason is `credential_inaccessible` (logged at `debug`, so a denied Keychain does not flood the log). `sce setup` is excluded from managed telemetry so that it never reaches the credential store. a valid unexpired `token` is used only as the `Authorization: Bearer` credential for managed OTLP trace and log export; the `accessor` is never transmitted. Absent, expired, malformed, or unavailable rows select `NoopTelemetry`. Every Noop fallback is classified (`disabled_by_config`, `not_configured`, `credential_inaccessible`, `credential_unavailable`, `credential_expired`, `lookup_timeout`, `database_error`, `path_resolution_error`, `exporter_init_failed`) and logged locally as `sce.telemetry.fallback`; failures log at `warn` (forced, so they reach the log file at the default `error` level, never stderr while `log_to_file=true`), with the redacted `TokenStorageError` text for database and path errors, and policy-disabled telemetry, a missing `auth.db` or telemetry row, an inaccessible credential store, or missing or expired credentials log at `debug`. Concurrent lookups from many hook processes are supported by the auth DB's multiprocess WAL and migration-free current-schema open ([auth-db.md](auth-db.md)). Both this lookup and the header helper's repository lookup are existing-DB reads: a missing `auth.db` yields no credential and creates no DB file or encryption key. Claude-invoked SCE hooks and the `sce hooks codex` / `sce hooks codex-mutation-scope` hooks are admitted to this lookup and export one `sce.hook` span. Every other hook, the hidden header helper, and the `sce codex` launcher skip the lookup and stay Noop. See [cli-observability-contract.md](cli-observability-contract.md). ## Doctor health check @@ -80,7 +80,8 @@ flowchart LR - Policy gate: the helper first resolves the effective access policy from its working directory ([access-policy.md](../cli/access-policy.md)). When telemetry is not `Enabled` (including `auth.mode: disabled`, a skipped invalid discovered config, or an unresolvable config), it fails closed before the destination tripwire, the `auth.db` existence check, repository resolution, or the auth DB. Repository discovery is Git-root relative, so a launch from a subdirectory applies the same repository policy as a launch from the root. `repository_id_for` uses the same `.git` ancestor walk, so policy and repository identity describe the same root. - The helper then checks only whether `auth.db` exists (a stat). Without it the helper fails closed before resolving the repository, so a never-logged-in machine spawns no `git` process. With it, the credential lookup uses the non-interactive credential-store path and never prompts. - Repository resolution and the credential lookup together are bounded by `CREDENTIAL_LOOKUP_DEADLINE`. Resolution spawns one `git config --get` process, which is needed to compute the repository ID; there is no network call and no issuance. Every failure exits nonzero with the fixed stderr diagnostic `Telemetry credential is unavailable.` and empty stdout. That includes a missing `auth.db`, which the helper never creates or migrates, so concurrent helper calls on a never-logged-in machine cannot race to initialize it. The helper never initializes managed exporter telemetry. -- It is omitted from `sce --help`, `sce auth --help`, and shell completions. +- Explicit repository: the hidden `--repo ` flag (`AuthSubcommand::TelemetryHeadersForRepository`) replaces the working directory with ``. The policy gate, the destination tripwire, the `auth.db` check, repository resolution, and `CREDENTIAL_LOOKUP_DEADLINE` then apply to ``. A missing path, a path outside Git, or an unenrolled or opted-out repository fails closed with the same fixed diagnostic and empty stdout. The `sce codex` launcher passes this flag, because Codex runs the helper from `CODEX_HOME` with no repository context ([codex-native-telemetry-launcher.md](codex-native-telemetry-launcher.md)). The no-argument form keeps the Claude behavior above. +- It is omitted from `sce --help`, `sce auth --help`, and shell completions. The `--repo` flag is also hidden. ## Security boundaries @@ -88,6 +89,7 @@ flowchart LR - Trust boundary: the local OS account. Any process running as the user can run `sce auth telemetry-headers` from an enrolled repository, or read the auth DB key, and obtain the token. The helper is not a defense against code the user executes; it prevents accidental cross-workspace attribution and refuses visible misdirection. - Endpoint pinning is not claimed. The helper cannot observe Claude's effective exporter destination. Claude's documentation says `OTEL_*` variables are not passed to subprocesses, and in testing, project-level `env` overrides were not visible to the helper. Server-managed settings and `--settings` files are also not inspectable from the helper. Claude itself pins the destination only when the endpoint, or `otelHeadersHelper`, is set in managed settings (Claude Code 2.1.217+ for per-signal endpoints, 2.1.251+ for `BETA_TRACING_ENDPOINT`); a user-level install has no such guarantee. - Residual risk: with a user-level install, any configuration path that Claude honors but the helper cannot see (a shell `OTEL_*`/`BETA_TRACING_ENDPOINT` variable in a Claude version that strips them from helpers, `--settings`, or a future precedence change) can send the bearer to another collector. The exposure is bounded by the token's scope: telemetry-only, non-renewable, 90-day lifetime. Local deletion does not revoke it; server-side revocation by accessor is not yet available. Organizations that need an enforced destination should set `OTEL_EXPORTER_OTLP_ENDPOINT=https://otel.crocoderlab.dev` and `otelHeadersHelper` in Claude managed settings. +- Codex endpoint residual risk: the `sce codex` launcher pins every Codex OTEL exporter key with process-local `-c` overrides and skips telemetry on visible user, profile, system, environment, or caller OTEL settings. MDM and cloud requirements are not readable and can override the pins. Upstream prevents a user-supplied helper from reaching a requirements-layer exporter. Details: [codex-native-telemetry-launcher.md](codex-native-telemetry-launcher.md#conflict-detection). - Token and accessor never appear in errors, logs, or `Debug` output; `TelemetryCredential` and the issuance response redact them, client and storage errors use fixed messages, and auth login's best-effort provisioning warning contains no credential or raw server-response data. The bearer is never written to Claude settings. - Encryption reuses the auth DB key handling described in [auth-db.md](auth-db.md). @@ -106,4 +108,8 @@ Claude Code's own OpenTelemetry export is separate from the SCE-CLI managed expo - Merge safety: repeated setup is byte-idempotent; unrelated settings, env, permissions, and hooks are preserved; writes are atomic via temp-file rename; an existing file's mode is kept and a new file uses `0600`; malformed JSON is never overwritten. - Conflicts and limits: a user-owned `otelHeadersHelper`, an explicit opt-out (`CLAUDE_CODE_ENABLE_TELEMETRY`, `CLAUDE_CODE_ENHANCED_TELEMETRY_BETA`, or `ENABLE_ENHANCED_TELEMETRY_BETA` not `1`, or any `OTEL_*_EXPORTER=none`), `OTEL_METRICS_INCLUDE_REPOSITORY` other than `true`, `OTEL_LOG_TOOL_DETAILS` other than `1`, a different helper refresh interval, or a differing generic/per-signal OTLP endpoint, headers, protocol, or exporter in user settings or in the Linux/macOS managed-settings file (`/etc/claude-code/managed-settings.json`, `/Library/Application Support/ClaudeCode/managed-settings.json`), causes the telemetry install to be skipped and reported with the specific reason while repository setup still succeeds. Environment variables present in a future Claude launch cannot be detected by setup and can override user settings. +## Codex-native telemetry + +Codex's own OpenTelemetry export is enabled only by the `sce codex` launcher. `sce setup` writes no Codex OTEL config. The launcher passes process-local overrides that run the helper with `--repo` and pin traces and metrics to the managed endpoint; native Codex logs stay off. See [codex-native-telemetry-launcher.md](codex-native-telemetry-launcher.md). + See also: [auth-db.md](auth-db.md), [cli-observability-contract.md](cli-observability-contract.md), [../context-map.md](../context-map.md) From ddb43c8aee926ea3cb92fb05d80e733479ccfb2a Mon Sep 17 00:00:00 2001 From: David Abram Date: Tue, 24 Nov 2026 16:29:38 +0100 Subject: [PATCH 4/4] codex: Harden native telemetry launch safety Restrict native Codex export to invocation modes with verified repository attribution, reject unsupported options across the full argument list, preserve `--` boundaries, and canonicalize explicit helper paths. Extend regression coverage and keep Codex arguments unchanged for plain launches. Record the Codex 0.172.0 live verification, privacy constraints, parity contract, launcher behavior, and synchronized CLI context. Remove the tracked temporary runtime log and retain the documented validation follow-ups. Plan: `codex-native-otel-instrumentation` (T03) --- cli/context/tmp/sce-24_11_2026.log | 9 - cli/src/services/auth_command/mod.rs | 23 ++- cli/src/services/codex_telemetry/mod.rs | 165 ++++++++++++------ cli/src/services/codex_telemetry/tests.rs | 90 +++++++++- cli/src/services/parse/command_runtime.rs | 23 ++- context/architecture.md | 2 +- context/cli/access-policy.md | 2 +- context/cli/cli-command-surface.md | 2 +- .../cli/codex-mutation-scope-integration.md | 29 +-- context/cli/execution-glossary.md | 15 +- context/context-map.md | 4 +- context/glossary.md | 10 +- context/overview.md | 4 +- .../codex-native-otel-instrumentation.md | 77 +++++++- context/sce/cli-observability-contract.md | 2 +- .../sce/codex-native-telemetry-contract.md | 80 ++++++--- .../sce/codex-native-telemetry-launcher.md | 14 +- context/sce/telemetry-credential.md | 2 +- 18 files changed, 402 insertions(+), 151 deletions(-) delete mode 100644 cli/context/tmp/sce-24_11_2026.log diff --git a/cli/context/tmp/sce-24_11_2026.log b/cli/context/tmp/sce-24_11_2026.log deleted file mode 100644 index bec8c3e66..000000000 --- a/cli/context/tmp/sce-24_11_2026.log +++ /dev/null @@ -1,9 +0,0 @@ -timestamp=2026-11-24T14:00:57.147Z log_format=text level=warn event_id=sce.hooks.claude_mutation_scope.pre_tool_use_fail_closed message=mutation-scope runtime boundary failed before durable completion: Operation 'execute repository Agent Trace DB database query' failed after 2 attempt(s) under write contention (db_name=repository Agent Trace DB, operation=execute repository Agent Trace DB database query, attempts=2, busy_timeout_ms=1000, contention_deadline_ms=2250 [no retry is scheduled past this cutoff], elapsed_ms=2035, cause=database busy (busy timeout exhausted)). Last error: repository Agent Trace DB execute failed: INSERT INTO mutation_trace_worktrees - (worktree_id, cursor_tree, revision, tainted, failure_kind, needs_rebaseline) - VALUES (?1, ?2, ?3, 0, 'healthy', 0) - ON CONFLICT (worktree_id) DO NOTHING: database is locked. Try: retry after the database lock clears; if the issue persists, stop other SCE processes using this database and rerun the command context=establish_start -timestamp=2026-11-24T14:01:02.164Z log_format=text level=warn event_id=sce.telemetry.fallback message=Managed telemetry disabled for this invocation; continuing without export reason=lookup_timeout -timestamp=2026-11-24T14:01:02.165Z log_format=text level=warn event_id=sce.telemetry.fallback message=Managed telemetry disabled for this invocation; continuing without export reason=lookup_timeout -timestamp=2026-11-24T14:12:42.500Z log_format=text level=warn event_id=sce.telemetry.fallback message=Managed telemetry disabled for this invocation; continuing without export reason=lookup_timeout -timestamp=2026-11-24T14:12:42.501Z log_format=text level=warn event_id=sce.telemetry.fallback message=Managed telemetry disabled for this invocation; continuing without export reason=lookup_timeout -timestamp=2026-11-24T14:25:24.748Z log_format=text level=error event_id=sce.error.SCE-ERR-RUNTIME message=Telemetry credential is unavailable. error_code=SCE-ERR-RUNTIME error_class=runtime error_surface=internal error_source=Telemetry credential is unavailable. diff --git a/cli/src/services/auth_command/mod.rs b/cli/src/services/auth_command/mod.rs index 6217ca219..aff183a15 100644 --- a/cli/src/services/auth_command/mod.rs +++ b/cli/src/services/auth_command/mod.rs @@ -118,7 +118,7 @@ where } async fn run_telemetry_headers(repository: Option) -> Result { - let working_dir = repository.or_else(|| std::env::current_dir().ok()); + let working_dir = telemetry_headers_working_dir(repository); let telemetry_enabled = working_dir.as_deref().is_some_and(telemetry_enabled_for); telemetry_headers_with( working_dir, @@ -131,6 +131,15 @@ async fn run_telemetry_headers(repository: Option) -> Result) -> Option { + match repository { + Some(path) => std::fs::canonicalize(path) + .ok() + .filter(|path| path.is_dir()), + None => std::env::current_dir().ok(), + } +} + pub(crate) fn telemetry_enabled_for(working_dir: &Path) -> bool { config::resolve_auth_runtime_config(working_dir) .is_ok_and(|config| config.access_policy.telemetry_enabled()) @@ -1134,6 +1143,10 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let enrolled = git_repository_with_remote(dir.path(), "a", "git@github.com:acme/a.git"); let unenrolled = git_repository_with_remote(dir.path(), "b", "git@github.com:acme/b.git"); + let enrolled_subdir = enrolled.join("src").join("module"); + std::fs::create_dir_all(&enrolled_subdir).unwrap(); + let enrolled_file = enrolled.join("file"); + std::fs::write(&enrolled_file, "").unwrap(); let not_git = dir.path().join("plain"); std::fs::create_dir_all(¬_git).unwrap(); let enrolled_id = repository_id_for(&enrolled).expect("enrolled repository identity"); @@ -1141,7 +1154,7 @@ mod tests { let headers_for = |repository: PathBuf| { let enrolled_id = enrolled_id.clone(); telemetry_headers_with( - Some(repository), + telemetry_headers_working_dir(Some(repository)), true, false, || true, @@ -1153,15 +1166,15 @@ mod tests { }; assert_eq!( - headers_for(enrolled.join("src").join("module")) - .await - .unwrap(), + headers_for(enrolled_subdir).await.unwrap(), r#"{"Authorization":"Bearer tok-a"}"# ); for (case, repository) in [ ("unenrolled", unenrolled), ("not git", not_git), ("missing", dir.path().join("missing")), + ("missing inside enrolled repo", enrolled.join("missing")), + ("file inside enrolled repo", enrolled_file), ] { let error = headers_for(repository).await.expect_err(case); assert_eq!(error.to_string(), TELEMETRY_HEADERS_UNAVAILABLE, "{case}"); diff --git a/cli/src/services/codex_telemetry/mod.rs b/cli/src/services/codex_telemetry/mod.rs index 66de70413..fbb49def9 100644 --- a/cli/src/services/codex_telemetry/mod.rs +++ b/cli/src/services/codex_telemetry/mod.rs @@ -3,6 +3,7 @@ pub mod command; use std::fmt; use std::future::Future; use std::io; +use std::iter::Peekable; use std::path::{Path, PathBuf}; use crate::services::default_paths::enclosing_repository_root; @@ -34,15 +35,15 @@ const USER_OWNED_OTEL_KEYS: [&str; 4] = [ const CONFIG_OPTIONS: [&str; 2] = ["-c", "--config"]; const PROFILE_OPTIONS: [&str; 2] = ["-p", "--profile"]; const DIRECTORY_OPTIONS: [&str; 2] = ["-C", "--cd"]; -const OTHER_VALUE_OPTIONS: [&str; 16] = [ +const IMAGE_OPTIONS: [&str; 2] = ["-i", "--image"]; +const UNSUPPORTED_OPTIONS: [&str; 3] = ["--remote", "--remote-auth-token-env", "--worktree"]; +const OTHER_VALUE_OPTIONS: [&str; 14] = [ "-m", "--model", "-s", "--sandbox", "-a", "--ask-for-approval", - "-i", - "--image", "--enable", "--disable", "--local-provider", @@ -69,7 +70,7 @@ const HELP_OR_VERSION_OPTIONS: [&str; 4] = ["-h", "--help", "-V", "--version"]; const EXEC_SUBCOMMANDS: [&str; 2] = ["exec", "e"]; const RESUME_SUBCOMMAND: &str = "resume"; const FORK_SUBCOMMAND: &str = "fork"; -const SESSIONLESS_SUBCOMMANDS: [&str; 9] = [ +const SESSIONLESS_SUBCOMMANDS: &[&str] = &[ "login", "logout", "completion", @@ -78,16 +79,31 @@ const SESSIONLESS_SUBCOMMANDS: [&str; 9] = [ "a", "sandbox", "debug", - "help", + "update", + "doctor", + "plugin", + "archive", + "unarchive", + "delete", + "migrate-rollouts", + "migrate-nfs-db", + "git-credential", + "execpolicy", ]; -const UNSUPPORTED_SUBCOMMANDS: [&str; 7] = [ +const UNSUPPORTED_SUBCOMMANDS: &[&str] = &[ + "agents", + "app", "app-server", "exec-server", "remote-control", "cloud", + "cloud-tasks", "mcp", "mcp-server", "review", + "queue", + "responses-api-proxy", + "tcp-tunnel", ]; #[derive(Clone, Debug, Eq, PartialEq)] @@ -100,8 +116,10 @@ pub(crate) enum LaunchMode { pub(crate) enum PlainLaunchReason { Sessionless, ResumeWithoutDirectory, + InteractiveResume, InteractiveFork, UnsupportedSubcommand(String), + UnsupportedOption(&'static str), UnrecognizedOption(String), NotRepository, TelemetryDisabled, @@ -118,12 +136,18 @@ impl PlainLaunchReason { "resume needs an explicit `-C ` to attribute the session to a repository" .to_string() } + Self::InteractiveResume => { + "interactive resume has no verified repository attribution".to_string() + } Self::InteractiveFork => { "interactive fork chooses its working directory after launch".to_string() } Self::UnsupportedSubcommand(subcommand) => { format!("`{subcommand}` is not a supported telemetry launch mode") } + Self::UnsupportedOption(option) => { + format!("`{option}` is not supported with SCE native telemetry") + } Self::UnrecognizedOption(option) => { format!("unrecognized Codex option `{option}`") } @@ -218,64 +242,72 @@ impl LaunchContext { } pub(crate) fn classify_launch(args: &[String]) -> LaunchMode { - let mut tokens = args.iter().map(String::as_str); + let mut tokens = args.iter().map(String::as_str).peekable(); let mut directory = None; - let mut in_exec = false; + let mut command = LaunchCommand::Interactive; while let Some(token) = tokens.next() { if token == "--" { break; } - match read_option(token, &mut tokens) { + let option_name = token.split_once('=').map_or(token, |(name, _)| name); + if let Some(option) = UNSUPPORTED_OPTIONS + .iter() + .copied() + .find(|option| *option == option_name) + { + return LaunchMode::Plain(PlainLaunchReason::UnsupportedOption(option)); + } + match read_option(token, &mut tokens, command) { OptionToken::Directory(value) => directory = Some(PathBuf::from(value)), OptionToken::Other => {} OptionToken::HelpOrVersion => return LaunchMode::Plain(PlainLaunchReason::Sessionless), OptionToken::Unrecognized => { return LaunchMode::Plain(PlainLaunchReason::UnrecognizedOption(token.to_string())) } - OptionToken::Positional => { - let subcommand = if in_exec { - format!("exec {token}") - } else { - token.to_string() - }; - match (in_exec, token) { - (false, _) if EXEC_SUBCOMMANDS.contains(&token) => in_exec = true, - (_, RESUME_SUBCOMMAND) => return classify_resume(directory, tokens), - (false, FORK_SUBCOMMAND) => { - return LaunchMode::Plain(PlainLaunchReason::InteractiveFork) - } - (_, "help") => return LaunchMode::Plain(PlainLaunchReason::Sessionless), - (false, _) if SESSIONLESS_SUBCOMMANDS.contains(&token) => { - return LaunchMode::Plain(PlainLaunchReason::Sessionless) - } - (_, _) if UNSUPPORTED_SUBCOMMANDS.contains(&token) => { - return LaunchMode::Plain(PlainLaunchReason::UnsupportedSubcommand( - subcommand, - )) - } - _ => return LaunchMode::Telemetry { directory }, + OptionToken::Positional => match (command, token) { + (LaunchCommand::Interactive, _) if EXEC_SUBCOMMANDS.contains(&token) => { + command = LaunchCommand::Exec; } - } + (LaunchCommand::Interactive, RESUME_SUBCOMMAND) => { + return LaunchMode::Plain(PlainLaunchReason::InteractiveResume); + } + (LaunchCommand::Interactive, FORK_SUBCOMMAND) => { + return LaunchMode::Plain(PlainLaunchReason::InteractiveFork) + } + (LaunchCommand::Exec, RESUME_SUBCOMMAND) => command = LaunchCommand::ExecResume, + (LaunchCommand::Exec, FORK_SUBCOMMAND) => command = LaunchCommand::ExecFork, + (LaunchCommand::Interactive | LaunchCommand::Exec, "help") => { + return LaunchMode::Plain(PlainLaunchReason::Sessionless) + } + (LaunchCommand::Interactive, _) if SESSIONLESS_SUBCOMMANDS.contains(&token) => { + return LaunchMode::Plain(PlainLaunchReason::Sessionless); + } + (LaunchCommand::Interactive, _) if UNSUPPORTED_SUBCOMMANDS.contains(&token) => { + return LaunchMode::Plain(PlainLaunchReason::UnsupportedSubcommand( + token.to_string(), + )); + } + (LaunchCommand::Exec, "review") => { + return LaunchMode::Plain(PlainLaunchReason::UnsupportedSubcommand( + "exec review".to_string(), + )); + } + _ => {} + }, } } + if command == LaunchCommand::ExecResume && directory.is_none() { + return LaunchMode::Plain(PlainLaunchReason::ResumeWithoutDirectory); + } LaunchMode::Telemetry { directory } } -fn classify_resume<'a>( - mut directory: Option, - mut tokens: impl Iterator, -) -> LaunchMode { - while let Some(token) = tokens.next() { - if let OptionToken::Directory(value) = read_option(token, &mut tokens) { - directory = Some(PathBuf::from(value)); - } - } - match directory { - Some(directory) => LaunchMode::Telemetry { - directory: Some(directory), - }, - None => LaunchMode::Plain(PlainLaunchReason::ResumeWithoutDirectory), - } +#[derive(Clone, Copy, Eq, PartialEq)] +enum LaunchCommand { + Interactive, + Exec, + ExecFork, + ExecResume, } enum OptionToken<'a> { @@ -286,38 +318,56 @@ enum OptionToken<'a> { Positional, } -fn read_option<'a>(token: &'a str, rest: &mut impl Iterator) -> OptionToken<'a> { +fn read_option<'a>( + token: &'a str, + rest: &mut Peekable>, + command: LaunchCommand, +) -> OptionToken<'a> { if token == "-" || !token.starts_with('-') { return OptionToken::Positional; } if HELP_OR_VERSION_OPTIONS.contains(&token) { return OptionToken::HelpOrVersion; } - if FLAG_OPTIONS.contains(&token) { + if FLAG_OPTIONS.contains(&token) + || (command == LaunchCommand::ExecResume && matches!(token, "--last" | "--all")) + { return OptionToken::Other; } - let Some((name, value)) = split_option(token, rest) else { + let Some((name, Some(value))) = split_option(token, rest) else { return OptionToken::Unrecognized; }; + let accepts_directory = matches!(command, LaunchCommand::Interactive | LaunchCommand::Exec); if DIRECTORY_OPTIONS.contains(&name) { - value.map_or(OptionToken::Other, OptionToken::Directory) - } else { - OptionToken::Other + return if accepts_directory && !value.is_empty() { + OptionToken::Directory(value) + } else { + OptionToken::Unrecognized + }; + } + if IMAGE_OPTIONS.contains(&name) && token == name && accepts_directory { + while rest.next_if(|value| is_option_value(value)).is_some() {} } + OptionToken::Other +} + +fn is_option_value(token: &str) -> bool { + token == "-" || !token.starts_with('-') } fn split_option<'a>( token: &'a str, - rest: &mut impl Iterator, + rest: &mut Peekable>, ) -> Option<(&'a str, Option<&'a str>)> { let is_value_option = |name: &str| { CONFIG_OPTIONS.contains(&name) || PROFILE_OPTIONS.contains(&name) || DIRECTORY_OPTIONS.contains(&name) + || IMAGE_OPTIONS.contains(&name) || OTHER_VALUE_OPTIONS.contains(&name) }; if is_value_option(token) { - return Some((token, rest.next())); + return Some((token, rest.next_if(|value| is_option_value(value)))); } if !token.starts_with("--") && token.len() > 2 && token.is_char_boundary(2) { let (name, value) = token.split_at(2); @@ -330,7 +380,7 @@ fn split_option<'a>( fn option_values<'a>(args: &'a [String], names: &[&str]) -> Vec<&'a str> { let mut values = Vec::new(); - let mut tokens = args.iter().map(String::as_str); + let mut tokens = args.iter().map(String::as_str).peekable(); while let Some(token) = tokens.next() { if token == "--" { break; @@ -497,6 +547,9 @@ fn shell_quote(value: &str) -> String { pub(crate) fn repository_root_for(launch_dir: &Path) -> Option { let launch_dir = std::fs::canonicalize(launch_dir).ok()?; + if !launch_dir.is_dir() { + return None; + } enclosing_repository_root(&launch_dir).map(Path::to_path_buf) } diff --git a/cli/src/services/codex_telemetry/tests.rs b/cli/src/services/codex_telemetry/tests.rs index 00bf2f927..205a6b9cc 100644 --- a/cli/src/services/codex_telemetry/tests.rs +++ b/cli/src/services/codex_telemetry/tests.rs @@ -37,6 +37,16 @@ fn codex_telemetry_classifies_new_sessions_exec_and_exec_fork_as_telemetry_modes ), (vec!["--cd=/work/b"], telemetry(Some("/work/b"))), (vec!["-C/work/b", "prompt"], telemetry(Some("/work/b"))), + ( + vec!["exec", "prompt", "--cd=/work/b"], + telemetry(Some("/work/b")), + ), + ( + vec!["-C", "/work/a", "exec", "-C", "/work/b", "fork", "session"], + telemetry(Some("/work/b")), + ), + (vec!["exec", "-i", "a.png", "resume"], telemetry(None)), + (vec!["exec", "fork", "help", "review"], telemetry(None)), (vec!["-m", "resume"], telemetry(None)), (vec!["-c", "model=fork", "prompt"], telemetry(None)), (vec!["--", "--help"], telemetry(None)), @@ -46,15 +56,15 @@ fn codex_telemetry_classifies_new_sessions_exec_and_exec_fork_as_telemetry_modes } #[test] -fn codex_telemetry_requires_explicit_directory_for_resume() { +fn codex_telemetry_requires_explicit_directory_before_exec_resume() { for (argv, expected) in [ ( vec!["resume", "019a-session"], - plain(PlainLaunchReason::ResumeWithoutDirectory), + plain(PlainLaunchReason::InteractiveResume), ), ( vec!["resume", "--last"], - plain(PlainLaunchReason::ResumeWithoutDirectory), + plain(PlainLaunchReason::InteractiveResume), ), ( vec!["exec", "resume", "019a-session", "prompt"], @@ -62,16 +72,47 @@ fn codex_telemetry_requires_explicit_directory_for_resume() { ), ( vec!["resume", "019a-session", "-C", "/work/a"], - telemetry(Some("/work/a")), + plain(PlainLaunchReason::InteractiveResume), ), ( vec!["-C", "/work/a", "resume", "019a-session"], + plain(PlainLaunchReason::InteractiveResume), + ), + ( + vec!["exec", "--cd", "/work/a", "resume", "019a-session"], + telemetry(Some("/work/a")), + ), + ( + vec!["-C", "/work/a", "exec", "resume", "--last"], telemetry(Some("/work/a")), ), ( vec!["exec", "resume", "--cd", "/work/a", "019a-session"], + plain(PlainLaunchReason::UnrecognizedOption("--cd".into())), + ), + ( + vec!["exec", "resume", "019a-session", "--", "-C/work/b"], + plain(PlainLaunchReason::ResumeWithoutDirectory), + ), + ( + vec![ + "exec", + "-C/work/a", + "resume", + "019a-session", + "--", + "-C/work/b", + ], telemetry(Some("/work/a")), ), + ( + vec!["exec", "-ia.png", "resume", "019a-session"], + plain(PlainLaunchReason::ResumeWithoutDirectory), + ), + ( + vec!["exec", "prompt", "resume", "019a-session"], + plain(PlainLaunchReason::ResumeWithoutDirectory), + ), ] { assert_eq!(classify_launch(&args(&argv)), expected, "{argv:?}"); } @@ -116,9 +157,34 @@ fn codex_telemetry_launches_unproven_and_sessionless_modes_without_telemetry() { "--brand-new=value".into(), )), ), + ( + vec!["prompt", "--remote", "unix://"], + plain(PlainLaunchReason::UnsupportedOption("--remote")), + ), + ( + vec!["exec", "fork", "session", "--worktree"], + plain(PlainLaunchReason::UnsupportedOption("--worktree")), + ), + ( + vec!["exec", "-C/work/a", "resume", "session", "--remote=unix://"], + plain(PlainLaunchReason::UnsupportedOption("--remote")), + ), + ( + vec!["exec", "-C/work/a", "resume", "session", "--unknown"], + plain(PlainLaunchReason::UnrecognizedOption("--unknown".into())), + ), + ( + vec!["prompt", "agents"], + plain(PlainLaunchReason::UnsupportedSubcommand("agents".into())), + ), (vec!["login"], plain(PlainLaunchReason::Sessionless)), + (vec!["doctor"], plain(PlainLaunchReason::Sessionless)), (vec!["--help"], plain(PlainLaunchReason::Sessionless)), (vec!["exec", "-h"], plain(PlainLaunchReason::Sessionless)), + ( + vec!["exec", "fork", "--help"], + plain(PlainLaunchReason::Sessionless), + ), (vec!["--version"], plain(PlainLaunchReason::Sessionless)), ] { assert_eq!(classify_launch(&args(&argv)), expected, "{argv:?}"); @@ -543,7 +609,7 @@ fn codex_telemetry_plan_prepends_overrides_for_the_resolved_repository() { ); let resumed = plan( - &["resume", "019a-session", "-C", "../second"], + &["exec", "-C", "../second", "resume", "019a-session"], &repos.root, &context_in(&repos.first), &files, @@ -641,6 +707,20 @@ fn codex_telemetry_plan_forwards_arguments_unchanged_when_telemetry_is_skipped() assert!(resume.plan.notice.is_some()); assert_eq!(resume.policy_checked, None); + let fork = ["exec", "fork", "session", "--worktree"]; + let unproven = plan( + &fork, + &repos.root, + &context_in(&repos.first), + &clean, + true, + true, + ); + assert_eq!(unproven.plan.argv, args(&fork)); + assert!(unproven.plan.notice.is_some()); + assert_eq!(unproven.policy_checked, None); + assert_eq!(unproven.authorized_for, None); + let help = plan( &["--help"], &repos.root, diff --git a/cli/src/services/parse/command_runtime.rs b/cli/src/services/parse/command_runtime.rs index 6f9db1bdc..0b9b2fe0b 100644 --- a/cli/src/services/parse/command_runtime.rs +++ b/cli/src/services/parse/command_runtime.rs @@ -36,10 +36,14 @@ where Err(error) => return handle_clap_error(&args_vec, &error), }; - let Some(command) = cli.command else { + let Some(mut command) = cli.command else { return Ok(help_command()); }; + if let cli_schema::Commands::Codex { args } = &mut command { + // Clap consumes a leading `--`, which belongs to Codex. + *args = args_vec.into_iter().skip(2).collect(); + } convert_clap_command(command) } @@ -587,6 +591,23 @@ mod tests { ); } + #[test] + fn codex_preserves_argument_terminators() { + for args in [ + &["--", "--help"][..], + &["exec", "resume", "--", "-C/work"][..], + ] { + let argv = ["sce", "codex"] + .into_iter() + .chain(args.iter().copied()) + .collect::>(); + let RuntimeCommand::Codex(command) = parse(&argv) else { + panic!("expected Codex launcher"); + }; + assert_eq!(command.args, args); + } + } + #[test] fn sync_parses_to_sync_request_with_default_text_format() { let command = parse(&["sce", "sync"]); diff --git a/context/architecture.md b/context/architecture.md index 4377f14ab..317f47727 100644 --- a/context/architecture.md +++ b/context/architecture.md @@ -56,7 +56,7 @@ The repository includes a new placeholder Rust binary crate at `cli/`. - `cli/src/services/managed_telemetry.rs` (+ `managed_telemetry/trace_export.rs`, `managed_telemetry/log_export.rs`) owns hardcoded managed OTLP defaults, credential-backed runtime telemetry selection from the encrypted auth DB, and bounded fail-open OTLP/HTTP protobuf export of `sce.command` spans (or one `sce.hook` span, with `sce.mutation_scope`/`sce.git_snapshot`/`sce.persistence` operation children opened through `trace_export::in_child_span` at the Claude and Codex adapter seams and in `mutation_trace::runtime`, for Claude-invoked hooks and the two Codex hook subcommands admitted by `managed_span_kind` in `cli/src/app.rs`; Codex hook spans are always roots) and allowlisted `Logger` events to the pinned canonical collector (metrics endpoint reserved, not exported); see `context/sce/cli-observability-contract.md`. - `cli/src/services/codex_telemetry/` owns the public `sce codex` launcher: invocation-mode classification, Codex OTEL conflict detection, and process-local `-c` overrides that run the hidden header helper with `--repo` and pin Codex traces and metrics to the managed endpoint before it `exec`s `codex`; it never writes Codex config or initializes managed exporter telemetry. See `context/sce/codex-native-telemetry-launcher.md`. - `cli/src/services/observability.rs` no longer owns duplicate log enums or parsing helpers; it consumes the canonical primitive seam from `cli/src/services/config/mod.rs` and stays focused on concrete `Logger` behavior plus the `NoopTelemetry`-backed telemetry capability boundary. -- `cli/src/cli_schema.rs` is now the canonical owner for top-level command metadata for the real clap-backed command set (`auth`, `config`, `setup`, `doctor`, `hooks`, `policy`, `sync`, `version`, `completion`), including the slim top-level help purpose text and per-command visibility on `sce`, `sce help`, and `sce --help`; `cli/src/command_surface.rs` remains the custom top-level help renderer and known-command classifier, adding the synthetic `help` row plus the ASCII banner while consuming that shared metadata instead of maintaining a parallel command catalog. +- `cli/src/cli_schema.rs` is now the canonical owner for top-level command metadata for the real clap-backed command set (`auth`, `codex`, `config`, `setup`, `doctor`, `hooks`, `policy`, `sync`, `version`, `completion`), including the slim top-level help purpose text and per-command visibility on `sce`, `sce help`, and `sce --help`; `cli/src/command_surface.rs` remains the custom top-level help renderer and known-command classifier, adding the synthetic `help` row plus the ASCII banner while consuming that shared metadata instead of maintaining a parallel command catalog. - `cli/src/services/default_paths.rs` is the canonical production path catalog for the CLI: it resolves config/state/cache roots with platform-aware XDG or `dirs` fallbacks through an internal `roots` seam, exposes named default paths for current persisted artifacts and database/log files (global config, auth tokens, auth DB, local DB, default observability log directory, and the sole Agent Trace DB path helper `agent_trace_db_path_for_repository` under `repos//agent-trace.db`; the former global-sentinel and per-checkout Agent Trace path helpers were removed by the `retire-legacy-agent-trace-db` plan), and owns canonical repo-relative, embedded-asset, install, hook, and context-path accessors so non-test production path definitions have one shared owner. Compile-time generated payload paths are owned by `build.rs` under `OUT_DIR`, not by the default-path catalog. Current production consumers such as config discovery, observability config resolution, doctor reporting, setup/install flows, database adapters, checkout identity, Agent Trace storage resolution, and local hook runtime path resolution consume this shared catalog rather than defining owned path literals in their own modules. - `cli/src/services/agent_trace.rs` is the Rust CLI owner for the SCE web base URL (`SCE_WEB_BASE_URL`) and exposes helpers for SCE-owned URL construction: Agent Trace conversation lookup URLs, persisted Agent Trace trace URLs, Agent Trace session URLs, and setup-created config schema URLs. Production Rust code should consume those helpers instead of repeating `sce.crocoder.dev` literals. The config resolver separately owns the `control_plane_base_url` runtime seam, whose baked `sce sync` default is `https://sce.crocoderlab.dev`; this control-plane host is not a web URL or schema owner. - `cli/src/services/config/mod.rs` is the config service facade and `sce config` orchestration surface (`show`, `validate`, `--help`), with bare `sce config` routed by `cli/src/app.rs` to the same help payload as `sce config --help`. Focused submodules own the implementation slices: `types.rs` owns shared config/runtime primitives, `schema.rs` owns generated schema embedding plus typed file parsing, `schema_declaration.rs` owns typed `$schema` release-series classification and the actionable `/$schema` validation messages, `policy.rs` owns bash-policy semantic validation plus policy-specific formatting and runtime preset-catalog access for the Rust evaluator, `resolver.rs` owns deterministic config-file discovery, file-layer merging, explicit value precedence (`flags > env > config file > defaults` where flag-backed), shared auth-key resolution, observability-runtime resolution, attribution-hooks runtime gate and `agent_trace.auto_sync` resolution, database-retry config resolution and `DATABASE_RETRY_CONFIG` `OnceLock` initialization, default-discovered invalid-file degradation, strict invalid-discovered-layer errors for Agent Trace storage, and explicit-path fatal errors for `--config` / `SCE_CONFIG_FILE`, and private `render.rs` owns `sce config show` / `sce config validate` text and JSON output construction plus rendering-specific display-value helpers. The facade preserves existing `services::config` imports for startup/auth/hooks callers while delegating command execution to resolution plus rendering submodules. diff --git a/context/cli/access-policy.md b/context/cli/access-policy.md index cb372fdf2..7b5165248 100644 --- a/context/cli/access-policy.md +++ b/context/cli/access-policy.md @@ -127,7 +127,7 @@ Setup then enforces the re-resolved mode with a login step: it never logs in und ## Enforcement -- **Managed telemetry startup** (commands and admitted Claude hooks): `cli/src/app.rs` takes `telemetry_enabled()` from the startup `ResolvedObservabilityRuntimeConfig`. When telemetry is not `Enabled`, `RuntimeTelemetry::resolve` returns Noop with fallback reason `disabled_by_config` (logged at `debug`). This happens before `auth.db` is opened or the credential store is touched. See [telemetry credential](../sce/telemetry-credential.md). +- **Managed telemetry startup** (commands and admitted Claude and Codex hooks) uses `telemetry_enabled()` from the startup `ResolvedObservabilityRuntimeConfig`. When policy disables telemetry, `RuntimeTelemetry::resolve` selects Noop before opening `auth.db` or touching the credential store. It records `disabled_by_config` at `debug`. See [telemetry credential](../sce/telemetry-credential.md). - **`sce doctor` managed-telemetry health:** doctor resolves the policy for the inspected repository root once. A resolution failure counts as `invalid_config`. The row reports the effective state (`Managed telemetry: enabled for this repository` or `Managed telemetry: disabled (reason: )`) and the deciding layer, and JSON adds `managed_telemetry.policy`. When telemetry is not `Enabled`, the health is `disabled_by_config`. Doctor may then check whether `auth.db` exists (for the opt-in note), but never opens it or touches the credential store. See [telemetry credential: doctor health check](../sce/telemetry-credential.md#doctor-health-check). - **`sce doctor` SCE login row:** under effective `mandatory`, doctor confirms the saved WorkOS session non-interactively with a deadline and without creating or migrating `auth.db`. A current access token counts as logged in. An expired one is refreshed against WorkOS (the only case where doctor makes a network request) and the refreshed tokens are saved. A rejected refresh fails, and its problem summary names the WorkOS reason. WorkOS unreachable keeps the session logged in for 24h after its last confirmation. Login status is independent of telemetry credentials and repository bindings. Unreadable storage, outdated schema, lookup failures, and WorkOS unreachable past the grace report `unavailable` with a warning and a reason instead of claiming logout. A missing login is a blocking `[FAIL] SCE login` that names the deciding config file, with the fix `Run 'sce auth login'.`. Other modes skip the lookup. Local SCE features are never blocked. See [doctor human text: SCE login row](../sce/doctor-human-text-contract.md#sce-login-row). - **Claude session login notice:** the Claude-only `sce-info` hooks module (`config/lib/sce-info/hooks/register.ts`) owns it. On an interactive `session.start`, after Claude's own start step, it first probes `sce --version` (5 s timeout); when that cannot start, it logs the install guidance described in [patterns](../patterns.md) and skips doctor. Otherwise it runs `sce doctor --format json` in the session's working directory. When `sce_login.state` is `not_logged_in` (effective `mandatory` without a saved usable or renewable WorkOS session), it writes the single transcript line `Login required for this repository. Run 'sce auth login'.` through `$.ui.log`. A doctor command that cannot run, unparseable output, any other login state, or a non-interactive session shows nothing. The notice never fails or blocks the session. `sce hooks claude-model-state` emits no notice. OpenCode, Pi, and Codex sessions get no notice. diff --git a/context/cli/cli-command-surface.md b/context/cli/cli-command-surface.md index d655adf14..0c7db2b3d 100644 --- a/context/cli/cli-command-surface.md +++ b/context/cli/cli-command-surface.md @@ -111,7 +111,7 @@ An interactive `setup` run instead resolves the selection through an `inquire` m `setup` now executes end-to-end and prints deterministic completion details including selected target(s) and per-target install count. `setup` with a selected Claude target also merges Claude-native OpenTelemetry settings into user-level Claude `settings.json` (`$CLAUDE_CONFIG_DIR` else `~/.claude`) and prints a fixed telemetry line (configured, configured but not ready for this repository when interactive setup finds no valid credential bound to it, configured with repository authorization not checked for non-interactive and target-flag runs, which never read authentication storage, skipped on conflict/malformed JSON, or skipped because the effective access policy does not enable telemetry, in which case settings are untouched) without failing repository setup; see [telemetry credential](../sce/telemetry-credential.md). The hidden auth helper is intentionally not part of the public command listing. `doctor` now executes end-to-end with explicit diagnosis and repair-intent surfaces: `sce doctor` stays read-only and `sce doctor --fix` selects repair-intent mode. The former Agent Trace database inspection routes are unavailable; doctor owns repository-scoped Agent Trace DB health (checkout-identity diagnostics were removed by the `remove-checkout-id` plan; see `context/cli/checkout-identity.md`). The current `doctor` runtime aggregates `ServiceLifecycle::diagnose` and `ServiceLifecycle::fix` calls across all registered service providers (`config`, `local_db`, `auth_db`, `agent_trace_db`, `hooks`) plus integration checks, covering state-root resolution, global and repo-local `sce/config.json` readability/schema validation, local DB and repository-scoped Agent Trace DB path/health, DB-parent readiness barriers, the repo hook rollout slice when a repository target is detected, and post-commit Agent Trace auto-sync readiness derived from canonical managed-block currency plus resolved configuration. The readiness fact reports enabled/current, explicit disabled, not-ready, and not-applicable states in text and JSON without launching synchronization; Claude's inventory is only `Plugins`, `Commands`, and `Skills`, while OpenCode retains `Agents`. Fix mode delegates to each provider's `fix` implementation, which reuses the canonical setup hook install flow to repair missing/stale/non-executable required hooks and missing hooks directories, and it can bootstrap missing canonical database parent directories when the resolved paths match canonical owned locations. -`sce codex [codex arguments...]` is a public launcher that runs Codex CLI with Codex-native OpenTelemetry export pointed at the managed collector for the launch repository. It forwards every argument to `codex` verbatim (including `--help`), prepends process-local `-c` overrides only for repository-safe invocation modes when telemetry is enabled, authorized, and unconflicted, and otherwise launches Codex unchanged with a one-line stderr reason. See [Codex native telemetry launcher](../sce/codex-native-telemetry-launcher.md). The hidden `sce auth telemetry-headers` helper and its hidden `--repo` flag stay absent from public help. +`sce codex [codex arguments...]` launches Codex CLI and forwards all arguments, including `--help`. For supported modes with enabled, authorized telemetry and compatible config, it prepends process-local overrides that send native traces and metrics to the managed collector for the launch repository. Other launches use the original arguments. A skip notice explains conflicts and other skips, except for sessionless launches and policy-disabled telemetry. See [Codex native telemetry launcher](../sce/codex-native-telemetry-launcher.md). `sce sync [--format text|json]` is the implemented user-invocable synchronization command: it synchronizes the current repository's Agent Trace DB with the control-plane ingestion API; local DB and Agent Trace DB bootstrap continue to happen through `setup`, and DB health/repair continues to happen through `doctor`. Under `auth.mode: disabled`, `sce sync` fails with `auth.disabled_by_config` before storage or credential access (see [effective access policy](access-policy.md#enforcement)). See [agent-trace-sync-command.md](agent-trace-sync-command.md) and [sync-command.md](sync-command.md). diff --git a/context/cli/codex-mutation-scope-integration.md b/context/cli/codex-mutation-scope-integration.md index 30084c317..17eecf318 100644 --- a/context/cli/codex-mutation-scope-integration.md +++ b/context/cli/codex-mutation-scope-integration.md @@ -209,20 +209,13 @@ are verified against the supported upstream event names. ## Existing Codex evidence remains separate -The existing `sce hooks codex` behavior is additive and unchanged: it captures -`UserPromptSubmit`/`Stop` conversation rows, applies the Bash policy, and -captures `PostToolUse(apply_patch)` diff evidence. The mutation-scope adapter -writes only through the generic mutation runtime and only to `mutation_trace_*` -tables. It does not write `diff_traces`, `post_commit_patch_intersections`, -`agent_traces`, `messages`, or `parts`, and it does not fold the complementary -apply-patch evidence pipeline into mutation-scope storage. - -Codex has no Codex-managed background execution surface in the supported -`codex exec` path. A foreground Bash command can still spawn a self-detaching -descendant that writes after `PostToolUse`; the adapter does not supervise -processes, inspect process groups, poll for staleness, or treat `PostToolUse` as -proof that every descendant stopped mutating. Such writes are outside the -closed tracked interval and remain conservatively unscoped. +The existing `sce hooks codex` behavior is additive and unchanged: it captures `UserPromptSubmit`/`Stop` conversation rows, applies the Bash policy, and captures `PostToolUse(apply_patch)` diff evidence. The mutation-scope adapter writes only through the generic mutation runtime and only to `mutation_trace_*` tables. It does not write `diff_traces`, `post_commit_patch_intersections`, `agent_traces`, `messages`, or `parts`, and it does not fold the complementary apply-patch evidence pipeline into mutation-scope storage. + +Codex has no Codex-managed background execution surface in the supported `codex exec` path. A foreground Bash command can still spawn a self-detaching descendant that writes after `PostToolUse`; the adapter does not supervise processes, inspect process groups, poll for staleness, or treat `PostToolUse` as proof that every descendant stopped mutating. Such writes are outside the closed tracked interval and remain conservatively unscoped. + +## Managed trace spans + +When repository telemetry is authorized, each `sce hooks codex-mutation-scope` process emits one independent `sce.hook` root. The adapter wraps each coordinate or abandon call in `sce.mutation_scope`. The coordinator emits `sce.git_snapshot` and `sce.persistence` only when it executes those operations. An event that takes no adapter action emits only the hook span. Export failure does not change the adapter's admission or recovery result. The [observability contract](../sce/cli-observability-contract.md#managed-trace-export) defines the span attributes. The [live check](../sce/codex-native-telemetry-contract.md#live-verification) records the hierarchy for a tracked `PostToolUse(apply_patch)` event. ## Unsupported / coverage boundary @@ -240,13 +233,7 @@ that excluded tools are read-only, harmless, or immediately detectable. ## Verification evidence -The adapter is exercised through real temporary Git repositories, real -repository Agent Trace databases, and the production entrypoint. Regressions -cover write-ahead admission, duplicate and reused identities, tracked -success/failure, cleanup signals, linked worktrees, MCP pass-through, -mutate-then-error and parallel MCP, tracked-tool plus MCP overlap, denial -recovery, crash points, both directions of the boundary-aware attribution rule, -and scope provenance for both tracked tools. +The adapter is exercised through real temporary Git repositories, real repository Agent Trace databases, and the production entrypoint. Regressions cover write-ahead admission, duplicate and reused identities, tracked success/failure, cleanup signals, linked worktrees, MCP pass-through, mutate-then-error and parallel MCP, tracked-tool plus MCP overlap, denial recovery, crash points, both directions of the boundary-aware attribution rule, and scope provenance for both tracked tools. The frozen protocol/Quint/runtime baseline and the Agent Trace SQL/schema boundary remain unchanged after the accepted D14 follow-up: diff --git a/context/cli/execution-glossary.md b/context/cli/execution-glossary.md index 26727cea7..41b28b633 100644 --- a/context/cli/execution-glossary.md +++ b/context/cli/execution-glossary.md @@ -3,9 +3,20 @@ - `command loop`: The `clap` derive-based parser + dispatcher in `cli/src/cli_schema.rs`, `cli/src/services/parse/command_runtime.rs`, and `cli/src/app.rs` that routes `help`, `config`, `setup`, `doctor`, `auth`, `hooks`, `policy`, `sync`, `version`, and `completion`, executes implemented command flows, emits command-local help payloads for supported subcommand trees, resolves unknown command paths to the longest valid parent's help surface, and returns deterministic actionable errors for unknown options and other invalid invocation. - `RuntimeCommand seam`: Internal static command-execution abstraction in `cli/src/services/command_registry.rs` where clap-parsed commands are represented as a `RuntimeCommand` enum with variants for `Help`, `HelpText`, `Version`, `Completion`, `Auth`, `Config`, `Setup`, `Doctor`, `Hooks`, `Policy`, and `Sync`. The enum owns `name()` and async `execute(...)` dispatch, directly awaited under the application-level multi-thread Tokio runtime (distinct from retained DB-owned runtimes), delegating behavior to service-owned command payload structs while avoiding boxed `dyn RuntimeCommand` handles. Parsed request construction lives in `cli/src/services/parse/command_runtime.rs` when user-provided options or subcommands are required. - `logger trait boundary`: `services::observability::traits::Logger` mirrors the current observability logger API (`info`, `debug`, `warn`, `error`, `log_cli_error`) for generic command/runtime bounds and tests, with each method accepting `Option<&str>` session context for file routing; the concrete `services::observability::Logger` implements it and `NoopLogger` remains available for side-effect-free tests. -- `telemetry trait boundary`: `services::observability::traits::Telemetry` defines the `with_default_subscriber` command-lifecycle capability used by generic app-runtime bounds and tests. The generic async callback deliberately makes this capability non-object-safe and statically selected through `HasTelemetry::Telemetry`. `NoopTelemetry` awaits the action once and installs no subscriber; production `RuntimeTelemetry` selects it unless a valid unexpired telemetry credential is stored, in which case managed telemetry attaches its subscriber to the command future so every poll is scoped (a thread-local guard across await is insufficient). Managed telemetry exports OTLP/HTTP protobuf traces and logs to the hardcoded canonical collector, fail-open and with bounded shutdown after command output; hook invocations, `sce policy bash`, and `sce auth telemetry-headers` always use `NoopTelemetry`. -- `sce codex` launcher: The public command in `cli/src/services/codex_telemetry/` that `exec`s Codex CLI with process-local `-c` OTEL overrides for repository-safe invocation modes, or unchanged with a one-line reason otherwise ([launcher](../sce/codex-native-telemetry-launcher.md)). +- `telemetry trait boundary`: `services::observability::traits::Telemetry` defines the `with_default_subscriber` command-lifecycle capability used by generic app-runtime bounds and tests. The generic async callback deliberately makes this capability non-object-safe and statically selected through `HasTelemetry::Telemetry`. `NoopTelemetry` awaits the action once and installs no subscriber; production `RuntimeTelemetry` selects it unless a valid unexpired telemetry credential is stored, in which case managed telemetry attaches its subscriber to the command future so every poll is scoped (a thread-local guard across await is insufficient). Managed telemetry exports OTLP/HTTP protobuf traces and logs to the hardcoded canonical collector, fail-open and with bounded shutdown after command output; admitted Claude and Codex hooks can use managed telemetry. The launcher and header helper use `NoopTelemetry`. +- `sce codex` launcher: The public command in `cli/src/services/codex_telemetry/` that `exec`s Codex CLI with process-local `-c` OTEL overrides for supported, authorized and unconflicted launches ([launcher](../sce/codex-native-telemetry-launcher.md)). - `Codex hook span kind`: `ManagedSpanKind::CodexHook`, the managed-trace kind for `sce hooks codex` and `sce hooks codex-mutation-scope`; it exports one root `sce.hook` span with `sce.agent=codex` and `sce.codex.*` correlation attributes and never adopts `TRACEPARENT` ([observability](../sce/cli-observability-contract.md#managed-trace-export)). - `AppContext`: Generic borrowed dependency view in `cli/src/app.rs` passed through static command dispatch. `AppRuntime` owns the concrete production logger, `RuntimeTelemetry` (`NoopTelemetry` or managed export), filesystem, and git implementations; `AppContext` stores references to those dependencies plus an optional `repo_root: Option`, not owned `Arc` trait objects. Because it borrows from `AppRuntime`, `AppContext` is command-scoped: borrowing across directly awaited execution is safe while the owner lives, but detached work cannot retain that borrowed view. No new `Send`, `Sync`, or `'static` command bounds are required. The `repo_root` field is `None` at startup and command paths can derive a repo-root-scoped context with `AppContext::with_repo_root(...)` / `ContextWithRepoRoot`, preserving the borrowed runtime dependencies while attaching the resolved root. Narrow accessor traits (`HasLogger`, `HasTelemetry`, `HasFs`, `HasGit`, `HasRepoRoot`) let command and lifecycle call sites express capability requirements without depending on the full production context type; logger/telemetry/fs/git accessors use associated concrete capability types and return `&Self::{Capability}` rather than object-erased `&dyn ...` values. +## Observability terms + +- `log_to_file`: Flat SCE config-file boolean controlling file-log emission and normal logger `stderr` routing. It defaults to `true`, is surfaced with source metadata by `sce config show`, and resolves independently from `log_dir`; enabled file logging routes normal logger records only to the file, while disabled file logging routes only error-level logger records to `stderr`. An omitted `log_dir` uses the default location, while an explicitly empty config value remains invalid. See [CLI observability contract](../sce/cli-observability-contract.md). +- **Telemetry credential** — The Control Plane issues an OpenBao token and accessor for managed OTLP export. SCE stores them in the encrypted auth DB and uses the token as the bearer. The credential must be unexpired and authorized for the repository. Logout deletes the local credential. [Credential contract](../sce/telemetry-credential.md). +- **`sce.hook` span** — The process span for an admitted Claude or Codex hook. It carries the agent, outcome, and available event, tool, and correlation IDs. The Claude hook adopts valid upstream context. SCE starts an independent trace for each Codex hook. SCE emits child spans when their operations run. [Observability contract](../sce/cli-observability-contract.md#managed-trace-export). +- `sce observability baseline`: App-runtime logging contract in `cli/src/services/observability.rs` and `cli/src/app.rs` with config-resolved observability inputs, deterministic env-over-config-file-over-default precedence for non-flag logging keys, default-backed `log_dir` / `SCE_LOG_DIR` file routing by machine-local date plus optional session filename partitioning, creation-triggered retention of direct regular `*.log` files to 10 entries, stable lifecycle `event_id` values, tracing for all emitted records, normal logger records routed only to files when `log_to_file=true`, and only error-level logger records routed to `stderr` when `log_to_file=false`. +- `SCE_LOG_LEVEL`: Optional runtime env key for `sce` observability threshold; allowed values are `error`, `warn`, `info`, and `debug`, defaulting to `error` when unset. +- `SCE_LOG_FORMAT`: Optional runtime env key for `sce` observability record format; allowed values are `text` and `json`, defaulting to `text` when unset. +- `SCE_LOG_DIR`: Optional runtime env key for `sce` observability log-directory configuration; when set, it overrides config-file `log_dir` and the `/sce/logs` default and must be non-empty. +- `log_file_retention_limit`: Flat top-level `sce/config.json` key validated as an integer with minimum `1`. It has config-file > default precedence only, defaults to `10`, merges global before local, appears in `sce config show` with provenance, and is carried by `ResolvedObservabilityRuntimeConfig`; the concrete logger stores the resolved value and uses it for primary and v2 creation-triggered cleanup. + See [application execution runtime](../architecture.md#application-execution-runtime), [capability traits](capability-traits.md), and [observability](../sce/cli-observability-contract.md). diff --git a/context/context-map.md b/context/context-map.md index 1c383bfa3..2268819f9 100644 --- a/context/context-map.md +++ b/context/context-map.md @@ -58,9 +58,9 @@ Feature/domain context: - `context/sce/cli-shell-completion-contract.md` (implemented `sce completion` contract for deterministic Bash/Zsh/Fish completion script generation) - `context/sce/claude-raw-hook-capture.md` (removed feature: the former `sce hooks claude-capture` raw-capture route and its supporting types, replaced by the active `diff-trace` and `conversation-trace` intakes) - `context/sce/claude-hook-trace-propagation.md` (probe evidence for Claude Code 2.1.301 command-hook trace context: `TRACEPARENT` names the `claude_code.interaction` span, not the tool span, and only when Claude tracing is active; hook-to-tool correlation by `tool_use_id`; `CLAUDECODE` + `CLAUDE_PROJECT_DIR` presence as the Claude hook-caller signal; T05 live Dash0 verification (doctor and session-boundary hook spans observed, parented tool-hook hierarchy unverified) and the opt-in live smoke procedure; the shipped `sce.hook` contract lives in `cli-observability-contract.md`, admission decision `context/decisions/2026-10-17-claude-hook-managed-trace-admission.md`) -- `context/sce/codex-native-telemetry-contract.md` (probe evidence for Codex CLI 0.172.0 native OTEL export: the `otel.headers_helper` invocation contract (runs from `CODEX_HOME` without repository context, timer-only refresh, export suspended on failure), `-c`/profile/user/requirements precedence and credential reach to unpinned exporters, attribution per invocation mode (`resume` without `-C` uses the stored session cwd), no current-span `TRACEPARENT` for command hooks, hook-to-native identifier mapping, observed token/cache/tool semantics and privacy controls, the decided launcher-plus-hook-span mechanism, and the Claude/Codex parity matrix; this is probe evidence and the decision record; shipped behavior is in `context/sce/codex-native-telemetry-launcher.md`) +- [Codex native telemetry contract](sce/codex-native-telemetry-contract.md) — Codex 0.172.0 probe evidence, live Dash0 checks, privacy controls, Claude/Codex parity, and Control Plane follow-ups. The [launcher reference](sce/codex-native-telemetry-launcher.md) describes invocation and config precedence. - `context/sce/codex-native-telemetry-launcher.md` (shipped `sce codex` launcher: invocation-mode classification (new interactive, `exec`, `exec fork`, resume only with `-C`), conflict detection over environment, caller `-c otel.*`, user, profile, and readable `/etc/codex` OTEL settings, process-local `-c` overrides that run `sce auth telemetry-headers --repo ` and pin traces and metrics to the managed endpoint with logs off, Unix `exec` preserving terminal, signals, and exit code, and residual limits) -- `context/sce/cli-observability-contract.md` (implemented config-backed runtime observability contract for the flat logging config-file shape with explicit config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` env-over-config-over-`/sce/logs` fallback, append-only local-date/session log file routing with a one-time complete-record `-v2.log` fallback on primary open/append/flush failure, creation-triggered retention of direct regular `*.log` files to 10 entries, reliable producer-native diff-trace/conversation-trace session routing and hook-specific non-duplicated Agent Trace DB-open error events, deterministic session filename sanitization, concrete `Logger` behavior plus the `NoopTelemetry`-backed telemetry capability boundary, logger and deliberately non-object-safe generic async telemetry boundaries with static capability dispatch and future-aware polling scope, AppContext observability wiring, generic `RunOutcome` final rendering, runtime-classified repeated telemetry action protection, operator-facing `sce config show` observability reporting, managed OTLP trace/log export (credential-gated, hardcoded canonical collector, Claude-only hook admission with one `sce.hook` span and correlation-only session/tool-use IDs, its `sce.mutation_scope`/`sce.git_snapshot`/`sce.persistence` operation child spans with a span-kind-specific export filter, allowlisted fields, bounded fail-open lifecycle, reserved metrics endpoint), and the trimmed `sce config validate` status-only validation surface) +- `context/sce/cli-observability-contract.md` (implemented config-backed runtime observability contract for the flat logging config-file shape with explicit config-file/default `log_to_file`, `log_dir` / `SCE_LOG_DIR` env-over-config-over-`/sce/logs` fallback, append-only local-date/session log file routing with a one-time complete-record `-v2.log` fallback on primary open/append/flush failure, creation-triggered retention of direct regular `*.log` files to 10 entries, reliable producer-native diff-trace/conversation-trace session routing and hook-specific non-duplicated Agent Trace DB-open error events, deterministic session filename sanitization, concrete `Logger` behavior plus the `NoopTelemetry`-backed telemetry capability boundary, logger and deliberately non-object-safe generic async telemetry boundaries with static capability dispatch and future-aware polling scope, AppContext observability wiring, generic `RunOutcome` final rendering, runtime-classified repeated telemetry action protection, operator-facing `sce config show` observability reporting, managed OTLP trace/log export (credential-gated, hardcoded canonical collector, Claude and Codex hook admission with one `sce.hook` span and correlation-only IDs, its `sce.mutation_scope`/`sce.git_snapshot`/`sce.persistence` operation child spans with a span-kind-specific export filter, allowlisted fields, bounded fail-open lifecycle, reserved metrics endpoint), and the trimmed `sce config validate` status-only validation surface) - `context/sce/shared-context-code-workflow.md` (canonical `/next-task` task-synchronization lifecycle and validation-only `/validate` lifecycle, package-local phase references with single-skill control flow, and the task-synchronization-scoped `sce-decision` sibling invocation with ADR reuse/blocker propagation) - `context/sce/shared-context-plan-workflow.md` (canonical `/change-to-plan` workflow, package-local context-load/plan-authoring/template references, clarification/readiness gate contract, and one-task/one-atomic-commit task slicing) - [Context workflow rules](sce/context-workflow-rules.md) (canonical bootstrap, ongoing context maintenance, task synchronization, hygiene, discoverability, and feature-existence rules) diff --git a/context/glossary.md b/context/glossary.md index 899bf14a1..3eb55861c 100644 --- a/context/glossary.md +++ b/context/glossary.md @@ -1,5 +1,5 @@ # Glossary -- CLI execution terminology: [command dispatch, runtime dependencies, telemetry, the `sce codex` launcher, and the Codex hook span kind](cli/execution-glossary.md). Auth mode, policy layer (user/repository), effective access policy, setup repository access preferences, and the `auth.disabled_by_config` rejection: [effective access policy](cli/access-policy.md). Setup login step and `auth.setup_login_required`: [setup login](sce/setup-repo-local-config-bootstrap.md#setup-login). +- CLI execution terminology: [command dispatch, runtime dependencies, logging, telemetry credentials, the `sce codex` launcher, and hook spans](cli/execution-glossary.md). Auth mode, policy layer (user/repository), effective access policy, setup repository access preferences, and the `auth.disabled_by_config` rejection: [effective access policy](cli/access-policy.md). Setup login step and `auth.setup_login_required`: [setup login](sce/setup-repo-local-config-bootstrap.md#setup-login). - `pkl-check-generated`: Flake app exposed as `nix run .#pkl-check-generated`; canonical ephemeral-generation check that rejects committed target/schema/mirror outputs, evaluates exact workflow metadata, the generated artifact contract, semantic layout/path/inventory/content/parity/observational checks, and the optional-workflow manifest's content against the catalog, requires the shared helper-composition rule and SCE-scoped workflow prohibitions, enforces ordered catalog-derived OpenCode skill permissions plus explicit-permission artifact integrity, rejects stale sibling-package references or unresolved internalization tokens in workflow entrypoint `SKILL.md` documents, proves contract failures through checked-in negative fixtures, and delegates deterministic generation plus payload/input inventories to the generated-input producer while preserving its established inventory report. - `repo-level verification preference`: Current repository guidance that contributor-facing validation/check flows should prefer `nix flake check`; direct Cargo verification commands are secondary and used only when explicitly requested or for narrow targeted debugging, while `cargo fmt` remains the explicit autofix path. Required quick checks after each completed task in this repo are `nix run .#pkl-check-generated` and `nix flake check`. - disposable plan lifecycle: Policy where `context/plans/` holds active execution artifacts only; completed plans are disposable and durable outcomes must be reflected in current-state context files and/or `context/decisions/`. @@ -68,7 +68,6 @@ - `cli cargo install contract`: Supported Cargo install surface for the `shared-context-engineering` crate, which installs the `sce` binary: crates.io (`cargo install shared-context-engineering --locked`) and local checkout (`./scripts/run-cli-cargo.sh install --path cli --locked`). Direct `cargo install --git` is unsupported because it has no repository pre-Cargo generation boundary. - `cli crates.io publication posture`: Current Cargo package posture in `cli/Cargo.toml` where crates.io-facing metadata is publication-ready for the `shared-context-engineering` crate, with crate-facing install guidance owned by `cli/README.md`. - `Nix performance recommendations`: Repo-local operator guidance in `AGENTS.md` covering optional user-level `~/.config/nix/nix.conf` tuning (`max-jobs = auto`, `cores = 0`) and the explicit root/admin-only boundary for `/etc/nix/nix.conf` `auto-optimise-store = true`. -- `log_to_file`: Flat SCE config-file boolean controlling file-log emission and normal logger `stderr` routing. It defaults to `true`, is surfaced with source metadata by `sce config show`, and resolves independently from `log_dir`; enabled file logging routes normal logger records only to the file, while disabled file logging routes only error-level logger records to `stderr`. An omitted `log_dir` uses the default location, while an explicitly empty config value remains invalid. See [CLI observability contract](sce/cli-observability-contract.md). - `sce` (CLI foundation): Rust binary crate at `cli/` with implemented auth command flows (`auth login|logout|whoami`) plus auth-local bare-command guidance (`sce auth`, `sce auth --help`), Control Plane `/me`-backed whoami profile output using flat email/name/role/permissions/organization labels, exact logged-out login guidance, implemented setup installation flow including lifecycle-aggregated local DB and Agent Trace DB bootstrap, implemented attribution-only `hooks` subcommand routing/validation entrypoints, and a fully implemented top-level `sce sync` command that synchronizes the current repository's Agent Trace DB with the control plane and renders the documented text/JSON output (see `context/cli/sync-command.md`). - `auth login stored-credential renewal`: The `sce auth login` behavior that first validates every stored credential through the existing non-forced token path, preserves valid credentials, refreshes expired credentials, and falls back to device authorization when credentials are absent or renewal fails. After WorkOS persistence, every successful fresh, valid-stored, or renewed login path issues and saves one replacement telemetry credential through the resolved Control Plane client when the effective access policy enables telemetry (otherwise provisioning reports `disabled`); provisioning is best effort and unavailable status retains successful WorkOS authentication. Renewal reports retain `login` labels in text and JSON; credential renewal is not exposed as a public subcommand. The auth command boundary treats missing-credential logout/whoami calls as successful state queries (except `whoami` under `auth.mode: mandatory`), classifies authenticated Control Plane failures as `UserError::NotAuthenticated`, token-storage plus `AuthError::Io`/`Storage` failures as `UserError::AuthStorageUnavailable` (`auth.storage_unavailable`), and approved user-facing rendering/prompt fallbacks as `UserError::UnexpectedFailure` (`general.unexpected_failure`); fixed catalog messages expose no storage or implementation details while technical sources remain available for structured observability, and remaining auth-command failures use `UnexpectedFailure` with preserved technical sources. - `command surface contract`: The current top-level command/help catalog split where `cli/src/cli_schema.rs` owns the real clap-backed command metadata (top-level purpose text plus help visibility for `auth`, `config`, `setup`, `doctor`, `hooks`, `policy`, `sync`, `version`, and `completion`) and `cli/src/command_surface.rs` consumes that catalog for the custom banner/help surface plus known-command classification, while still adding the synthetic `help` row. @@ -79,8 +78,6 @@ - `local Turso adapter`: Module in `cli/src/services/local_db/mod.rs` that defines `LocalDbSpec` and exposes `LocalDb` as a `TursoDb` alias. It resolves the canonical local DB path with `local_db_path()`, currently declares zero migrations, and inherits retry-backed `new()`, `execute()`, `query()`, and `query_map()` behavior from the shared generic adapter. - `encrypted Turso adapter`: Generic native async adapter seam in `cli/src/services/db/mod.rs` exposed as `EncryptedTursoDb`, structurally parallel to `TursoDb` and owning no Tokio runtime. Its constructor resolves the encryption key via `encryption_key::get_or_create_encryption_key(&db_path, db_name)`, which derives a Turso-compatible 64-character hex key from non-empty `SCE_AUTH_DB_ENCRYPTION_KEY` env-secret text before falling back to OS credential-store keyring get-or-create behavior; credential-store default registration is guarded by stable `OnceLock` plus an atomic in-progress flag so errors or panics leave initialization retryable without mutex poisoning. The adapter enables Turso local encryption with strict `aegis256` cipher selection through `turso::EncryptionOpts`, wraps encrypted local open/connect in the default DB connection-open retry policy, and runs embedded migrations after retry has produced a connection; execute, query, query_map, and migration operations are async and preserve `__sce_migrations` tracking parity. `open_existing_current_at` is its non-migrating existing-DB open, returning `ExistingDbOpen::{Missing, SchemaNotCurrent, Open}` and used only by telemetry readiness lookups. - `auth DB adapter`: Module in `cli/src/services/auth_db/mod.rs` that defines `AuthDbSpec` and exposes `AuthDb` as an `EncryptedTursoDb` alias. It resolves the canonical `/sce/auth.db` path with `auth_db_path()`, keeps encryption mandatory with `SCE_AUTH_DB_ENCRYPTION_KEY` env-secret precedence before OS keyring fallback and no plaintext mode, and embeds ordered auth migrations where baseline SQL creates `auth_credentials` without `user_id`, with `updated_at`, and a trigger that auto-refreshes `updated_at` on row updates. Auth runtime token-storage is now wired through `cli/src/services/token_storage.rs`, which persists tokens via the `auth_credentials` table in the encrypted auth DB instead of a JSON file. -- `telemetry credential`: Telemetry-only OpenBao token and accessor issued by the Control Plane `POST /auth/telemetry/credential`, stored as one fixed row in the encrypted auth DB `telemetry_credentials` table by `cli/src/services/telemetry_credential_storage.rs`, returned only while unexpired, removed by `sce auth logout`, not revoked server-side by local deletion, and used as the sole bearer secret for managed OTLP export (never the accessor); see `context/sce/telemetry-credential.md`. -- `sce.hook span`: The single root-of-process managed trace span a Claude-invoked SCE hook exports in place of `sce.command`, carrying `sce.agent=claude`, the hook event, tool name, outcome, and the Claude `session_id`/`tool_use_id` as correlation-only attributes. It is parented on a valid Claude-provided `TRACEPARENT` (the `claude_code.interaction` span, so it sits beside `claude_code.tool`) and is otherwise an independent root. Its only exported children are `sce.mutation_scope` (one per adapter seam call) and, beneath it, `sce.git_snapshot` and `sce.persistence`, each emitted only when that operation actually runs and carrying only `sce.outcome`. Admission is Claude-only (Claude-only hook subcommands by argv; shared hook subcommands and `sce policy bash` only with `CLAUDECODE` and `CLAUDE_PROJECT_DIR` present); see `context/sce/cli-observability-contract.md`. - `AuthDbLifecycle`: Lifecycle provider in `cli/src/services/auth_db/lifecycle.rs` that implements `ServiceLifecycle` for encrypted auth DB setup/doctor integration. `diagnose` collects auth DB path health problems, `fix` bootstraps missing auth DB parent directory, and `setup` calls `AuthDb::new()`. Registered as `LifecycleProvider::AuthDb` in the shared lifecycle catalog. - `agent trace DB adapter`: Modules under `cli/src/services/agent_trace_db/` that define the sole repository-scoped `RepositoryAgentTraceDb = TursoDb` adapter (the checkout-scoped `AgentTraceDb`/`AgentTraceDbSpec` adapter and its 15-file migration chain were removed by the `retire-legacy-agent-trace-db` plan). The repository adapter uses the `agent-trace-repository` migration set (fresh baseline schema plus additive `source_instance_id` and `claude_model_state` migrations) with `repository_metadata`, repository-level `diff_traces`, `post_commit_patch_intersections`, `agent_traces`, `messages`, and `parts` tables, no row-level `checkout_id`, typed parameterized insert helpers, the non-exported `claude_model_state` latest-locally-observed register with exact `(session_id, agent_id)` reads and guarded writes, and chronological recent `diff_traces` query/parse support. `AgentTraceDbLifecycle` initializes/checks repository-scoped storage through `agent_trace_storage`. - `post-commit Agent Trace auto-sync readiness`: The doctor report fact that explains whether the enabled post-commit trigger is ready without invoking it. Doctor compares the installed `post-commit` hook's SCE managed block using the same currency semantics as setup and resolves config-file-only `agent_trace.auto_sync` with source metadata. JSON states are `ready`, `disabled`, `not_ready`, and `not_applicable`; `disabled` covers both the explicit opt-out and an access policy that disallows background cloud operations, and is healthy, while existing hook problems continue to own overall readiness and remediation. See [automatic Agent Trace synchronization](cli/agent-trace-auto-sync.md) and [doctor human text](sce/doctor-human-text-contract.md). @@ -131,14 +128,10 @@ - `sce exit-code class contract`: Stable top-level process exit-code mapping owned by `cli/src/app.rs` (`0` success, `2` parse failure, `3` validation failure, `4` runtime failure, `5` dependency failure) so automation can branch on failure class without parsing text errors. - `sce stderr error-code taxonomy`: Stable internal failure diagnostic classes emitted by `cli/src/app.rs` (`SCE-ERR-PARSE`, `SCE-ERR-VALIDATION`, `SCE-ERR-RUNTIME`, `SCE-ERR-DEPENDENCY`) via styled `Error []: ...` stderr formatting; expected catalog failures emit only their redacted, unstyled catalog message. - `class-default Try guidance injection`: `cli/src/app.rs` diagnostic behavior that appends `Try:` remediation text by failure class only for internal failures when an error message does not already include `Try:` guidance. -- `sce observability baseline`: App-runtime logging contract in `cli/src/services/observability.rs` and `cli/src/app.rs` with config-resolved observability inputs, deterministic env-over-config-file-over-default precedence for non-flag logging keys, default-backed `log_dir` / `SCE_LOG_DIR` file routing by machine-local date plus optional session filename partitioning, creation-triggered retention of direct regular `*.log` files to 10 entries, stable lifecycle `event_id` values, tracing for all emitted records, normal logger records routed only to files when `log_to_file=true`, and only error-level logger records routed to `stderr` when `log_to_file=false`. - `general unexpected user error`: `UserError::UnexpectedFailure` (`general.unexpected_failure`) catalog entry with the fixed sentence `An unexpected error occurred. Check the log files for more details.`. `sce sync` uses it for non-authentication and non-credential-storage failures while preserving the technical source for observability; the message exposes no path or implementation details. - `sce stdout/stderr contract`: App-level stream routing contract in `cli/src/app.rs` where command success payloads are emitted on stdout only, while redacted user-facing diagnostics and text-mode `sce sync` progress are emitted on stderr; JSON sync emits no human progress. -- `SCE_LOG_LEVEL`: Optional runtime env key for `sce` observability threshold; allowed values are `error`, `warn`, `info`, and `debug`, defaulting to `error` when unset. -- `SCE_LOG_FORMAT`: Optional runtime env key for `sce` observability record format; allowed values are `text` and `json`, defaulting to `text` when unset. - `SCE_LOG_FILE`: Optional runtime env key for `sce` observability file sink path; when set, rendered observability lines are mirrored to this file path with parent-directory auto-create behavior. - `SCE_LOG_FILE_MODE`: Optional runtime env key controlling `SCE_LOG_FILE` write policy; allowed values are `truncate` and `append`, defaults to `truncate`, and requires `SCE_LOG_FILE`. -- `SCE_LOG_DIR`: Optional runtime env key for `sce` observability log-directory configuration; when set, it overrides config-file `log_dir` and the `/sce/logs` default and must be non-empty. - `app startup phases`: Current `cli/src/app.rs` execution model that separates dependency checking, startup-context construction, runtime initialization, command parse/execute, and output rendering into named helpers while preserving the CLI's existing exit-code, stderr-diagnostic, and degraded-startup behavior; output rendering and execution-phase logging helpers live in `cli/src/services/app_support.rs`. - `RunOutcome`: Generic final render payload in `cli/src/services/app_support.rs` (`RunOutcome`) carrying a command result, optional startup diagnostic, and optional logger implementing the logger trait boundary. Production construction in `cli/src/app.rs` uses the concrete observability logger, while rendering is not hardcoded to that production type. - `RuntimeCommand`: Static enum in `cli/src/services/command_registry.rs` containing concrete command payloads and their direct execution dispatch. `cli_schema::Commands` owns the Clap command grammar; `parse/command_runtime.rs` converts parsed requests directly into `RuntimeCommand` without a parallel command-name registry or default-constructor catalog. @@ -164,7 +157,6 @@ - `config render seam`: Canonical ownership in `cli/src/services/config/render.rs` for `sce config show` and `sce config validate` text/JSON output construction, including rendering-specific config-path formatting, resolved-value formatting, validation issue/warning rendering, and auth display-value redaction/abbreviation helpers; `cli/src/services/config/mod.rs` delegates rendering to this private submodule after resolver-owned runtime config resolution. - `sce config schema artifact`: Canonical JSON Schema for global and repo-local `sce/config.json` files, authored in `config/pkl/base/sce-config-schema.pkl`, generated to payload-relative `config/schema/sce-config.schema.json` beneath Cargo `OUT_DIR` or packaging fallback roots, and embedded by `cli/src/services/config/schema.rs` for shared `sce config validate` and doctor config validation. The current schema accepts any canonical `$schema` declaration in the CLI's `major.minor` config schema compatibility series (derived from `.version`), flat logging keys (`log_level`, `log_format`, `log_dir`, positive-integer `log_file_retention_limit`), and existing auth/config keys. - `config schema compatibility series`: The `major.minor` part of the CLI version from `.version`. Any canonical `https://sce.crocoder.dev/v..[-pre][+build]/config.json` declaration in that series is accepted. `config/pkl/base/sce-config-schema-url.pkl` derives the schema's series `pattern`, and `cli/src/services/config/schema_declaration.rs` classifies declarations as absent, current, older, newer, or unrecognized. Only `sce setup` upgrades an older-series declaration, and it changes only `$schema` in the canonical repository and global config. See `context/decisions/2026-11-10-setup-upgrades-config-schema-declarations.md`. -- `log_file_retention_limit`: Flat top-level `sce/config.json` key validated as an integer with minimum `1`. It has config-file > default precedence only, defaults to `10`, merges global before local, appears in `sce config show` with provenance, and is carried by `ResolvedObservabilityRuntimeConfig`; the concrete logger stores the resolved value and uses it for primary and v2 creation-triggered cleanup. - `bash tool policy config surface`: Nested repo config namespace under `.sce/config.json` at `policies.bash`, currently supporting unique built-in `presets` plus repo-owned `custom` argv-prefix rules with deterministic validation, merged global/local resolution, and first-class `sce config show|validate` reporting. - `attribution hooks gate`: Enabled-by-default local hook runtime gate resolved through shared config precedence in `cli/src/services/config/mod.rs` (with parsing in `schema.rs`): opt-out env `SCE_ATTRIBUTION_HOOKS_DISABLED` overrides repo/global config key `policies.attribution_hooks.enabled` with inverted semantics, and the current enabled path activates commit-msg-only attribution gated by the staged-diff AI-overlap preflight. - `StagedDiffAiOverlapResult`: Three-valued enum in `cli/src/services/hooks/mod.rs` returned by the staged-diff AI-overlap evidence check: `Overlap` (staged diff overlaps with at least one recent AI/editor diff trace), `NoOverlap` (no overlap found; staged diff and recent traces were both available but share no touched lines, or staged patch has no touched lines), `Error` (DB open failure, schema not ready, query error, staged diff read failure, or clock failure). Both `NoOverlap` and `Error` map to `ai_contribution_present = false` at the commit-msg policy seam; `Error` additionally triggers `sce.hooks.commit_msg.ai_overlap_error` logging. diff --git a/context/overview.md b/context/overview.md index b720946e9..34248c06a 100644 --- a/context/overview.md +++ b/context/overview.md @@ -56,7 +56,7 @@ The generated `/next-task` workflow persists task-level context-synchronization - **Stdout/stderr:** command payloads on stdout only; redacted diagnostics and text-mode `sce sync` progress on stderr, while JSON sync remains silent (see `context/sce/cli-stdout-stderr-contract.md`). - **Observability:** config-resolved logging with tracing, explicit config-file/default `log_to_file` control, suppression of normal logger records on `stderr` when file logging is enabled, error-only logger routing to `stderr` when file logging is disabled, and optional dated/session-partitioned `log_dir` / `SCE_LOG_DIR` files with retention (see `context/sce/cli-observability-contract.md`). - **Config precedence:** `flags > env > config file > defaults` (see `context/cli/config-precedence-contract.md`); invalid default-discovered config remains degradable for ordinary startup, while setup and Agent Trace storage fail closed before side effects or fallback identity selection. The config-file-only `agent_trace.auto_sync` setting resolves omitted values to `false`, while setup explicitly writes `true` into a newly created repo-local config; source metadata feeds the post-commit trigger and doctor readiness boundaries. Its asynchronous post-commit behavior and doctor capability reporting are documented in `context/cli/agent-trace-auto-sync.md`. -- **Codex native telemetry:** `sce codex` launches Codex with Codex traces and metrics exported to the managed collector under a repository-scoped credential, for repository-safe invocation modes only; plain `codex` launches export only SCE Codex hook spans (see `context/sce/codex-native-telemetry-launcher.md`). +- **Codex native telemetry** — For supported invocations, `sce codex` uses a repository-scoped credential to send Codex traces and metrics to the managed collector. The launcher disables native logs. Authorized SCE Codex hook spans can export independently of the launcher. [Launcher reference](sce/codex-native-telemetry-launcher.md) · [Live verification](sce/codex-native-telemetry-contract.md#live-verification). - **Attribution hooks:** enabled by default, gated by staged-diff AI-overlap preflight; `SCE_ATTRIBUTION_HOOKS_DISABLED` opt-out (see `context/sce/agent-trace-commit-msg-coauthor-policy.md`). - **Setup behavior choices:** interactive setup asks independent Yes-default confirmations for post-commit Agent Trace auto-sync and commit-attribution trailers, persists the answers under `agent_trace.auto_sync` and `policies.attribution_hooks.enabled`, and leaves existing behavior keys/omissions untouched during non-interactive setup. Interactive setup also asks for the SCE auth mode and telemetry consent, saves those answers only to the repository `.sce/config.json` before the target install, so they apply only to that repository, and reports the re-resolved effective access policy in an `SCE access` section. It then runs `sce auth login` from the repository root when the effective mode is `mandatory` or the user accepted the `optional` login offer, never under `disabled`; a failed mandatory login exits with `auth.setup_login_required`. Saved answers skip their prompts on reruns; interactive-only `sce setup --reconfigure` asks them all again with the saved values as defaults. The runtime resolver and hook contracts remain authoritative (see `context/sce/setup-repo-local-config-bootstrap.md`). - **Install channels:** repo-flake Nix, Cargo, npm, and source-built Flatpak (`dev.crocoder.sce`); Homebrew deferred (see `context/sce/cli-first-install-channels-contract.md`). @@ -66,7 +66,7 @@ Its command loop is implemented with `clap` derive-based argument parsing and `a The current doctor presentation contract supersedes the earlier output-shape scaffolding wording above: human text uses the compact Environment/Repository/Integrations hierarchy with healthy rows collapsed and unhealthy branches expanded, while JSON retains complete path, identity, problem, and fix-result detail. See `context/sce/doctor-human-text-contract.md`. The command loop now enforces a stable exit-code contract in `cli/src/app.rs`: `2` parse failures, `3` invocation validation failures, `4` runtime failures, and `5` dependency startup failures. Auth command orchestration routes authenticated Control Plane authentication failures, token-storage failures, and approved user-facing fallback failures through typed `CliError::User` catalog entries (`NotAuthenticated`, `AuthStorageUnavailable`, `NotGitRepository`, and `UnexpectedFailure`) while retaining technical sources for observability; missing-credential logout/whoami state queries succeed with their documented text/JSON reports (except `whoami` under `auth.mode: mandatory`, which fails with `NotAuthenticated`), `auth.mode: disabled` rejects login/whoami with `AuthDisabledByConfig` before credential storage, and internal auth failures remain runtime errors. The same runtime also emits stable CLI stderr diagnostics: internal failures use `SCE-ERR-PARSE`, `SCE-ERR-VALIDATION`, `SCE-ERR-RUNTIME`, or `SCE-ERR-DEPENDENCY` in deterministic `Error []: ...` diagnostics with class-default `Try:` remediation appended when missing, while expected failures emit only their redacted, unstyled catalog messages. The command boundary's former flat, string-only `ClassifiedError` has been replaced by typed `CliError` in `cli/src/services/error.rs`: `CliError::User` carries a closed catalog (`NotAuthenticated`, `NotGitRepository`, `NotGitRemote`, authentication-storage `AuthStorageUnavailable`, and general `UnexpectedFailure`) for expected, deliberately-explained failures rendered without the technical source, wrapper, styling, or automatic `Try:` guidance; the general entry renders one fixed static log-files guidance sentence without dynamic path text. `CliError::Internal` carries a live `anyhow::Error` source rendered as the real error chain with the existing styled wrapper and class-default remediation; `app_support` is the sole owner of the distinct terminal paths, and `sce sync` classifies authentication, credential-storage, and all other sync failures as cataloged user errors while preserving their technical sources for observability. Setup preflight errors preserve technical sources, including the configured remote name, while raw remote URLs remain out of user-facing diagnostics. See `context/sce/cli-error-code-taxonomy.md` for the full contract. -The app runtime now also includes a structured observability baseline in `cli/src/services/observability.rs`: deterministic env-controlled log threshold/format (`SCE_LOG_LEVEL` defaults to `error`; `SCE_LOG_FORMAT` defaults to `text`), default-backed log-directory routing (`SCE_LOG_DIR` / config-file `log_dir` / `/sce/logs`) with per-operation machine-local dated file selection, optional session filename partitioning, and creation-triggered retention of direct regular `*.log` files to 10 entries, stable lifecycle event IDs, normal logger records routed only to files when file logging is enabled and only error-level logger records routed to `stderr` when file logging is disabled, direct file-write diagnostics remaining on `stderr`, and `observability::traits` boundaries for logger and telemetry behavior. When the effective access policy enables telemetry (`telemetry.enabled`, see `context/cli/access-policy.md`) and the encrypted auth DB holds a valid unexpired telemetry credential, commands also export `sce.command` spans (Claude-invoked SCE hooks export one root `sce.hook` span instead, with `sce.mutation_scope`/`sce.git_snapshot`/`sce.persistence` children only for operations that ran; other hooks export nothing) and allowlisted logger events as OTLP/HTTP protobuf to the hardcoded `https://otel.crocoderlab.dev` `/v1/traces` and `/v1/logs` paths (bearer token only, redirects disabled, ambient `OTEL_EXPORTER_OTLP_*` and repo config cannot redirect it, fail-open and bounded); with telemetry not enabled by policy or without a credential nothing is exported, and `/v1/metrics` is reserved with no metrics pipeline. +The app runtime now also includes a structured observability baseline in `cli/src/services/observability.rs`: deterministic env-controlled log threshold/format (`SCE_LOG_LEVEL` defaults to `error`; `SCE_LOG_FORMAT` defaults to `text`), default-backed log-directory routing (`SCE_LOG_DIR` / config-file `log_dir` / `/sce/logs`) with per-operation machine-local dated file selection, optional session filename partitioning, and creation-triggered retention of direct regular `*.log` files to 10 entries, stable lifecycle event IDs, normal logger records routed only to files when file logging is enabled and only error-level logger records routed to `stderr` when file logging is disabled, direct file-write diagnostics remaining on `stderr`, and `observability::traits` boundaries for logger and telemetry behavior. When the effective access policy enables telemetry (`telemetry.enabled`, see `context/cli/access-policy.md`) and the encrypted auth DB holds a valid unexpired telemetry credential, commands also export `sce.command` spans (admitted Claude and Codex hooks each export one `sce.hook` span, with children only for operations that run) and allowlisted logger events as OTLP/HTTP protobuf to the hardcoded `https://otel.crocoderlab.dev` `/v1/traces` and `/v1/logs` paths (bearer token only, redirects disabled, ambient `OTEL_EXPORTER_OTLP_*` and repo config cannot redirect it, fail-open and bounded); with telemetry not enabled by policy or without a credential nothing is exported, and this SCE-process exporter sends no metrics. One application-level multi-thread Tokio runtime directly awaits static command dispatch through async credentials, lifecycle providers, hooks, sync/export, and Turso persistence. The shared Turso adapters own no runtime or executor bridge, and foreground hooks return after required persistence completes. See [application execution runtime](architecture.md#application-execution-runtime). The app command dispatcher now enforces a centralized stdout/stderr stream contract in `cli/src/app.rs`: command success payloads are emitted on stdout only, while redacted user-facing diagnostics and text-mode sync progress are emitted on stderr; JSON sync remains silent. `cli/src/app.rs` also now runs through explicit startup phases — dependency check, observability config resolution, runtime initialization, command parse/execute, and output rendering — with the app runtime carrying logger/telemetry plus static command-catalog state across those phases while preserving the existing exit-code and degraded-startup contracts. Within that lifecycle, `parse_command_phase` delegates clap-to-runtime conversion to `cli/src/services/parse/command_runtime.rs`, which returns a static `RuntimeCommand` enum, `services::app_support::execute_command_phase` logs around enum-owned `execute_with_stderr(...)` dispatch, and generic `RunOutcome` rendering logs classified errors through the logger trait boundary without coupling render support to the production logger type. Command payload structs for `help`, `version`, `completion`, `auth`, `config`, `setup`, `doctor`, `hooks`, and `sync` live in service-owned `command.rs` files; `cli/src/services/command_registry.rs` owns the deterministic static command-name catalog and enum variants instead of boxed command trait objects. The CLI now also enforces a shared output-format parser contract in `cli/src/services/output_format.rs`, with canonical `--format ` parsing and command-specific actionable invalid-value guidance reused by `config` and `version` services. A compile-safe service lifecycle seam also exists in `cli/src/services/lifecycle.rs`: `ServiceLifecycle` exposes default no-op `diagnose`, `fix`, and `setup` methods against the narrow `HasRepoRoot` accessor, uses lifecycle-owned health/fix/setup result types, and owns the shared static `LifecycleProvider` enum catalog/factory with deterministic config → local*db → auth_db → agent_trace_db → hooks ordering and no boxed provider aggregation. Hooks has a `services/hooks/lifecycle.rs` provider for hook rollout diagnosis/fix/setup, config has a `services/config/lifecycle.rs` provider for global/repo-local config validation plus repo-local config bootstrap, local_db has a `services/local_db/lifecycle.rs` provider for canonical local DB path health, parent-directory readiness/bootstrap, and `LocalDb::new()` setup, auth_db has a `services/auth_db/lifecycle.rs` provider for canonical auth DB path health and parent-directory readiness/bootstrap; its setup creates only the parent directory and never creates `auth.db` or resolves a key, and agent_trace_db has a `services/agent_trace_db/lifecycle.rs` provider for repository-scoped Agent Trace DB setup and repository DB path health/parent readiness from resolved repository identity, returning an actionable "requires a Git repository" diagnostic outside repository context (no global/checkout fallback path). Doctor runtime aggregates the full shared provider catalog for `diagnose` and `fix` and adapts lifecycle records into doctor-owned output records; setup command aggregates the shared provider catalog for `setup` with hooks included only when requested and adapts lifecycle setup outcomes before rendering setup-owned messages. diff --git a/context/plans/codex-native-otel-instrumentation.md b/context/plans/codex-native-otel-instrumentation.md index 7643d4b58..bba9b6acb 100644 --- a/context/plans/codex-native-otel-instrumentation.md +++ b/context/plans/codex-native-otel-instrumentation.md @@ -16,17 +16,17 @@ Credential provisioning, the encrypted `auth.db`, repository enrollment, the eff 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: Durable context records evidence from real Codex 0.172.0 runs against a local OTLP receiver with dummy credentials. The evidence covers: the header-helper invocation contract (argv form, working directory, environment, stdout format, refresh cadence, failure recovery, header caching); configuration precedence across `-c`, profiles, user `config.toml`, and enterprise requirements; whether a helper-authorized header can reach a non-canonical exporter; attribution behavior for interactive, `exec`, `resume`, `fork`, working-directory changes, and multiple threads; whether command hooks receive `TRACEPARENT`/`TRACESTATE` that names an exported Codex span (distinguished from inherited process environment); the mapping between native session identifiers and SCE `cx_` session identities; the exported token, cost, cache, tool, duration, model, repository, and subagent attributes with their observed semantics; and which config options control prompt, response, and tool-argument content in native logs. The record ends with one implementation decision and a Claude/Codex parity matrix. +- [x] AC1: Durable context records evidence from real Codex 0.172.0 runs against a local OTLP receiver with dummy credentials. The evidence covers: the header-helper invocation contract (argv form, working directory, environment, stdout format, refresh cadence, failure recovery, header caching); configuration precedence across `-c`, profiles, user `config.toml`, and enterprise requirements; whether a helper-authorized header can reach a non-canonical exporter; attribution behavior for interactive, `exec`, `resume`, `fork`, working-directory changes, and multiple threads; whether command hooks receive `TRACEPARENT`/`TRACESTATE` that names an exported Codex span (distinguished from inherited process environment); the mapping between native session identifiers and SCE `cx_` session identities; the exported token, cost, cache, tool, duration, model, repository, and subagent attributes with their observed semantics; and which config options control prompt, response, and tool-argument content in native logs. The record ends with one implementation decision and a Claude/Codex parity matrix. - Validate: Inspect `context/sce/codex-native-telemetry-contract.md` for the evidence tables, the Codex version, the decision, and the parity matrix. `git ls-files` shows no probe script or receiver fixture. `rg -n 'Bearer [A-Za-z0-9._-]{12,}|hvs\.|s\.[A-Za-z0-9]{20,}' context/sce/codex-native-telemetry-contract.md` returns no match. - [ ] AC2: `sce auth telemetry-headers` with no arguments behaves exactly as before for Claude. When the T01 decision requires explicit repository context, the helper accepts it, applies the same access-policy gate, destination tripwire, `auth.db` presence check, repository-binding lookup, and `CREDENTIAL_LOOKUP_DEADLINE` to that repository, and fails closed with the fixed diagnostic `Telemetry credential is unavailable.` and empty stdout for a missing, non-Git, unenrolled, opted-out, or otherwise unauthorized repository. The helper never initializes managed telemetry. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml telemetry_headers`; the existing no-argument tests in `cli/src/services/auth_command/mod.rs` and `cli/src/services/telemetry_credential_storage.rs` pass unchanged; `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_span_kind`. - [ ] AC3: Native Codex telemetry is enabled only through the mechanism the T01 decision selects, and only for invocation modes that T01 proved repository-safe. When the decision selects a `sce codex` launcher, it resolves the effective repository and access policy before launch, supplies native OTEL settings only as process-local `-c` overrides that pin `MANAGED_OTLP_ENDPOINT` / `MANAGED_OTLP_PROTOCOL` and the helper with explicit repository context, forwards supported Codex arguments unchanged, preserves the terminal, signal delivery, and the Codex exit code, and refuses or launches without SCE telemetry for unproven modes. No credential is written to any file, and no global Codex config is changed unless T01 proves it necessary. - Validate: Targeted Rust tests for the launch argument builder and mode classification (`nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml codex_telemetry`); `rg -n 'Bearer|OTEL_EXPORTER_OTLP_HEADERS' cli/src/services` shows no credential in launch arguments or written config; inspection of the T02 completion record for the exit-code and signal checks. -- [ ] AC4: SCE credentials cannot be sent to an exporter that targets an unrelated endpoint through any path T01 identified. User-owned or enterprise-managed Codex OTEL configuration that conflicts with the managed endpoint causes SCE to skip native telemetry and report the reason; it is never overwritten. +- [x] AC4: SCE credentials cannot be sent to an exporter that targets an unrelated endpoint through any path T01 identified. User-owned or enterprise-managed Codex OTEL configuration that conflicts with the managed endpoint causes SCE to skip native telemetry and report the reason; it is never overwritten. - Validate: Targeted Rust tests per conflict class identified in T01; inspection of the residual-risk statement in `context/sce/telemetry-credential.md`. - [ ] AC5: With a valid stored credential, each `sce hooks codex` and `sce hooks codex-mutation-scope` process exports exactly one `sce.hook` span with `service.name=sce`, `sce.agent=codex`, `sce.hook.command`, `sce.hook.event`, `sce.hook.tool` when present, `sce.outcome`, and only the Codex session, turn, tool-use, and model identifiers that T01 verified. `sce.mutation_scope`, `sce.git_snapshot`, and `sce.persistence` child spans appear only when that operation executed in the process. Claude hook spans keep their current names and `sce.claude.*` attributes. - Validate: `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_telemetry`, including loopback-receiver tests over Codex `PostToolUse(apply_patch)` and non-tracked fixtures that decode the OTLP payload and assert span name, count, parent links, and attributes; existing Claude loopback tests pass unchanged. -- [ ] AC6: A Codex hook `sce.hook` span is parented on upstream `TRACEPARENT` only when T01 proved that Codex supplies valid current-span context for that hook execution. Otherwise the span is an independent root with correlation attributes. No trace ID or parent span ID is ever derived from a session, turn, or tool-use identifier. +- [x] AC6: A Codex hook `sce.hook` span is parented on upstream `TRACEPARENT` only when T01 proved that Codex supplies valid current-span context for that hook execution. Otherwise the span is an independent root with correlation attributes. No trace ID or parent span ID is ever derived from a session, turn, or tool-use identifier. - Validate: Loopback-receiver tests for valid, invalid, all-zero, and missing traceparent when parenting ships; otherwise `rg -n 'extract_parent_context' cli/src/services/managed_telemetry` shows extraction gated to the proven agent only, and `context/sce/codex-native-telemetry-contract.md` states the verdict. - [ ] AC7: Telemetry cannot change Codex hook behavior. With credential lookup failure, an expired credential, a refused or stalled receiver, or exporter timeout, hook stdout, stderr, exit code, permission decisions, Agent Trace DB rows, and mutation-trace state match the telemetry-disabled run, and process lifetime stays within `CREDENTIAL_LOOKUP_DEADLINE` + `SHUTDOWN_TIMEOUT`. - Validate: Parity tests running the same Codex hook fixtures with Noop and with failing managed telemetry, comparing outputs and persisted state and asserting elapsed-time bounds. @@ -116,15 +116,82 @@ Persist this field in every plan; this is durable plan state, not chat state: - Deviations: the helper repository argument ships as a separate `TelemetryHeadersForRepository` variant so the existing no-argument parse test and code path stay unchanged, which drops `Copy` from `AuthSubcommand`/`AuthRequest`; `otel.span_attributes` repository attribution was not added (T01 local choice); `plan_launch_with` takes an injected repository-root resolver because this machine has a stray `/tmp/.git` directory that made a temp-dir "not a repository" test non-hermetic; the ADR is left to the context-synchronization decision gate; SCE hook runs during the session wrote an untracked `cli/context/tmp/` log (not part of this change). - Context synchronization: synced -- [ ] T03: `Record live Codex telemetry verification and the Claude/Codex parity contract in durable context` (status:todo) +- [x] T03: `Record live Codex telemetry verification and the Claude/Codex parity contract in durable context` (status:done) - Task ID: T03 - Scope: In — real Codex sessions through the shipped mechanism against `https://otel.crocoderlab.dev` with existing managed credentials; Dash0 observation of every AC8 item; a Claude regression session; the live-verification section, final parity matrix, upstream limitations, minimum verified Codex version, and control-plane follow-up list in `context/sce/codex-native-telemetry-contract.md`; synchronization of every file under Context sync. Out — code changes (a defect found here is recorded with its evidence and fixed in a new task appended to this plan); Control Plane or warehouse changes; recording real tokens, prompts, or tool content. - Dependencies: T02 - Done when: every AC8 item is recorded as observed in the correct Dash0 dataset with trace IDs, or recorded as not verifiable with the exact reason; AC9 context matches the shipped code; the minimum verified Codex version is stated. - Verify: inspection of the live-verification section and the Context sync files against the code; `rg -n 'telemetry-headers' context/cli/cli-command-surface.md` shows no public listing; `rg -n 'Bearer [A-Za-z0-9._-]{12,}' context/` returns no match. - - Context synchronization: pending + - Completed: 2026-11-24 + - Files changed: `context/sce/codex-native-telemetry-contract.md`, `context/cli/cli-command-surface.md`, `context/cli/codex-mutation-scope-integration.md` + - Result: Recorded Dash0 delivery in `sce-crocoder` for Codex CLI 0.172.0. Confirmed native traces, token, cache, model and tool series, independent SCE hook roots, the mutation child-span hierarchy, tool and subagent identifier joins, and Claude tool-hook parenting and native metrics. Confirmed zero native Codex log records in the check window. Real sessions for repository opt-out, process-local global opt-out and failed authorization had no matching spans. The launcher preserved the user-owned config in a scratch conflict check. Added the final parity matrix, smoke procedure, limitations, minimum verified version, and Control Plane follow-ups. + - Verify results: Checked the live evidence and documented contracts against the launcher, credential and hook code. Dash0 trace IDs and scenario-specific evidence are in the native telemetry contract. The public command reference and `sce auth --help` omit the hidden helper. The context bearer scan, expanded contract credential scan, and `git diff --check` passed. The targeted Nix-wrapped `telemetry_credential_storage` and `codex_telemetry` suites passed 14 and 11 tests respectively. + - Context impact: domain-local documentation. Updates the Codex telemetry evidence and command and mutation-scope references. The shipped launcher, managed exporter, and hook behavior are unaffected. + - Deviations: Native log delivery is unavailable because the launcher disables it for privacy. Codex 0.172.0 supplies no native cost metric or per-session metric identifier. Disposable credentials for live rotation, expiry and logout, a second enrolled workspace, and enterprise-managed Codex config were unavailable. The contract records those limits and the corresponding local test evidence. + - Context synchronization: synced ## Open questions - Is launcher-only coverage worth its cost? If T01 proves that `CODEX_HOME` execution makes a user-level `config.toml` install unable to identify the repository, only `sce codex` launches will export native telemetry, and every plain `codex` launch stays dark. That is weaker than Claude parity, where a user-level install covers every launch. A smaller alternative is to ship only the T02 Codex hook spans, which need no launcher, and defer native export until upstream passes a working directory or repository context to the helper. - Will Codex native metrics be usable without control-plane work? Codex metric names and units differ from `claude_code.*`, and this plan excludes warehouse and dashboard changes. Delivered Codex metrics may not appear in existing SCE views until the follow-ups T03 records are done. + +## Validation Report + +**Status:** failed + +**Date:** 2026-11-24 + +### Commands run + +- `nix flake check` -> exit 0 (all checks passed on `x86_64-linux`). +- `nix run .#pkl-check-generated` -> exit 0 (157 generated files verified). +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_telemetry` -> exit 0 (23 passed). +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml telemetry` -> exit 0 (112 passed). +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml codex` -> exit 0 (60 passed). +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml auth` -> exit 0 (25 passed). +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml telemetry_headers` -> exit 0 (11 passed). +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml managed_span_kind` -> exit 0 (3 passed). +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml codex_telemetry` -> exit 0 (11 passed, including the visible conflict classes). +- `nix develop -c ./scripts/run-cli-cargo.sh test --manifest-path cli/Cargo.toml matches_telemetry_disabled_run` -> exit 0 (2 passed for refused and stalled receivers). +- `git ls-files` and `git diff --name-only a0562c0b --` with `probe|otlp.?receiver|telemetry.*fixture|(^|/)(tmp|scratch)(/|$)` path filters -> exit 0 (tracked fixtures predate the plan; the plan delta adds one temporary runtime log). +- `git ls-files --stage -- cli/context/tmp/sce-24_11_2026.log` -> exit 0 (the log is tracked and was introduced by `977ac744`). +- `nix run nixpkgs#ripgrep -- -l 'Bearer [A-Za-z0-9._-]{12,}|hvs\.|s\.[A-Za-z0-9]{20,}' context/sce/codex-native-telemetry-contract.md` -> exit 1 (expected, no matches). +- `nix run nixpkgs#ripgrep -- -n 'Bearer|OTEL_EXPORTER_OTLP_HEADERS' cli/src/services` -> exit 0 (matches include existing credential handling and tests; inspection confirmed no credential in launcher overrides or written Codex config). +- `nix run nixpkgs#ripgrep -- -n -C 4 'extract_parent_context' cli/src/services/managed_telemetry` -> exit 0 (extraction is Claude-only). +- `nix run nixpkgs#ripgrep -- -n 'telemetry-headers' context/cli/cli-command-surface.md` -> exit 1 (expected, no public listing). +- `codex --version`, `codex exec --help`, `codex exec fork --help`, and `codex exec resume --help` -> exit 0 (0.172.0; fork and resume accept `--worktree` and `--remote`). +- `git diff --check` and `git diff --cached --check` -> exit 0 (no whitespace errors). + +### Success-criteria verification + +- [x] AC1: Record the Codex 0.172.0 probe, implementation decision, and parity matrix -> The contract covers all requested topics with observations, source evidence, or explicit limits. The repository adds no probe or receiver fixture for this plan. The contract credential scan found no matches. +- [ ] AC2: Preserve the Claude helper and fail closed for invalid explicit repository context -> The unchanged Claude assertions, storage tests, and managed-telemetry bypass passed. The explicit-repository test also expects a header for an absent subdirectory under the enrolled root, contrary to the missing-path guarantee. +- [ ] AC3: Enable native telemetry only on repository-safe invocations -> Override pinning and forwarding tests passed. The T02 record confirms Unix exit status 7 and SIGTERM status 143. Classification stops at `exec fork` and ignores unknown options after `resume`, so accepted switches such as `--worktree` can pass the telemetry classifier. Only `exec resume -C` has recorded directory-probe evidence. +- [x] AC4: Keep credentials pinned to the managed exporter and preserve conflicting config -> Conflict tests passed for caller, user, profile, readable system, and environment settings. Override tests pin all three signal keys. T01 documents upstream helper isolation for requirements-layer exporters and the limits of inspecting MDM and cloud requirements. +- [ ] AC5: Export the specified Codex hook spans and identifiers while preserving Claude spans -> Loopback tests passed for `sce hooks codex`, tracked and untracked mutation-scope fixtures, and existing Claude spans. Live evidence confirms the operation hierarchy. The fixtures also assert `sce.codex.agent_id` and `sce.codex.agent_type`, beyond AC5’s stated identifier list. +- [x] AC6: Keep Codex hook spans as independent roots -> The parent extraction branch is Claude-only. Tests cover valid, invalid, all-zero, and absent inbound context, and loopback payloads show independent Codex roots. +- [ ] AC7: Preserve complete hook behavior and process lifetime across telemetry failures -> The refused and stalled receiver tests passed. They compare in-process return values, seam inputs, state-file names, and separate timing checks. They bypass credential admission and the production persistence seam and leave process stderr, exit status, permission decisions, database rows, persisted contents, and the combined time budget unverified. +- [ ] AC8: Record the required live Dash0 delivery and scenario coverage -> T03 records native traces and metrics, SCE hook spans, correlation, and Claude regression evidence in `sce-crocoder`. Native logs are disabled for privacy, Codex 0.172.0 exposes no cost signal or per-session metric ID, and live replacement, expiry, logout, second-workspace routing, and managed-config verification remain open. +- [ ] AC9: Align current-state context with the shipped implementation and keep the helper hidden -> The Context sync documents, launcher ADR, parity matrix, version, privacy settings, and follow-ups are present. The public command scan found no helper listing. The documented missing-path check and the statement that unrecognized launcher options always disable telemetry disagree with the implementation. + +### Failed checks and follow-ups + +- AC2: A missing explicit path can inherit an enrolled ancestor's credential. The test `telemetry_headers_bind_the_explicit_repository_and_fail_closed_elsewhere` expects success for a descendant it never creates. Enforce the intended explicit `--repo` path contract or revise that contract with an explicit decision. +- AC3: The launch classifier returns at `exec fork` before checking remaining options, and `classify_resume` ignores unrecognized options and continues past `--`. `--worktree` and `--remote` are available on fork and resume in Codex 0.172.0. Check mode-changing options and the argument terminator across the complete invocation. Establish repository attribution for interactive `resume -C` or keep it plain. +- AC5: The implementation and T01 decision include two subagent attributes outside the AC5 wording. Decide whether to include the verified subagent fields in the criterion or narrow the exporter. +- AC7: `cli/src/services/hooks/codex_mutation_scope/telemetry_tests.rs` checks selected outcomes at an injected seam. Add subprocess-level parity evidence for both Codex hook commands across lookup failure, expiry, receiver refusal, receiver stall, and exporter timeout, with production-equivalent persistence and the combined time bound. +- AC8: `context/sce/codex-native-telemetry-contract.md` and T03 record incomplete live outcomes. Decide how the criterion should represent privacy-disabled logs, unavailable cost and metric identifiers, and the one-workspace evidence. Obtain disposable credentials, a second enrolled workspace, and an enterprise fixture for the applicable outstanding checks. +- AC9: `context/sce/telemetry-credential.md` promises rejection of missing paths. `context/sce/codex-native-telemetry-launcher.md` promises unrecognized options disable native telemetry. Align these contracts with the resolution of AC2 and AC3. +- Temporary artifact: `cli/context/tmp/sce-24_11_2026.log` is the runtime log noted in T02 and was tracked by `977ac744`. Remove it from the delivered tree in a repair session. + +### Residual risks + +- A running Codex process can retain its launch-repository credential across an in-process thread or directory change and keeps cached headers until refresh. +- Unreadable MDM and cloud requirements can override local pins or logging settings. T01 documents the upstream requirements-layer helper isolation from source. +- Flake validation covered `x86_64-linux`. Nix omitted three incompatible systems. + +### Retry + +After repairs, rerun: + +`/validate context/plans/codex-native-otel-instrumentation.md` diff --git a/context/sce/cli-observability-contract.md b/context/sce/cli-observability-contract.md index 6d9523666..1cfaf39b6 100644 --- a/context/sce/cli-observability-contract.md +++ b/context/sce/cli-observability-contract.md @@ -100,7 +100,7 @@ Runtime observability consumes the shared resolved observability config from `cl - Export is OTLP/HTTP protobuf to the hardcoded `https://otel.crocoderlab.dev/v1/traces`. A pinned HTTP client sets `Authorization: Bearer ` (token only, never the accessor), disables redirects, rebuilds the request to the fixed endpoint, and bounds requests to 3s. Ambient `OTEL_EXPORTER_OTLP_*` values cannot redirect it. - Each command emits one `sce.command` span with `sce.command.name`, `sce.outcome` (`success`/`failure`), and `sce.error.class` (the `SCE-ERR-*` code on failure); resource attributes are `service.name=sce` and `service.version`. Raw arguments, paths, and error chains are not exported. - An admitted Claude hook process emits exactly one `sce.hook` span instead (no `sce.command` span), with `sce.agent=claude`, `sce.hook.command`, `sce.outcome`, `sce.error.class`, and, when present as non-empty strings in the Claude hook stdin payload, `sce.hook.event` (`hook_event_name`), `sce.hook.tool` (`tool_name`), `sce.claude.session_id`, and `sce.claude.tool_use_id`. `sce.hook.command` is the stable SCE entry point (`ClaudeHookCommand`: `diff-trace`, `conversation-trace`, `claude-mutation-scope`, `claude-model-state`, `policy-bash`), so the several SCE hooks that one Claude event runs produce distinguishable spans; each Claude hook entry point records it with `trace_export::record_claude_hook_command` as its first step, before reading stdin, so the span carries it even when stdin is empty, cannot be read, or is not JSON, and when the hook then fails. `trace_export::record_claude_hook_payload(stdin)` is the only payload reader: each entry point passes its stdin to it once after a successful read, it returns immediately when the current span is disabled (Noop), and it copies only those four fields. Session and tool-use IDs are opaque correlation identifiers: span attributes only, never metric attributes, never used to derive a trace ID. Tool input and response, prompts, `cwd`, transcript paths, file contents, and the raw payload are never exported. Parent context: for the Claude `sce.hook` kind only, `ManagedTraceTelemetry::new` reads `TRACEPARENT` (and `TRACESTATE` when present) from the process environment, extracts it with `TraceContextPropagator`, and keeps it only when the remote span context is valid; `root_span` then attaches it with `set_parent`, so `sce.hook` shares Claude Code's trace ID, its parent is the upstream span (Claude Code 2.1.301 supplies `claude_code.interaction`, making `sce.hook` a sibling of `claude_code.tool`), and its own span ID is freshly generated. Child spans created inside the instrumented hook future inherit that trace across `.await` points and worker migration. No global propagator is registered and `sce.command` never reads the variables. A missing, malformed, or all-zero traceparent (the normal case when Claude tracing is off) yields an independent SCE root. Claude `SessionStart` and `SessionEnd` hooks run outside any interaction span, so their `sce.hook` is always a root. Live status: Dash0 (dataset `sce-crocoder`) shows `sce doctor`, Claude session-boundary `sce.hook` spans, and parented tool-hook `sce.hook` spans with operation children under `claude_code.interaction`. Concurrent hook processes previously lost spans because the auth DB credential lookup failed with `LockingError` and fell back to Noop; that is fixed, and the fix is verified by multiprocess regression tests but not yet re-verified live in Dash0. The evidence and the opt-in smoke procedure are in [claude-hook-trace-propagation.md](claude-hook-trace-propagation.md). Telemetry failures never change hook stdout, permission decisions, persisted state, or exit codes. -- An admitted Codex hook process emits exactly one `sce.hook` span with `sce.agent=codex`, `sce.hook.command` (`CodexHookCommand`: `codex`, `codex-mutation-scope`), `sce.outcome`, `sce.error.class`, and, when present as non-empty strings in the Codex hook stdin payload, `sce.hook.event` (`hook_event_name`), `sce.hook.tool` (`tool_name`), `sce.codex.session_id`, `sce.codex.turn_id`, `sce.codex.tool_use_id`, `sce.codex.model`, `sce.codex.agent_id`, and `sce.codex.agent_type`. Each Codex entry point records the command with `trace_export::record_codex_hook_command` before reading stdin and passes stdin once to `trace_export::record_codex_hook_payload`, which copies only those fields. The identifiers join to native Codex telemetry: `session_id` equals `conversation.id`, `turn_id` equals `turn.id`, `tool_use_id` equals `call_id`, and a subagent `agent_id` equals the child `conversation.id` ([codex-native-telemetry-contract.md](codex-native-telemetry-contract.md#identifier-mapping)). Codex hook spans are always independent roots: `upstream_parent_context` adopts `TRACEPARENT` only for the Claude hook kind, because Codex hooks inherit `TRACEPARENT` from the process that launched Codex, never the current Codex span. No trace or parent span ID is derived from a session, turn, or tool-use identifier. Codex hooks keep their fail-open behavior; telemetry failures never change their stdout, permission decisions, persisted state, or exit codes. +- An admitted Codex hook process emits exactly one `sce.hook` span with `sce.agent=codex`, `sce.hook.command` (`CodexHookCommand`: `codex`, `codex-mutation-scope`), `sce.outcome`, `sce.error.class`, and, when present as non-empty strings in the Codex hook stdin payload, `sce.hook.event` (`hook_event_name`), `sce.hook.tool` (`tool_name`), `sce.codex.session_id`, `sce.codex.turn_id`, `sce.codex.tool_use_id`, `sce.codex.model`, `sce.codex.agent_id`, and `sce.codex.agent_type`. Each Codex entry point records the command with `trace_export::record_codex_hook_command` before reading stdin and passes stdin once to `trace_export::record_codex_hook_payload`, which copies only those fields. The identifiers join to native Codex telemetry: `session_id` equals `conversation.id`, `turn_id` equals `turn.id`, `tool_use_id` equals `call_id`, and a subagent `agent_id` equals the child `conversation.id` ([codex-native-telemetry-contract.md](codex-native-telemetry-contract.md#identifier-mapping)). Codex hook spans are always independent roots: `upstream_parent_context` adopts `TRACEPARENT` only for the Claude hook kind, because Codex hooks inherit `TRACEPARENT` from the process that launched Codex, never the current Codex span. No trace or parent span ID is derived from a session, turn, or tool-use identifier. Codex hook telemetry failures never change stdout, permission decisions, persisted state, or exit codes. [Live verification](codex-native-telemetry-contract.md#live-verification). - Operation child spans: `trace_export::in_child_span(ManagedChildSpan, future)` wraps an existing operation in one of three named spans, each carrying only `sce.outcome` (`success`/`failure` from the operation's `Result`): `sce.mutation_scope` around every Claude and Codex adapter seam call (one coordinate or abandon boundary), `sce.git_snapshot` around the coordinator's tree capture and pin, and `sce.persistence` around the mutation-store phase of a coordinate boundary (initialize, scope/provenance registration, CAS commit loop) and of an abandon. The hierarchy is `sce.hook → sce.mutation_scope → {sce.git_snapshot, sce.persistence}`. A child span exists only when its operation runs: a read-only tool, an untracked background shell, or a close with no matching attempt exports `sce.hook` alone. Snapshot-failure taint persistence and conversation/diff-trace Agent Trace DB writes have no span. The span filter depends on the span kind: a `sce.command` dispatch exports only `sce.command` (ordinary commands that reach the coordinator, such as ref maintenance, still export one span), and a `sce.hook` dispatch exports only `sce.hook` and the three child names. Without a managed hook dispatch the child spans are disabled, and they never change ordering, locking, or errors. - The exporter uses a bounded batch queue on a dedicated thread. Final stdout/stderr rendering and classified-error logging run inside the command span (`run_command_lifecycle_with_context`), so `sce.outcome` reflects the rendered result (a stdout write failure is `failure`) and the final `sce.error.*` log is exported. Trace and log providers shut down concurrently under one shared `SHUTDOWN_TIMEOUT` (3s) deadline after rendering; failures never change command results or exit codes. - Process lifetime: `app::run_process` owns the Tokio runtime (at least two workers) and ends it with `shutdown_timeout(RUNTIME_SHUTDOWN_GRACE)` (500ms), so a stalled keychain, database, or exporter worker cannot keep the process alive. The async deadlines bound when the command proceeds; the runtime grace is the hard process-level bound. Abandoned workers are not cancelled, only no longer awaited. diff --git a/context/sce/codex-native-telemetry-contract.md b/context/sce/codex-native-telemetry-contract.md index 8cbc31a69..807c64b38 100644 --- a/context/sce/codex-native-telemetry-contract.md +++ b/context/sce/codex-native-telemetry-contract.md @@ -1,6 +1,6 @@ # Codex native telemetry contract -Probe evidence for Codex CLI 0.172.0 native OpenTelemetry export, the `otel.headers_helper` invocation contract, configuration precedence, command-hook trace context, and identifier mapping. This file records the implementation decision for native Codex telemetry and Codex hook spans, and the Claude/Codex parity matrix. +This contract records the Codex OpenTelemetry probe, the shipped launcher and hook behavior, and live Dash0 verification. The minimum verified Codex CLI version is **0.172.0**. ## Provenance @@ -58,9 +58,9 @@ A helper header reaches every explicit `otlp-http` exporter in the effective con | `codex` interactive, new session | Observed under a pty: `service.name=codex_cli_rs`. The helper got the launch-time argv and ran from `CODEX_HOME`. | Yes, for the first thread. | | `codex exec` | Observed: `service.name=codex_exec`. The thread and hook `cwd` equal the launch directory. | Yes. | | `codex exec resume ` without `-C` | Observed: launched from repository B, the session and every hook ran in repository A (the stored session cwd). | **No.** The launch directory does not identify the working repository. | -| `codex exec resume -C ` | Observed: the session ran in ``. | Yes, when the repository is resolved from `-C`. | +| Non-interactive resume with explicit `-C ` | Observed: the session ran in ``. | Yes, when the repository is resolved from `-C`. Codex 0.172.0 accepts `codex exec -C resume `. | | `codex exec fork ` | Observed: the new session id ran in the launch directory, not in the source session's cwd. | Yes. | -| `codex resume` / `codex fork` (interactive) | Source: `tui/src/cwd_prompt.rs` asks the user to choose between the session directory and the current one, and defaults to the session directory. | No. The choice is made after launch. | +| `codex resume` / `codex fork` (interactive) | Source: `tui/src/cwd_prompt.rs` can ask the user to choose between the session directory and the current one. The T01 directory probe used `exec resume`. | Unverified for telemetry. | | `-C ` | Observed with resume. The process working directory is irrelevant to the helper. | Resolve the repository from `-C` when present. | | In-process directory change or multiple threads | Source and observed: the helper command is fixed per process, while threads (subagents, `/new`, in-TUI resume, app-server) each carry their own cwd. Subagents inherit the parent's cwd (observed). | Not safe for a thread whose cwd leaves the launch repository. This is a residual risk; Codex exposes no per-thread hook into the helper. | | `codex app-server` / remote | Not probed. Multi-client and multi-thread by design. | Unproven. | @@ -120,39 +120,37 @@ Resource attributes on all signals: `service.name` (`codex_exec` | `codex_cli_rs | Personal identifiers | `user.email` and `user.account_id` on every Codex log event (observed) | No config control. | | Spans and metrics | No prompt, response, tool-argument, or output attributes observed. `cwd` paths appear on a few spans. | — | -Every content-bearing field is on the log signal. Spans and metrics carry identifiers, counts, and durations only. +The probe found prompt, response, and tool content on the log signal. Spans and metrics carry operational metadata. Some spans include absolute working directories. ## Implementation decision 1. **Hook spans ship without a launcher.** `sce hooks codex` and `sce hooks codex-mutation-scope` are admitted to managed telemetry as Codex-only hook subcommands. Each exports one `sce.hook` span (`sce.agent=codex`). Verified correlation attributes are `sce.codex.session_id` (the raw stdin `session_id`), `sce.codex.turn_id`, `sce.codex.tool_use_id`, `sce.codex.model`, and, for subagent hook runs, `sce.codex.agent_id`/`sce.codex.agent_type`. Every span is an independent root, with **no `TRACEPARENT` extraction** for Codex. `sce.mutation_scope`, `sce.git_snapshot`, and `sce.persistence` children reuse the existing contract. 2. **Native export requires a thin `sce codex` launcher.** A user-level `config.toml` install cannot identify the repository: the helper runs from `CODEX_HOME` with no repository context, and a fixed user-level command would attribute every repository to one credential. The launcher resolves the repository and effective access policy first, then `exec`s `codex` with process-local overrides only: - - `otel.headers_helper` set to `"" auth telemetry-headers --repo ''`, under the hidden flag name T02 chooses; - - `otel.headers_helper_refresh_interval_ms=300000`, matching the Claude 5-minute debounce; - - `otel.trace_exporter` and `otel.metrics_exporter` = `otlp-http` with `endpoint = MANAGED_OTLP_ENDPOINT + "/v1/traces"` / `"/v1/metrics"` and `protocol = "binary"` (`MANAGED_OTLP_PROTOCOL = http/protobuf`); - - **`otel.exporter = "none"`**: native log export stays off, because 0.172.0 cannot redact tool arguments or the user email from logs. Tokens, cache, model, tool counts, and durations remain available from metrics and spans. - - `otel.log_user_prompt=false`, `otel.log_agent_responses=false`, and `otel.log_guardian_assessments=false`, pinned explicitly; - - optionally `otel.span_attributes.sce.repository.id=` for trace-side repository attribution. This is a T02 local choice, traces only. - No credential appears in arguments or files, and no global Codex config is written. -3. **Safe modes.** The launcher enables native telemetry for new interactive sessions, `exec`, `exec fork`, and `resume`/`exec resume` **only with an explicit `-C`** (the repository is resolved from `-C` when present). It launches **without SCE telemetry**, with a one-line notice, for `resume` without `-C`, interactive `fork`, `app-server`, `exec-server`, `remote-control`, `cloud`, `mcp`, and unknown subcommands. In-process thread switching to another repository is a recorded residual risk. + - `otel.headers_helper` runs `'' auth telemetry-headers --repo ''`. The launcher shell-quotes both paths. + - `otel.headers_helper_refresh_interval_ms=300000` sets a five-minute timer. + - `otel.trace_exporter` and `otel.metrics_exporter` use `otlp-http` with `protocol = "binary"` and the managed endpoint's `/v1/traces` and `/v1/metrics` paths respectively. + - `otel.exporter = "none"` disables native log export. Codex 0.172.0 cannot redact tool arguments or user email from logs. + - `otel.log_user_prompt`, `otel.log_agent_responses`, and `otel.log_guardian_assessments` are all `false`. + + The helper supplies the credential at runtime. The launcher passes no credential in its arguments and writes no Codex config. It adds no repository span attribute. +3. **Safe modes.** The launcher enables native telemetry for new interactive sessions, `exec`, `exec fork`, and `exec resume` with an explicit `-C` (or `--cd`) before `resume`. The repository comes from that directory when supplied. Interactive resume, interactive fork, worktree launches, and remote launches run without SCE native export. The [launcher reference](codex-native-telemetry-launcher.md#invocation-modes) lists the modes and skip notices. In-process thread switching can leave native export bound to the original launch repository. 4. **Conflict detection.** The launcher skips native telemetry and reports the reason, never overwriting anything, when any of the following holds: - `$CODEX_HOME/config.toml` or the selected profile file defines `otel.exporter`, `otel.trace_exporter`, `otel.metrics_exporter`, or `otel.headers_helper`, because the user owns an OTEL destination; - a readable `/etc/codex/requirements.toml`, `/etc/codex/managed_config.toml`, or `/etc/codex/config.toml` defines any `otel.*` key, because enterprise settings would override the pins or force content logging; - - the caller's arguments include an `otel.*` `-c` override or `--profile` in an unreadable form. + - the caller's arguments include an `otel` or `otel.*` override, a visible destination environment variable points elsewhere, or the user or selected profile config cannot be read or parsed. MDM and cloud requirements cannot be read and are a residual risk. Upstream still prevents a user helper from reaching a managed exporter (`headers_helper_targets`). -5. **Helper repository context.** The hidden `sce auth telemetry-headers` gains an explicit repository argument. With it, the policy gate, destination tripwire, `auth.db` presence check, repository-binding lookup, and `CREDENTIAL_LOOKUP_DEADLINE` apply to that path instead of `current_dir()`. The no-argument form stays byte-identical for Claude. The tripwire stays meaningful, because Codex passes its environment to the helper. -6. **Setup and doctor.** No `sce setup` change is needed: no Codex config is written. Doctor changes are optional and out of the minimum T02 scope. -7. **ADR.** The launcher is a substantive architectural choice, so T02 records one ADR. - -The open question "is launcher-only coverage worth its cost" is answered by evidence: plain `codex` launches cannot be attributed safely. T02 ships the launcher together with the hook spans, and a plain `codex` launch keeps only the SCE hook spans. +5. **Helper repository context.** The hidden `--repo ` selects the directory for the policy gate, destination tripwire, `auth.db` presence check, and repository-binding lookup. Repository resolution and credential lookup share `CREDENTIAL_LOOKUP_DEADLINE`. The no-argument form continues to use Claude's launch directory. Codex passes its environment to the helper. +6. **Setup and doctor.** Setup leaves Codex OTEL configuration to the launcher. Doctor reports existing managed-telemetry health without a Codex-native delivery check. +7. **Decision record.** [Native Codex telemetry via the `sce codex` launcher](../decisions/2026-11-24-codex-native-telemetry-via-sce-codex-launcher.md). ## Claude/Codex parity matrix -Claude semantics come from existing SCE context (`telemetry-credential.md`, `claude-hook-trace-propagation.md`) and Claude Code monitoring documentation. They were not re-probed in T01, and T03 confirms them in Dash0. +The Claude column draws on the [credential contract](telemetry-credential.md) and [Claude hook propagation evidence](claude-hook-trace-propagation.md). The live checks below confirm Claude hook parenting and token and cost delivery. Other Claude cells describe the existing contract. -| Capability | Claude Code (SCE install) | Codex 0.172.0 (decided mechanism) | +| Capability | Claude Code (SCE install) | Codex 0.172.0 with SCE | |---|---|---| -| Activation | User-level settings; every launch | `sce codex` launches only; plain `codex` exports nothing natively | -| Repository attribution | Helper uses the launch cwd; `vcs.*` on metrics and logs via `OTEL_METRICS_INCLUDE_REPOSITORY` | Helper gets an explicit repository argument; no native repository attribute; optional `span_attributes` on traces | +| Activation | User-level settings with authorization from the launch directory | `sce codex` enables native export on supported, authorized launches. SCE hook spans can also export during plain `codex` launches. | +| Repository attribution | Helper uses the launch cwd; `vcs.*` on metrics and logs via `OTEL_METRICS_INCLUDE_REPOSITORY` | Repository credential binding selects the workspace dataset. Some native spans carry `cwd`. The launcher adds no repository ID to spans or metrics. | | Helper refresh | Debounce 300 s; on demand | Fixed timer (300 s via launcher); start-up run; no refresh on 401 | | Helper failure | Export unauthenticated or failing | Export suspended and data dropped; one stderr warning | | Token usage | `claude_code.token.usage` counter; `input` excludes cache reads; separate `cacheRead`/`cacheCreation` | `codex.turn.token_usage` histogram per turn; `input` **includes** `cached_input`; also `cache_write_input`, `reasoning_output`, `total`. Not summable against Claude `input` without subtracting `cached_input` | @@ -163,7 +161,7 @@ Claude semantics come from existing SCE context (`telemetry-credential.md`, `cla | Prompt and response content | Prompts redacted by default | Prompts redacted; responses off; tool arguments and output excluded by disabling logs | | Native log events | Exported | Disabled (privacy) | | Native traces | Enhanced beta tracing | Exported; high volume | -| Subagent attribution | Agent names with tool details | `session_source=subagent_thread_spawn__dN`; child `conversation.id`; hook `agent_id` | +| Subagent attribution | Agent names with tool details | Metrics use `session_source=subagent_thread_spawn__dN`. The hook's `sce.codex.agent_id` matches the child's native `conversation.id`. | | SCE hook spans | `sce.hook`, `sce.agent=claude`, `sce.claude.*` | `sce.hook`, `sce.agent=codex`, `sce.codex.*` | | Hook span parenting | `TRACEPARENT` → `claude_code.interaction` span | Independent root; Codex never propagates current-span context | | Hook-to-native join | `tool_use_id` ↔ `claude_code.tool` | `session_id` ↔ `conversation.id`, `turn_id` ↔ `turn.id`, `tool_use_id` ↔ `call_id` | @@ -178,3 +176,39 @@ Claude semantics come from existing SCE context (`telemetry-credential.md`, `cla - There is no trace-volume or target filter configuration. - Refresh is timer-only, with no refresh on authentication failure. - Requirements-layer OTEL settings override runtime `-c`. + +## Live verification + +On 2026-11-24, the SCE worktree build (`0.4.0-pre-alpha-v14` with the launcher) ran Codex CLI 0.172.0 against `https://otel.crocoderlab.dev` in the enrolled `codex-otel` repository. Queries used the Dash0 dataset `sce-crocoder` (SCE CroCoder). A receiver response alone is insufficient evidence of delivery. + +| AC8 item | Observation | +|---|---| +| Native traces and repository attribution | At 14:33 UTC, `sce codex exec` completed session `01a20df9-d0af-7321-a5fb-2798282462f2` with exit 0 and no launcher skip notice. Native trace `ab5a6cad90b461dd3e44f9ddeb4477f5` contains the `codex_exec` `apply_patch` span. Its sampling spans report a `cwd` in `codex-otel`. The workspace dataset and those span attributes establish routing and repository context for this run. Native metrics lack a repository or session identifier. | +| Hook delivery and correlation | Dash0 returned ten `sce.hook` spans for that session. Trace `e3875fe9c047dd9f25f8d982050aebd8` contains the root `codex-mutation-scope` `PostToolUse(apply_patch)` hook with `sce.agent=codex`, `sce.outcome=success`, and `sce.codex.model=gpt-6.2-sol`. Its descendants are `sce.mutation_scope`, `sce.git_snapshot`, and `sce.persistence`. The root's session, turn, and tool-use IDs match native `conversation.id`, `turn.id`, and `call_id` in the separate native trace. | +| Token, cache, model, tool, and duration metrics | A Dash0 query at 14:37 UTC found six `codex.turn.token_usage` series for `gpt-6.2-sol`, including `cached_input` and `cache_write_input`. It also found native `codex.tool.call` and `codex.tool.call.duration_ms` series with that model. These are dataset-level series in the run window. Per-session metric attribution is unavailable because the series lack a conversation ID. The token semantics come from the T01 probe. | +| Cost | A `codex.*cost*` metric query for `codex_exec` at 14:37 UTC returned no series, consistent with the T01 probe. Codex 0.172.0 supplies no native cost signal. | +| Native logs and content | The `codex_exec` log query returned zero records from 14:29 UTC through the positive runs. The launcher disables native logs, so live native log delivery is unavailable by design. The inspected native `codex.turn_input` and `apply_patch` span attribute keys had no prompt, response, patch, argument, or output content fields. These checks cover the sampled spans and the observed log window. | +| Subagent attribution | A second `sce codex exec` run at 14:54 UTC completed parent session `01a20e0c-e19e-7082-a863-4e03db041822`. The `SubagentStop` hook in trace `b14670c36c4a176ef79121dc62908b4c` carries the parent session, agent type `default`, and `sce.codex.agent_id=01a20e0d-0712-7f61-8b5b-0b81791f5a5f`. That ID equals `conversation.id` on the child's `run_turn` and `codex.sampling` in native trace `c7cf8d72a47f71dbeb6cdce08e7664f8`. The dataset also has a `codex.turn.token_usage` series with `session_source=subagent_thread_spawn_01a20e0c-e19e-7082-a863-4e03db041822_d1`. | +| Unchanged Claude telemetry | In the concurrent Claude window, trace `fc4a49e91a65212130c11d07a3ba1523` contains `sce.agent=claude` tool hooks parented to `claude_code.interaction`. Dash0 also returned `claude_code.token.usage` and `claude_code.cost.usage` series. | +| Failed authorization | An unenrolled scratch repository with consent enabled caused the launcher to report that no credential was authorized. Codex completed session `01a20e0e-a73a-7d92-b662-66eeaf2a86de`. A direct helper check exited nonzero with the fixed diagnostic and empty stdout. | +| Repository opt-out | A scratch Git repository used the enrolled repository identity. The helper initially authorized it. After setting repository `telemetry.enabled=false`, the helper denied it and Codex completed session `01a20e0e-8dc2-7202-9eb7-b3cc805d522f`. | +| Global consent withdrawal | A process-local XDG config root supplied a global SCE `telemetry.enabled=false` while the enrolled repository still granted consent. The helper denied it and Codex completed session `01a20e0e-6b9f-7222-8b2e-f50c6ccbfdf4`. The live check covered new launches. A running process keeps its cached headers until the next helper refresh. | +| Negative-run Dash0 check | The three denial runs started between 14:55:55 and 14:56:10 UTC. A query in `sce-crocoder` found zero spans matching their `conversation.id` or `sce.codex.session_id`. Native metrics have no session ID, so this query cannot establish per-session metric absence. | +| Credential replacement, expiry, and logout | Live delivery was not verifiable with the existing usable credential. Inducing these cases against the managed collector requires a disposable authenticated session with separately replaceable or expiring credentials. The isolated `telemetry_credential_storage` tests passed for replacement, expiry, and logout. The T01 loopback probe verified suspension and recovery at helper refresh. | +| Two repositories in different workspaces | Live routing was verified for one enrolled workspace. A second authorized workspace session and its enrolled repository were unavailable for this check. The isolated storage suite passed the cross-workspace rejection test. The unenrolled scratch repository only exercises failed authorization. | +| Preservation of user-owned and managed config | The real launcher detected a user-owned exporter in scratch `CODEX_HOME`, passed the original arguments to a Codex stub without telemetry overrides, and left both scratch and normal user config hashes unchanged. There was no local `/etc/codex` config or inspectable MDM/cloud fixture. The targeted launcher suite passed the injected managed-system conflict test. | + +### Repeat the live smoke check + +1. Use Codex 0.172.0, an enrolled repository with trusted SCE hooks, an authorized SCE login, and read access to its Dash0 workspace dataset. Use a synthetic turn and a disposable worktree for an `apply_patch` check. +2. Run `sce codex -C exec`. Retain the session ID and UTC window. Run a separate turn with a subagent for the child-identity check. +3. In Dash0, locate the native trace by `conversation.id` and the SCE hook by `sce.codex.session_id`. For a tracked tool, compare the turn and call IDs and check the independent root and operation children. For a subagent, compare `sce.codex.agent_id` to the child's `conversation.id`. +4. Query Codex token and tool metrics for the time window. Check that Codex-native logs are absent and inspect attribute keys on the turn and tool spans. Record only identifiers and metadata needed to reproduce the query. + +## Control Plane follow-ups + +- Map Codex token, cache, model, tool, and duration signals into ingestion and dashboards. Keep Codex's inclusive `input` separate from Claude's uncached input, or subtract `cached_input` before comparing them. Preserve each signal's units and temporality. +- Derive cost only where model pricing and cache categories are known. Label derived values separately from Claude's native USD cost metric. +- Join native and SCE traces by the observed session, turn, and tool IDs. Keep workspace routing separate from repository grouping, and avoid implying per-session or per-repository attribution for native metric series that lack those identifiers. +- Measure trace volume and decide which spans and attributes the collector needs to retain, including whether to retain absolute `cwd` values. Keep native logs disabled until Codex can redact tool content and personal identifiers. +- Verify replacement, expiry, logout, and routing across two enrolled workspaces with disposable live credentials. Recheck managed-config behavior in an enterprise environment. diff --git a/context/sce/codex-native-telemetry-launcher.md b/context/sce/codex-native-telemetry-launcher.md index 227d09cce..7de34d926 100644 --- a/context/sce/codex-native-telemetry-launcher.md +++ b/context/sce/codex-native-telemetry-launcher.md @@ -2,7 +2,7 @@ `sce codex [codex arguments...]` launches Codex CLI with Codex's own OpenTelemetry export pointed at the managed collector. The export uses a repository-scoped telemetry credential. A plain `codex` launch exports no native telemetry. SCE Codex hook spans are independent of the launcher (see [cli-observability-contract.md](cli-observability-contract.md#managed-trace-export)). -Code: `cli/src/services/codex_telemetry/` (`mod.rs` for classification, conflict detection, and overrides; `command.rs` for execution). Decision: [ADR](../decisions/2026-11-24-codex-native-telemetry-via-sce-codex-launcher.md). Probe evidence for Codex 0.172.0: [codex-native-telemetry-contract.md](codex-native-telemetry-contract.md). +Code: `cli/src/services/codex_telemetry/` (`mod.rs` for classification, conflict detection, and overrides; `command.rs` for execution). Decision: [ADR](../decisions/2026-11-24-codex-native-telemetry-via-sce-codex-launcher.md). The minimum verified Codex CLI version is 0.172.0. [Probe evidence](codex-native-telemetry-contract.md) · [Live verification](codex-native-telemetry-contract.md#live-verification). ## Launch flow @@ -32,14 +32,16 @@ flowchart TD | --- | --- | | New interactive session, with or without a prompt | Yes | | `exec`, `e`, `exec fork` | Yes | -| `resume`, `exec resume` with `-C ` (before or after the subcommand) | Yes; the repository comes from `` | -| `resume`, `exec resume` without `-C` | No; the session runs in its stored directory | +| `exec resume` with `-C ` before `resume` | Yes. The repository comes from ``. | +| `exec resume` without `-C` | Plain launch. The session runs in its stored directory. | +| Interactive `resume` | Plain launch. Repository attribution is unverified even with `-C`. | | Interactive `fork` | No; the directory is chosen after launch | -| `app-server`, `exec-server`, `remote-control`, `cloud`, `mcp`, `mcp-server`, `review`, `exec review` | No; unproven | -| `login`, `logout`, `completion`, `features`, `apply`, `sandbox`, `debug`, `help`, `-h`, `--help`, `-V`, `--version` | No; sessionless, without a notice | +| Other session modes, including `agents`, `queue`, `app-server`, `cloud`, `review`, and `exec review` | Plain launch. Repository attribution is unverified. | +| `--worktree`, `--remote`, or `--remote-auth-token-env` | Plain launch. Repository attribution is unverified. | +| Sessionless commands, including `login`, `logout`, `doctor`, and `help`, and the help and version flags | Plain launch without a notice. | | An option the launcher does not recognize | No; the value boundary is unknown | -`-C`/`--cd` sets the launch directory, resolved against the process working directory. The repository root is the nearest ancestor with a `.git` entry. +The launcher checks options before `--`, including options after a prompt or session ID. `-C`/`--cd` sets the launch directory, resolved against the process working directory. The repository root is the nearest ancestor with a `.git` entry. ## Conflict detection diff --git a/context/sce/telemetry-credential.md b/context/sce/telemetry-credential.md index d869f1b9b..46123e6a2 100644 --- a/context/sce/telemetry-credential.md +++ b/context/sce/telemetry-credential.md @@ -73,7 +73,7 @@ flowchart LR ## Hidden header helper -- `sce auth telemetry-headers` is a hidden (`hide = true`) subcommand intended for Claude Code's `otelHeadersHelper`. On every call it prints exactly one JSON object, `{"Authorization":"Bearer "}`, so a replaced credential is picked up on the next call. +- `sce auth telemetry-headers` is a hidden subcommand used by Claude Code's `otelHeadersHelper` and the Codex launcher's `otel.headers_helper`. On success it prints exactly one JSON object, `{"Authorization":"Bearer "}`. Each call reads the current authorized credential, so the next successful call picks up a replacement. - Launch context (verified against Claude Code 2.1.284 with a real `claude -p` run): Claude runs the helper with no arguments, with its working directory set to the directory Claude was launched from (possibly a subdirectory), and without `CLAUDE_PROJECT_DIR`. Claude's documentation states that it does not pass `OTEL_*` variables to subprocesses. The helper therefore uses only the working directory, ignores `CLAUDE_PROJECT_DIR` (a value inherited from a parent session could name another project), and never requires an `OTEL_*` variable to be present. - Authorization: the helper walks up to the enclosing Git root, resolves the repository ID with the same precedence as Agent Trace storage, and prints headers only when that repository is bound to the identity of a valid credential that the current WorkOS session owns (see Repository bindings). An unbound repository, a repository bound to another user or workspace, a directory outside Git, or a repository without a resolvable identity gets no token. `.claude/settings.json`, SCE hook markers, and remote names are never treated as proof of ownership. - Destination tripwire: if `OTEL_EXPORTER_OTLP_ENDPOINT`, a per-signal `OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINT`, or `BETA_TRACING_ENDPOINT` is visible to the helper with a non-canonical value, the helper refuses. This catches visible misconfiguration only. It is not endpoint pinning (see Security boundaries).