Command reference¶
Full flag reference for every agent-strace command, in the order agent-strace --help-all lists them: the commands that
review an agent pull request, the capture and session commands they need, then plumbing and labs commands.
Global options¶
| Flag | Default | Description |
|---|---|---|
--trace-dir DIR |
$AGENT_TRACE_DIR, else .agent-traces |
Trace store that commands read and write |
-h, --help |
List the commands for reviewing an agent pull request, and the capture and session commands they need | |
--help-all |
List every command, including plumbing and labs commands | |
--version |
Print the version |
The store is chosen in this order:
--trace-dir DIR, when given.$AGENT_TRACE_DIR, when set to a non-empty value. Hooks and auto-instrumentation write to the same directory, solist,replay,health,mcpand the other commands see their sessions..agent-traces.
An empty AGENT_TRACE_DIR is treated as unset. Relative paths resolve against the current working directory.
Help and labs¶
labs¶
Lists the labs commands by group, with one-line help, and exits 0. Labs commands are experimental or specialist commands outside the review job. They keep their names, flags, output and exit codes, and print no warning; only agent-strace --help leaves them out. See labs.md.
agent-strace --help also leaves out plumbing that other tools call: hook, pr-comment, export, inspect, tree, annotate, validate and backfill-meta. agent-strace --help-all lists every command.
Session IDs¶
A command that takes a session ID also takes a prefix of one.
- An exact ID wins, even when a longer ID starts with it.
run1selectsrun1, notrun10. - If
run1is in the trace directory but is not a session, for example after itsmeta.jsonis moved out,run1finds no session. It does not selectrun10.verifyreads onlyevents.ndjson, so it still checksrun1whenrun1/meta.jsonis a regular file it cannot read. - A prefix that matches one session selects that session.
- A prefix that matches two or more sessions is refused. Nothing is read or written, and the command exits 1 with one line:
The line names at most 5 IDs in sorted order, then and N more. Give a longer prefix or the full ID. agent-strace list shows the IDs. A session with a corrupt meta.json counts as a match. cost --tenant counts only that tenant's sessions. review, pr-comment, setup --verify --live, the server and MCP tools report the refusal their own way. See list.
An argument that is not a valid session ID, such as .. or a path like .agent-traces/abc123/, is refused too. That is an argument that is empty, . or .., or holds /, \ or a control character. Nothing is read or written, and the command exits 1 with one line. The line shows the argument as a Python string literal, so a control character prints as its escape:
This holds for a session ID given as an argument or with --session, --diff or --parent, and for the second ID of diff, compare and eval compare. health prints the same line. review, pr-comment and setup --verify --live print it in their own line, as in review: invalid session ID or prefix: '..'. review exits 2. An empty argument keeps its meaning in a command that gives it one, such as the latest session.
A session whose directory or meta.json is a symlink is not read, and the link is not followed. Neither is a session whose meta.json is not a regular file. Such a session counts as not found. list does not show it, and a command given its ID prints Session not found: ID and exits 1. The hooks and the collector still refuse to write to it.
Recorded text in output¶
Traces keep the raw text, which can hold escape codes and line breaks.
replay, record -v, record-http -v, explain, tree, approval list,
dashboard, review, pr-comment, standup, oncall, cognitive-debt,
cost, fingerprint, drift, skills, token-budget, budget-report,
team-report, regression, annotate --list, optimize, audit,
audit-readiness, verify, policy generate, policy backtest,
policy diff, policy coverage, mcp-scan, a2a-tree, why, timeline,
diff, compare, postmortem, stats, list, import --discover and the record types in the import summary show each character that
Python's str.isprintable() rejects as its escape, such as \x1b, \n or
\u202e, so recorded text cannot move the cursor, hide a command or write to
the clipboard. pr-comment posts
the same escapes, so a bidi control cannot make one path look like another on
the pull request. In the Markdown from review --format markdown and
pr-comment, CR and LF show as spaces. In prompts, responses, tool output,
error messages, reasons, annotation notes, cluster descriptions, standup
uncertainty lines, phase names, hint phrases, test results, A2A tasks and the
postmortem root cause and recommendations, each run of whitespace shows as
one space instead. The optimize preview splits the proposed addition at LF
only, as --apply writes it, and shows each line on its own + line, so a CR
or U+2028 shows as an escape. The prompt that compare --rerun prints keeps
its lines and indentation, and shows each backslash as \\, so its escapes
read back to the exact prompt. inspect, approval show,
review --format json, cognitive-debt --format json,
regression --format json, annotate --list --export-format json,
timeline --format json and compare --format json print JSON with the raw
text. Every JSON and CSV output keeps the raw text, and so do the fingerprint
files that fingerprint --output and drift --save-baseline write, and the
postmortem.md file that postmortem writes. export --format csv,
cost --breakdown provider --csv and team-report --export csv change only a
lone UTF-16 surrogate, such as \ud83d. UTF-8 cannot encode one, so they
write its escape, the same text the trace file holds.
Review an agent pull request¶
review¶
agent-strace review [SESSION_ID ...] [--format text|json|markdown]
[--branch NAME] [--fail-on STATUSES]
[--min-confidence low|medium|high]
[--findings NAMES] [--config FILE]
[--evidence-packet FILE] [--cognitive-debt FILE]
[--cognitive-debt-mode report|check]
[--artifact-url URL]
[--commits RANGE] [--otel-logs FILE]
[--agent-trace-records FILE]
[--publish-note | --from-note] [--entire]
[--strict-links] [--ci-checks]
[--disclosure off|report|check] [--pr-body FILE]
[--junit FILE] [--change-record FILE] [--approvals]
present, partial, missing, inconclusive), a confidence (high,
medium, low), and its evidence source. Prompt text and command strings are
never printed. See review.md.
| Flag | Description |
|---|---|
SESSION_ID ... |
Session IDs or prefixes; otherwise use sessions attributed to the current branch |
--format text\|json\|markdown |
Terminal text, versioned JSON, or a PR comment body (default: text) |
--branch NAME |
Branch to link sessions by (default: from CI or git) |
--fail-on STATUSES |
Comma-separated statuses that fail: missing, partial, inconclusive, or none (default: missing) |
--min-confidence low\|medium\|high |
Lowest confidence that can fail the check (default: medium) |
--findings NAMES |
Comma-separated findings the threshold applies to: rationale, scope, validation, stewardship, evidence (default: all) |
--config FILE |
Config file with a review block (default: .agent-strace.yaml, .yml, or .json if present) |
--evidence-packet FILE |
Evidence packet HTML from share. Shown as uploaded, local and not uploaded, or not generated. |
--cognitive-debt FILE |
JSON from cognitive-debt --format json. Reads schema_version 1 and status. unknown is unavailable, never a pass. |
--cognitive-debt-mode report\|check |
report adds the result. check also fails unless the result is a pass (default: report). |
--artifact-url URL |
https URL of the uploaded artifact. Without it, files are shown as not uploaded. |
--commits RANGE |
Git revision range to read Entire-Checkpoint, Agent-Logs-Url, Claude-Session, Assisted-by and Generated-by trailers, agent co-authors, and Copilot cloud agent authors from |
--otel-logs FILE |
Claude Code OpenTelemetry logs export to read safety_event from |
--agent-trace-records FILE |
Agent Trace records to read line attribution from |
--publish-note |
Write the findings to a git note on HEAD in refs/notes/agent-strace. Needs a session named on the command line or matched by branch. See review notes. |
--from-note |
When no session is linked, read the findings from the review note for the head commit |
--disclosure off\|report\|check |
Compare the AI assistance the PR declares with the agent evidence. report adds the result, check also fails on evidence_not_declared or agent_signoff (default: the config file, then off) |
--pr-body FILE |
PR description to match disclosure patterns in (default: the GitHub pull_request event, then GitLab's CI_MERGE_REQUEST_DESCRIPTION). Needs the check on with pr_body as a source. |
--entire |
When no session is linked by name, by branch or by the pull request's changed files, review the Entire checkpoints that Entire-Checkpoint trailers in --commits name, read from this clone with git. With --from-note, the review note is read when no checkpoint session is. Needs --commits; cannot be combined with --publish-note. See Entire checkpoints. |
--strict-links |
Review only agent-trace sessions named on the command line, matched by branch, or that wrote the pull request's files in this repository (file_overlap). A session linked by commit_time, latest, file_overlap_other_branch or file_overlap_unverified is refused: listed as refused, not reviewed, and with --entire or --from-note the Entire checkpoints or the review note are read in its place. Review notes are not session links, so a note found by a weak note link is still read, with low evidence confidence. With no session left every finding is inconclusive, which the default threshold passes. --fail-on replaces the default threshold, so fail such a pull request with a second, Evidence-only run: --fail-on inconclusive --min-confidence low --findings evidence. See strict links. |
--ci-checks |
Also read the GitHub check runs and commit statuses on the head commit (the pull request's head in a pull request job, else the end of --commits, else HEAD) and check the session's test runs and "tests passed" claims against them. A red CI after the session's tests passed, after a review note reported a present validation, or after the agent said they passed, makes a present validation finding partial. Needs GITHUB_TOKEN or GH_TOKEN and GITHUB_REPOSITORY or a GitHub origin remote. When CI cannot be read, stderr says why, the finding records unreadable, and the result is unchanged. Without the flag no CI is read. Cannot be combined with --publish-note. See check test claims against CI. |
--junit FILE |
Also write the review as JUnit XML, for the test report and merge check of GitLab, Azure Pipelines, Bitbucket Pipelines, Jenkins or any CI that reads JUnit. See gate merges on any forge. |
--change-record FILE |
Also write a JSON change record of the pull or merge request, for change-management evidence. See change record. |
--approvals |
With --change-record, read the GitHub pull request's reviews and commits into the record's approval block, with whether an approval of the change's head SHA is independent of the author, the commit authors and the session operators. A bot's approval is listed but never independent. Reads GITHUB_TOKEN or GH_TOKEN. Never changes the gate. See approvals. |
--publish-note prints the push command to stderr. The note holds the
findings, the session IDs and links, and each session's event count, event
SHA-256 and hash-chain state, but no prompt or tool content. A weak link, more
than 50 sessions or 500 --commits commits, or a note over 64 KiB exits 2
and writes nothing. Otherwise the exit code follows the threshold.
--from-note looks for the PR head commit (from the pull request event, or
HEAD), then the --commits commits newest first. A note attached to a commit
comes first, then a note published for a commit with the same patch ID. A
note found any way but on the head commit is a weak link. A note that is over
64 KiB, is not valid JSON, nests too deep, or has a field of the wrong type is
unsupported and not used. The report says the findings were reported by the
author's machine and are unsigned, and JSON adds a top-level note:
| Key | Value |
|---|---|
ref |
refs/notes/agent-strace |
state |
used, not_found, unsupported, or skipped (sessions were found) |
reason |
Why no note was used, or null |
head |
The commit looked up |
commit |
The commit whose note was used or refused |
ci_commits |
Commits checked |
match |
Only when used: head, rewritten, commit, or patch_id |
link |
Only when used: note, note_rewritten, note_commit, or note_patch_id |
weak |
Only when used: true unless match is head |
newer_commits |
Only when used: commits newer than commit on the branch |
covered_commits |
Only when used: commits checked that the note names |
reported_by, signed |
Only when used: always author and false |
published_at, tool, note_head, head_patch_id, branch, sessions |
Only when used: from the note |
Entire checkpoints in review¶
--entire reads each checkpoint that an Entire-Checkpoint trailer in the
--commits range names, from refs under refs/entire/checkpoints/ or the
entire/checkpoints/v1 branch, and reviews its sessions instead of the
agent-trace sessions. Nothing is fetched or written to the repository, and the
trace store is opened read-only: the sessions live in a temporary store for the
run. Each
session is linked as entire_checkpoint, a strong link. The Evidence health
finding grades it partial, never present, with the reason
provider_blind_spot: a checkpoint is the session author's own record, read
after the session from Entire's compact transcript, and is unsigned. See
Entire checkpoints for what is read
and how a session is graded.
A session named on the command line, matched by branch, or that wrote the
pull request's changed files (file_overlap) takes precedence:
the checkpoints are not read, and stderr says so. When no Entire session is
read, stderr names any checkpoint not in the clone with the fetch command, and
the review falls back to the review note with --from-note, else to agent-trace
sessions. pr-comment --review --entire builds its findings the same way, and
also opens the trace store read-only. When it reads the checkpoints, it
neither reads nor summarizes the weakly linked agent-trace sessions. In
the GitHub Action, review-fetch-agent-refs fetches the checkpoints a pull
request names; see evidence order. A checkpoint
that cannot be read, such as one whose metadata.json is not a JSON object,
that holds a file over 64 MiB or more than 64 session directories, is skipped
and named on stderr with the reason; the other checkpoints are still read. So
is a session within a checkpoint that cannot be turned into an agent-trace
session. A field of the wrong type, such as a files_touched that is not a
list, reads as absent. One review reads at most 512 MiB from checkpoints in
total; checkpoints past that are skipped the same way. An invalid or
unreadable --commits range exits 2, even when a linked session means the
checkpoints are not read. So does a range of more than 500 commits, since
checkpoints are read from at most 500; narrow --commits.
--commits and --otel-logs add external evidence
signals to the evidence health finding: in text and markdown after the
findings, and in JSON as facts.external on the evidence finding and as
top-level external, in the same shape as health --format json. They never change a finding's status,
the threshold or the exit code. Only --disclosure check can fail on them.
--commits also reads git-ai notes when the clone
has refs/notes/ai, and --agent-trace-records adds one more signal. The
Scope finding then lists the files with agent lines that no linked session
wrote, in text as "Agent lines from external attribution, not written in a
linked session (not graded)" and in JSON as facts.external_attribution.
--disclosure adds the disclosure check: what the PR
description and the commit messages in --commits declare, compared with the
linked sessions and the external evidence. With --from-note, the sessions in
the review note on the head commit count as linked. The check's state is one of consistent,
declared_no_evidence, evidence_not_declared, agent_signoff and
not_compared, in text and markdown after the external evidence and in JSON
as top-level disclosure. The PR description is never printed. The config
keys are disclosure, disclosure_patterns and disclosure_sources.
A --commits A..B range also gives the files the PR changes
(git diff A...B). In a pull request job without it, they come from the
target branch the CI system names: GITHUB_BASE_REF on GitHub, or the GitLab,
Bitbucket, Azure Pipelines or Gerrit variable listed in
how sessions are linked. A session found only by commit time must have
written one of them: the session that wrote the most is linked by
file_overlap when it was recorded in this repository, and by the weak
file_overlap_unverified when its repository is not known. Sessions recorded
in another repository are skipped. With no overlap the report has no session,
unless the time-linked session's capture shows no file writes. Scope lists the
changed files no linked session wrote as facts.pr_files_not_written (at most
50, with facts.pr_files_not_written_count). JSON
has a top-level evidence: linked, weak (a weak session link caps every
confidence at low), or none. See the PR's changed files.
--junit writes one test case per finding, plus one for the cognitive debt
check and one for the disclosure check when they are on. A finding that fails
the threshold is a failure, and an inconclusive finding that does not is
skipped, so the file has a failure exactly when the review exits 1. Suite
properties give the result, the evidence state, the branch, the threshold and
the linked sessions. The file holds no prompt text, command strings or
timestamps. It is written before the review prints, and only when the review
exits 0 or 1: when the review exits 2, an existing file is left as it was.
--change-record writes one agent-strace-change-record/v1 JSON record: the
pull or merge request and pipeline, read from the CI environment; each linked
session with its link, evidence source and source_trace_sha256, the digest
its evidence packet records; the five findings as request, scope, testing,
human oversight and evidence health; the gate result; the keys to join the
forge's approval on; and what the record does not show. It holds no prompt
text, command strings or generation time. It is written like --junit, and
with both flags both files are written or neither is: a path that is not a
regular file, such as a directory, is refused before either is written. The two
flags cannot name the same file, which on a file system that ignores case
includes names that differ only in case. A merge queue run records no head
SHA, and its source branch is the pull request's head branch that the review
read. A pull request job whose event payload cannot be read records no head
SHA either, and the record's limits say so. A GitLab merge request from a fork
is named in the target project.
Sessions that --strict-links refused are listed as refused.
The branches and head SHA are read as the review reads them to link sessions,
and the repository is named as its host names it (on Azure Repos, with its
organization and project).
An Entire session's digest is the same on every run, and equals that of the
session import --entire --commits stores from the same range in the same
workspace.
--approvals adds the
approvals GitHub has when the record is written, compared with the change's head
SHA (in a merge queue, the pull request's head on GitHub); when they cannot be
read, the record says why, one warning line without the token goes to stderr,
and the exit code is unchanged.
Flags override the config file. Exit codes: 0 pass, 1 threshold,
cognitive debt or disclosure check failed, 2 bad config, unknown session,
unreadable --pr-body, a --commits value that is not a revision range,
--publish-note with --from-note, --approvals without --change-record, a
note that could not be published, or a --junit or --change-record file that
could not be written.
share¶
agent-strace share [session-id] [-o FILE | --stdout] [--open]
agent-strace share [session-id] --include-content [--postmortem] [-o FILE | --stdout] [--open]
agent-strace share [session-id] [--include-content] --dry-run [--format text|json]
agent-strace share --assignment [session-id] --output submission.zip
Values from the trace are escaped in the HTML, so markup in them shows as text.
The packet's Est. cost and its estimated cost breakdown appear only when the
trace records a model name or token usage. Otherwise Est. cost says not
captured and no breakdown is shown.
The packet names where its evidence came from: agent-trace session for a
session recorded by hooks or added with import, and Entire checkpoint for
one added with import --entire. An Entire packet also
names the checkpoint IDs and, after import --entire --commits, the commits
whose trailers name them. A file write made from the checkpoint's
files_touched list says it is listed there, not an observed write. A value
the checkpoint does not record, such as the start time, the duration, or the
tool calls of a session without a compact transcript, shows not recorded
instead of a time or a zero.
| Flag | Description |
|---|---|
session-id |
Session ID or prefix (default: latest session) |
-o, --output FILE |
Output path (default: session-<id>.html) |
--stdout |
Write the HTML to stdout instead of a file |
--open |
Open the written HTML in the default browser |
--include-content |
Include full prompts, responses, commands, paths, tool inputs, tool results, and other content-rich values |
--postmortem |
Include postmortem analysis; requires --include-content |
--dry-run |
Print a value-free disclosure preview instead of writing HTML |
--format text\|json |
Preview format (default: text); requires --dry-run |
--assignment |
Write a privacy-minimized assignment ZIP instead of HTML |
Use --include-content only when a full replay is required. This is the
migration path for users who previously relied on ordinary share output
containing full event payloads and every annotation. The generated file displays
a full-content warning. --postmortem now returns an actionable error unless
--include-content is also present.
Every packet embeds a versioned disclosure manifest with the packet schema,
agent-strace version, selected mode, evidence-health result, provider and
capture provenance, redaction and anonymization state, limitations, behavior
counts, and deterministic SHA-256 integrity references. Its provenance holds
evidence_source and, for an Entire checkpoint, entire_checkpoint with the
checkpoint IDs, the commits, and not_recorded, the values the checkpoint
does not record; otherwise entire_checkpoint is null. Source traces and
annotation sidecars are read-only inputs and are not changed.
--dry-run matches the selected output mode. Without --include-content, it
reports minimized. With --include-content, it reports include_content.
The preview includes category counts, included and omitted annotation counts,
redaction and anonymization actions, sensitive-field warnings, evidence-health
status, known-gap count, provider and capture provenance, included categories,
omitted categories, and limitations. It never prints prompt, response, command,
path, result, or annotation text. No HTML is written, printed, or opened.
--output, --stdout, and --open are ignored with a note on stderr, so the
flag can be appended to the command being reviewed. --format json prints one
object with session_id plus the
disclosure preview fields.
--assignment instead creates a deterministic, privacy-minimized ZIP with a
sanitized trace, offline replay, derived stats/cost/lint reports, and a versioned
manifest. It cannot be combined with --stdout, --open, --postmortem, or
--dry-run. It also cannot be combined with --include-content. Assignment
bundles keep their separate privacy format and are not evidence packets. The
output name must have a lowercase .zip suffix and is atomically written with
owner-only permissions. On Windows the file instead gets the access rules of
its folder. The trace store and the output path may pass through
root-owned operating system links such as /tmp on macOS. Other symlinks in
their parent directories are refused; see
Symlinked parent directories. See the
assignment review guide for the privacy boundary and
interpretation limits.
Every event's data must be a JSON object. If any event's data is an array,
string, number, boolean, or null (for example after a hand edit or from another
writer), share exits 1 before it writes, prints, or opens anything. This applies
to ordinary share, --dry-run, and --assignment, so the preview never succeeds
for a session that share refuses. Ordinary share and --dry-run name the first
such event by position and event type and count the rest, for example
Error: session event data must be an object: event 4 of 9 (tool_result) has
string data; 1 more event has non-object data. The message never includes data
values. The preview refuses these sessions instead of counting them, because key
names cannot be read from a non-object payload. Other commands that read event
data refuse the same way; see
Sessions with non-object event data.
Ordinary share and --dry-run also exit 1 this way when the session's
started_at, or its ended_at when it is not null, is not a Unix time in
seconds. The line is Error: session started_at must be a Unix time in seconds,
or the same for ended_at.
cognitive-debt¶
agent-strace cognitive-debt [--session ID] [--since DATE] [--until DATE]
[--by repository|branch] [--threshold N]
[--format text|json|badge] [--output FILE]
[--json-output FILE] [--badge-output FILE]
[--github-token TOKEN]
[--commits RANGE] [--agent-trace-records FILE]
Each write counts the lines it adds, read from the argument shapes of Claude Code, Codex, GitHub Copilot CLI, Cursor and Gemini CLI. Failed and dry-run calls are not counted, nor are files in no git repository, such as an agent's plan file. Local review evidence is read from the session's branch only, and only a Reviewed-by: trailer naming another person counts (weight 0.75). With --github-token, reviews and comments by people other than the pull request author count; a merged pull request alone does not. When the recorded working_dir is missing, git runs in the current checkout if one of its remotes names the session's git_repo and the recorded directory was the repository root. See Agent-written lines and Review evidence for every rule and weight.
| Flag | Description |
|---|---|
--session ID |
Score one session by ID or prefix |
--since DATE |
Start of reporting window. Accepts ISO dates or durations like 30d; default is 30d |
--until DATE |
End of reporting window. Accepts ISO dates or durations like 7d; default is now |
--by repository|branch |
Group summary rows by repository or branch. The legacy author value is accepted as an alias for repository and never emits individual rankings |
--threshold N |
Label known unreviewed coverage above this ratio; default is 0.7 |
--format text|json|badge |
Terminal text, versioned machine JSON, or Shields static JSON |
--output FILE, -o FILE |
Atomically write the complete output to a file |
--json-output FILE |
Also write the JSON report to this file, from the same run as the main output |
--badge-output FILE |
Also write the badge JSON to this file, from the same run as the main output |
--github-token TOKEN |
Optional GitHub token for merged PR review and comment evidence; local git works without it. Defaults to AGENT_STRACE_GITHUB_TOKEN, which keeps the token off the command line. |
--commits RANGE |
Also count agent lines from the git-ai notes (refs/notes/ai) on the commits in this range |
--agent-trace-records FILE |
Also count agent lines from Agent Trace records |
--json-output and --badge-output let one run write every format, so the reports agree and GitHub is asked once. They are written before the main output; if any file cannot be written, cognitive-debt exits 1 with "report output could not be written safely". In one run, each GitHub API request is made at most once and shared by every file that needs it. When a request fails, those files count no GitHub review, and one warning on stderr gives the number of failed requests.
--commits and --agent-trace-records add one workflow per source, git-ai notes or Agent Trace, and an "External attribution" block that shows AI and mixed lines on separate lines. Both count as agent-written. Lines a reported session already captured count once, under that session. The reporting window does not apply to them. A source that cannot be read, or whose every note or record is malformed, exits 1 with Error:; a clone without refs/notes/ai also prints the command that fetches it. See git-ai notes and Agent Trace records.
agent-strace watch --rules cognitive-debt:0.8 enables a live rule that alerts when a session has modified files that have not yet had human review.
The text report prints each file path relative to the session's recorded working_dir when the file is below it, and unchanged otherwise. JSON keeps the recorded path and adds relative_path, which is null when the file is not below the recorded working_dir. See File paths.
cognitive-debt exits 1 with "trace input could not be read safely" when a session it reads has a corrupt meta.json. It exits 1 with the same line when the start time of a session it reads is not usable, with or without --session. Without --session, it reads every session in the store. With --session, it prints Session not found: ID and exits 1 when no session has that ID or prefix, or when the store refuses to read the session. See Session IDs.
GitHub Actions¶
The agent-trace review composite action runs the reviewability check on a pull request, writes the table to the GitHub Actions step summary, posts or updates one PR comment, and fails the step per the threshold, so it works as a required status check. When the eval config exists, it also runs evals, adds a scored table to the step summary, and exits non-zero on regression.
permissions:
contents: read
pull-requests: write
steps:
- uses: Siddhant-K-code/agent-trace@v0.132.0
with:
config: .agent-evals.yaml
baseline: .agent-evals-baseline.json
tolerance: "0.05"
The Action runs the direct eval on the latest session in trace-dir. Save
its baseline with agent-strace eval --save-baseline .agent-evals-baseline.json
and commit the file. The Action compares a criterion only when the baseline
holds its name, and eval ci --save-baseline writes scorer names, so do not
use that file here. .agent-traces/ ignores itself in git, so commit a session
with git add -f, or restore sessions into trace-dir before the step. See
examples/ci/agent-eval.yml for a full
workflow.
| Input | Default | Description |
|---|---|---|
config |
.agent-evals.yaml |
Eval config file. With run-eval: auto, the eval runs only when this file exists. |
baseline |
none | Baseline scores file for regression gating |
save-baseline |
none | Path to write current scores as a new baseline |
tolerance |
0.05 |
Max allowed score regression (0.0 to 1.0) |
trace-dir |
.agent-traces |
Session storage directory |
python-version |
3.12 |
Python version |
install-extras |
none | Optional extras, e.g. openai,anthropic |
agent-strace-version |
none | CLI version to install from PyPI, e.g. 0.108.1. Overrides the version taken from the Action ref. Use a version no older than the Action ref: the Action's scripts pass review flags that older versions reject, and the check then ends in error. |
post-pr-comment |
auto |
Post or update the structured session summary on the PR. auto posts on pull_request and pull_request_target events when github-token is set; a comment it cannot post is a warning and leaves the result unchanged. true posts on any event and fails the step when the comment is not posted. false never posts. With review, also posts when no session exists but a review note or Entire checkpoints were read, external evidence shows agent involvement, or the review-disclosure check fails |
github-token |
${{ github.token }} |
Token for PR comments, in a merge queue to read the pull request a gh-readonly-queue/* branch tests, and with cognitive-debt-team to read the reviews of merged pull requests. The workflow token needs pull-requests: write to comment and pull-requests: read to read reviews. |
run-eval |
auto |
Run agent-strace eval. auto runs it only when the config file exists, true always runs it, false never does. Any other value fails the step. |
upload-traces |
auto |
Upload trace-dir as the agent-traces artifact. auto uploads only when the eval runs, so a job without the eval uploads no raw traces. true uploads on every run, as earlier versions did. false never uploads. Any other value fails the step. |
review |
true |
Run agent-strace review and fail the step per the threshold. With post-pr-comment, the table is added to the single PR comment. false skips it. |
review-fail-on |
none | Statuses that fail the check. Empty uses the config file, then missing. |
review-min-confidence |
none | Lowest confidence that can fail. Empty uses the config file, then medium. |
review-commits |
none | Revision range, such as origin/main..HEAD, passed as --commits to the check and to cognitive debt. Needs fetch-depth: 0. Fetches refs/notes/ai from the PR head repository for the git-ai notes, and the Entire checkpoints its trailers name, unless review-fetch-agent-refs is false. |
review-fetch-agent-refs |
auto |
With review and review-commits: read-only fetch of agent evidence refs from the PR head repository, refs/notes/ai and the Entire checkpoints that Entire-Checkpoint trailers in the range name, so the check reads the checkpoints when no agent-trace session is linked. It grades their sessions like agent-trace sessions, so their findings can fail the check per the threshold. See evidence order. auto and true fetch; true without review-commits adds a notice. false fetches neither. A range over 500 commits adds a notice and skips the checkpoints. A failed fetch never fails the job; any other value fails the step. |
review-otel-logs |
none | Claude Code OpenTelemetry logs export, passed as --otel-logs to the check |
review-agent-trace-records |
none | Agent Trace records file, passed as --agent-trace-records to the check and to cognitive debt |
review-note |
true |
With review and no session in trace-dir linked to the PR: fetch refs/notes/agent-strace from the PR head repository and use the review note. Its findings were reported by the author's machine and are unsigned. false turns this off. |
review-commits |
none | Git revision range for external evidence, such as origin/${{ github.base_ref }}..HEAD. Needs fetch-depth: 0. Also the commit messages the disclosure check reads. |
review-otel-logs |
none | Claude Code OpenTelemetry logs export in the workspace, for external evidence |
review-disclosure |
none | With review: off, report, or check, the disclosure check. check also fails on evidence_not_declared or agent_signoff. Empty uses the config file, then off. |
review-strict-links |
false |
With review: true passes --strict-links, so a session linked only by time, on another branch, or in a repository not known to be this one is refused, not reviewed. See strict links. Any other value than true or false fails the step. |
review-ci-checks |
false |
With review: true passes --ci-checks to the check, so it also reads the check runs and commit statuses on the pull request's head commit. Give the job checks: read and statuses: read, and run it after the test jobs with needs:; otherwise CI reads as pending. See check test claims against CI. Any other value than true or false fails the step. |
review-approvals |
false |
With review: true passes --approvals to the review run that writes change-record.json, so the record's approval block holds the pull request's GitHub approvals and whether one of the head is independent. Give the job pull-requests: read. Approvals usually come after the pull request opens, so run it on merge_group or on pull_request_review with types: [submitted]. Never changes the check result. See approvals. Any other value than true or false fails the step. |
cognitive-debt |
auto |
With review: false skips the report, report adds it, check also fails unless the result is a pass. unknown is never a pass. auto is false on pull_request, pull_request_target and merge_group and report on other events: cognitive debt reads GitHub reviews of merged pull requests only, so before merge it cannot see the review. Run it on the default branch after merge, or use cognitive-debt-team on a schedule. |
cognitive-debt-team |
false |
true runs the team cognitive debt report instead of the eval, the review and the PR comment: the commits on the checked-out branch in cognitive-debt-window, the Entire checkpoints their trailers name (imported into trace-dir), the git-ai notes in refs/notes/ai and review-agent-trace-records, grouped by repository. Writes the JSON, the badge and the job summary, and never fails on debt. Needs fetch-depth: 0, contents: read and pull-requests: read. For schedule and workflow_dispatch; on a pull request it warns that it cannot see the review. review-fetch-agent-refs: false skips the fetch. Any other value fails the step. |
cognitive-debt-window |
30d |
With cognitive-debt-team: the reporting window, passed as --since. A duration such as 30d or an ISO date before now; any other value fails the step. |
| Output | Description |
|---|---|
passed |
true if all scorers passed, false if one failed; empty if the eval did not run |
summary-path |
Path to the written eval summary markdown |
review-passed |
true or false when review ran; empty otherwise |
review-result |
pass, fail, or error when review ran |
review-markdown-path |
Path to review.md on the runner |
review-json-path |
Path to review.json on the runner |
review-junit-path |
Path to review.junit.xml on the runner: the review as JUnit XML, with a failure exactly when review-result is fail. Empty if review did not run or ended in error. See gate merges on any forge. |
change-record-path |
Path to change-record.json on the runner: the agent-strace-change-record/v1 record of the pull request. Empty if review did not run or ended in error. See change record. |
review-evidence |
linked, weak, or none: how the reviewed sessions were linked. Empty if review did not run. See evidence. |
evidence-packet-path |
Path to the metadata-only evidence packet; empty if not generated |
cognitive-debt-json-path |
Path to the schema v1 cognitive debt JSON, for the review session or the cognitive-debt-team report; empty if not generated |
cognitive-debt-badge-path |
Path to the Shields endpoint JSON, for the review session or the cognitive-debt-team report; empty if not generated |
cognitive-debt-status |
clean, partial, above_threshold, unknown, or empty |
cognitive-debt-result |
pass, fail, or unavailable; empty with cognitive-debt-team |
artifacts-dir |
Directory with the PR evidence files, or the cognitive-debt-team files |
evidence-artifact-url |
URL of the agent-trace-pr-evidence artifact; empty if not uploaded |
The Action ref you pin decides the CLI version:
Ref in uses: |
CLI installed |
|---|---|
Release tag vX.Y.Z |
agent-strace==X.Y.Z from PyPI. Right after a release PyPI can lag, so the step retries for about 45 seconds, then installs the Action checkout of that tag. |
Branch, commit SHA, other tag, or uses: ./ |
The Action checkout, so the code matches the ref |
Any ref, with agent-strace-version set |
That version from PyPI. The step fails if it is not installable. It must be no older than the Action ref. |
The step logs the source and version it installed. It never installs an
unpinned agent-strace.
When the eval step runs, the trace directory is uploaded as the agent-traces
artifact, also when the eval fails. It can hold prompt and tool content. A
job without the eval (no eval config, or run-eval: "false") does not upload
it. Set upload-traces to true to upload it on every run, or false to
never upload it.
With review, the evidence packet and cognitive debt files are uploaded as
agent-trace-pr-evidence, and review.json, review.md, review.junit.xml
and change-record.json as agent-trace-pr-review. See review.md.
Capture sessions¶
setup¶
agent-strace setup [--cli claude|codex|gemini|cursor|copilot|copilot-cloud|opencode|all]
[--redact | --no-redact] [--global] [--verify]
[--live] [--session SESSION_ID]
[--managed [--executable PATH]]
--cli claude prints Claude Code settings JSON for ~/.claude/settings.json (or $CLAUDE_CONFIG_DIR/settings.json); --cli codex writes $CODEX_HOME/hooks.json or ~/.codex/hooks.json, the directory Codex reads (a set CODEX_HOME must already exist; CODEX_CONFIG_DIR is ignored), first preserving an existing file once as hooks.json.agent-strace.bak, unless an enabled agent-trace Codex plugin in $CODEX_HOME/config.toml already registers the hooks, in which case it writes nothing, prints the plugin path and how to remove it, and says that it did not apply a given --redact or --no-redact (see codex-plugin.md); --cli gemini writes a Gemini CLI extension under $GEMINI_CLI_HOME/.gemini/extensions/agent-strace or ~/.gemini/extensions/agent-strace, the directory Gemini CLI loads (GEMINI_CONFIG_DIR is ignored); --cli cursor writes .cursor/hooks.json or $CURSOR_CONFIG_DIR/hooks.json; --cli copilot writes $COPILOT_HOME/hooks/agent-strace.json or ~/.copilot/hooks/agent-strace.json, unless an enabled agent-trace Copilot CLI plugin under installed-plugins already registers the hooks, in which case it writes nothing, prints the plugin path, and says that it did not apply a given --redact or --no-redact; --cli copilot-cloud writes .github/hooks/agent-strace.json and .github/hooks/agent-strace-cloud.sh at the root of the current git repository for Copilot cloud agent, prints the hooks JSON, and prints an optional copilot-setup-steps.yml without writing it (partial and unverified coverage; see copilot-cloud-agent.md); --cli opencode writes the OpenCode plugin to $OPENCODE_CONFIG_DIR/plugins/agent-trace.js, $XDG_CONFIG_HOME/opencode/plugins/agent-trace.js or ~/.config/opencode/plugins/agent-trace.js, first preserving a different file it did not write once as agent-trace.js.agent-strace.bak, and prints an opencode.json MCP entry for agent-strace mcp without writing it (see setup.md); --cli all configures all supported local CLIs and excludes copilot-cloud and opencode. Restore Codex with cp ~/.codex/hooks.json.agent-strace.bak ~/.codex/hooks.json (use $CODEX_HOME when set); repeated setup runs do not overwrite the backup. Secret redaction is enabled by default; use --no-redact only for trusted local traces.
| Flag | Default | Description |
|---|---|---|
--cli PROVIDER |
claude |
Configure claude, codex, gemini, cursor, copilot, copilot-cloud, opencode, or all (all excludes copilot-cloud and opencode) |
--verify |
off | Read-only check of installed hooks and the agent-trace CLI version; requires --cli codex or --cli claude; returns non-zero if incomplete or hooks are disabled; does not capture events. With --cli codex: Codex user-level hooks in $CODEX_HOME or ~/.codex, or instead the hooks of an agent-trace Codex plugin that config.toml enables (with a warning when hooks.json also has agent-trace hooks, so every event is recorded twice), and the config.toml [features] hooks flag; also fails if a set CODEX_HOME is not an existing directory; skips Codex profiles, -c overrides, and project, system, or managed config layers. With --cli claude: Claude Code user settings hooks, plus hook-disabling settings and agent-trace hooks in project, local, and managed settings (see setup.md) |
--live |
off | With --verify, run the static setup check and then inspect the newest recorded session whose hook evidence matches the requested provider. Reports the session, capture method, event types, boundaries, redaction, evidence health, and packaged capture-matrix gaps. Returns non-zero when matching reviewable evidence is unavailable. Supports claude and codex only and never starts a provider process |
--session SESSION_ID |
newest matching | Select a session ID or prefix for --verify --live instead of automatic newest-provider selection |
--redact |
on | Explicitly enable secret redaction in generated hook commands |
--no-redact |
off | Disable automatic secret redaction in generated hook commands |
--global |
off | Compatibility flag; Claude setup already targets the user-level settings file |
--managed |
off | Print machine-wide hooks for Copilot CLI policy (/etc/github-copilot/policy.d/agent-strace.json, or C:\ProgramData\GitHub\Copilot\policy.d\ on Windows) or a Claude Code managed settings drop-in (managed-settings.d/agent-strace.json), and print the target path on standard error. Writes nothing. Hooks run an absolute agent-strace path in exec form with hook --metadata-only. Requires --cli copilot or --cli claude; --no-redact is rejected. With --verify, read-only check of the installed managed files: root ownership and permissions (POSIX), one metadata-only hook per event, managed disableAllHooks, and the executable version; warns on user-level agent-trace hooks and an enabled agent-trace Copilot CLI plugin. --live works with --cli claude only. See Platform-team install |
--executable PATH |
agent-strace on PATH |
With --managed, the absolute path the hooks run |
Use the full live verification after recording one harmless local session:
The static configuration result and the recorded-evidence result are printed
separately. Missing or stale setup, unsupported providers, no matching session,
empty or unreadable evidence, provider mismatch, and unknown or invalid
evidence health return non-zero with a diagnostic. See
live capture verification.
health¶
agent-strace health [session-id] [--format text|json]
[--commits RANGE] [--otel-logs FILE]
[--agent-trace-records FILE]
verification_status.
Evidence health: partial
Session: abc123def456ghij
Provider: claude (from hook events)
Finalized: yes
Events: 6
Types: session_start 1, session_end 1, tool_call 1, tool_result 1, user_prompt 1, assistant_response 1
Redaction: on (recorded at session start)
Redacted: 1 of 6 events
| Status | Exit code |
|---|---|
healthy, partial |
0 |
unknown, invalid |
1 |
A missing session, an empty store or an unreadable session also exits 1.
partial passes because some providers can never be healthy: every entry
declares known gaps, so their sessions are at least partial.
| Flag | Description |
|---|---|
--format text\|json |
Output format (default: text) |
--commits RANGE |
Git revision range, such as origin/main..HEAD, to read Entire-Checkpoint, Agent-Logs-Url, Claude-Session, Assisted-by and Generated-by trailers, agent co-authors, and Copilot cloud agent authors from |
--otel-logs FILE |
Claude Code OpenTelemetry logs export (OTLP JSON or JSON Lines) to read safety_event from |
--agent-trace-records FILE |
Agent Trace records (one record, a JSON array, or JSON Lines) to read line attribution from |
--commits and --otel-logs add external evidence
signals after the health result. Each signal has a source, a status
(present, missing, unpushed or inconclusive) and a confidence. They are
reported, not graded: they never change the status, the reasons or the exit
code. A range git cannot read is reported as an inconclusive signal. A range
that is not a revision expression exits 2.
--commits also reads git-ai notes when the clone
has refs/notes/ai, and --agent-trace-records adds one more signal. Both
report AI, mixed, human and unknown line counts.
External evidence (commits origin/main..HEAD):
- Entire checkpoint 01JD4S7Y2V9Q8M3K5N6P7R8T0W: unpushed (high). Trailer present in 1 commit, not pushed: the checkpoint ref is local and waiting in Entire's push queue.
- Copilot agent logs: missing (high). No Agent-Logs-Url trailer and no Copilot cloud agent author or co-author; 3 commits read.
Reported, not graded: never changes a status or the exit code.
Each reason has a kind:
observed: found in the recorded events, such asmissing_session_end,unpaired_tool_callorsession_active.provider_limitation: declared for the provider in the packaged capture matrix, never inferred from the trace. Everyknown_gapsentry is listed verbatim, followed by one line for eachcoveragecapability markedunavailable.provider_definedcoverage adds no line. When the entry listsevents_before_startand only those event types precede the first session start,declared_events_before_session_startreplaces the observedevents_before_session_start. GitHub Copilot CLI declaresuser_prompt, because it sends the first prompt before its session start. When the entry listsresults_without_requests, result events of those types with noparent_idare reported once asdeclared_results_without_requestsinstead of one orphan each. Codex declaresllm_response.
The provider comes only from hook-written evidence: the session_start and
stop events the hooks record, or the metadata the hooks write when a session's
first hook was not SessionStart. Names set with record --name, the SDK or an
importer are not used. A session read from an
Entire checkpoint, whose
session_start mode is entire-checkpoint, applies the entire entry when no
hook evidence names a provider. When no matrix entry applies, no provider
limitations are assessed and a note says why. This covers sessions recorded by
the MCP proxy, exec wrapper or SDK, other imported sessions, providers without
an entry (Gemini CLI, Cursor) and sessions whose events name more than one
provider.
Whether the session has finished:
- Finished when its metadata records a usable end time.
- Active when the matrix marks
session_endas captured for the provider and a hook active-session marker still names the session. Active sessions reportsession_activeinstead ofmissing_session_end. A crashed session can leave its marker behind and keep reading as active. - Otherwise not known, and a missing end marker is reported as observed.
Codex installs made before setup registered its SessionEnd hook never end a
session, so those sessions keep their markers and read as active. Re-run
agent-strace setup --cli codex and trust the new hooks in /hooks.
A resumed or compacted session is assessed as one session. See session boundaries.
Event types and redaction are reported as facts. They never change the status, the reasons or the exit code.
- Event types are counted per type, in a fixed order. Only types present in the trace are listed.
- The redaction mode comes from the
session_startevents that hooks, the Copilot and Codex transcript imports and the Entire checkpoint reader write. Each one recordsredactionasonoroff, including resume and compact starts. The mode isonoroffwhen every session start recorded the same value,mixedwhen they differ or only some recorded it, andnot_recordedwhen none did. Sessions recorded before hooks wrote the field and sessions captured by the MCP proxy, exec wrapper, SDK or another importer read asnot_recorded. When a session's first hook was not SessionStart, that implicit start counts asnot_recorded, so a later resume or compact start makes the sessionmixed. A startup session start replaces that metadata, as GitHub Copilot CLI does after its first prompt. The mode is not recorded for each event. - The redacted count is the number of events whose
redactedflag is set, counted asshare --dry-runcounts them. Redaction sets the flag only when it changed something, so zero redacted events does not prove that redaction was on. Redacted session metadata is reported separately.
--format json prints the evidence-health result and the inputs supplied to it:
| Key | Contents |
|---|---|
status, reasons, provider, capture_method, capture_matrix_version, observed_start, observed_end, event_count, schema_version |
The evidence-health result. Each reason has code, message, kind and event_id |
session_id |
The resolved session |
session_finalized |
true, false (active) or null (not known) |
provider_source |
hook_events, hook_metadata, checkpoint_import (an Entire checkpoint session) or null |
event_types |
Count of each observed event type, such as {"session_start": 1, "tool_call": 2}. Empty when the session has no events |
redaction |
mode (on, off, mixed or not_recorded), session_start_modes (on, off or not_recorded for each session start in order: the implicit start first when the first hook was not SessionStart, then each session_start event), redacted_event_count and metadata_redacted |
capture_matrix |
schema_version, version (SHA-256 of the packaged matrix), the entry applied or null, its blind_spots (source, text, and capability for coverage lines) and a note when no entry was applied |
external |
Only with --commits, --otel-logs or --agent-trace-records: commits, otel_logs (file name), agent_trace_records (file name), graded (always false), shows_agent (see agent involvement) and signals, each with source (entire_checkpoint, copilot_agent_logs, claude_session, assisted_by, generated_by, agent_coauthor, claude_code_otel, commit_trailers, git_ai_notes or agent_trace_records), subject, status, confidence, detail and facts |
capture_matrix_version is empty when no entry was applied, while
capture_matrix.version always names the matrix that was consulted. To list
only the gaps found in the trace:
import¶
agent-strace import <path.jsonl>
agent-strace import --discover [--claude-dir DIR] [--copilot-dir DIR] [--codex-dir DIR]
agent-strace import --enrich [--with-text] <events.jsonl>
agent-strace import --entire [CHECKPOINT_ID ...] [--commits RANGE]
aw_session.jsonl file, a GitHub Copilot events.jsonl or a Codex rollout. A Copilot or Codex import builds a full session for runs that had no hooks installed, such as the Copilot app or sessions recorded before setup; see Copilot and Codex transcripts. --enrich adds what the Copilot hooks cannot see to a session they captured; see Enriching a Copilot hook session. --entire imports sessions from Entire checkpoints in the git clone; see Entire checkpoints.
--discover lists available sessions in ~/.claude/projects/ (--claude-dir), Copilot's session-state/<id>/events.jsonl files (--copilot-dir, default $COPILOT_HOME or ~/.copilot) and Codex rollouts under sessions/ and archived_sessions/ (--codex-dir, default $CODEX_HOME or ~/.codex). It reads only each Copilot and Codex file's first line, lists the session's working directory and path, and leaves out Codex Guardian review threads. It lists only regular files, or symlinks to them, and skips entries it cannot read, such as a broken symlink. The imported session starts with a session_start event, which holds the cwd when the log records a working directory.
The first JSON-object line that is not skipped (see below) decides the
format. A gh-aw aw_session.jsonl file starts with a session.format record;
it is read as described in Import GitHub Agentic Workflows runs,
never as a Claude Code transcript, and a first line shaped like one of its
events (a dotted type and a provenance.component) is refused for its
missing header. A Codex rollout starts with a session_meta
record, and a Copilot events.jsonl with a session.start record whose
producer is copilot-agent; both are read as described in
Copilot and Codex transcripts, whatever
the file is called. A Claude Code log also needs at least one
Claude Code transcript record, a line whose type is user, assistant, system or
summary. A Claude transcript's other lines, such as
file-history-snapshot, are skipped.
For a Claude Code log, the session ID is the first sessionId in the log
that is a usable session ID: 1 to 128 ASCII letters, digits, dots, underscores or hyphens, starting
with a letter or digit. When a log with Claude Code records has none, the ID
is the file name without .jsonl. When that is not usable either, import
exits 1. If the trace
directory already holds a session with that ID, import writes nothing,
prints Session <id> is already imported; nothing written. with the
session's directory, and exits 0, so importing the same file twice does not
duplicate its events. To import a log again, for example after the Claude
session continued, delete that directory first. Nothing is written until the
whole log has been converted, so a log that fails to import leaves no partial
session behind.
Lines that are not JSON objects are skipped, as lines that are not JSON are.
So are lines that are not UTF-8, such as a last line cut mid-character, lines
nested more than 64 levels deep and lines that hold a number too long to
convert. A field of the wrong type reads as absent: for example, message text
that is not a string, or a durationMs that is not a finite number of 0 or
more. A durationMs that would make the total duration too large to store is
skipped too. Only a whole number of 0 or more counts as tokens. In a Claude
Code log, an entry whose timestamp is not an ISO 8601 time from 1970 on,
such as a number, null or a time before 1970, is imported with the
timestamp 0.0.
These errors print one line to stderr, exit 1 and write nothing:
Session log not found: <path>: the log does not exist.Cannot read session log <path>: <reason>: the log cannot be read, for example because it is a directory, a symlink loop or a file you cannot read.Cannot import <path>: no Claude Code transcript records; import reads Claude Code transcripts, gh-aw aw_session.jsonl files, GitHub Copilot events.jsonl files and Codex rollouts only: no line is a Claude Code transcript record and the first record is not a Copilot or Codex one, for example an empty file or another tool's JSONL. Earlier versions imported such a file as an emptyclaude-codesession, named after the file when the log had nosessionId. Versions before Copilot and Codex transcripts were imported refused those two formats with a pointer tosetup.Cannot import <path>: <reason>: neither the log nor its file name or directory holds a usable session ID, the trace store refuses the session, for example because it was erased, the rollout is a Codex Guardian review thread (it is a Codex Guardian review thread, not an agent session), or anaw_session.jsonlfile has a missing, invalid or unsupportedsession.formatheader (see The header).
For an aw_session.jsonl file, the summary also prints how many events had
no recorded time (timing: inferred) and the records it did not import, by
type, for example Skipped 3 records not imported: engine.heartbeat 1,
firewall.token_usage (repeated requestId) 1, otel.span 1.
Claude Code writes one log line per content block of a model response and
repeats the response's token usage on each. The import keeps that usage once,
on the response's last line, so token totals, request counts and
cost count each response once. Sessions imported by earlier versions
count the usage once per line; delete the session's directory and import the
log again to correct their totals.
Each response's assistant_response event stores the recorded model, the
transcript message.id as message_id, stop_reason when the line has one,
and its token usage. cost prices the session from that usage, and
export --format otlp and otlp-genai turn each response with usage into a
chat {model} span with its model, token counts, stop reason and message ID,
except a <synthetic> API error message, which sent no request.
The span's start is inferred, not recorded. See
Model responses imported from a transcript.
Sessions imported by earlier versions have no message_id or stop_reason;
import the log again to add them.
Each tool_use block becomes a tool_call event that stores the block's ID
as tool_use_id (and as request_id). Each tool_result block becomes a
tool_result event linked to the earlier call with that ID in the same
conversation stream, with the call's tool_name, the time between the two
lines as duration_ms, and the result text as result; a sidechain's result
never links to a call of another stream. export --format otlp and
otlp-genai then show the call and its result as one tool span with the
toolu_... ID as gen_ai.tool.call.id, and a result marked is_error as a
failed one. A result with no earlier call of its ID stays unpaired. See
Tool results imported from a transcript.
Sessions imported by earlier versions show each call and its result as two
spans; delete the session's directory and import the log again to pair them.
Copilot and Codex transcripts¶
GitHub Copilot CLI and the Copilot app write each session to
<COPILOT_HOME>/session-state/<id>/events.jsonl. Codex writes each thread to
<CODEX_HOME>/sessions/YYYY/MM/DD/rollout-*.jsonl. Neither format is
documented, so every field is read defensively: a record or field of an
unexpected shape is skipped and counted, never trusted.
The session ID is the first 16 characters of the agent's own session ID, the
ID its hooks use: Copilot's sessionId, else the session-state directory
name, and the Codex thread id, else the UUID in the file name. The full ID
is stored as the session's conversation_id. A session the hooks already
captured is therefore never duplicated: import prints Session <id> is
already imported; nothing written. and, for a Copilot file, the
import --enrich command that adds what the hooks missed.
What is imported:
- Prompts become
user_promptevents and assistant text becomesassistant_responseevents withtextandmodel. Copilot messages that are not typed prompts (skill, agent, system and autopilot messages) are skipped. Codex prompts and replies are each read from one record kind, so no text is stored twice. Reasoning, encrypted content, Codex base instructions and the context Codex injects as user and developer messages are never stored. - Tool calls become
tool_callevents withtool_use_id, paired by call ID with atool_resultor, when the tool failed, anerror. A Codex shell output that reports a non-zero exit code, or a custom tool output that starts withScript failed, is anerror;exit_codeis stored when the log records it. - Each Copilot
session.usage_recordand each Codextoken_usage_record(or, in a rollout without one, eachtoken_countwhose total changed) becomes anassistant_responsewithmodel,provider,message_idandusage, socostand the exports count the session's tokens. As for Codex hook sessions, no request event is recorded andllm_requestsstays 0. - Copilot
subagent.started,subagent.completedandsubagent.failedbecomesubagent_startandsubagent_stop. The subagent's own records stay in the session withagent_id,agent_type,is_sidechainandcontext_streamsidechain:<id>. - A Copilot
session.errorbecomes anerrorevent and asession.resumeasession_startwith sourceresume. - A forked Codex thread's copy of its parent's history is skipped.
Text is cut to 2,000 characters and goes through the same secret redaction as
hook capture, on unless AGENT_TRACE_NO_REDACT=1. Each session_start
records redaction as on or off, so health reports the mode.
A record with no usable time takes the time of the record before it. A record
timed earlier than the one before it keeps its place in file order: its own
time is stored as source_timestamp. Besides the usual counts, the summary
prints the number of model calls with token usage, how many events were
recorded out of time order, and the records not imported, by kind, for
example Skipped 4 records not imported: hook.start 2, session.info 1,
user.message (not a prompt) 1.
Enriching a Copilot hook session¶
Copilot hook payloads carry no response text, model or token usage, and a
tool denied at the permission prompt leaves its tool_call without an
outcome (see the capture matrix).
agent-strace import --enrich <events.jsonl> adds them to the session the
hooks captured, from that session's own transcript:
- an
assistant_responsewith token usage for each model call; - an outcome for each tool call the hooks left without one, such as a denied
tool, with empty result or error text unless
--with-textis given; - with
--with-text, the assistant response text and outcome text.--with-textis content-bearing: it stores the model's replies, which can quote prompts, files and command output.
Each is added once, however often enrichment runs. Only the main agent's
records are read, because Copilot subagents run under their own hook
sessions. Added events have a source_type that ends in (enrichment).
When the session has already ended, they are written between a
session_start (source resume, mode transcript-enrichment) and a
session_end that names the transcript in source ([OMITTED] when only
metadata is added). The session's total_tokens and errors are updated.
Enrichment never stores content less redacted than the session already holds:
- A session captured with
hook --metadata-onlygets metadata only: models, token counts and message IDs.--with-textadds no text and says so. - A session whose
session_startrecorded redactionon, or whose metadata says it was redacted, is redacted again, whatever the environment says now. - A session whose start does not record a redaction mode gets metadata only, with a note.
--enrich exits 1 with Cannot enrich from <path>: <reason> when the file
is not a Copilot events.jsonl (a Codex rollout is refused: Codex hooks
already record response text and token usage) or when the store has no
session with its ID (import it without --enrich). It prints Enriched
session <id>: added <n> events and any notes.
To enrich every Copilot hook session as it ends, set AGENT_STRACE_ENRICH=1
in the environment the Copilot hooks run in. AGENT_STRACE_ENRICH=text also
adds response text and is content-bearing, as --with-text is. The
sessionEnd hook finds the transcript through the transcriptPath that
agentStop recorded, else at
session-state/<sessionId>/events.jsonl under $COPILOT_HOME (default
~/.copilot). It reads at most
64 MB for at most 3 seconds, well inside the hook's 10 second timeout. When
the file is larger or slower, or enrichment fails for any other reason, it
adds nothing, prints one agent-strace: enrichment skipped: <reason> line to
stderr and the hook still succeeds. With AGENT_STRACE_ENDPOINT set, the
events are in the collector, not the local store, so enrichment is skipped.
Entire checkpoints¶
agent-strace import --entire [CHECKPOINT_ID ...] [--commits RANGE] imports
the sessions recorded in Entire checkpoints into the trace store. It reads
them from this clone with git alone, from refs under
refs/entire/checkpoints/ or the entire/checkpoints/v1 branch: nothing is
fetched and no Entire account is needed. It is the reader that
review --entire uses, so what is read, what
is never read (full.jsonl) and how text is redacted and scrubbed are the
same; see Sessions read from a checkpoint.
| Flag | Description |
|---|---|
--entire [CHECKPOINT_ID ...] |
Import the sessions of these checkpoints, and of those that --commits names. Cannot be combined with a path, --discover, --enrich or --with-text. |
--commits RANGE |
With --entire, also import the checkpoints that Entire-Checkpoint trailers in this git revision range name, such as origin/main..HEAD |
Each Entire session becomes one agent-trace session, named as the agent-strace
hooks and transcript imports name it: the first 16 characters of the agent's
own session ID. A session that spans several checkpoints is joined into one.
A session whose checkpoint records no usable agent session ID is named
entire- and a name made from the ID it records, or
entire-<checkpoint ID>-<index> when it records none.
A session already in the trace store is not imported again, whether the hooks
captured it, it was imported from the agent's transcript, or an earlier
import --entire wrote it. That includes a Claude Code JSONL import, which
names the session by the agent's full session ID. It is left as it is, and
one line goes to stderr:
Skipped session <id> from checkpoint <checkpoint ID>: already in the store
(captured by hooks or imported before); nothing written. Each imported
session prints Imported session <id> (<agent>, <n> events) from checkpoint
<checkpoint ID>.
A session that tenant delete erased, under its 16-character ID or the
agent's full session ID, is not written again; stderr names it with
import: cannot import session <id> from checkpoint <checkpoint ID>: session
<id> was erased and cannot be recreated. The agent's full session ID counts
for this check and the one above even when it holds a path or a secret, which
keeps it out of the imported session's metadata. Each session is written whole
or not at all: its events first, then its meta.json, under one store lock. If
a write fails, such as on a full disk, the import removes only what it wrote,
so the next import writes the session. An import killed before it writes
meta.json leaves a .publish.json marker in the session directory, and the
next import replaces the events it wrote. Otherwise a session directory that
holds events but no meta.json, such as one a hook wrote to before the
session's metadata or after the kill, counts as already in the store: it is
skipped and left as it is.
share, cognitive-debt and health
then work on the imported sessions, as review does by session ID.
health grades them partial at best, with the reason provider_blind_spot:
see Sessions read from a checkpoint.
A share packet labels them Entire checkpoint and names the checkpoint and
commits; see share.
A checkpoint not in the clone is named on stderr with the command to fetch
pushed checkpoints:
git fetch origin 'refs/entire/checkpoints/*:refs/entire/checkpoints/*'.
A checkpoint that cannot be read, such as one whose metadata.json is not a
JSON object or holds a file over 64 MiB, is skipped and named on stderr with
the reason; the other checkpoints are still imported.
Exit codes:
| Code | Meaning |
|---|---|
0 |
Every session read was imported or skipped as already in the store |
1 |
No session was read, because every checkpoint was missing, unreadable or held no agent session; the trace store could not be read, such as when --trace-dir is a file; or a session could not be written to the store, such as one that was erased |
2 |
No checkpoint ID or range, an invalid checkpoint ID, a path, --discover, --enrich or --with-text with --entire, --commits without --entire, or a --commits value that is empty or not a revision range, that git cannot read or that has more than 500 commits |
Look at a session¶
list¶
List all captured sessions with ID, timestamp, duration, tool calls, and errors.
--tenant ID performs an exact tenant match before listing metadata.
A meta.json written by an older collector can hold a start time or end time
that is not a usable number, such as text, a list, an object, true, null,
NaN or a value out of range. list, stats, replay and tree show such a
value as missing, as they do for the duration of a session that has not
ended. replay --expand-subagents shows event times from the root session's
start. When that start is missing, it counts from the root's first event, as
replay does.
A start time that is not usable also reads as missing in these commands:
dashboardshows?.dashboard --trend --htmltakes its period and annotation positions from the usable starts.timelinecounts from the first event and shows that event's time as the start.fingerprinttakes the period from the usable starts. With none, the period and the default ID are empty.curvecounts the session, but measures the days from the usable starts.samplewritesnullas the start, and--strategy recenttreats the session as the oldest.mcp-scanfinds no session earlier than it, and does not count it as earlier than another session.reviewsorts the session as if it started at 0.skills <id>times the skill loads from the first event.pr-commentandeval gatedo not use it for the duration.pr-commentandreviewnever link the session by commit time. When no session has a usable start time, they link the latest session.server --dashboardtakes the start from the first item on the review and share pages, and leavesstarted_atout of/api/sessions.
An end time that is not usable reads as no end, as null does:
postmortemandpostmortem --listtreat the session as not ended, so a stale heartbeat reports it as crashed.healthdoes not count the session as finished.baseline checkscores it as an open session, andbaseline updateleaves it out.eval gatereports the session askilledwhen it has nosession_endevent, and does not use the end for the duration.pr-commentreports the session as in progress when it has nosession_endevent, and does not use the end for the duration.server --dashboardtakes the end from thesession_endevent on the review and share pages, and leavesended_atout of/api/sessions.
Such a session is in no time window. dashboard --trend --since, drift,
budget-report, team-report, context-score, lint --all --since,
mcp-scan without --session, oncall, cost --breakdown provider,
cost --tenant, policy backtest, policy diff, policy coverage,
eval dataset auto, baseline update, and the project budget in watch,
record and record-http leave it out. skills without a session ID counts
it as unreadable or malformed.
config-watch affected always leaves it out, since it cannot place the
session after a change. share refuses a session whose start time, or end
time when set, is not usable. See share. cognitive-debt --session
refuses such a session, as cognitive-debt without --session does.
A meta.json can also hold a total_duration_ms, tool_calls, llm_requests,
errors, total_tokens or depth that is not a usable number, such as text,
an object, null, NaN, infinity, a negative number, true or an integer too
large for a float. A count or a depth must also be an integer, so 2.5 and
3.0 are not usable. A command that reads one of these fields treats such a
value as missing, and so do the server --dashboard pages. Each shows, writes
or sends what it does for a session without that field. For a duration, some
commands use the end time minus the start time instead. A count or a depth
reads as 0. A hook that adds to such a count starts again from 0. The
exceptions:
baseline updateleaves out a session whose duration,tool_callsorllm_requestsholds such a value, andbaseline checkreports it as[UNSCORED]. A duration that isnullor empty still counts as 0 ms. Seebaseline.org-reportrefuses a session whose duration is not usable or whose count or depth is not a non-negative integer.sharerefuses NaN and infinity, as it does in anymeta.jsonfield.validatereports a value that breaks the trace schema.- For the
mcptools, see mcp.md. inspect, theserverAPI and other commands that copy the whole record keep the value as stored.
A meta.json can also hold an agent_name, command, team,
parent_event_id, trace_id, parent_span_id or trace_flags that is not a
string, such as null, a list, an object, a number, true, NaN or infinity.
A command that reads one of these fields as text treats such a value as
missing, and so do the server --dashboard pages. Each shows, writes or sends
what it does for a session without that field. An attribution that is not an
object reads as {}. Only true counts as redacted. The exceptions:
org-reportrefuses the session.- A
tenant_idthat is not a string does not read as missing, because that would move the session out of its tenant.backfill-metadoes not rebuild a parent whose child session has one. Thetenantcommands andorg-reportrefuse the session. So do the OTLP exports (export --format otlp,otlp-genaiandtemporal) and theserver --dashboardOTLP download. They also refuse atenant_idthat is only whitespace, and a strippedtenant_idover 256 characters or with a control character. They export an acceptedtenant_idstripped. See Sessions with unusable event timestamps for the line. sharerefuses NaN and infinity, as it does in anymeta.jsonfield.- For the
mcptools, see mcp.md. inspect, theserverAPI and other commands that copy the whole record keep the value as stored.
A meta.json is corrupt when it is not valid JSON, is not a JSON object, or
nests objects and arrays more than 128 levels deep. list, stats and
health skip that session and show the rest of the store. audit-readiness
fails its hash chain integrity check and names the session. Commands that read
that one session by its ID, such as inspect, replay, explain, export,
stats <id> and health <id>, exit 1 with one line. So do the exports that
read every session in the store: compliance export without a session ID,
export --format eu-ai-act --all, and export with --scores, --metrics or
--backend and --since. The line names the session and the reason:
A session ID prefix gets the same line and exit code when the corrupt session
is the only match. A prefix that also matches another session, readable or
corrupt, is refused as ambiguous, with the line that names the
matches. review and pr-comment print either line after their own prefix, as
in review: session <id> has a corrupt meta.json: <reason>. review exits 2
and pr-comment exits 1.
setup --verify --live --session names either one in its own failure line and
exits 1.
cognitive-debt keeps Error: trace input could not be read safely for a
corrupt session, and prints the ambiguous prefix line as is.
cost --tenant skips a corrupt session, because its tenant cannot be read.
agent-strace server answers GET /sessions/<prefix> and
GET /sessions/<prefix>/events with 400 and the message, for a corrupt session
and for an ambiguous prefix. With --dashboard, the session's events and its
review, compare, share, and OTLP actions answer the same way. MCP tools return
it as an error. verify checks only events.ndjson, so it still checks a
session given by its full ID.
To read the session again, move its meta.json out of the session directory.
Then run agent-strace backfill-meta --apply, which rebuilds the metadata from
the session's events.
| Column | Counts |
|---|---|
Tools |
Tool calls from any capture method: hook tool calls, MCP tools/call through the proxy, @trace_tool, imported tool uses |
LLM |
Model requests: MCP sampling/createMessage, @trace_llm_call, imported responses with token usage. Hooks record none, so hook sessions show 0 |
Err |
Failed tool calls (hooks, decorator) and JSON-RPC errors (MCP proxy) |
replay¶
agent-strace replay [session-id] [--format terminal|html] [--live] [--speed N]
[--filter TYPES] [--limit N] [--expand-subagents] [--tree]
[--diff SESSION_B] [-o FILE]
| Flag | Description |
|---|---|
--format html |
Export self-contained HTML viewer |
--diff SESSION_B |
Export side-by-side HTML diff against SESSION_B |
--live |
Replay with real-time delays |
--speed N |
Speed multiplier for --live (default: 1.0) |
--filter TYPES |
Comma-separated event types to show |
--limit N |
Cap at N events |
--expand-subagents |
Inline subagent sessions under the parent tool_call that started them (the child's parent_event_id). When one tool_call started several, each shows, in start order |
--tree |
Show session hierarchy without full replay |
Both HTML outputs show event text and session ids as plain text.
When stdout and stderr are both terminals and the session recorded a git
branch or commit, replay ends with one line on stderr that names the next
step: Review what this session proved before you open a PR: agent-strace review <id>.
It adds --trace-dir when the store is not the default one. --diff prints
no such line. Piped or redirected output never has it.
Codex runs subagents inside the parent session. Replay tags each of their
tool events with [subagent <agent_type> <last 8 characters of agent_id>],
shows the full agent=<agent_id> on subagent_start/subagent_stop, and
shows what the subagent returned under subagent_stop. --tree and
--expand-subagents use the same tags and list each in-session subagent with
its tool count under the session.
The --format html cost counter is the running agent-strace cost estimate at
the default model, so it ends at that command's session total. For a session
agent-strace cost refuses, the counter shows n/a instead of a dollar figure.
explain¶
Plain-English phase breakdown: what the agent did, files touched, retries, wasted time. Each phase lists the Codex subagents that ran in it with their tool counts. No LLM required. On a terminal, it ends with the same agent-strace review <id> line as replay.
Other¶
mcp¶
Start an MCP server that exposes your session store as queryable tools for a debugging agent: list_sessions, get_session, search_events, get_session_summary, diff_sessions, health, skills, and review. Read-only. Use the global --trace-dir (agent-strace --trace-dir DIR mcp) or AGENT_TRACE_DIR to pick the store. Client setup for Claude Code, Copilot CLI, Codex, and Gemini CLI: mcp.md.
telemetry¶
Show or change the anonymous product telemetry preference. Telemetry is enabled
by default outside CI, test runs and temporary home directories (see
Throwaway environments), but events are
sent only after the one-time notice has been shown or telemetry was explicitly
enabled. The notice appears on an
interactive command, or as a hook message at the start of an interactive Claude
Code, Codex, or Gemini CLI session (see
When sending starts);
status says when it is still waiting for the notice, and whether the one-time
research invite was shown. disable persists an
opt-out and deletes the local anonymous installation ID. DO_NOT_TRACK=1 or
AGENT_STRACE_TELEMETRY=0 always disables collection;
AGENT_STRACE_TELEMETRY=1 explicitly enables it, including in CI and those
environments. See
telemetry.md for the exact event schema and maintainer setup.
labs is under Help and labs.
Plumbing¶
Stable commands that agent hooks, the GitHub Action, share and other tools call. agent-strace --help leaves them out and agent-strace --help-all lists them.
hook¶
agent-strace hook [--provider claude|codex|gemini|cursor|copilot|opencode] [--metadata-only] <event>
setup. It
reads one provider hook payload as JSON from standard input and appends the
normalized event to the active session. --provider defaults to claude.
--metadata-only keeps event types, timing, IDs, tool names, model, reasons,
token counts, and the key names of tool input, and replaces every other string
value (prompts, responses, tool input and output, errors, paths, diffs) with
[OMITTED]. Secret redaction is always on, whatever AGENT_TRACE_NO_REDACT
says, and each event records "capture": "metadata-only". setup --managed
uses it. See Platform-team install.
| Event | Recorded data |
|---|---|
session-start |
Start the provider-scoped session, or continue it on resume or compact and keep its metadata. Records redaction: on or off, the secret-redaction mode the hook wrote with |
user-prompt |
User prompt text and available provider metadata |
pre-tool |
Tool name and input before execution, plus agent_id and agent_type when a Codex subagent made the call |
post-tool |
Successful tool result and duration when it can be linked to the call, plus agent_id and agent_type when a Codex subagent made the call |
post-tool-failure |
Failed tool result as an error event |
file-write |
Provider-reported file edit |
stop |
Assistant response or provider stop metadata |
subagent-start |
Subagent start in the parent session: agent type and name, plus the child session ID for GitHub Copilot CLI or the agent ID for Codex |
subagent-stop |
Subagent stop in the parent session, with the same fields and the stop reason when the provider sends one. For Codex, also the subagent's final message as text and its agent_transcript_path, both redacted |
session-end |
Finish the active session and clear its hook state. Records duration_ms, the time since started_at in meta.json, and stores it as total_duration_ms. When started_at is not a usable time, or is later than the end, the session still ends, session_end has no duration_ms, and total_duration_ms is 0. A repeated session-end for a session that already ended, and was not resumed since, records nothing and keeps the first end time |
post-model-request |
Codex only: one llm_response per model request with the model, status, error, turn ID and token usage, plus agent_id and agent_type for a subagent's request |
post-tool stores the tool's output as the event's result text, and
post-tool-failure as its error text. Output the agent sends as a string is
stored as sent. Output it sends as an object or list, such as Claude Code's
Bash {"stdout": ..., "stderr": ..., "interrupted": ..., "isImage": ...},
Claude Code's Read {"type": "text", "file": {...}} or Codex's
{"exit_code": ..., "output": ...}, is stored as compact JSON with the
agent's field names and order, for example
{"stdout":"hi","stderr":"","interrupted":false,"isImage":false}. Bash output
is stored as the whole object, not just its streams, so interrupted, an exit
code and any other field the agent sends are kept. Secrets are redacted in the
object, field by field, before it is written as JSON. Then a result longer
than 1000 characters keeps its first 1000 and ... (truncated), and an error
keeps its first 500. Hooks in 0.121.1 and earlier stored an object as a
Python repr, such as
{'stdout': 'hi', 'stderr': '', 'interrupted': False, 'isImage': False}.
Sessions recorded then keep that text, and readers that look inside a result,
such as the test-runner summary, read both forms.
Provider-specific aliases in generated configurations are normalized to these
events. Prefer agent-strace setup --cli PROVIDER over invoking hook
manually. See setup.md for provider event coverage and generated
configuration paths.
pr-comment¶
agent-strace pr-comment [SESSION_ID] [--dry-run] [--platform github|gitlab]
[--repo OWNER/REPO] [--pr NUMBER]
[--api-url URL] [--share-url URL]
[--review] [--fail-on STATUSES]
[--min-confidence low|medium|high]
[--findings NAMES] [--config FILE]
[--evidence-packet FILE] [--cognitive-debt FILE]
[--cognitive-debt-mode report|check]
[--artifact-url URL]
[--commits RANGE] [--otel-logs FILE]
[--agent-trace-records FILE]
[--from-note] [--entire] [--strict-links]
[--ci-checks]
[--disclosure off|report|check] [--pr-body FILE]
With --review, the comment leads with the check result and why, then the
evidence headline, each linked session with its source (agent-trace session,
review note, or Entire checkpoint) and how it was linked, and the five
findings. The session table, file activity, flags, and replay commands follow
in a collapsed Session details block, where the Cost and Model rows are
left out when no linked session captured them. Every linked session is
summarized. Without --review, the layout is unchanged.
Without a session, pr-comment exits 1 with No agent-trace sessions found.
With --review and no named session, it still renders: the comment says no
agent-trace session was linked, shows the five findings as the review reports
them (all inconclusive, low), and lists external evidence from --commits
and --otel-logs. It has no session table, file activity, flags, or replay
commands. This covers a Copilot cloud agent pull request, whose job leaves no
session in the repository. Errors include failed model requests; for a session recorded by an earlier version,
the comment shows the larger of the stored count and the count from its
events.
Cost is shown only when the trace records a model name or token usage, and
then as an estimate (see cost). Otherwise the comment says not
captured; GitHub Copilot CLI hooks, for example, carry neither. The model row
says not captured when no event names a model. Files read and modified use
the same evidence as the reviewability Scope finding: file and edit tool events
plus the files shell commands read or wrote. Paths are shown relative to the
session's working directory (/tmp and /private/tmp are the same directory
on macOS); paths outside it keep only their last three components.
| Flag | Description |
|---|---|
SESSION_ID |
Explicit session ID or prefix; otherwise use sessions attributed to the current branch |
--dry-run |
Render locally without resolving a PR or making a network request |
--platform github\|gitlab |
Review platform (default: github) |
--repo OWNER/REPO |
Override the repository/project inferred from CI or the git remote |
--pr NUMBER |
Override the PR/MR number inferred from CI or the current branch |
--api-url URL |
GitHub Enterprise or self-hosted GitLab API base URL |
--share-url URL |
Optional HTML replay URL; {session_id} is replaced for each session |
--review |
Lead the comment with the reviewability check result and findings, move the session summary into a collapsed block, and exit 1 when the threshold fails |
--fail-on STATUSES |
With --review: statuses that fail. See review. |
--min-confidence low\|medium\|high |
With --review: lowest confidence that can fail |
--findings NAMES |
With --review: findings the threshold applies to |
--config FILE |
With --review: config file with a review block |
--evidence-packet FILE |
With --review: list the evidence packet. See review. |
--cognitive-debt FILE |
With --review: add the cognitive debt result from a schema v1 JSON report |
--cognitive-debt-mode report\|check |
With --review: check fails unless the cognitive debt result is a pass |
--artifact-url URL |
With --review: https URL of the uploaded artifact |
--commits RANGE |
With --review: add external evidence from commit trailers. See review. Ignored without --review. |
--otel-logs FILE |
With --review: add external evidence from a Claude Code OpenTelemetry export. Ignored without --review. |
--agent-trace-records FILE |
With --review: add external evidence from Agent Trace records. Ignored without --review. |
--from-note |
With --review and no session linked: read the findings from the review note on the head commit. The comment says they were reported by the author's machine. Exits 2 without --review. |
--entire |
With --review, when no session is linked by name, by branch or by the pull request's changed files: read the findings from the Entire checkpoints that Entire-Checkpoint trailers in --commits name, as review --entire does. The comment says the findings read the Entire checkpoints named in the pull request's commits, which the author reports, and quotes no transcript text. When no checkpoint can be read, the comment is the one without --entire, which with --from-note reads the review note. Needs --review and --commits. Exits 2 otherwise, and for an invalid or unreadable --commits range or one of more than 500 commits, as review --entire does. |
--strict-links |
With --review: refuse sessions linked only weakly, as review --strict-links does. The comment lists them as refused and summarizes only the sessions kept. Exits 2 without --review. |
--ci-checks |
With --review: also read the GitHub check runs and commit statuses on the head commit, as review --ci-checks does. Exits 2 without --review. |
--disclosure off\|report\|check |
With --review: the disclosure check. See review. |
--pr-body FILE |
With --review and the disclosure check: the PR description to match. See review. |
With --review, the comment is still posted or updated when the check fails.
The exit code then follows the threshold and the cognitive debt and disclosure
checks.
GitHub uses GITHUB_TOKEN or GH_TOKEN. GitLab requires a writable project or
personal access token in GITLAB_TOKEN, GITLAB_ACCESS_TOKEN, or
PRIVATE_TOKEN; GitLab job tokens cannot write merge-request notes. Tokens are
read only from the environment. A token with a character that is not printable
ASCII, such as a trailing newline, is refused before any request, and the
error does not repeat it.
The request that creates or updates the comment does not follow redirects, so pass the final API URL. The GETs that find the pull or merge request and list its comments follow a redirect only to the same scheme, host and port.
export¶
agent-strace export <session-id> [--format json|csv|ndjson|otlp|otlp-genai|temporal|eu-ai-act]
[--endpoint URL] [--header 'NAME: VALUE'] [--service-name NAME]
[--protocol http/json|http/protobuf] [--agent-id ID]
[--include-subagents] [--anonymize] [--output FILE]
agent-strace export --format eu-ai-act --all [--since DURATION_OR_DATE]
[--until DURATION_OR_DATE] [--output FILE]
agent-strace export [<session-id> | --since Nd] [--scores] [--metrics]
[--backend otlp|langfuse]
--format otlp-genai writes OTLP/HTTP JSON that follows the OpenTelemetry
GenAI semantic conventions, with additive OpenInference attributes: an
invoke_agent {agent} root span, chat {model} model request spans and
execute_tool {tool} tool spans, with gen_ai.provider.name (and the
deprecated gen_ai.system). These names replaced gen_ai.agent.session,
gen_ai.client.operation and gen_ai.tool.call/{tool}. The root carries the
conversation as gen_ai.input.messages and gen_ai.output.messages, and each
tool span its input and result as gen_ai.tool.call.arguments and
gen_ai.tool.call.result. See
Spans and attributes.
--format otlp-genai names skill loads and marks compacted context. A
Claude Code Skill, Copilot CLI skill or Gemini CLI activate_skill call
whose arguments name a skill gets gen_ai.skill.name and the span name
execute_tool {tool} {skill}, also when the call failed. A chat span
whose request came after a recorded compaction in the same context gets
gen_ai.conversation.compacted true; the attribute is never false.
--format otlp, temporal and watch --stream-otlp add neither. See
Skill loads and compacted context.
When the session has an eval.json from eval run or eval ci,
--format otlp-genai adds one gen_ai.evaluation.result event per saved
result to the invoke_agent root span, at the span's end time:
gen_ai.evaluation.name is the scorer, gen_ai.evaluation.score.value the
score, gen_ai.evaluation.score.label pass or fail from the saved
passed, and gen_ai.evaluation.explanation the reason, cut to 1,000
characters and left out when empty. Export never scores the session itself: a
result without a true or false passed, a finite number score and a
non-empty scorer is left out, and an unreadable eval.json adds no events.
With --include-subagents each session's results go on its own root span.
Without eval.json the payload is unchanged. --format otlp and temporal add
no evaluation events; export --scores --backend otlp sends the scores as
agent_strace.eval.score gauges. See
Evaluation results.
--scores sends the scores in each session's eval.json: as Langfuse scores
with --backend langfuse (the default), or as agent_strace.eval.score gauges
with a judge attribute with --backend otlp. A session with no eval.json
sends none.
In --format otlp, a failed tool call and a tool call with no result are
tool/{tool} spans with the same gen_ai.* identity as a call that returned
a result. Earlier versions named them {tool}. An error is a tool call only
when it pairs with a call or has its own tool_name. See
Classic tool spans.
In both OTLP formats, a tool span's gen_ai.tool.call.id is the model's ID
for the call, the tool_use_id that hooks and import store,
such as toolu_.... A call with none keeps its event ID there, as earlier
versions did for every call. See
Spans and attributes.
In both OTLP formats, a call whose event names an earlier one in retry_of
has a span link to that call's span.
In both OTLP formats, each model response that import read from a
Claude Code transcript with token usage is a chat {model} span with the
recorded model, token counts, stop reason and message ID, as well as an event
on the root span. The transcript does not record when the request started, so
the span starts at the latest earlier user prompt, tool result or imported
response of the same conversation stream, or has zero length, and carries
agent.strace.timing=inferred. A <synthetic> message, which Claude Code
writes for an API error without sending a request, gets no span. See
Model responses imported from a transcript.
--include-subagents exports the session and the subagent sessions under it,
as agent-strace tree shows them, as one trace in one payload. Each
subagent's root span is under the span of the call that started it. It works
with --format otlp and otlp-genai, to a file or with --endpoint. Without
--endpoint it writes --output or trace-<12-character session
ID>-<format>.json and prints OTLP payload for N sessions written to FILE.
See Subagents in one trace.
--format json, csv, ndjson and eu-ai-act print to stdout. With
--output FILE they write FILE in UTF-8 instead and print one line on stderr
that names it. The file holds the same text stdout gets. --format otlp,
otlp-genai and temporal without --endpoint write the payload to
--output or to trace-<12-character session ID>-<format>.json.
--anonymize writes to --output or to
session-<12-character session ID>-anon.json. When export cannot write its
file, it prints one line such as Error: cannot write out.json: No such file or
directory on stderr and exits 1. --scores, --metrics and --backend do
not read --output.
--format json and ndjson write strict JSON. A number in an event that
reads as NaN or infinity, such as NaN or 1e400, is written as null, as
JavaScript's JSON.stringify writes it, and such a duration_ms is left out.
This holds for a session that an earlier version stored with the bare NaN,
Infinity or -Infinity tokens, too. --format csv writes a NaN or infinite
timestamp or duration_ms as nan, inf or -inf, and the data cell as
stored.
With --endpoint URL, --format otlp, otlp-genai and temporal POST the
payload to an OTLP/HTTP collector instead of writing a file. Give the
collector's base URL: export drops trailing slashes from the path and appends
/v1/traces unless the path already ends with it, and keeps the query string.
This is the rule watch --stream-otlp uses:
--endpoint |
Spans are POSTed to |
|---|---|
http://localhost:6006 (Phoenix, with --protocol http/protobuf) |
http://localhost:6006/v1/traces |
http://localhost:4318/v1/traces |
http://localhost:4318/v1/traces |
https://cloud.langfuse.com/api/public/otel/ |
https://cloud.langfuse.com/api/public/otel/v1/traces |
https://otel.example.com/ingest?team=a |
https://otel.example.com/ingest/v1/traces?team=a |
--header 'NAME: VALUE' adds a request header, such as an API key; repeat it
for more headers. It is read only with --endpoint. Spaces around the name
and the value are dropped. The name may contain only ASCII letters, digits and
!#$%&'*+-.^_`|~, the value must be printable ASCII and not empty, and no
name may be given twice, in any letter case.
--protocol http/json|http/protobuf sets how the POST encodes the payload:
http/json sends it as OTLP JSON (Content-Type: application/json),
http/protobuf as OTLP protobuf (application/x-protobuf). Both carry the
same payload: export builds the JSON and converts it, with the standard
library only. Some collectors take only one: Phoenix's /v1/traces takes only
protobuf. Without the flag, export reads OTEL_EXPORTER_OTLP_TRACES_PROTOCOL,
then OTEL_EXPORTER_OTLP_PROTOCOL, as OpenTelemetry SDKs do; the first one
set wins, and with neither set export sends JSON. It works with every format
--endpoint takes and with --include-subagents. Export reads the variables
only with --endpoint: --output files and the default file are always
JSON. agent-strace has no gRPC exporter.
--agent-id ID puts gen_ai.agent.id = ID on every span: the root, every
model request and tool span, and with --include-subagents every subagent
span too. Use it to send spans to a backend that finds an agent's spans by
that ID, such as a Microsoft Foundry external agent registered with the same
ID (see Azure Monitor and Microsoft Foundry).
Without the flag, export reads AGENT_STRACE_AGENT_ID; an empty or blank
variable counts as unset. With neither, export emits no gen_ai.agent.id: it
never derives one from the session. The ID is sent exactly as given. It works
with --format otlp, otlp-genai and temporal, to a file or with
--endpoint; the agent-strace session ID stays on session.id. The
OpenTelemetry GenAI conventions mark gen_ai.agent.id as Development.
--all, --since and --until select sessions by start time. Only two paths
read them. Every other path exports one session and reads none of the three.
| Path | Reads | Values |
|---|---|---|
--scores, --metrics or --backend, with no session ID |
--since |
The last N days, as N or Nd, such as 7, 7d or 0.5d. N is ASCII digits with at most one . between digits. 0d selects nothing. |
--format eu-ai-act --all |
--since and --until |
A duration back from now, such as 7d or 12h, a date such as 2026-03-31, a time such as 2026-03-31T12:00:00Z, or Unix seconds. A date, or a time with no offset, is UTC. |
--scores, --metrics and --backend with --since read every session in
the store before they send anything. When the store refuses a session or
another entry, even one outside the window, they print one line for the first
one in name order and exit 1. A corrupt meta.json or an unusable start time
cannot place a session in or out of the window. The line is Error: session
<id> has a corrupt meta.json: <reason>, Error: cannot read session <id>:
<reason>, such as started_at is not a usable time, or the store's line for
an entry that is not a session, such as Error: unrecognized or incomplete
session directory: notes. The store's own directories, such as datasets and
.approvals, are not sessions and are skipped. The events are not read to list
the sessions, so --metrics still exports a session with an unreadable line,
without cost_usd.
Export checks --endpoint, --header, --protocol, --agent-id, --all,
--since and --until before it reads the session or writes anything. It
refuses these with one line on stderr and exit 1:
--endpointwhere it would be ignored: with--format json,csv,ndjsonoreu-ai-act, or with--anonymize,--scores,--metricsor--backend. The line names the flag to use instead, such as--otlp-endpointfor--backend otlpand--langfuse-hostfor Langfuse.- An
--endpointthat is empty, does not start withhttp://orhttps://, has no host or a bad port, contains spaces or control characters, or carries a user name or password:invalid --endpoint value: <reason>. - A
--headerthat breaks the rules above. The line names it by position:invalid --header 2: its value is empty. --include-subagentswith--format json,csv,ndjson,temporaloreu-ai-act, or with--anonymize,--scores,--metricsor--backend:--include-subagents is not used with --format csv; use --format otlp or otlp-genai, or the flag it is not used with.--protocolwithout--endpoint:--protocol is used only with --endpoint; OTLP files are always JSON.grpc, from--protocolor a variable:--protocol grpc is not supported: agent-strace sends OTLP over HTTP only; use http/protobuf or http/json, with the variable's name in place of--protocolwhen it came from one. Any other value:invalid --protocol value: use http/json or http/protobuf. A line about a variable ends; or pass --protocol to override it.- An
--agent-idthat is empty or only spaces:invalid --agent-id value: it is empty. --agent-idwith--format json,csv,ndjsonoreu-ai-act, or with--anonymize,--scores,--metricsor--backend:--agent-id is not used with --format csv; use --format otlp, otlp-genai or temporal, or the flag it is not used with. These ignoreAGENT_STRACE_AGENT_ID.--all,--sinceor--untilwith--format json,csv,ndjson,otlp,otlp-genaiortemporal, or with--anonymize, which export one session:--since is not used with --format json, which exports one session; use --format eu-ai-act --all. With--include-subagentsthe line saysone session and its subagents. With--anonymizeit endswithout --anonymize.--allor--untilwith--scores,--metricsor--backend:--all is not used with --metrics; use --since Nd for the last N days. The line names the flags given. With a session ID,--sincetoo:--since is not used with --metrics and a session ID; drop the session ID for the last N days.- A
--sincewith--scores,--metricsor--backendthat is notNorNd, such as12h, a date,7dd,-1,nan,infor an empty value:invalid --since value: with --metrics, use a number of days as N or Nd, such as 7d. --sinceor--untilwith--format eu-ai-actand no--all:--since is not used with --format eu-ai-act without --all; add --all to export the sessions in the window. With a session ID, the line saysadd --all and drop the session ID.- A session ID with
--format eu-ai-act --all:a session ID is not used with --format eu-ai-act --all; drop it to export the sessions in the window, or drop --all to export that session. - A
--sinceor--untilwith--format eu-ai-act --allthat is not a duration, a date, a time or Unix seconds, or that is not a finite time, such asgarbage, an empty value,2026-01-01Z,2026-W01-1,nanor1e400:invalid --since value: with --format eu-ai-act --all, use a duration such as 7d or 12h, a date such as 2026-03-31, a time such as 2026-03-31T12:00:00Z, or Unix seconds.
The lines never repeat the URL or a header, which can carry a token. They never
repeat a --since or --until value either.
The POST does not follow redirects, so pass the final URL. Any 2xx answer is
success: export prints Exported N events to scheme://host[:port] (HTTP code)
and exits 0. Any other answer, a network error, or no answer within 30 seconds
prints OTLP export to scheme://host[:port] failed: <reason> and exits 1. The
collector or a proxy writes the reason, so each unprintable character in it
shows as its escape, such as \x1b. When the collector sent an error body,
its first 200 characters follow on a second, indented line, with each line
break, ESC or other unprintable character replaced by a space, so the rest of
an escape code, such as [31m, still shows. These lines name only the URL's
scheme://host[:port], never its path, query or user info, or a header value.
When the answer is 415 Unsupported Media Type, a last indented line names the
other encoding, such as This collector does not accept OTLP JSON; send
protobuf with --protocol http/protobuf.
When export cannot convert the session, --format otlp and otlp-genai print
OTLP export failed: <reason> and temporal prints
Temporal export failed: <reason>. Export then exits 1 without writing a file
or sending anything, with or without --endpoint.
--format otlp and otlp-genai emit gen_ai.conversation.id with the
agent's own session ID when the session has one (hook payloads that carry
session_id, Claude JSONL import), so exports join with native Copilot CLI
and Claude Code telemetry. See
production.md.
The GenAI payload preserves provider, model, tools, span parenting, exceptions, token counts, recorded cost, redaction state, persisted provenance, and observed structural evidence gaps. It does not reconstruct redacted values, estimate missing cost, include provider capture-matrix blind spots, or replace source NDJSON hash-chain verification. See OpenInference compatibility.
The OTLP formats and --backend langfuse export each model request's whole
input, output and prompt cache read and write token counts. otlp-genai also
exports the recorded reasoning output tokens. See
Token usage and prompt caching.
--format temporal emits OTLP/HTTP JSON using the upstream W3C trace ID and
Temporal activity parent span previously captured by watch. It can be written
to a file or sent directly with --endpoint. See
Temporal workflows.
--format eu-ai-act writes a structured JSON package with Article 12 logging
evidence, Article 13 transparency documentation, hash-chain integrity metadata,
and event-level line hashes for agent-strace verify --from-export. See
EU AI Act export package.
With --all, the eu-ai-act export reads every session in the store and keeps
those that started within --since and --until. It refuses when the store
refuses to read any session in it, even one outside that window, so the package
never leaves out a session. See
Sessions with mismatched or unreadable events.
With --all, --since and --until take these values. Each reads the same
way on every host and every Python:
- A duration back from now, as
NdorNh, such as7d,0.5dor12h. - Unix seconds, such as
1767225600. A value of only digits is Unix seconds, so20260101is not a date. - A date, as
YYYY-MM-DD, such as2026-03-31, is a UTC day. A--sincedate starts at 00:00 UTC. A--untildate covers the whole UTC day.--until 2026-03-31keeps a session that started at 23:59:59.5 UTC on March 31, and leaves out one that started at 00:00 UTC on April 1.--since 2026-01-01 --until 2026-03-31keeps the sessions that started in the first quarter of 2026 in UTC, March 31 included. - A time: a date, then
T,tor a space, thenHH,HH:MM,HH:MM:SSorHH:MM:SS.F, where F is one or more digits. Digits past the sixth are dropped. A time can end inZ,z,+HH:MMor-HH:MM. A time with no offset is UTC. A--untiltime keeps a session that started at that instant.
A date or a time takes ASCII digits only. Offset minutes must be under 60, and
the offset under 24 hours. A date with no time cannot take Z or an offset.
Export refuses every other form, such as 2026-01-01Z, a week date such as
2026-W01-1, a basic form such as 20260101T00, an offset such as +0000,
+00 or +05:30:15, a comma before the fraction, hour 24, second 60 and a
separator other than T, t or a space.
The eu-ai-act export also refuses to export a session whose started_at, or
ended_at when set, is not a Unix time in seconds. It prints one Error: line
on stderr and exits 1. It prints no package and writes no file. For one
session, the line is Error: session started_at must be a Unix time in seconds,
or the same message for ended_at. With --all, the line names the session,
as in Error: session <session-id> ended_at must be a Unix time in seconds.
--all refuses a bad started_at first, when it lists the store, even for a
session outside the window. That line is
Error: cannot read session <session-id>: started_at is not a usable time.
inspect¶
Dump full session as JSON (meta + events).
tree¶
Show the parent/child session hierarchy for a root session, including per-node cost, tool calls, status, and duration. Parent links come from record --parent, AGENT_STRACE_PARENT_SESSION, A2A trace propagation, imported trace metadata, or GitHub Copilot CLI's subagentStart/subagentStop hooks, which link task subagent sessions to their parent. Copilot sessions captured before those hooks were registered stay unlinked; see the capture matrix. Codex subagents run inside the parent session, so they are listed under it as subagent <agent_type> <short agent_id> N tools lines, and --format json adds a subagents list to that node.
annotate¶
agent-strace annotate <session-id> [--event ID] [--at OFFSET] [--note TEXT] [--label LABEL]
[--author NAME] [--shareable] [--list] [--delete ANNOTATION_ID]
[--filter-label LABEL] [--filter-author AUTHOR] [--since Nd]
[--export-format json]
--shareable to allow an annotation to appear
in a privacy-minimized evidence packet. Full-content packets include all
annotations.
Annotations are stored in annotations.jsonl in the session directory, one
JSON object per line. If another tool writes that file, only
"shareable": true marks an annotation shareable. Any other value, such as
1 or "true", keeps it private. Commands that read annotations skip a line
that is not a JSON object or is not valid UTF-8. They also skip a line with a
field of the wrong type, such as a note that is not a string. --delete
still removes such a line by its annotation_id.
| Flag | Description |
|---|---|
--event ID |
Event ID to annotate |
--at OFFSET |
Time offset to annotate (e.g. 2m14s, 1:30) |
--note TEXT |
Text note to attach |
--label LABEL |
Label chip (root-cause, decision, retry, fix, question) |
--author NAME |
Author name or email |
--shareable |
Allow the annotation to appear in privacy-minimized evidence packets |
--list |
List all annotations for the session |
--delete ID |
Delete an annotation by ID |
--filter-label LABEL |
Filter --list by label |
--filter-author AUTHOR |
Filter --list by author |
--since Nd |
Filter --list to annotations created in the last N days |
--export-format json |
Output --list as JSON instead of terminal text |
validate¶
agent-strace validate [TARGET] [--format text|json] [--allow-active]
[--replay-baseline FILE]
agent-strace validate --corpus [--format text|json]
meta.json and event schemas, relationship rules, ordering
policy, summary consistency, and hash-chain states. The default target is the
latest session. Validation is read-only and exits 0 only for a conformant
valid report. The path to the session may pass through root-owned operating
system links such as /tmp on macOS. Other symlinks on it are refused; see
Symlinked parent directories.
| Flag | Description |
|---|---|
--format text\|json |
Human-readable result or the versioned validation report |
--allow-active |
Treat requests in the open span as in flight; requests followed by a recorded session end still require outcomes |
--replay-baseline FILE |
Compare tool-call behavior with an existing regression fixture; symbolic links are rejected, and a symlink in a parent directory must be root-owned |
--corpus |
Validate all packaged Agent Evidence Corpus cases and exact expected labels |
The validator distinguishes missing usage from explicit zero usage. It accepts
legacy records that omit event session_id and hash links, but it does not
silently repair them. See Public trace schema for all rules,
status meanings, and compatibility decisions.
Each event line must be strict JSON. Earlier versions wrote a NaN or infinite
number in an event as the bare token NaN, Infinity or -Infinity. These
tokens are not JSON, so validate reports such a line as
event_schema_invalid. Current versions write the number as null and leave
out a NaN or infinite duration_ms, so new event lines do not hold the
tokens. A session that an earlier version recorded is not rewritten, so its
lines are still flagged.
A session continued by resume or compact is incomplete until its final
span has an end marker. An earlier end, cumulative duration, or successful
tool result does not fill the missing boundary. --allow-active does not
make that session complete.
backfill-meta¶
Write meta.json for session directories that have events.ndjson but no
metadata. Stores captured before the subagent capture fix contain many of
these: GitHub Copilot CLI subagents (the task tool) fired prompt, tool and
stop hooks but never sessionStart. list, skills and the other readers
that list sessions skip those directories, and tenant report, tenant export,
tenant delete and org-report stop with "unrecognized or incomplete session
directory" while any of them exist.
backfill-meta does not link those sessions to their parent; only the
Copilot subagentStart/subagentStop hooks do, as sessions are captured.
The command scans the flat store and every workspaces/<id>/ store. It is a
dry run unless --apply is given.
| Flag | Description |
|---|---|
--apply |
Write the metadata. Without it nothing is written |
--agent-name NAME |
Agent name when the events do not identify one (default: agent-cli, the hooks' default) |
--format text\|json |
Output format (default: text) |
Metadata is derived from the events, with the same field meaning as the hook-written metadata:
| Field | Value |
|---|---|
started_at / ended_at |
Earliest and latest event timestamps |
total_duration_ms |
ended_at - started_at |
tool_calls / errors / llm_requests |
Count of tool_call events, of error events plus failed model requests, and of llm_request events |
agent_name |
From a hook session_start mode or a hook stop response provider; otherwise --agent-name; otherwise agent-cli |
command |
"<agent_name> (backfilled)", distinct from captured metadata and from hook metadata marked (no session-start) |
tenant_id |
The single string tenant ID on the events, or empty. AGENT_STRACE_TENANT_ID is ignored |
workspace_id |
The workspace store the directory is in |
attribution |
Empty: the current user and git state do not describe the original capture |
conversation_id |
Empty: the events do not carry the agent's full session ID, so the export omits gen_ai.conversation.id |
Safety:
events.ndjsonis only read, so the hash chain checked byverifyis unchanged.meta.jsonis created exclusively and never replaces an existing file, even one that appears during the run.- Writes hold the store write lock used by every other writer.
- Symlinked entries and workspaces are reported and never followed. Invalid session IDs, empty or unparseable event streams, and events naming another session are reported and skipped. A stream is unparseable when a line:
- is not a valid event, or nests more than 128 levels
- has no
timestamp - has a
timestampthat is not a Unix time in seconds, such as a negative number, a time in milliseconds or a time after 9999-12-30T00:00:00Z (on Windows the limit can be lower, near the end of the year 3000) - has an
event_idorparent_idthat is not a string - has no
event_id, or an empty one - Sessions covered by a tenant erasure tombstone, or named by a pending tenant delete or tag journal, are skipped so erased data is never resurrected. An unreadable erasure audit or journal blocks the whole store.
- Event streams with more than one tenant ID, and parents whose child sessions
belong to another tenant, are skipped. A child session whose
meta.jsonholds atenant_idthat is not a string counts as another tenant, so its parent is skipped ascross_tenant_child. - A present
tenant_idthat is not a string is reported asinvalid_tenant; missing or empty tenant IDs remain untagged. - Directories with
identity.jsonare skipped: the signature covers metadata fields that cannot be rebuilt.
Backfilled sessions keep their original timestamps, so retention age limits
apply to them as soon as they are visible. Run agent-strace retention status
after --apply and before the next retention clean.
Exit status is 1 when a store cannot be scanned or a write fails, otherwise 0.
Labs¶
Experimental and specialist commands outside the review job, grouped as agent-strace labs lists them. They keep their names, flags, output and exit codes. See labs.md.
Labs: Capture without hooks¶
record¶
Capture an MCP stdio server session. Wraps <command> as a transparent proxy.
Tracing never stops the relay. A field with an unexpected JSON type is traced as if it were missing. A response with any error but null, even 0, "" or {}, is traced as an error event. If that error is not an object, the event has no code. A tool result is traced as a tool_result event. Its content_types lists the type of each content item. Its content_preview joins the non-empty text values of the content items with a newline, and is cut at 200 characters. A result with isError: true is stored with is_error: true, also when it has no content. A result that did not fail and has no content is not traced. A JSON-RPC batch is traced one message at a time, on one line or in a Content-Length frame. If the proxy cannot trace a message, for example JSON nested more than 128 levels deep or a full disk, it forwards the message anyway, records no event for it and prints a note to stderr. The note names only the exception type:
record forwards the bytes it reads unchanged in both directions, in the framing they came in: a line, or a Content-Length frame with its headers. That includes blank lines, carriage returns and lines that are not JSON. A line or body it cannot parse as JSON is still forwarded and gets the note shown above. A blank line gets no note.
When the agent closes its side of stdin, record closes the server's stdin, so the server sees the end of input. Everything the server writes before it exits reaches the agent and the trace before the session ends, and record exits with the server's exit code. If the agent stops reading the server's output, record stops the server. On SIGTERM or SIGINT, record stops the server too and exits with 128 plus the signal number (143 or 130). This holds from the moment the session is created: a signal that comes before the server starts ends the session, and the server is not started. Each of these ends the session with a session_end event and an end time.
Stopping the server also stops the processes it started, and when the server exits by itself record stops any process it left running before the session ends. On Windows this covers every process: the server runs in a job object that kills every process in it when the job is closed, including when record itself is killed. If the server cannot be put in a job object, it is not run, and record reports that it could not start the server. On POSIX it is best effort. The server runs in its own process group and session, and record sends SIGTERM to the group and to every other process it found, waits up to 5 seconds, then kills what is left. It finds a process in three ways: it descends from the server or from a process found earlier, it is in the server's process group, or its environment holds the random token record puts in AGENT_STRACE_RECORD_TREE for the server. The token is looked for even after the server exits; the process group only while the server's PID still has the start time it had. record reads the process table every second while the server runs, so a process seen once is still found after it leaves its parent. Each process is kept with its start time, and a process whose PID now has another start time, the server included, is never signalled. A process that leaves the server's process group, leaves its parent and clears its environment, all within a second of starting, is not found and keeps running. On macOS, record can only read the environment of processes run by the same user. record leaves the server unreaped after it exits until the rest are stopped, so its PID and process group name no other process. It uses os.waitid for this, or a kqueue on macOS with Python before 3.13. If the server exits before the kqueue watches it, or there is neither, the server is reaped when it exits and its process group is no longer signalled; the processes found the other two ways still are. If record is started with SIGCHLD ignored, it sets SIGCHLD back to the default while it runs, so the server starts with the default too. If something else reaps the server first, its exit code is lost and record exits 255.
If the server's output is not all relayed 5 seconds after the server exits, because a process the server started still holds it open or the agent is not reading it, record stops those processes the same way. It records an error event and sets output_truncated in session_end, and prints agent-strace: server output was cut short: ... if stderr takes it.
session_end is always the last event, and its counts match the events recorded before it. A message the agent sends while the session is ending is still relayed to the server, but not recorded. No write to the agent's stdout or stderr starts or finishes after it, including the lines record prints itself. A message from the server is recorded before it is relayed. If the agent does not take a write within 5 more seconds, record cancels that write and waits until it has ended. It then records an error event naming the stream and sets output_truncated in session_end. The part not yet written is never written, and nothing more is written to that stream. Lines record prints itself, such as --verbose events and the closing summary, are best effort: they still go to stderr if only stdout was cancelled, and a cancelled one is recorded the same way. The error events and output_truncated are the record of what the agent did not get. A message recorded just before its write was cancelled stays in the trace, so the trace can hold a message the agent did not get in full; output_truncated marks that case.
If the server cannot start, record prints agent-strace: could not start the MCP server: <reason>, records an error event and ends the session. It exits 127 when the command is not found, 126 when it cannot be run and 1 otherwise. If the --parent session is deleted while record runs, the link is dropped at the end, with a note on stderr, so the end time is still saved.
| Flag | Description |
|---|---|
--name NAME |
Label for the session |
--parent SESSION |
Link this session as a child of a parent session |
--redact |
Strip secrets before writing to disk; kept for compatibility because this is now the default |
--no-redact |
Disable automatic secret redaction |
AGENT_STRACE_PARENT_SESSION can also be set by orchestrators that spawn child agents. When --parent or AGENT_STRACE_PARENT_SESSION names no session, record prints Parent session not found: <value>, exits 1 and creates no session.
record-http¶
agent-strace record-http --url URL [--port N] [--name NAME] [--parent SESSION]
[--ca-file FILE] [--allow-host NAME] [--no-redact]
--port (default: 5100) and proxies to --url.
Pass the server's endpoint URL as --url, such as http://127.0.0.1:8000/mcp or https://mcp.example.com/sse, and point the client at the proxy root, such as http://127.0.0.1:5100. A request for the root goes to the --url path. A request for any other path goes to the same path on the server, such as the message path a legacy SSE server gives the client. A query in --url, such as an API key, is sent with every request, before the client's own query.
The trace saves --url as given, and redaction removes a key in it only if the key matches a detected pattern. To keep a key out of the trace, send it from the client, in its Authorization header or in its URL query. The proxy forwards both and records neither.
The proxy forwards GET, POST and DELETE. Of the client's headers it forwards only Authorization, Accept, Content-Type, Mcp-Session-Id, Mcp-Protocol-Version and Last-Event-ID, so a server that needs another header, such as X-API-Key, can't be reached through it. When the server answers with an event stream, each event reaches the client as it arrives, so progress and server requests such as elicitation are not held back. Each event's data is traced as a JSON-RPC message or batch, read by the event stream rules of the HTML standard: data: lines with or without a space after the colon, several data: lines joined with a newline, CRLF, LF or CR line endings, and the event ends at a blank line.
A request body, JSON reply or event that holds a JSON-RPC batch is forwarded unchanged. Each message in the batch is traced as if it came alone, so a tool call in a batch still links to its result. Tool results are traced as in record, with the same preview and is_error flag. Tracing never stops or changes forwarding. A message the proxy cannot trace is handled as in record: it reaches the other side as it arrived, and stderr gets the same note.
Requests are handled concurrently, so an open stream does not block other requests. On Ctrl-C the proxy closes open streams, including TLS handshakes still in progress, waits up to 5 seconds for in-flight requests, then records the session end.
For an https:// URL the proxy verifies the server certificate and host name with the system CA store, sends the URL host as SNI (none for an IP address) and in the Host header. To trust a private CA, pass --ca-file with its PEM file. The bundle replaces the system CA store, so include any public CAs the upstream also needs. Setting SSL_CERT_FILE to the PEM file also works; it replaces OpenSSL's default CA file for the whole process. There is no flag to turn verification off. A TLS failure, such as an untrusted certificate or a host name mismatch, returns 502 to the agent and records an error event.
To refuse requests from web pages, the proxy answers 421 to a Host that is not localhost, an IP address or an --allow-host name, and 403 to an Origin that is not a page on localhost, a loopback address or an --allow-host name. It neither traces nor forwards these requests. If a client gets 421 because it connects by another name, such as host.docker.internal or a tunnel name, restart record-http with --allow-host NAME for that name.
A tracestate header from the calling agent links this session as its child only when the caller's session is in the same trace store, and is ignored otherwise. If the parent session is gone when the proxy stops, the session is saved without the link and stderr says so. A linked session's depth is one more than its parent's, and a session linked later moves the sessions below it down with it. When the proxy stops it saves only its own counters and end time, so a link another proxy wrote to this session while it ran is kept.
--parent and AGENT_STRACE_PARENT_SESSION work as in record. When either names no session, record-http prints Parent session not found: <value> and exits 1. It creates no session and starts no proxy.
| Flag | Default | Description |
|---|---|---|
--url URL |
required | The MCP server's endpoint URL (http:// or https://), such as http://127.0.0.1:8000/mcp |
--port N |
5100 |
Local proxy port |
--name NAME |
none | Label for the session |
--parent SESSION |
none | Link this session as a child of a parent session |
--ca-file FILE |
system CA store | Trust a custom CA bundle for the HTTPS upstream. Replaces the system CA store. Requires an https:// URL; a missing or unreadable file, or a file with no certificate, exits with code 2 before a session is created |
--allow-host NAME |
none | Also accept requests whose Host is NAME, on any port, and requests from pages on NAME. Repeatable. For a client that connects by another name, such as host.docker.internal or a tunnel. Exact match, no wildcards |
--redact |
on | Strip secrets before writing to disk; kept for compatibility because this is now the default |
--no-redact |
off | Disable automatic secret redaction |
--verbose |
off | Print events to stderr during recording |
--quiet |
off | Suppress all output except errors |
auto¶
Run a command with every Python interpreter it starts auto-instrumented: python script.py, python -m module, and console or shebang scripts that run Python. Exits with the command's exit code, or 128 plus the signal number when a signal killed the command. How it works and its limits: integrations.md.
| Flag | Description |
|---|---|
--framework NAME, -f NAME |
Framework to instrument, or a comma-separated list: openai-agents, langchain, langgraph, litellm, anthropic, openai, strands, crewai |
--detect |
Instrument every installed framework (the default when --framework is not given) |
Events go to $AGENT_TRACE_DIR or .agent-traces. Use the global --trace-dir (agent-strace --trace-dir DIR auto -- <command>) to choose the store.
On Linux and macOS the command runs in a process group of its own. SIGTERM, SIGINT and SIGHUP sent to agent-strace auto, by PID or to its process group, are passed on to the command's whole process group once. agent-strace then waits until every process in that group has exited, deletes its temporary directory and exits 143, 130 or 129 (128 plus the signal number). A signal agent-strace was started with ignored, for example SIGHUP under nohup, stays ignored. A signal that arrives before the command starts stops agent-strace without starting it.
When agent-strace runs in the foreground of a terminal, it hands the terminal to the command's process group, as a shell does for a job. Ctrl-C and Ctrl- then go to the command alone, and agent-strace exits with the command's code. If Ctrl-C or Ctrl- kills the command, agent-strace takes the terminal back, deletes its temporary directory and sends the same signal to its own process group, so a shell script or loop that runs agent-strace auto stops as it would if the command had run without agent-strace. agent-strace then dies of the signal, unless it was started with the signal ignored or with a handler of its own. A command that handles Ctrl-C and exits, or that sends SIGINT or SIGQUIT to itself, does not stop the script; a small helper process in the command's group tells these cases apart from a key press. When Ctrl-Z stops the command, agent-strace takes the terminal back and stops too; fg and bg resume both.
Limits: a process that leaves the command's process group (with setsid or setpgid, as daemons do) is not signalled or waited for. SIGKILL sent to agent-strace or to its process group does not reach the command. After a normal exit, agent-strace does not wait for background processes the command left running.
Labs: Session analysis¶
stats¶
Tool call frequency and timing. When a Codex subagent made tool calls in the session, a Subagent Tool Calls section counts them per subagent. --include-subagents rolls up across the full subagent tree.
The Errors section lists error events and failed model requests (model request failed: <message>), each failed request once. A cancelled request is not listed.
timeline¶
Structured phase-by-phase view with tool calls, errors, retries, and cost per phase.
A tool result marks the call its parent_id names as ok or failed. A result
without a usable parent_id marks the newest call in the phase that has no
result or error yet.
A failed model request is a failed LLM response failed entry that fails its
phase and counts toward the session's errors, once even when an error event
is also linked to it. A cancelled request is marked ⊘ (cancelled in JSON)
and is not counted as an error. See failed model requests.
When the session's started_at is not a usable time, the timeline counts from
the first event, and the header and the JSON started_at show that event's
time. See list.
| Flag | Default | Description |
|---|---|---|
--format |
text |
text or json |
--model |
sonnet |
Pricing model: sonnet, opus, haiku, gpt4, gpt4o |
diff¶
Compare two sessions structurally.
Phases are numbered from 1 in each session. The output names the first phase where the sessions differ, lists each phase that appears in only one session, and shows both phase numbers when a matched phase sits at a different place in each session (Phase 3 in A, 4 in B).
| Flag | Description |
|---|---|
--semantic |
Compare by outcome, not event order |
--compare |
Side-by-side table with verdict (cost, duration, tools, errors) |
--eval-config FILE |
With --semantic, compare scores from this eval config's scorers (default: .agent-evals.yaml; skipped if missing) |
why¶
Trace the causal chain backwards from event #N. Run replay first to see event numbers.
compare¶
agent-strace compare <session-id-a> <session-id-b> [--format text|json]
agent-strace compare --tag TAG [--last N] [--format text|json]
agent-strace compare <session-id> --rerun [--model MODEL]
| Flag | Description |
|---|---|
--tag TAG |
Compare the two newest sessions whose name or command contains TAG, ignoring case. The older one is the baseline. Fewer than 2 matches exits 1. |
--last N |
With --tag, take the N newest matches (default: 2). Only the two newest are compared, so an N above 2 changes nothing, and an N of 0 or 1 always exits 1. |
--rerun |
Takes one session ID. Prints that session's first recorded user prompt to stderr, says the rerun is not automated yet, and exits 1. It does not run the agent or compare sessions. A session with no recorded prompt also exits 1. |
--model MODEL |
Accepted for --rerun, but not used yet, so it has no effect. |
--format text\|json |
Output format (default: text) |
lint¶
Flag bad behavior patterns: tool loops, reasoning spirals, budget proximity,
context saturation, redundant reads, error-retry loops, no-output sessions, and
post-compaction regressions. The post-compaction-regression rule warns when
re-reading, exploration, context saturation, or other lint findings increase
after a detected compaction.
--strict exits 1 on any WARN or ERROR. Configure rules via .agent-strace-lint.json.
budget-proximity compares the session's agent-strace cost total, at the
default model, with the budget_dollars or max_cost_dollars in its
session_start event, and fires at threshold (default 0.90) of the budget.
Earlier versions estimated the cost from the size of prompts, model requests
and responses at $9 per million tokens.
context-saturation fires once, at the first model event (llm_request,
llm_response or assistant_response) whose input tokens reach threshold
(default 0.80) of the model's context limit. It reads the tokens as
token-budget does, except that a count too large for a float
reads as missing, as a count of 0 does. The limit is the one the event records
in context_window, context_window_tokens or max_context_tokens, or else
the limit of the event's model, found as for token-budget.
So gpt-5 gets 272,000, its maximum input, not its 400,000 context window. A
model with no known limit uses 200,000 tokens. When no model event records
input tokens, the rule estimates them: it adds up the JSON size of each user
prompt and llm_request, four characters to a token, and fires at the first
one where the sum reaches threshold. The limit is then that of the first
model event that names a model or records a limit, and the finding shows the
tokens with ~. Earlier versions always used the estimate, against 200,000
tokens.
lint refuses a session in which an event the enabled rules read has data
that is not a JSON object, with the same Error: session event data must be
an object: ... message on stderr and exit code 1 as cost, stats and the
other commands in
Sessions with non-object event data.
It checks every event while post-compaction-regression is enabled, since
that rule reads every event. With --all, lint still reports every other
session, prints one Error: session <id> event data must be an object: ...
line on stderr per refused session, and exits 1. Earlier versions printed
[lint] Rule '...' failed: ... to stderr for such a session, then
✓ No issues found and exit code 0.
If a rule raises, the other rules still run, but the report is incomplete and
never shows ✓ No issues found. The text report lists each rule that could
not run:
Could not run 1 rule(s) in session 3f9a2c1b7d4e, so these findings are incomplete:
FAILED no-output RuntimeError: boom
0 error(s), 0 warning(s), 0 info(s). 1 rule(s) could not run. Exit code: 1
--format json prints one object per session (a list with --all) with
session_id, errors, warnings, infos, findings (each with rule,
level, message, line_start and line_end) and rule_errors (each with
rule, error_type and message; empty when every rule ran). Refused
sessions are left out of the JSON list and reported on stderr.
Exit codes:
| Code | Meaning |
|---|---|
0 |
Every rule ran on every session, with no ERROR finding (and, with --strict, no WARN) |
1 |
An ERROR finding, a WARN with --strict, a rule that could not run (with or without --strict), a refused session, or no matching session |
postmortem¶
Generate a structured postmortem for failed or crashed sessions. watch
writes a lightweight heartbeat while monitoring; if the heartbeat becomes
stale and the session has no clean SESSION_END, postmortem classifies the
crash and writes .agent-traces/<session-id>/postmortem.md with recovery
context. A SESSION_START after the last SESSION_END (a resume) reopens the
session, so that SESSION_END and its exit code no longer count. An ended_at
in meta.json that is not a usable time reads as no end.
| Flag | Description |
|---|---|
--list |
List crashed sessions and write missing postmortem.md files |
--stale-after SECONDS |
Heartbeat age before a session is treated as crashed (default: 30) |
--agents-md FILE |
AGENTS.md file used for instruction-violation checks |
standup¶
Deprecated: removed in 1.0.0; use agent-strace explain. See Deprecated commands.
Structured standup from a session trace. No LLM required. Covers files touched, approaches tried, dependencies added, TODOs written.
Two or more failed tool calls in a row make an approach, named after the tool call whose failure came first. A failed tool call is an error event linked to the call, or a tool_result with is_error: true, success: false, a nonzero exit_code or a status of error, failed, failure or timeout. A tool_result with is_error: false, success: true, exit_code: 0 or a status of success, succeeded, ok or completed succeeded, whatever its text says. A result with status: "cancelled" is neither. Status matching ignores case and surrounding spaces. Only a result that records none of these is judged by the words "error", "failed" or "traceback" in its content. The approach shows as "Tried and abandoned" when a later tool call succeeds. If the trace ends first, it shows as "Still failing when the session ended" when a session_end event or the session's end time comes after the failures, and as "Still failing when the trace ends" otherwise, for example while the session is still running.
Labs: Context and skills¶
context-score¶
agent-strace context-score [--file AGENTS.md] [--history N] [--compare]
[--min-sessions N] [--format text|json]
config-watch. Each dimension (cost, tool calls, lint findings, scope violations per session) scores 50 + 100 × (baseline − current) / baseline, clipped to 0–100; the overall score is their mean. With no version history it reports current-version stats only.
Like config-watch, run it from the repository root. It reads the context file from the current directory. It reads the sessions and the config-watch snapshots from the trace store, and uses only the snapshots taken in the current directory. If the current directory cannot be read, it prints one error line and exits 1.
Read with care:
- Efficiency proxies, not outcomes. Tests, task success, merges, and reverts are not measured.
- 50 means no change vs baseline, which grades F (A ≥ 90 … F < 60).
- Lower cost or fewer tool calls scores higher, even if the agent skipped work.
- Before/after only: no task-mix control, no confidence intervals, default minimum 5 sessions per version.
- Baseline is the oldest version, or the previous version with --compare.
- Sessions that start before the first config-watch snapshot count as the current version.
- Sessions are not filtered by repository. If several repositories share a trace store, the sessions of all of them are scored.
- Cost is the agent-strace cost total at the default model. Sessions it refuses are reported as N not priced and left out of cost averages (avg_cost is null in JSON when none is priced), and the cost dimension needs --min-sessions priced sessions per version.
- Lint findings, redundant reads and context saturation come from agent-strace lint. Sessions it refuses or where a lint rule could not run are reported as N not linted (unlinted_sessions in JSON) and left out of those averages, which show n/a in text and null in JSON when no session is linted. The lint dimension needs --min-sessions linted sessions per version.
- Ignores skills and whether the agent read the context file. For adoption, see skills.md. For controlled instruction evidence, see instruction-compliance.md.
| Flag | Description |
|---|---|
--file PATH |
Context file to score, relative to the current directory; defaults to the first existing AGENTS.md, CLAUDE.md, or GEMINI.md |
--history N |
Days of session history to analyse; default is 30 |
--compare |
Compare current context version against the previous version |
--min-sessions N |
Minimum sessions per version before scoring; default is 5 |
--format text|json |
Output format |
skills¶
agent-strace skills [SESSION_ID] [--since DATE] [--workspace PATH]
[--skills-dir DIR ...] [--min-sessions N]
[--from-claude [--claude-dir DIR] | --from-copilot [--copilot-dir DIR]
| --from-codex [--codex-dir DIR]] [--format text|json]
SESSION_ID to aggregate per skill. Skills with disable-model-invocation: true are listed as user-only instead of never loaded, and alias or forwarder skills get hints. To test whether a skill loads when it should, use skills eval. See skills.md.
| Flag | Description |
|---|---|
SESSION_ID |
Session ID or prefix. Omit for aggregate mode |
--since DATE |
Aggregate window. Accepts ISO dates or durations like 30d; default is 30d |
--workspace PATH |
Repository root for skill discovery when a session has no session_start cwd; default is the current directory |
--skills-dir DIR |
Extra skill directory to scan (plugin or app-bundled skills). Repeatable |
--min-sessions N |
Minimum sessions for the never-loaded and user-only lists and for each group in the loaded vs not-loaded comparison; default is 5 |
--from-claude |
Read existing Claude Code transcripts (DIR/projects/*/*.jsonl) instead of the trace store. Writes no persistent trace store; uses a temporary directory deleted on exit. Imported events are redacted as in import |
--claude-dir DIR |
Claude Code config directory for --from-claude; default is $CLAUDE_CONFIG_DIR, else ~/.claude |
--from-copilot |
Read existing GitHub Copilot CLI and app session logs (DIR/session-state/*/events.jsonl) instead of the trace store. Same temporary store as --from-claude. Availability is the skill list each session recorded |
--copilot-dir DIR |
Copilot home for --from-copilot; default is $COPILOT_HOME, else ~/.copilot |
--from-codex |
Read existing Codex rollouts (DIR/sessions/**/rollout-*.jsonl and DIR/archived_sessions/**/rollout-*.jsonl) instead of the trace store. Same temporary store as --from-claude. Availability is the skill list each session recorded |
--codex-dir DIR |
Codex home for --from-codex; default is $CODEX_HOME, else ~/.codex |
--format text\|json |
Output format |
With no sessions in the trace store, the command prints how to read Claude Code, GitHub Copilot or Codex history or set up capture instead of an empty report. In JSON mode the report is still printed and the hint goes to stderr.
When sessions are left out of the aggregate, the first line says how many and why, for example Skills across 2 of 7 sessions since 2026-10-16 (5 started before the window). Reasons: the session started before the --since window, or its stored trace cannot be read or its start time is not usable (shown as unreadable or malformed). With the --from-* flags, sessions that skills eval ran in its temporary workspaces are left out too, and stderr gives the count. JSON adds sessions_total and sessions_excluded. With --from-claude, transcripts that share a session ID are merged into one session, and the Read N Claude Code session(s) line says how many. With --from-claude, only regular .jsonl files are read, each as import reads it. A transcript is counted as unreadable when it cannot be read, has no Claude Code transcript record, or has no usable session ID. The three --from-* flags are mutually exclusive. With --from-copilot or --from-codex, the Read line also says how many sessions recorded their skill list and what was skipped, and JSON availability_basis is recorded or mixed. With --from-copilot, skill directories that recorded loads point to are scanned like --skills-dir, and a builtin skill path from a deleted Copilot CLI version resolves to the newest installed version. With --from-copilot or --from-codex, a record timestamp that cannot be read as a time from 1970 on, such as a negative number or an integer too large for a float, is ignored, and the event takes the time of the event before it or of the session start. The log formats are internal to each agent and can change; see skills.md.
skills eval¶
agent-strace skills eval CASES_FILE (--agent claude|copilot | --agent-cmd TEMPLATE | --from-traces DIR)
[--runs N] [--timeout SECONDS] [--case ID ...]
[--workspace PATH] [--skills-dir DIR ...]
[--save-traces DIR] [--keep-workspaces] [--format text|json|markdown]
[--fail-on-miss] [--fail-on-false-trigger]
disable-model-invocation: true are marked user-only. See skills-eval.md and instruction-compliance.md.
The one-word spelling skills-eval is deprecated and will be removed in 1.0.0; use agent-strace skills eval. See Deprecated commands.
| Flag | Description |
|---|---|
CASES_FILE |
JSON list of {id, skill, prompt, should_trigger} with optional fixture_dir, runs, note, instructions, and expected_actions |
--agent claude\|copilot |
Run a preset headless command. Presets never approve every tool |
--agent-cmd TEMPLATE |
Custom agent command. Placeholders: {prompt} (required), {workspace}, {trace_dir}, {hooks_plugin_dir}, {claude_settings} |
--from-traces DIR |
Score recorded runs in DIR/<case_id>/<run>/ instead of running an agent |
--runs N |
Runs per case without its own runs; default is 3 |
--timeout SECONDS |
Per-run timeout; default is 300 |
--case ID |
Only this case. Repeatable |
--workspace PATH |
With --from-traces: repository root for skill discovery when a run has no recorded cwd |
--skills-dir DIR |
Extra skill directory to scan. Repeatable |
--save-traces DIR |
Copy each run's trace store to DIR/<case_id>/run-<n>/ with run.json. Must be new or empty |
--keep-workspaces |
Keep each run's temp workspace, traces, and agent logs |
--format text\|json\|markdown |
Output format |
--fail-on-miss |
Exit 1 if a should-trigger run missed or was unscored |
--fail-on-false-trigger |
Exit 1 if a should-not-trigger run loaded the skill or was unscored |
compaction¶
Detect provider-reported input-token drops between consecutive model requests
and report the context discarded by compaction.
| Flag | Description |
|---|---|
SESSION_ID |
Session ID or prefix (default: latest) |
--diff |
Classify constraints, decisions, and file context as survived or likely dropped |
--behavior-diff |
Compare lint findings, re-reads, loops, and exploration around compaction |
--compaction-threshold RATIO |
Minimum token drop ratio (default: 0.50) |
The discarded context is priced at the model's input rate. The rate is found
as cost --breakdown provider finds it, Bedrock premium included. A
model with no price uses $3 per 1M tokens.
--behavior-diff counts context saturation with the context-saturation rule
of lint at its default threshold, so the two agree. Earlier versions
replaced the rule's count with their own check whenever an event recorded input
tokens, and compaction exited 1 with an OverflowError for a count such as
10**400.
See the context compaction guide for interpretation and live checkpoint setup.
token-budget¶
Show how full the model's context window is at each LLM request. The model is detected from the session (default: latest). A request's input tokens are the whole prompt it sent, so each request's fill is its own input tokens divided by the context limit; requests are not added together. A request at or above --warning-threshold of the limit (default: 0.9) is marked ← warning.
The context limit comes from a bundled table. Each entry is the most input tokens one request to the model can carry. Each Claude model's entry is its window from Anthropic's models overview: 1,000,000 tokens for Opus 4.6 and later Opus models, Sonnet 4.6 and later Sonnet models, Haiku 5.5, and every Fable and Mythos model, and 200,000 for Opus 4.5 and earlier, Sonnet 4.5 and earlier, Haiku 4.5 and the Claude 3 models. Each OpenAI, Gemini and Amazon Nova entry is from the model's page: the maximum input that the page states, when that is no larger than the context window, and the context window otherwise. So gpt-5 gets 272,000, the maximum input on its page, not its 400,000 context window. The model name finds its entry by the Model names rule of cost. So us.anthropic.claude-sonnet-4-5-20250929-v1:0, anthropic/claude-sonnet-4-5 and claude-sonnet-4.5 get the 200,000 limit of claude-sonnet-4-5, and o1-mini-2024-09-12 gets the 128,000 limit of o1-mini. A model with no entry, such as mistral-large-latest, has no known limit. Then the header says Context limit: unknown tokens, each fill and the Current and Peak lines show n/a, no request is marked, and no Headroom line is printed. For such a model, watch gives no --max-context-pct alert, and compaction, --checkpoint-at and the context-saturation rule of lint use a limit of 200,000 tokens.
The input tokens are read the way compaction reads them: provider keys such as input_tokens or prompt_tokens, nested usage objects, and Anthropic cache read and write tokens. A request with no count is estimated from the size of its own recorded data and shown with ~. That data may not hold the whole prompt, so an estimated fill can be lower than the real one.
Below the table: the last request's fill (Current), the highest fill and the request it came from (Peak, which can be higher than Current after compaction), the tokens left at the last request (Headroom), and the input tokens sent over all requests added together (Input sent, a volume figure, not a fill).
freshness¶
Check how stale the agent's last view of the codebase is. Reports the files changed since the last session and a freshness score from 0 to 100. A score of 100 means nothing changed.
The base is the newest commit on the first-parent chain of HEAD made at or before the start of the newest session. A commit from a branch merged after that time does not count as seen. When no commit is that old, the base is the empty tree, so every file in HEAD shows as added. Each changed file has git's change type: added, deleted, modified or renamed. A renamed file shows under its new name.
| Flag | Description |
|---|---|
--since YYYY-MM-DD |
Use 00:00 UTC on this date instead of the start of the newest session |
--scope GLOB |
Count only the files that match GLOB as in scope |
--repo PATH |
Check the repository that contains PATH. Default is . |
File names and globs are relative to the repository's top level, as git prints them. So --scope 'src/**' matches src/app.py from any directory of the repository.
Without --scope, the scope list comes from CLAUDE.md at the repository's top level. If that file lists no globs, it comes from AGENTS.md there. The list is the - and * bullets under a heading line that ends in : and mentions scope, files, include or watch. The bullet marker and any backticks around the glob are removed. With no scope list, every file is in scope.
freshness prints one line to stderr and exits 1, with no report, when:
- The store has no session and
--sinceis not given. The line starts withNo sessions found. - The newest session has no usable start time and
--sinceis not given. --sinceis not a date in the formYYYY-MM-DD.- The path does not exist, is not in a git repository, or the repository has no commits.
- git is not installed, fails, or runs longer than 30 seconds.
- The repository is a shallow clone with no commit that old. Run
git fetch --unshallow, or pass a later--since.
config-watch¶
agent-strace config-watch snapshot [--label TEXT] [--watch PATH]
agent-strace config-watch check [--format text|json] [--watch PATH]
agent-strace config-watch history [--format text|json]
agent-strace config-watch affected [--since DURATION] [--format text|json]
check exits 1 when config has changed (CI gate).
Run it from the repository root. It hashes the watched files in the current directory and reads .agent-strace-watch.json there. Snapshots are kept in .config-snapshots.json in the global trace store (--trace-dir, else $AGENT_TRACE_DIR, else .agent-traces). Each snapshot records the directory it hashed, shown as workspace in history --format json. check, history and affected use only the snapshots of the current directory, so several repositories can share one trace store. affected still lists sessions from all of them.
When the current directory has no snapshot, check prints No snapshots yet for <dir> and exits 1. If the current directory cannot be read, for example because it was deleted, config-watch prints one error line and exits 1.
Snapshots taken by older versions have no workspace. They belong to the directory that holds the trace store, which is the repository root in the default layout. With a trace store elsewhere, older versions kept the snapshots in <parent>/.agent-traces/.config-snapshots.json, where <parent> is the directory that holds the trace store. config-watch and context-score still read the untagged snapshots there, before the trace store's own, but never write to that file. A snapshot stays with the directory it hashed, so take a new one after you move or rename a repository.
optimize¶
agent-strace optimize [SESSION_ID] [--target FILE] [--dataset NAME] [--dry-run] [--apply]
[--base-url URL] [--model MODEL] [--api-key KEY]
AGENTS.md or any instruction file. Three built-in heuristic patterns require no LLM. --apply keeps \r\n line endings in a file that already uses them and writes \n otherwise, on every OS.
optimize calls an OpenAI-compatible LLM only when it has both a URL and a key. Otherwise it uses only the heuristics. For each value, the first one that is set wins, and an empty value counts as unset:
- URL:
--base-url, thenOPENAI_BASE_URL, thenAGENT_STRACE_LLM_URL. - Key:
--api-key, thenOPENAI_API_KEY, thenAGENT_STRACE_LLM_KEY. - Model:
--model, thenAGENT_STRACE_LLM_MODEL, thengpt-4o-mini.
The POST does not follow redirects, so pass the final URL. A failed request, or a reply that is not the JSON the prompt asks for, falls back to the heuristics.
Without --apply, or with --dry-run, optimize prints the proposal and writes nothing. --dry-run --apply prints the same as --dry-run.
--apply prints no preview, so it refuses an addition with a character that the preview shows as an escape, such as ESC, a lone CR, U+202E, U+2028 or a no-break space. A tab is allowed. It prints one error line that names the cluster, exits 1 and writes nothing. Run without --apply to see the escapes.
optimize reads and writes the target as UTF-8, whatever the locale. If the target is not valid UTF-8, or cannot be read or written (for example, it is a directory), optimize prints one error line and exits 1. A target that is not valid UTF-8 is left unchanged, with or without --apply.
a2a-tree¶
Visualise the A2A agent call graph. Exports as OTLP spans for Jaeger, Tempo, or any OpenTelemetry backend. A failed call span has status ERROR; a successful one leaves status UNSET (see Span status). Each agent span starts at the session's started_at and lasts its total_duration_ms. A sub-session that is not in the store starts and ends where the first call that names it starts.
Each sub-session is shown once under the agent that called it. When an agent calls the same sub-session more than once, every call is listed and the sub-session line ends with N delegations. A sub-session that another agent in the tree also calls (a diamond) is shown in full under its first caller and as name [shown above] under the others. Only a session that is already on the path from the root is shown as [cycle] → name. References are not counted again in Total agents, the total cost, or Max depth. In the JSON output each session has one span with an agent.delegations attribute; a shared or cyclic reference adds a span link to the calling agent's span, with agent.link set to shared or cycle.
A sub-session that is not in the store shows as [not found]. When the store
refuses to read the root session or a sub-session, a2a-tree prints one
Error: line and exits 1 before it prints anything. A sub-session whose
directory, meta.json or events.ndjson is a symlink is refused too. So is a
root session whose events.ndjson is a symlink. See
Sessions with mismatched or unreadable events.
A field of an a2a_call event with the wrong type reads as missing. See
Fields with the wrong type. A duration_ms or
cost_usd that is not a number, or is negative, NaN, infinity, or too large
for a float, reads as 0. Only success: false marks a call failed. A call
with any other success value, or with none, counts as successful.
--format json refuses a call time that OTLP cannot carry, as
Sessions with unusable event timestamps
describes. It also refuses a started_at that is not a Unix time in seconds,
or that OTLP cannot carry, in any session of the tree.
Labs: Evaluation and fixtures¶
eval¶
agent-strace eval [session-id] [--config FILE] [--baseline FILE]
[--save-baseline FILE] [--tolerance N] [--format table|json]
agent-strace eval run [session-id]
agent-strace eval compare <session-a> <session-b>
agent-strace eval ci [session-id]
agent-strace eval dataset auto [--name NAME] [--filter FILTER] [--since Nd] [--label TEXT]
1 when a criterion fails or a score regresses beyond the allowed
tolerance, making it suitable for CI. The run, compare, and ci subcommands
remain available for legacy normalized scorers. The legacy llm_judge scorer
takes base_url, api_key and model from its entry under scorers, and a
missing or empty one from the same environment variables as optimize.
The direct command, run, compare and ci print Session not found: <id>
and exit 1 when a session ID or prefix matches no session. With no ID and no
sessions, the direct command, run and ci print No sessions found. and
exit 1. Earlier versions of run and ci printed No sessions found. for
an unknown ID.
run and ci save their results to <trace-dir>/<session-id>/eval.json,
replacing the file an earlier run wrote, and print
Eval results written to <path> on stderr. ci --save-baseline saves it too.
The file is a JSON object with version (1), session_id, command
(eval run or eval ci), evaluated_at (Unix seconds),
agent_strace_version, passed, pass_count, fail_count,
weighted_score and results: one entry per scorer, in config order, with
scorer, score, threshold, passed and reason. A scorer that fails is
a verdict and is saved. export --scores,
export --format otlp-genai, dashboard --trend and
eval dataset auto --filter low-eval-score:N read the file. Earlier versions
wrote no eval.json, so those readers found no scores unless one was written by
hand.
run and ci save nothing when a scorer could not judge the session: an
unknown scorer type, a regex scorer with an unknown event type or a bad
pattern, an llm_judge with no endpoint or key or whose request or reply
failed, a custom scorer that raised, or a cost_under scorer that could not
estimate the cost. They also save nothing when a score or threshold is not a
finite number, such as threshold: nan. They then print
Eval results not saved: <why> on stderr and leave an earlier eval.json as it
was. The report and the exit code do not change. An unknown session saves
nothing either.
The direct command and compare do not write eval.json. The direct command's
values are raw measurements, such as dollars, seconds, counts or a status, and
the readers of eval.json take each score as a number from 0 to 1. Its
--save-baseline file keeps its results.
ci --baseline FILE fails when a score is more than --tolerance below the
score that ci --save-baseline saved for that scorer. The file must be a
UTF-8 JSON object that maps scorer names to finite numbers. A scorer the file
does not name is not compared, and a name that no scorer has is ignored. When
the file is missing or cannot be read, is not a JSON object, or holds a score
that is not a finite number, ci prints Baseline error: <why> on stderr and
exits 1. It prints the table and saves eval.json first, and writes no
--github-summary. A file that the direct command's --save-baseline wrote
holds text and an object, so ci refuses it. Earlier versions compared none
of its scores and passed. They also passed when the file was missing or could
not be read, or held a score of NaN, -Infinity, false or null. Some other
files stopped ci with a traceback. --save-baseline saves and exits 0
without reading --baseline.
The direct command's --baseline prints Baseline error: <why> and exits 1
for JSON nested too deeply. Earlier versions stopped with a traceback.
The direct command's --baseline also refuses a score of NaN, Infinity
or -Infinity, or a number such as 1e400 that reads as infinity, under any
name. For a criterion whose fail_on is above, at_or_above, below or
at_or_below, it refuses a baseline score that is not a finite number:
true, false, text such as "abc" or "NaN", or an int too large for a
float. Text that is a number, such as "100", reads as that number. An
equal or not_equal criterion compares any other score as it is. Each
refusal prints Baseline error: <why> and exits 1 before the table, so it
saves no --save-baseline file and writes no step summary. Earlier versions
showed such a criterion with no score and failed it. An equal or not_equal
criterion with a NaN or infinite baseline failed on every run, and
--format json wrote a bare NaN or Infinity, which is not JSON.
eval dataset auto adds sessions from the last --since days (default: 7d)
that match --filter (default: has-errors) to
<trace-dir>/datasets/NAME.jsonl, or to
<trace-dir>/workspaces/<id>/datasets/NAME.jsonl when AGENT_STRACE_WORKSPACE
is set. --dataset FILE writes to a different path.
agent-strace optimize --dataset NAME reads the same file.
In eval dataset auto, --since is N or Nd, such as 7, 7d or 0.5d.
N is ASCII digits with at most one . between digits. 0d selects nothing.
Any other value, an empty one too, prints
invalid --since value: use a number of days as N or Nd, such as 7d on stderr
and exits 1. It adds no session and writes no --dataset file.
The has-errors filter and the error_count scorer count error events and
failed model requests, each failed request once. A cancelled request is not an error.
--filter also accepts high-retry, cost-above:N, wide-blast,
long-duration:Ns and low-eval-score:N. cost-above:N adds sessions whose
agent-strace cost total, with its default model, is above $N. Earlier
versions priced each session's token count at a flat $3 per million. A session
that agent-strace cost refuses never matches it. low-eval-score:N adds
sessions whose eval.json scores, from eval run or eval ci, average below
N. A session with no eval.json never matches it.
Configure named criteria in .agent-evals.yaml:
evals:
- name: cost-ceiling
scorer: cost_usd
threshold: 0.50
fail_on: above
- name: no-errors
scorer: error_count
threshold: 0
fail_on: above
- name: task-completed
scorer: session_status
expected: completed
fail_on: not_equal
Built-in scorers are cost_usd, error_count, session_status,
redundant_read_ratio, tool_call_count, context_fill_ratio,
duration_seconds, and lint_violations. A custom Python callable can be
referenced as package.module:function and receives session events plus any
criterion-specific parameters it declares. When a lint rule could not run, a
lint_violations criterion fails with no score, and its reason names the rule.
session_status reports completed, killed or timeout from the last
session_end, by the rules in
Session root status with killed for
terminated. So Copilot's error and abort reasons are killed, and so is
an exit code too large for a float. It differs from those rules in three ways:
- With no
session_end, or when a latersession_start(a resume) reopened the session, the session iscompletedwhen its metadata has a usableended_atother than 0, elsekilled. - It also reads a text exit code such as
"1". - It reads a reason that is not text, such as a list, as text.
Earlier versions ignored an error or abort reason. Such a session was
completed with exit code 0 or none, and timeout with exit code 124.
For an exit code too large for a float, they failed the criterion with no
score and the reason int too large to convert to float.
They read a resumed session by the session_end before the resume.
| Flag | Default | Description |
|---|---|---|
--config FILE |
.agent-evals.yaml |
Named criteria configuration |
--baseline FILE |
— | Compare current raw scores with a saved baseline |
--save-baseline FILE |
— | Save current scores as versioned JSON |
--tolerance N |
0 |
Allowed fractional regression from the baseline |
--format table\|json |
table |
Human-readable or machine-readable output |
score¶
agent-strace score SUBMISSION.zip --rubric FILE [--format text|json]
agent-strace score DIRECTORY --rubric FILE --compare [--format text|json]
.zip suffix, anonymizes input filenames, rejects
duplicate bundles, and gives equal scores the same rank with digest-stable tie
ordering.
| Flag | Description |
|---|---|
SUBMISSION.zip |
One canonical assignment bundle |
DIRECTORY |
Directory of direct lowercase .zip files; requires --compare |
--rubric FILE |
Required strict assignment rubric; symbolic links are rejected, and a symlink in a parent directory must be root-owned |
--compare |
Score and rank a bounded directory batch |
--format text\|json |
Human-readable table/detail or versioned JSON (default: text) |
Invalid archives and rubrics exit non-zero. A low rubric score is a report for
human review, not a pass/fail hiring gate. See hiring.md. The
bundle, the comparison directory, and the rubric follow the same
symlink rule as share --assignment.
baseline¶
agent-strace baseline update [--since Nd] [--output FILE]
agent-strace baseline check [session-id] [--baseline FILE] [--sigma N]
agent-strace baseline show [--baseline FILE]
.agent-traces/baseline.json.
| Command or flag | Default | Description |
|---|---|---|
update |
— | Build a profile from completed sessions in the selected time window |
update --since Nd |
30d |
Include sessions started within the last N days |
update --output FILE |
.agent-traces/baseline.json |
Write the profile to a custom path |
check [session-id] |
latest | Check a session ID or prefix against the profile |
check --baseline FILE |
.agent-traces/baseline.json |
Read a custom profile |
check --sigma N |
2.0 |
Flag metrics more than N standard deviations from the mean |
show --baseline FILE |
.agent-traces/baseline.json |
Display profile statistics from a custom path |
update --since is the last N days, as N or Nd, such as 7, 7d or
0.5d. N is ASCII digits with at most one . between digits. 0d selects
nothing. Any other value, an empty one too, prints
invalid --since value: use a number of days as N or Nd, such as 7d on stderr
and exits 1. That check runs before the store is read, so update writes no
profile and leaves the one at --output as it was.
check and show read a profile file, as update writes, from
--baseline FILE or the default path. It must be UTF-8 JSON, and may start
with a byte order mark. With no file at the path, they print
No baseline found at FILE on stderr and exit 1, and check adds the command
that builds one. When they cannot read the file, they print
Could not read baseline file FILE: REASON on stderr and exit 1. They cannot
read the file when:
- the path is empty
- the path cannot be opened, such as a directory or a file without read permission
- it is not UTF-8 or not a JSON object
- it nests more than 128 levels
- it holds NaN, an infinity, a float out of range or an int of more than 4300 digits
cost_usd,tool_calls,duration_ms,error_rateorllm_requestsis not an object- in one of those,
mean,minormaxis not a number that fits in a float, orstddevorcountis not such a number of 0 or more
A missing key reads as 0. created_at and session_count may hold any value.
When created_at is not a usable time, show prints build time unknown in
place of the build time. The Could not read line shows each character of
FILE and REASON that str.isprintable() rejects as its escape, and show
does the same for session_count.
The profile tracks cost, tool calls, duration, error rate, and LLM requests.
The error rate counts failed model requests as errors; rebuild profiles saved by earlier
versions with baseline update to include them.
Cost matches agent-strace cost with its default model. A session whose
events cannot be priced adds no cost sample. That includes a session that
agent-strace cost refuses, such as one with an
unusable event timestamp.
Profiles saved by older versions
recorded every cost as 0, so rebuild yours with baseline update after
upgrading.
check exits with status 1 for an anomalous session, a missing session, or a
missing or unreadable baseline, so it can be used as a CI gate. See
production.md for an example.
check also scores a session with no usable end time, such as one that is still
running or was crashed or killed (an agent that watch kills usually never
records an end time). Its tool calls and LLM requests are the larger of the metadata
counter and the matching events, its duration runs from the start to its last
event, and its cost is priced from its events. These four only grow as a
session runs, so for an open session they count only when above the mean; a
value at or below the mean scores 0. Error rate is compared both ways. The
header shows open session, and the exit status follows the same rule as for
an ended session. Open sessions never go into a profile.
A session that cannot be measured at all is reported as [UNSCORED] with the
reason, and check exits 1. Earlier versions reported it as [OK] and
exited 0. update leaves such a session out of the profile. A session cannot
be measured when its metadata is missing or unreadable, or when its
tool_calls, llm_requests or total_duration_ms is not a usable number,
such as text, NaN or 2.5 in a count. A duration that is null, false or
empty counts as 0 ms, as a missing one does.
freeze¶
agent-strace freeze [session-id] [--output FILE] [--task TEXT] [--format text|json]
agent-strace regression <fixture-file> [session-id] [--threshold N] [--format text|json]
regression compares a later session against the fixture and exits non-zero when structural divergence exceeds --threshold (default: 0.0).
sample¶
agent-strace sample [--strategy worst|diverse|recent|random] [--n N]
[--deduplicate] [--seed N] [--output FILE]
Each record's score.cost_estimate is the session's agent-strace cost total
with its default model, and the worst and diverse strategies rank and
compare sessions by it. Earlier versions split llm_response token counts
80/20 and priced them at $3 and $15 per million. For a session that
agent-strace cost refuses, cost_estimate is null and the session is
ranked and compared on its other scores only.
score.error_rate, which the worst and diverse strategies use, counts
failed model requests as errors.
A started_at that is not a usable time is written as null, and
--strategy recent treats the session as the oldest. See list.
Sessions whose event streams cannot be read are skipped with a reported count; the scoring count includes only readable sessions that remain after optional deduplication. The selected records use that same in-memory snapshot, and the output file is replaced atomically only after every record serializes. A serialization or write failure exits nonzero without leaving partial output.
drift¶
agent-strace drift (--since Nd | --current YYYY-MM-DD:YYYY-MM-DD)
[--baseline FILE] [--baseline-range YYYY-MM-DD:YYYY-MM-DD]
[--save-baseline FILE] [--threshold N] [--format table|json]
--since or --current;
without either, drift exits 1. With --since Nd, the newer half of the
sessions in that window is the current set, and the older half is the baseline
unless --baseline FILE or --baseline-range supplies one. --current
always needs --baseline FILE or --baseline-range. Exits 1 when the drift
score exceeds --threshold (default: 0.20).
The cost_usd dimension uses each session's agent-strace cost total at the
default model. Sessions that command refuses are left out of the cost
statistics, and a Sessions not priced line counts them
(baseline_unpriced_sessions and current_unpriced_sessions in JSON). When one
side has no priced session, cost_usd scores n/a (null in JSON) and the
overall score averages the other dimensions.
The error rate counts failed model requests as errors. Baselines saved by earlier versions left them out; save them again to compare like with like.
--since, --current and --baseline-range leave out a session whose
started_at is not a usable time. See list.
--since is the last N days, as N or Nd, such as 7, 7d or 0.5d. N is
ASCII digits with at most one . between digits. 0d selects nothing. Any
other value, an empty one too, prints
invalid --since value: use a number of days as N or Nd, such as 7d on stderr
and exits 1. That check comes before --baseline is read, and
--save-baseline writes no file. With --current, drift does not read
--since.
--baseline FILE reads a fingerprint file, as fingerprint --output or
drift --save-baseline writes. It must be UTF-8 JSON, and may start with a
byte order mark. When drift cannot read it, drift prints
Could not read fingerprint file FILE: REASON on stderr and exits 1, and
--save-baseline writes no file. drift cannot read the file when:
- the path is empty
- the file is missing or cannot be read
- it is not UTF-8 or not a JSON object
- it nests more than 128 levels
- it holds NaN, an infinity, a float out of range or an int of more than 4300 digits
- its
period,tool_mixor a statistic has the wrong type
A tool_mix value must be a number of 0 or more. A statistic's mean, p50
and p95 must be numbers that fit in a float.
fingerprint¶
agent-strace fingerprint [--sessions N] [--output FILE] [--format text|json]
agent-strace fingerprint --compare A.json B.json [--threshold N] [--format text|json]
Cost statistics are the agent-strace cost totals of the priced sessions.
unpriced_sessions counts the sessions that command refuses, and cost_usd is
null when no session is priced. Fingerprints saved by older versions counted
those sessions as $0.
The period runs from the earliest to the latest usable started_at. A session
whose start is not usable still counts. When no start is usable, the text shows
ID: (none) and Period: - to -, and the JSON fingerprint_id and both
period fields are empty. See list.
--compare reads both files the same way as drift --baseline,
and names the first file it cannot read.
Labs: Guardrails and security¶
watch¶
agent-strace watch [session-id] [--agent-pid PID] [--timeout DURATION] [--budget DOLLARS]
[--on-violation ACTION] [--webhook URL] [--config FILE]
[--on-death CMD] [--policy FILE] [--rules FILE_OR_BUILTINS] [--stream-to URL]
[--stream-otlp] [--protocol http/json|http/protobuf] [--agent-id ID]
[--stream-batch-size N] [--stream-flush-interval S] [--loop-threshold N]
[--loop-window N] [--max-context-pct N]
[--compaction-checkpoint] [--checkpoint-at RATIO] [--dry-run]
[--tenant-id ID]
| Flag | Description |
|---|---|
--agent-pid PID |
Agent process that pause, kill and approval actions signal. A kill also signals the processes the agent started (see below). Watch exits with an error if the PID does not exist or cannot be signalled. Watch records the process start time and checks it before each signal, so it never signals a process that reused the PID (see below). Not supported on Windows |
--timeout DURATION |
Kill the agent once this much time has passed since watch started, whatever --on-violation says. Checked on every poll cycle, so an agent that writes no events is still killed. Needs --agent-pid; without it watch alerts and warns once. DURATION is a number of seconds, such as 90, or one or more groups of a number and a unit, with optional spaces, such as 30m, 2h, 1h30m, 1h 30m or 5 minutes. The units, case-insensitive, are s, sec, secs, second, seconds, m, min, mins, minute, minutes, h, hr, hrs, hour, hours, d, day and days. Watch refuses at startup, with one line and exit 1, an empty value, any other text, such as 1w, 1h30, 1e3m or -5m, and a value that is not a finite number of seconds more than 0, such as 0, -5, nan or inf |
--budget DOLLARS |
Kill the agent when spend exceeds this many dollars, whatever --on-violation says. Needs --agent-pid; without it watch alerts and warns once. Pass a plain number such as 5, not $5; 0 kills at any spend. A negative, infinite or NaN value is refused at startup with one line and exit 1 |
--loop-threshold N |
Alert when the same tool call and arguments repeat N times; default is 3 |
--loop-window N |
Number of recent events to scan for repeated identical tool calls; default is 10 |
--on-violation terminal\|file\|kill |
Action when a rule fires (default: terminal) |
--webhook URL |
POST each alert as JSON to this http:// or https:// URL. Watch refuses at startup, with one line and exit 1, a URL with any other scheme or none, no host, a bad port, spaces or control characters, or a user name or password; when --webhook is not given, the same check applies to webhook.url in the --config file. Redirects are not followed, so pass the final URL. Any answer other than 2xx is a failure |
--config FILE |
JSON file that sets watch limits and actions; see Config file below. Watch refuses a file it cannot use, with one line and exit 1, before it reads the session or writes anything. Flags given on the command line override the file |
--max-context-pct N |
Alert when one LLM request's input tokens, its whole context, reach N percent of the model's context limit (default: 90). Read as for token-budget, and a model with no known limit gives no alert. The alert fires once per crossing: a later request below N percent, such as one after compaction, re-arms it. N must be from 1 to 100; any other value is refused at startup |
--on-death CMD |
Shell command that watch runs once, after it sends the agent SIGTERM, and only if it sent it: not on --dry-run, without --agent-pid, or when the signal could not be sent (see below). {post_mortem_path} is replaced with the path of the post-mortem JSON file, or with nothing if watch could not write it |
--compaction-checkpoint |
Write a recovery checkpoint before context saturation |
--checkpoint-at RATIO |
Context fill ratio that triggers a checkpoint (default: 0.80). The limit is the one a request records in context_window, context_window_tokens or max_context_tokens, or else is found as for token-budget. A model with no known limit uses 200,000 tokens |
--policy FILE |
Scope policy file to enforce (default: .agent-scope.json). Watch reads its files.write.deny globs and alerts ScopeWatcher: write to PATH denied by policy once for each denied path that an edit names, from any edit tool, file_write event or apply_patch patch. PATH is resolved as described in Paths and edits below |
--rules FILE_OR_BUILTINS |
A JSON or YAML rules file (see Rules file format below), or comma-separated built-in rules such as mcp-poisoning,loop:3/10,budget:5,timeout:30m,cognitive-debt:0.8 (see Built-in rules below). A value that names an existing file is a rules file. Watch refuses a value it cannot use, with one line and exit 1, before it reads the session or writes anything |
--stream-to URL |
POST events as NDJSON to this http:// or https:// URL while watching. Watch refuses at startup, with one line and exit 1, a URL with no host, a bad port, spaces or control characters, or a user name or password. A failed POST prints one line that names only the URL's scheme://host[:port], and watch goes on. Redirects are not followed, so pass the final URL. When watch stops, it waits up to 15 seconds for the last POST; if the wait runs out or Ctrl-C stops it, one line gives the number of events not confirmed sent |
--stream-otlp |
With --stream-to, POST OTLP/HTTP spans instead of NDJSON, as JSON unless --protocol says otherwise. Trailing slashes are dropped from the URL path and /v1/traces is appended unless the path already ends with it; the query is kept. Pass the collector base URL, such as http://localhost:4318. See Live OTLP streaming |
--protocol http/json\|http/protobuf |
With --stream-otlp, the OTLP/HTTP encoding: http/json (application/json) or http/protobuf (application/x-protobuf), which Phoenix needs. Without the flag, watch reads OTEL_EXPORTER_OTLP_TRACES_PROTOCOL, then OTEL_EXPORTER_OTLP_PROTOCOL; with neither set it sends JSON. Watch refuses at startup, with one line and exit 1, grpc, any other value, and --protocol without --stream-to and --stream-otlp. The first POST answered 415 adds a line that names the other --protocol. NDJSON streaming ignores the variables. See export |
--agent-id ID |
With --stream-otlp, put gen_ai.agent.id = ID on every streamed span, for a backend that finds an agent's spans by it, such as a Microsoft Foundry external agent. Without the flag, watch reads AGENT_STRACE_AGENT_ID; an empty or blank variable counts as unset, and with neither watch emits no gen_ai.agent.id. Watch refuses at startup, with one line and exit 1, an empty or blank value and --agent-id without --stream-to and --stream-otlp. NDJSON streaming ignores the variable. See export |
--stream-batch-size N |
With --stream-to, send once N events are waiting (default: 10) |
--stream-flush-interval S |
With --stream-to, send waiting events once S seconds have passed since the last POST (default: 2.0). 0 sends each event at once. A negative, infinite or NaN value is refused at startup |
--dry-run |
Evaluate rules without acting |
--tenant-id ID |
Tag the session and all events; defaults to AGENT_STRACE_TENANT_ID |
--timeout and --budget kill whatever --on-violation says, with or
without --config. Every other watch check acts with --on-violation (or
watchers.retry.alert from --config), including --max-duration,
--max-cost and the file's duration and cost limits. They set the same
limits as --timeout and --budget, but a default (1800 seconds and $10)
always applies, so they kill only when that action is kill. A project
budget's per_session_max changes the cost limit; see Project budget
config below. The --rules built-ins budget:N and timeout:D change
these limits too, but never raise a limit that kills; see Built-in rules
below. Bad --max-duration and --max-cost values are refused
like bad --timeout and --budget values.
Every duration limit counts wall-clock time from when watch starts,
including time the agent spends paused. A duration limit that kills, from
--timeout, or from --max-duration, watchers.duration.max_minutes or
timeout:D while the action is kill, is checked on every poll cycle, so
an agent that writes no events is still killed at the deadline. Any other
duration limit is checked when an event arrives. With a limit that kills
and --agent-pid, watch does not stop for lack of events before the
deadline while the agent process runs, and it waits up to 10 seconds past
the deadline so the SIGKILL that follows SIGTERM after 5 seconds is
still sent. Once the agent process has exited, or its PID now belongs to
another process (see below), the limit kills nothing and the deadline sends no
alert: the idle timeout (5 minutes without events) applies again, and a later
event past the deadline acts with --on-violation. Without --agent-pid, the
deadline still alerts on time, and the idle timeout is unchanged.
Alert channels never stop or delay the alert's pause or kill: watch writes the
alert log before it acts, and sends the --webhook POST and any Slack or Teams
notification (AGENT_STRACE_SLACK_WEBHOOK, AGENT_STRACE_TEAMS_WEBHOOK) after
the pause or kill, the post-mortem and the --on-death command. A channel that
fails prints one line and watch goes on; a webhook, Slack or Teams line names
only the URL's scheme://host[:port].
Each alert is one line on the terminal and one line in the alert log
(.agent-traces/alerts.log). The agent writes the text of its tool calls, so
an alert can quote escape codes or line breaks. Watch shows each character
that Python's str.isprintable() rejects as its escape, such as \x1b, \n
or \u202e, so the agent cannot hide an alert or forge a log entry. Other
[watch], [stream] and [notify] lines that quote the session or a server
reply do the same. The --webhook payload, --stream-to and the post-mortem
are JSON and keep the raw text.
A kill sends the agent SIGTERM, then SIGCONT, and SIGKILL 5 seconds
later. SIGCONT lets a stopped agent act on SIGTERM: a process stopped by a
pause or require_approval rule, VS Code Pause, Ctrl-Z or kill -STOP runs
no SIGTERM handler until it is continued, and on Linux even the default
action waits. A stopped agent that ignores SIGTERM runs again until the
SIGKILL. Only once SIGTERM is sent does watch write the post-mortem
(watchdog-postmortem.json in the session directory, with the alert as its
reason) and run --on-death. If it cannot send SIGTERM, watch prints
Agent pid PID was not killed: and the reason, sends no other signal, and
writes no post-mortem and runs no --on-death. Watch kills the agent once:
apart from the SIGCONT and SIGKILL that follow SIGTERM, it sends that
PID no other signal. A later
kill, pause or require_approval alert is printed, logged and sent as
usual, plus the line Agent pid PID was already killed; no signal sent, and
a require_approval alert creates no approval request. VS Code Pause and
Resume are ignored after the kill.
A kill also ends the processes the agent started, such as a hung test or a
dev server. Just before the agent's SIGTERM, watch lists every process whose
parent chain leads to the agent, in any process group or session, so a
command run in its own session or pty is included. It reads /proc on Linux
and runs ps once on macOS and other POSIX systems. Watch sends SIGTERM to
the agent and then to each listed process, parents first, and then SIGCONT
to all of them in the same order, so a stopped process acts on SIGTERM. Five
seconds after SIGTERM, watch sends SIGKILL to the agent and to each listed
process that still runs. If the agent's SIGTERM cannot be sent, no other
process gets a signal. Watch lists only once: a process the agent starts
after SIGTERM, such as a hook that records the end of the session, is left
to finish. Apart from the agent, watch never signals PID 1, watch itself, a
process below watch (such as its ps or --on-death command), the processes
between the agent and watch when watch runs under the agent, or a listed
process whose PID now belongs to another process. After Killing agent
process PID, watch names the child processes it signalled:
The line names at most 10 PIDs, then and N more, and is left out when the
agent has no child process. A process that watch is not allowed to signal is
named in Child process PID not killed: not allowed to signal it. A process
that has already exited needs no line. If watch cannot list the processes,
for example because ps did not finish within 2 seconds, it kills the agent
as before and prints Could not list the agent's child processes, so they
were not killed: and the reason. No line shows a command line or its
arguments, since they can hold secrets.
Watch does not exit before that SIGKILL. If watch is about to exit less
than 5 seconds after a kill, for example because the session ended or you
pressed Ctrl-C, it waits until it has sent SIGKILL or every process it
signalled has exited, for at most 7 seconds after SIGTERM. A wait longer
than a second prints Waiting Ns to send SIGKILL to processes that did not
exit on SIGTERM; press Ctrl-C to stop waiting. Ctrl-C ends the wait and names
the signalled PIDs that still run.
A kill does not reach a process that left the agent's tree before the kill,
such as a daemon that forked twice, or a process the agent started through
another service, such as a container run by a container runtime. To stop
those too, run a command for them with --on-death.
Watch does not guess the agent PID. Capture hooks run as children of a
shell, so their parent is not reliably the agent, and signalling the wrong
process is worse than not signalling. Pass --agent-pid to let watch stop,
resume and kill the agent:
Without --agent-pid, every check still alerts, but pause, kill and
require_approval actions and VS Code Pause cannot stop the agent. The first
time one of them fires, watch prints Cannot ...: no agent PID is known
once. A require_approval rule still creates the approval request. A kill
writes no post-mortem and runs no --on-death.
If the agent exits, the OS can give its PID to an unrelated process. At
startup watch records the agent's start time (field 22 of /proc/PID/stat on
Linux, ps -o lstart= on macOS and other POSIX systems). Before a pause,
resume or kill, while it holds a pause, and as it exits with a pause held,
watch reads the start time again. While a duration limit that kills keeps watch
running, it reads it at the deadline and at most every 5 seconds otherwise. If
it differs, watch sends no signal, prints and writes to the alert log
Agent pid PID: the PID now belongs to another process ..., so no agent was
signalled (without , so no agent was signalled when watch was not about
to signal), treats the agent as exited, clears any pause it held, and never
signals that PID again; the heartbeat then reports no agent PID, so VS Code
Pause is refused. Later require_approval rules create requests with no agent
PID, and kill writes no post-mortem and runs no --on-death. If either start
time cannot be read, watch signals as before. ps reports start times to the
second, so on macOS a PID reused within the same second is not detected.
Project budget config (.agent-strace.yaml):
When this block is present, watch checks rolling seven-day spend at startup
and during the session. warn_at writes a terminal warning and alert-log entry.
stop_at blocks new record and record-http sessions. per_session_max
uses the watchdog cost guard and kills only the over-budget session. When
the cost limit kills, that is, it comes from --budget, or from
--max-cost or watchers.cost.max_dollars while the action
(--on-violation, or watchers.retry.alert from --config) is kill, the
lower of the two applies, so per_session_max never raises it. Otherwise
per_session_max replaces the cost limit, including the default $10: a cost
limit that only alerts or pauses never fires, and the session is killed at
per_session_max.
watch, record and record-http read the first of .agent-strace.yaml,
.agent-strace.yml and .agent-strace.json in the working directory, and
only that file. The keys go in the budget block, or at the top level when
there is no budget key, but not both. Values:
| Key | Value |
|---|---|
weekly |
Dollars, 0 or more. 0, null or no value means no weekly budget |
per_session_max |
Dollars, 0 or more. 0, null or no value means no per-session limit |
warn_at, stop_at |
A fraction of weekly, from 0 to 10: 0.9 is 90%. null or no value keeps the default, 0.8 and 1 |
A number may be quoted ("20"), and a dollar amount may start with one $
($20). true, false, yes, nan, inf and other text are refused. A
percent such as stop_at: 90 is refused: it would mean 90 times weekly.
An empty budget: block, with every key commented out, or budget: {}
sets no budget. Inside budget, a key other than these four is refused.
Other top-level keys are ignored, and a file that sets no budget keys sets
no budget, so a file that holds only other config, such as a review or
retention block or the apply sections, works as before.
The file must be UTF-8, and may start with a byte order mark. A .json
file that is not empty must hold a JSON object. YAML is read in a small
subset: one key: value per line, every budget key indented the same,
values plain or quoted, and comments after #. Flow style such as
budget: {weekly: 20}, anchors, tags and block scalars are refused in the
budget keys. A line the reader cannot read is refused when it names a
budget key, and skipped otherwise. A budget key given twice is refused.
When the file cannot be read or parsed, or a budget key holds a value that
cannot be used, watch, record and record-http refuse to start. They
print one line that names the file and the problem, exit 1, and write nothing:
no session, no alert log, no heartbeat. They never run without the budget:
[watch] invalid project budget in .agent-strace.yaml: budget.per_session_max must be a finite number, 0 or more, not -5
agent-strace: invalid project budget in .agent-strace.yml: budget.stop_at must be a number from 0 to 10, a fraction of weekly such as 0.9 for 90%, not 90
Rules file format (.watch-rules.json):
{
"rules": [
{ "name": "cost cap", "condition": "cost_usd > 0.50", "action": "kill" },
{ "name": "protected env", "condition": "file_path matches \"**/production.env\"", "action": "kill" },
{ "name": "large edit", "condition": "files_modified > 30", "action": "pause" }
]
}
The same rules in YAML (.watch-rules.yaml):
rules:
- name: cost cap
condition: cost_usd > 0.50
action: kill
- name: protected env
condition: file_path matches "**/production.env"
action: kill # stop the agent
- name: large edit
condition: files_modified > 30
action: pause
The top level holds one key, rules: a list of one or more rules. A rule
has only these keys, and each value is a string:
| Key | Value |
|---|---|
condition |
Required. One of the two forms below |
action |
Required, in lower case. alert and terminal print the alert. file also writes it to the alert log. pause and kill also write it to the alert log and stop or kill the agent. require_approval is described below. Every action but require_approval also sends the alert to --webhook, Slack and Teams when they are set up |
name |
Optional. Names the rule in alerts and refusals; the default is unnamed |
notify |
Optional. Slack and Teams alerts and approval requests show it as the rule name |
A condition is one of:
METRIC OP NUMBER. METRIC iscost_usd(estimated spend in dollars),files_modified(distinct files that edits named; see Paths and edits below),duration_minutes(minutes since watch started) orconsecutive_test_failures(tool results in a row that read as failures). OP is>,>=,<,<=or==. NUMBER is a plain number such as5or0.50, with no sign,$, exponent or unit.file_path matches "GLOB", or the same with single quotes. It fires on a tool call,file_writeevent orfile_readevent that names a path matching GLOB, a shell-style pattern in which*also matches/. Reads count as well as edits. GLOB must not be empty.
Extra spaces between the parts are allowed. Nothing may follow the number or the closing quote, so one condition cannot combine two tests.
Paths and edits. file_path matches, files_modified, the
cognitive-debt built-in and --policy read the file paths each event
names:
- A tool call names each of its
file_path,path,absolute_path,filePath,target_file,notebook_pathanduriarguments, also when the arguments are stored as a JSON string. Anapply_patchcall whose arguments are the patch text, as GitHub Copilot CLI stores them, names the file on each*** Add File:,*** Update File:,*** Delete File:and*** Move to:line, so a move names both files. - A
file_writeorfile_readevent names itspath,file_pathoruri.
An edit is a file_write event or a call to apply_patch, create,
delete_file, edit, edit_file, file_edit, insert, multiedit,
notebookedit, patch, replace, search_replace, str_replace,
str_replace_based_edit_tool, str_replace_editor, write, write_file
or write_to_file, in any case. A str_replace_editor or
str_replace_based_edit_tool call with command view is a read.
files_modified, cognitive-debt and --policy count edits only;
file_path matches fires on reads too. Shell commands are never edits, so a
file written by echo x > f or sed -i is not counted.
A relative path resolves against the cwd of the latest session_start
event that names an absolute one, including one written before watch
started, so a resumed session that moved to another directory resolves
against the new one. Paths are joined and normalized as text: . and ..
collapse, symlinks are not followed and the file system is not read. A
Windows cwd such as C:\repo works too, and its paths come out with /,
such as C:/repo/a.py. When no session_start names an absolute cwd, a
relative path is matched as stored. Watch never falls back to its own
directory or to the working_dir saved in the session metadata: watch may
run elsewhere, and a wrong base could kill the agent for a file it never
touched. file_path matches and --policy test the resolved
path and the path as stored. files_modified counts distinct resolved
paths, so /app/a.py and a.py with cwd /app count once. A URI such as
file:///app/x and a path that starts with ~ are matched as stored.
A file whose name ends in .json, or whose first character other than
whitespace is { or [, is read as JSON. Any other file is read as YAML,
and watch reads only this subset of it:
rules:on its own line, after an optional---line.- Each rule starts with
-, every rule at the same indentation. Eachkey: valuepair sits on its own line, aligned with the rule's first key. A rule may also start with a line that holds only-. - Each value fits on one line, and quotes are optional. A value in a matching
pair of single or double quotes loses that pair and nothing else. In single
quotes
''stands for one'; in double quotes the only escapes are\"and\\. - Quote a value that starts with a character YAML reserves, such as
[,{,&,*,!,|,>,%or@, or that contains:. - Outside quotes, a
#after a space starts a comment. ~,nulland an empty value are null, which no key accepts.- Indent with spaces. Blank lines and comment lines may go anywhere.
Watch checks --rules at startup. It refuses the value, prints one line and
exits 1, before it reads the session or writes anything, when the value is
empty; the file cannot be read, is a directory or is empty; the file is not
UTF-8 (a byte order mark is refused too); the file is not valid JSON, or has a
line outside the YAML subset; the top level holds anything but the rules
list; or a rule breaks the rules above. A key given twice is refused too.
--dry-run refuses the same way. The line names the file, and for a rule its
position and name, but never a notify value:
[watch] invalid --rules file .watch-rules.json: rule 1 'cost cap': condition has an unknown metric 'cost'; use files_modified, cost_usd, consecutive_test_failures or duration_minutes
A pause rule keeps the agent stopped until a human resumes it: send
SIGCONT, or, while watch runs, run Pause Agent and then Resume Agent in
VS Code. A require_approval rule keeps it stopped until the request is
decided; the VS Code Resume command does not release it. Both rules stop only
the agent process, and a command the agent is running goes on until it ends.
Approving releases the pause. Denying leaves the agent stopped like a pause
rule, because an agent that handles SIGTERM only acts on it after SIGCONT.
A kill ends any pause, since it sends SIGCONT right after SIGTERM; a
pending request stays pending. While watch holds a pause, the idle timeout does
not count; the pause is dropped if the agent process exits. If watch cannot
send SIGSTOP (the PID is gone or watch may not signal it), it prints and logs
Agent pid PID was not paused: REASON and holds no pause; a require_approval
request is still created. If it cannot send SIGCONT for a VS Code Resume, it
prints was not resumed and drops the pause, since it could never release it.
--dry-run reports a require_approval rule without pausing or
creating a request.
Watch never resumes the agent when it exits, whether on Ctrl-C, the end of the session or an error. VS Code Resume needs a running watch, so if watch still holds a pause, it prints and writes to the alert log how to release it:
[watch] Watch stopped while agent pid 4120 is paused by a watch rule. It stays stopped, and VS Code Resume needs a running watch: run 'kill -CONT 4120' to resume it.
[watch] Watch stopped while agent pid 4120 is paused for approval 3f2a9c1e07bd. It stays stopped until the request is decided: run 'agent-strace approval approve 3f2a9c1e07bd' to resume it.
A pause from VS Code says paused by the editor, and a denied request says
paused by a watch rule. Watch says nothing when it killed the agent, the
agent has exited, or its PID now belongs to another process.
Built-in rules (--rules mcp-poisoning,loop:3/10,budget:5,timeout:30m):
| Rule | Effect |
|---|---|
mcp-poisoning |
Alert on MCP tool poisoning indicators, the checks mcp-scan runs. Takes no value |
loop, loop:N, loop:N/W |
Loop detection always runs. loop:N sets its threshold, like --loop-threshold, and loop:N/W also sets its window, like --loop-window. N and W are whole numbers, 1 or more |
budget:N |
Sets the cost limit to N dollars. N is a finite number, 0 or more, and may start with one $. Like --max-cost, it acts with --on-violation and does not kill as --budget does. It may lower a cost limit that kills, but never raises it (see below) |
timeout:D |
Sets the duration limit to D, a duration more than 0 such as 30m or 2h. Like --max-duration, it acts with --on-violation, so unlike --timeout it kills only when that action is kill; it is then checked on every poll cycle, as --timeout is. It may lower a duration limit that kills, but never raises it (see below) |
cognitive-debt, cognitive-debt:N |
Alert when the session has modified files that have not had human review. N is the threshold, from 0 to 1; without it, cognitive_debt_threshold from --config is used, or 0.8 |
A cost limit kills when it comes from --budget or per_session_max, or
from --max-cost, watchers.cost.max_dollars or budget:N while the
action (--on-violation, or watchers.retry.alert from --config) is
kill. A duration limit kills when it comes from --timeout, or from
--max-duration, watchers.duration.max_minutes or timeout:D while the
action is kill; it is then checked on every poll cycle, like --timeout.
When a flag, the config file or per_session_max sets a limit that kills,
the lower of that limit and the budget:N or timeout:D value applies, and
the limit still kills: --budget 5 --rules budget:10 and
--budget 10 --rules budget:5 both kill above $5. Any other limit is
replaced, and so are the defaults, $10 and 1800 seconds, even with
--on-violation kill: --max-cost 5 --rules budget:10 alerts above $10,
and --on-violation kill --rules timeout:2h sets a 2 hour limit that kills.
Names are lower case, and each rule may be listed once. Watch refuses, at startup, an item that is not one of these, a value out of range, an empty item, a rule listed twice, and a rules file listed with built-in rules:
Config file (--config FILE):
{
"watchers": {
"retry": { "max": 5, "alert": "kill" },
"cost": { "max_dollars": 10 },
"duration": { "max_minutes": 30 },
"loop": { "identical_calls": 3, "window": 10, "sequence_length": 3, "max_repeats": 3 },
"scope": { "policy": ".agent-scope.json" }
},
"webhook": { "url": "https://hooks.example.com/agent-watch" },
"operation_rules": [
{ "tool": "bash", "pattern": "rm -rf *", "action": "block", "reason": "destructive delete" }
],
"max_context_pct": 90,
"built_in_rules": ["mcp-poisoning"],
"cognitive_debt_threshold": null
}
Every key is optional. A key that is not in the file keeps its default.
| Key | Value | Default | Overridden by |
|---|---|---|---|
watchers.retry.max |
Whole number, 0 or more: alert when the same Bash command runs more than this many times | 5 |
--max-retries |
watchers.retry.alert |
terminal, file, kill, pause or require_approval. This is the action for every watcher, not only retries |
terminal |
--on-violation |
watchers.cost.max_dollars |
Number, 0 or more | 10 |
--max-cost, --budget |
watchers.duration.max_minutes |
Number more than 0 | 30 |
--max-duration, --timeout |
watchers.loop.identical_calls |
Whole number, 1 or more: alert when an identical tool call repeats this many times. When it is absent, threshold is read, then max_repeats |
3 |
--loop-threshold |
watchers.loop.window |
Whole number, 1 or more: recent events to scan for identical tool calls | 10 |
--loop-window |
watchers.loop.sequence_length |
Whole number, 1 or more: length of a repeated event sequence | 3 |
|
watchers.loop.max_repeats |
Whole number, 1 or more: repeats of that sequence before an alert | 3 |
|
watchers.scope.policy |
Non-empty string: scope policy file | .agent-scope.json |
--policy |
webhook.url |
String: the URL alerts are POSTed to. Empty means no webhook. When --webhook is not given, watch refuses at startup a URL it cannot POST to, as for --webhook |
"" |
--webhook |
operation_rules |
Array of objects, each with tool (string, default *), pattern (glob, default *), action (alert or block, default alert) and reason (string). action only changes the alert text; what watch does is set by watchers.retry.alert |
[] |
|
max_context_pct |
Whole number from 1 to 100 | 90 |
--max-context-pct |
built_in_rules |
Array of mcp-poisoning, loop and cognitive-debt |
[] |
--rules adds to it |
cognitive_debt_threshold |
null, or a number from 0 to 1 |
null (0.8 is used) |
--rules cognitive-debt:N |
Watch checks the file at startup. It refuses the file, prints one line and
exits 1, before it reads the session or writes anything, when the file is
missing or unreadable, is not UTF-8 JSON (a byte order mark is refused too),
its top level is not an object, a key above has the wrong type or a value out
of range, or an action or rule name is not one listed above. true and
false are not numbers, NaN and Infinity are refused, and null is
refused everywhere except cognitive_debt_threshold. A whole number may be
written as 2.0. The line names the file, the key and what the value must
be, but never the value:
[watch] invalid --config file .agent-watch.json: watchers.retry.alert must be one of terminal, file, kill, pause, require_approval
Other keys are ignored, except the project budget keys above, so the same
file can hold them: a budget block, or top-level weekly, warn_at,
stop_at and per_session_max. Watch checks them by the rules in Project
budget config above, so null is allowed for them. It checks a budget
block even when the block sets neither weekly nor per_session_max. A
value it cannot use refuses the file the same way:
[watch] invalid --config file .agent-watch.json: budget.per_session_max must be a finite number, 0 or more
When the --config file sets either weekly or per_session_max, its
budget keys replace the standard project config for that run, so a budget
in .agent-strace.yaml, .agent-strace.yml or .agent-strace.json is not
read then, nor checked. A key counts as set when it is present, even as
null or 0. When the file sets neither key, watch reads the standard
project config.
Flags given on the command line override the file, and a flag that is not
given keeps the file's value. --on-death, which has no key, applies with
--config too. per_session_max from the project budget config is applied
after the flags and the file: it lowers a cost limit that kills but never
raises it, and it replaces any other cost limit (see Project budget
config above). --rules built-ins such as budget:5 are applied last,
the same way: budget:N and timeout:D lower a limit that kills, including
per_session_max, but never raise it, and they replace any other limit (see
Built-in rules above).
approval¶
agent-strace approval list [--state pending|approved|denied]
agent-strace approval show <request-id>
agent-strace approval approve <request-id> [--by NAME] [--no-resume]
agent-strace approval deny <request-id> [--reason TEXT] [--by NAME] [--no-kill]
action=require_approval pauses the agent while it waits for a decision.
watch can only pause the agent when it was started with --agent-pid.
Approving resumes the agent with SIGCONT by default; denying terminates it
with SIGTERM by default. Both signal only the agent process, and a command
the agent is running goes on until it ends. A request created by a watch
without --agent-pid has no agent PID: approve and deny still record the
decision and exit 0, but signal nothing and say so.
A request made by watch --agent-pid also stores the agent's start time in
agent_start_time. Before approve or deny signals the PID, it reads the
start time again. If it differs, the agent has exited and its PID was reused:
the decision is still recorded and the command exits 0, but nothing is
signalled and it prints decision recorded, but agent PID was not signalled:
the PID now belongs to another process. Requests written by older versions
have no agent_start_time, and are signalled as before, as are requests whose
start time cannot be read now (for example on Windows).
A request is decided once. If two reviewers approve or deny the same request
at the same time, exactly one succeeds and the other exits non-zero with
Request already approved or Request already denied. Records with an
unknown state are skipped by list and rejected by show, approve and
deny.
show, approve and deny take a request ID or a unique prefix of one, and
resolve it the same way. An exact ID wins, even when longer IDs start with it.
The argument is plain text, so *, ? and [ match only themselves. A
prefix that matches two or more requests is refused. The command names the
prefix and up to five matching IDs in sorted order, records nothing, signals
nothing and exits 1:
A request file that cannot be read still counts as a match, so a prefix never
skips it to reach another request. A symlink counts too, and is never
followed. When such a file is the only match, or has the exact ID, the
command prints Request REQUEST_ID has an invalid record: REASON with the
full ID and exits 1. REASON is is a symlink for a symlink. An argument that
is empty, . or .., or holds /, \ or a control character is refused
with invalid request ID before any file is read. These messages show each
character of an ID that str.isprintable() rejects as its escape.
| Command/flag | Description |
|---|---|
list --state STATE |
List requests, optionally filtered to pending, approved, or denied |
show REQUEST_ID |
Show a request by ID or unique ID prefix |
approve REQUEST_ID |
Approve a pending request by ID or unique ID prefix |
approve --by NAME |
Record the approver name |
approve --no-resume |
Approve without sending SIGCONT to the agent |
deny REQUEST_ID |
Deny a pending request by ID or unique ID prefix |
deny --reason TEXT |
Record the reason for denial |
deny --by NAME |
Record the reviewer name |
deny --no-kill |
Deny without sending SIGTERM to the agent |
audit¶
Check tool calls against a policy file. Flags sensitive file access even without a policy. Exits 1 on violations.
--verify-chain checks the session's hash chain first, as verify
does. If the chain is not intact, it prints the verify message, skips the
policy audit and exits 1.
Policy file (.agent-scope.json):
{
"files": {
"read": { "allow": ["src/**", "tests/**"], "deny": [".env"] },
"write": { "allow": ["src/**"], "deny": [".github/**"] }
},
"commands": {
"allow": ["pytest", "uv run", "cat"],
"deny": ["curl", "wget", "rm -rf"]
},
"network": { "deny_all": true, "allow": ["localhost"] }
}
audit-tools¶
Detect which AI coding tools are used in a repository: Claude Code, Cursor,
GitHub Copilot, Codex / ChatGPT, Windsurf, and Aider. Detection uses config
file signals and, for some tools, commit message patterns. The report also
flags known LLM provider endpoints other than Anthropic, OpenAI and Gemini
(such as OpenRouter or Mistral) in committed .env, .env.* and *.env
files, each endpoint judged on its own, and PII-like patterns in recent
commits. Reads local files and git history only: no network
calls, no API keys. --since takes a git date (default: 90 days ago).
--approved is a comma-separated list of the tool names above
(case-insensitive); any other detected tool is reported as unapproved.
mcp-scan¶
agent-strace mcp-scan [--session ID] [--since DURATION_OR_DATE] [--watch]
[--patterns FILE] [--project-root DIR] [--format text|json]
| Flag | Description |
|---|---|
--session ID |
Scan one session by ID or prefix |
--since DURATION_OR_DATE |
Scan recent sessions since a duration or ISO date (default: 7d) |
--watch |
Tail the selected/latest session and alert as new events arrive |
--patterns FILE |
Add regex patterns from a plain text file |
--project-root DIR |
Root used to detect writes outside the project (default: .) |
--format text\|json |
Output format (default: text) |
Custom patterns are read from ~/.agent-strace/mcp-patterns.txt by default. Add one case-insensitive regex per line; blank lines and # comments are ignored.
policy¶
agent-strace policy [generate] [SESSION_ID ...] [--output FILE] [--dry-run]
agent-strace policy backtest [--policy FILE] [--days N] [--show-sessions] [--format text|json]
agent-strace policy diff OLD_POLICY NEW_POLICY [--days N] [--format text|json]
agent-strace policy coverage [--policy FILE] [--days N] [--show-uncovered] [--format text|json]
.agent-scope.json from observed traces, or evaluate a proposed policy
offline against stored sessions before enforcement. The existing bare policy
form remains an alias for policy generate.
| Command / flag | Description |
|---|---|
generate [SESSION_ID ...] |
Suggest a policy from selected sessions, or all sessions by default |
backtest |
Report per-rule matches and calls/sessions that would be blocked |
diff OLD NEW |
Compare both policies over the identical history window |
coverage |
Measure the fraction of tool calls matched by an explicit rule |
--policy FILE |
Policy to evaluate (default: .agent-scope.json) |
--days N |
Evaluate sessions started in the last N days (default: 30) |
--show-sessions |
List session IDs containing calls that would be blocked |
--show-uncovered |
List calls that did not match an explicit rule |
--format text\|json |
Human-readable or machine-readable output |
Backtesting is read-only and uses the same matching semantics as audit; it
never enforces a policy or contacts a remote service.
verify¶
agent-strace verify [session-id] [--format text|json]
agent-strace verify --from-export FILE [--format text|json]
agent-strace verify --note [REV] [--format text|json]
Each event after the first stores prev_hash, the SHA-256 of the exact
previous line of events.ndjson. verify reports one state and exits 0 only
for unanchored:
| State | Meaning | Exit |
|---|---|---|
unanchored |
Every event after the first links to the exact previous line. A single event is unanchored |
0 |
partial |
Some events after the first have no prev_hash. Every link that is present matches |
1 |
legacy |
Two or more events and no links. Sessions recorded before v0.62.0 look like this | 1 |
empty |
No events | 1 |
missing |
The session has no events.ndjson |
1 |
broken |
A link does not match, the first event has a prev_hash, a prev_hash is not a string, or a line is not a UTF-8 JSON object |
1 |
A missing link means an edit to the event before it can't be detected, so
partial and legacy fail. These are the states validate reports. See
Hash-chain states. Only verify reports
missing.
--format json prints these keys:
| Key | Value |
|---|---|
session_id |
Full session ID |
ok |
true only for unanchored, the same as exit 0 |
total_events |
Number of non-blank lines in events.ndjson |
broken_at |
0-based index of the line that breaks the chain, or null |
broken_event_id |
event_id of that line, or "" when it has none or can't be parsed |
state |
One of the states above |
links_verified |
Links that are present and match, counted up to a broken line |
first_unlinked_at |
0-based index of the first event after the first with no prev_hash, or null |
root_hash |
SHA-256 of the last line, or "" with no events. The EU AI Act export uses the same value |
The chain is not keyed or anchored. It can't detect events deleted from the
end, or an edit followed by a rebuild of every later hash. To catch those, keep
root_hash and total_events from verify --format json somewhere the agent
can't write, and compare them later.
--from-export FILE checks an EU AI Act package. See
EU AI Act export package.
--note [REV] reads the review note attached to
REV (default HEAD) and compares each session it names with the trace
directory. A session is match, extended (the note's events match and
more were added), differs, missing, or unreadable. It exits 0 only when
every session is match or extended, and 1 with no note, an unsupported
note, or a REV that is not a commit. It compares event logs only and does
not re-derive the findings. JSON has ref, commit, ok, state
(checked, no_note, or unsupported) and reason. When checked, it adds
note_head, published_at, tool and sessions, each with session_id,
state, note_events, note_chain, events and chain. It can't be
combined with a session ID or --from-export.
identity¶
agent-strace identity show
agent-strace identity sign <session-id>
agent-strace identity verify <session-id>
show creates a persistent identity (stored in ~/.agent-strace/identity.json) if one does not exist. sign attaches an HMAC signature to a session. verify checks the signature.
Use machine identity to prove which machine produced a session — useful for compliance and multi-machine deployments.
workspace¶
agent-strace workspace list
agent-strace workspace new <name>
agent-strace workspace use <name>
agent-strace workspace rm <name> [--force]
<trace-dir>/workspaces/<name>/. use prints export AGENT_STRACE_WORKSPACE=<name>; run eval $(agent-strace workspace use <name>) so later commands in that shell read and write that workspace. rm refuses to delete a workspace that has sessions unless --force is given.
Labs: Cost and reports¶
cost¶
agent-strace cost [session-id] [--model MODEL] [--input-price N] [--output-price N]
agent-strace cost --breakdown provider [--since DATE_OR_DURATION] [--csv] [--live-pricing]
agent-strace cost --tenant ID [--since DATE_OR_DURATION]
Tokens are estimated from the size of each event. A session that records each
model request as an llm_response with no llm_request and its own token
counts, as OpenAI Codex does, is priced from those recorded counts instead,
and no event is also estimated from size. So is a Claude Code session read by
import, whose assistant_response events carry each response's
recorded usage; a response recorded on several events with the same
message_id counts once. Sessions recorded by hooks carry no usage and keep
the size estimate. tree, timeline, replay, watch and the EU AI Act
compliance export count tokens the same way. See
Responses recorded without a request
and
Model responses imported from a transcript.
--breakdown provider aggregates all stored sessions in the selected window by
inferred provider and model. It uses actual recorded token counters and a bundled,
dated pricing snapshot, so the default path makes no network calls. CSV output has
the stable columns provider, model, session_id, input_tokens,
output_tokens, and cost_usd, followed by cache_read_tokens and
cache_write_tokens. Usage recorded without a model name is listed
under the model (not recorded) (an empty model in CSV) and the provider
Unknown, with no estimated price.
Model names. A recorded model name finds its bundled price by this rule.
Case is ignored. One provider prefix is dropped: bedrock/, aws/bedrock/,
openai/, anthropic/, google/ or models/. A Bedrock ARN in the aws,
aws-us-gov or aws-cn partition stands for the model ID after its
foundation-model/ or inference-profile/. Then a Bedrock geography prefix
is dropped (us., eu., apac., jp., au., us-gov., ca., in. or
global.), and then a leading anthropic.. Then, in a name that starts with
claude-, a dot between two digits reads as a dash. The name uses the longest
table name that it equals, or that it starts with followed by -, : or @.
So us.anthropic.claude-sonnet-4-5-20250929-v1:0,
anthropic.claude-sonnet-4-5-20250929-v1:0, claude-sonnet-4-5-20250929 and
claude-sonnet-4.5 use claude-sonnet-4-5, anthropic/claude-3.5-sonnet:beta
uses claude-3-5-sonnet, and gpt-4o-2024-08-06 uses gpt-4o. A name such as
claude or claude-opus-47 has no price. compaction,
inflation, token-budget and
watch read model names by the same rule.
AWS Bedrock. These names are listed under AWS Bedrock: a bedrock/ or
aws/bedrock/ name, a model ID that starts with a Bedrock vendor, with or
without a geography prefix, and every Bedrock ARN. The Bedrock vendors are
ai21., amazon., anthropic., cohere., deepseek., luma., meta.,
minimax., mistral., moonshot., moonshotai., nvidia., openai.,
qwen., stability., twelvelabs., writer., xai. and zai.. A Bedrock
model with no bundled price, such as deepseek.v3.2, is listed under AWS
Bedrock with no estimated price. An application inference profile,
provisioned model or custom model ARN names no model. It is listed under AWS
Bedrock with no estimated price.
A us., eu., apac., jp., au., us-gov., ca. or in. profile of
Claude Sonnet 4.5, Haiku 4.5, Opus 4.5 or a later model costs 1.1 times the
bundled rate, which is the global rate. All five rates are multiplied: input,
output, cache read, cache write and long cache write. This holds inside
bedrock/, aws/bedrock/ and an inference-profile ARN too. The
Anthropic pricing page
says regional and multi-region endpoints cost 10 percent more than global
ones for these models. The
AWS Bedrock pricing page lists the
US rates of Claude Sonnet 4.5 at 1.1 times its global rates. Older models get
no premium, as the Anthropic page leaves them out: claude-opus-4-1,
claude-opus-4, claude-sonnet-4, claude-3-7-sonnet, claude-3-5-sonnet,
claude-3-haiku and claude-3-opus. Non-Claude models such as Nova get none
either.
A global. profile, a bare anthropic. model ID and a foundation-model ARN
use the bundled rate. A global. profile has no premium. A bare ID or a
foundation-model ARN does not show whether the call went to a regional
endpoint.
Claude in Amazon Bedrock
always uses a bare ID, and its region is part of the endpoint. So on a
regional endpoint the real cost is 10 percent higher than the estimate.
| Flag | Default | Description |
|---|---|---|
--model |
sonnet |
sonnet, opus, haiku, gpt4, gpt4o |
--input-price |
— | Custom input price per 1M tokens (requires --output-price) |
--output-price |
— | Custom output price per 1M tokens (requires --input-price) |
--breakdown provider |
— | Aggregate Anthropic, OpenAI, AWS Bedrock, and Gemini usage |
--since DATE_OR_DURATION |
30d |
ISO date or duration such as 7d, 24h, or 2w |
--csv |
off | Emit raw per-session/model rows instead of the dashboard |
--live-pricing |
off | Request authoritative live rates; error when compatible provider APIs are unavailable rather than scrape or guess |
--tenant ID |
— | Scope an explicit session or aggregate the selected time window to one tenant |
Recorded prompt-cache usage is priced at the model's cache rates: cache reads (cached input) at the cache read rate and cache writes at the cache write rate. A write recorded with the long lifetime (Anthropic 1 hour, OpenAI 12 hours) uses the long write rate. These usage shapes are read:
| Source | Cache fields | Input count |
|---|---|---|
| OpenAI Chat Completions | prompt_tokens_details: cached_tokens, cache_write_tokens |
prompt_tokens includes them |
| OpenAI Responses | input_tokens_details: cached_tokens, cache_write_tokens, cache_write_tokens_details (ttl_30m_tokens, ttl_12h_tokens) |
input_tokens includes them |
OpenAI Codex token_usage |
cached_input_tokens, cache_write_input_tokens |
input_tokens includes them |
| Anthropic Messages, imported Claude Code transcripts | cache_read_input_tokens, cache_creation_input_tokens, cache_creation (ephemeral_5m_input_tokens, ephemeral_1h_input_tokens) |
input_tokens excludes them, so they are added |
| Bedrock Converse | cacheReadInputTokens, cacheWriteInputTokens, cacheDetails (ttl, inputTokens) |
inputTokens excludes them, so they are added |
| Gemini | cachedContentTokenCount |
promptTokenCount includes them |
input_tokens in every report is the whole input, cache reads and writes
included, and the cache parts are reported beside it: in the per-session text
output when non-zero, and in the CSV columns above. Anthropic and Bedrock usage
therefore reports more input tokens than its own input_tokens field. Gemini
thinking tokens are counted as output and tool-use prompt tokens as input, as
Gemini bills them. OpenAI and Codex output already includes reasoning tokens.
A recorded count that is negative or above 9,007,199,254,740,991 (2**53 - 1)
reads as missing, as if the field were absent. So a session whose responses
record no usable count keeps the size estimate. Above 2**53 - 1, a JSON
reader that uses doubles cannot keep every count exact (see
I-JSON). Earlier
versions read a larger count, so a huge one could make a cost infinite or stop
the command with an OverflowError.
Cache tokens are billed at the input rate when the model has no published
cache rate (for example the haiku, gpt4 and gpt4o choices of --model,
retired models, and --input-price), and a long write without its own rate
uses the default write rate. Tokens estimated from event size have no cache
split. Pricing estimates exclude batch discounts, service-tier differences,
long-context premiums, data-residency premiums, cache storage fees, and
non-token charges. The only regional difference they include is the Bedrock
premium above. Other regional rates, such as GovCloud rates, are excluded.
When a pricing page lists a temporary promotional price and the price that
follows it, the following price is used. To update the bundled table, check the
official URLs in PRICING_SOURCES, update PRICING (each key's provider is
derived from its name), advance PRICING_SNAPSHOT_DATE, and extend
tests/test_provider_cost.py for every added model family.
budget-report¶
Weekly spend digest: total cost, top sessions, cost by tool, watchdog savings.
team-report¶
agent-strace team-report [--since DATE] [--until DATE] [--by author|branch|pr] [--export text|csv|json] [--outlier-threshold N]
| Flag | Description |
|---|---|
--since DATE |
Start of reporting window. Accepts ISO dates or durations like 7d; default is 7 days ago |
--until DATE |
End of reporting window. Accepts ISO dates or durations like 7d; default is now |
--by author|branch|pr |
Group by git author, active branch, or PR inferred from branch names like pr-123 |
--export text|csv|json |
Output format. csv is intended for spreadsheets and finance workflows |
--outlier-threshold N |
Flag sessions whose cost is above N times the report average; default is 2.0 |
Session costs are agent-strace cost totals at the default model. A session
that command refuses, or whose events cannot be read, is not priced: it is left
out of the total, the averages and the outliers, and the Total line says how
many sessions were not priced. A group with no priced session shows n/a for
its cost and average (empty in CSV, null in JSON), and so does the total when
no session in the report is priced. CSV output has an
unpriced_sessions column and JSON an unpriced_sessions field.
dashboard¶
Multi-session aggregate view. --trend shows eval quality and behavioral metrics over time.
The eval quality comes from the eval.json that eval run and eval ci
save in each session. --trend prints a Quality trend (eval pass rate): line
for each scorer, with its pass rate in the earlier and the later half of the
sessions, and --trend --html draws a chart for each. A session with no
eval.json has no eval scores, and with none in any session the section is left
out.
A session's errors include its failed model requests, and a session with any error is not
counted as succeeded. Neither is a session whose session_end says it timed
out or was killed (a timeout or killed status, a reason naming one, or a
nonzero exit code); earlier versions counted such a session as succeeded when
it recorded no errors. A session with no session_end and no errors still
counts as succeeded. For a session recorded by an earlier version, whose
stored count leaves failed requests out, the dashboard shows the larger of the
stored count and the count from its events. The --trend error rate counts
failed requests too.
Session costs, the total and the cost trend match agent-strace cost with its
default model, so recorded token usage, cache reads and writes included, is
priced at the model's rates. Earlier versions priced each session's token count
at a flat $3 per million. A session whose events cannot be read, or that
agent-strace cost refuses, is not priced: its cost shows n/a, it is left out
of the total and the cost trend, and the total says how many sessions were not
priced (--trend prints a Sessions not priced line, and its HTML report
marks the cost chart). It is never counted as $0.
Values from the trace are escaped in the HTML from -o and --trend --html,
so markup in them shows as text.
A started_at that is not a usable time shows as ?, and --trend --since
leaves the session out. --trend --html takes its period and annotation
positions from the usable starts. With none, the period is empty and no
annotation is placed. See list.
--trend --since is the last N days, as N or Nd, such as 7, 7d or
0.5d. N is ASCII digits with at most one . between digits. 0d selects
nothing. Any other value, an empty one too, prints
invalid --since value: use a number of days as N or Nd, such as 7d on stderr
and exits 1, and --html writes no file. Without --trend, dashboard does
not read --since.
# Add a timeline annotation (appears as a vertical marker on trend charts)
agent-strace dashboard annotate --date 2026-05-10 --note "Added retry policy"
oncall¶
Cross-reference agent-modified files against git history to find gaps before a rotation.
curve¶
Deprecated: removed in 1.0.0, with no replacement. See Deprecated commands.
Personal agent cost-efficiency curve by task type. Verdict per type: efficient / over sweet spot / do this yourself.
A session whose started_at is not a usable time counts in the sessions, but
the days come from the usable starts only. See list.
inflation¶
Deprecated: removed in 1.0.0, with no replacement. See Deprecated commands.
Estimate how many more tokens, and how much more money, the stored sessions would cost on another model's tokenizer. No API calls required.
It reads the llm_request, user_prompt, assistant_response and llm_response events of the newest sessions. It estimates the tokens of the system prompt, tool definitions, user messages and assistant messages from their size. Each count is multiplied by each model's tokenizer factor and rounded.
| Flag | Default | Description |
|---|---|---|
--compare MODELS |
claude-opus-4-6,claude-opus-4-7 |
The baseline model and the model to compare, as two names separated by one comma. Space around each name is ignored. Each name must have a tokenizer factor. |
--sessions N |
30 |
Read the newest N sessions. Must be 1 or more. |
--daily-sessions N |
8 |
Sessions per day for the Daily and Monthly rows. Must be a finite number, 0 or more. A month is 30 days. |
Prices come from the bundled table that cost uses. The system prompt, tool definitions and user messages use the input rate. Assistant messages use the output rate. A Bedrock name is priced as in cost --breakdown provider, so a us., eu., apac., jp., au., us-gov., ca. or in. profile of Claude Sonnet 4.5, Haiku 4.5, Opus 4.5 or a later model costs 1.1 times the bundled rate. A model with no bundled price, such as gpt-4, o1 or gemini-1.5-pro, shows n/a in each cost cell of its column and in each cost delta. Its token rows still print. claude-sonnet-4-7 uses the claude-sonnet-4 price, as in cost and dashboard.
These models have a tokenizer factor. claude-opus-4-6 is the 1.0 baseline.
| Factor | Models |
|---|---|
| 0.95 | gemini-1.5-pro, gemini-2.0-flash |
| 1.00 | claude-opus-4-6, claude-sonnet-4-5, claude-haiku-3-5, claude-3-opus, claude-3-sonnet, claude-3-haiku, gpt-4 |
| 1.05 | gpt-4o, gpt-4o-mini, o1, o3 |
| 1.35 | claude-sonnet-4-7 |
| 1.38 | claude-opus-4-7 |
A model name resolves by the Model names rule of cost. Case is ignored. A provider prefix such as anthropic/ or bedrock/, a Bedrock geography prefix such as us., jp., au., us-gov. or global., and then a leading anthropic. are dropped. A Bedrock foundation-model or inference-profile ARN stands for its model ID. In a name that starts with claude-, a dot between two digits reads as a dash. A dated or suffixed name resolves to its base model: the longest name in the table that it equals, or that it starts with followed by -, : or @. So gpt-4o-2024-08-06 uses gpt-4o, gpt-4o-mini-2024-07-18 uses gpt-4o-mini, and anthropic/claude-opus-4-7, anthropic.claude-opus-4-7, us.anthropic.claude-opus-4-7-v1:0 and claude-opus-4.7 use claude-opus-4-7. A name such as claude or claude-opus-47 has no factor.
The header counts only the sessions with prompt or model content. A session with only tool calls is left out, so it does not lower the per-session average. With no such session, the count and the averages are 0. "Largest inflation source" names the content type that adds the most tokens. A tie keeps the first type in table order. The line is left out when no type adds tokens.
inflation refuses the values below before it reads any session. It prints one Error: line to stderr that names the flag and the value, prints nothing to stdout, and exits 2.
- A
--comparevalue that is not two names separated by one comma, or that has an empty name. - A
--comparemodel with no tokenizer factor. The message lists the models that have one. - A
--sessionsvalue below 1. - A
--daily-sessionsvalue that is negative,nanor infinite. A value too large for a float, such as1e400, is infinite.
Labs: Collector, administration and compliance¶
server¶
agent-strace server [--port N] [--host HOST] [--storage DIR] [--auth-key KEY]
[--allow-host NAME] [--dashboard]
agent-strace server keygen
| Flag | Description |
|---|---|
--port N |
Port to listen on (default: 4317) |
--host HOST |
Host to bind to (default: 127.0.0.1 with --dashboard, otherwise 0.0.0.0) |
--storage DIR |
Trace storage directory (default: $AGENT_STRACE_STORAGE or .agent-traces) |
--dashboard |
Serve the session list and evidence review at /; non-loopback binding requires --auth-key |
--auth-key KEY |
Require Authorization: Bearer KEY on all requests (also read from AGENT_STRACE_AUTH_KEY) |
--allow-host NAME |
Also accept GET requests whose Host is NAME, on any port. Repeatable. For a tunnel, forwarded port or reverse proxy that passes its own name. Exact match, no wildcards. No effect with --auth-key or on a non-loopback bind |
To refuse requests from web pages, the server answers 403 to any POST with an Origin header and, on a loopback bind without --auth-key, to any GET whose Host is not localhost, an IP address or an --allow-host name (server.md).
The server has no SSO, so it refuses to start with --auth, --oidc-issuer, --oidc-client-id, --oidc-client-secret or --enforce-sso; use --auth-key to require authentication.
keygen prints a new ast_-prefixed API key to stdout. Set AGENT_STRACE_AUTH_KEY on the client side to inject the header automatically into all outbound collector requests.
auth¶
agent-strace auth login --server URL [--force]
agent-strace auth logout --server URL
agent-strace auth status [--server URL]
login asks you to open <URL>/auth/login, complete the IdP login, and paste the token from the success page. agent-strace server has no SSO and serves no /auth/login. The token is stored per server in ~/.agent-strace/auth.json (mode 0600, written atomically under a file lock) and expires after one hour. --force re-authenticates when a valid token already exists. status without --server lists every stored server. Other commands do not read the stored token; apply --server authenticates with --auth-key.
rbac¶
agent-strace rbac assign (--user EMAIL | --group GROUP) --role ROLE [--workspace ID] [--by NAME]
agent-strace rbac revoke (--user EMAIL | --group GROUP) [--workspace ID]
agent-strace rbac list [--workspace ID]
agent-strace rbac check --user EMAIL --action ACTION [--workspace ID]
owner,
admin, member, viewer, and machine. Workspace roles are
workspace:admin, workspace:member, and workspace:viewer.
| Flag | Description |
|---|---|
--user EMAIL |
Select a user principal for assign or revoke; required unless --group is used |
--group GROUP |
Select a group principal for assign or revoke; required unless --user is used |
--role ROLE |
Role to assign; required for assign |
--workspace ID |
Assign, revoke, list, or check in a workspace context; omit for org-level operations |
--by NAME |
Record the assigner name in the audit trail |
--action ACTION |
Authorization action to check; required for check |
Supported actions are read_sessions, run_agent, annotate,
manage_policies, manage_identities, manage_workspaces,
export_compliance, manage_rbac, manage_billing, and manage_sso.
Unknown actions require the effective owner role.
Assignments are stored in rbac.json in the global trace store (--trace-dir, else $AGENT_TRACE_DIR, else .agent-traces).
apply¶
Apply .agent-strace.yaml to the local store, or to a hosted collector with --server URL (authenticated with --auth-key KEY). A --auth-key with a character that is not printable ASCII, such as a newline, is refused before any request, also with --dry-run: apply prints --auth-key holds a character that is not printable ASCII, such as a newline on stderr and exits 1. The POSTs to --server do not follow redirects, so pass the final URL. The GET that lists the server's workspaces follows a redirect only to the same scheme, host and port. apply makes that GET only when the config declares a workspace with a name. If it fails, or its reply is not a list of workspaces with names, apply prints one ! line, sends nothing else and exits 1, also with --dry-run. Use --dry-run to preview changes without writing. The local store is --dir DIR when given, else the global trace store (--trace-dir, else $AGENT_TRACE_DIR, else .agent-traces).
config-diff¶
Show drift between .agent-strace.yaml and the local store: --dir DIR when given, else the global trace store. It does not contact a hosted collector.
tenant¶
agent-strace tenant report [--month YYYY-MM] [--model MODEL] [--format text|json]
agent-strace tenant export ID [--format json] [--output FILE]
agent-strace tenant delete ID --confirm
--confirm and appends a minimal audit record. See the
multi-tenant deployment guide for isolation and GDPR notes.
tenant report, tenant export, tenant delete and org-report stop with
"corrupt session in tenant store: started_at is
not a usable Unix time. That covers text, NaN, a negative number, and a value
out of range, such as a time sent in milliseconds. tenant delete then
deletes nothing. The collector answers 400 to such a started_at, but a store
written by an older collector, or edited by hand, can still hold one. To
continue, set started_at in that session's meta.json to a Unix time in
seconds.
tenant report, tenant export and tenant delete also stop with this error
when a session's meta.json has no tenant_id but its events carry one.
tenant delete then deletes nothing. org-report and cognitive-debt do not
apply this check, so they are not affected. Normal capture never writes this
state, but an older store or a hand edit can. To continue, set tenant_id in
that session's meta.json to the tenant ID its events carry.
tenant report, tenant export, tenant delete and org-report also stop
with this error when a session's meta.json is corrupt: not valid JSON, not a
JSON object, or nested more than 128 levels. tenant delete then deletes
nothing. See list for the fix.
retention¶
agent-strace retention status
agent-strace retention clean [--dry-run] [--max-age-days N] [--max-sessions N] [--max-size-mb N]
.agent-strace.yaml:
Limits apply in order: age, then session count, then storage size. The size
limit accounts for space freed by sessions already selected by the age/count
limits, including their compaction checkpoints, before selecting additional
sessions from oldest to newest. Use retention clean --dry-run to preview.
Retention never deletes an open session, and open sessions do not count toward
max_sessions or max_size_mb. A session is open when its metadata has no end
time, or when a hook .active-session* marker in the trace store names it. An
end time that is not a usable Unix time, such as text, NaN, a negative number or
a value out of range, counts as no end time. An open session with no writes to
its directory for 7 days is treated as abandoned (for example, the agent crashed
before its session end hook ran) and is handled like a finished session.
status and clean print how many open sessions were kept.
Retention ages a session by its start time. When the start time is not a usable
Unix time, it uses the newest write to the session directory instead. That is
the latest time the session can have started. This applies to the age limit, the
order of the count and size limits, and the Oldest: line of status. A
session with no usable start time and no readable file time is kept and does
not count toward any limit.
max_size_mb measures only what retention can free: each finished session
directory plus its compaction checkpoint. Datasets, approval records, logs and
other files in the store are not counted. status reports the same measure for
all sessions as Size.
clean deletes under the store write lock and checks again that each session is
still finished, so a session resumed after selection is kept. Deleting a session
also removes its compaction checkpoint, its approval records, its entries in
datasets/*.jsonl, and any hook marker or pending-call state that names it.
org-report¶
agent-strace org-report [--month YYYY-MM] [--team SELECTOR]
[--format text|json|html] [--anonymize]
[--model MODEL] [-o FILE]
[--endpoint URL] [--auth-key-file FILE]
[--ca-file FILE] [--allow-insecure-http]
agent-strace cost for the selected model; the report shows its coverage and
labels averages as per cost-estimated session. With no cost-estimated session,
the averages and median are n/a (null in JSON). Task
types and anomaly callouts are heuristics, not completion or efficiency
measurements. See the organization reporting guide for the
security boundary and interpretation details.
| Flag | Description |
|---|---|
--month YYYY-MM |
Half-open UTC calendar month; default is the current UTC month |
--team SELECTOR |
Exact team tag or workspace. Use tag:NAME or workspace:NAME to resolve a name collision |
--format text\|json\|html |
Terminal text, strict versioned JSON, or self-contained static HTML |
--anonymize |
Replace team/workspace and attributed identity labels with deterministic aliases local to this report |
--model MODEL |
Bundled offline pricing model; default is sonnet |
--output FILE, -o FILE |
Atomically write the complete report; symlinked destinations are refused |
--endpoint URL |
Explicit collector base URL. This command never infers it from AGENT_STRACE_ENDPOINT |
--auth-key-file FILE |
Read the collector bearer key from a file; otherwise use AGENT_STRACE_AUTH_KEY |
--ca-file FILE |
Trust a custom CA bundle for the HTTPS collector. Replaces the system CA store |
--allow-insecure-http |
Opt in to plain HTTP for a non-loopback collector |
compliance¶
agent-strace compliance export [session-id] --framework eu-ai-act|soc2|hipaa|all
[--since Nd] [--output FILE]
Without a session ID, compliance export reports each ended session that
started in the last --since days (default 30d). It refuses when the store
refuses to read any session in it, even one outside that window, so it never
leaves out a session or reports it as empty. With a session ID, it refuses that
session the same way. A session whose events.ndjson is a symlink is refused
too. See
Sessions with mismatched or unreadable events.
compliance export also refuses to report a session whose started_at, or
ended_at when set, is not a Unix time in seconds. It prints one Error: line
on stderr and exits 1. It prints no report and writes no file. With a session
ID, the line is Error: session started_at must be a Unix time in seconds, or
the same message for ended_at. Without a session ID, or with --since, the
line names the session, as in
Error: session <session-id> ended_at must be a Unix time in seconds.
That path refuses a bad started_at first, when it lists the store, even for a
session outside the window. That line is
Error: cannot read session <session-id>: started_at is not a usable time.
--since is the last N days, as N or Nd, such as 7, 7d or 0.5d. N is
ASCII digits with at most one . between digits. 0d selects nothing. Any
other value, an empty one too, prints
invalid --since value: use a number of days as N or Nd, such as 7d on stderr
and exits 1, with or without a session ID. That check runs before the store is
read, so it prints no report and writes no --output file.
This is the legacy compatibility command. For a privacy-minimized, explicitly
heuristic evidence crosswalk with current versioned framework manifests, use
compliance-report. The two output schemas and claims
are intentionally separate.
| Framework | Coverage |
|---|---|
eu-ai-act |
Transparency, human oversight, data governance |
soc2 |
Access control, availability, confidentiality |
hipaa |
PHI handling, audit trail, access logs |
For an auditor-facing EU AI Act Article 12/13 package, use the session export path:
agent-strace export <session-id> --format eu-ai-act --output compliance-report.json
agent-strace export --all --since 2026-01-01 --until 2026-03-31 \
--format eu-ai-act --output Q1-audit.json
agent-strace verify --from-export compliance-report.json
agent-strace audit-readiness [--format text|json]
EU AI Act export package¶
Each session's article_12.trace_integrity holds:
| Key | Value |
|---|---|
hash_chain_valid |
true only when the session's chain is unanchored |
hash_chain_state |
The session's verify state |
root_hash |
SHA-256 of the last event line |
event_count |
Number of events |
compliance_metadata.tamper_evident is true only when the package has at
least one session and every session's hash_chain_valid is true. Sessions
that fail are still exported.
verify --from-export FILE exits 0 only when all of these hold:
- Every session has events, and each event's
seqis its position, counting from 1. - The first event has no
prev_hash. Every laterprev_hashand everyline_hashis 64 lowercase hex characters. Eachprev_hashequals the previous event'sline_hash. hash_chain_validistrue.hash_chain_stateisunanchored, or absent as in exports from earlier versions.root_hashequals the last event'sline_hash, andevent_countequals the number of events.compliance_metadata.session_countequals the number of sessions, andtamper_evidentistrue.article_12.logging_obligationsholds the same records as the sessions.
A package with a session that has missing links or no events fails. A fully
linked session exported by an earlier version still passes. With
--format json, each entry in failures has session_id, seq (the
event's position), event_id and reason. session_id is null for a
problem with the whole package.
The check reads only the package. It can't compare summaries or Article 13
with the source store. It can't see a deleted event when the editor also fixed
seq, the links, event_count and root_hash. To catch that, compare each
session's root_hash and event_count with root_hash and total_events
from agent-strace verify <session-id> --format json on the source store.
compliance-report¶
agent-strace compliance-report --framework aicpa-tsc|owasp-agentic|eu-ai-act
[--since UTC_OR_DURATION] [--until UTC]
[--format json|sarif|pdf] [--output FILE]
[--policy FILE] [--rescan [installed|FILE]]
Build a privacy-minimized evidence crosswalk from the flat trace store and all
workspace stores. It reports only evidence_observed, risk_signal, gap, or
not_assessed. These are evidence labels, not control conclusions. JSON is the
authoritative output; SARIF and PDF are deterministic limited projections.
See the compliance evidence guide for interpretation,
framework sources, privacy behavior, and limitations.
| Flag | Description |
|---|---|
--framework ID |
Required crosswalk: aicpa-tsc, owasp-agentic, or eu-ai-act |
--since VALUE |
Inclusive UTC timestamp/date or duration such as 90d; default is 90d |
--until UTC |
Exclusive UTC timestamp/date; default is the fixed snapshot time |
--format FORMAT |
json (authoritative), sarif, or pdf; default is json |
--output FILE, -o FILE |
Atomically write a nonsymlinked private file with mode 0600; required for PDF. A symlink in a parent directory must be root-owned |
--policy FILE |
Evaluate a bounded local policy at report time; outcomes are would_allow/would_deny, never historical authorization |
--rescan [installed\|FILE] |
With no value or installed, explicitly reuse the installed manifest; a file selects a local versioned JSON manifest. Performs no network, CVE, or SBOM scan |
PDF support is optional: pip install 'agent-strace[pdf]'.
audit-readiness¶
Check whether the local trace store has hash-chain integrity, retention
coverage, timestamp continuity, and hash-chain presence before generating an
EU AI Act audit package.
Hash chain integrity fails when a session's chain is broken or its
events.ndjson is missing. Hash chain presence warns when a session's chain is
empty, legacy or partial, and lists it in sessions_missing_prev_hashes.
See the states under verify. Missing links cost 20 points.
Hash chain integrity also fails when the store refuses to read a session: its
meta.json is corrupt, its started_at, or ended_at when set, is
not a usable time, a tenant ID in it is not valid, or its events are
mismatched or unreadable.
It fails too for each store entry that makes export --all refuse: a symlink,
a directory with no meta.json or no events.ndjson, a directory whose name
is not a session ID, and a session whose meta.json or events.ndjson is a
symlink or not a regular file. It fails as well for a session with an event
whose data is not an object or whose timestamp is not a Unix time in
seconds, because export --all refuses that session too. See
non-object event data and
unusable event timestamps. The
check counts the session or entry and names it with the reason:
FAIL Hash chain integrity: 4 sessions checked
cannot read session c3d4e5f6a7b80003: line 5 of events.ndjson is not valid JSON
cannot read session c3d4e5f6a7b80004: no meta.json
cannot read session c3d4e5f6a7b80005: event data must be an object: event 3 of 7 (tool_call) has array data
With --format json, the session or entry is in broken_sessions, and in
refused_sessions with its session_id and reason. For an entry,
session_id holds its name.
Like export --all, the check skips plain files, and the .approvals,
.tenant-journal, checkpoints and datasets directories when they hold no
session files. Outside a workspace, it skips the workspaces directory the
same way. It reads a symlinked trace directory, but export --all refuses
one, so pass the real directory with --trace-dir.
ready needs a score of 80 or more, no broken chain and no missing links. A
session with missing links makes the store not ready even when retention and
continuity pass, because an EU AI Act export of that session fails
verify --from-export. The command exits 0 when the store is ready and 1
when it is not.
Symlinked parent directories¶
share --assignment, score, compliance-report --output, and validate
refuse a path when one of its directories is a symbolic link, because a cloned
repository or an unpacked archive can plant links that move where these
commands read or write. They follow a symlink in a parent directory only when
all of these hold:
- root owns the symlink;
- root owns the directory that holds it;
- group and other users cannot write that directory, or it has the sticky bit.
This covers operating system links such as /tmp, /var, and /etc on macOS,
so absolute paths under the default macOS TMPDIR work. The components of a
trusted symlink's target are checked by the same rule. A symlink that the
current user owns is always refused. No symlink is trusted on Windows, where
Python reports owner ID 0 for every file, or when the command runs as root.
For validate, the rule covers the path to the session directory, whether
TARGET names the directory or the session is found by ID, prefix, or as the
latest session under --trace-dir or AGENT_TRACE_DIR. It also covers the
directories that hold the --replay-baseline file. On Windows, validate
also refuses directory junctions on these paths. When this rule refuses a
path, validate reports the session as invalid and exits 1.
validate --corpus resolves the path to the installed package first, so this
rule does not apply to that path. Python already imported agent-strace through
that path, so a symlink on it has already decided which code runs.
On Windows, share --assignment and score also refuse directory junctions in
the trace store, session, output, submission, comparison directory, and rubric
paths.
On Windows, compliance-report also refuses directory junctions in the output
path, the trace store directory, its session directories, and .approvals.
These are still refused when they are symbolic links, even root-owned ones:
the output file, the rubric, the submission bundle, the replay baseline file,
and the trace store directory that share --assignment reads.
Sessions with non-object event data¶
Hook capture records every event's data as a JSON object, and
agent-strace server refuses an event whose data is not an object (see
server.md). An older collector stored array, string,
number, and boolean data as it arrived, and a hand edit can store any JSON
value, so a session can still contain non-object data. A command that reads
keys from data checks the session first. If an event it reads has non-object
data, the command writes one line to stderr and exits 1 before it prints,
writes, sends, or opens anything. optimize with an LLM configured is the one
exception, described below. The line looks like this:
Error: session event data must be an object: event 6 of 25 (tool_call) has string data; 5 more events have non-object data
The message names the first such event by position and event type, gives the
JSON type of its data, and counts every other event in the session with
non-object data. It never includes data values or event IDs. Commands that read
more than one session name the session, for example Error: session
c3d4e5f6a7b80003 event data must be an object: event 3 of 7 (tool_call) has
array data.
These commands refuse such sessions: a2a-tree, audit, budget-report,
cognitive-debt, compaction, compare, compliance export,
context-score --file, cost, dashboard --trend, diff, explain,
export with --format otlp, otlp-genai, temporal, or eu-ai-act or with
--backend, inflation, lint, mcp-scan --session, oncall, optimize,
policy generate, postmortem, pr-comment, replay, sample, share,
standup, stats, team-report, tenant report, timeline, token-budget,
and why. A command refuses only when it reads an event whose data is not an
object, so the same session keeps working with commands that never read that
event. When only the cost calculation reads such an event, context-score,
dashboard, drift, export --metrics --backend otlp, fingerprint,
replay --format html, sample, team-report and eval dataset auto --filter
cost-above:N show the session as not priced instead of refusing it, as
described for each command. For example, export --format otlp-genai and
temporal pair events by
ID and do not read a tool_call that an error event pairs with.
export --format temporal checks the session's Temporal trace context first, so
a session without one keeps its Temporal export failed message. optimize
with --base-url and --api-key checks the events in its prompt before it sends
the request. When the LLM returns no patterns, optimize falls back to its
heuristics, which read more events, so it can refuse after it sent the request.
freeze, regression, compliance-report, org-report, and compare for
events other than decisions already stopped on these sessions with their own
error message and exit code 1, and they keep it.
audit-readiness does not refuse such a session. Its hash chain integrity
check fails when any event of a session has non-object data, and names the
session with the reason. export --format eu-ai-act --all refuses that store.
See audit-readiness.
list, inspect, tree, verify, and export --format json, ndjson, or csv
keep working on these sessions. The export formats include the data as stored,
except that json and ndjson write a NaN or infinite number as null.
watch keeps running when a live event that one of its checks reads has
non-object data. It skips the checks for that event, prints one line such as
[watch] Skipped checks for one tool_call event because its data is a string,
not an object. to stderr, and still counts the event. A file_read event is
read only while a file_path matches rule that has not fired is active. watch
--compaction-checkpoint refuses at startup when the session already has an
event with non-object data. mcp-scan --watch refuses at startup in the same
way and skips live events with non-object data with an [mcp-scan] line.
Without --stream-otlp, watch --stream-to sends a live event with non-object
data as stored. With --stream-otlp, watch turns each batch into spans and
leaves out each such event whose data the span converter reads, with one line
per event on stderr such as [stream] Left one tool_result event out of the
OTLP stream because its data is an array, not an object. The other events of
the batch are still sent. The converter reads user_prompt,
assistant_response, llm_request, llm_response, tool_call,
tool_result, and error data, but not the data of a tool_call that an error
event pairs with, so that tool_call and events such as session_start,
decision, and file_read stay in the batch. Leaving an event out can change
how the others pair, so the check repeats on the events that are left: when an
error event and the tool_call it pairs with both have non-object data, both are
left out. Nothing is sent for a session with no event left in the batch. If the
conversion still fails, watch prints one line such as [stream] Could not
convert 4 events to OTLP spans (KeyError); they were not sent., which names
the exception type but never its message, and keeps sending later batches.
Fields with the wrong type¶
When data is an object but a field inside it has the wrong type, commands read
that field as missing. Examples are a number where a tool name belongs, a string
where an arguments object belongs, and a list where a prompt belongs. The
command behaves as if the key were absent and keeps going, without a traceback
or an error message. A number field accepts integers and decimals. true,
false, and numeric strings such as "12" are not numbers, so they read as
missing too. watch, mcp, compliance-report, and audit-readiness read
fields the same way. cognitive-debt is the exception. It stops with an error
when a write event's tool name, path, or arguments have the wrong type, and it
counts the lines of text inside content stored as a list or an object.
Some output still prints the stored value as it is, for example the share
page, export --format json, the otlp and otlp-genai exports, audit,
postmortem, and the compliance export access log. Cost and token estimates
still count the stored size of each event.
record and record-http link a tool result or a JSON-RPC error to its call
only when the JSON-RPC id is a string or a number. With any other id they
forward both messages and record both events without the link.
The top-level event fields duration_ms, event_id, parent_id, and
redacted follow the same rule. A duration_ms that is not a number, or is
negative, NaN, infinity, or too large for a float, reads as missing. An
event_id or parent_id that is not a non-empty string reads as missing, so
no event links through it. Only true counts as redacted. The otlp and
otlp-genai exports still give each event its own span ID. inspect,
sample, and export --format json, ndjson, or csv keep the stored value,
except a duration_ms that reads as NaN or infinity, such as NaN or 1e400.
inspect, sample, json and ndjson leave it out, and csv writes it as
nan, inf or -inf.
validate reports each such value as event_schema_invalid, and org-report
refuses any of them. compliance-report refuses an event_id or parent_id
that is not a string, an empty event_id, and a NaN or infinite
duration_ms. share refuses a NaN or infinite duration_ms, and
share --assignment refuses any duration_ms that is not a usable number.
Sessions with unusable event timestamps¶
An event's timestamp is a Unix time in seconds, from 0 to
9999-12-30T00:00:00Z. The limit is the same in every time zone. On Windows it
can be lower, near the end of the year 3000. agent-strace server refuses an
event whose timestamp is not such a time (see
server.md). In Python, TraceStore.append_event
and append_events raise ValueError for a NaN or infinite timestamp and
write nothing. A batch with one such event writes none of its events. A
session stored by an older version, or edited by hand, can still hold text,
null, true, an object, an array, NaN, infinity, a negative number, or a
time after 9999-12-30T00:00:00Z, such as a time in milliseconds. The commands
in the two lists below check the session first. If an event a command reads
has such a timestamp, the command writes one line to stderr and exits 1 before
it prints, writes, sends, or opens anything. The line looks like this:
Error: session event timestamp must be a Unix time in seconds: event 6 of 25 (tool_call) has a string timestamp; 5 more events have unusable timestamps
The message names the first such event by position and event type, and says
what kind of value its timestamp is: string, null, boolean, object,
array, non-finite, negative, or out-of-range. It counts every other
event in the session with an unusable timestamp. It never includes the value.
Commands that read more than one session name the session, for example
Error: session c3d4e5f6a7b80003 event timestamp must be a Unix time in
seconds: event 3 of 7 (tool_call) has an array timestamp.
These commands check every event of the session: annotate --at, compare,
cost, diff, explain, export --format eu-ai-act, postmortem,
pr-comment, replay, review, share without --assignment, standup,
tenant report, and timeline. cost --tenant checks each session it
prices. replay checks every event even when --filter or --limit hides
the bad one, and replay --expand-subagents checks every session it shows.
These commands check only the events they read, so the same session keeps working when the bad event is one they never read:
a2a-tree --format json: eacha2a_callevent in every session of the tree. The text tree reads no call timestamp, so it does not check.compaction: the first event and thellm_requestevent of each compaction it finds. It checks nothing in a session with no compaction.compliance export:tool_callanderrorevents.eval gate: every event, when the config hascost_usd, or hasduration_secondsand the session metadata holds no usable duration. It names the session.eval run,eval compare, andeval ci: each session they score. Withcost_underin the config, they check every event, ascostdoes. Withduration_underand nocost_under, they check the first and last events. They name the session.export --backend langfuse:tool_call,tool_result,llm_request,llm_response, anderrorevents. It checks after the credentials and before it sends anything.export --format otlp:user_prompt,assistant_response,decision,tool_call,tool_result,error,llm_request, andllm_responseevents.export --format otlp-genaiand--format temporal: the same types withoutdecision.oncall:tool_callandfile_writeevents.sample: the first and last events of each session it scores.token-budget: the first event and eachllm_requestevent.watch --compaction-checkpoint, at startup: the first event and the first read of each file, even when no context is at the--checkpoint-atratio yet, since every checkpoint the watch writes shows their times. It also checks the lastllm_requestevent of the agent and of each subagent whose context is already at that ratio.
audit-readiness does not refuse such a session. Its hash chain integrity
check fails when any event of a session has an unusable timestamp, and names
the session with the reason. export --format eu-ai-act --all refuses that
store. See audit-readiness.
compliance export, share, and export --format otlp, otlp-genai,
temporal, and eu-ai-act also refuse a session whose started_at, or
ended_at when set, is not a Unix time in seconds, with
Error: session started_at must be a Unix time in seconds or the same message
for ended_at. compliance export without a session ID and
export --format eu-ai-act --all name the session, as in
Error: session <session-id> ended_at must be a Unix time in seconds. For
started_at, both refuse first while they list the store, with
Error: cannot read session <session-id>: started_at is not a usable time.
audit-readiness fails its hash chain integrity check for a session whose
ended_at is set but not usable, and names the session with the reason.
export --format temporal checks the session's Temporal trace
context first, so a session without one keeps its Temporal export failed
message. export <session-id> --backend langfuse refuses a session whose
started_at is not a Unix time in seconds with the same started_at line. So
do --scores and --metrics without --backend, which send to Langfuse too.
Langfuse reads no ended_at. The check runs after the credentials check and
before anything is sent. With --since, the store listing refuses such a
session first, as export describes. a2a-tree --format json
refuses a session of the tree whose started_at is not a Unix time in
seconds, with
Error: session <session-id> started_at must be a Unix time in seconds. It
checks the session's a2a_call timestamps first. It reads no ended_at, and
the text tree reads neither.
OTLP carries each time as an unsigned 64-bit count of nanoseconds, so the
latest time it can carry is 2554-07-21T23:34:33.709551615Z. A later time is
still a Unix time in seconds, and the other commands accept it. export
--format otlp, otlp-genai, and temporal refuse an event timestamp they
check, started_at, or ended_at when set, if it is past that time. They run
this check after the checks above, so a session those refuse keeps its
message. The line looks like this:
Error: session event timestamp is past the latest time OTLP can carry (2554-07-21T23:34:33.709551615Z): event 6 of 25 (tool_call); 5 more events have timestamps past that time
For the session times, the line is Error: session started_at is past the
latest time OTLP can carry (2554-07-21T23:34:33.709551615Z) or the same
message for ended_at. With --include-subagents, export checks every
session in the tree this way, once every session passes the checks above. The
line then names the session, such as Error: session <session-id> ended_at is
past the latest time OTLP can carry (2554-07-21T23:34:33.709551615Z).
a2a-tree --format json refuses a started_at or an a2a_call timestamp
past that time in any session of the tree, once every session passes the
checks above. So an unusable time anywhere in the tree comes first. The line
names the session, such as Error: session <session-id> event timestamp is
past the latest time OTLP can carry (2554-07-21T23:34:33.709551615Z): event 3
of 4 (tool_call). For started_at, the line is
Error: session <session-id> started_at is past the latest time OTLP can carry (2554-07-21T23:34:33.709551615Z).
In one session, a past started_at comes before a past call.
A span ends at its start plus its duration. A duration_ms whose span would
end past that time reads as missing, so the span lasts 1 ms, as it does when
the duration is missing. A session with no ended_at ends its root span at
started_at plus total_duration_ms. A total whose root span would end past
that time reads as missing, so the root span ends at started_at. A 1 ms span
that starts less than 1 ms before that time ends at that time.
In a2a-tree --format json, a call duration_ms whose span would end past
that time reads as missing, so the call span ends at its start, as it does
when the duration is missing. A total_duration_ms whose agent span would end
past that time reads as missing too, so the agent span ends at its start.
export --format otlp, otlp-genai, and temporal also refuse a session
whose meta.json tenant_id the store would refuse. The store strips
whitespace from both ends of a tenant ID. It refuses a value that is not a
string, a string that is only whitespace, or a stripped string that is over
256 characters or holds a control character. The exports run this check last,
so a session the checks above refuse keeps its message. Nothing is written or
sent. The line gives the reason and never the value:
The other reasons are cannot be empty, cannot exceed 256 characters, and
cannot contain control characters. With --include-subagents, export checks
the tenant of every session in the tree once every session passes the checks
above. The line then names the session, such as Error: session <session-id>
tenant_id must be a string. An accepted tenant_id is exported stripped, so
" acme " exports acme. An empty tenant_id exports no tenant attribute.
drift and fingerprint skip a session whose first or last event has an
unusable timestamp, as they skip other sessions they cannot read. baseline
leaves the cost out for a session that agent-strace cost refuses: the session
adds no cost sample to baseline update, and baseline check does not compare
its cost. For an open session, baseline check measures the duration from the
event timestamps it can use, and reports no duration when started_at is not a
Unix time in seconds. dashboard, context-score, team-report, export
--metrics --backend otlp, and eval dataset auto --filter cost-above:N price
a session from its token usage and event sizes, not its timestamps, so they
still show its cost.
watch --stream-otlp leaves out each user_prompt, assistant_response,
tool_call, tool_result, error, llm_request, and llm_response event
whose timestamp is unusable or past the latest time OTLP can carry. It prints
one line per event on stderr, such as [stream] Left one tool_call event out of
the OTLP stream because its timestamp is not a Unix time in seconds. For a
timestamp past that time, the line is [stream] Left one tool_call event out of
the OTLP stream because its timestamp is past the latest time OTLP can carry
(2554-07-21T23:34:33.709551615Z). The lines follow the order of the batch. An
event that also has non-object data gets only this line. The other events of
the batch, and later batches, are still sent.
watch --compaction-checkpoint leaves a live event out of the checkpoint when
its timestamp is unusable and a checkpoint would show it: the first event, the
first read of a file, or the event that triggers a checkpoint. It prints one
line with its other checkpoint lines, such as [watch] Left one file_read event
out of the compaction checkpoint because its timestamp is not a Unix time in
seconds. The watch keeps running and passes the event to its other checks.
With agent-strace server --dashboard, the review, compare, share, and OTLP
actions answer 400 with the same message. The OTLP action checks the events
and session times that export --format otlp checks, including the latest time
OTLP can carry. The others check every event. After its checks, the OTLP action
also refuses a session whose tenant_id the store would refuse, with the same
message.
health and skills read an integer timestamp too large for a float as they
read infinity, and compliance-report reads it as it reads 1e300. Earlier
versions stopped with a traceback.
lint finds compactions without reading a timestamp, so its
post-compaction-regression rule runs on these sessions. Earlier versions
reported Could not run 1 rule(s) and exited 1 when the first event or the
llm_request event of a compaction had a string, null, object, array, or
too-large integer timestamp.
list, inspect, tree, verify, stats, export --format json, ndjson,
or csv, tenant export, and the events API keep working on these sessions.
Those that print a timestamp print it as stored, except that inspect,
export --format json and ndjson, tenant export, and the events API print
one that reads as NaN or infinity as null. postmortem --list, compare
--rerun, cost --breakdown provider, annotate --event, and replay --tree
do not check and work as before.
tree, a2a-tree, budget-report, and curve do not check before they price
a session. When they cannot price it, they count its cost as $0, as earlier
versions did. An unusable timestamp on the first or last event can cause that.
Sessions with mismatched or unreadable events¶
A session directory holds one session. So that one session's or tenant's events are never read as another's, the store refuses to read a session when:
- its
meta.jsonhas asession_idother than the directory name. - an event has a
session_idother than the directory name, including a number such as5. An event with nosession_idbelongs to the session. - an event has a
tenant_idother than thetenant_idinmeta.json. Whenmeta.jsonhas notenant_id, only thetenantcommands refuse an event that has one, as described undertenant.
Most commands that read such a session write one line to stderr and exit 1 before they print, write, send, or open anything. The line names the session by its directory and says which check failed:
The tenant check says event tenant does not match session metadata. A
meta.json that names another session counts as corrupt, so its line
reads:
Error: session c3d4e5f6a7b80003 has a corrupt meta.json: metadata session ID does not match its directory
No line includes the session ID or tenant ID found in the files, event IDs, or data values.
The store also refuses a session when a line of events.ndjson is not an event
it can read. The message gives the position of the first such line, says what
is wrong with it, and counts the other unreadable lines:
Error: cannot read session c3d4e5f6a7b80003: line 5 of events.ndjson is not valid JSON; 2 more lines are unreadable
A line is unreadable when it is not valid UTF-8, is not valid JSON, is JSON but
not an object (for example is an array, not an object), has no event_type,
or has an event_type that agent-strace does not know. A line that nests
objects and arrays more than 128 levels deep, the event object included, is
unreadable too (is nested too deeply), and so is a line with an integer too
long to read. The store never writes such an event: appending one raises an
error and writes nothing. An empty line
is skipped, but a line of spaces between events is not valid JSON. The message
never includes the line, its event_type, or the parser's message. When a
session has both a mismatch and an unreadable line, the message reports the
mismatch.
These commands refuse such a session with this line: a2a-tree, audit,
compliance export, cost, diff, explain, export in every format,
health, inspect, lint, postmortem, replay, share, standup,
stats, timeline, token-budget, tree, and why. Some commands print the
same message their own way:
compare,org-report, andpr-commentprint the message after their own prefix and exit 1.annotateprints it with no prefix and exits 1.reviewandcompactionprint it after their own prefix and exit 2.freeze,regression, andexport --backend langfuseprint the reason after their own prefix, which names the session, and exit 1. For example:Could not freeze session <id>: line 5 of events.ndjson is not valid JSON.setup --verify --liveprintsLive capture verification failed:and a sentence that names the session and gives the reason, and exits 1.cognitive-debtkeepsError: trace input could not be read safely, and thetenantcommands keepcorrupt session in tenant store: <id>.
health, stats, standup, and lint without a session ID read the newest
session, so they refuse when the newest session has a mismatched or unreadable
event. lint --all prints the report of every other session, then one Error:
line for each session it cannot read, and exits 1. stats, standup, and
lint treat a session with
non-object event data the same way.
compliance export without a session ID and export --format eu-ai-act --all
read every session in the store. When the store refuses any of them, even one
outside --since or --until, they print the line for the first such session
by directory name and exit 1 before they print or write anything. So a bulk
export never leaves out a session or reports it as empty. They refuse the same
way when a session's started_at is not a usable time, or when the store holds
a symlink or a directory that is not a complete session. When the trace
directory itself is a symlink, pass the real directory with --trace-dir. To
export the store again, make the checks at the end of this section, then move
the session directory out of the store. For a corrupt meta.json, you can
follow the backfill-meta steps under list instead.
audit-readiness does not refuse. Its hash chain integrity check fails and
names each session or store entry that makes the bulk exports refuse, with the
reason. See audit-readiness.
agent-strace server answers GET /sessions/<id>/events for such a session
with 400 and {"error": "<message>"}. When meta.json names another session,
GET /sessions/<id> answers the same way (see
server.md). For a mismatched or unreadable event,
org-report --endpoint then stops with
org-report failed: collector request failed with HTTP 400 instead of
reporting without the session. With --dashboard, the session's events and its
review, compare, share, and OTLP actions answer 400 with the message. MCP tools
return an error result with it.
list, validate, verify, freshness, and postmortem --list keep working.
verify still checks the hash chain and reports where it breaks. validate
reports the session invalid and names the check that failed.
A session whose meta.json names another session is skipped the way
list describes for a corrupt meta.json. list leaves it out, and
so do health, stats, standup, and lint without a session ID. So does
GET /sessions, so org-report --endpoint does not see it. Commands given its
ID, or a prefix that matches only that session, print the corrupt
meta.json line that list shows. So does a2a-tree for a
sub-session. The bulk exports above refuse the store, and audit-readiness
lists the session.
baseline update, budget-report, curve, dashboard --trend, inflation,
optimize, sample, and team-report go on without the session's events, as
before. dashboard shows the session as not priced. Earlier versions stopped
dashboard with a traceback when a line was not an object or had no
event_type. watch, mcp-scan --watch, and skills skip a line they cannot
parse.
When two IDs differ, do not edit one to match the other. The events may belong
to another session or tenant. Check instead how they got into this directory:
whether the directory was renamed, or copied or restored from another store,
and whether a script or a second agent wrote to it. For a tenant mismatch, check
which tenant each capture ran under (AGENT_STRACE_TENANT_ID). For an
unreadable line, check whether a crash or a full disk cut a write short, or the
file was edited. verify shows whether the events changed after they were
written. When meta.json names another session, make the same checks before
you follow the backfill-meta steps under list.