Base: codex-main originale (prima del fork aKode)
This commit is contained in:
73
codex-rs/state/src/model/backfill_state.rs
Normal file
73
codex-rs/state/src/model/backfill_state.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
use anyhow::Result;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use sqlx::Row;
|
||||
use sqlx::sqlite::SqliteRow;
|
||||
|
||||
/// Persisted lifecycle state for rollout metadata backfill.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BackfillState {
|
||||
/// Current lifecycle status.
|
||||
pub status: BackfillStatus,
|
||||
/// Last processed rollout watermark.
|
||||
pub last_watermark: Option<String>,
|
||||
/// Last successful completion time.
|
||||
pub last_success_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
impl Default for BackfillState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
status: BackfillStatus::Pending,
|
||||
last_watermark: None,
|
||||
last_success_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BackfillState {
|
||||
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
|
||||
let status: String = row.try_get("status")?;
|
||||
let last_success_at = row
|
||||
.try_get::<Option<i64>, _>("last_success_at")?
|
||||
.map(epoch_seconds_to_datetime)
|
||||
.transpose()?;
|
||||
Ok(Self {
|
||||
status: BackfillStatus::parse(status.as_str())?,
|
||||
last_watermark: row.try_get("last_watermark")?,
|
||||
last_success_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Backfill lifecycle status.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum BackfillStatus {
|
||||
Pending,
|
||||
Running,
|
||||
Complete,
|
||||
}
|
||||
|
||||
impl BackfillStatus {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
BackfillStatus::Pending => "pending",
|
||||
BackfillStatus::Running => "running",
|
||||
BackfillStatus::Complete => "complete",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(value: &str) -> Result<Self> {
|
||||
match value {
|
||||
"pending" => Ok(Self::Pending),
|
||||
"running" => Ok(Self::Running),
|
||||
"complete" => Ok(Self::Complete),
|
||||
_ => Err(anyhow::anyhow!("invalid backfill status: {value}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn epoch_seconds_to_datetime(secs: i64) -> Result<DateTime<Utc>> {
|
||||
DateTime::<Utc>::from_timestamp(secs, 0)
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid unix timestamp: {secs}"))
|
||||
}
|
||||
11
codex-rs/state/src/model/graph.rs
Normal file
11
codex-rs/state/src/model/graph.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
use strum::AsRefStr;
|
||||
use strum::Display;
|
||||
use strum::EnumString;
|
||||
|
||||
/// Status attached to a directional thread-spawn edge.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, AsRefStr, Display, EnumString)]
|
||||
#[strum(serialize_all = "snake_case")]
|
||||
pub enum DirectionalThreadSpawnEdgeStatus {
|
||||
Open,
|
||||
Closed,
|
||||
}
|
||||
57
codex-rs/state/src/model/log.rs
Normal file
57
codex-rs/state/src/model/log.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
use serde::Serialize;
|
||||
use sqlx_macros::FromRow;
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct LogEntry {
|
||||
pub ts: i64,
|
||||
pub ts_nanos: i64,
|
||||
pub level: String,
|
||||
pub target: String,
|
||||
pub message: Option<String>,
|
||||
pub feedback_log_body: Option<String>,
|
||||
pub thread_id: Option<String>,
|
||||
pub process_uuid: Option<String>,
|
||||
pub module_path: Option<String>,
|
||||
pub file: Option<String>,
|
||||
pub line: Option<i64>,
|
||||
}
|
||||
|
||||
impl LogEntry {
|
||||
pub(crate) fn estimated_bytes(&self) -> i64 {
|
||||
let feedback_log_body = self.feedback_log_body.as_ref().or(self.message.as_ref());
|
||||
feedback_log_body.map_or(0, String::len) as i64
|
||||
+ self.level.len() as i64
|
||||
+ self.target.len() as i64
|
||||
+ self.module_path.as_ref().map_or(0, String::len) as i64
|
||||
+ self.file.as_ref().map_or(0, String::len) as i64
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, FromRow)]
|
||||
pub struct LogRow {
|
||||
pub id: i64,
|
||||
pub ts: i64,
|
||||
pub ts_nanos: i64,
|
||||
pub level: String,
|
||||
pub target: String,
|
||||
pub message: Option<String>,
|
||||
pub thread_id: Option<String>,
|
||||
pub process_uuid: Option<String>,
|
||||
pub file: Option<String>,
|
||||
pub line: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LogQuery {
|
||||
pub levels_upper: Vec<String>,
|
||||
pub from_ts: Option<i64>,
|
||||
pub to_ts: Option<i64>,
|
||||
pub module_like: Vec<String>,
|
||||
pub file_like: Vec<String>,
|
||||
pub thread_ids: Vec<String>,
|
||||
pub search: Option<String>,
|
||||
pub include_threadless: bool,
|
||||
pub after_id: Option<i64>,
|
||||
pub limit: Option<usize>,
|
||||
pub descending: bool,
|
||||
}
|
||||
69
codex-rs/state/src/model/memories.rs
Normal file
69
codex-rs/state/src/model/memories.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::ThreadMetadata;
|
||||
|
||||
/// Stored stage-1 memory extraction output for a single thread.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Stage1Output {
|
||||
pub thread_id: ThreadId,
|
||||
pub rollout_path: PathBuf,
|
||||
pub source_updated_at: DateTime<Utc>,
|
||||
pub raw_memory: String,
|
||||
pub rollout_summary: String,
|
||||
pub rollout_slug: Option<String>,
|
||||
pub cwd: PathBuf,
|
||||
pub git_branch: Option<String>,
|
||||
pub generated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// Result of trying to claim a stage-1 memory extraction job.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Stage1JobClaimOutcome {
|
||||
/// The caller owns the job and should continue with extraction.
|
||||
Claimed { ownership_token: String },
|
||||
/// Existing output is already newer than or equal to the source rollout.
|
||||
SkippedUpToDate,
|
||||
/// Another worker currently owns a fresh lease for this job.
|
||||
SkippedRunning,
|
||||
/// The job is in backoff and should not be retried yet.
|
||||
SkippedRetryBackoff,
|
||||
/// The job has exhausted retries and should not be retried automatically.
|
||||
SkippedRetryExhausted,
|
||||
}
|
||||
|
||||
/// Claimed stage-1 job with thread metadata.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Stage1JobClaim {
|
||||
pub thread: ThreadMetadata,
|
||||
pub ownership_token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Stage1StartupClaimParams<'a> {
|
||||
pub scan_limit: usize,
|
||||
pub max_claimed: usize,
|
||||
pub max_age_days: i64,
|
||||
pub min_rollout_idle_hours: i64,
|
||||
pub allowed_sources: &'a [String],
|
||||
pub lease_seconds: i64,
|
||||
}
|
||||
|
||||
/// Result of trying to claim a phase-2 consolidation job.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Phase2JobClaimOutcome {
|
||||
/// The caller owns the global lock and may inspect the memory workspace.
|
||||
Claimed {
|
||||
ownership_token: String,
|
||||
/// Snapshot of `input_watermark` at claim time.
|
||||
input_watermark: i64,
|
||||
},
|
||||
/// The global job is in retry backoff.
|
||||
SkippedRetryUnavailable,
|
||||
/// The global job completed recently enough that consolidation is cooling down.
|
||||
SkippedCooldown,
|
||||
/// Another worker currently owns a fresh global consolidation lease.
|
||||
SkippedRunning,
|
||||
}
|
||||
59
codex-rs/state/src/model/mod.rs
Normal file
59
codex-rs/state/src/model/mod.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
mod backfill_state;
|
||||
mod graph;
|
||||
mod log;
|
||||
mod memories;
|
||||
mod project;
|
||||
mod queued_item;
|
||||
mod rollout_migration_state;
|
||||
mod thread_attachment;
|
||||
mod thread_goal;
|
||||
mod thread_metadata;
|
||||
|
||||
pub use backfill_state::BackfillState;
|
||||
pub use backfill_state::BackfillStatus;
|
||||
pub use graph::DirectionalThreadSpawnEdgeStatus;
|
||||
pub use log::LogEntry;
|
||||
pub use log::LogQuery;
|
||||
pub use log::LogRow;
|
||||
pub use memories::Phase2JobClaimOutcome;
|
||||
pub use memories::Stage1JobClaim;
|
||||
pub use memories::Stage1JobClaimOutcome;
|
||||
pub use memories::Stage1Output;
|
||||
pub use memories::Stage1StartupClaimParams;
|
||||
pub use project::CreatedProject;
|
||||
pub use project::Project;
|
||||
pub use project::ProjectRoot;
|
||||
pub use project::ProjectSortKey;
|
||||
pub use project::ProjectsPage;
|
||||
pub use queued_item::QueuedUserSubmissionRecord;
|
||||
pub use rollout_migration_state::RolloutMigrationCursor;
|
||||
pub use rollout_migration_state::RolloutMigrationSkippedRollout;
|
||||
pub use rollout_migration_state::RolloutMigrationState;
|
||||
pub use thread_attachment::AddThreadAttachmentOutcome;
|
||||
pub use thread_attachment::RemoveThreadAttachmentOutcome;
|
||||
pub use thread_attachment::ThreadAttachment;
|
||||
pub use thread_attachment::ThreadAttachmentArchiveFilter;
|
||||
pub use thread_attachment::ThreadAttachmentOwner;
|
||||
pub use thread_attachment::ThreadAttachmentOwnerPage;
|
||||
pub use thread_attachment::ThreadAttachmentPage;
|
||||
pub use thread_goal::ThreadGoal;
|
||||
pub use thread_goal::ThreadGoalStatus;
|
||||
pub use thread_metadata::Anchor;
|
||||
pub use thread_metadata::BackfillStats;
|
||||
pub use thread_metadata::ExtractionOutcome;
|
||||
pub use thread_metadata::SortDirection;
|
||||
pub use thread_metadata::SortKey;
|
||||
pub use thread_metadata::ThreadMetadata;
|
||||
pub use thread_metadata::ThreadMetadataBuilder;
|
||||
pub use thread_metadata::ThreadRelationFilter;
|
||||
pub use thread_metadata::ThreadSection;
|
||||
pub use thread_metadata::ThreadSectionAppearance;
|
||||
pub use thread_metadata::ThreadSectionsPage;
|
||||
pub use thread_metadata::ThreadsPage;
|
||||
|
||||
pub(crate) use thread_goal::ThreadGoalRow;
|
||||
pub(crate) use thread_metadata::ThreadRow;
|
||||
pub(crate) use thread_metadata::anchor_from_item;
|
||||
pub(crate) use thread_metadata::datetime_to_epoch_millis;
|
||||
pub(crate) use thread_metadata::datetime_to_epoch_seconds;
|
||||
pub(crate) use thread_metadata::epoch_millis_to_datetime;
|
||||
39
codex-rs/state/src/model/project.rs
Normal file
39
codex-rs/state/src/model/project.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProjectRoot {
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Project {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub roots: Vec<ProjectRoot>,
|
||||
pub metadata: BTreeMap<String, String>,
|
||||
pub position: i64,
|
||||
pub created_at_ms: i64,
|
||||
pub updated_at_ms: i64,
|
||||
pub recency_at_ms: Option<i64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProjectSortKey {
|
||||
Position,
|
||||
RecencyAt,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CreatedProject {
|
||||
pub project: Project,
|
||||
pub created: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProjectsPage {
|
||||
pub projects: Vec<Project>,
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
22
codex-rs/state/src/model/queued_item.rs
Normal file
22
codex-rs/state/src/model/queued_item.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
use anyhow::Result;
|
||||
use codex_protocol::ThreadId;
|
||||
use sqlx::Row;
|
||||
use sqlx::sqlite::SqliteRow;
|
||||
|
||||
/// One durable, ordered user submission for a thread.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct QueuedUserSubmissionRecord {
|
||||
pub id: String,
|
||||
pub thread_id: ThreadId,
|
||||
pub payload: String,
|
||||
}
|
||||
|
||||
impl QueuedUserSubmissionRecord {
|
||||
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
|
||||
Ok(Self {
|
||||
id: row.try_get("id")?,
|
||||
thread_id: ThreadId::try_from(row.try_get::<String, _>("thread_id")?)?,
|
||||
payload: row.try_get("payload_json")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
67
codex-rs/state/src/model/rollout_migration_state.rs
Normal file
67
codex-rs/state/src/model/rollout_migration_state.rs
Normal file
@@ -0,0 +1,67 @@
|
||||
//! SQLite-backed bookkeeping types shared by rollout migrations.
|
||||
//!
|
||||
//! A migration cursor says “everything through this creation-ordered thread was checked.” A
|
||||
//! skipped rollout stores enough file fingerprint information to tell whether a previously
|
||||
//! unmigratable rollout is still unchanged.
|
||||
//!
|
||||
//! These types are intentionally generic so future rollout migrations can reuse the same state
|
||||
//! shape without depending on legacy -> paginated policy.
|
||||
|
||||
use anyhow::Result;
|
||||
use sqlx::Row;
|
||||
use sqlx::sqlite::SqliteRow;
|
||||
|
||||
/// Creation-ordered thread frontier checked by one rollout migration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct RolloutMigrationCursor {
|
||||
pub thread_created_at: i64,
|
||||
pub thread_id: String,
|
||||
}
|
||||
|
||||
/// Persisted progress for one rollout migration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RolloutMigrationState {
|
||||
pub last_checked_thread: Option<RolloutMigrationCursor>,
|
||||
}
|
||||
|
||||
impl RolloutMigrationState {
|
||||
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
|
||||
let thread_created_at = row.try_get("last_checked_thread_created_at")?;
|
||||
let thread_id = row.try_get("last_checked_thread_id")?;
|
||||
let last_checked_thread = match (thread_created_at, thread_id) {
|
||||
(Some(thread_created_at), Some(thread_id)) => Some(RolloutMigrationCursor {
|
||||
thread_created_at,
|
||||
thread_id,
|
||||
}),
|
||||
(None, None) => None,
|
||||
_ => {
|
||||
return Err(anyhow::anyhow!(
|
||||
"rollout migration state has incomplete last checked thread"
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
last_checked_thread,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// An unchanged rollout that one migration can safely skip.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RolloutMigrationSkippedRollout {
|
||||
pub rollout_path: String,
|
||||
pub rollout_size_bytes: i64,
|
||||
pub rollout_modified_at_ns: i64,
|
||||
pub skip_reason: String,
|
||||
}
|
||||
|
||||
impl RolloutMigrationSkippedRollout {
|
||||
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
|
||||
Ok(Self {
|
||||
rollout_path: row.try_get("rollout_path")?,
|
||||
rollout_size_bytes: row.try_get("rollout_size_bytes")?,
|
||||
rollout_modified_at_ns: row.try_get("rollout_modified_at_ns")?,
|
||||
skip_reason: row.try_get("skip_reason")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
70
codex-rs/state/src/model/thread_attachment.rs
Normal file
70
codex-rs/state/src/model/thread_attachment.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
//! Thread attachment records and outcomes; membership changes independently of resource contents.
|
||||
|
||||
use codex_protocol::ThreadId;
|
||||
use serde_json::Value;
|
||||
|
||||
/// A bounded attachment durably associated with one thread.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadAttachment {
|
||||
/// Stable, server-assigned UUIDv7 attachment identity.
|
||||
pub id: String,
|
||||
/// Thread that owns this attachment.
|
||||
pub thread_id: ThreadId,
|
||||
/// Client-defined attachment category.
|
||||
pub attachment_type: String,
|
||||
/// Client-defined stable identity within the owning thread and attachment category.
|
||||
pub identity_key: String,
|
||||
/// Bounded, client-defined attachment metadata.
|
||||
pub payload: Value,
|
||||
/// Integer Unix timestamp in seconds when the attachment was attached.
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
/// Result of attaching one uniquely identified thread attachment.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum AddThreadAttachmentOutcome {
|
||||
/// A new durable attachment was created.
|
||||
Created(ThreadAttachment),
|
||||
/// The attachment was already attached; its payload and creation time are unchanged.
|
||||
Existing(ThreadAttachment),
|
||||
}
|
||||
|
||||
/// Result of removing a thread attachment.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RemoveThreadAttachmentOutcome {
|
||||
/// An attached attachment was removed.
|
||||
Removed(ThreadAttachment),
|
||||
/// No attachment with the requested identity was attached.
|
||||
NotFound,
|
||||
}
|
||||
|
||||
/// One deterministically ordered page of attachments across selected threads.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadAttachmentPage {
|
||||
/// Attachments ordered by thread identity, creation time, and attachment identity.
|
||||
pub attachments: Vec<ThreadAttachment>,
|
||||
/// Opaque cursor for the next page, or `None` when the selection is exhausted.
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
/// Selects attachment owners by their persisted archive state.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ThreadAttachmentArchiveFilter {
|
||||
All,
|
||||
NonArchived,
|
||||
Archived,
|
||||
}
|
||||
|
||||
/// A thread whose current attachment membership contains the requested resource.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadAttachmentOwner {
|
||||
pub thread_id: ThreadId,
|
||||
pub archived: bool,
|
||||
}
|
||||
|
||||
/// One page of attachment owners, ordered by thread ID.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadAttachmentOwnerPage {
|
||||
pub threads: Vec<ThreadAttachmentOwner>,
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
117
codex-rs/state/src/model/thread_goal.rs
Normal file
117
codex-rs/state/src/model/thread_goal.rs
Normal file
@@ -0,0 +1,117 @@
|
||||
use anyhow::Result;
|
||||
use anyhow::anyhow;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_protocol::ThreadId;
|
||||
use serde::Serialize;
|
||||
use sqlx::Row;
|
||||
use sqlx::sqlite::SqliteRow;
|
||||
|
||||
use super::epoch_millis_to_datetime;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum ThreadGoalStatus {
|
||||
Active,
|
||||
Paused,
|
||||
Blocked,
|
||||
UsageLimited,
|
||||
BudgetLimited,
|
||||
Complete,
|
||||
}
|
||||
|
||||
impl ThreadGoalStatus {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Active => "active",
|
||||
Self::Paused => "paused",
|
||||
Self::Blocked => "blocked",
|
||||
Self::UsageLimited => "usage_limited",
|
||||
Self::BudgetLimited => "budget_limited",
|
||||
Self::Complete => "complete",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_active(self) -> bool {
|
||||
self == Self::Active
|
||||
}
|
||||
|
||||
pub fn is_terminal(self) -> bool {
|
||||
matches!(self, Self::BudgetLimited | Self::Complete)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for ThreadGoalStatus {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(value: &str) -> Result<Self> {
|
||||
match value {
|
||||
"active" => Ok(Self::Active),
|
||||
"paused" => Ok(Self::Paused),
|
||||
"blocked" => Ok(Self::Blocked),
|
||||
"usage_limited" => Ok(Self::UsageLimited),
|
||||
"budget_limited" => Ok(Self::BudgetLimited),
|
||||
"complete" => Ok(Self::Complete),
|
||||
other => Err(anyhow!("unknown thread goal status `{other}`")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadGoal {
|
||||
pub thread_id: ThreadId,
|
||||
pub goal_id: String,
|
||||
pub objective: String,
|
||||
pub status: ThreadGoalStatus,
|
||||
pub token_budget: Option<i64>,
|
||||
pub tokens_used: i64,
|
||||
pub time_used_seconds: i64,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
pub(crate) struct ThreadGoalRow {
|
||||
pub thread_id: String,
|
||||
pub goal_id: String,
|
||||
pub objective: String,
|
||||
pub status: String,
|
||||
pub token_budget: Option<i64>,
|
||||
pub tokens_used: i64,
|
||||
pub time_used_seconds: i64,
|
||||
pub created_at_ms: i64,
|
||||
pub updated_at_ms: i64,
|
||||
}
|
||||
|
||||
impl ThreadGoalRow {
|
||||
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
|
||||
Ok(Self {
|
||||
thread_id: row.try_get("thread_id")?,
|
||||
goal_id: row.try_get("goal_id")?,
|
||||
objective: row.try_get("objective")?,
|
||||
status: row.try_get("status")?,
|
||||
token_budget: row.try_get("token_budget")?,
|
||||
tokens_used: row.try_get("tokens_used")?,
|
||||
time_used_seconds: row.try_get("time_used_seconds")?,
|
||||
created_at_ms: row.try_get("created_at_ms")?,
|
||||
updated_at_ms: row.try_get("updated_at_ms")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<ThreadGoalRow> for ThreadGoal {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(row: ThreadGoalRow) -> Result<Self> {
|
||||
Ok(Self {
|
||||
thread_id: ThreadId::try_from(row.thread_id)?,
|
||||
goal_id: row.goal_id,
|
||||
objective: row.objective,
|
||||
status: ThreadGoalStatus::try_from(row.status.as_str())?,
|
||||
token_budget: row.token_budget,
|
||||
tokens_used: row.tokens_used,
|
||||
time_used_seconds: row.time_used_seconds,
|
||||
created_at: epoch_millis_to_datetime(row.created_at_ms)?,
|
||||
updated_at: epoch_millis_to_datetime(row.updated_at_ms)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
901
codex-rs/state/src/model/thread_metadata.rs
Normal file
901
codex-rs/state/src/model/thread_metadata.rs
Normal file
@@ -0,0 +1,901 @@
|
||||
use anyhow::Result;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_protocol::SanitizedGitUrl;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use codex_protocol::protocol::SandboxPolicy;
|
||||
use codex_protocol::protocol::SessionSource;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use codex_protocol::protocol::ThreadSource;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sqlx::Row;
|
||||
use sqlx::sqlite::SqliteRow;
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// The sort key to use when listing threads.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SortKey {
|
||||
/// Sort by the thread's creation timestamp.
|
||||
CreatedAt,
|
||||
/// Sort by the thread's last update timestamp.
|
||||
UpdatedAt,
|
||||
/// Sort by the thread's product recency timestamp.
|
||||
RecencyAt,
|
||||
/// Sort by the thread's stable position within its user-selected section.
|
||||
SectionPosition,
|
||||
}
|
||||
|
||||
/// Sort direction to use when listing threads.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SortDirection {
|
||||
Asc,
|
||||
Desc,
|
||||
}
|
||||
|
||||
/// Thread relationship used to filter thread listings.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ThreadRelationFilter {
|
||||
/// Return only threads whose immediate parent is the given thread.
|
||||
DirectChildrenOf(ThreadId),
|
||||
/// Return every thread transitively descended from the given thread.
|
||||
DescendantsOf(ThreadId),
|
||||
/// Return only saved threads attached to this parent.
|
||||
AttachedThreadsOf(ThreadId),
|
||||
}
|
||||
|
||||
/// A pagination anchor used for keyset pagination.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Anchor {
|
||||
/// The timestamp component of the anchor.
|
||||
pub ts: DateTime<Utc>,
|
||||
/// The thread ID component used to disambiguate equal recency timestamps.
|
||||
pub id: Option<ThreadId>,
|
||||
}
|
||||
|
||||
/// Visual presentation metadata owned by a thread section.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ThreadSectionAppearance {
|
||||
pub icon: Option<String>,
|
||||
pub color: Option<String>,
|
||||
}
|
||||
|
||||
/// An independently persisted thread section and its user-facing presentation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ThreadSection {
|
||||
/// Opaque UUIDv7 identifying the section independently of its name.
|
||||
pub id: String,
|
||||
/// User-facing section name.
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub appearance: Option<ThreadSectionAppearance>,
|
||||
}
|
||||
|
||||
impl ThreadSection {
|
||||
pub(crate) fn from_row(
|
||||
(id, name, appearance): (String, String, Option<String>),
|
||||
) -> Result<Self> {
|
||||
Ok(Self {
|
||||
id,
|
||||
name,
|
||||
appearance: appearance
|
||||
.map(|appearance| serde_json::from_str(&appearance))
|
||||
.transpose()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor-paginated page of independently persisted thread sections.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadSectionsPage {
|
||||
/// Sections in ascending identifier order.
|
||||
pub sections: Vec<ThreadSection>,
|
||||
/// Identifier after which the next page starts, if any.
|
||||
pub next_cursor: Option<String>,
|
||||
}
|
||||
|
||||
/// A single page of thread metadata results.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadsPage {
|
||||
/// The thread metadata items in this page.
|
||||
pub items: Vec<ThreadMetadata>,
|
||||
/// Immediate parents for page items found through the persisted spawn graph.
|
||||
pub parent_thread_ids: HashMap<ThreadId, ThreadId>,
|
||||
/// The next anchor to use for pagination, if any.
|
||||
pub next_anchor: Option<Anchor>,
|
||||
/// The number of rows scanned to produce this page.
|
||||
pub num_scanned_rows: usize,
|
||||
}
|
||||
|
||||
/// The outcome of extracting metadata from a rollout.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ExtractionOutcome {
|
||||
/// The extracted thread metadata.
|
||||
pub metadata: ThreadMetadata,
|
||||
/// The explicit thread memory mode from rollout metadata, if present.
|
||||
pub memory_mode: Option<String>,
|
||||
/// The number of rollout lines that failed to parse.
|
||||
pub parse_errors: usize,
|
||||
}
|
||||
|
||||
/// Canonical persisted thread metadata.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadMetadata {
|
||||
/// The parent of an attached thread, derived from canonical rollout metadata.
|
||||
pub attached_thread_parent_id: Option<ThreadId>,
|
||||
/// Originator recorded at creation, if available.
|
||||
pub originator: Option<String>,
|
||||
/// ChatGPT user that created the thread, if known.
|
||||
pub creator_user_id: Option<String>,
|
||||
/// ChatGPT account at creation, if known.
|
||||
pub creator_account_id: Option<String>,
|
||||
/// The thread identifier.
|
||||
pub id: ThreadId,
|
||||
/// The absolute rollout path on disk.
|
||||
pub rollout_path: PathBuf,
|
||||
/// The creation timestamp.
|
||||
pub created_at: DateTime<Utc>,
|
||||
/// The last update timestamp.
|
||||
pub updated_at: DateTime<Utc>,
|
||||
/// The product recency timestamp.
|
||||
pub recency_at: DateTime<Utc>,
|
||||
/// The session source (stringified enum).
|
||||
pub source: String,
|
||||
/// Persisted thread history contract selected when this thread was created.
|
||||
pub history_mode: ThreadHistoryMode,
|
||||
/// Optional analytics source classification for this thread.
|
||||
pub thread_source: Option<ThreadSource>,
|
||||
/// Optional random unique nickname assigned to an AgentControl-spawned sub-agent.
|
||||
pub agent_nickname: Option<String>,
|
||||
/// Optional role (agent_role) assigned to an AgentControl-spawned sub-agent.
|
||||
pub agent_role: Option<String>,
|
||||
/// Optional canonical agent path assigned to an AgentControl-spawned sub-agent.
|
||||
pub agent_path: Option<String>,
|
||||
/// The model provider identifier.
|
||||
pub model_provider: String,
|
||||
/// The latest observed model for the thread.
|
||||
pub model: Option<String>,
|
||||
/// The latest observed reasoning effort for the thread.
|
||||
pub reasoning_effort: Option<ReasoningEffort>,
|
||||
/// The working directory for the thread.
|
||||
pub cwd: PathBuf,
|
||||
/// Version of the CLI that created the thread.
|
||||
pub cli_version: String,
|
||||
/// A best-effort thread title.
|
||||
pub title: String,
|
||||
/// Explicit user-facing thread name, if one was set.
|
||||
pub name: Option<String>,
|
||||
/// Best available user-facing preview for discovery and list display.
|
||||
pub preview: Option<String>,
|
||||
/// The sandbox policy (stringified enum).
|
||||
pub sandbox_policy: String,
|
||||
/// The approval mode (stringified enum).
|
||||
pub approval_mode: String,
|
||||
/// The last observed token usage.
|
||||
pub tokens_used: i64,
|
||||
/// First user message observed for this thread, if any.
|
||||
pub first_user_message: Option<String>,
|
||||
/// The archive timestamp, if the thread is archived.
|
||||
pub archived_at: Option<DateTime<Utc>>,
|
||||
/// The user-selected section for this thread, if any.
|
||||
pub section: Option<ThreadSection>,
|
||||
/// The stable sparse ordering rank within the user-selected section.
|
||||
pub section_position: Option<i64>,
|
||||
/// The time when the thread most recently entered its current section.
|
||||
pub section_entered_at: Option<DateTime<Utc>>,
|
||||
/// Canonical project assignment owned by app-server, if any.
|
||||
pub project_id: Option<String>,
|
||||
/// User-selected Daybreak preference, absent until explicitly set.
|
||||
pub daybreak_enabled: Option<bool>,
|
||||
/// The git commit SHA, if known.
|
||||
pub git_sha: Option<String>,
|
||||
/// The git branch name, if known.
|
||||
pub git_branch: Option<String>,
|
||||
/// The git origin URL, if known.
|
||||
pub git_origin_url: Option<SanitizedGitUrl>,
|
||||
}
|
||||
|
||||
/// Builder data required to construct [`ThreadMetadata`] without parsing filenames.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ThreadMetadataBuilder {
|
||||
/// Originator recorded at creation, if available.
|
||||
pub originator: Option<String>,
|
||||
/// ChatGPT user that created the thread, if known.
|
||||
pub creator_user_id: Option<String>,
|
||||
/// ChatGPT account at creation, if known.
|
||||
pub creator_account_id: Option<String>,
|
||||
/// The thread identifier.
|
||||
pub id: ThreadId,
|
||||
/// The absolute rollout path on disk.
|
||||
pub rollout_path: PathBuf,
|
||||
/// The creation timestamp.
|
||||
pub created_at: DateTime<Utc>,
|
||||
/// The last update timestamp, if known.
|
||||
pub updated_at: Option<DateTime<Utc>>,
|
||||
/// The product recency timestamp, if known.
|
||||
pub recency_at: Option<DateTime<Utc>>,
|
||||
/// The session source.
|
||||
pub source: SessionSource,
|
||||
/// Persisted thread history contract selected when this thread was created.
|
||||
pub history_mode: ThreadHistoryMode,
|
||||
/// Optional analytics source classification for this thread.
|
||||
pub thread_source: Option<ThreadSource>,
|
||||
/// Optional random unique nickname assigned to the session.
|
||||
pub agent_nickname: Option<String>,
|
||||
/// Optional role (agent_role) assigned to the session.
|
||||
pub agent_role: Option<String>,
|
||||
/// Optional canonical agent path assigned to the session.
|
||||
pub agent_path: Option<String>,
|
||||
/// The model provider identifier, if known.
|
||||
pub model_provider: Option<String>,
|
||||
/// The working directory for the thread.
|
||||
pub cwd: PathBuf,
|
||||
/// Version of the CLI that created the thread.
|
||||
pub cli_version: Option<String>,
|
||||
/// The sandbox policy.
|
||||
pub sandbox_policy: SandboxPolicy,
|
||||
/// The approval mode.
|
||||
pub approval_mode: AskForApproval,
|
||||
/// The archive timestamp, if the thread is archived.
|
||||
pub archived_at: Option<DateTime<Utc>>,
|
||||
/// The git commit SHA, if known.
|
||||
pub git_sha: Option<String>,
|
||||
/// The git branch name, if known.
|
||||
pub git_branch: Option<String>,
|
||||
/// The git origin URL, if known.
|
||||
pub git_origin_url: Option<SanitizedGitUrl>,
|
||||
}
|
||||
|
||||
impl ThreadMetadataBuilder {
|
||||
/// Create a new builder with required fields and sensible defaults.
|
||||
pub fn new(
|
||||
id: ThreadId,
|
||||
rollout_path: PathBuf,
|
||||
created_at: DateTime<Utc>,
|
||||
source: SessionSource,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
rollout_path,
|
||||
created_at,
|
||||
updated_at: None,
|
||||
recency_at: None,
|
||||
originator: None,
|
||||
creator_user_id: None,
|
||||
creator_account_id: None,
|
||||
source,
|
||||
history_mode: ThreadHistoryMode::Legacy,
|
||||
thread_source: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
agent_path: None,
|
||||
model_provider: None,
|
||||
cwd: PathBuf::new(),
|
||||
cli_version: None,
|
||||
sandbox_policy: SandboxPolicy::new_read_only_policy(),
|
||||
approval_mode: AskForApproval::OnRequest,
|
||||
archived_at: None,
|
||||
git_sha: None,
|
||||
git_branch: None,
|
||||
git_origin_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build canonical thread metadata, filling missing values from defaults.
|
||||
pub fn build(&self, default_provider: &str) -> ThreadMetadata {
|
||||
let source = crate::extract::enum_to_string(&self.source);
|
||||
let sandbox_policy = crate::extract::enum_to_string(&self.sandbox_policy);
|
||||
let approval_mode = crate::extract::enum_to_string(&self.approval_mode);
|
||||
let created_at = canonicalize_datetime(self.created_at);
|
||||
let updated_at = self
|
||||
.updated_at
|
||||
.map(canonicalize_datetime)
|
||||
.unwrap_or(created_at);
|
||||
let recency_at = self
|
||||
.recency_at
|
||||
.map(canonicalize_datetime)
|
||||
.unwrap_or(updated_at);
|
||||
let guardian_review = crate::is_guardian_review_source(&self.source);
|
||||
ThreadMetadata {
|
||||
attached_thread_parent_id: None,
|
||||
originator: self.originator.clone(),
|
||||
creator_user_id: self.creator_user_id.clone(),
|
||||
creator_account_id: self.creator_account_id.clone(),
|
||||
id: self.id,
|
||||
rollout_path: self.rollout_path.clone(),
|
||||
created_at,
|
||||
updated_at,
|
||||
recency_at,
|
||||
source,
|
||||
history_mode: self.history_mode,
|
||||
thread_source: self.thread_source.clone(),
|
||||
agent_nickname: self.agent_nickname.clone(),
|
||||
agent_role: self.agent_role.clone(),
|
||||
agent_path: self
|
||||
.agent_path
|
||||
.clone()
|
||||
.or_else(|| self.source.get_agent_path().map(Into::into)),
|
||||
model_provider: self
|
||||
.model_provider
|
||||
.clone()
|
||||
.unwrap_or_else(|| default_provider.to_string()),
|
||||
model: None,
|
||||
reasoning_effort: None,
|
||||
cwd: self.cwd.clone(),
|
||||
cli_version: self.cli_version.clone().unwrap_or_default(),
|
||||
title: if guardian_review {
|
||||
crate::GUARDIAN_THREAD_TITLE.to_string()
|
||||
} else {
|
||||
String::new()
|
||||
},
|
||||
name: (guardian_review && self.history_mode == ThreadHistoryMode::Paginated)
|
||||
.then(|| crate::GUARDIAN_THREAD_TITLE.to_string()),
|
||||
preview: guardian_review.then(|| crate::GUARDIAN_THREAD_PREVIEW.to_string()),
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
tokens_used: 0,
|
||||
first_user_message: None,
|
||||
archived_at: self.archived_at.map(canonicalize_datetime),
|
||||
section: None,
|
||||
section_position: None,
|
||||
section_entered_at: None,
|
||||
project_id: None,
|
||||
daybreak_enabled: None,
|
||||
git_sha: self.git_sha.clone(),
|
||||
git_branch: self.git_branch.clone(),
|
||||
git_origin_url: self.git_origin_url.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadMetadata {
|
||||
/// Preserve SQLite-owned Git fields when rollout-derived metadata is reconciled.
|
||||
pub fn prefer_existing_git_info(&mut self, existing: &Self) {
|
||||
if matches!(self.history_mode, ThreadHistoryMode::Paginated)
|
||||
&& matches!(existing.history_mode, ThreadHistoryMode::Paginated)
|
||||
{
|
||||
// `self` was rebuilt from the rollout's initial SessionMeta. `existing` is the
|
||||
// current SQLite row. Once that row says paginated, metadata updates are SQLite-only,
|
||||
// so a NULL is an explicit clear, not missing data. Copy the whole tuple or the stale
|
||||
// rollout value would be written back during reconciliation.
|
||||
self.git_sha = existing.git_sha.clone();
|
||||
self.git_branch = existing.git_branch.clone();
|
||||
self.git_origin_url = existing.git_origin_url.clone();
|
||||
return;
|
||||
}
|
||||
if existing.git_sha.is_some() {
|
||||
self.git_sha = existing.git_sha.clone();
|
||||
}
|
||||
if existing.git_branch.is_some() {
|
||||
self.git_branch = existing.git_branch.clone();
|
||||
}
|
||||
if existing.git_origin_url.is_some() {
|
||||
self.git_origin_url = existing.git_origin_url.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserve an existing user-facing title when reconciling rollout-derived metadata.
|
||||
pub fn prefer_existing_explicit_title(&mut self, existing: &Self) {
|
||||
let existing_title = existing.title.trim();
|
||||
if existing_title.is_empty()
|
||||
|| existing.first_user_message.as_deref().map(str::trim) == Some(existing_title)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let title = self.title.trim();
|
||||
if title.is_empty()
|
||||
|| self.first_user_message.as_deref().map(str::trim) == Some(title)
|
||||
|| (title == crate::GUARDIAN_THREAD_TITLE
|
||||
&& crate::extract::metadata_is_guardian_review(self))
|
||||
{
|
||||
self.title = existing.title.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the list of field names that differ between `self` and `other`.
|
||||
pub fn diff_fields(&self, other: &Self) -> Vec<&'static str> {
|
||||
let mut diffs = Vec::new();
|
||||
if self.id != other.id {
|
||||
diffs.push("id");
|
||||
}
|
||||
if self.rollout_path != other.rollout_path {
|
||||
diffs.push("rollout_path");
|
||||
}
|
||||
if self.created_at != other.created_at {
|
||||
diffs.push("created_at");
|
||||
}
|
||||
if self.updated_at != other.updated_at {
|
||||
diffs.push("updated_at");
|
||||
}
|
||||
if self.source != other.source {
|
||||
diffs.push("source");
|
||||
}
|
||||
if self.creator_user_id != other.creator_user_id {
|
||||
diffs.push("creator_user_id");
|
||||
}
|
||||
if self.creator_account_id != other.creator_account_id {
|
||||
diffs.push("creator_account_id");
|
||||
}
|
||||
if self.originator != other.originator {
|
||||
diffs.push("originator");
|
||||
}
|
||||
if self.agent_nickname != other.agent_nickname {
|
||||
diffs.push("agent_nickname");
|
||||
}
|
||||
if self.agent_role != other.agent_role {
|
||||
diffs.push("agent_role");
|
||||
}
|
||||
if self.agent_path != other.agent_path {
|
||||
diffs.push("agent_path");
|
||||
}
|
||||
if self.model_provider != other.model_provider {
|
||||
diffs.push("model_provider");
|
||||
}
|
||||
if self.model != other.model {
|
||||
diffs.push("model");
|
||||
}
|
||||
if self.reasoning_effort != other.reasoning_effort {
|
||||
diffs.push("reasoning_effort");
|
||||
}
|
||||
if self.cwd != other.cwd {
|
||||
diffs.push("cwd");
|
||||
}
|
||||
if self.cli_version != other.cli_version {
|
||||
diffs.push("cli_version");
|
||||
}
|
||||
if self.title != other.title {
|
||||
diffs.push("title");
|
||||
}
|
||||
if self.name != other.name {
|
||||
diffs.push("name");
|
||||
}
|
||||
if self.preview != other.preview {
|
||||
diffs.push("preview");
|
||||
}
|
||||
if self.sandbox_policy != other.sandbox_policy {
|
||||
diffs.push("sandbox_policy");
|
||||
}
|
||||
if self.approval_mode != other.approval_mode {
|
||||
diffs.push("approval_mode");
|
||||
}
|
||||
if self.tokens_used != other.tokens_used {
|
||||
diffs.push("tokens_used");
|
||||
}
|
||||
if self.first_user_message != other.first_user_message {
|
||||
diffs.push("first_user_message");
|
||||
}
|
||||
if self.archived_at != other.archived_at {
|
||||
diffs.push("archived_at");
|
||||
}
|
||||
if self.section != other.section {
|
||||
diffs.push("section");
|
||||
}
|
||||
if self.section_position != other.section_position {
|
||||
diffs.push("section_position");
|
||||
}
|
||||
if self.section_entered_at != other.section_entered_at {
|
||||
diffs.push("section_entered_at");
|
||||
}
|
||||
if self.project_id != other.project_id {
|
||||
diffs.push("project_id");
|
||||
}
|
||||
if self.daybreak_enabled != other.daybreak_enabled {
|
||||
diffs.push("daybreak_enabled");
|
||||
}
|
||||
if self.git_sha != other.git_sha {
|
||||
diffs.push("git_sha");
|
||||
}
|
||||
if self.git_branch != other.git_branch {
|
||||
diffs.push("git_branch");
|
||||
}
|
||||
if self.git_origin_url != other.git_origin_url {
|
||||
diffs.push("git_origin_url");
|
||||
}
|
||||
diffs
|
||||
}
|
||||
}
|
||||
|
||||
fn canonicalize_datetime(dt: DateTime<Utc>) -> DateTime<Utc> {
|
||||
epoch_millis_to_datetime(datetime_to_epoch_millis(dt)).unwrap_or(dt)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ThreadRow {
|
||||
attached_thread_parent_id: Option<String>,
|
||||
originator: Option<String>,
|
||||
creator_user_id: Option<String>,
|
||||
creator_account_id: Option<String>,
|
||||
id: String,
|
||||
rollout_path: String,
|
||||
created_at: i64,
|
||||
updated_at: i64,
|
||||
recency_at: i64,
|
||||
source: String,
|
||||
history_mode: String,
|
||||
thread_source: Option<String>,
|
||||
agent_nickname: Option<String>,
|
||||
agent_role: Option<String>,
|
||||
agent_path: Option<String>,
|
||||
model_provider: String,
|
||||
model: Option<String>,
|
||||
reasoning_effort: Option<String>,
|
||||
cwd: String,
|
||||
cli_version: String,
|
||||
title: String,
|
||||
name: Option<String>,
|
||||
preview: String,
|
||||
sandbox_policy: String,
|
||||
approval_mode: String,
|
||||
tokens_used: i64,
|
||||
first_user_message: String,
|
||||
archived_at: Option<i64>,
|
||||
section: Option<String>,
|
||||
section_name: Option<String>,
|
||||
section_appearance: Option<String>,
|
||||
section_position: Option<i64>,
|
||||
section_entered_at_ms: Option<i64>,
|
||||
project_id: Option<String>,
|
||||
daybreak_enabled: Option<bool>,
|
||||
git_sha: Option<String>,
|
||||
git_branch: Option<String>,
|
||||
git_origin_url: Option<String>,
|
||||
}
|
||||
|
||||
impl ThreadRow {
|
||||
pub(crate) fn try_from_row(row: &SqliteRow) -> Result<Self> {
|
||||
Ok(Self {
|
||||
attached_thread_parent_id: row.try_get("attached_thread_parent_id")?,
|
||||
originator: row.try_get("originator")?,
|
||||
creator_user_id: row.try_get("creator_user_id")?,
|
||||
creator_account_id: row.try_get("creator_account_id")?,
|
||||
id: row.try_get("id")?,
|
||||
rollout_path: row.try_get("rollout_path")?,
|
||||
created_at: row.try_get("created_at")?,
|
||||
updated_at: row.try_get("updated_at")?,
|
||||
recency_at: row.try_get("recency_at")?,
|
||||
source: row.try_get("source")?,
|
||||
history_mode: row.try_get("history_mode")?,
|
||||
thread_source: row.try_get("thread_source")?,
|
||||
agent_nickname: row.try_get("agent_nickname")?,
|
||||
agent_role: row.try_get("agent_role")?,
|
||||
agent_path: row.try_get("agent_path")?,
|
||||
model_provider: row.try_get("model_provider")?,
|
||||
model: row.try_get("model")?,
|
||||
reasoning_effort: row.try_get("reasoning_effort")?,
|
||||
cwd: row.try_get("cwd")?,
|
||||
cli_version: row.try_get("cli_version")?,
|
||||
title: row.try_get("title")?,
|
||||
name: row.try_get("name")?,
|
||||
preview: row.try_get("preview")?,
|
||||
sandbox_policy: row.try_get("sandbox_policy")?,
|
||||
approval_mode: row.try_get("approval_mode")?,
|
||||
tokens_used: row.try_get("tokens_used")?,
|
||||
first_user_message: row.try_get("first_user_message")?,
|
||||
archived_at: row.try_get("archived_at")?,
|
||||
section: row.try_get("section")?,
|
||||
section_name: row.try_get("section_name")?,
|
||||
section_appearance: row.try_get("section_appearance")?,
|
||||
section_position: row.try_get("section_position")?,
|
||||
section_entered_at_ms: row.try_get("section_entered_at_ms")?,
|
||||
project_id: row.try_get("project_id")?,
|
||||
daybreak_enabled: row.try_get("daybreak_enabled")?,
|
||||
git_sha: row.try_get("git_sha")?,
|
||||
git_branch: row.try_get("git_branch")?,
|
||||
git_origin_url: row.try_get("git_origin_url")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<ThreadRow> for ThreadMetadata {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(row: ThreadRow) -> std::result::Result<Self, Self::Error> {
|
||||
let ThreadRow {
|
||||
attached_thread_parent_id,
|
||||
originator,
|
||||
creator_user_id,
|
||||
creator_account_id,
|
||||
id,
|
||||
rollout_path,
|
||||
created_at,
|
||||
updated_at,
|
||||
recency_at,
|
||||
source,
|
||||
history_mode,
|
||||
thread_source,
|
||||
agent_nickname,
|
||||
agent_role,
|
||||
agent_path,
|
||||
model_provider,
|
||||
model,
|
||||
reasoning_effort,
|
||||
cwd,
|
||||
cli_version,
|
||||
title,
|
||||
name,
|
||||
preview,
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
tokens_used,
|
||||
first_user_message,
|
||||
archived_at,
|
||||
section,
|
||||
section_name,
|
||||
section_appearance,
|
||||
section_position,
|
||||
section_entered_at_ms,
|
||||
project_id,
|
||||
daybreak_enabled,
|
||||
git_sha,
|
||||
git_branch,
|
||||
git_origin_url,
|
||||
} = row;
|
||||
let thread_source = thread_source
|
||||
.map(|thread_source| thread_source.parse())
|
||||
.transpose()
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
let history_mode = history_mode.parse().map_err(anyhow::Error::msg)?;
|
||||
let section = match (section, section_name) {
|
||||
(Some(id), Some(name)) => {
|
||||
Some(ThreadSection::from_row((id, name, section_appearance))?)
|
||||
}
|
||||
(None, None) => None,
|
||||
(Some(id), None) => {
|
||||
return Err(anyhow::anyhow!(
|
||||
"thread references an unknown section: {id}"
|
||||
));
|
||||
}
|
||||
(None, Some(name)) => {
|
||||
return Err(anyhow::anyhow!(
|
||||
"thread has a section name without a section id: {name}"
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(Self {
|
||||
id: ThreadId::try_from(id)?,
|
||||
attached_thread_parent_id: attached_thread_parent_id
|
||||
.map(ThreadId::try_from)
|
||||
.transpose()?,
|
||||
originator,
|
||||
creator_user_id,
|
||||
creator_account_id,
|
||||
rollout_path: PathBuf::from(rollout_path),
|
||||
created_at: epoch_millis_to_datetime(created_at)?,
|
||||
updated_at: epoch_millis_to_datetime(updated_at)?,
|
||||
recency_at: epoch_millis_to_datetime(recency_at)?,
|
||||
source,
|
||||
history_mode,
|
||||
thread_source,
|
||||
agent_nickname,
|
||||
agent_role,
|
||||
agent_path,
|
||||
model_provider,
|
||||
model,
|
||||
reasoning_effort: reasoning_effort
|
||||
.and_then(|value| value.parse::<ReasoningEffort>().ok()),
|
||||
cwd: PathBuf::from(cwd),
|
||||
cli_version,
|
||||
title,
|
||||
name,
|
||||
preview: (!preview.is_empty()).then_some(preview),
|
||||
sandbox_policy,
|
||||
approval_mode,
|
||||
tokens_used,
|
||||
first_user_message: (!first_user_message.is_empty()).then_some(first_user_message),
|
||||
archived_at: archived_at.map(epoch_seconds_to_datetime).transpose()?,
|
||||
section,
|
||||
section_position,
|
||||
section_entered_at: section_entered_at_ms
|
||||
.map(epoch_millis_to_datetime)
|
||||
.transpose()?,
|
||||
project_id,
|
||||
daybreak_enabled,
|
||||
git_sha,
|
||||
git_branch,
|
||||
git_origin_url: git_origin_url
|
||||
.and_then(|origin_url| SanitizedGitUrl::try_from(origin_url).ok()),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn anchor_from_item(item: &ThreadMetadata, sort_key: SortKey) -> Option<Anchor> {
|
||||
let ts = match sort_key {
|
||||
SortKey::CreatedAt => item.created_at,
|
||||
SortKey::UpdatedAt => item.updated_at,
|
||||
SortKey::RecencyAt => item.recency_at,
|
||||
SortKey::SectionPosition => DateTime::<Utc>::from_timestamp_millis(item.section_position?)?,
|
||||
};
|
||||
Some(Anchor {
|
||||
ts,
|
||||
id: Some(item.id),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn datetime_to_epoch_millis(dt: DateTime<Utc>) -> i64 {
|
||||
dt.timestamp_millis()
|
||||
}
|
||||
|
||||
pub(crate) fn datetime_to_epoch_seconds(dt: DateTime<Utc>) -> i64 {
|
||||
dt.timestamp()
|
||||
}
|
||||
|
||||
pub(crate) fn epoch_millis_to_datetime(value: i64) -> Result<DateTime<Utc>> {
|
||||
// Values older than 2020 if interpreted as milliseconds are legacy second-precision rows.
|
||||
// Convert them in memory so old state DBs keep ordering correctly after new writes use ms.
|
||||
const MIN_EPOCH_MILLIS: i64 = 1_577_836_800_000;
|
||||
let millis = if value < MIN_EPOCH_MILLIS {
|
||||
value.saturating_mul(1000)
|
||||
} else {
|
||||
value
|
||||
};
|
||||
DateTime::<Utc>::from_timestamp_millis(millis)
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid unix timestamp millis: {value}"))
|
||||
}
|
||||
|
||||
pub(crate) fn epoch_seconds_to_datetime(value: i64) -> Result<DateTime<Utc>> {
|
||||
DateTime::<Utc>::from_timestamp(value, 0)
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid unix timestamp seconds: {value}"))
|
||||
}
|
||||
|
||||
/// Statistics about a backfill operation.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BackfillStats {
|
||||
/// The number of rollout files scanned.
|
||||
pub scanned: usize,
|
||||
/// The number of rows upserted successfully.
|
||||
pub upserted: usize,
|
||||
/// The number of rows that failed to upsert.
|
||||
pub failed: usize,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ThreadMetadata;
|
||||
use super::ThreadRow;
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use codex_protocol::SanitizedGitUrl;
|
||||
use codex_protocol::ThreadId;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::ThreadHistoryMode;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn thread_row(reasoning_effort: Option<&str>) -> ThreadRow {
|
||||
ThreadRow {
|
||||
attached_thread_parent_id: None,
|
||||
originator: None,
|
||||
creator_user_id: None,
|
||||
creator_account_id: None,
|
||||
id: "00000000-0000-0000-0000-000000000123".to_string(),
|
||||
rollout_path: "/tmp/rollout-123.jsonl".to_string(),
|
||||
created_at: 1_700_000_000,
|
||||
updated_at: 1_700_000_100,
|
||||
recency_at: 1_700_000_100,
|
||||
source: "cli".to_string(),
|
||||
history_mode: "legacy".to_string(),
|
||||
thread_source: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
agent_path: None,
|
||||
model_provider: "openai".to_string(),
|
||||
model: Some("gpt-5".to_string()),
|
||||
reasoning_effort: reasoning_effort.map(str::to_string),
|
||||
cwd: "/tmp/workspace".to_string(),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
title: String::new(),
|
||||
name: None,
|
||||
preview: String::new(),
|
||||
sandbox_policy: "read-only".to_string(),
|
||||
approval_mode: "on-request".to_string(),
|
||||
tokens_used: 1,
|
||||
first_user_message: String::new(),
|
||||
archived_at: None,
|
||||
section: None,
|
||||
section_name: None,
|
||||
section_appearance: None,
|
||||
section_position: None,
|
||||
section_entered_at_ms: None,
|
||||
project_id: None,
|
||||
daybreak_enabled: None,
|
||||
git_sha: None,
|
||||
git_branch: None,
|
||||
git_origin_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn expected_thread_metadata(reasoning_effort: Option<ReasoningEffort>) -> ThreadMetadata {
|
||||
ThreadMetadata {
|
||||
attached_thread_parent_id: None,
|
||||
originator: None,
|
||||
creator_user_id: None,
|
||||
creator_account_id: None,
|
||||
id: ThreadId::from_string("00000000-0000-0000-0000-000000000123")
|
||||
.expect("valid thread id"),
|
||||
rollout_path: PathBuf::from("/tmp/rollout-123.jsonl"),
|
||||
created_at: DateTime::<Utc>::from_timestamp(1_700_000_000, 0).expect("timestamp"),
|
||||
updated_at: DateTime::<Utc>::from_timestamp(1_700_000_100, 0).expect("timestamp"),
|
||||
recency_at: DateTime::<Utc>::from_timestamp(1_700_000_100, 0).expect("timestamp"),
|
||||
source: "cli".to_string(),
|
||||
history_mode: ThreadHistoryMode::Legacy,
|
||||
thread_source: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
agent_path: None,
|
||||
model_provider: "openai".to_string(),
|
||||
model: Some("gpt-5".to_string()),
|
||||
reasoning_effort,
|
||||
cwd: PathBuf::from("/tmp/workspace"),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
title: String::new(),
|
||||
name: None,
|
||||
preview: None,
|
||||
sandbox_policy: "read-only".to_string(),
|
||||
approval_mode: "on-request".to_string(),
|
||||
tokens_used: 1,
|
||||
first_user_message: None,
|
||||
archived_at: None,
|
||||
section: None,
|
||||
section_position: None,
|
||||
section_entered_at: None,
|
||||
project_id: None,
|
||||
daybreak_enabled: None,
|
||||
git_sha: None,
|
||||
git_branch: None,
|
||||
git_origin_url: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_row_parses_reasoning_effort() {
|
||||
let metadata = ThreadMetadata::try_from(thread_row(Some("high")))
|
||||
.expect("thread metadata should parse");
|
||||
|
||||
assert_eq!(
|
||||
metadata,
|
||||
expected_thread_metadata(Some(ReasoningEffort::High))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_row_preserves_model_defined_reasoning_effort_values() {
|
||||
let metadata = ThreadMetadata::try_from(thread_row(Some("future")))
|
||||
.expect("thread metadata should parse");
|
||||
|
||||
assert_eq!(
|
||||
metadata,
|
||||
expected_thread_metadata(Some(ReasoningEffort::Custom("future".to_string())))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_row_rejects_unknown_history_mode() {
|
||||
let mut row = thread_row(/*reasoning_effort*/ None);
|
||||
row.history_mode = "future".to_string();
|
||||
|
||||
assert!(ThreadMetadata::try_from(row).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paginated_rollout_git_info_keeps_rollout_values_until_sqlite_mode_is_paginated() {
|
||||
let mut reconciled = expected_thread_metadata(/*reasoning_effort*/ None);
|
||||
reconciled.history_mode = ThreadHistoryMode::Paginated;
|
||||
reconciled.git_sha = Some("rollout-sha".to_string());
|
||||
reconciled.git_branch = Some("rollout-branch".to_string());
|
||||
reconciled.git_origin_url = Some(
|
||||
SanitizedGitUrl::try_from("https://example.com/rollout-origin")
|
||||
.expect("valid git remote URL"),
|
||||
);
|
||||
let existing = expected_thread_metadata(/*reasoning_effort*/ None);
|
||||
let expected = reconciled.clone();
|
||||
|
||||
reconciled.prefer_existing_git_info(&existing);
|
||||
|
||||
assert_eq!(reconciled, expected);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user