Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS claude_session_auth_state (
session_id TEXT PRIMARY KEY,
provider TEXT NOT NULL CHECK (provider IN ('anthropic', 'aws_bedrock', 'google_vertex', 'microsoft_foundry', 'custom_gateway', 'unknown')),
billing_mode TEXT NOT NULL CHECK (billing_mode IN ('api_key', 'subscription', 'cloud_provider', 'unknown')),
auth_env_key TEXT CHECK (auth_env_key IS NULL OR auth_env_key IN ('claude_code_use_bedrock', 'claude_code_use_vertex', 'claude_code_use_foundry', 'anthropic_auth_token', 'anthropic_api_key', 'claude_code_oauth_token')),
confidence TEXT NOT NULL CHECK (confidence IN ('inferred', 'unknown')),
observed_at_ms INTEGER NOT NULL CHECK (observed_at_ms >= 0)
);
114 changes: 114 additions & 0 deletions cli/src/services/agent_trace_db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use turso::Value as TursoValue;

use crate::services::{
db::{DbSpec, TursoDb},
hooks::claude_auth_detection::{AuthEnvKey, AuthProvider, BillingMode, DetectionConfidence},
patch::{parse_patch, ParseError, ParsedPatch},
structured_patch::{derive_claude_structured_patch, ClaudeStructuredPatchDerivationResult},
};
Expand Down Expand Up @@ -132,6 +133,38 @@ FROM claude_model_state
WHERE session_id = ?1 AND agent_id = ?2
LIMIT 1";

/// Change-only: an identical classification leaves the row, including
/// `observed_at_ms`, untouched. `auth_env_key` is nullable, so it compares with `IS NOT`.
pub const UPSERT_CLAUDE_SESSION_AUTH_STATE_SQL: &str = "INSERT INTO claude_session_auth_state (
session_id,
provider,
billing_mode,
auth_env_key,
confidence,
observed_at_ms
) VALUES (?1, ?2, ?3, ?4, ?5, ?6)
ON CONFLICT (session_id) DO UPDATE SET
provider = excluded.provider,
billing_mode = excluded.billing_mode,
auth_env_key = excluded.auth_env_key,
confidence = excluded.confidence,
observed_at_ms = excluded.observed_at_ms
WHERE excluded.provider <> claude_session_auth_state.provider
OR excluded.billing_mode <> claude_session_auth_state.billing_mode
OR excluded.auth_env_key IS NOT claude_session_auth_state.auth_env_key
OR excluded.confidence <> claude_session_auth_state.confidence";

pub const SELECT_CLAUDE_SESSION_AUTH_STATE_SQL: &str = "SELECT
session_id,
provider,
billing_mode,
auth_env_key,
confidence,
observed_at_ms
FROM claude_session_auth_state
WHERE session_id = ?1
LIMIT 1";

const CONVERSATION_TEXT_EVENT_OPERATION_NAME: &str = "insert conversation text event";
const CONVERSATION_TEXT_EVENT_RETRY_HINT: &str = "retry after the database lock clears; if the issue persists, stop other SCE processes using this database and rerun the command";

