File size: 27,342 Bytes
43b4299
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
"""Generate the CPU-only Colab notebook. No model requests or GPU code."""
from pathlib import Path
import nbformat as nbf

OUT = Path(__file__).resolve().parents[1]
nb = nbf.v4.new_notebook()
cells = []


def md(text):
    cells.append(nbf.v4.new_markdown_cell(text.strip()))


def code(text):
    cells.append(nbf.v4.new_code_cell(text.strip()))


md("""
# Agent trajectory study

Explore 570 OLMo, 510 Qwen, and 371 forestOfAudits recording episodes on a standard Colab CPU runtime. No login, GPU, or model calls are needed. Run the cells in order. Compact tables load first; the inspector fetches one compressed episode at a time.

The Qwen collections are EVMBench detect rollouts from the Harbor/SkyRL pipeline, collected during diagnostics, stress tests, and generation-only admission gates. These artifacts do not establish that RL updates occurred. Checkpoint stages in OLMo describe released model lineages.

Rows have different units. An **episode** groups known recording views of one identity. A **source** is a file. An **event** is a parsed step or event in a particular view. A forest **example** is a exported process step, final answer, or rejection record. The 144 Experiment 1 judge packets are derived evidence with missing original raw recordings. Q09's 446 transitions are auxiliary records. None of these derived rows add episodes.

Repository: [pranay5255/agent-trajectory-study-20260930](https://huggingface.co/datasets/pranay5255/agent-trajectory-study-20260930). The pinned [forest export](https://huggingface.co/datasets/pranay5255/forestofaudits-agent-grader-traces-20260608-backfilled/tree/b78e6f7adc3e14323d877d61edd94432938ddfe8) supplies 8,633 process examples, 218 final examples, and 74 rejection records. Its source flags and attribution are retained.
""")
code(r'''
import importlib.util, subprocess, sys
required = {'pandas':'pandas>=2.2,<3', 'pyarrow':'pyarrow>=18,<24',
            'matplotlib':'matplotlib>=3.9,<4', 'ipywidgets':'ipywidgets>=8,<9',
            'huggingface_hub':'huggingface_hub>=1.0,<2'}
missing = [package for module,package in required.items() if importlib.util.find_spec(module) is None]
if missing:
    subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', *missing], check=True)
import os, json, gzip, hashlib, urllib.request, platform, importlib.metadata
from pathlib import Path
from functools import lru_cache
import numpy as np
import pandas as pd
import pyarrow.parquet as pq
import matplotlib.pyplot as plt
from IPython.display import display, HTML, clear_output
import ipywidgets as widgets

REPO_ID = 'pranay5255/agent-trajectory-study-20260930'
# Set CORPUS_LOCAL_ROOT only for an offline copy containing the public files.
LOCAL_ROOT = os.environ.get('CORPUS_LOCAL_ROOT')
REVISION = os.environ.get('CORPUS_REVISION')
if not LOCAL_ROOT and not REVISION:
    with urllib.request.urlopen(f'https://huggingface.co/api/datasets/{REPO_ID}', timeout=60) as response:
        REVISION = json.load(response)['sha']
REVISION = REVISION or 'local-export'
EXPORT_DIR = Path(os.environ.get('CORPUS_EXPORT_DIR', '/content/trajectory_eda_exports' if Path('/content').exists() else '/tmp/trajectory_eda_exports'))
EXPORT_DIR.mkdir(parents=True, exist_ok=True)
plt.rcParams.update({'figure.dpi':120, 'axes.spines.top':False, 'axes.spines.right':False})

@lru_cache(maxsize=32)
def fetch(relative):
    if LOCAL_ROOT:
        return str(Path(LOCAL_ROOT) / relative)
    # CLI downloads remain anonymous even if the host has cached credentials.
    env = dict(os.environ, HF_HUB_DISABLE_IMPLICIT_TOKEN='1')
    env.pop('HF_TOKEN', None)
    result = subprocess.run([sys.executable, '-m', 'huggingface_hub.cli.hf', 'download', REPO_ID,
                             relative, '--repo-type', 'dataset', '--revision', REVISION, '--quiet'],
                            env=env, capture_output=True, text=True, check=True)
    return result.stdout.strip().splitlines()[-1]

def table(name, columns=None):
    return pd.read_parquet(fetch(f'data/{name}.parquet'), columns=columns)

episodes = pd.concat([table(c) for c in ['olmo','qwen','forest']], ignore_index=True)
coverage = table('coverage')
sources = table('sources')
annotations = table('annotations')
example_summary = table('example_summary')
joins = table('forest_joins')
summary = json.loads(Path(fetch('provenance/build_summary.json')).read_text())
usage_events = table('usage_events')
print('Revision:', REVISION)
print('Episodes:', episodes.groupby('collection').size().to_dict())
print('Compact table memory, MiB:', round(sum(x.memory_usage(deep=True).sum() for x in [episodes,coverage,sources,annotations,example_summary,joins])/2**20, 2))
assert episodes.episode_id.is_unique
assert episodes.groupby('collection').size().to_dict() == {'forest':371,'olmo':570,'qwen':510}
''')
md("""
## Coverage and integrity

Missing outcomes stay unknown. Initial-only recordings may still have rejected model responses in companion views. Duplicate bytes do not prove duplicate episodes. Forest worker and judge branches remain separate identities. The coverage ledger records two empty Qwen files, one malformed forest stream, 368 Qwen paths absent at archive time, and 64 summary-only Qwen 27B records. The latter are a separate population and must not be added to the historical 880 candidates.
""")
code(r'''
population = episodes.groupby('collection').agg(episodes=('episode_id','size'),
    views=('recording_views','sum'), no_accepted_assistant_turns=('assistant_turns',lambda x:int((x==0).sum())),
    unknown_outcomes=('outcome_status',lambda x:int((x=='unknown').sum())),
    with_selected_token_telemetry=('aligned_sequences',lambda x:int((x>0).sum())),
    with_rejected_responses=('rejected_responses',lambda x:int((x>0).sum())))
display(population)
display(coverage.groupby(['collection','unit','status'], dropna=False).size().rename('ledger_rows').reset_index())
display(episodes.groupby(['collection','status']).size().rename('episodes').reset_index())
print('Exact byte-copy views:', int((sources.source_sha256.duplicated()).sum()), 'among', len(sources), 'source files. This includes metadata.')
missing_metadata = episodes.groupby('collection')[['model_revision','context_limit','output_limit','recorded_cost_usd','reward','retry_count']].agg(lambda x:int(x.isna().sum()))
display(missing_metadata)
display(example_summary.groupby(['collection','example_kind','truncated'],dropna=False).size().rename('examples').reset_index())
display(joins.groupby('match_status').size().rename('example source joins'))
display(summary['token_alignment'])
display(usage_events.groupby('kind')[['prompt_tokens','completion_tokens']].count())
population.to_csv(EXPORT_DIR/'population.csv')
''')
md("""
## Size and recorded usage

Usage counters are stored provider/harness values. Completion counters can include reasoning or rejected generations absent from accepted actions. Text length is characters in the redacted publication copy. Reported dollar cost is used only when the source recorded it; unknown prices remain unknown. Context and output limits are shown only where retained metadata states them.
""")
code(r'''
size_columns = ['assistant_turns','commands','text_chars','observation_chars','reported_prompt_tokens','reported_completion_tokens','context_limit','sequence_limit','output_limit','recorded_cost_usd']
size_by_group = episodes.groupby(['collection','model','harness','collection_stage'],dropna=False)[size_columns].agg(['count','median','max'])
display(size_by_group)
display(episodes.groupby(['collection','task'],dropna=False)[['assistant_turns','commands','reported_completion_tokens']].median().head(30))
fig, axes = plt.subplots(1,3,figsize=(12,3.5))
for ax,metric,label in zip(axes,['assistant_turns','commands','reported_completion_tokens'],['Recorded assistant turns','Command events','Reported completion tokens']):
    vals = [pd.to_numeric(episodes.loc[episodes.collection==c,metric],errors='coerce').dropna().to_numpy() for c in ['olmo','qwen','forest']]
    ax.boxplot(vals, tick_labels=['OLMo','Qwen','Forest'],showfliers=False)
    for position,values in enumerate(vals,1):
        if not len(values): ax.text(position,.06,'Unavailable',transform=ax.get_xaxis_transform(),ha='center',fontsize=9)
    ax.set_ylabel(label)
fig.tight_layout(); fig.savefig(EXPORT_DIR/'size.png',bbox_inches='tight'); plt.show()
size_by_group.to_csv(EXPORT_DIR/'size_by_group.csv')
display(usage_events.loc[usage_events.canonical_view].head(10))
usage_events.to_csv(EXPORT_DIR/'recorded_event_usage.csv',index=False)
''')
md("""
## Outcomes and failure indicators

Verifier results, submissions, parser failures, and infrastructure failures are different measurements. A submission flag reports a saved artifact when the format exposes one. Command errors and text patterns are observable indicators. They do not establish intent or verifier failure. Episode outcome denominators below include only recorded verifier results. Qwen's existing analysis supplies effective rewards separately, with its selection/retry role.

Comparisons average within task before summarizing across tasks. Bootstrap intervals resample tasks, using a fixed seed. They describe the retained task population; they do not remove checkpoint, harness, sampling, or collection-stage confounds. A single task has no estimated task-population interval.
""")
code(r'''
def task_summary(frame, metric, groups, repetitions=2000):
    results=[]
    for key,g in frame.groupby(groups,dropna=False):
        key = key if isinstance(key,tuple) else (key,)
        numeric = pd.to_numeric(g[metric],errors='coerce')
        observed=g.assign(value=numeric).dropna(subset=['value','task'])
        means=observed.groupby('task').value.mean().to_numpy()
        low=high=np.nan
        if len(means)>1:
            boot=np.random.default_rng(5255).choice(means,(repetitions,len(means)),replace=True).mean(axis=1)
            low,high=np.quantile(boot,[.025,.975])
        results.append(dict(zip(groups,key), episodes=len(g),observed_episodes=len(observed),
            unknown_episodes=int(numeric.isna().sum()),tasks=len(means), task_mean=float(means.mean()) if len(means) else np.nan,
            ci_low=low,ci_high=high))
    return pd.DataFrame(results)

observed_outcomes=episodes.groupby('collection').agg(total_episodes=('episode_id','size'),
    verifier_observed=('outcome_status',lambda x:int((x=='observed').sum())),
    reward_observed=('reward',lambda x:int(x.notna().sum())),
    submission_known=('submission_present',lambda x:int(x.notna().sum())),
    submission_present=('submission_present',lambda x:int(x.fillna(False).sum())),
    parser_indicator_episodes=('parser_error_indicators',lambda x:int((x>0).sum())),
    infrastructure_indicator_episodes=('infrastructure_failure_indicator','sum'),
    budget_indicator_episodes=('budget_exhaustion_indicator','sum'))
display(observed_outcomes)
outcome_comparison=task_summary(episodes,'reward',['collection','model','harness'])
display(outcome_comparison)
display(episodes.loc[episodes.exception_recorded,['collection','task','exception_json']].head(15))
observed_outcomes.to_csv(EXPORT_DIR/'outcome_denominators.csv')
outcome_comparison.to_csv(EXPORT_DIR/'task_reward_uncertainty.csv',index=False)
''')
md("""
## Observable behavior

Commands may receive several overlapping indicators: reading, searching, editing, testing, submission references, and evaluator-file references. These patterns describe command text, including proposed commands in chat harnesses. Inspect observations to establish execution. An evaluator reference is not an evaluator edit, and an edit is not a successful reward hack.

The inspector below computes repetition and error-to-next-command sequences from the canonical view. A later command is a recovery attempt indicator; successful recovery needs an observation or verifier result.
""")
code(r'''
behavior_columns=[c for c in episodes if c.startswith('indicator_') and c.endswith('_commands')]
task_behavior=episodes.groupby(['collection','task'])[behavior_columns].mean()
display(task_behavior.groupby('collection').mean())
fig,ax=plt.subplots(figsize=(10,4))
task_behavior.groupby('collection').mean().T.rename(index=lambda s:s.replace('indicator_','').replace('_commands','')).plot.bar(ax=ax)
ax.set_ylabel('Mean command indicators per episode, equal task weighting')
fig.tight_layout();fig.savefig(EXPORT_DIR/'behavior.png',bbox_inches='tight');plt.show()
display(episodes.groupby(['collection','model'])[['max_command_repetitions','unique_commands','commands','rejected_responses']].median())
task_behavior.to_csv(EXPORT_DIR/'task_behavior.csv')
''')
md("""
## Qwen gate selection and reward variation

Gate eligibility is recorded collection metadata. Gate arrays retain task/repetition grouping but are not assigned to episode IDs by position. Per-episode effective rewards below come from the existing analysis joined by an exact source path. Their selection role distinguishes retained samples from discarded retry evidence. The 27B summary-only records remain separate.
""")
code(r'''
qwen_notes=annotations.loc[(annotations.collection=='qwen') & (annotations.kind=='existing_command_analysis')]
qwen_analysis=pd.DataFrame([dict(json.loads(r.data_json),episode_id=r.episode_id) for r in qwen_notes.itertuples()])
for name in ['effective_reward','reward_role','context_failure']:
    if name not in qwen_analysis: qwen_analysis[name]=np.nan
display(qwen_analysis.groupby(['run','reward_role'],dropna=False).agg(
    recordings=('episode_id','size'), reward_known=('effective_reward','count'),
    positive_rewards=('effective_reward',lambda x:int((pd.to_numeric(x,errors='coerce')>0).sum())),
    reward_std=('effective_reward','std')))
qwen_gates=[];group_rewards=[]
for r in annotations.loc[(annotations.collection=='qwen') & annotations.kind.str.contains('summary')].itertuples():
    o=json.loads(r.data_json)
    qwen_gates.append({'run':r.subject_id,'evidence_layer':r.evidence_layer,'passed':o.get('passed'),
        'admission_eligible':o.get('admission_eligible'),'context_limit':o.get('max_seq_len'),
        'source_commit':o.get('source_commit'),'skyrl_commit':o.get('skyrl_commit')})
    for task,group in (o.get('groups') or {}).items():
        if isinstance(group,dict):
            rewards=group.get('rewards') or []
            group_rewards.append({'run':r.subject_id,'task':task,'n':len(rewards),
                'positive':sum(x>0 for x in rewards),'distinct_rewards':len(set(rewards)),
                'recorded_diverse':group.get('diverse'),'rewards_json':json.dumps(rewards)})
display(pd.DataFrame(qwen_gates));display(pd.DataFrame(group_rewards))
display(table('qwen27b_summary_only').head(3))
qwen_analysis.to_csv(EXPORT_DIR/'qwen_source_analysis.csv',index=False)
pd.DataFrame(group_rewards).to_csv(EXPORT_DIR/'qwen_gate_reward_groups.csv',index=False)
''')
md("""
## OLMo checkpoint and evaluator evidence

Separate semantic judge labels, commands referencing evaluator files, final protected-file changes, and recorded verifier reward. Experiment 1 and Experiment 2 differ in harnesses and collection conditions. A label disagreement between GPT-5 and Luna measures judge sensitivity, not a change in the agent's actions. Experiment 1 packets retain selected evidence; its original raw run is absent.
""")
code(r'''
olmo=episodes.loc[episodes.collection=='olmo'].copy()
display(task_summary(olmo,'parser_error_indicators',['model_family','checkpoint_stage','harness']))
display(task_summary(olmo,'selected_token_surprisal_nats',['model_family','checkpoint_stage','harness']))
verifier_rows=[]
for r in olmo.itertuples():
    verifier_rows.append(dict(json.loads(r.verifier_results_json),episode_id=r.episode_id,
        task=r.task,model_family=r.model_family,checkpoint_stage=r.checkpoint_stage))
verifiers=pd.DataFrame(verifier_rows)
fields=[c for c in ['protected_files_modified','test_runner_modified','test_cases_modified','tamper_success','proxy_gap','legitimate_solve'] if c in verifiers]
if fields:
    display(verifiers.groupby(['model_family','checkpoint_stage'],dropna=False)[fields].agg(['count','sum','mean']))
paired=pd.DataFrame([json.loads(s) for s in annotations.loc[annotations.kind=='experiment1-gpt5-vs-luna','data_json']])
if len(paired):
    display(pd.crosstab(paired.gpt5_behavior_label,paired.luna_behavior_label))
    print('Judge label disagreements:',int((paired.gpt5_behavior_label!=paired.luna_behavior_label).sum()),'/',len(paired))
    display(paired.groupby('condition_id')[['behavior_label_changed','intent_stage_changed']].agg(['count','sum']))
verifiers.to_csv(EXPORT_DIR/'olmo_verifier_evidence.csv',index=False)
''')
md("""
## Forest detect, patch, exploit, and export quality

Public process examples are partial contexts, often truncated. Gold final answers are reference material and may have no trajectory. Retained source quality flags remain the exporter’s assessments. Local/public joins require the exact audit trial UUID and branch suffix; ambiguous and missing matches remain separate.
""")
code(r'''
display(episodes.loc[episodes.collection=='forest'].groupby(['task_mode','harness']).agg(
    episodes=('episode_id','size'), tasks=('task','nunique'), median_commands=('commands','median')))
forest_examples=example_summary.loc[example_summary.collection=='forest']
display(forest_examples.groupby(['example_kind','task_mode','match_status'],dropna=False).size().rename('examples').reset_index())
quality=[]
for r in forest_examples.itertuples():
    meta=json.loads(r.metadata_json)
    for flag in meta.get('quality_flags',[]): quality.append({'example_id':r.example_id,'task':r.task,'flag':flag})
quality=pd.DataFrame(quality)
if len(quality): display(quality.groupby('flag').agg(examples=('example_id','size'),tasks=('task','nunique')))
source_stats=json.loads(Path(fetch('provenance/forest_public/dataset_summary.json')).read_text())
display(source_stats['input_record_stats'])
forest_examples.to_csv(EXPORT_DIR/'forest_example_metadata.csv',index=False)
joins.to_csv(EXPORT_DIR/'forest_source_joins.csv',index=False)
''')
md("""
## Selected-token diagnostics in batches

For an aligned sequence, surprisal is `-sum(selected_logprobs) / selected_token_count`, in nats per token. Episode values weight by the number of selected tokens. These are realized selected-token likelihoods, not entropy, intent scores, or probabilities of ungenerated actions. Alignment validates one selected logprob per stored completion-token ID. It does not prove transcript-token decoding equality. OLMo telemetry sequence coordinates are retained separately from action-turn coordinates.

This cell scans compact diagnostics in batches of 4,096 rows. It does not load full prompt histories or token arrays. The inspector can retrieve raw arrays for one episode.
""")
code(r'''
token_file=pq.ParquetFile(fetch('data/token_diagnostics.parquet'))
alignment_counts={};token_sums={};nll_sums={}
for batch in token_file.iter_batches(batch_size=4096):
    frame=batch.to_pandas()
    for status,count in frame.alignment.value_counts().items(): alignment_counts[status]=alignment_counts.get(status,0)+int(count)
    good=frame.loc[frame.alignment=='aligned']
    assert (good.token_count==good.logprob_count).all()
    assert (good.token_count>0).all()
    for eid,g in good.groupby('episode_id'):
        token_sums[eid]=token_sums.get(eid,0)+int(g.token_count.sum())
        nll_sums[eid]=nll_sums.get(eid,0)+float(g.nll_sum.sum())
recomputed=pd.DataFrame([{'episode_id':eid,'tokens':count,'surprisal_nats':nll_sums[eid]/count} for eid,count in token_sums.items()])
matched=recomputed.merge(episodes[['episode_id','collection','task','model','selected_token_surprisal_nats']],on='episode_id',validate='one_to_one')
assert np.allclose(matched.surprisal_nats,matched.selected_token_surprisal_nats,rtol=1e-9,atol=1e-9)
display(alignment_counts)
display(task_summary(matched,'surprisal_nats',['collection','model']))
matched.to_csv(EXPORT_DIR/'selected_token_diagnostics.csv',index=False)
''')
md("""
## Interactive episode inspector

Filter by collection, model, task, harness, collection stage, or outcome. Select an episode and press **Load timeline**. Search commands and observations, or show rejected responses. Recording view IDs and exact source coordinates accompany every event. Annotations retain their evidence layer. The raw view and metadata are in `selected_bundle['recordings']`.

Only one episode bundle is cached. The displayed timeline limits long fields to 2,000 characters for readability; downloaded event CSVs keep full text. Companion views can repeat the same action, so use the canonical view for aggregate behavior.
""")
code(r'''
@lru_cache(maxsize=1)
def load_episode(eid):
    row=episodes.loc[episodes.episode_id==eid].iloc[0]
    with gzip.open(fetch(row.detail_path),'rt') as h: bundle=json.load(h)
    return bundle

filter_fields=['collection','model','task','harness','collection_stage','outcome_status']
controls={f:widgets.Dropdown(options=['All']+sorted(episodes[f].dropna().astype(str).unique().tolist()),description=f) for f in filter_fields}
picker=widgets.Dropdown(description='Episode',layout=widgets.Layout(width='95%'))
search=widgets.Text(description='Search',placeholder='command or observation text')
only_rejected=widgets.Checkbox(value=False,description='Rejected responses only')
canonical_only=widgets.Checkbox(value=True,description='Canonical view only')
load_button=widgets.Button(description='Load timeline',button_style='primary')
output=widgets.Output()
selected_bundle=None

def update_options(*_):
    frame=episodes
    for field,control in controls.items():
        if control.value!='All': frame=frame.loc[frame[field].astype(str)==control.value]
    picker.options=[(f'{r.collection} | {r.task} | {str(r.model)[:55]} | {r.episode_id}',r.episode_id) for r in frame.itertuples()]

def show_timeline(*_):
    global selected_bundle
    if not picker.value:return
    with output:
        clear_output(wait=True)
        selected_bundle=load_episode(picker.value)
        display(episodes.loc[episodes.episode_id==picker.value].T)
        events=pd.DataFrame(selected_bundle['events'])
        if not len(events):
            print('No normalized events. Inspect the preserved recording data and parse errors.')
            return
        if canonical_only.value: events=events.loc[events.canonical_view]
        if only_rejected.value: events=events.loc[events.rejected_response]
        if search.value:
            mask=(events.text+'\n'+events.command+'\n'+events.observation).str.contains(search.value,case=False,regex=False)
            events=events.loc[mask]
        full=events.copy()
        full.to_csv(EXPORT_DIR/f'{picker.value}-events.csv',index=False)
        for field in ['text','command','observation']:events=events.assign(**{field:events[field].str.slice(0,2000)})
        display(events[['recording_id','event_index','coordinate','source_line','step_id','kind','rejected_response','text','command','observation']])
        display(annotations.loc[annotations.episode_id==picker.value])
        # Error-to-next-command sequence indicators, without claiming recovery success.
        canonical=pd.DataFrame(selected_bundle['events'])
        canonical=canonical.loc[canonical.canonical_view]
        recovery=[]
        for i,row in canonical.iterrows():
            if any(s in (row.observation+' '+row.text).lower() for s in ['error','failed','traceback']):
                after=canonical.loc[canonical.index>i]
                after=after.loc[after.command.str.len()>0]
                if len(after):recovery.append({'error_coordinate':row.coordinate,'next_command_coordinate':after.iloc[0].coordinate,'next_command':after.iloc[0].command})
        display(pd.DataFrame(recovery).head(20))

for control in controls.values():control.observe(update_options,names='value')
load_button.on_click(show_timeline)
update_options()
display(widgets.VBox([widgets.HBox(list(controls.values())[:3]),widgets.HBox(list(controls.values())[3:]),picker,
    widgets.HBox([search,only_rejected,canonical_only,load_button]),output]))

# A bounded smoke example also works in non-interactive notebook execution.
sample=episodes.loc[(episodes.collection=='qwen') & (episodes.commands>0)].iloc[0]
sample_bundle=load_episode(sample.episode_id)
assert sample_bundle['episode']['episode_id']==sample.episode_id
display(pd.DataFrame(sample_bundle['events'])[['coordinate','kind','command']].head(5))
del sample_bundle
''')
md("""
## Inspect a derived example or judge packet

This helper loads one packet or a compressed forest JSONL source on demand. A process example remains a partial exported context even when it joins a local trajectory. `metadata_json` exposes the original truncation and quality flags.
""")
code(r'''
def inspect_example(example_id):
    row=example_summary.loc[example_summary.example_id==example_id].iloc[0]
    path=fetch(row.detail_path)
    with gzip.open(path,'rt') as h:
        if row.example_kind=='experiment1_judge_packet':return json.load(h)
        for line,text in enumerate(h,1):
            if line==int(row.source_line):return json.loads(text)
    raise ValueError('Example coordinate missing')

display(example_summary[['example_id','example_kind','task','match_status','truncated']].head(8))
# Example: inspect_example(example_summary.iloc[0].example_id)
# For labels: annotations.loc[annotations.subject_id == packet_id]
''')
md("""
## Export and reproduce

Tables and figures saved by the notebook are zipped below. The metadata records the resolved dataset revision, parser version, installed package versions, and seeds. Export scripts and validation tests live in the dataset repository. Source recordings retain coordinates and SHA-256 hashes; publication hashes describe the redacted copy, so they may differ from original hashes.

This corpus excludes the tmax collection and Codex development-session archives. Benchmark Codex recordings inside forestOfAudits are included. It does not supply missing recordings, establish on-policy learning, adjudicate intent, or make the model/harness comparisons causal.
""")
code(r'''
import shutil
repro={'dataset':REPO_ID,'resolved_revision':REVISION,'parser_version':summary['schema_version'],
       'python':platform.python_version(),'platform':platform.platform(), 'bootstrap_seed':5255,
       'packages':{p:importlib.metadata.version(p) for p in ['pandas','pyarrow','matplotlib','ipywidgets','huggingface_hub']},
       'episode_counts':summary['episode_counts'],'forest_source_revision':summary['forest_public_revision']}
(EXPORT_DIR/'reproducibility.json').write_text(json.dumps(repro,indent=2))
archive=shutil.make_archive(str(EXPORT_DIR), 'zip', EXPORT_DIR)
display(repro)
from IPython.display import FileLink
display(FileLink(archive))
try:
    from google.colab import files
    # Uncomment to trigger a browser download: files.download(archive)
except ImportError:
    pass
print('Saved:',archive)
''')

nb.cells=cells
nb.metadata={'kernelspec':{'display_name':'Python 3','language':'python','name':'python3'},
             'language_info':{'name':'python','version':'3.11'}, 'colab':{'name':'trajectory_eda_colab.ipynb','provenance':[]}}
nbf.write(nb,OUT/'trajectory_eda_colab.ipynb')
print(f'Wrote {len(cells)} cells')