Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/webcodex-store/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ mod agent_task;
mod agent_wait;
mod agent_wake;
mod audit;
mod trace_query;
pub use trace_query::{ToolTraceCallRecord, ToolTraceQueryFilter};
mod communication;
mod connection_observation;
mod external_observations;
Expand Down
3 changes: 3 additions & 0 deletions crates/webcodex-store/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -633,6 +633,9 @@ impl Database {
"CREATE INDEX IF NOT EXISTS idx_action_events_operation_started
ON action_events(operation, started_at DESC)
WHERE operation IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_action_events_trace_diagnostic_time
ON action_events(COALESCE(request_observed_at_ms, window_started_at_ms, started_at * 1000) DESC, event_id DESC)
WHERE server_trace_id IS NOT NULL;
CREATE VIEW IF NOT EXISTS code_mode_action_traces AS
SELECT
event_id,
Expand Down
94 changes: 94 additions & 0 deletions crates/webcodex-store/src/trace_query.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
//! Read-only bounded diagnostic index over ActionAudit, not another trace store.
use crate::Database;
use rusqlite::params;
use serde::Serialize;

pub struct ToolTraceQueryFilter<'a> {
pub window_key: Option<&'a str>,
pub project: Option<&'a str>,
pub tool_name: Option<&'a str>,
pub since_ms: i64,
pub until_ms: i64,
pub include_nonmeaningful: bool,
pub offset: usize,
pub limit: usize,
}

#[derive(Debug, Serialize)]
pub struct ToolTraceCallRecord {
pub trace_ref: String,
pub window_key: Option<String>,
pub window_source: Option<String>,
pub project: Option<String>,
pub tool_name: Option<String>,
pub method: String,
pub observed_at_ms: i64,
pub response_handed_at_ms: Option<i64>,
pub duration_ms: i64,
pub status: String,
}