Expand Down Expand Up @@ -179,6 +212,22 @@ pub struct ClaudeModelStateObservation {
pub observed_at_ms: i64,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClaudeSessionAuthState {
pub session_id: String,
pub provider: AuthProvider,
pub billing_mode: BillingMode,
pub auth_env_key: Option<AuthEnvKey>,
pub confidence: DetectionConfidence,
pub observed_at_ms: i64,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ClaudeSessionAuthStateUpsertOutcome {
Upserted { rows_changed: u64 },
SkippedMissingMigration,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DiffTracePatchRow {
pub id: i64,
Expand Down Expand Up @@ -426,6 +475,71 @@ fn claude_model_state_observation_from_turso(
})
}

async fn upsert_claude_session_auth_state_with<M: DbSpec>(
db: &TursoDb<M>,
input: ClaudeSessionAuthState,
) -> Result<u64> {
db.execute(
UPSERT_CLAUDE_SESSION_AUTH_STATE_SQL,
(
input.session_id,
input.provider.as_str(),
input.billing_mode.as_str(),
input.auth_env_key.map(AuthEnvKey::as_str),
input.confidence.as_str(),
input.observed_at_ms,
),
)
.await
}

async fn claude_session_auth_state_by_session_with<M: DbSpec>(
db: &TursoDb<M>,
session_id: &str,
) -> Result<Option<ClaudeSessionAuthState>> {
let rows = db
.query_map(
SELECT_CLAUDE_SESSION_AUTH_STATE_SQL,
(session_id,),
claude_session_auth_state_from_turso,
)
.await?;

Ok(rows.into_iter().next())
}

fn claude_session_auth_state_from_turso(row: &turso::Row) -> Result<ClaudeSessionAuthState> {
Ok(ClaudeSessionAuthState {
session_id: row
.get(0)
.context("failed to read claude_session_auth_state.session_id")?,
provider: AuthProvider::from_str(
row.get::<String>(1)
.context("failed to read claude_session_auth_state.provider")?
.as_str(),
)?,
billing_mode: BillingMode::from_str(
row.get::<String>(2)
.context("failed to read claude_session_auth_state.billing_mode")?
.as_str(),
)?,
auth_env_key: row
.get::<Option<String>>(3)
.context("failed to read claude_session_auth_state.auth_env_key")?
.as_deref()
.map(AuthEnvKey::from_str)
.transpose()?,
confidence: DetectionConfidence::from_str(
row.get::<String>(4)
.context("failed to read claude_session_auth_state.confidence")?
.as_str(),
)?,
observed_at_ms: row
.get(5)
.context("failed to read claude_session_auth_state.observed_at_ms")?,
})
}

async fn insert_messages_with<M: DbSpec>(
db: &TursoDb<M>,
inputs: Vec<InsertMessageInsert>,
Expand Down
96 changes: 94 additions & 2 deletions cli/src/services/agent_trace_db/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ use super::{
diff_trace_patches_before_commit_with, insert_agent_trace_with,
insert_conversation_text_event_with, insert_diff_trace_with, insert_messages_with,
insert_parts_with, insert_post_commit_patch_intersection_with, recent_diff_trace_patches_with,
upsert_claude_model_state_with, AgentTraceInsert, ClaudeModelStateObservation,
upsert_claude_model_state_with, upsert_claude_session_auth_state_with, AgentTraceInsert,
ClaudeModelStateObservation, ClaudeSessionAuthState, ClaudeSessionAuthStateUpsertOutcome,
CommitTimeCutoff, DiffTraceInsert, InsertMessageInsert, InsertPartInsert,
PostCommitPatchIntersectionInsert, RecentDiffTracePatches,
};
Expand All @@ -23,6 +24,9 @@ const SELECT_REPOSITORY_METADATA_SQL: &str =
"SELECT repository_id, source_instance_id FROM repository_metadata WHERE id = 1";
const SELECT_SQLITE_OBJECT_SQL: &str =
"SELECT name FROM sqlite_master WHERE type = ?1 AND name = ?2 LIMIT 1";
const SELECT_APPLIED_MIGRATION_IDS_SQL: &str = "SELECT id FROM __sce_migrations";
const HOOK_RUNTIME_OPTIONAL_MIGRATION_ID: &str = "008_claude_session_auth_state";
const SELECT_MIGRATION_APPLIED_SQL: &str = "SELECT id FROM __sce_migrations WHERE id = ?1 LIMIT 1";
const RECORD_REPOSITORY_SCHEMA_MIGRATION_SQL: &str =
"INSERT OR IGNORE INTO __sce_migrations (id) VALUES ('001_repository_schema')";
const REQUIRED_REPOSITORY_SCHEMA_TABLES: &[&str] = &[
Expand Down Expand Up @@ -246,7 +250,56 @@ impl RepositoryAgentTraceDb {
.await
}

/// Hook-runtime readiness: strict parity, or strict parity minus exactly
/// [`HOOK_RUNTIME_OPTIONAL_MIGRATION_ID`], so hooks keep working until
/// `sce setup` applies that migration. Setup, repair, and doctor stay strict.
pub async fn ensure_schema_ready_for_hook_runtime(&self) -> Result<()> {
let strict = self.ensure_schema_ready_for_hooks().await;
if strict.is_err()
&& self
.ledger_lacks_only_hook_runtime_optional_migration()
.await?
{
return Ok(());
}
strict
}

async fn ledger_lacks_only_hook_runtime_optional_migration(&self) -> Result<bool> {
if !self
.sqlite_object_exists("table", "__sce_migrations")
.await?
{
return Ok(false);
}
let mut applied_ids = self
.query_map(SELECT_APPLIED_MIGRATION_IDS_SQL, (), |row| {
row.get::<String>(0).map_err(Into::into)
})
.await?;
applied_ids.sort_unstable();
let mut expected_ids = generated_migrations::AGENT_TRACE_REPOSITORY_MIGRATIONS
.iter()
.map(|(id, _)| *id)
.filter(|id| *id != HOOK_RUNTIME_OPTIONAL_MIGRATION_ID)
.collect::<Vec<_>>();
expected_ids.sort_unstable();
Ok(applied_ids == expected_ids)
}

pub async fn repair_missing_repository_schema_migration_metadata(&self) -> Result<()> {
self.record_repository_schema_migration_metadata().await?;
self.ensure_schema_ready_for_hooks().await
}

pub async fn repair_missing_repository_schema_migration_metadata_for_hook_runtime(
&self,
) -> Result<()> {
self.record_repository_schema_migration_metadata().await?;
self.ensure_schema_ready_for_hook_runtime().await
}

async fn record_repository_schema_migration_metadata(&self) -> Result<()> {
for table in REQUIRED_REPOSITORY_SCHEMA_TABLES {
if !self.sqlite_object_exists("table", table).await? {
anyhow::bail!(
Expand All @@ -258,7 +311,7 @@ impl RepositoryAgentTraceDb {

self.execute(RECORD_REPOSITORY_SCHEMA_MIGRATION_SQL, ())
.await?;
self.ensure_schema_ready_for_hooks().await
Ok(())
}

async fn sqlite_object_exists(&self, object_type: &str, name: &str) -> Result<bool> {
Expand Down Expand Up @@ -370,6 +423,45 @@ impl RepositoryAgentTraceDb {
super::claude_model_state_by_session_and_agent_with(self, session_id, agent_id).await
}

/// Skips without writing when the hook-runtime-optional migration that
/// creates `claude_session_auth_state` has not been applied yet.
pub async fn upsert_claude_session_auth_state(
&self,
input: ClaudeSessionAuthState,
) -> Result<ClaudeSessionAuthStateUpsertOutcome> {
if !self
.migration_applied(HOOK_RUNTIME_OPTIONAL_MIGRATION_ID)
.await?
{
return Ok(ClaudeSessionAuthStateUpsertOutcome::SkippedMissingMigration);
}
let rows_changed = upsert_claude_session_auth_state_with(self, input).await?;
Ok(ClaudeSessionAuthStateUpsertOutcome::Upserted { rows_changed })
}

#[cfg_attr(
not(test),
expect(
dead_code,
reason = "latest-state read interface has no production reader until a future export change"
)
)]
pub async fn claude_session_auth_state_by_session(
&self,
session_id: &str,
) -> Result<Option<ClaudeSessionAuthState>> {
super::claude_session_auth_state_by_session_with(self, session_id).await
}

async fn migration_applied(&self, migration_id: &str) -> Result<bool> {
let rows = self
.query_map(SELECT_MIGRATION_APPLIED_SQL, (migration_id,), |row| {
row.get::<String>(0).map_err(Into::into)
})
.await?;
Ok(!rows.is_empty())
}

pub async fn recent_diff_trace_patches(
&self,
cutoff_time_ms: i64,
Expand Down
Loading
Loading