-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcodex.rs
More file actions
1733 lines (1648 loc) · 62.3 KB
/
Copy pathcodex.rs
File metadata and controls
1733 lines (1648 loc) · 62.3 KB
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Codex CLI transcript source.
//!
//! Codex appends one JSON object per line to
//! `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl` (sessions archived from the
//! picker move to a flat `~/.codex/archived_sessions/rollout-*.jsonl`). Each
//! line is `{"timestamp": "<iso8601>", "type": "<kind>", "payload": {…}}`. The
//! relevant kinds for conversation text are:
//!
//! * `session_meta` — first line; `payload.cwd`, session `id`. Real rollouts
//! carry no `model` here (only `model_provider`); the active model is on
//! `turn_context` lines and can change mid-session.
//! * `event_msg` with `payload.type == "user_message"` — a real user prompt
//! (`payload.message`).
//! * `event_msg` with `payload.type == "agent_message"` — a real assistant reply
//! (`payload.message`).
//! * `event_msg` with `payload.type == "token_count"` — per-API-call usage; a
//! turn's tool loop emits one per call, so a turn's true cost is the *sum*
//! (see [`CodexTurnUsage`]).
//! * `event_msg` with `payload.type == "thread_goal_updated"` — the structured
//! session goal and its lifecycle (`payload.goal.{objective,status,tokensUsed,
//! timeUsedSeconds,createdAt,updatedAt}`). `TraceDecay` records each state as a
//! compact `goal` row (objective as text, the rest in `metadata_json`) so the
//! session's goal and whether it is still active is searchable. `status` is
//! stored verbatim — real rollouts emit `active`/`paused`, but any future
//! value (e.g. `completed`) is carried through unchanged rather than mapped to
//! a fixed enum. Consecutive events that repeat the same `(objective, status)`
//! within one parse pass are deduped; each genuine transition keeps its row.
//! * `compacted` — Codex context-compression boundary. The rollout stores the
//! replacement history and an encrypted compaction body, so `TraceDecay` records
//! the boundary/provenance as a summary record without claiming plaintext
//! access to Codex's private summary.
//! * `response_item` goal context — Codex replays active thread goals as
//! synthetic user context. `TraceDecay` indexes those as compact goal-context
//! records so LCM can catalog the objective and budget without treating the
//! instruction boilerplate as normal conversation.
//! * subagent rollouts — separate `rollout-*.jsonl` files whose leading
//! `session_meta` has `thread_source == "subagent"` and parent ids in
//! `forked_from_id` / `source.subagent.thread_spawn.parent_thread_id`.
//!
//! `response_item` entries are intentionally skipped except for Codex goal
//! context blocks: they usually carry auto-injected synthetic context and
//! duplicate the `agent_message`/`user_message` turns, so ingesting them would
//! double-count the conversation. Goal context blocks are cataloged as compact
//! `goal_context` rows because real rollouts often record them only in
//! `response_item` form. This append-only JSONL is read with the shared
//! byte-offset machinery and scoped per turn by the latest Codex cwd context.
mod context;
mod events;
use std::io::BufRead;
use std::path::{Path, PathBuf};
use serde_json::Value;
use crate::accounting::parser::parse_timestamp;
use crate::sessions::SessionMessageRecord;
use crate::sessions::shared::{
ProjectMembership, ProjectRootMatcherCache, StoredCursor, append_tool_calls_metadata,
content_storage_text_and_tools, title_from_messages,
};
use crate::sessions::source::{
ParsedTranscript, SessionDraft, TranscriptSource, collect_files_with_ext, stream_new_jsonl,
};
use context::CodexContextState;
const PROVIDER: &str = "codex";
/// `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl` → date dirs add depth.
const MAX_SCAN_DEPTH: u8 = 6;
/// Threshold above which a tool call's arguments / a tool output is flagged as
/// truncated in metadata. Raw tool-call arguments and tool outputs are never
/// embedded in the FTS-searchable message text (they can carry secrets); only
/// byte counts and this truncation flag are recorded. The lossless body already
/// lives in the Codex rollout itself, recoverable via `source_path`/
/// `source_offset`.
const TOOL_EVENT_PREVIEW_BYTES: usize = 2000;
/// Session metadata read from a rollout's leading `session_meta` line.
struct CodexMeta {
cwd: PathBuf,
session_id: String,
model: Option<String>,
git: Option<Value>,
parent_session_id: Option<String>,
is_subagent: bool,
agent_id: Option<String>,
agent_nickname: Option<String>,
agent_role: Option<String>,
thread_source: Option<String>,
}
/// Codex CLI transcript locator + parser.
pub struct CodexSource {
sessions_dir: PathBuf,
archived_sessions_dir: PathBuf,
user_scope: Option<UserCodexScope>,
project_matchers: ProjectRootMatcherCache,
}
struct UserCodexScope {
session_id: Option<String>,
registered_roots: Vec<PathBuf>,
}
impl CodexSource {
/// Source rooted at the real `~/.codex`. Returns `None` when the
/// home directory cannot be resolved.
pub fn new() -> Option<Self> {
let home = crate::sessions::home_dir()?;
Some(Self::with_home(&home))
}
/// Source rooted at `<home>/.codex` (used by tests).
pub fn with_home(home: &Path) -> Self {
let codex_home = home.join(".codex");
Self {
sessions_dir: codex_home.join("sessions"),
archived_sessions_dir: codex_home.join("archived_sessions"),
user_scope: None,
project_matchers: ProjectRootMatcherCache::default(),
}
}
/// Restricts ingestion to sessions that cannot be attributed to a registered project.
#[must_use]
pub fn for_user_scope(
mut self,
session_id: Option<String>,
registered_roots: Vec<PathBuf>,
) -> Self {
self.user_scope = Some(UserCodexScope {
session_id,
registered_roots,
});
self
}
}
impl TranscriptSource for CodexSource {
fn provider(&self) -> &'static str {
PROVIDER
}
fn transcript_paths(&self, _project_root: &Path) -> Vec<PathBuf> {
// Archiving a session moves its rollout out of the dated tree; both
// locations are real transcripts and must be ingested.
let mut paths = collect_files_with_ext(&self.sessions_dir, "jsonl", MAX_SCAN_DEPTH);
paths.extend(collect_files_with_ext(
&self.archived_sessions_dir,
"jsonl",
MAX_SCAN_DEPTH,
));
paths
}
fn parse_new(
&self,
path: &Path,
prev: StoredCursor,
project_root: &Path,
max_new_bytes: Option<u64>,
) -> Option<ParsedTranscript> {
// `session_meta` (line 1) is authoritative for session identity and the
// initial cwd. Later context records can move one rollout between scopes.
let meta = session_meta(path)?;
if self
.user_scope
.as_ref()
.and_then(|scope| scope.session_id.as_deref())
.is_some_and(|session_id| session_id != meta.session_id)
{
return None;
}
let new = stream_new_jsonl(path, prev, max_new_bytes)?;
let mut messages = Vec::new();
let mut turn_usage = CodexTurnUsage::default();
// Collapses identical consecutive goal states within this parse pass:
// `thread_goal_updated` fires on every token/time tick, so only an
// objective- or status-change opens a new `goal` row.
let mut last_goal_key: Option<(String, Option<String>)> = None;
let mut structured = events::CodexStructuredState::new();
let replayed_from_start =
prev.position > 0 && new.lines.first().is_some_and(|line| line.offset == 0);
let mut context_state = if prev.position > 0 && !replayed_from_start {
CodexContextState::scan_prior(path, prev.position, &meta)
} else {
CodexContextState::from_meta(&meta)
};
let project_matcher = self
.user_scope
.is_none()
.then(|| self.project_matchers.get(project_root));
let registered_root_matchers = self
.user_scope
.as_ref()
.map(|scope| {
scope
.registered_roots
.iter()
.map(|root| self.project_matchers.get(root))
.collect::<Vec<_>>()
})
.unwrap_or_default();
let mut last_in_scope_cwd = None;
let mut last_in_scope_git = None;
for line in &new.lines {
let is_context_record = context_state.observe_context_record(&line.value, path, &meta);
let in_scope = if self.user_scope.is_none() {
context_state.cwd.as_deref().map_or(Some(false), |cwd| {
project_matcher
.as_ref()
.map(|matcher| matcher.contains_status(cwd).definitive())
.unwrap_or(Some(false))
})
} else {
context_state.cwd.as_deref().map_or(Some(true), |cwd| {
let mut unknown = false;
for matcher in ®istered_root_matchers {
match matcher.contains_status(cwd) {
ProjectMembership::Match => return Some(false),
ProjectMembership::NoMatch => {}
ProjectMembership::Unknown => unknown = true,
}
}
(!unknown).then_some(true)
})
}?;
if !in_scope {
if compacted_summary_from_line(
&line.value,
&meta,
context_state.model.as_deref(),
path,
line.offset,
context_state.compaction_depth + 1,
)
.is_some()
{
context_state.compaction_depth += 1;
}
continue;
}
last_in_scope_cwd.clone_from(&context_state.cwd);
last_in_scope_git.clone_from(&context_state.git);
// Non-consuming: harvest session-level policy/effort/rate-limit
// summary before the line is routed to its owning handler below.
structured.observe_summary(&line.value);
if is_context_record {
continue;
}
if turn_usage.observe(&line.value) {
continue;
}
if let Some(rows) = structured.event_from_line(
&line.value,
&meta,
context_state.model.as_deref(),
path,
line.offset,
) {
for mut message in rows {
context::annotate_message(
&mut message,
context_state.cwd.as_deref(),
context_state.git.as_ref(),
&self.project_matchers,
);
messages.push(message);
}
continue;
}
if let Some(event) = codex_goal_event_from_line(&line.value) {
let key = event.dedup_key();
if last_goal_key.as_ref() == Some(&key) {
continue;
}
last_goal_key = Some(key);
let mut message = goal_event_message(
&meta,
context_state.model.as_deref(),
path,
line.offset,
timestamp_from_record(&line.value),
&event,
);
context::annotate_message(
&mut message,
context_state.cwd.as_deref(),
context_state.git.as_ref(),
&self.project_matchers,
);
messages.push(message);
continue;
}
if let Some(mut message) = response_item_goal_context_from_line(
&line.value,
&meta,
context_state.model.as_deref(),
path,
line.offset,
) {
context::annotate_message(
&mut message,
context_state.cwd.as_deref(),
context_state.git.as_ref(),
&self.project_matchers,
);
messages.push(message);
continue;
}
if let Some(mut message) = response_item_tool_event_from_line(
&line.value,
&meta,
context_state.model.as_deref(),
path,
line.offset,
) {
context::annotate_message(
&mut message,
context_state.cwd.as_deref(),
context_state.git.as_ref(),
&self.project_matchers,
);
messages.push(message);
continue;
}
if let Some(mut message) = compacted_summary_from_line(
&line.value,
&meta,
context_state.model.as_deref(),
path,
line.offset,
context_state.compaction_depth + 1,
) {
flush_turn_usage(&mut messages, &mut turn_usage);
context_state.compaction_depth += 1;
context::annotate_message(
&mut message,
context_state.cwd.as_deref(),
context_state.git.as_ref(),
&self.project_matchers,
);
messages.push(message);
continue;
}
if let Some(mut message) = goal_context_from_line(
&line.value,
&meta,
context_state.model.as_deref(),
path,
line.offset,
) {
context::annotate_message(
&mut message,
context_state.cwd.as_deref(),
context_state.git.as_ref(),
&self.project_matchers,
);
messages.push(message);
continue;
}
if let Some(mut message) = message_from_line(
&line.value,
&meta,
context_state.model.as_deref(),
path,
line.offset,
) {
// A new user prompt closes the previous turn: attach that
// turn's summed API-call usage to its assistant reply.
if message.role == "user" {
flush_turn_usage(&mut messages, &mut turn_usage);
}
context::annotate_message(
&mut message,
context_state.cwd.as_deref(),
context_state.git.as_ref(),
&self.project_matchers,
);
messages.push(message);
}
}
// The final turn's trailing token_count(s) arrive after its
// agent_message; flush them onto it.
flush_turn_usage(&mut messages, &mut turn_usage);
// Emit any `exec_command` calls whose paired output never arrived in
// this pass so the tool call is not silently dropped.
for mut message in structured.flush_pending(&meta, path) {
context::annotate_message(
&mut message,
last_in_scope_cwd.as_deref(),
last_in_scope_git.as_ref(),
&self.project_matchers,
);
messages.push(message);
}
let project = self.user_scope.as_ref().map_or_else(
|| project_root.to_string_lossy().to_string(),
|_| "user".to_string(),
);
let draft = SessionDraft {
session_id: meta.session_id.clone(),
project_key: project.clone(),
project_path: project,
title: title_from_messages(&messages),
// The summary is session-wide and may include evidence observed
// after Codex changed cwd into a registered project. User scope
// stores only the filtered message rows, never that mixed summary.
metadata_json: context::session_metadata_json(
&meta,
self.user_scope.is_none().then_some(&structured.summary),
&self.project_matchers,
),
parent_session_id: meta.parent_session_id.clone(),
is_subagent: meta.is_subagent,
agent_id: meta.agent_id.clone(),
parent_tool_use_id: None,
};
Some(ParsedTranscript {
draft,
messages,
new_cursor: new.new_cursor,
})
}
}
/// Read the leading `session_meta` line of a rollout for cwd/session-id/model.
fn session_meta(path: &Path) -> Option<CodexMeta> {
let file = std::fs::File::open(path).ok()?;
let reader = std::io::BufReader::new(file);
for line in reader.lines().take(4).map_while(Result::ok) {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let Ok(value) = serde_json::from_str::<Value>(trimmed) else {
continue;
};
if let Some(meta) = session_meta_from_record(&value, path) {
return Some(meta);
}
}
None
}
fn session_meta_from_record(record: &Value, path: &Path) -> Option<CodexMeta> {
if record.get("type").and_then(Value::as_str) != Some("session_meta") {
return None;
}
let payload = record.get("payload").unwrap_or(record);
let cwd = payload
.get("cwd")
.and_then(Value::as_str)
.filter(|cwd| !cwd.is_empty())
.map(PathBuf::from)?;
let session_id = payload
.get("id")
.or_else(|| payload.get("session_id"))
.and_then(Value::as_str)
.filter(|id| !id.is_empty())
.map_or_else(
|| {
path.file_stem()
.and_then(|stem| stem.to_str())
.unwrap_or("unknown")
.to_string()
},
ToString::to_string,
);
// Note: real rollouts have no `model` in session_meta — only
// `model_provider` (e.g. "openai"), which is *not* a model and must
// not be stored as one; `turn_context` lines carry the actual model.
let model = payload
.get("model")
.and_then(Value::as_str)
.map(str::to_string);
let git = payload.get("git").filter(|git| git.is_object()).cloned();
let parent_session_id = string_field(payload, "forked_from_id")
.or_else(|| nested_string_field(payload, "/source/subagent/thread_spawn/parent_thread_id"));
let thread_source = string_field(payload, "thread_source");
let agent_nickname = string_field(payload, "agent_nickname")
.or_else(|| nested_string_field(payload, "/source/subagent/thread_spawn/agent_nickname"));
let agent_role = string_field(payload, "agent_role")
.or_else(|| nested_string_field(payload, "/source/subagent/thread_spawn/agent_role"));
let is_subagent = thread_source.as_deref() == Some("subagent")
|| parent_session_id.is_some()
|| payload.pointer("/source/subagent").is_some();
let agent_id = is_subagent.then(|| {
agent_nickname
.clone()
.or_else(|| agent_role.clone())
.unwrap_or_else(|| session_id.clone())
});
Some(CodexMeta {
cwd,
session_id,
model,
git,
parent_session_id,
is_subagent,
agent_id,
agent_nickname,
agent_role,
thread_source,
})
}
fn string_field(payload: &Value, key: &str) -> Option<String> {
payload
.get(key)
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
.map(str::to_string)
}
fn nested_string_field(payload: &Value, pointer: &str) -> Option<String> {
payload
.pointer(pointer)
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
.map(str::to_string)
}
struct CodexTurnContext {
model: Option<String>,
cwd: Option<PathBuf>,
}
/// Context recorded on a `turn_context` line. Real rollouts use this for the
/// active model and current cwd; both can change mid-session.
fn turn_context_from_record(record: &Value) -> Option<CodexTurnContext> {
if record.get("type").and_then(Value::as_str) != Some("turn_context") {
return None;
}
let payload = record.get("payload").unwrap_or(record);
let model = payload
.get("model")
.and_then(Value::as_str)
.filter(|model| !model.is_empty())
.map(str::to_string);
let cwd = payload
.get("cwd")
.and_then(Value::as_str)
.filter(|cwd| !cwd.is_empty())
.map(PathBuf::from);
Some(CodexTurnContext { model, cwd })
}
/// Map one rollout line to a provider-neutral message, or `None` for non-message
/// events (`response_item`, tool calls, token counts, …).
fn message_from_line(
record: &Value,
meta: &CodexMeta,
model: Option<&str>,
path: &Path,
offset: i64,
) -> Option<SessionMessageRecord> {
if record.get("type").and_then(Value::as_str) != Some("event_msg") {
return None;
}
let payload = record.get("payload")?;
let role = match payload.get("type").and_then(Value::as_str)? {
"user_message" => "user",
"agent_message" => "assistant",
_ => return None,
};
let content = payload.get("message")?;
let (text, tool_names) = content_storage_text_and_tools(content, payload.get("tool_calls"));
if text.trim().is_empty() {
return None;
}
let timestamp = timestamp_from_record(record);
if let Some(goal_context) = codex_goal_context_from_text(&text) {
return Some(goal_context_message(
meta,
model,
path,
offset,
timestamp,
&goal_context,
&message_metadata(payload, Some(&goal_context)),
));
}
Some(SessionMessageRecord {
provider: PROVIDER.to_string(),
message_id: format!("{}:{offset}", meta.session_id),
session_id: meta.session_id.clone(),
role: role.to_string(),
timestamp,
ordinal: offset,
text,
kind: Some("message".to_string()),
model: model.map(str::to_string),
tool_names: (!tool_names.is_empty()).then(|| tool_names.join(",")),
source_path: Some(path.to_string_lossy().to_string()),
source_offset: Some(offset),
metadata_json: serde_json::to_string(&message_metadata(payload, None)).ok(),
})
}
fn response_item_goal_context_from_line(
record: &Value,
meta: &CodexMeta,
model: Option<&str>,
path: &Path,
offset: i64,
) -> Option<SessionMessageRecord> {
if record.get("type").and_then(Value::as_str) != Some("response_item") {
return None;
}
let payload = record.get("payload")?;
if payload.get("type").and_then(Value::as_str) != Some("message") {
return None;
}
let text = collect_response_item_text(payload.get("content").unwrap_or(payload));
let goal_context = codex_goal_context_from_text(&text)?;
let mut metadata = message_metadata(payload, Some(&goal_context));
if let Value::Object(map) = &mut metadata {
map.insert(
"source_event".to_string(),
Value::String("response_item".to_string()),
);
if let Some(role) = payload.get("role").and_then(Value::as_str) {
map.insert("source_role".to_string(), Value::String(role.to_string()));
}
}
Some(goal_context_message(
meta,
model,
path,
offset,
timestamp_from_record(record),
&goal_context,
&metadata,
))
}
fn response_item_tool_event_from_line(
record: &Value,
meta: &CodexMeta,
model: Option<&str>,
path: &Path,
offset: i64,
) -> Option<SessionMessageRecord> {
if record.get("type").and_then(Value::as_str) != Some("response_item") {
return None;
}
let payload = record.get("payload")?;
let response_item_type = payload.get("type").and_then(Value::as_str)?;
// Serialize the output payload once and share it with both helpers below.
let output = payload.get("output").map(compact_response_item_value);
let (role, text, metadata) = match response_item_type {
"function_call" | "custom_tool_call" | "tool_search_call" | "web_search_call" => {
let tool_name = response_item_tool_name(payload, response_item_type);
let text =
response_item_tool_call_text(response_item_type, tool_name.as_deref(), payload);
(
"tool",
text,
response_item_tool_metadata(
response_item_type,
payload,
tool_name,
output.as_deref(),
),
)
}
"function_call_output" | "custom_tool_call_output" => {
let text = response_item_tool_output_text(payload, output.as_deref())?;
(
"tool",
text,
response_item_tool_metadata(response_item_type, payload, None, output.as_deref()),
)
}
"reasoning" => {
let text = response_item_reasoning_summary_text(payload)?;
(
"assistant",
text,
response_item_tool_metadata(response_item_type, payload, None, output.as_deref()),
)
}
_ => return None,
};
if text.trim().is_empty() {
return None;
}
Some(SessionMessageRecord {
provider: PROVIDER.to_string(),
message_id: format!("{}:{offset}", meta.session_id),
session_id: meta.session_id.clone(),
role: role.to_string(),
timestamp: timestamp_from_record(record),
ordinal: offset,
text,
kind: Some(if response_item_type == "reasoning" {
"reasoning".to_string()
} else {
"tool_event".to_string()
}),
model: model.map(str::to_string),
tool_names: response_item_tool_name(payload, response_item_type),
source_path: Some(path.to_string_lossy().to_string()),
source_offset: Some(offset),
metadata_json: serde_json::to_string(&metadata).ok(),
})
}
fn response_item_tool_name(payload: &Value, response_item_type: &str) -> Option<String> {
payload
.get("name")
.and_then(Value::as_str)
.map(str::to_string)
.or_else(|| match response_item_type {
"tool_search_call" => Some("tool_search".to_string()),
"web_search_call" => Some("web_search".to_string()),
_ => None,
})
}
fn response_item_tool_call_text(
response_item_type: &str,
tool_name: Option<&str>,
payload: &Value,
) -> String {
let label = tool_name.unwrap_or(response_item_type);
let mut parts = vec![format!("Codex tool call: {label}")];
if let Some(namespace) = payload.get("namespace").and_then(Value::as_str) {
parts.push(format!("namespace: {namespace}"));
}
if let Some(call_id) = payload.get("call_id").and_then(Value::as_str) {
parts.push(format!("call_id: {call_id}"));
}
// Never embed raw arguments in the FTS-searchable text — they can carry
// secrets (tokens, credentials, private paths). Record only the byte count;
// the lossless arguments remain in the rollout at `source_offset`.
if let Some(arguments_bytes) = response_item_arguments_bytes(payload) {
parts.push(format!("arguments_bytes: {arguments_bytes}"));
}
parts.join("\n")
}
/// Byte length of a tool call's arguments payload (`arguments`/`input`/`action`,
/// whichever is present) after compact serialization. Returns `None` when the
/// item carries no argument payload.
fn response_item_arguments_bytes(payload: &Value) -> Option<usize> {
payload
.get("arguments")
.or_else(|| payload.get("input"))
.or_else(|| payload.get("action"))
.map(compact_response_item_value)
.map(|arguments| arguments.len())
}
fn response_item_tool_output_text(payload: &Value, output: Option<&str>) -> Option<String> {
let call_id = payload
.get("call_id")
.and_then(Value::as_str)
.unwrap_or("unknown");
let output = output?;
let output_bytes = output.len();
// Record only the byte count — the raw tool output can carry secrets and
// must not land in the FTS-searchable text. The full body stays in the
// rollout, recoverable via `source_path`/`source_offset`.
Some(format!(
"Codex tool output: {call_id}\noutput_bytes: {output_bytes}"
))
}
fn response_item_reasoning_summary_text(payload: &Value) -> Option<String> {
let summary = payload.get("summary")?;
let text = collect_response_item_text(summary);
(!text.trim().is_empty()).then(|| format!("Codex reasoning summary:\n{text}"))
}
fn compact_response_item_value(value: &Value) -> String {
value
.as_str()
.map(str::to_string)
.unwrap_or_else(|| serde_json::to_string(value).unwrap_or_else(|_| value.to_string()))
}
fn response_item_tool_metadata(
response_item_type: &str,
payload: &Value,
tool_name: Option<String>,
output: Option<&str>,
) -> Value {
let mut metadata = serde_json::Map::new();
metadata.insert(
"source".to_string(),
Value::String("codex_response_item".to_string()),
);
metadata.insert(
"response_item_type".to_string(),
Value::String(response_item_type.to_string()),
);
for key in ["call_id", "id", "status", "namespace"] {
if let Some(value) = payload.get(key) {
metadata.insert(key.to_string(), value.clone());
}
}
if let Some(tool_name) = tool_name {
metadata.insert("tool_name".to_string(), Value::String(tool_name));
}
// Byte counts + truncation flags only — never the raw argument/output bytes.
if let Some(arguments_bytes) = response_item_arguments_bytes(payload) {
metadata.insert(
"arguments_bytes".to_string(),
Value::from(arguments_bytes as i64),
);
metadata.insert(
"arguments_truncated".to_string(),
Value::Bool(arguments_bytes > TOOL_EVENT_PREVIEW_BYTES),
);
}
if let Some(output) = output {
metadata.insert("output_bytes".to_string(), Value::from(output.len() as i64));
metadata.insert(
"output_truncated".to_string(),
Value::Bool(output.len() > TOOL_EVENT_PREVIEW_BYTES),
);
}
Value::Object(metadata)
}
fn goal_context_message(
meta: &CodexMeta,
model: Option<&str>,
path: &Path,
offset: i64,
timestamp: Option<i64>,
goal_context: &CodexGoalContext,
metadata: &Value,
) -> SessionMessageRecord {
SessionMessageRecord {
provider: PROVIDER.to_string(),
message_id: format!("{}:{offset}", meta.session_id),
session_id: meta.session_id.clone(),
role: "system".to_string(),
timestamp,
ordinal: offset,
text: goal_context.storage_text(),
kind: Some("goal_context".to_string()),
model: model.map(str::to_string),
tool_names: None,
source_path: Some(path.to_string_lossy().to_string()),
source_offset: Some(offset),
metadata_json: serde_json::to_string(&metadata).ok(),
}
}
/// Codex's structured session goal, parsed from a `thread_goal_updated`
/// `event_msg`. `status` is stored verbatim; the parser deliberately does not
/// map it to a fixed enum so an unrecognized future value survives round-trip.
struct CodexGoalEvent {
objective: String,
status: Option<String>,
thread_id: Option<String>,
tokens_used: Option<i64>,
time_used_seconds: Option<i64>,
created_at: Option<i64>,
updated_at: Option<i64>,
}
impl CodexGoalEvent {
/// Key used to collapse identical consecutive lifecycle states within one
/// parse pass. Token/time drift on the same `(objective, status)` is
/// progress within a state, not a transition, so it does not open a new row.
fn dedup_key(&self) -> (String, Option<String>) {
(self.objective.clone(), self.status.clone())
}
fn metadata(&self) -> Value {
let mut goal = serde_json::Map::new();
goal.insert(
"source".to_string(),
Value::String("codex_thread_goal".to_string()),
);
goal.insert(
"source_event".to_string(),
Value::String("thread_goal_updated".to_string()),
);
goal.insert(
"objective".to_string(),
Value::String(self.objective.clone()),
);
if let Some(status) = &self.status {
goal.insert("status".to_string(), Value::String(status.clone()));
}
if let Some(thread_id) = &self.thread_id {
goal.insert("thread_id".to_string(), Value::String(thread_id.clone()));
}
if let Some(tokens_used) = self.tokens_used {
goal.insert("tokens_used".to_string(), Value::from(tokens_used));
}
if let Some(time_used_seconds) = self.time_used_seconds {
goal.insert(
"time_used_seconds".to_string(),
Value::from(time_used_seconds),
);
}
if let Some(created_at) = self.created_at {
goal.insert("created_at".to_string(), Value::from(created_at));
}
if let Some(updated_at) = self.updated_at {
goal.insert("updated_at".to_string(), Value::from(updated_at));
}
Value::Object(goal)
}
}
/// Parse a `thread_goal_updated` `event_msg` into a [`CodexGoalEvent`], or
/// `None` for any other line. A goal with an empty/absent objective is skipped
/// (there is nothing to catalog or search).
fn codex_goal_event_from_line(record: &Value) -> Option<CodexGoalEvent> {
if record.get("type").and_then(Value::as_str) != Some("event_msg") {
return None;
}
let payload = record.get("payload")?;
if payload.get("type").and_then(Value::as_str) != Some("thread_goal_updated") {
return None;
}
let goal = payload.get("goal")?;
let objective = goal
.get("objective")
.and_then(Value::as_str)
.map(str::trim)
.filter(|objective| !objective.is_empty())?
.to_string();
Some(CodexGoalEvent {
objective,
status: goal
.get("status")
.and_then(Value::as_str)
.map(str::trim)
.filter(|status| !status.is_empty())
.map(str::to_string),
thread_id: goal
.get("threadId")
.and_then(Value::as_str)
.or_else(|| payload.get("threadId").and_then(Value::as_str))
.filter(|thread_id| !thread_id.is_empty())
.map(str::to_string),
tokens_used: goal.get("tokensUsed").and_then(Value::as_i64),
time_used_seconds: goal.get("timeUsedSeconds").and_then(Value::as_i64),
created_at: goal.get("createdAt").and_then(Value::as_i64),
updated_at: goal.get("updatedAt").and_then(Value::as_i64),
})
}
/// Build the compact `goal` session row: the objective as searchable text, the
/// lifecycle fields in `metadata_json`. Role `system` matches the other
/// non-conversational Codex rows (goal context, compaction summaries).
fn goal_event_message(
meta: &CodexMeta,
model: Option<&str>,
path: &Path,
offset: i64,
timestamp: Option<i64>,
event: &CodexGoalEvent,
) -> SessionMessageRecord {
SessionMessageRecord {
provider: PROVIDER.to_string(),
message_id: format!("{}:{offset}", meta.session_id),
session_id: meta.session_id.clone(),
role: "system".to_string(),
timestamp,
ordinal: offset,
text: event.objective.clone(),
kind: Some("goal".to_string()),
model: model.map(str::to_string),
tool_names: None,
source_path: Some(path.to_string_lossy().to_string()),
source_offset: Some(offset),
metadata_json: serde_json::to_string(&event.metadata()).ok(),
}
}
fn collect_response_item_text(value: &Value) -> String {
match value {
Value::String(text) => text.clone(),
Value::Array(items) => items
.iter()
.map(collect_response_item_text)
.filter(|text| !text.is_empty())
.collect::<Vec<_>>()
.join("\n"),
Value::Object(map) => {
if let Some(text) = map.get("text").and_then(Value::as_str) {
return text.to_string();
}
["content", "message", "item"]