impl Database {
/// The caller must hold administrator diagnostic authority. This index is
/// not an authority oracle; UI/model adapters share the same authorized query.
pub fn query_tool_trace_calls(
&self,
query: &ToolTraceQueryFilter<'_>,
) -> anyhow::Result<Vec<ToolTraceCallRecord>> {
anyhow::ensure!(
query.since_ms >= 0
&& query.until_ms >= query.since_ms
&& query.until_ms - query.since_ms <= 31 * 86_400_000,
"invalid trace time range"
);
anyhow::ensure!(
query.offset <= 10_000 && query.limit <= 65,
"invalid trace query bounds"
);
let conn = self.lock_connection(crate::StoreDomain::Audit);
let mut statement = conn.prepare(
"SELECT server_trace_id, client_window_key, client_window_source,
project, operation, action_name,
COALESCE(request_observed_at_ms, window_started_at_ms, started_at * 1000),
response_handed_at_ms, duration_ms, status
FROM action_events
WHERE server_trace_id IS NOT NULL
AND COALESCE(request_observed_at_ms, window_started_at_ms, started_at * 1000) >= ?1
AND COALESCE(request_observed_at_ms, window_started_at_ms, started_at * 1000) <= ?2
AND (?3 IS NULL OR client_window_key = ?3)
AND (?4 IS NULL OR project = ?4)
AND (?5 IS NULL OR operation = ?5)
AND (?6 OR window_meaningful = 1)
ORDER BY COALESCE(request_observed_at_ms, window_started_at_ms, started_at * 1000) DESC, event_id DESC
LIMIT ?7 OFFSET ?8",
)?;
let rows = statement.query_map(
params![
query.since_ms,
query.until_ms,
query.window_key,
query.project,
query.tool_name,
query.include_nonmeaningful,
query.limit as i64,
query.offset as i64
],
|row| {
Ok(ToolTraceCallRecord {
trace_ref: row.get(0)?,
window_key: row.get(1)?,
window_source: row.get(2)?,
project: row.get(3)?,
tool_name: row.get(4)?,
method: row.get(5)?,
observed_at_ms: row.get(6)?,
response_handed_at_ms: row.get(7)?,
duration_ms: row.get(8)?,
status: row.get(9)?,
})
},
)?;
rows.collect::<rusqlite::Result<Vec<_>>>()
.map_err(Into::into)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,23 @@ pub(super) fn output_schema_for_tool(name: &str) -> Option<Value> {
),
])),
"read_tool_trace" => Some(wrapped_output_schema(vec![
("trace_mode", schema_type("string", "Trace mode; read_tool_trace requires full.")),
("trace_mode", schema_type("string", "Observed captured mode: metadata, full, or unknown.")),
("capture_mode", schema_type("string", "Current capture switch; separate from retained data.")),
("capture_health", open_object_schema("Process-since-start queue/budget/write failure counters; not per-trace completeness or prior-process history.")),
("response_handoff_observed", schema_type("boolean", "A handler-return event exists in the retained index; absence is inconclusive and presence does not prove remote delivery.")),
("status", schema_type("string", "available or unavailable; missing capture does not prove absent execution.")),
("coverage", schema_type("string", "Coverage boundary; observed events are not a completeness guarantee.")),
("events", array_schema(open_object_schema("One retained lifecycle or bounded diagnostic event."), "Byte- and count-bounded event page.")),
("calls", array_schema(open_object_schema("One observed ActionAudit call, with exact trace and optional Window identity."), "Time/filter-bounded call page.")),
("windows", array_schema(open_object_schema("Window candidate aggregated only from the returned call page."), "Observed candidate Windows; no guessed links.")),
("query", open_object_schema("Effective fixed query interval and filters; reuse on the next page.")),
("entry_count", schema_type("integer", "Retained trace event count.")),
("max_page_bytes", schema_type("integer", "Diagnostic event page byte bound.")),
("possible_reasons", array_schema(schema_type("string", "Possible, not established, absence reason."), "Unknown missing-capture causes.")),
("delivery_boundary", schema_type("string", "Server handoff is not downstream receipt or model reading.")),
("window_summary_scope", schema_type("string", "Window counts describe only returned calls.")),
("payload_count", schema_type("integer", "Total indexed payloads in this trace.")),
("returned_count", schema_type("integer", "Payload metadata entries returned in listing mode.")),
("returned_count", schema_type("integer", "Entries returned in the selected call/event listing mode.")),
("offset", schema_type("integer", "Listing offset.")),
("next_offset", nullable_schema("integer", "Next listing offset or null.")),
("payloads", array_schema(open_object_schema("Safe payload metadata: payload_index, phase, payload_bytes, compressed_bytes, payload_sha256, and payload_available. Native paths are never returned."), "Bounded payload metadata.")),
Expand Down
2 changes: 1 addition & 1 deletion crates/webcodex-tool-contracts/src/registry/tool_specs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ fn operator_family_descriptors(family: ToolOperatorExtensionFamily) -> Vec<ToolD
let descriptors = match family {
ToolOperatorExtensionFamily::SkillRuntime | ToolOperatorExtensionFamily::SkillManagement => skills::tool_descriptors(),
ToolOperatorExtensionFamily::MemoryRuntime | ToolOperatorExtensionFamily::MemoryManagement => memory::tool_descriptors(),
ToolOperatorExtensionFamily::TraceDiagnostics => vec![tool_descriptor("read_tool_trace", "Admin-only bounded reader for Server-hosted full tool-request traces. Omit payload_index to list safe payload metadata first; then read one bounded JSON payload by index. Available only when full trace mode is enabled. Trace payloads may contain sensitive tool data and never grant execution authority.")],
ToolOperatorExtensionFamily::TraceDiagnostics => vec![tool_descriptor("read_tool_trace", "Admin-only diagnostics over retained ActionAudit and Server trace files. Omit trace_ref to find calls/windows using query time range, exact Project or tool; reuse returned query bounds when paging. With trace_ref, offset/limit page metadata events (including bounded supplied/kernel arguments and context-return receipts); payload events advertise payload_index for explicit full-payload reads. Query and trace_ref cannot be combined. Missing capture is unknown, not proof the call did not occur. Stored captures remain readable after capture is disabled. No new authority, execution, or retry permission.")],
};
descriptors
.into_iter()
Expand Down
9 changes: 7 additions & 2 deletions crates/webcodex-tool-contracts/src/tool_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5197,9 +5197,14 @@ pub enum ToolCall {
client_id: Option<String>,
},

/// Admin-only bounded read of one Server-hosted full tool-request trace.
/// Admin-only diagnostic query or exact retained metadata/full trace read.
/// Omit trace_ref to query calls by time/Project/tool/Window; supply it to
/// read an event page, or add payload_index for one retained full payload.
ReadToolTrace {
trace_ref: String,
#[serde(default)]
trace_ref: Option<String>,
#[serde(default)]
query: Option<crate::tool_inputs::ToolTraceQuery>,
#[serde(default)]
offset: Option<usize>,
#[serde(default)]
Expand Down
3 changes: 3 additions & 0 deletions crates/webcodex-tool-contracts/src/tool_inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize};

mod trace;
pub use trace::ToolTraceQuery;

pub use webcodex_core::workflow_session_contract::{ExecutionPurpose, ExecutionShell, SessionMode};

/// Serde default helper: `true`. Used by `ToolCall` variants whose `allow_patch`
Expand Down
32 changes: 32 additions & 0 deletions crates/webcodex-tool-contracts/src/tool_inputs/trace.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
//! Operator diagnostic selection, never a Window/Session authority grant.
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ToolTraceQuery {
/// Exact observed Window key. Omit to discover candidates by time/Project/tool.
#[serde(default)]
#[schemars(length(min = 64, max = 64))]
pub window_key: Option<String>,
/// Exact canonical Project id; paths and short Project refs are not query aliases.
#[serde(default)]
#[schemars(length(min = 1, max = 512))]
pub project: Option<String>,
/// Exact canonical operation name.
#[serde(default)]
#[schemars(length(min = 1, max = 128))]
pub tool_name: Option<String>,
/// Inclusive Unix milliseconds; omission starts 24 hours before until_ms.
#[serde(default)]
#[schemars(range(min = 0))]
pub since_ms: Option<i64>,
/// Inclusive Unix milliseconds; omission uses the query's observed current time.
/// Copy the returned effective range when paging. Maximum span is 31 days.
#[serde(default)]
#[schemars(range(min = 0))]
pub until_ms: Option<i64>,
/// Include passive UI polling and support calls. Default false.
#[serde(default)]
pub include_nonmeaningful: bool,
}
2 changes: 2 additions & 0 deletions crates/webcodex-tool-runtime-contracts/src/tool_audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2315,11 +2315,13 @@ impl ToolCallAuditProjection for ToolCall {
}),
Self::ReadToolTrace {
trace_ref,
query,
offset,
limit,
payload_index,
} => serde_json::json!({
"trace_ref": trace_ref,
"query_present": query.is_some(),
"offset": offset,
"limit": limit,
"payload_index": payload_index,
Expand Down
95 changes: 85 additions & 10 deletions docs/agent/tool-request-tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,66 @@ is actually required.

## Enable a bounded capture

Tracing is disabled by default. Metadata mode records lightweight lifecycle
information; `full` additionally captures request/response payloads for forensic
debugging.
Tracing is disabled by default. `metadata` now persists lifecycle events and
bounded operator diagnostic details for selected development tools; it is no
longer journal-only. It retains actual paths, selection parameters and bounded
command/argv text, while omitting large bodies and credential-labelled fields.
`full` additionally captures request/response payloads. This is operator data,
not the safe business-audit projection; arbitrary inline secrets in commands or
arguments are not guaranteed to be redacted.

```text
WEBCODEX_TOOL_REQUEST_TRACE=full
WEBCODEX_TOOL_REQUEST_TRACE=metadata
WEBCODEX_TOOL_REQUEST_TRACE_DIR=/var/lib/webcodex/tool-request-traces
WEBCODEX_TOOL_REQUEST_TRACE_RETENTION_HOURS=168
WEBCODEX_TOOL_REQUEST_TRACE_MAX_TOTAL_BYTES=2147483648
```

Apply the Server environment change using the normal deployment lifecycle, then
reproduce the target call once. Disable `full` tracing again when the diagnostic
capture is complete.
Apply the Server environment change using the normal deployment lifecycle.
Use `full` only when the omitted body is necessary to reproduce a specific
problem, and disable it again after capture. Changing this switch does not
reconstruct earlier omitted data. Already-retained metadata and payloads remain
readable by an administrator when capture is off.

In WebUI, open Work / Windows and use **Find calls by time or Project**. A Window
hash is optional. Calls in the existing Window activity view also have an explicit
**Inspect call diagnostics** action. Listing and expansion never automatically
fetch full payloads or introduce a refresh timer. The shared MCP reader remains
the admin-only `read_tool_trace` operator extension, behind its existing protocol
and authority checks; no new Direct tool is added.

Examples of `read_tool_trace` arguments:

```json
{"query":{"project":"agent:xa:webcodex","tool_name":"work_on_project"},"limit":20}
```

```json
{"trace_ref":"<exact-server-trace-uuid>","limit":20}
```

```json
{"trace_ref":"<exact-server-trace-uuid>","payload_index":0}
```

Use either query filters or an exact trace, not both. Default query range is the
last 24 hours; explicit Unix-millisecond ranges may span at most 31 days. Copy
the returned effective `query` and `next_offset` when paging. The retained
ActionAudit index is live: late inserts and retention can change later pages;
a fixed time range is not a transaction held across requests. Window summaries
cover the returned page only. Missing Host Window identity stays missing.

The default trace listing returns lifecycle/diagnostic **events**, including
payload-index entries when full data exists. A full payload is fetched only by
an explicit `payload_index` read; its existing size/digest/private-file checks
remain enforced. Unknown or malformed selectors never authorize another read.

## Server trace layout

Each captured request has a Server-generated `server_trace_id`. The default full
store keeps one directory per trace under the configured trace root. The trace
directory contains lifecycle events plus compressed JSON payloads, for example:
Each captured request has a Server-generated `server_trace_id`. Both enabled
modes use the existing private, bounded trace directory and background writer.
Metadata writes only `events.jsonl`; full can additionally write compressed JSON
payloads. The following raw file commands are operator-only, for example:

```bash
TRACE_ROOT=/var/lib/webcodex/tool-request-traces
Expand All @@ -52,6 +92,34 @@ For example, a caller-visible wrapper field such as
`context_request` can be compared between the raw and effective
argument layers without making that field part of ordinary user troubleshooting.

## Metadata evidence stages

- `supplied_arguments`: selected bounded arguments and `_wc` before MCP envelope
parsing; gateway entry and selected target remain distinct. `_wc` is captured
even on other ordinary tools, without copying their business payload. Suppressed
trace-reader/continuation tools keep their existing sensitive-data exclusions.
- `kernel_arguments`: the business arguments entering the canonical parser after
adapter envelope processing. This is not a claim that parsing, authorization,
execution or all later normalization succeeded.
- `execution_evidence`: producer-reported normalization, effect, execution state,
Job and effective timing fields before model compaction, when available.
- `response_summary`: bounded final returned selectors/outcomes and context
receipts. Instructions record source path/scope/fingerprint, content inclusion,
returned byte count, truncation and continuation, not instruction content.
Missing materials keep their actual reason (including budget omission).

Each diagnostic is at most 8 KiB, with bounded nodes, depth, fields, items and
UTF-8 text previews. Large script/stdin/file/patch/text/log bodies are omitted
without serializing them merely to find their size. An explicit truncation or
omission marker is not an empty value. There is no guarantee of complete args
when the bound is reached. A fingerprint is identity evidence, not recoverable
content. Returned instruction material does not prove model reading/compliance.

The current implementation does not add per-Window full-capture arming, automatic
failure-triggered capture, or retroactive payload reconstruction. Those require
an independently designed operator control boundary; ordinary diagnostics stay
read-only. Details: [bounded metadata diagnostics](../implementation/bounded-meta-trace-diagnostics.md).

## Runner correlation

When a request reaches a Runner, `events.jsonl` records the existing
Expand All @@ -78,6 +146,13 @@ Check the Server journal for trace-capture diagnostics. In particular:
Trace failures are fail-open for the underlying tool call: they reduce forensic
evidence but do not redefine the tool result.

Diagnostic reads return `capture_health` counters for queue/budget drops and write
failures since this Server process started. These aggregate counters neither
attribute a loss to one trace nor survive process replacement. A missing capture
returns `trace_not_retained` with possible causes instead of claiming execution
never happened. Missing handoff events are likewise inconclusive. Legacy
metadata captured only in journals is not backfilled into the file index.

## Delivery boundary

`tool_handler_returned` proves only that WebCodex handed a response to the HTTP
Expand Down
Loading
Loading