diff --git a/Cargo.lock b/Cargo.lock index 29ae3504..49cfe440 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -249,6 +249,21 @@ dependencies = [ "zstd", ] +[[package]] +name = "atomic-facade" +version = "0.13.0" +dependencies = [ + "atomic-canonical", + "atomic-core", + "atomic-repository", + "blake3", + "log", + "serde", + "serde_json", + "tempfile", + "thiserror 1.0.69", +] + [[package]] name = "atomic-identity" version = "0.13.0" diff --git a/Cargo.toml b/Cargo.toml index 3ce1a156..dc9fdfc1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ members = [ "atomic-cli", "atomic-core", "atomic-config", + "atomic-facade", "atomic-identity", "atomic-remote", "atomic-repository", @@ -28,6 +29,7 @@ atomic-agent = { path = "atomic-agent" } atomic-canonical = { path = "atomic-canonical" } atomic-core = { path = "atomic-core" } atomic-config = { path = "atomic-config" } +atomic-facade = { path = "atomic-facade" } atomic-identity = { path = "atomic-identity" } atomic-remote = { path = "atomic-remote" } atomic-repository = { path = "atomic-repository" } diff --git a/atomic-facade/Cargo.toml b/atomic-facade/Cargo.toml new file mode 100644 index 00000000..3f1b24fb --- /dev/null +++ b/atomic-facade/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "atomic-facade" +description = "Native API layer over Atomic's command-level read operations — embed the CLI's reads in local UIs, tools, and agent harnesses instead of shelling out" +version.workspace = true +edition.workspace = true +authors.workspace = true +license.workspace = true +repository.workspace = true +homepage.workspace = true +rust-version.workspace = true + +[dependencies] +atomic-canonical = { workspace = true } +atomic-core = { workspace = true } +atomic-repository = { workspace = true } + +serde = { workspace = true } +serde_json = { workspace = true } +thiserror = { workspace = true } +blake3 = { workspace = true } +log = { workspace = true } + +[dev-dependencies] +tempfile = { workspace = true } diff --git a/atomic-facade/src/attestations.rs b/atomic-facade/src/attestations.rs new file mode 100644 index 00000000..be377984 --- /dev/null +++ b/atomic-facade/src/attestations.rs @@ -0,0 +1,323 @@ +//! Attestation dual-read for intents and memories. +//! +//! An attestation is stored as a first-class tracked vault entry +//! (`attestations//attested.md` for intents, +//! `attestations/memory//attested.md` for memories) whose body is the +//! signed JSON-LD node. Pre-upgrade attestations live in a legacy sidecar +//! under `/canonical/…/attested.jsonld`. Reads prefer the tracked +//! entry and fall back to the sidecar, classifying the result against the +//! current source content (Fresh vs Stale). Malformed artifacts fail open +//! (logged, treated as absent) so a read still works on the raw entry. + +use std::path::PathBuf; + +use atomic_canonical::{CanonicalNode, MemoryNode}; +use atomic_core::pristine::VaultEntry; +use atomic_repository::Repository; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use serde_json::{Map, Value}; + +use crate::error::{FacadeError, FacadeResult}; + +/// The two lift inputs pulled off a stored `VaultEntry`. +#[derive(Debug, Clone)] +pub struct LiftInputs { + /// The parsed frontmatter spine (a JSON object). + pub frontmatter: Map, + /// The markdown body (without any frontmatter block). + pub body: String, +} + +/// Parse a `VaultEntry` into the frontmatter map + body the lift consumes. +pub fn inputs_from_entry(kind: &'static str, entry: &VaultEntry) -> FacadeResult { + let frontmatter: Map = + serde_json::from_str(&entry.frontmatter_json).map_err(|e| FacadeError::Malformed { + message: format!("{kind} frontmatter is not valid JSON: {e}"), + })?; + let body = String::from_utf8_lossy(&entry.content_bytes).into_owned(); + Ok(LiftInputs { frontmatter, body }) +} + +/// Digest of (frontmatter + body) recorded at attest time; recomputed on read +/// to classify an attestation as Fresh or Stale. NOT the vault content hash. +pub fn source_content_hash(inputs: &LiftInputs) -> String { + let fm = serde_json::to_string(&inputs.frontmatter).unwrap_or_default(); + let mut hasher = blake3::Hasher::new(); + hasher.update(fm.as_bytes()); + hasher.update(b"\0"); + hasher.update(inputs.body.as_bytes()); + format!("blake3:{}", hasher.finalize().to_hex()) +} + +/// Freshness of an attestation relative to the current source. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum AttestationStatus { + /// No attestation on disk (tracked or legacy). + None, + /// Attestation present; recorded source hash matches the current source. + Fresh, + /// Attestation present but the source changed since it was signed. + Stale, +} + +/// A loaded attestation: the signed node plus its freshness classification. +#[derive(Debug)] +pub enum Attested { + /// No attestation found. + None, + /// Present and matching the current source. + Fresh(Box), + /// Present but the source changed since signing. + Stale(Box), +} + +impl Attested { + /// The serializable status. + pub fn status(&self) -> AttestationStatus { + match self { + Self::None => AttestationStatus::None, + Self::Fresh(_) => AttestationStatus::Fresh, + Self::Stale(_) => AttestationStatus::Stale, + } + } + + /// The signed node, if present. + pub fn node(&self) -> Option<&N> { + match self { + Self::None => None, + Self::Fresh(n) | Self::Stale(n) => Some(n), + } + } +} + +/// Sanitize an id for use as a directory name in attestation paths. Keeps +/// ASCII alphanumerics, `-` and `_`; everything else becomes `_`. +pub fn sanitize_id(id: &str) -> String { + id.chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '-' || c == '_' { + c + } else { + '_' + } + }) + .collect() +} + +// ── Intent attestations ───────────────────────────────────────────────── + +/// Normalize an intent id via the repository resolver, falling back to the +/// uppercased raw arg when nothing resolves (matches the CLI's `attest`). +pub fn normalized_intent_id(repo: &Repository, id: &str) -> String { + repo.resolve_intent_key(id) + .unwrap_or_else(|_| id.to_uppercase()) +} + +/// Tracked-vault path of an intent's attestation. +pub fn intent_attestation_vault_path(repo: &Repository, id: &str) -> String { + format!( + "attestations/{}/attested.md", + sanitize_id(&normalized_intent_id(repo, id)) + ) +} + +/// Load an intent's attestation, preferring the tracked vault entry and +/// falling back to the legacy sidecar(s). +pub fn load_intent_attestation( + repo: &Repository, + id: &str, + inputs: &LiftInputs, +) -> FacadeResult> { + let vpath = intent_attestation_vault_path(repo, id); + if let Some(found) = load_tracked(repo, &vpath, inputs)? { + return Ok(found); + } + + let normalized = intent_sidecar_path(repo, &normalized_intent_id(repo, id)); + let raw = intent_sidecar_path(repo, id); + let candidates = if raw == normalized { + vec![normalized] + } else { + vec![normalized, raw] + }; + load_legacy_sidecar(&candidates, inputs) +} + +fn intent_sidecar_path(repo: &Repository, id: &str) -> PathBuf { + repo.dot_dir() + .join("canonical") + .join("intents") + .join(sanitize_id(id)) + .join("attested.jsonld") +} + +// ── Memory attestations ───────────────────────────────────────────────── + +/// Normalize a bare id, `memory/`, `.md`, or `memory/.md` to the +/// canonical vault path `memory/.md`. +pub fn normalize_memory_path(id_or_path: &str) -> String { + let without_prefix = id_or_path.strip_prefix("memory/").unwrap_or(id_or_path); + let stem = without_prefix.strip_suffix(".md").unwrap_or(without_prefix); + format!("memory/{stem}.md") +} + +/// The `` stem for any accepted memory path form. +pub fn memory_id(id_or_path: &str) -> String { + let path = normalize_memory_path(id_or_path); + path.strip_prefix("memory/") + .and_then(|s| s.strip_suffix(".md")) + .unwrap_or(&path) + .to_string() +} + +/// Tracked-vault path of a memory's attestation (namespaced under +/// `attestations/memory/` so memory ids never collide with intent keys). +pub fn memory_attestation_vault_path(id_or_path: &str) -> String { + format!( + "attestations/memory/{}/attested.md", + sanitize_id(&memory_id(id_or_path)) + ) +} + +/// Load a memory's attestation, preferring the tracked vault entry and +/// falling back to the legacy sidecar. +pub fn load_memory_attestation( + repo: &Repository, + id_or_path: &str, + inputs: &LiftInputs, +) -> FacadeResult> { + let vpath = memory_attestation_vault_path(id_or_path); + if let Some(found) = load_tracked(repo, &vpath, inputs)? { + return Ok(found); + } + + let sidecar = repo + .dot_dir() + .join("canonical") + .join("memory") + .join(sanitize_id(&memory_id(id_or_path))) + .join("attested.jsonld"); + load_legacy_sidecar(&[sidecar], inputs) +} + +// ── Shared read machinery ─────────────────────────────────────────────── + +/// Read + classify the tracked vault entry at `vpath`. `Ok(None)` means "no +/// usable tracked entry — try the legacy sidecar". +fn load_tracked( + repo: &Repository, + vpath: &str, + inputs: &LiftInputs, +) -> FacadeResult>> { + let Some(entry) = repo.vault_retrieve(vpath)? else { + return Ok(None); + }; + + let raw = String::from_utf8_lossy(&entry.content_bytes); + let node: N = match serde_json::from_str(raw.trim_end()) { + Ok(node) => node, + Err(e) => { + log::warn!("ignoring malformed tracked attestation {vpath}: {e}"); + return Ok(None); + } + }; + + let recorded = serde_json::from_str::(&entry.frontmatter_json) + .ok() + .and_then(|v| { + v.get("sourceContentHash") + .and_then(Value::as_str) + .map(str::to_owned) + }); + Ok(Some(classify(node, recorded.as_deref(), inputs))) +} + +/// Read + classify the first existing legacy sidecar. Missing/corrupt +/// sidecars fail open to `Attested::None`. +fn load_legacy_sidecar( + candidates: &[PathBuf], + inputs: &LiftInputs, +) -> FacadeResult> { + let Some(path) = candidates.iter().find(|p| p.exists()) else { + return Ok(Attested::None); + }; + + // An existing-but-unreadable sidecar (e.g. permissions) is a real IO + // failure, not "no attestation" — same hard error as the CLI bridge. + let raw = std::fs::read_to_string(path) + .map_err(|e| FacadeError::Repository(atomic_repository::RepositoryError::Io(e)))?; + let artifact: Value = match serde_json::from_str(&raw) { + Ok(v) => v, + Err(e) => { + log::warn!( + "ignoring unparsable attestation sidecar {}: {e}", + path.display() + ); + return Ok(Attested::None); + } + }; + let Some(node_val) = artifact.get("node").cloned() else { + log::warn!( + "attestation sidecar {} has no 'node' — ignoring", + path.display() + ); + return Ok(Attested::None); + }; + let node: N = match serde_json::from_value(node_val) { + Ok(n) => n, + Err(e) => { + log::warn!( + "ignoring malformed attestation node in {}: {e}", + path.display() + ); + return Ok(Attested::None); + } + }; + + let recorded = artifact + .get("source") + .and_then(|s| s.get("sourceContentHash")) + .and_then(Value::as_str); + Ok(classify(node, recorded, inputs)) +} + +fn classify(node: N, recorded: Option<&str>, inputs: &LiftInputs) -> Attested { + let current = source_content_hash(inputs); + match recorded { + Some(h) if h == current => Attested::Fresh(Box::new(node)), + _ => Attested::Stale(Box::new(node)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn memory_path_normalization() { + for form in ["notes", "notes.md", "memory/notes", "memory/notes.md"] { + assert_eq!(normalize_memory_path(form), "memory/notes.md"); + assert_eq!(memory_id(form), "notes"); + } + } + + #[test] + fn sanitize_replaces_non_identifier_chars() { + assert_eq!(sanitize_id("PIMO::user::1"), "PIMO__user__1"); + assert_eq!(sanitize_id("ok-id_2"), "ok-id_2"); + } + + #[test] + fn attestation_status_serializes_lowercase() { + assert_eq!( + serde_json::to_string(&AttestationStatus::Fresh).unwrap(), + "\"fresh\"" + ); + assert_eq!( + serde_json::to_string(&AttestationStatus::None).unwrap(), + "\"none\"" + ); + } +} diff --git a/atomic-facade/src/changes.rs b/atomic-facade/src/changes.rs new file mode 100644 index 00000000..080724ae --- /dev/null +++ b/atomic-facade/src/changes.rs @@ -0,0 +1,216 @@ +//! Change detail and history-log read operations. +//! +//! DTO field names and skip rules mirror `atomic change -f json` and +//! `atomic log -f json`. + +use atomic_core::change::{Author, Change, GraphOp}; +use atomic_core::types::{Base32, Hash}; +use atomic_repository::{HistoryEntry, HistoryOptions, Repository}; +use serde::{Deserialize, Serialize}; + +use crate::error::FacadeResult; +use crate::identifier::resolve_change; +use crate::provenance::ProvenanceDto; + +/// A change author. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AuthorDto { + /// The author's name. + pub name: String, + /// The author's email (if available). + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, +} + +impl From<&Author> for AuthorDto { + fn from(author: &Author) -> Self { + Self { + name: author.name.clone(), + email: author.email.clone(), + } + } +} + +/// A one-line summary of a graph op inside a change. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HunkSummaryDto { + /// Op type (FileAdd, FileDel, FileMove, Edit, …). + pub hunk_type: String, + /// Path affected (if applicable). + #[serde(skip_serializing_if = "Option::is_none")] + pub path: Option, +} + +/// Full detail of a single change. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChangeDetail { + /// Full base32 hash. + pub hash: String, + /// The change message. + pub message: String, + /// The description (if any). + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + /// The authors. + pub authors: Vec, + /// Timestamp (RFC 3339). + pub timestamp: String, + /// Dependencies as base32 hashes. + pub dependencies: Vec, + /// Graph-op summaries. + pub hunks: Vec, + /// Whether the change carries AI provenance. + pub has_provenance: bool, + /// First provenance record (if any). + #[serde(skip_serializing_if = "Option::is_none")] + pub provenance: Option, + /// Unhashed payload (agent turn transcript etc.), verbatim. + #[serde(skip_serializing_if = "Option::is_none")] + pub unhashed: Option, + /// Sequence number on the resolved view (if the change is on its log). + #[serde(skip_serializing_if = "Option::is_none")] + pub sequence: Option, +} + +impl ChangeDetail { + /// Build from a loaded change. + pub fn from_change(change: &Change, hash: &Hash, sequence: Option) -> Self { + Self { + hash: hash.to_base32(), + message: change.hashed.header.message.clone(), + description: change.hashed.header.description.clone(), + authors: change + .hashed + .header + .authors + .iter() + .map(AuthorDto::from) + .collect(), + timestamp: change.hashed.header.timestamp.to_rfc3339(), + dependencies: change + .hashed + .dependencies + .iter() + .map(Hash::to_base32) + .collect(), + hunks: change.hashed.hunks.iter().map(hunk_summary).collect(), + has_provenance: change.has_provenance(), + provenance: change.hashed.provenance.first().map(ProvenanceDto::from), + unhashed: change.unhashed.clone(), + sequence, + } + } +} + +/// One entry of a view's history log. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct LogEntry { + /// Sequence number in the view. + pub sequence: u64, + /// The change hash (base32). + pub hash: String, + /// The Merkle state after this change (base32). + pub state: String, + /// The change message (if the header was loaded). + #[serde(skip_serializing_if = "Option::is_none")] + pub message: Option, + /// The change description (if the header was loaded). + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option, + /// The authors (if the header was loaded). + #[serde(skip_serializing_if = "Vec::is_empty", default)] + pub authors: Vec, + /// Timestamp (RFC 3339, if the header was loaded). + #[serde(skip_serializing_if = "Option::is_none")] + pub timestamp: Option, + /// Whether this change is tagged. + pub is_tagged: bool, +} + +impl From<&HistoryEntry> for LogEntry { + fn from(entry: &HistoryEntry) -> Self { + Self { + sequence: entry.sequence, + hash: entry.hash.to_base32(), + state: entry.state.to_base32(), + message: entry.message().map(String::from), + description: entry.description().map(String::from), + authors: entry + .authors() + .map(|authors| authors.iter().map(AuthorDto::from).collect()) + .unwrap_or_default(), + timestamp: entry.timestamp().map(|t| t.to_rfc3339()), + is_tagged: entry.is_tagged, + } + } +} + +/// Options for [`list_log`]. +#[derive(Debug, Clone, Default)] +pub struct LogQuery { + /// View to read (default: the repository's current view). + pub view: Option, + /// Maximum number of entries (default: unlimited). + pub limit: Option, + /// Include changes inherited from ancestor views (draft views only). + pub include_inherited: bool, +} + +/// Resolve an identifier and return the change's full detail. +/// +/// `spec` accepts a hash, hash prefix, `#seq`, bare sequence, `@`, or `None` +/// for the latest change on the view. +pub fn change_detail( + repo: &Repository, + view: Option<&str>, + spec: Option<&str>, +) -> FacadeResult { + let (hash, sequence) = resolve_change(repo, view, spec)?; + let change = repo.load_change(&hash)?; + Ok(ChangeDetail::from_change(&change, &hash, sequence)) +} + +/// The view's history, newest first, with headers loaded. +pub fn list_log(repo: &Repository, query: &LogQuery) -> FacadeResult> { + let mut options = HistoryOptions::default() + .load_headers(true) + .include_inherited(query.include_inherited); + if let Some(view) = &query.view { + options = options.view(view); + } + if let Some(limit) = query.limit { + options = options.limit(limit); + } + + let entries = repo.reverse_log(options)?; + Ok(entries.iter().map(LogEntry::from).collect()) +} + +fn hunk_summary(op: &GraphOp) -> HunkSummaryDto { + let (hunk_type, path) = match op { + GraphOp::FileAdd { path, .. } => ("FileAdd", Some(path.clone())), + GraphOp::FileDel { path, .. } => ("FileDel", Some(path.clone())), + GraphOp::FileMove { path, .. } => ("FileMove", Some(path.clone())), + GraphOp::FileUndel { path, .. } => ("FileUndel", Some(path.clone())), + GraphOp::DirAdd { path, .. } => ("DirAdd", Some(path.clone())), + GraphOp::DirDel { path, .. } => ("DirDel", Some(path.clone())), + GraphOp::DirUndel { path, .. } => ("DirUndel", Some(path.clone())), + GraphOp::Edit { local, .. } => ("Edit", Some(local.path.clone())), + GraphOp::Replacement { local, .. } => ("Replacement", Some(local.path.clone())), + GraphOp::SolveNameConflict { path, .. } => ("SolveNameConflict", Some(path.clone())), + GraphOp::UnsolveNameConflict { path, .. } => ("UnsolveNameConflict", Some(path.clone())), + GraphOp::SolveOrderConflict { local, .. } => { + ("SolveOrderConflict", Some(local.path.clone())) + } + GraphOp::UnsolveOrderConflict { local, .. } => { + ("UnsolveOrderConflict", Some(local.path.clone())) + } + GraphOp::ResurrectZombies { local, .. } => ("ResurrectZombies", Some(local.path.clone())), + GraphOp::AddRoot { .. } => ("AddRoot", None), + GraphOp::DelRoot { .. } => ("DelRoot", None), + }; + HunkSummaryDto { + hunk_type: hunk_type.to_string(), + path, + } +} diff --git a/atomic-facade/src/error.rs b/atomic-facade/src/error.rs new file mode 100644 index 00000000..5f13eb75 --- /dev/null +++ b/atomic-facade/src/error.rs @@ -0,0 +1,78 @@ +//! Error type shared by every facade operation. + +use atomic_repository::RepositoryError; + +/// Errors returned by facade read operations. +/// +/// Variants are deliberately coarse and HTTP-mappable: a server embedding the +/// facade can translate `NotFound`/`ChangeNotFound`/`ViewNotFound` to 404, +/// `InvalidIdentifier`/`Ambiguous` to 400, and everything else to 500. +#[derive(Debug, thiserror::Error)] +pub enum FacadeError { + /// The underlying repository operation failed. + #[error(transparent)] + Repository(#[from] RepositoryError), + + /// The caller-supplied change/intent/memory identifier could not be parsed. + #[error("invalid identifier: {message}")] + InvalidIdentifier { + /// Why the identifier was rejected. + message: String, + }, + + /// A hash prefix matched more than one change. + #[error("ambiguous hash prefix '{prefix}' ({} matches)", matches.len())] + Ambiguous { + /// The prefix the caller supplied. + prefix: String, + /// Every full hash the prefix matched, base32-encoded. + matches: Vec, + }, + + /// No change matched the identifier. + #[error("change not found: {id}")] + ChangeNotFound { + /// The identifier as supplied by the caller. + id: String, + }, + + /// The named view does not exist. + #[error("view not found: {name}")] + ViewNotFound { + /// The view name as supplied by the caller. + name: String, + }, + + /// The named vault entity (intent, memory) does not exist. + #[error("{kind} not found: {id}")] + NotFound { + /// Entity kind ("intent", "memory"). + kind: &'static str, + /// The identifier as supplied by the caller. + id: String, + }, + + /// Stored data could not be parsed (corrupt frontmatter, bad JSON-LD). + #[error("malformed stored data: {message}")] + Malformed { + /// What failed to parse and why. + message: String, + }, +} + +impl FacadeError { + /// Whether this error maps to a caller mistake (vs. server-side failure). + pub fn is_client_error(&self) -> bool { + matches!( + self, + Self::InvalidIdentifier { .. } + | Self::Ambiguous { .. } + | Self::ChangeNotFound { .. } + | Self::ViewNotFound { .. } + | Self::NotFound { .. } + ) + } +} + +/// Result alias used across the facade. +pub type FacadeResult = Result; diff --git a/atomic-facade/src/identifier.rs b/atomic-facade/src/identifier.rs new file mode 100644 index 00000000..ad14f52a --- /dev/null +++ b/atomic-facade/src/identifier.rs @@ -0,0 +1,248 @@ +//! Change identifier parsing and resolution. +//! +//! Accepts the same identifier forms as `atomic change`/`atomic log`: +//! a full 52-character base32 hash, a hash prefix (≥ 4 chars), a sequence +//! number (`#12` or `12`), `@` for the latest change, or no identifier at +//! all (also latest). + +use atomic_core::pristine::{ViewState, ViewTxnT}; +use atomic_core::types::{Base32, Hash}; +use atomic_repository::{find_change_sequence, get_change_at_sequence, HistoryError, Repository}; + +use crate::error::{FacadeError, FacadeResult}; + +/// A parsed change identifier. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ChangeIdentifier { + /// Full 52-character base32 hash. + FullHash(Hash), + /// Hash prefix (4–51 characters, uppercased). + HashPrefix(String), + /// Sequence number in a view's history. + Sequence(u64), + /// No identifier — the most recent change on the view. + Latest, +} + +impl ChangeIdentifier { + /// Parse an identifier string. + /// + /// `None`, `""`, and `"@"` all mean [`ChangeIdentifier::Latest`]. A + /// `#`-prefixed or purely numeric string is a sequence number. A + /// 52-character base32 string is a full hash; 4–51 base32 characters + /// are a prefix. + pub fn parse(spec: Option<&str>) -> FacadeResult { + let s = match spec { + None | Some("") => return Ok(Self::Latest), + Some(s) => s.trim(), + }; + + if s == "@" { + return Ok(Self::Latest); + } + + if s.starts_with("@~") { + return Err(FacadeError::InvalidIdentifier { + message: format!("relative reference '@~N' is not yet supported: {s}"), + }); + } + + if let Some(num) = s.strip_prefix('#') { + return num.parse::().map(Self::Sequence).map_err(|_| { + FacadeError::InvalidIdentifier { + message: format!("invalid sequence number: {num}"), + } + }); + } + + if s.chars().all(|c| c.is_ascii_digit()) { + return s.parse::().map(Self::Sequence).map_err(|_| { + FacadeError::InvalidIdentifier { + message: format!("invalid sequence number: {s}"), + } + }); + } + + let upper = s.to_uppercase(); + if !upper + .chars() + .all(|c| "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".contains(c)) + { + return Err(FacadeError::InvalidIdentifier { + message: format!("invalid hash characters in '{s}' — hashes use base32 (A-Z, 2-7)"), + }); + } + + if upper.len() == 52 { + return Hash::from_base32(upper.as_bytes()) + .map(Self::FullHash) + .ok_or_else(|| FacadeError::InvalidIdentifier { + message: format!("invalid base32 hash: {s}"), + }); + } + + if upper.len() >= 4 { + Ok(Self::HashPrefix(upper)) + } else { + Err(FacadeError::InvalidIdentifier { + message: format!("hash prefix too short: '{s}' (minimum 4 characters)"), + }) + } + } +} + +/// Resolve a change identifier to a `(hash, sequence)` pair on a view. +/// +/// `view` defaults to the repository's current view. The returned sequence is +/// `None` when the change exists in the store but is not on the view's log. +pub fn resolve_change( + repo: &Repository, + view: Option<&str>, + spec: Option<&str>, +) -> FacadeResult<(Hash, Option)> { + let id = ChangeIdentifier::parse(spec)?; + let view_name = view.unwrap_or_else(|| repo.current_view()); + + match id { + ChangeIdentifier::FullHash(hash) => { + if !repo.has_change(&hash) { + return Err(FacadeError::ChangeNotFound { + id: hash.to_base32(), + }); + } + let seq = sequence_for_hash(repo, view_name, &hash)?; + Ok((hash, seq)) + } + ChangeIdentifier::HashPrefix(prefix) => resolve_prefix(repo, view_name, &prefix), + ChangeIdentifier::Sequence(seq) => { + let hash = resolve_sequence(repo, view_name, seq)?; + Ok((hash, Some(seq))) + } + ChangeIdentifier::Latest => latest_change(repo, view_name), + } +} + +fn sequence_for_hash(repo: &Repository, view_name: &str, hash: &Hash) -> FacadeResult> { + let txn = repo.pristine().read_txn().map_err(|e| { + FacadeError::Repository(atomic_repository::RepositoryError::Database(e.to_string())) + })?; + let view = get_view(&txn, view_name)?; + find_change_sequence(&txn, &view, hash).map_err(history_error) +} + +fn resolve_prefix( + repo: &Repository, + view_name: &str, + prefix: &str, +) -> FacadeResult<(Hash, Option)> { + let mut matches: Vec = Vec::new(); + for result in repo.iter_changes() { + let hash = result?; + if hash.to_base32().starts_with(prefix) { + matches.push(hash); + } + } + + match matches.as_slice() { + [] => Err(FacadeError::ChangeNotFound { + id: prefix.to_string(), + }), + [hash] => { + let seq = sequence_for_hash(repo, view_name, hash)?; + Ok((*hash, seq)) + } + many => Err(FacadeError::Ambiguous { + prefix: prefix.to_string(), + matches: many.iter().map(Hash::to_base32).collect(), + }), + } +} + +fn resolve_sequence(repo: &Repository, view_name: &str, seq: u64) -> FacadeResult { + let txn = repo.pristine().read_txn().map_err(|e| { + FacadeError::Repository(atomic_repository::RepositoryError::Database(e.to_string())) + })?; + let view = get_view(&txn, view_name)?; + let entry = get_change_at_sequence(&txn, &view, seq).map_err(|e| match e { + HistoryError::SequenceOutOfRange { sequence, max } => FacadeError::InvalidIdentifier { + message: format!( + "sequence {sequence} out of range — view has {} changes (0-{max})", + max + 1 + ), + }, + other => history_error(other), + })?; + Ok(entry.hash) +} + +fn latest_change(repo: &Repository, view_name: &str) -> FacadeResult<(Hash, Option)> { + let txn = repo.pristine().read_txn().map_err(|e| { + FacadeError::Repository(atomic_repository::RepositoryError::Database(e.to_string())) + })?; + let view = get_view(&txn, view_name)?; + + if view.change_count == 0 { + return Err(FacadeError::ChangeNotFound { + id: format!("latest change on empty view '{view_name}'"), + }); + } + + let seq = view.change_count - 1; + let entry = get_change_at_sequence(&txn, &view, seq).map_err(history_error)?; + Ok((entry.hash, Some(seq))) +} + +fn get_view(txn: &T, view_name: &str) -> FacadeResult { + txn.get_view(view_name) + .map_err(|e| { + FacadeError::Repository(atomic_repository::RepositoryError::Database(e.to_string())) + })? + .ok_or_else(|| FacadeError::ViewNotFound { + name: view_name.to_string(), + }) +} + +fn history_error(e: HistoryError) -> FacadeError { + FacadeError::Repository(atomic_repository::RepositoryError::Database(e.to_string())) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_latest_forms() { + for spec in [None, Some(""), Some("@")] { + assert_eq!( + ChangeIdentifier::parse(spec).unwrap(), + ChangeIdentifier::Latest + ); + } + } + + #[test] + fn parse_sequence_forms() { + assert_eq!( + ChangeIdentifier::parse(Some("#7")).unwrap(), + ChangeIdentifier::Sequence(7) + ); + assert_eq!( + ChangeIdentifier::parse(Some("42")).unwrap(), + ChangeIdentifier::Sequence(42) + ); + } + + #[test] + fn parse_prefix_uppercases() { + assert_eq!( + ChangeIdentifier::parse(Some("abcd")).unwrap(), + ChangeIdentifier::HashPrefix("ABCD".to_string()) + ); + } + + #[test] + fn parse_rejects_short_prefix_and_bad_chars() { + assert!(ChangeIdentifier::parse(Some("abc")).is_err()); + assert!(ChangeIdentifier::parse(Some("not-a-hash!")).is_err()); + } +} diff --git a/atomic-facade/src/intents.rs b/atomic-facade/src/intents.rs new file mode 100644 index 00000000..cf9d2938 --- /dev/null +++ b/atomic-facade/src/intents.rs @@ -0,0 +1,173 @@ +//! Intent listing and detail reads. + +use atomic_repository::{IntentInfo, Repository}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::attestations::{inputs_from_entry, load_intent_attestation, AttestationStatus}; +use crate::error::{FacadeError, FacadeResult}; + +/// One row of the intent list. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct IntentSummary { + /// Normalized intent id (e.g. `PIMO-1`). + pub id: String, + /// Title. + pub title: String, + /// Status (e.g. `open`, `in_progress`, `done`). + pub status: String, + /// Priority (e.g. `low`, `medium`, `high`). + pub priority: String, + /// Assignee, if any. + #[serde(skip_serializing_if = "Option::is_none")] + pub assignee: Option, + /// Number of linked goals. + pub goals: u32, + /// Ids of intents blocking this one. + #[serde(skip_serializing_if = "Vec::is_empty", default)] + pub blocked_by: Vec, +} + +impl From<&IntentInfo> for IntentSummary { + fn from(info: &IntentInfo) -> Self { + Self { + id: info.id.clone(), + title: info.title.clone(), + status: info.status.clone(), + priority: info.priority.clone(), + assignee: info.assignee.clone(), + goals: info.goals, + blocked_by: info.blocked_by.clone(), + } + } +} + +/// Full detail of a stored intent. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct IntentDetail { + /// Normalized intent id. + pub id: String, + /// Frontmatter as a JSON object. + pub frontmatter: Value, + /// Markdown body (without the frontmatter block). + pub body: String, + /// Vault-relative path of the entry, when the manifest records one. + #[serde(skip_serializing_if = "Option::is_none")] + pub vault_path: Option, + /// Freshness of the intent's attestation. + pub attestation: AttestationStatus, + /// The signed JSON-LD node, when an attestation exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub attested_node: Option, +} + +/// Intents from the vault manifest, optionally filtered by status +/// (`None` or `Some("all")` lists everything). +pub fn list_intents(repo: &Repository, status: Option<&str>) -> FacadeResult> { + let infos = repo.vault_intent_list(status)?; + Ok(infos.iter().map(IntentSummary::from).collect()) +} + +/// A single intent's content plus its attestation state. +/// +/// `id` accepts the same forms as the CLI: `PIMO-1`, `pimo-1`, a bare +/// number, a ULID, or a unique prefix. +pub fn intent_detail(repo: &Repository, id: &str) -> FacadeResult { + // An id the resolver rejects means no such intent — surface it as a + // client-facing NotFound. Infrastructure failures (database, IO) must + // stay server errors, not 404s. + let normalized = repo.resolve_intent_key(id).map_err(|e| match &e { + atomic_repository::RepositoryError::InvalidOperation { .. } => FacadeError::NotFound { + kind: "intent", + id: id.to_string(), + }, + _ if e.is_not_found() => FacadeError::NotFound { + kind: "intent", + id: id.to_string(), + }, + _ => FacadeError::Repository(e), + })?; + let entry = repo.vault_intent_show(&normalized)?; + let inputs = inputs_from_entry("intent", &entry)?; + let attested = load_intent_attestation(repo, &normalized, &inputs)?; + + let vault_path = vault_path_for(repo, &normalized)?; + + Ok(IntentDetail { + id: normalized, + frontmatter: Value::Object(inputs.frontmatter), + body: inputs.body, + vault_path, + attestation: attested.status(), + attested_node: attested + .node() + .map(serde_json::to_value) + .transpose() + .map_err(|e| FacadeError::Malformed { + message: format!("attested node did not serialize: {e}"), + })?, + }) +} + +/// The vault-relative path of a stored intent via the manifest, if recorded. +fn vault_path_for(repo: &Repository, id: &str) -> FacadeResult> { + let manifest = repo.vault_manifest()?; + Ok(manifest + .intents + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(id)) + .map(|(_, summary)| summary.vault_path.clone()) + .filter(|p| !p.is_empty())) +} + +#[cfg(test)] +mod tests { + use super::*; + use atomic_repository::IntentCreateOptions; + + fn repo_with_intent() -> (Repository, String, tempfile::TempDir) { + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + let result = repo + .vault_intent_create(IntentCreateOptions { + title: "Facade test intent".to_string(), + priority: Some("medium".to_string()), + assignee: None, + labels: Vec::new(), + session_id: None, + turn_id: None, + }) + .unwrap(); + (repo, result.id, dir) + } + + #[test] + fn list_and_detail_roundtrip() { + let (repo, id, _dir) = repo_with_intent(); + + let summaries = list_intents(&repo, None).unwrap(); + assert_eq!(summaries.len(), 1); + assert_eq!(summaries[0].title, "Facade test intent"); + + let detail = intent_detail(&repo, &id).unwrap(); + assert_eq!(detail.attestation, AttestationStatus::None); + assert!(detail.frontmatter.is_object()); + + // JSON output carries the expected top-level fields. + let json = serde_json::to_value(&detail).unwrap(); + assert!(json.get("id").is_some()); + assert!(json.get("body").is_some()); + assert_eq!(json.get("attestation").unwrap(), "none"); + } + + #[test] + fn detail_not_found_is_client_error() { + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + + let err = intent_detail(&repo, "NOPE-99").unwrap_err(); + assert!(err.is_client_error(), "unexpected error: {err}"); + } +} diff --git a/atomic-facade/src/lib.rs b/atomic-facade/src/lib.rs new file mode 100644 index 00000000..ffecb7ed --- /dev/null +++ b/atomic-facade/src/lib.rs @@ -0,0 +1,54 @@ +//! # atomic-facade +//! +//! The native API layer over Atomic's command-level read operations. +//! +//! Everything an integration needs is already on the laptop, inside the +//! repository. This crate lets **local embedders** — UIs, tools, agent +//! harnesses — read that data in-process as typed values: every function +//! is what a CLI command does *minus* the terminal. It takes an open +//! [`atomic_repository::Repository`], returns serde-serializable DTOs, +//! and never prints, prompts, or exits — no shelling out to the `atomic` +//! binary, no parsing its output. +//! +//! This is deliberately **not** a server contract. Atomic is local-first; +//! the storage server is primarily transport, and any server-side read +//! surface is a separate, intentional decision — not something this crate +//! implies or requires. +//! +//! For changes and log, JSON field names and skip rules deliberately mirror +//! the CLI's `-f json` output, so serialized responses and CLI output stay +//! interchangeable. The view/intent/memory DTOs are richer shapes than the +//! CLI's terse `--json` rows — new surface, not a CLI contract. +//! +//! All reads are synchronous (redb + filesystem). When embedding in an +//! async runtime, wrap calls in `spawn_blocking`, open repositories with +//! `Repository::open_readonly`, and share one `Pristine` per repository +//! via `Repository::open_with_pristine` — redb allows only one open +//! `Database` per file. +//! +//! | Module | CLI equivalent | +//! |---|---| +//! | [`changes`] | `atomic change -f json`, `atomic log -f json` | +//! | [`views`] | `atomic view list` | +//! | [`intents`] | `atomic intent list` / `show` | +//! | [`memories`] | `atomic memory list` / `show` | +//! | [`attestations`] | the intent/memory attestation dual-read | +//! | [`identifier`] | hash / prefix / `#seq` / `@` resolution | + +pub mod attestations; +pub mod changes; +pub mod error; +pub mod identifier; +pub mod intents; +pub mod memories; +pub mod provenance; +pub mod views; + +pub use attestations::{AttestationStatus, Attested, LiftInputs}; +pub use changes::{change_detail, list_log, ChangeDetail, LogEntry, LogQuery}; +pub use error::{FacadeError, FacadeResult}; +pub use identifier::{resolve_change, ChangeIdentifier}; +pub use intents::{intent_detail, list_intents, IntentDetail, IntentSummary}; +pub use memories::{list_memories, memory_detail, MemoryDetail, MemorySummary}; +pub use provenance::{CostDto, ProvenanceDto, TokenUsageDto}; +pub use views::{list_views, view_summary, ViewSummary}; diff --git a/atomic-facade/src/memories.rs b/atomic-facade/src/memories.rs new file mode 100644 index 00000000..a8b3a042 --- /dev/null +++ b/atomic-facade/src/memories.rs @@ -0,0 +1,184 @@ +//! Memory listing and detail reads. +//! +//! Memories are flat files at `memory/.md` read through the generic +//! vault path — there is no per-memory repository method. The default +//! `memory/MEMORY.md` index scaffold (frontmatter `type: index`) is not a +//! canonical memory and is excluded from listings. + +use atomic_repository::Repository; +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::attestations::{ + inputs_from_entry, load_memory_attestation, memory_id, normalize_memory_path, AttestationStatus, +}; +use crate::error::{FacadeError, FacadeResult}; + +/// One row of the memory list. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct MemorySummary { + /// The id stem (filename without `memory/` and `.md`). + pub id: String, + /// Vault-relative path (`memory/.md`). + pub path: String, + /// Last update timestamp (RFC 3339). + pub updated_at: String, +} + +/// Full detail of a stored memory. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct MemoryDetail { + /// The id stem. + pub id: String, + /// Vault-relative path. + pub path: String, + /// Frontmatter as a JSON object. + pub frontmatter: Value, + /// Markdown body (without the frontmatter block). + pub body: String, + /// Whether this is a freeform memory (no canonical identity/kind fields). + pub freeform: bool, + /// Freshness of the memory's attestation. + pub attestation: AttestationStatus, + /// The signed JSON-LD node, when an attestation exists. + #[serde(skip_serializing_if = "Option::is_none")] + pub attested_node: Option, +} + +/// Memories in the vault, most recently updated first. +pub fn list_memories(repo: &Repository, limit: Option) -> FacadeResult> { + let entries = repo.vault_list("memory/", None)?; + + let mut items: Vec = entries + .iter() + .filter(|e| !e.path.starts_with("attestations/")) + .filter(|e| !is_index_scaffold(repo, &e.path)) + .map(|e| MemorySummary { + id: memory_id(&e.path), + path: e.path.clone(), + updated_at: e.updated_at.clone(), + }) + .collect(); + + // updated_at is RFC 3339, so lexical order == chronological order; + // id is a stable tiebreaker. + items.sort_by(|a, b| { + b.updated_at + .cmp(&a.updated_at) + .then_with(|| a.id.cmp(&b.id)) + }); + if let Some(limit) = limit { + items.truncate(limit); + } + Ok(items) +} + +/// A single memory's content plus its attestation state. +/// +/// `id_or_path` accepts a bare id, `memory/`, `.md`, or the full +/// `memory/.md` path. +pub fn memory_detail(repo: &Repository, id_or_path: &str) -> FacadeResult { + let path = normalize_memory_path(id_or_path); + let entry = repo + .vault_retrieve(&path)? + .ok_or_else(|| FacadeError::NotFound { + kind: "memory", + id: id_or_path.to_string(), + })?; + + let inputs = inputs_from_entry("memory", &entry)?; + let attested = load_memory_attestation(repo, id_or_path, &inputs)?; + let freeform = is_freeform(&inputs.frontmatter); + + Ok(MemoryDetail { + id: memory_id(id_or_path), + path, + frontmatter: Value::Object(inputs.frontmatter), + body: inputs.body, + freeform, + attestation: attested.status(), + attested_node: attested + .node() + .map(serde_json::to_value) + .transpose() + .map_err(|e| FacadeError::Malformed { + message: format!("attested node did not serialize: {e}"), + })?, + }) +} + +/// A freeform memory has none of the canonical identity/kind fields. +fn is_freeform(frontmatter: &serde_json::Map) -> bool { + ["@id", "uid", "id", "memoryKind", "kind"] + .iter() + .all(|key| !frontmatter.contains_key(*key)) +} + +/// The default `memory/MEMORY.md` scaffold carries `type: index` frontmatter +/// and is not a canonical memory. Fail-open: unreadable entries are treated +/// as real memories so nothing is silently hidden. +fn is_index_scaffold(repo: &Repository, path: &str) -> bool { + let Ok(Some(entry)) = repo.vault_retrieve(path) else { + return false; + }; + serde_json::from_str::(&entry.frontmatter_json) + .ok() + .and_then(|v| v.get("type").and_then(|t| t.as_str()).map(str::to_owned)) + .as_deref() + == Some("index") +} + +#[cfg(test)] +mod tests { + use super::*; + use atomic_core::pristine::VaultEntryType; + + fn repo_with_memory() -> (Repository, tempfile::TempDir) { + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + repo.init_vault().unwrap(); + repo.vault_store( + "memory/test-note.md", + VaultEntryType::Memory, + b"A fact worth keeping.\n".to_vec(), + "{}".to_string(), + ) + .unwrap(); + (repo, dir) + } + + #[test] + fn list_excludes_index_scaffold() { + let (repo, _dir) = repo_with_memory(); + + let memories = list_memories(&repo, None).unwrap(); + assert_eq!(memories.len(), 1, "only the real memory: {memories:?}"); + assert_eq!(memories[0].id, "test-note"); + assert_eq!(memories[0].path, "memory/test-note.md"); + } + + #[test] + fn detail_accepts_all_path_forms() { + let (repo, _dir) = repo_with_memory(); + + for form in [ + "test-note", + "test-note.md", + "memory/test-note", + "memory/test-note.md", + ] { + let detail = memory_detail(&repo, form).unwrap(); + assert_eq!(detail.id, "test-note"); + assert!(detail.freeform); + assert_eq!(detail.attestation, AttestationStatus::None); + assert!(detail.body.contains("A fact worth keeping.")); + } + } + + #[test] + fn detail_not_found_is_client_error() { + let (repo, _dir) = repo_with_memory(); + let err = memory_detail(&repo, "does-not-exist").unwrap_err(); + assert!(err.is_client_error(), "unexpected error: {err}"); + } +} diff --git a/atomic-facade/src/provenance.rs b/atomic-facade/src/provenance.rs new file mode 100644 index 00000000..2513e040 --- /dev/null +++ b/atomic-facade/src/provenance.rs @@ -0,0 +1,149 @@ +//! Serializable provenance DTOs. +//! +//! Field names and skip rules mirror `atomic change -f json` so a server +//! response and the CLI's JSON output stay interchangeable. + +use atomic_core::change::{PromptContent, Provenance}; +use atomic_core::types::Base32; +use serde::{Deserialize, Serialize}; + +/// AI provenance attached to a change. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ProvenanceDto { + /// AI vendor/provider. + pub vendor: String, + /// Model identifier. + pub model: String, + /// Model version (if available). + #[serde(skip_serializing_if = "Option::is_none")] + pub model_version: Option, + /// Tool used to interact with the AI. + pub tool: String, + /// Type of AI contribution. + pub suggestion_type: String, + /// Token usage. + #[serde(skip_serializing_if = "Option::is_none")] + pub tokens: Option, + /// Cost information. + #[serde(skip_serializing_if = "Option::is_none")] + pub cost: Option, + /// Temperature setting. + #[serde(skip_serializing_if = "Option::is_none")] + pub temperature: Option, + /// Request timestamp. + #[serde(skip_serializing_if = "Option::is_none")] + pub timestamp: Option, + /// Request ID from the provider. + #[serde(skip_serializing_if = "Option::is_none")] + pub request_id: Option, + /// Session ID. + #[serde(skip_serializing_if = "Option::is_none")] + pub session_id: Option, + /// Hash of the prompt (base32), when only the hash is stored. + #[serde(skip_serializing_if = "Option::is_none")] + pub prompt_hash: Option, + /// Additional metadata key/value pairs. + #[serde(skip_serializing_if = "Option::is_none")] + pub metadata: Option, + /// Agent mode: "build", "code", "ask", … + #[serde(skip_serializing_if = "Option::is_none")] + pub agent_mode: Option, + /// Why the model stopped on the final step. + #[serde(skip_serializing_if = "Option::is_none")] + pub finish_reason: Option, + /// Number of LLM roundtrips (steps) in the turn. + #[serde(skip_serializing_if = "Option::is_none")] + pub step_count: Option, + /// Human-readable session slug (e.g. "mighty-rocket"). + #[serde(skip_serializing_if = "Option::is_none")] + pub session_slug: Option, + /// Model-provider signature over the reasoning blocks. + #[serde(skip_serializing_if = "Option::is_none")] + pub reasoning_signature: Option, + /// Concatenated reasoning/thinking text from the turn. + #[serde(skip_serializing_if = "Option::is_none")] + pub reasoning_text: Option, + /// The agent's structured task plan at turn completion (JSON string). + #[serde(skip_serializing_if = "Option::is_none")] + pub task_plan: Option, +} + +/// Token usage counters. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct TokenUsageDto { + #[serde(skip_serializing_if = "Option::is_none")] + pub input: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub output: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub total: Option, +} + +/// Cost in micro-USD. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CostDto { + pub amount_micros: u64, + pub currency: String, +} + +impl From<&Provenance> for ProvenanceDto { + fn from(prov: &Provenance) -> Self { + let tokens = if prov.tokens.is_empty() { + None + } else { + Some(TokenUsageDto { + input: Some(prov.tokens.input_tokens), + output: Some(prov.tokens.output_tokens), + total: Some(prov.tokens.total_tokens), + }) + }; + + let cost = if prov.cost.is_zero() { + None + } else { + Some(CostDto { + amount_micros: prov.cost.micro_usd, + currency: "USD".to_string(), + }) + }; + + let prompt_hash = match &prov.prompt { + PromptContent::Hashed(h) => Some(h.to_base32()), + _ => None, + }; + + let metadata = if prov.metadata.is_empty() { + None + } else { + Some(serde_json::Value::Array( + prov.metadata + .iter() + .map(|(k, v)| serde_json::json!({ "key": k, "value": v })) + .collect(), + )) + }; + + Self { + vendor: format!("{:?}", prov.vendor), + model: prov.model.clone(), + model_version: prov.model_version.clone(), + tool: format!("{:?}", prov.tool), + suggestion_type: format!("{:?}", prov.suggestion_type), + tokens, + cost, + temperature: prov.temperature.map(|t| t as f64 / 1000.0), + timestamp: prov.timestamp, + request_id: prov.request_id.clone(), + session_id: prov.session_id.clone(), + prompt_hash, + metadata, + agent_mode: prov.agent_mode.clone(), + finish_reason: prov.finish_reason.clone(), + step_count: prov.step_count, + session_slug: prov.session_slug.clone(), + reasoning_signature: prov.reasoning_signature.clone(), + reasoning_text: prov.reasoning_text.clone(), + task_plan: prov.task_plan.clone(), + } + } +} diff --git a/atomic-facade/src/views.rs b/atomic-facade/src/views.rs new file mode 100644 index 00000000..e20317b2 --- /dev/null +++ b/atomic-facade/src/views.rs @@ -0,0 +1,84 @@ +//! View listing as serializable summaries. + +use atomic_core::pristine::ViewScope; +use atomic_repository::Repository; +use serde::{Deserialize, Serialize}; + +use crate::error::FacadeResult; + +/// A view and its state, ready for JSON serialization. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ViewSummary { + /// View name. + pub name: String, + /// Merkle state (base32). + pub state: String, + /// Total changes visible through the view's filter chain. + pub change_count: u64, + /// Changes recorded on this view itself (excludes inherited ones). + pub own_change_count: u64, + /// "draft" or "shared". + pub scope: String, + /// Parent view name (absent for the root view). + #[serde(skip_serializing_if = "Option::is_none")] + pub parent: Option, + /// Whether this is the repository's current view. + pub is_current: bool, +} + +/// All views in the repository, sorted by name. +pub fn list_views(repo: &Repository) -> FacadeResult> { + let current = repo.current_view().to_string(); + let mut names = repo.list_views()?; + names.sort(); + + names + .into_iter() + .map(|name| view_summary_inner(repo, &name, ¤t)) + .collect() +} + +/// A single view's summary. +pub fn view_summary(repo: &Repository, name: &str) -> FacadeResult { + view_summary_inner(repo, name, repo.current_view()) +} + +fn view_summary_inner(repo: &Repository, name: &str, current: &str) -> FacadeResult { + let info = repo.get_view_info(name)?; + let state = info.state_base32(); + Ok(ViewSummary { + name: info.name, + state, + change_count: info.change_count, + own_change_count: info.own_change_count, + scope: scope_label(info.scope).to_string(), + parent: info.parent_name, + is_current: name == current, + }) +} + +fn scope_label(scope: ViewScope) -> &'static str { + match scope { + ViewScope::Draft => "draft", + ViewScope::Shared => "shared", + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lists_default_view_as_current() { + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + + let views = list_views(&repo).unwrap(); + assert!(!views.is_empty()); + + let current: Vec<_> = views.iter().filter(|v| v.is_current).collect(); + assert_eq!(current.len(), 1, "exactly one current view"); + assert_eq!(current[0].name, repo.current_view()); + assert_eq!(current[0].scope, "shared"); + } +} diff --git a/atomic-facade/tests/facade_read_test.rs b/atomic-facade/tests/facade_read_test.rs new file mode 100644 index 00000000..899e1dfe --- /dev/null +++ b/atomic-facade/tests/facade_read_test.rs @@ -0,0 +1,86 @@ +//! End-to-end reads over a real repository: record a change, then resolve +//! and serialize it through every facade entry point a server would call. + +use atomic_facade::{change_detail, list_log, list_memories, list_views, resolve_change, LogQuery}; +use atomic_repository::{Repository, TrackingOptions}; + +fn repo_with_change() -> (Repository, String, tempfile::TempDir) { + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + + std::fs::create_dir_all(dir.path().join("src")).unwrap(); + std::fs::write(dir.path().join("src/lib.rs"), "pub fn one() -> u8 { 1 }\n").unwrap(); + repo.add("src/lib.rs", TrackingOptions::default()).unwrap(); + let outcome = repo + .record_all("feat: add one()") + .expect("record should succeed"); + + use atomic_core::types::Base32; + (repo, outcome.hash().to_base32(), dir) +} + +#[test] +fn change_detail_resolves_every_identifier_form() { + let (repo, hash, _dir) = repo_with_change(); + + // Latest (None and "@"), full hash, and prefix all resolve to the record. + for spec in [None, Some("@"), Some(hash.as_str()), Some(&hash[..8])] { + let detail = change_detail(&repo, None, spec) + .unwrap_or_else(|e| panic!("spec {spec:?} failed: {e}")); + assert_eq!(detail.hash, hash); + assert_eq!(detail.message, "feat: add one()"); + assert!(!detail.hunks.is_empty(), "change should carry hunks"); + } + + // Sequence form: resolve the latest to learn its sequence, then round-trip. + let (_, seq) = resolve_change(&repo, None, None).unwrap(); + let seq = seq.expect("latest change has a sequence"); + let by_seq = change_detail(&repo, None, Some(&format!("#{seq}"))).unwrap(); + assert_eq!(by_seq.hash, hash); + assert_eq!(by_seq.sequence, Some(seq)); +} + +#[test] +fn log_lists_the_recorded_change_newest_first() { + let (repo, hash, _dir) = repo_with_change(); + + let entries = list_log(&repo, &LogQuery::default()).unwrap(); + assert!(!entries.is_empty()); + assert_eq!(entries[0].hash, hash, "newest entry first"); + assert_eq!(entries[0].message.as_deref(), Some("feat: add one()")); + + let limited = list_log( + &repo, + &LogQuery { + limit: Some(1), + ..LogQuery::default() + }, + ) + .unwrap(); + assert_eq!(limited.len(), 1); +} + +#[test] +fn unknown_view_is_a_client_error() { + let (repo, _hash, _dir) = repo_with_change(); + let err = change_detail(&repo, Some("no-such-view"), None).unwrap_err(); + assert!(err.is_client_error(), "unexpected error: {err}"); +} + +#[test] +fn full_read_surface_serializes_to_json() { + let (repo, _hash, _dir) = repo_with_change(); + + let views = list_views(&repo).unwrap(); + let memories = list_memories(&repo, None).unwrap(); + let log = list_log(&repo, &LogQuery::default()).unwrap(); + + // Everything a forge endpoint would return must serialize cleanly. + let payload = serde_json::json!({ + "views": views, + "memories": memories, + "log": log, + }); + let text = serde_json::to_string(&payload).unwrap(); + assert!(text.contains("\"views\"")); +}