P0: workspace scaffold, CI gates, tc-domain, tc-config, tc-db vs real Postgres
- Cargo workspace with 1250-line and no-placeholder CI gates wired first - tc-domain: id newtypes, SessionKey codec (proptest round-trip), Role, GatedCategory (spec §15), AccessPolicy, core entities - tc-config: figment TOML+env config, DeployTarget/provider/auth selection with semantic validation - migrations/0001: full spec §14 schema incl. DB-enforced append-only audit_log - tc-db: compile-time-checked sqlx repos (workspaces, users, agents+policies, credits, audit) with committed .sqlx offline metadata - tc-testkit: per-test real-Postgres databases (testcontainers or TC_TEST_DATABASE_URL), embedded migrations Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
use sqlx::PgPool;
|
||||
use tc_domain::{
|
||||
AccessPolicy, Agent, AgentId, AgentScope, AgentStatus, HumanScope, UserId, WorkspaceId,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::DbError;
|
||||
|
||||
/// Inserts an agent together with its access policy in one transaction —
|
||||
/// an agent without a policy must never be observable (§7.7).
|
||||
pub async fn insert(pool: &PgPool, agent: &Agent, policy: &AccessPolicy) -> Result<(), DbError> {
|
||||
let (humans_mode, human_ids): (&str, Vec<Uuid>) = match &policy.humans {
|
||||
HumanScope::EntireTeam => ("entire_team", Vec::new()),
|
||||
HumanScope::Specific(ids) => ("specific", ids.iter().map(UserId::as_uuid).collect()),
|
||||
};
|
||||
let (agents_mode, agent_ids): (&str, Vec<Uuid>) = match &policy.agents {
|
||||
AgentScope::Any => ("any", Vec::new()),
|
||||
AgentScope::Specific(ids) => ("specific", ids.iter().map(AgentId::as_uuid).collect()),
|
||||
};
|
||||
|
||||
let mut tx = pool.begin().await.map_err(DbError::from)?;
|
||||
sqlx::query!(
|
||||
"INSERT INTO agents
|
||||
(id, workspace_id, name, job_title, system_prompt, avatar, accent,
|
||||
wallpaper, managed_by, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",
|
||||
agent.id.as_uuid(),
|
||||
agent.workspace_id.as_uuid(),
|
||||
agent.name,
|
||||
agent.job_title,
|
||||
agent.system_prompt,
|
||||
agent.avatar,
|
||||
agent.accent,
|
||||
agent.wallpaper,
|
||||
agent.managed_by.as_uuid(),
|
||||
agent.status.as_str(),
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
sqlx::query!(
|
||||
"INSERT INTO access_policies
|
||||
(agent_id, humans_mode, human_ids, agents_mode, agent_ids)
|
||||
VALUES ($1, $2, $3, $4, $5)",
|
||||
agent.id.as_uuid(),
|
||||
humans_mode,
|
||||
&human_ids,
|
||||
agents_mode,
|
||||
&agent_ids,
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
tx.commit().await.map_err(DbError::from)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The left-rail roster (§4): live agents of a workspace, oldest first.
|
||||
pub async fn roster(pool: &PgPool, workspace_id: WorkspaceId) -> Result<Vec<Agent>, DbError> {
|
||||
let rows = sqlx::query!(
|
||||
"SELECT id, workspace_id, name, job_title, system_prompt, avatar,
|
||||
accent, wallpaper, managed_by, status
|
||||
FROM agents
|
||||
WHERE workspace_id = $1 AND deleted_at IS NULL
|
||||
ORDER BY created_at, id",
|
||||
workspace_id.as_uuid(),
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|row| Agent {
|
||||
id: AgentId::from(row.id),
|
||||
workspace_id: WorkspaceId::from(row.workspace_id),
|
||||
name: row.name,
|
||||
job_title: row.job_title,
|
||||
system_prompt: row.system_prompt,
|
||||
avatar: row.avatar,
|
||||
accent: row.accent,
|
||||
wallpaper: row.wallpaper,
|
||||
managed_by: UserId::from(row.managed_by),
|
||||
status: row.status.parse().expect("status CHECK constraint"),
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub async fn access_policy(pool: &PgPool, agent_id: AgentId) -> Result<AccessPolicy, DbError> {
|
||||
let row = sqlx::query!(
|
||||
"SELECT humans_mode, human_ids, agents_mode, agent_ids
|
||||
FROM access_policies WHERE agent_id = $1",
|
||||
agent_id.as_uuid(),
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
let humans = if row.humans_mode == "entire_team" {
|
||||
HumanScope::EntireTeam
|
||||
} else {
|
||||
HumanScope::Specific(row.human_ids.into_iter().map(UserId::from).collect())
|
||||
};
|
||||
let agents = if row.agents_mode == "any" {
|
||||
AgentScope::Any
|
||||
} else {
|
||||
AgentScope::Specific(row.agent_ids.into_iter().map(AgentId::from).collect())
|
||||
};
|
||||
Ok(AccessPolicy { humans, agents })
|
||||
}
|
||||
|
||||
pub async fn set_status(
|
||||
pool: &PgPool,
|
||||
agent_id: AgentId,
|
||||
status: AgentStatus,
|
||||
) -> Result<(), DbError> {
|
||||
let result = sqlx::query!(
|
||||
"UPDATE agents SET status = $2 WHERE id = $1 AND deleted_at IS NULL",
|
||||
agent_id.as_uuid(),
|
||||
status.as_str(),
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
if result.rows_affected() == 0 {
|
||||
return Err(DbError::NotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deleting a claw is destructive and gated (§7.7); rows are kept for audit.
|
||||
pub async fn soft_delete(pool: &PgPool, agent_id: AgentId) -> Result<(), DbError> {
|
||||
let result = sqlx::query!(
|
||||
"UPDATE agents SET deleted_at = now(), status = 'offline'
|
||||
WHERE id = $1 AND deleted_at IS NULL",
|
||||
agent_id.as_uuid(),
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
if result.rows_affected() == 0 {
|
||||
return Err(DbError::NotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
use sqlx::PgPool;
|
||||
use tc_domain::{AgentId, UserId, WorkspaceId};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::DbError;
|
||||
|
||||
/// Who performed an audited action (§15: every decision is attributable).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub enum Actor {
|
||||
User(UserId),
|
||||
Agent(AgentId),
|
||||
System,
|
||||
}
|
||||
|
||||
impl Actor {
|
||||
fn kind(&self) -> &'static str {
|
||||
match self {
|
||||
Actor::User(_) => "user",
|
||||
Actor::Agent(_) => "agent",
|
||||
Actor::System => "system",
|
||||
}
|
||||
}
|
||||
|
||||
fn id(&self) -> Option<Uuid> {
|
||||
match self {
|
||||
Actor::User(id) => Some(id.as_uuid()),
|
||||
Actor::Agent(id) => Some(id.as_uuid()),
|
||||
Actor::System => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Appends an audit entry and returns its sequence id. The table rejects
|
||||
/// UPDATE/DELETE at the database level (see migration 0001).
|
||||
pub async fn append(
|
||||
pool: &PgPool,
|
||||
workspace_id: WorkspaceId,
|
||||
actor: Actor,
|
||||
event_type: &str,
|
||||
subject_type: &str,
|
||||
subject_id: &str,
|
||||
detail: serde_json::Value,
|
||||
) -> Result<i64, DbError> {
|
||||
let row = sqlx::query!(
|
||||
"INSERT INTO audit_log
|
||||
(workspace_id, actor_kind, actor_id, event_type, subject_type,
|
||||
subject_id, detail)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
RETURNING id",
|
||||
workspace_id.as_uuid(),
|
||||
actor.kind(),
|
||||
actor.id(),
|
||||
event_type,
|
||||
subject_type,
|
||||
subject_id,
|
||||
detail,
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(row.id)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use sqlx::PgPool;
|
||||
use tc_domain::WorkspaceId;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::DbError;
|
||||
|
||||
/// Available credits = sum of remaining balances across all lots; credits
|
||||
/// never expire (§8.4).
|
||||
pub async fn balance(pool: &PgPool, workspace_id: WorkspaceId) -> Result<i64, DbError> {
|
||||
let row = sqlx::query!(
|
||||
r#"SELECT COALESCE(SUM(remaining), 0)::BIGINT AS "balance!"
|
||||
FROM credit_lots WHERE workspace_id = $1"#,
|
||||
workspace_id.as_uuid(),
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(row.balance)
|
||||
}
|
||||
|
||||
pub async fn add_lot(
|
||||
pool: &PgPool,
|
||||
workspace_id: WorkspaceId,
|
||||
amount: i64,
|
||||
source: &str,
|
||||
) -> Result<(), DbError> {
|
||||
sqlx::query!(
|
||||
"INSERT INTO credit_lots (id, workspace_id, amount, remaining, source)
|
||||
VALUES ($1, $2, $3, $3, $4)",
|
||||
Uuid::now_v7(),
|
||||
workspace_id.as_uuid(),
|
||||
sqlx::types::BigDecimal::from(amount),
|
||||
source,
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod agents;
|
||||
pub mod audit;
|
||||
pub mod credits;
|
||||
pub mod users;
|
||||
pub mod workspaces;
|
||||
@@ -0,0 +1,99 @@
|
||||
use sqlx::PgPool;
|
||||
use tc_domain::{Role, User, UserId, WorkspaceId};
|
||||
|
||||
use crate::DbError;
|
||||
|
||||
fn role_to_str(role: Role) -> &'static str {
|
||||
match role {
|
||||
Role::Owner => "owner",
|
||||
Role::Member => "member",
|
||||
}
|
||||
}
|
||||
|
||||
fn role_from_str(s: &str) -> Role {
|
||||
// The CHECK constraint guarantees only these two values exist.
|
||||
if s == "owner" {
|
||||
Role::Owner
|
||||
} else {
|
||||
Role::Member
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts a user. `created_at` is assigned by the database; the value on
|
||||
/// the input struct is ignored.
|
||||
pub async fn insert(pool: &PgPool, user: &User) -> Result<(), DbError> {
|
||||
sqlx::query!(
|
||||
"INSERT INTO users (id, workspace_id, email, role, display_name)
|
||||
VALUES ($1, $2, $3, $4, $5)",
|
||||
user.id.as_uuid(),
|
||||
user.workspace_id.as_uuid(),
|
||||
user.email,
|
||||
role_to_str(user.role),
|
||||
user.display_name,
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get(pool: &PgPool, id: UserId) -> Result<User, DbError> {
|
||||
let row = sqlx::query!(
|
||||
"SELECT id, workspace_id, email, role, display_name, created_at
|
||||
FROM users WHERE id = $1",
|
||||
id.as_uuid(),
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(User {
|
||||
id: UserId::from(row.id),
|
||||
workspace_id: WorkspaceId::from(row.workspace_id),
|
||||
email: row.email,
|
||||
role: role_from_str(&row.role),
|
||||
display_name: row.display_name,
|
||||
created_at: row.created_at,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn find_by_email(pool: &PgPool, email: &str) -> Result<User, DbError> {
|
||||
let row = sqlx::query!(
|
||||
"SELECT id, workspace_id, email, role, display_name, created_at
|
||||
FROM users WHERE email = $1",
|
||||
email,
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(User {
|
||||
id: UserId::from(row.id),
|
||||
workspace_id: WorkspaceId::from(row.workspace_id),
|
||||
email: row.email,
|
||||
role: role_from_str(&row.role),
|
||||
display_name: row.display_name,
|
||||
created_at: row.created_at,
|
||||
})
|
||||
}
|
||||
|
||||
/// Members table for the Team page (§8.3), in join order.
|
||||
pub async fn list_by_workspace(
|
||||
pool: &PgPool,
|
||||
workspace_id: WorkspaceId,
|
||||
) -> Result<Vec<User>, DbError> {
|
||||
let rows = sqlx::query!(
|
||||
"SELECT id, workspace_id, email, role, display_name, created_at
|
||||
FROM users WHERE workspace_id = $1
|
||||
ORDER BY created_at, id",
|
||||
workspace_id.as_uuid(),
|
||||
)
|
||||
.fetch_all(pool)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|row| User {
|
||||
id: UserId::from(row.id),
|
||||
workspace_id: WorkspaceId::from(row.workspace_id),
|
||||
email: row.email,
|
||||
role: role_from_str(&row.role),
|
||||
display_name: row.display_name,
|
||||
created_at: row.created_at,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
use sqlx::PgPool;
|
||||
use tc_domain::{Workspace, WorkspaceId};
|
||||
|
||||
use crate::DbError;
|
||||
|
||||
pub async fn insert(pool: &PgPool, workspace: &Workspace) -> Result<(), DbError> {
|
||||
sqlx::query!(
|
||||
"INSERT INTO workspaces (id, name, plan) VALUES ($1, $2, $3)",
|
||||
workspace.id.as_uuid(),
|
||||
workspace.name,
|
||||
workspace.plan,
|
||||
)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get(pool: &PgPool, id: WorkspaceId) -> Result<Workspace, DbError> {
|
||||
let row = sqlx::query!(
|
||||
"SELECT id, name, plan FROM workspaces WHERE id = $1",
|
||||
id.as_uuid(),
|
||||
)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(Workspace {
|
||||
id: WorkspaceId::from(row.id),
|
||||
name: row.name,
|
||||
plan: row.plan,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user