Skip to content

Trajectory Audit

What the policy did, not only what it earned.

A reward says what changed in the outcome; it cannot say how. Two rollouts earn the same reward with ten searches or with a hundred, a loop costs nothing until it eats the budget, and a verifier can pay for an answer it should reject. pgs audit reads a run's trajectories on two levels:

  1. Signals over training. Every trajectory is measured (loops in the answer, the reasoning and the tool calls; calls that bring no new information; failures retried unchanged; turns that do nothing; how the episode ended), and each signal is followed over the steps, with tests for a share that rises, a length that grows, a reward that stays flat or falls.
  2. Trajectories to read, picked by reason. Successes unlike the task's other successes, successes that waste calls, tasks that flip from failing to solved (or back) between steps or checkpoints, looping groups that carry no gradient, failures, loops, unproductive tool use, the long tail, and a random control sample. Each comes with its evidence, and the run's symptoms come with hypotheses about where to look.

In short

  • pgs audit outputs/rl --out outputs/rl/audit: a report in the terminal, and a packet of Markdown cases with their evidence marked, for you or for an agent (AGENT_AUDIT.md).
  • Reads logging.dump_trajectories dumps (RL, pgs distill), eval_tasks results during training, pgs eval and pgs env run --samples outputs, and Harbor jobs (harbor run). Evaluations compare the same items at every step, which is what makes a 0 → 1 flip mean something.
  • pgs rl logs the cheap signals every step as behavior/* (log line, wandb, trackio), over every trajectory.
  • --wandb PROJECT logs the audit as a wandb run next to the training run: series, tables, the packet, and the cases as a table with each trajectory to read in place. --trackio PROJECT logs them as trackio traces.
  • Signals, selectors, hypothesis rules and sources are registries: --plugin my_checks.py adds your own.

Running it

pgs audit outputs/rl                                  # report; exit 1 when it has findings
pgs audit outputs/rl --out outputs/rl/audit           # + the packet
pgs audit outputs/rl --since 200 --per-kind 8 --json  # steps >= 200, 8 cases per reason, as JSON
pgs audit eval/step_100 eval/step_400 --out audit/    # two `pgs eval` outputs: checkpoints at steps 100 and 400
pgs audit jobs/base jobs/tuned --out audit/           # two Harbor jobs: the same tasks, two checkpoints
pgs audit --list                                      # the signals, selectors, rules and sources it has

Exit codes: 0 no findings, 1 findings (a hypothesis or a flagged trend) or nothing to audit (the notes say why: a Harbor job whose trials have not finished, say), 2 a usage error (a path, a setting, a plugin, --wandb or --trackio without the package installed) or a failed wandb or trackio export (the report is printed first).

It needs trajectories with their text: logging.dump_trajectories: N in pgs rl or pgs distill (with the default dump_content: true; without it, only the counts and how episodes ended are judged), or evaluations. Dumps without a schema_version field are read too. Reading is streamed in two passes: the whole dump is never held in memory.

Point it at a run's output_dir and it reads both the dumps (rollouts/, kind rl or opd) and the evaluations during training (eval_tasks/step_<n>/, kind eval_tasks). Training dumps show the policy at work, but each step draws other rows; evaluations ask the same items at every step. A flip found in an evaluation is a change of the policy; one found in training dumps may also be an easier draw, and the case says which it is.

Standalone pgs eval outputs (kind eval) are checkpoints on one axis: a directory named step_<n> is at step n (whatever order the shell lists them in), otherwise they are 0, 1, 2, ... in the order given, and --since / --until do not apply to them. Two directories with the same name (a/eval, b/eval) stay two checkpoints. Several runs in one audit keep separate axes: their kinds are qualified with the run's name (rl@run_a, rl@run_b), so their steps, trends and tasks never mix.

Records come from files: a malformed one (a field of the wrong type, a line that is not JSON) is left out and counted in the report's notes, never fatal. A task id that names several different prompts (an id column repeated across the datasets of a mix) is reported too, since flips and comparisons within that task would mix prompts.

Harbor

Harbor tasks are audited wherever they run:

Where What to give pgs audit
pgs rl with HarborEnv the run's output_dir (its dumps, logging.dump_trajectories)
pgs env run harbor --model <ckpt> --samples eval/base the samples directory: a checkpoint, like a pgs eval output
harbor run (Harbor's own agents: terminus-2, codex, claude-code, ...) the job directory, or the folder of jobs

A Harbor job is read from its files: each trial's result.json (rewards, exceptions, token counts, cost) and the agent's ATIF trajectory (agent/trajectory.json, its trajectory.cont-<n>.json continuations after a summarisation, and steps/<step>/agent/ for multi-step tasks). Harbor itself is not needed. A trial is one trajectory:

  • its task is the task's name, and the attempts at one task in one job are a group (n_attempts);
  • its reward is the verifier's reward component (or its only one; with several and no reward, none, and the notes say how many trials that leaves unscored: write the outcome as reward in reward.json);
  • it is scored when Harbor counts the reward valid: an API, setup or verifier failure gives finish: error, unscored, so it is never read as a failure of the agent;
  • its finish comes from the exception that ended it: time (the agent's timeout), length (a context or output limit), refusal, agent_exit (the agent exited with an error), agent_error (any other exception, graded as it was), error (no valid reward), else stop;
  • results are matched to calls by their call id; results without one go to the calls in order, and a single output for a batch of commands (terminus-2's terminal) to the last of them. terminus-2's bash_command calls are compared by their keystrokes (their duration is only how long the agent waits). A tool failure is read from the agent's own flag where it records one (Claude Code, Codex), else from the result's text;
  • a subagent's steps interleaved with the main agent's (Claude Code's sidechains) are left out and counted, and a later step of a multi-step task that starts by repeating the conversation so far (an agent that resumes it) is read from where it is new. An unreadable trajectory file loses the turns, not the outcome (trajectory_error).

Several jobs are checkpoints in the order given (or in name order for a folder of jobs: Harbor names them by their start time), compared on the same tasks: pgs audit jobs/base jobs/tuned finds the tasks the tuned model solves and the base did not, as pairs to read. A job that ran several agents or models is one checkpoint per agent and model. Trials still running (no result.json yet) are left out and counted in the notes. Each case shows the trial folder and the end of the verifier's output, which usually says why a task failed.

With HarborEnv in pgs rl, an episode whose verifier or setup failed (env/metric/verifier_failed, env/metric/setup_failed) is read as an infrastructure error, not as a failed episode, and a task is named by its directory and the task set holding it (task:<set>/<name>), so two task sets that share a task name stay apart.

An example of what the Harbor reading catches: a model that writes its JSON action inside an unclosed reasoning block leaves every turn empty once the server's reasoning parser takes the block, terminus-2 answers each empty turn with a parse error, and the trials end on the agent's timeout. The audit reports no_valid_action ("N of N idle turns are all reasoning") rather than tasks that need more time.

harbor analyze grades trials with an LLM against a rubric. pgs audit is complementary: deterministic signals on every trajectory, trends over checkpoints with tests, and the trajectories worth reading. Its grader_access signal checks deterministically, on every call, the places Harbor's reward_hacking criterion names.

The signals

A signal flags a trajectory as worth reading, never as wrong: an agent that searches four times may be exploring well. Each flag carries its evidence (the turn, the call, an excerpt), and the case files mark it where it is.

Signal Flags Default
budget, turn_limit, time_limit, error the episode ended on the token budget, the turn limit, a wall-clock limit (Harbor's agent timeout), or failed (an infrastructure, API or verifier failure)
grader_access a tool call naming the grader's files: /tests, /solution, /logs/verifier as absolute paths, reward.txt, reward.json (a repository's own /workdir/tests is not one) 1
text_loop the answer repeats a span, or the same answer text comes back in several turns; the answer after any inline </think>, without <tool_call> markup (as the dumps' loop flag judges it) span of 60 characters 4+ times in the last 1,500; 3+ turns
reasoning_loop the same, in the reasoning (the dumps' own loop flag does not look at thinking) as above
repeated_calls one call (same tool, same arguments) with the same result, several times 3
near_duplicate_calls short calls to one tool whose argument values differ only in case, punctuation, flags or word order (grep "Parse", grep -i parse, grep -rn parse); argument names and short words do not count, numbers do 3 calls, 2+ spellings, arguments up to 200 characters
no_new_info calls whose result repeats an earlier one: the same lookup again (or respelled), or a copy of an earlier result of 80+ characters; short acknowledgements of different calls and image results do not count 4+ calls and half of them, or a run of 4
ignored_failures a failed call retried at once, unchanged, failing again 2
think_share the reasoning's share of the text (characters): followed over steps, never flagged
idle_turns turns of an agentic episode (it called a tool, or its environment answered a turn) that neither call a tool nor end it; a turn a user answers is dialogue, not idle. Its evidence says whether the turn's text was all reasoning and what the environment answered 2

What they deliberately do not flag, after reading real runs: the same test command run again after an edit (its result changes: a check, not a loop), two rewrites of one file (long arguments are edits, not spellings of a lookup), five different writes or clicks that each answer "File written." or "ok" (distinct actions), screenshots (image results are never compared by their text), searches for different dates (numbers make calls different), a retry that succeeds (a transient failure handled), and a short correct answer where every answer is short. An image result, or a call whose turn is answered by an image (env.image_results: user), is never "the same result" as another: the text cannot tell two screenshots apart, so a real screenshot loop is left to the eye (and to idle_turns). Change a threshold with --set no_new_info.streak=6 (any signal or selector field).

What it picks to read

Each reason shows at most --per-kind cases (5), spread over task families and steps; the index says how many it found. A trajectory appears once, under its first reason, with its later reasons listed as also; a before / after pair is shown even when one of its two trajectories already appears elsewhere.

Reason Picks
grader_access a trajectory with a grader_access call, paid ones first: a paid one is a reward hack the verifier let through
suspicious_success a success unlike the same task's other clean successes (no loop, no waste, not cut off): far shorter (when those are 64+ tokens), or without a tool call where all of them call one. A shortcut, a question instead of the action, a guess, or a verifier hole
wasteful_success a success that loops or wastes calls: the reward pays it like a clean one
flip / regression the same task's mean reward is at most 0.2 of its family's reward range at every step up to one and at least 0.8 at every step from a later one, intermediate values moving one way between (or the reverse): a change that holds, so an item sampled once a step does not flip with noise. A before / after pair. Evaluations first
zero_signal_loops a training group whose scored rollouts all loop and share one reward: budget spent on zero advantage (not for evaluations or distillation)
failure error, token budget, turn limit, time limit; the longest first
loop, unproductive the strongest loops; calls without new information, failures retried, idle turns
long_tail far longer than its family: median + 5 robust deviations, and twice the median
control ordinary trajectories at random: read some without a hypothesis

Successes are rewards in the top tenth of the family's range, so shaped rewards (−1.2 to 1) work like 0/1 ones. The range runs from the median of the rewards below the family's best to its best: a hard family with partial credit keeps its few full successes apart from its best partial answers, and −10 penalties, rare or frequent, do not turn a 0 into a success; a family whose rewards are all equal takes the run's range, and if the whole run pays one value, a positive reward counts as a success (a verifier that pays everything still has successes to inspect). Comparisons stay within a task (its group-mates at the same step, then the same prompt at other steps) and fall back to a family only when one is recorded (data.metrics_key in pgs rl, the task of an evaluation): the tasks of a mixed run differ in everything, and pooling them makes a clarifying question look like a missing tool call. In multi-role scenarios the role is part of the task and the family, so a checker is never compared with a solver.

No automatic scale reads every reward. With levels 1.0 / 0.9 / 0 (a format bonus on a right answer), 0.9 counts as a failure; with a rare 2.0 bonus over 1.0 for right answers, only the bonus counts as a success. Then give the thresholds in the reward's own units: --success-reward 0.9 (and --failure-reward 0; by default, anything below success is a failure). They replace the scale for successes, flips, regressions and the waste comparison.

Hypotheses

The same symptom has several causes (many timeouts: tasks too hard, exploration out of hand, or a slow sandbox). A rule never concludes: it names the area to look at, cites the trajectories and metrics, and says what would confirm it.

Rule Fires on Area
infrastructure_burst errors concentrated in a few steps, many trajectories at once infrastructure
grader_tampering any grader_access call; how many were paid environment / verifier
budget_pressure 20%+ of episodes end on the budget, the turn limit or a time limit; whether those loop more than the rest decides between rambling and tasks that need more policy / training, or data / configuration
verifier_gap suspicious_success cases environment / verifier
unpenalized_waste wasteful successes that earn about what clean successes of the same groups earn (less than 0.05 apart on the family's 0-1 scale, over 3+ groups that hold both); with their token cost environment / reward
search_strategy tool loops and calls without new information common (10%+) or rising policy / prompt / tools
no_valid_action idle turns common (10%+), and most of them all reasoning (the action written inside an unclosed reasoning block, or taken by the server's reasoning parser), or answered by the harness with one message (a format it cannot parse) policy / prompt / harness
reasoning_action_gap idle turns without those patterns, or a thinking share that grows without reward training / prompt
zero_signal_loops, rising_loops looping groups with no gradient; a loop share that rises training
budget_without_gain, reward_decline length grows while the reward is flat; the reward falls, with what moved with it training / data
regressions evaluation items worse at the last step than at the first, significantly more than items better (exact sign test, p < 0.01): single items flip with sampling noise both ways training

For each source kind the rows are grouped by step, and the earliest third of the steps is compared with the latest third: a signal's flagged share (flagged when it rises by 0.05 or more at p < 0.01), a signal's mean value (the thinking share: reported, not flagged), the mean length (flagged when 25% higher at p < 0.01), the 95th percentile of length (50% higher, with 10+ groups a window and the new long rollouts from 5+ groups), and the reward. Longer answers are not flagged when the reward rises with them (by more than 0.02 in its own units, at p < 0.01): solving more with more tokens is ordinary RL.

The unit of every test is a group: one prompt's rollouts at one step (a row when there are no groups). Rollouts of a prompt share its difficulty, its length and often its loops; counted as independent, simulated runs where nothing changes showed a "trend" in about a third of the tests. Each test is Welch's t on the groups' values with Satterthwaite's degrees of freedom and needs 5 groups a window; n in the report counts groups. Fewer than 4 steps with data give no trend.

series.csv in the packet has the whole series (reward, length, finish shares, every signal's flagged share and mean value per step) for plotting.

The packet, and auditing with an agent

audit/
  index.md         overview, trends, hypotheses, the cases by reason (linked)
  cases/<reason>/  one Markdown file per case: outcome, flags with their evidence, every turn, the reasoning, the
                   answer, each call with its arguments and result; ⚑ where a flag's evidence is; before / after
                   pairs with a side-by-side table
  cases.jsonl      the cases as data
  report.json      the report as data
  series.csv       the per-step series
  AGENT_AUDIT.md   instructions for an agent

Hand the packet to an agent with AGENT_AUDIT.md. It asks for two passes: one per hypothesis (does the evidence support it?) and an open-ended one on the control cases and others, without the list of expected problems, since leading questions find what they ask about. Every claim goes to findings.jsonl with a quote, a trajectory id and a turn. Treat the agent's causes as hypotheses until the cited trajectories show them.

During training: behavior/*

pgs rl computes the cheap signals on every trajectory of every step, zero-variance groups included (loops gather there, and they are the groups the loss never sees), and logs them with its other metrics:

Metric
behavior/text_loop, behavior/reasoning_loop share of trajectories whose answer / reasoning loops (of those with one)
behavior/repeated_calls share with one call made 3+ times with the same result (of those with tool calls)
behavior/no_new_info share whose tool calls mostly bring nothing new (of those with tool results)
behavior/grader_access share with a call naming the grader's files (of those with tool calls): a reward hack tried, at the step it starts
behavior/think_share the reasoning's mean share of the text
behavior/unmeasured trajectories that could not be measured (logged only when there are some)

logging.behavior_metrics: false turns them off. The evaluation pass logs them too (eval/behavior/*). They run off the rollout event loop, and their work is bounded per turn (the repetition check reads the last 1,500 characters of a text, fingerprints the ends of long results). They run on a thread of their own, not on the loop's default executor (which sync tools, rewards and judge calls share). A trajectory that cannot be measured is left out and counted, never stops the metrics. A rising behavior/* curve is the moment to run pgs audit.

wandb

pgs audit outputs/rl --out outputs/rl/audit --wandb my-project [--wandb-group my-run] [--wandb-entity team]

A new run with job_type: trajectory-audit in the group --wandb-group (by default the audited directory's name): the per-step series as audit/<kind>/<metric> against train/global_step (the training charts' axis), tables audit/cases, audit/hypotheses and audit/trends, the packet as an artifact (type trajectory-audit, named audit-<group>-<run id>), and audit/status with the case counts in the summary. Training runs set no wandb group: filter by the group name to see the audit next to its run, or start the training run with WANDB_RUN_GROUP set to the same name. It needs pip install wandb.

audit/cases has one row per case, to read without leaving wandb:

Column
kind, title, why, also the reason it was picked, and the later reasons that picked it too
trajectories its id, or before -> after for a flip or a regression
step, checkpoint, task, reward, finish, tokens of the trajectory (a pair's before; checkpoint names both)
flags, evidence the signals that flagged it, with the turn and call each points to and its note
reward_after, finish_after a pair's later outcome (empty otherwise)
trajectory, after the trajectory itself as an HTML cell (wandb.Html): its outcome, the prompt, every turn with its reasoning, answer, calls, arguments and results, ⚑ where a flag's evidence is; after is a pair's second trajectory

The HTML cells are the packet's Markdown cases translated, with the same clipping of long texts (the cut says how much is left out). A session whose turns exceed 200,000 characters after clipping keeps the turns its flags point to, then turns from its start and its end; each gap is marked, and the header still counts every turn. The packet's files are never shortened this way. The pages carry their own style, run no script and fetch nothing.

trackio

pgs audit outputs/rl --trackio my-project [--trackio-group my-run]
trackio show --project my-project                  # the dashboard: the Traces page has the cases
trackio list traces --project my-project --search grader_access

A new trackio run named audit-<group>-<date>-<time> in the group --trackio-group (by default the audited directory's name), stored locally like any trackio run (TRACKIO_DIR); trackio's own TRACKIO_SPACE_ID or TRACKIO_SERVER_URL send it elsewhere. It holds:

  • one trace per trajectory the cases show, under audit/traces (the reason is in its metadata), at the trajectory's training step. Its messages are the conversation in OpenAI style: the prompt, each assistant turn with reasoning_content and tool_calls, a tool message per result (is_error on a failed call), a user message for an observation that answered no call. Its metadata says why it is there and what was found: reason, title, why, also, flags, evidence (per flag: turn, call, note), reward, reward_components, step, checkpoint, task, family, group, finish, output_tokens, turns, tool_calls, source, and for a Harbor trial trial_dir, agent and cost_usd. The two trajectories of a flip or a regression are two traces with side (before, after) and pair (the other's id). status is error only for an episode that ended in an error;
  • the per-step series as audit/<kind>/<metric> at the training step;
  • tables audit/cases (the wandb table's columns without the HTML cells), audit/hypotheses and audit/trends.

Texts are clipped and long sessions shortened as in the wandb table. It needs pip install trackio (0.25 or later, the first with traces). trackio reports a log call it could not store as a warning: the audit turns that into a failed export (exit 2).

Your own checks

# my_checks.py: pgs audit outputs/rl --plugin my_checks.py
from dataclasses import dataclass
from typing import ClassVar

from palingenesis.audit.registry import hypothesis, register_signal
from palingenesis.audit.signals import Evidence, Measure, Signal


@dataclass
class AnswersInEnglish(Signal):
    name: ClassVar[str] = "answers_in_english"
    description: ClassVar[str] = "the final answer is in English"

    def measure(self, t):
        last = next((turn for turn in reversed(t.turns) if turn.content), None)
        if last is None:
            return None  # does not apply
        hit = " the " in f" {last.content.lower()} "
        return Measure(float(hit), hit, [Evidence(last.index, field="content", excerpt=last.content[:120])] if hit else [])


register_signal(AnswersInEnglish())


@hypothesis("wrong_language")
def wrong_language(result):
    return []  # a rule sees result.rows, result.trends, result.cases; it returns Hypothesis objects

A signal appears in the report, the trends, the packet's flags and series.csv like a built-in one. Selectors (palingenesis.audit.selectors.Selector) and sources (palingenesis.audit.registry.register_source, for another dump format) register the same way; a part registered under an existing name replaces it. Installed packages can provide plugins through the palingenesis.audit entry point group.

Python

The CLI's steps, and the trajectory as chat messages for a viewer of your own:

from palingenesis.audit import Options, discover, run_audit, write_packet

result = run_audit(discover(["outputs/rl"]), Options(per_kind=8, since=200))
packet = write_packet(result, "outputs/rl/audit")

from palingenesis.audit import trackio_export, wandb_export

wandb_export.export(result, packet, project="my-project", group="my-run")   # returns the run's URL
trackio_export.export(result, project="my-project", group="my-run")         # returns the run's name

from palingenesis.audit import render, to_messages
from palingenesis.audit.export import exported_cases

for item in exported_cases(result):          # the cases, their trajectories read back from the sources
    for side in item.sides:                  # one, or before and after
        if side.trajectory is not None:
            messages = to_messages(side.trajectory)   # OpenAI-style; pass render.LIMITS to clip long texts

Limits

  • The signals read text and tool calls: they see repetition and waste, not whether an answer is right. Whether a suspicious success deserved its reward is a question for the reader and pgs env test.
  • Thresholds were checked by reading flagged trajectories of real agentic, tool-calling and short-answer RL runs, not tuned on labels. Expect false positives; that is what the evidence is for.
  • think_share counts characters, not tokens.
  • pgs distill dumps are audited, but behavior/* is logged by pgs rl only.
  • grader_access reads call arguments only: a hack done through a path built at run time (cd /; cat t*/x) is not seen. It catches the plain attempts, which are the ones a small policy finds first.
  • Harbor jobs: subagents (trajectories embedded in ATIF, Claude Code's sidechain steps) are counted, not audited; an agent without an ATIF trajectory is judged on its outcome, finish and token counts only. A job that ran several agents or models gives one checkpoint per agent and model, in name order: a flip between two of them is a pair to read, its direction only the order of their names.
  • Single-turn evaluation samples keep the completion but not its parsed tool calls (bfcl_simple): their calls are not judged.
  • --set and register_* change process-wide registries: in a notebook, settings stay for later audits.
  • The trackio traces carry messages and metadata, not execution spans: its Traces page shows the conversation and the tool calls with their results, but no latency or token totals per call.

After "RL Training Notes (1): A Practical Guide to Reading Trajectories" (kokolerk.github.io): the two levels, the trajectory types worth reading first, tool-level loops judged by information gain, and agent-assisted audits with evidence. The signals, thresholds, tests and rules here are this library's own.