Skip to main content

graphforge_cli/
lib.rs

1//! Reusable GraphForge command-line interface.
2#![forbid(unsafe_code)]
3
4use std::collections::BTreeMap;
5use std::io::{self, Read, Write};
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8use std::time::Duration;
9
10use arrow::datatypes::DataType;
11use arrow::ipc::writer::StreamWriter;
12use arrow::record_batch::RecordBatch;
13use clap::{Args, Parser, Subcommand, ValueEnum, error::ErrorKind};
14use graphforge_api::{
15    CheckpointDiffDetail, CheckpointDiffScope, CheckpointRequest, CheckpointSelector,
16    DeleteCheckpointRequest, DiffCheckpointsRequest, ExecutionResult, GraphForge,
17    ListCheckpointsRequest, OperationId, PageRequest, PageToken, PreviewRevertCheckpointRequest,
18    RepositoryContext, RepositorySyncRequest, RepositorySyncStatus, RevertCheckpointPreview,
19    RevertCheckpointRequest, ShowCheckpointRequest,
20};
21use uuid::Uuid;
22
23include!(concat!(env!("OUT_DIR"), "/project_skills.rs"));
24
25mod auth;
26mod diagnostics;
27mod hub_clone;
28pub mod hub_fixture_artifacts;
29mod hub_http;
30mod hub_publish;
31#[cfg(feature = "hub-test-support")]
32pub mod hub_test_support;
33mod identity;
34mod maintenance_cli;
35mod ontology_cli;
36mod porcelain;
37mod portable_cli;
38mod research_cli;
39mod research_help;
40mod research_versions_cli;
41mod saved_queries_cli;
42mod source_artifact_cli;
43mod storage_attribution_cli;
44
45const MAX_SKILL_MANIFEST_BYTES: u64 = 256 * 1024;
46const MAX_SKILL_FILE_BYTES: u64 = 4 * 1024 * 1024;
47const MAX_SKILL_BUNDLE_BYTES: u64 = 8 * 1024 * 1024;
48const MAX_SKILL_BUNDLE_FILES: usize = 256;
49const MAX_SKILL_PATH_BYTES: usize = 1024;
50const OUT_OF_SYNC_EXIT_CODE: i32 = 4;
51
52fn project_skill_bundle() -> graphforge_api::SkillBundle<'static> {
53    graphforge_api::SkillBundle {
54        manifest: PROJECT_SKILL_MANIFEST,
55        files: PROJECT_SKILL_FILES,
56    }
57}
58
59struct OwnedSkillFile {
60    path: String,
61    bytes: Vec<u8>,
62}
63
64struct OwnedSkillBundle {
65    manifest: Vec<u8>,
66    files: Vec<OwnedSkillFile>,
67}
68
69fn read_bounded_file(
70    path: &Path,
71    maximum: u64,
72    message: &'static str,
73) -> Result<Vec<u8>, graphforge_api::GfError> {
74    let file = std::fs::File::open(path)
75        .map_err(|error| graphforge_api::GfError::Storage(error.to_string()))?;
76    let metadata = file
77        .metadata()
78        .map_err(|error| graphforge_api::GfError::Storage(error.to_string()))?;
79    if !metadata.is_file() || metadata.len() > maximum {
80        return Err(graphforge_api::GfError::Validation(message.into()));
81    }
82    let capacity = usize::try_from(metadata.len())
83        .map_err(|_| graphforge_api::GfError::Validation(message.into()))?;
84    let mut bytes = Vec::with_capacity(capacity);
85    file.take(maximum + 1)
86        .read_to_end(&mut bytes)
87        .map_err(|error| graphforge_api::GfError::Storage(error.to_string()))?;
88    if bytes.len() as u64 > maximum {
89        return Err(graphforge_api::GfError::Validation(message.into()));
90    }
91    Ok(bytes)
92}
93
94fn load_skill_file(
95    root: &Path,
96    entry: &serde_json::Value,
97) -> Result<(String, PathBuf, u64), graphforge_api::GfError> {
98    let path = entry
99        .get("path")
100        .and_then(serde_json::Value::as_str)
101        .ok_or_else(|| {
102            graphforge_api::GfError::Validation("project skill file path is required".into())
103        })?;
104    if path.is_empty() || path.len() > MAX_SKILL_PATH_BYTES {
105        return Err(graphforge_api::GfError::Validation(
106            "project skill file path exceeds byte bound".into(),
107        ));
108    }
109    let relative = Path::new(path);
110    if relative.is_absolute()
111        || relative
112            .components()
113            .any(|part| !matches!(part, std::path::Component::Normal(_)))
114    {
115        return Err(graphforge_api::GfError::Validation(
116            "project skill file path is not contained".into(),
117        ));
118    }
119    let mut candidate = root.to_path_buf();
120    for component in relative.components() {
121        candidate.push(component);
122        let component_metadata = std::fs::symlink_metadata(&candidate)
123            .map_err(|error| graphforge_api::GfError::Storage(error.to_string()))?;
124        if component_metadata.file_type().is_symlink() {
125            return Err(graphforge_api::GfError::Validation(
126                "packaged project skill paths must not contain symlinks".into(),
127            ));
128        }
129    }
130    let file_metadata = std::fs::symlink_metadata(&candidate)
131        .map_err(|error| graphforge_api::GfError::Storage(error.to_string()))?;
132    if file_metadata.file_type().is_symlink() || !file_metadata.is_file() {
133        return Err(graphforge_api::GfError::Validation(
134            "packaged project skill must be a real file".into(),
135        ));
136    }
137    if file_metadata.len() > MAX_SKILL_FILE_BYTES {
138        return Err(graphforge_api::GfError::Validation(
139            "packaged project skill exceeds per-file byte bound".into(),
140        ));
141    }
142    let canonical = candidate
143        .canonicalize()
144        .map_err(|error| graphforge_api::GfError::Storage(error.to_string()))?;
145    if !canonical.starts_with(root) {
146        return Err(graphforge_api::GfError::Validation(
147            "project skill file path escaped its bundle".into(),
148        ));
149    }
150    Ok((path.to_owned(), canonical, file_metadata.len()))
151}
152
153fn load_skill_bundle(root: &Path) -> Result<OwnedSkillBundle, graphforge_api::GfError> {
154    let metadata = std::fs::symlink_metadata(root)
155        .map_err(|error| graphforge_api::GfError::Storage(error.to_string()))?;
156    if metadata.file_type().is_symlink() || !metadata.is_dir() {
157        return Err(graphforge_api::GfError::Validation(
158            "packaged skill bundle root must be a real directory".into(),
159        ));
160    }
161    let root = root
162        .canonicalize()
163        .map_err(|error| graphforge_api::GfError::Storage(error.to_string()))?;
164    let manifest_path = root.join("manifest.json");
165    let manifest_metadata = std::fs::symlink_metadata(&manifest_path)
166        .map_err(|error| graphforge_api::GfError::Storage(error.to_string()))?;
167    if manifest_metadata.file_type().is_symlink() || !manifest_metadata.is_file() {
168        return Err(graphforge_api::GfError::Validation(
169            "packaged skill manifest must be a real file".into(),
170        ));
171    }
172    if manifest_metadata.len() > MAX_SKILL_MANIFEST_BYTES {
173        return Err(graphforge_api::GfError::Validation(
174            "packaged skill manifest exceeds byte bound".into(),
175        ));
176    }
177    let manifest = read_bounded_file(
178        &manifest_path,
179        MAX_SKILL_MANIFEST_BYTES,
180        "packaged skill manifest exceeds byte bound",
181    )?;
182    let value: serde_json::Value = serde_json::from_slice(&manifest).map_err(|error| {
183        graphforge_api::GfError::Validation(format!("invalid project skill manifest: {error}"))
184    })?;
185    let entries = value
186        .get("files")
187        .and_then(serde_json::Value::as_array)
188        .ok_or_else(|| {
189            graphforge_api::GfError::Validation("project skill manifest files are required".into())
190        })?;
191    if entries.len() > MAX_SKILL_BUNDLE_FILES {
192        return Err(graphforge_api::GfError::Validation(
193            "project skill bundle exceeds file bound".into(),
194        ));
195    }
196    let mut prepared = Vec::with_capacity(entries.len());
197    let mut total_bytes = 0_u64;
198    for entry in entries {
199        let file = load_skill_file(&root, entry)?;
200        total_bytes = total_bytes.checked_add(file.2).ok_or_else(|| {
201            graphforge_api::GfError::Validation(
202                "packaged project skill bundle exceeds total byte bound".into(),
203            )
204        })?;
205        if total_bytes > MAX_SKILL_BUNDLE_BYTES {
206            return Err(graphforge_api::GfError::Validation(
207                "packaged project skill bundle exceeds total byte bound".into(),
208            ));
209        }
210        prepared.push(file);
211    }
212    let mut files = Vec::with_capacity(prepared.len());
213    let mut read_bytes = 0_u64;
214    for (path, canonical, _) in prepared {
215        let bytes = read_bounded_file(
216            &canonical,
217            MAX_SKILL_FILE_BYTES,
218            "packaged project skill exceeds per-file byte bound",
219        )?;
220        read_bytes = read_bytes
221            .checked_add(bytes.len() as u64)
222            .filter(|total| *total <= MAX_SKILL_BUNDLE_BYTES)
223            .ok_or_else(|| {
224                graphforge_api::GfError::Validation(
225                    "packaged project skill bundle exceeds total byte bound".into(),
226                )
227            })?;
228        files.push(OwnedSkillFile { path, bytes });
229    }
230    Ok(OwnedSkillBundle { manifest, files })
231}
232
233/// GraphForge command-line interface.
234#[derive(Parser)]
235#[command(name = "graphforge", version, about = "GraphForge CLI")]
236struct Cli {
237    /// Print version info and exit.
238    #[arg(long)]
239    info: bool,
240
241    /// Persistent GraphForge project directory.
242    #[arg(long, global = true)]
243    project: Option<PathBuf>,
244
245    /// Code repository root; defaults to discovery from the current directory.
246    #[arg(long, global = true)]
247    project_dir: Option<PathBuf>,
248
249    #[command(flatten)]
250    diagnostics: storage_attribution_cli::DiagnosticsArgs,
251
252    /// Emit the stable machine-readable JSON result when supported.
253    #[arg(long, global = true)]
254    json: bool,
255
256    /// Internal packaged project-skill asset root used by distribution wrappers.
257    #[arg(long, global = true, hide = true)]
258    skills_bundle_dir: Option<PathBuf>,
259
260    #[command(subcommand)]
261    command: Option<Command>,
262}
263
264#[derive(Subcommand)]
265enum Command {
266    /// Manage your Hub browser session.
267    Auth(auth::AuthArgs),
268    /// Validate and exercise the Rust-owned telemetry lifecycle.
269    Telemetry(TelemetryArgs),
270    Clone(hub_clone::CloneArgs),
271    Publish(hub_publish::PublishArgs),
272    Hub(hub_clone::HubArgs),
273    /// Show the current Branch, its head and its upstream.
274    ///
275    /// Example: `gf status`
276    Status(porcelain::StatusArgs),
277    /// Show history, newest first.
278    ///
279    /// Example: `gf log -n 10`, `gf log v1`, `gf log --remote --all`
280    Log(porcelain::LogArgs),
281    /// Record a new Version of the Branch by running a query, with a message.
282    ///
283    /// Example: `gf commit -m "Raise scores" --query "MATCH (n:Item) SET n.score = 2"`
284    Commit(porcelain::CommitArgs),
285    /// List Branches, or create one at the current head or at `--from`.
286    ///
287    /// Example: `gf branch`, `gf branch feature/score`, `gf branch fix --from v1`
288    Branch(porcelain::BranchArgs),
289    /// Select the Branch the other verbs act on.
290    ///
291    /// Example: `gf switch feature/score`
292    Switch(porcelain::SwitchArgs),
293    /// List tags, create one on a Version, or delete one.
294    ///
295    /// Example: `gf tag`, `gf tag v1`, `gf tag v1 <version-uuid>`, `gf tag -d v1`
296    Tag(porcelain::TagArgs),
297    /// Publish the Branch head to its Hub repository.
298    ///
299    /// Example: `gf push owner/repository` the first time, then `gf push`
300    Push(porcelain::PushArgs),
301    /// Incorporate the Hub's head of the Branch's ref into the local Branch.
302    ///
303    /// Example: `gf pull`
304    Pull(porcelain::PullArgs),
305    /// Initialize repository-local GraphForge definitions and state.
306    Init(InitArgs),
307    /// Compare or reconcile declared definitions and source digests without ingesting data.
308    Sync(SyncArgs),
309    /// Remove only repository-local runtime state.
310    Remove(RemoveArgs),
311    /// Validate or resolve repository configuration.
312    Config {
313        #[command(subcommand)]
314        command: ConfigCommand,
315    },
316    /// Validate provider-neutral infrastructure intent without provisioning.
317    Infra {
318        #[command(subcommand)]
319        command: InfraCommand,
320    },
321    /// Manage project-local GraphForge agent skills.
322    Skills {
323        #[command(subcommand)]
324        command: SkillsCommand,
325    },
326    /// Restore the complete workspace from a checkpoint.
327    Revert(RevertArgs),
328    /// Export one immutable generation as a streaming portable package.
329    Export(portable_cli::PortableExportArgs),
330    /// Import a streaming portable package into a new or empty project.
331    Import(portable_cli::PortableImportArgs),
332    /// Portable selection preview, verification, staging, and OCI promotion.
333    Portable {
334        #[command(subcommand)]
335        command: portable_cli::PortableCommand,
336    },
337    /// Composable ontology module, bridge, activation, and composition lifecycle.
338    Ontology {
339        #[command(subcommand)]
340        command: ontology_cli::OntologyCommand,
341    },
342    /// Stream a Cypher result to Parquet or Arrow IPC without full materialization.
343    Query(portable_cli::QueryArgs),
344    /// Save, inspect, edit, and explicitly execute reusable project queries.
345    SavedQuery {
346        #[command(subcommand)]
347        command: saved_queries_cli::SavedQueryCommand,
348    },
349    /// Staged Arrow/Parquet graph-import sessions.
350    ImportSession {
351        #[command(subcommand)]
352        command: portable_cli::ImportSessionCommand,
353    },
354    /// Manage immutable named workspace checkpoints.
355    Checkpoint {
356        #[command(subcommand)]
357        command: CheckpointCommand,
358    },
359    /// Research Project metadata and bounded local discovery.
360    Research {
361        #[command(subcommand)]
362        command: research_cli::ResearchCommand,
363    },
364    /// Source and Artifact lifecycle: registration, lineage, preference, and impact.
365    SourceArtifact {
366        #[command(subcommand)]
367        command: source_artifact_cli::SourceArtifactCommand,
368    },
369    /// Explicit multi-mutation transactions (Rust-owned lifecycle).
370    Transaction {
371        #[command(subcommand)]
372        command: maintenance_cli::TransactionCommand,
373    },
374    /// Retention/GC and graph-delta compaction maintenance.
375    Maintenance {
376        #[command(subcommand)]
377        command: maintenance_cli::MaintenanceCommand,
378    },
379    /// Emit safe recovery-on-open evidence for the project.
380    Recovery,
381    /// Emit authenticated, identity-free retained storage attribution.
382    StorageAttribution(storage_attribution_cli::StorageAttributionArgs),
383}
384
385#[derive(Args)]
386struct TelemetryArgs {
387    /// disabled, in_memory, or otlp_http_json.
388    #[arg(long, default_value = "disabled")]
389    mode: String,
390    /// Explicit OTLP/HTTP collector base URL.
391    #[arg(long)]
392    endpoint: Option<String>,
393    /// OTLP header as lowercase-name=value; values are never printed.
394    #[arg(long = "header")]
395    headers: Vec<String>,
396    #[arg(long, default_value_t = 256)]
397    queue_capacity: usize,
398    #[arg(long, default_value_t = 64)]
399    batch_size: usize,
400    #[arg(long, default_value_t = 3_000)]
401    export_timeout_ms: u64,
402    #[arg(long, default_value_t = 5_000)]
403    lifecycle_timeout_ms: u64,
404    #[arg(long, default_value_t = 2)]
405    max_retries: u8,
406}
407
408fn run_telemetry(
409    args: TelemetryArgs,
410    output: &mut dyn Write,
411) -> Result<i32, graphforge_api::GfError> {
412    use graphforge_api::telemetry::{OtlpConfig, TelemetryConfig, TelemetryMode, TelemetryRuntime};
413    let mode = match args.mode.as_str() {
414        "disabled" => TelemetryMode::Disabled,
415        "in_memory" => TelemetryMode::InMemory,
416        "otlp_http_json" => TelemetryMode::OtlpHttpJson,
417        _ => {
418            return Err(graphforge_api::GfError::Validation(
419                "GF_TELEMETRY_INVALID_MODE".into(),
420            ));
421        }
422    };
423    let mut headers = BTreeMap::new();
424    for header in args.headers {
425        let Some((name, value)) = header.split_once('=') else {
426            return Err(graphforge_api::GfError::Validation(
427                "GF_TELEMETRY_INVALID_HEADER".into(),
428            ));
429        };
430        headers.insert(name.to_owned(), value.to_owned());
431    }
432    let otlp = args
433        .endpoint
434        .map(|endpoint| OtlpConfig { endpoint, headers });
435    let runtime = TelemetryRuntime::new(TelemetryConfig {
436        mode,
437        queue_capacity: args.queue_capacity,
438        batch_size: args.batch_size,
439        export_timeout: Duration::from_millis(args.export_timeout_ms),
440        lifecycle_timeout: Duration::from_millis(args.lifecycle_timeout_ms),
441        max_retries: args.max_retries,
442        otlp,
443        ..TelemetryConfig::default()
444    })
445    .map_err(|error| graphforge_api::GfError::Validation(error.code.as_str().to_owned()))?;
446    let flush = runtime.force_flush();
447    let shutdown = runtime.shutdown();
448    writeln!(
449        output,
450        "{}",
451        serde_json::json!({
452            "semantic_contract_version": graphforge_api::telemetry::SEMANTIC_CONTRACT_VERSION,
453            "scope": graphforge_api::telemetry::INSTRUMENTATION_SCOPE,
454            "mode": args.mode,
455            "flush": flush.as_str(),
456            "shutdown": shutdown.as_str()
457        })
458    )
459    .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
460    Ok(0)
461}
462
463#[derive(Args)]
464struct InitArgs {
465    /// Do not install missing project-local GraphForge agent skills.
466    #[arg(long)]
467    no_skills: bool,
468}
469
470#[derive(Args)]
471struct SyncArgs {
472    /// Compare declared repository state without publishing a generation.
473    #[arg(long, conflicts_with_all = ["idempotency_key", "actor_uuid"])]
474    check: bool,
475    /// Caller-owned operation identity, required only when applying drift.
476    #[arg(long)]
477    idempotency_key: Option<String>,
478    /// Optional caller-owned actor identity for a published snapshot.
479    #[arg(long, requires = "idempotency_key")]
480    actor_uuid: Option<String>,
481}
482
483#[derive(Subcommand)]
484enum SkillsCommand {
485    /// Install the packaged project-local skills.
486    Install(SkillMutationArgs),
487    /// Inspect managed skill provenance and user edits.
488    Status,
489    /// Update managed skills to the packaged bundle.
490    Update(SkillMutationArgs),
491    /// Remove only managed project-local skills.
492    Remove(SkillMutationArgs),
493}
494
495#[derive(Args)]
496struct SkillMutationArgs {
497    /// Explicitly resolve conflicts by replacing edited managed files.
498    #[arg(long)]
499    force: bool,
500}
501
502#[derive(Args)]
503struct RemoveArgs {
504    /// Required explicit non-interactive confirmation.
505    #[arg(long)]
506    yes: bool,
507}
508
509#[derive(Subcommand)]
510enum ConfigCommand {
511    /// Parse and validate graphforge.yaml.
512    Validate,
513    /// Emit deterministic, secret-free resolved configuration.
514    Resolve,
515    /// Set or show the credited author and committer (a per-user file).
516    User(identity::UserArgs),
517}
518
519#[derive(Subcommand)]
520enum InfraCommand {
521    /// Validate one named target without network access or mutation.
522    Validate(InfraValidateArgs),
523}
524
525#[derive(Args)]
526struct InfraValidateArgs {
527    /// Stable target identifier from graphforge.yaml.
528    #[arg(long)]
529    target: String,
530}
531
532#[derive(Subcommand)]
533enum CheckpointCommand {
534    /// Create a checkpoint of the current complete workspace.
535    Create(CreateArgs),
536    /// List active checkpoints in canonical order.
537    List(PageArgs),
538    /// Show authoritative metadata for one active checkpoint.
539    Show(ShowArgs),
540    /// Execute one read-only Cypher query against a checkpoint.
541    Open(OpenArgs),
542    /// Delete an active checkpoint reference.
543    Delete(DeleteArgs),
544    /// Diff two checkpoint/current endpoints.
545    Diff(DiffArgs),
546    /// Restore the complete workspace from a checkpoint.
547    Revert(RevertArgs),
548}
549
550#[derive(Args)]
551struct CreateArgs {
552    name: String,
553    #[arg(long)]
554    description: Option<String>,
555    #[arg(long)]
556    idempotency_key: String,
557    #[arg(long)]
558    actor_uuid: Option<String>,
559}
560
561#[derive(Args)]
562struct PageArgs {
563    #[arg(long, default_value_t = 100)]
564    limit: u32,
565    #[arg(long)]
566    after: Option<String>,
567}
568
569#[derive(Args)]
570struct ShowArgs {
571    name: String,
572}
573
574#[derive(Args)]
575struct OpenArgs {
576    name: String,
577    /// Read-only Cypher after `--`.
578    #[arg(last = true, required = true, num_args = 1..)]
579    query: Vec<String>,
580}
581
582#[derive(Args)]
583struct DeleteArgs {
584    name: String,
585    #[arg(long)]
586    idempotency_key: String,
587    #[arg(long)]
588    actor_uuid: Option<String>,
589}
590
591#[derive(Clone, Copy, ValueEnum)]
592enum ScopeArg {
593    Summary,
594    Graph,
595    Ontology,
596    Configuration,
597    Capabilities,
598    Provenance,
599    Knowledge,
600    Epistemic,
601    All,
602}
603
604#[derive(Clone, Copy, ValueEnum)]
605enum DetailArg {
606    Summary,
607    Records,
608}
609
610#[derive(Args)]
611struct DiffArgs {
612    /// Named checkpoint used as the earlier endpoint.
613    #[arg(long, conflicts_with = "from_current")]
614    from: Option<String>,
615    /// Use the current generation as the earlier endpoint.
616    #[arg(long, conflicts_with = "from")]
617    from_current: bool,
618    /// Named checkpoint used as the later endpoint.
619    #[arg(long, conflicts_with = "to_current")]
620    to: Option<String>,
621    /// Use the current generation as the later endpoint.
622    #[arg(long, conflicts_with = "to")]
623    to_current: bool,
624    #[arg(long, value_enum)]
625    scope: ScopeArg,
626    #[arg(long, value_enum)]
627    detail: DetailArg,
628    #[command(flatten)]
629    page: PageArgs,
630}
631
632#[derive(Args)]
633struct RevertArgs {
634    name: String,
635    /// Required bounded audit reason.
636    #[arg(long, required_unless_present = "preview")]
637    reason: Option<String>,
638    /// Required canonical UUID used for idempotent replay.
639    #[arg(long, required_unless_present = "preview")]
640    idempotency_key: Option<String>,
641    #[arg(long)]
642    actor_uuid: Option<String>,
643    /// Explicitly authorize this destructive operation in automation.
644    #[arg(long, conflicts_with = "preview")]
645    yes: bool,
646    /// Inspect the checkpoint and current generation without mutation.
647    #[arg(long)]
648    preview: bool,
649}
650
651pub(crate) fn canonical_uuid(value: &str) -> Result<Uuid, graphforge_api::GfError> {
652    let parsed = Uuid::parse_str(value)
653        .map_err(|_| graphforge_api::GfError::Validation("expected canonical UUID".into()))?;
654    if parsed.hyphenated().to_string() != value {
655        return Err(graphforge_api::GfError::Validation(
656            "expected canonical lowercase hyphenated UUID".into(),
657        ));
658    }
659    Ok(parsed)
660}
661
662fn actor(value: Option<&str>) -> Result<Option<Uuid>, graphforge_api::GfError> {
663    value.map(canonical_uuid).transpose()
664}
665
666fn page(args: &PageArgs) -> Result<PageRequest, graphforge_api::GfError> {
667    Ok(PageRequest {
668        limit: args.limit,
669        after: args.after.as_deref().map(PageToken::parse).transpose()?,
670        cancellation: None,
671    })
672}
673
674fn selector(
675    value: Option<String>,
676    current: bool,
677    endpoint: &str,
678) -> Result<CheckpointSelector, graphforge_api::GfError> {
679    match (value, current) {
680        (Some(name), false) => Ok(CheckpointSelector::Named(name)),
681        (None, true) => Ok(CheckpointSelector::Current),
682        _ => Err(graphforge_api::GfError::Validation(format!(
683            "exactly one of --{endpoint} or --{endpoint}-current is required"
684        ))),
685    }
686}
687
688fn write_result(
689    result: &ExecutionResult,
690    output: &mut dyn Write,
691) -> Result<(), graphforge_api::GfError> {
692    // The CLI IPC contract is one logical result batch. Engine/storage batches
693    // remain streaming internally; normalize only at this serialization edge.
694    let logical = if result.batches.is_empty() {
695        RecordBatch::new_empty(Arc::clone(&result.schema))
696    } else {
697        arrow::compute::concat_batches(&result.schema, &result.batches)
698            .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?
699    };
700    {
701        let mut writer = StreamWriter::try_new(&mut *output, result.schema.as_ref())
702            .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
703        writer
704            .write(&logical)
705            .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
706        writer
707            .finish()
708            .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
709    }
710    output
711        .flush()
712        .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))
713}
714
715#[derive(serde::Serialize)]
716struct JsonResultColumn<'a> {
717    name: &'a str,
718    data_type: String,
719    nullable: bool,
720}
721
722#[derive(serde::Serialize)]
723struct JsonExecutionResult<'a> {
724    contract: &'static str,
725    columns: Vec<JsonResultColumn<'a>>,
726    metadata: std::collections::BTreeMap<&'a str, &'a str>,
727    rows: Vec<Vec<serde_json::Value>>,
728}
729
730fn canonical_json_value(
731    value: serde_json::Value,
732    data_type: &DataType,
733) -> Result<serde_json::Value, graphforge_api::GfError> {
734    match (value, data_type) {
735        (serde_json::Value::String(hex), DataType::FixedSizeBinary(16)) => {
736            if hex.len() != 32 {
737                return Err(graphforge_api::GfError::Execution(
738                    "invalid 16-byte JSON result value".into(),
739                ));
740            }
741            let bytes = (0..hex.len())
742                .step_by(2)
743                .map(|index| u8::from_str_radix(&hex[index..index + 2], 16))
744                .collect::<Result<Vec<_>, _>>()
745                .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
746            Ok(serde_json::Value::String(
747                Uuid::from_slice(&bytes)
748                    .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?
749                    .hyphenated()
750                    .to_string(),
751            ))
752        }
753        (value, _) => Ok(value),
754    }
755}
756
757fn write_json_result(
758    result: &ExecutionResult,
759    output: &mut dyn Write,
760) -> Result<(), graphforge_api::GfError> {
761    let mut encoded = arrow::json::ArrayWriter::new(Vec::new());
762    let batches = result.batches.iter().collect::<Vec<_>>();
763    encoded
764        .write_batches(&batches)
765        .and_then(|()| encoded.finish())
766        .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
767    let objects: Vec<serde_json::Map<String, serde_json::Value>> =
768        serde_json::from_slice(&encoded.into_inner())
769            .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
770    let fields = result.schema.fields();
771    let mut rows = Vec::with_capacity(objects.len());
772    for mut object in objects {
773        let mut row = Vec::with_capacity(fields.len());
774        for field in fields {
775            let value = object
776                .remove(field.name())
777                .unwrap_or(serde_json::Value::Null);
778            row.push(canonical_json_value(value, field.data_type())?);
779        }
780        rows.push(row);
781    }
782    let value = JsonExecutionResult {
783        contract: "graphforge-cli-result/1",
784        columns: fields
785            .iter()
786            .map(|field| JsonResultColumn {
787                name: field.name(),
788                data_type: field.data_type().to_string(),
789                nullable: field.is_nullable(),
790            })
791            .collect(),
792        metadata: result
793            .schema
794            .metadata()
795            .iter()
796            .map(|(key, value)| (key.as_str(), value.as_str()))
797            .collect(),
798        rows,
799    };
800    serde_json::to_writer(&mut *output, &value)
801        .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
802    writeln!(output).map_err(|error| graphforge_api::GfError::Execution(error.to_string()))
803}
804
805fn write_execution_result(
806    result: &ExecutionResult,
807    json: bool,
808    output: &mut dyn Write,
809) -> Result<(), graphforge_api::GfError> {
810    if json {
811        write_json_result(result, output)
812    } else {
813        write_result(result, output)
814    }
815}
816
817#[derive(serde::Serialize)]
818struct JsonRevertPreview<'a> {
819    contract: &'static str,
820    checkpoint_uuid: Uuid,
821    source_generation_uuid: Uuid,
822    source_manifest_sha256: &'a str,
823    current_generation_uuid: Uuid,
824}
825
826fn write_revert_preview(
827    preview: &RevertCheckpointPreview,
828    json: bool,
829    output: &mut dyn Write,
830) -> Result<(), graphforge_api::GfError> {
831    if json {
832        serde_json::to_writer(
833            &mut *output,
834            &JsonRevertPreview {
835                contract: "graphforge-revert-preview/1",
836                checkpoint_uuid: preview.checkpoint_uuid,
837                source_generation_uuid: preview.source_generation_uuid,
838                source_manifest_sha256: &preview.source_manifest_sha256,
839                current_generation_uuid: preview.current_generation_uuid,
840            },
841        )
842        .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
843        writeln!(output).map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
844    } else {
845        writeln!(
846            output,
847            "checkpoint {} pins generation {} (sha256 {}); current generation is {}",
848            preview.checkpoint_uuid,
849            preview.source_generation_uuid,
850            preview.source_manifest_sha256,
851            preview.current_generation_uuid
852        )
853        .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
854    }
855    Ok(())
856}
857
858fn run_revert_preview(
859    path: &Path,
860    name: String,
861    json: bool,
862    output: &mut dyn Write,
863    diagnostics: &mut Diagnostics<'_>,
864) -> Result<(), graphforge_api::GfError> {
865    let preview =
866        GraphForge::preview_revert_to_checkpoint(path, PreviewRevertCheckpointRequest { name })?;
867    diagnostics.warn(&preview.warnings);
868    write_revert_preview(&preview, json, output)
869}
870
871fn run_revert(
872    graph: &mut GraphForge,
873    args: RevertArgs,
874    json: bool,
875    output: &mut dyn Write,
876) -> Result<(), graphforge_api::GfError> {
877    debug_assert!(args.yes && !args.preview);
878    let result = graph.revert_to_checkpoint(RevertCheckpointRequest {
879        name: args.name,
880        reason: args
881            .reason
882            .expect("clap requires --reason unless --preview is present"),
883        idempotency_key: OperationId(canonical_uuid(
884            args.idempotency_key
885                .as_deref()
886                .expect("clap requires --idempotency-key unless --preview is present"),
887        )?),
888        actor_uuid: actor(args.actor_uuid.as_deref())?,
889    })?;
890    write_execution_result(&result, json, output)
891}
892
893fn revert_args(command: &Command) -> Option<&RevertArgs> {
894    match command {
895        Command::Revert(args)
896        | Command::Checkpoint {
897            command: CheckpointCommand::Revert(args),
898        } => Some(args),
899        _ => None,
900    }
901}
902
903fn handle_revert_before_open(
904    command: &Command,
905    path: &Path,
906    json: bool,
907    output: &mut dyn Write,
908    diagnostics: &mut Diagnostics<'_>,
909) -> Result<bool, graphforge_api::GfError> {
910    let Some(args) = revert_args(command) else {
911        return Ok(false);
912    };
913    if args.preview {
914        run_revert_preview(path, args.name.clone(), json, output, diagnostics)?;
915        return Ok(true);
916    }
917    if !args.yes {
918        return Err(graphforge_api::GfError::Validation(
919            "revert requires explicit confirmation with --yes".into(),
920        ));
921    }
922    Ok(false)
923}
924
925#[allow(clippy::too_many_lines)] // one arm per repository command
926fn run_repository(
927    command: Command,
928    project_dir: Option<PathBuf>,
929    json: bool,
930    skill_bundle: &graphforge_api::SkillBundle<'_>,
931    output: &mut dyn Write,
932) -> Result<i32, graphforge_api::GfError> {
933    let start = project_dir.unwrap_or(
934        std::env::current_dir()
935            .map_err(|error| graphforge_api::GfError::Storage(error.to_string()))?,
936    );
937    let repository = RepositoryContext::discover(start)?;
938    let always_json = matches!(
939        &command,
940        Command::Config {
941            command: ConfigCommand::Resolve
942        }
943    );
944    let mut exit_code = 0;
945    let mut plain_output = "ok";
946    let value = match command {
947        Command::Init(args) => {
948            let init = repository.init_without_skills()?;
949            let skills = if args.no_skills {
950                None
951            } else {
952                Some(repository.skills_install(skill_bundle, false)?)
953            };
954            serde_json::to_value(serde_json::json!({
955                "root": ".",
956                "created_config": init.created_config,
957                "ignore_changed": init.ignore_changed,
958                "state": ".graphforge/state",
959                "skills": skills
960            }))
961        }
962        Command::Sync(args) => {
963            let result = repository.sync(RepositorySyncRequest {
964                check: args.check,
965                operation_uuid: args
966                    .idempotency_key
967                    .as_deref()
968                    .map(canonical_uuid)
969                    .transpose()?,
970                actor_uuid: actor(args.actor_uuid.as_deref())?,
971            })?;
972            if args.check && result.status == RepositorySyncStatus::Drift {
973                exit_code = OUT_OF_SYNC_EXIT_CODE;
974            }
975            plain_output = match result.status {
976                RepositorySyncStatus::InSync => "in_sync",
977                RepositorySyncStatus::Drift => "drift",
978                RepositorySyncStatus::Published => "published",
979            };
980            serde_json::to_value(result)
981        }
982        Command::Remove(args) => {
983            let receipt = repository.remove(args.yes)?;
984            serde_json::to_value(serde_json::json!({
985                "target": ".graphforge/state",
986                "removed": receipt.removed
987            }))
988        }
989        Command::Config {
990            command: ConfigCommand::Validate,
991        } => {
992            repository.load_config()?;
993            Ok(serde_json::json!({"valid": true}))
994        }
995        Command::Config {
996            command: ConfigCommand::Resolve,
997        } => Ok(repository.resolve_config()?),
998        Command::Config {
999            command: ConfigCommand::User(_),
1000        } => unreachable!("`gf config user` is dispatched before the repository commands"),
1001        Command::Infra {
1002            command: InfraCommand::Validate(args),
1003        } => {
1004            plain_output = "valid";
1005            serde_json::to_value(repository.validate_infra_target(&args.target)?)
1006        }
1007        Command::Skills {
1008            command: SkillsCommand::Install(args),
1009        } => serde_json::to_value(repository.skills_install(skill_bundle, args.force)?),
1010        Command::Skills {
1011            command: SkillsCommand::Status,
1012        } => serde_json::to_value(repository.skills_status(skill_bundle)?),
1013        Command::Skills {
1014            command: SkillsCommand::Update(args),
1015        } => serde_json::to_value(repository.skills_update(skill_bundle, args.force)?),
1016        Command::Skills {
1017            command: SkillsCommand::Remove(args),
1018        } => serde_json::to_value(repository.skills_remove(args.force)?),
1019        _ => unreachable!(),
1020    }
1021    .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
1022    if json || always_json {
1023        writeln!(
1024            output,
1025            "{}",
1026            serde_json::to_string(&value)
1027                .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?
1028        )
1029        .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
1030    } else {
1031        writeln!(output, "{plain_output}")
1032            .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
1033    }
1034    Ok(exit_code)
1035}
1036
1037fn run_repository_with_bundle(
1038    command: Command,
1039    project_dir: Option<PathBuf>,
1040    json: bool,
1041    bundle_dir: Option<&Path>,
1042    output: &mut dyn Write,
1043) -> Result<i32, graphforge_api::GfError> {
1044    let needs_packaged_bundle = matches!(&command, Command::Init(args) if !args.no_skills)
1045        || matches!(
1046            &command,
1047            Command::Skills {
1048                command: SkillsCommand::Install(_)
1049                    | SkillsCommand::Status
1050                    | SkillsCommand::Update(_)
1051            }
1052        );
1053    if !needs_packaged_bundle {
1054        return run_repository(command, project_dir, json, &project_skill_bundle(), output);
1055    }
1056    let owned_bundle = bundle_dir.map(load_skill_bundle).transpose()?;
1057    let owned_files = owned_bundle.as_ref().map(|bundle| {
1058        bundle
1059            .files
1060            .iter()
1061            .map(|file| graphforge_api::SkillBundleFile {
1062                path: &file.path,
1063                bytes: &file.bytes,
1064            })
1065            .collect::<Vec<_>>()
1066    });
1067    let embedded = project_skill_bundle();
1068    let skill_bundle =
1069        owned_bundle
1070            .as_ref()
1071            .zip(owned_files.as_ref())
1072            .map_or(embedded, |(bundle, files)| graphforge_api::SkillBundle {
1073                manifest: &bundle.manifest,
1074                files,
1075            });
1076    run_repository(command, project_dir, json, &skill_bundle, output)
1077}
1078
1079fn resolve_project_path(
1080    project: Option<PathBuf>,
1081    project_dir: Option<PathBuf>,
1082) -> Result<PathBuf, graphforge_api::GfError> {
1083    match project {
1084        Some(path) => Ok(path),
1085        None => Ok(RepositoryContext::discover(
1086            project_dir.unwrap_or(
1087                std::env::current_dir()
1088                    .map_err(|error| graphforge_api::GfError::Storage(error.to_string()))?,
1089            ),
1090        )?
1091        .state_path),
1092    }
1093}
1094
1095fn is_repository_command(command: &Command) -> bool {
1096    matches!(
1097        command,
1098        Command::Init(_)
1099            | Command::Sync(_)
1100            | Command::Remove(_)
1101            | Command::Config {
1102                command: ConfigCommand::Validate | ConfigCommand::Resolve
1103            }
1104            | Command::Infra { .. }
1105            | Command::Skills { .. }
1106    )
1107}
1108
1109#[allow(clippy::too_many_lines)] // CLI command dispatch table
1110pub(crate) enum CliRuntimeError {
1111    Core(graphforge_api::GfError),
1112    MultiOntology(graphforge_api::MultiOntologyError),
1113}
1114
1115impl From<graphforge_api::GfError> for CliRuntimeError {
1116    fn from(error: graphforge_api::GfError) -> Self {
1117        Self::Core(error)
1118    }
1119}
1120
1121impl From<graphforge_api::MultiOntologyError> for CliRuntimeError {
1122    fn from(error: graphforge_api::MultiOntologyError) -> Self {
1123        Self::MultiOntology(error)
1124    }
1125}
1126
1127use diagnostics::{Diagnostics, WarningOutput};
1128
1129#[allow(clippy::too_many_lines)]
1130fn run(
1131    cli: Cli,
1132    output: &mut dyn Write,
1133    diagnostics: &mut Diagnostics<'_>,
1134) -> Result<i32, CliRuntimeError> {
1135    let _capture = storage_attribution_cli::capture(&cli)?;
1136    let allocation = if cli.diagnostics.allocation_diagnostics {
1137        if !cli.json {
1138            return Err(graphforge_api::GfError::Validation(
1139                "allocation diagnostics require --json".into(),
1140            )
1141            .into());
1142        }
1143        Some(graphforge_api::StorageAllocationDiagnostics::read(
1144            std::io::stdin().lock(),
1145        )?)
1146    } else {
1147        None
1148    };
1149    let mut command_output = WarningOutput::new(&mut *output, cli.json, diagnostics);
1150    let result = run_with_allocation(cli, &mut command_output, diagnostics, allocation.as_ref());
1151    command_output
1152        .finish(result.is_ok(), diagnostics)
1153        .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
1154    let result = result?;
1155    if let Some(allocation) = allocation {
1156        let (current, peak) = allocation.totals()?;
1157        // The composition sums to `peak_allocated_bytes`, so a consumer can
1158        // attribute the whole high-water mark rather than a fraction of it.
1159        let (composition, residency, transitions, peak_transition) = allocation.peak_detail()?;
1160        serde_json::to_writer(&mut *output, &serde_json::json!({"contract":"graphforge-allocation-operation/1", "current_allocated_bytes":current, "peak_allocated_bytes":peak, "peak_component_allocated_bytes":composition, "component_residency":residency, "owner_transitions":transitions, "peak_transition":peak_transition})).map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
1161        writeln!(output).map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
1162    }
1163    Ok(result)
1164}
1165
1166/// Open the `--project` and report anything the open warns about.
1167fn open_cli_graph_warning(
1168    path: &Path,
1169    allocation: Option<&graphforge_api::StorageAllocationDiagnostics>,
1170    diagnostics: &mut Diagnostics<'_>,
1171) -> Result<GraphForge, graphforge_api::GfError> {
1172    let graph = open_cli_graph(path, allocation)?;
1173    diagnostics.warn(&graph.open_warnings());
1174    Ok(graph)
1175}
1176
1177pub(crate) fn open_cli_graph(
1178    path: &Path,
1179    allocation: Option<&graphforge_api::StorageAllocationDiagnostics>,
1180) -> Result<GraphForge, graphforge_api::GfError> {
1181    if let Some(allocation) = allocation {
1182        allocation.open(path)
1183    } else {
1184        let path = path.to_str().ok_or_else(|| {
1185            graphforge_api::GfError::Validation("--project must be valid UTF-8".into())
1186        })?;
1187        GraphForge::new(Some(path))
1188    }
1189}
1190
1191#[allow(clippy::too_many_lines)]
1192fn run_with_allocation(
1193    cli: Cli,
1194    output: &mut dyn Write,
1195    diagnostics: &mut Diagnostics<'_>,
1196    allocation: Option<&graphforge_api::StorageAllocationDiagnostics>,
1197) -> Result<i32, CliRuntimeError> {
1198    if cli.info {
1199        writeln!(output, "graphforge {}", env!("CARGO_PKG_VERSION"))
1200            .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
1201        return Ok(0);
1202    }
1203    let Some(command) = cli.command else {
1204        writeln!(output, "GraphForge — use --help for options")
1205            .map_err(|error| graphforge_api::GfError::Execution(error.to_string()))?;
1206        return Ok(0);
1207    };
1208    let command = match command {
1209        Command::Telemetry(args) => return run_telemetry(args, output).map_err(Into::into),
1210        command => command,
1211    };
1212    if let Command::Config {
1213        command: ConfigCommand::User(args),
1214    } = &command
1215    {
1216        return identity::run_config_user(args, cli.json, output)
1217            .map(|()| 0)
1218            .map_err(Into::into);
1219    }
1220    if is_repository_command(&command) {
1221        return run_repository_with_bundle(
1222            command,
1223            cli.project_dir,
1224            cli.json,
1225            cli.skills_bundle_dir.as_deref(),
1226            output,
1227        )
1228        .map_err(Into::into);
1229    }
1230    if let Command::Auth(args) = command {
1231        return auth::run(args, cli.json, output);
1232    }
1233    #[cfg(feature = "hub-test-support")]
1234    let command = match hub_test_support::dispatch(
1235        command,
1236        cli.project.as_deref(),
1237        cli.project_dir.as_deref(),
1238        cli.json,
1239        output,
1240        diagnostics,
1241        allocation,
1242    )? {
1243        std::ops::ControlFlow::Break(()) => return Ok(0),
1244        std::ops::ControlFlow::Continue(command) => command,
1245    };
1246    if let hub @ (Command::Clone(_) | Command::Publish(_) | Command::Hub(_)) = command {
1247        return hub_publish::run_hub_command(
1248            hub,
1249            cli.project,
1250            cli.project_dir,
1251            cli.json,
1252            output,
1253            &mut *diagnostics,
1254        );
1255    }
1256    if matches!(&command, Command::Push(_) | Command::Pull(_))
1257        || matches!(&command, Command::Log(args) if args.remote.is_some())
1258    {
1259        return porcelain::run_remote(
1260            command,
1261            cli.project,
1262            cli.project_dir,
1263            cli.json,
1264            output,
1265            &mut *diagnostics,
1266        )
1267        .map(|()| 0)
1268        .map_err(Into::into);
1269    }
1270    if let Command::Ontology { command } = &command
1271        && let Some(result) = ontology_cli::run_without_project(command, cli.json, output)
1272    {
1273        return result.map(|()| 0).map_err(Into::into);
1274    }
1275    // Repository-independent portable commands must not call RepositoryContext::discover.
1276    if let Command::Portable { command } = command {
1277        match command {
1278            portable_cli::PortableCommand::Verify(_)
1279            | portable_cli::PortableCommand::PublishOci(_)
1280            | portable_cli::PortableCommand::PullOci(_) => {
1281                return portable_cli::run_portable_without_graph(
1282                    Path::new(""),
1283                    command,
1284                    cli.json,
1285                    output,
1286                    allocation,
1287                )
1288                .map(|()| 0);
1289            }
1290            command => {
1291                let path = resolve_project_path(cli.project, cli.project_dir)?;
1292                let path_text = path.to_str().ok_or_else(|| {
1293                    graphforge_api::GfError::Validation("--project must be valid UTF-8".into())
1294                })?;
1295                let mut graph =
1296                    open_cli_graph_warning(Path::new(path_text), allocation, &mut *diagnostics)?;
1297                return portable_cli::run_portable(
1298                    &mut graph, &path, command, cli.json, output, allocation,
1299                )
1300                .map(|()| 0);
1301            }
1302        }
1303    }
1304    let path = resolve_project_path(cli.project, cli.project_dir)?;
1305    let command = match command {
1306        Command::Import(args) => {
1307            return portable_cli::run_import(
1308                &path,
1309                args,
1310                cli.json,
1311                output,
1312                &mut *diagnostics,
1313                allocation,
1314            )
1315            .map(|()| 0);
1316        }
1317        command => command,
1318    };
1319    if handle_revert_before_open(&command, &path, cli.json, output, &mut *diagnostics)? {
1320        return Ok(0);
1321    }
1322    let path_text = path.to_str().ok_or_else(|| {
1323        graphforge_api::GfError::Validation("--project must be valid UTF-8".into())
1324    })?;
1325    let mut graph = open_cli_graph_warning(Path::new(path_text), allocation, &mut *diagnostics)?;
1326    let command = match command {
1327        command @ (Command::Status(_)
1328        | Command::Log(_)
1329        | Command::Commit(_)
1330        | Command::Branch(_)
1331        | Command::Switch(_)
1332        | Command::Tag(_)) => {
1333            return porcelain::run_local(&mut graph, command, cli.json, output)
1334                .map(|()| 0)
1335                .map_err(Into::into);
1336        }
1337        Command::Export(args) => {
1338            return portable_cli::run_export(&graph, args, cli.json, output).map(|()| 0);
1339        }
1340        Command::SavedQuery { command } => {
1341            return saved_queries_cli::run(&mut graph, command, cli.json, output)
1342                .map(|()| 0)
1343                .map_err(Into::into);
1344        }
1345        Command::Query(args) => {
1346            return portable_cli::run_query(&graph, &args, cli.json, output)
1347                .map(|()| 0)
1348                .map_err(Into::into);
1349        }
1350        Command::ImportSession { command } => {
1351            return portable_cli::run_import_session(&graph, command, cli.json, output)
1352                .map(|()| 0)
1353                .map_err(Into::into);
1354        }
1355        Command::Recovery => {
1356            return maintenance_cli::run_recovery(&graph, cli.json, output)
1357                .map(|()| 0)
1358                .map_err(Into::into);
1359        }
1360        Command::StorageAttribution(args) => {
1361            return storage_attribution_cli::run_storage_attribution(
1362                graph, &path, &args, cli.json, output, allocation,
1363            )
1364            .map(|()| 0)
1365            .map_err(Into::into);
1366        }
1367        Command::Transaction { command } => {
1368            return maintenance_cli::run_transaction(&graph, command, cli.json, output)
1369                .map(|()| 0)
1370                .map_err(Into::into);
1371        }
1372        Command::Maintenance { command } => {
1373            return maintenance_cli::run_maintenance(&mut graph, command, cli.json, output)
1374                .map(|()| 0)
1375                .map_err(Into::into);
1376        }
1377        Command::Ontology { command } => {
1378            return ontology_cli::run_ontology(&mut graph, command, cli.json, output).map(|()| 0);
1379        }
1380        Command::Research { command } => {
1381            return research_cli::run_research(&mut graph, command, cli.json, output).map(|()| 0);
1382        }
1383        Command::SourceArtifact { command } => {
1384            return source_artifact_cli::run_source_artifact(&mut graph, command, cli.json, output)
1385                .map(|()| 0)
1386                .map_err(Into::into);
1387        }
1388        command => command,
1389    };
1390    let command = match command {
1391        Command::Revert(args)
1392        | Command::Checkpoint {
1393            command: CheckpointCommand::Revert(args),
1394        } => {
1395            return run_revert(&mut graph, args, cli.json, output)
1396                .map(|()| 0)
1397                .map_err(Into::into);
1398        }
1399        command => command,
1400    };
1401    let result = match command {
1402        Command::Checkpoint { command } => match command {
1403            CheckpointCommand::Create(args) => graph.checkpoint(CheckpointRequest {
1404                name: args.name,
1405                description: args.description,
1406                idempotency_key: OperationId(canonical_uuid(&args.idempotency_key)?),
1407                actor_uuid: actor(args.actor_uuid.as_deref())?,
1408            })?,
1409            CheckpointCommand::List(args) => {
1410                graph.list_checkpoints(ListCheckpointsRequest { page: page(&args)? })?
1411            }
1412            CheckpointCommand::Show(args) => {
1413                graph.show_checkpoint(ShowCheckpointRequest { name: args.name })?
1414            }
1415            CheckpointCommand::Open(args) => {
1416                let view = graph.open_checkpoint(&args.name)?;
1417                view.execute(&args.query.join(" "))?
1418            }
1419            CheckpointCommand::Delete(args) => {
1420                graph.delete_checkpoint(DeleteCheckpointRequest {
1421                    name: args.name,
1422                    idempotency_key: OperationId(canonical_uuid(&args.idempotency_key)?),
1423                    actor_uuid: actor(args.actor_uuid.as_deref())?,
1424                })?
1425            }
1426            CheckpointCommand::Diff(args) => graph.diff_checkpoints(DiffCheckpointsRequest {
1427                from: selector(args.from, args.from_current, "from")?,
1428                to: selector(args.to, args.to_current, "to")?,
1429                scope: match args.scope {
1430                    ScopeArg::Summary => CheckpointDiffScope::Summary,
1431                    ScopeArg::Graph => CheckpointDiffScope::Graph,
1432                    ScopeArg::Ontology => CheckpointDiffScope::Ontology,
1433                    ScopeArg::Configuration => CheckpointDiffScope::Configuration,
1434                    ScopeArg::Capabilities => CheckpointDiffScope::Capabilities,
1435                    ScopeArg::Provenance => CheckpointDiffScope::Provenance,
1436                    ScopeArg::Knowledge => CheckpointDiffScope::Knowledge,
1437                    ScopeArg::Epistemic => CheckpointDiffScope::Epistemic,
1438                    ScopeArg::All => CheckpointDiffScope::All,
1439                },
1440                detail: match args.detail {
1441                    DetailArg::Summary => CheckpointDiffDetail::Summary,
1442                    DetailArg::Records => CheckpointDiffDetail::Records,
1443                },
1444                page: page(&args.page)?,
1445            })?,
1446            CheckpointCommand::Revert(_) => unreachable!("revert handled before result dispatch"),
1447        },
1448        _ => unreachable!(),
1449    };
1450    write_execution_result(&result, cli.json, output)?;
1451    Ok(0)
1452}
1453
1454/// Captured result of one Rust-owned CLI invocation.
1455#[derive(Clone, Debug, Eq, PartialEq)]
1456pub struct CliExecution {
1457    /// Process-compatible exit status.
1458    pub exit_code: i32,
1459    /// Exact standard-output bytes, including Arrow IPC results.
1460    pub stdout: Vec<u8>,
1461    /// Exact standard-error bytes.
1462    pub stderr: Vec<u8>,
1463}
1464
1465/// Parse and execute the GraphForge CLI without terminating the host process.
1466pub fn execute<I, T>(args: I) -> CliExecution
1467where
1468    I: IntoIterator<Item = T>,
1469    T: Into<std::ffi::OsString> + Clone,
1470{
1471    let mut stdout = Vec::new();
1472    let mut stderr = Vec::new();
1473    let mut args: Vec<std::ffi::OsString> = args.into_iter().map(Into::into).collect();
1474    if args.is_empty() {
1475        args.push("graphforge".into());
1476    } else {
1477        args[0] = "graphforge".into();
1478    }
1479    let cli = match parse_cli(&args) {
1480        Ok(cli) => cli,
1481        Err(error) => return argument_error_execution(&error, requests_json(&args)),
1482    };
1483    let json = cli.json;
1484    let mut diagnostics = Diagnostics::new(json, &mut stderr);
1485    let result = run(cli, &mut stdout, &mut diagnostics);
1486    let warnings = diagnostics.collected();
1487    drop(diagnostics);
1488    let exit_code = match result {
1489        Ok(exit_code) => exit_code,
1490        Err(error) => {
1491            write_runtime_error(&error, json, &mut stderr, &warnings)
1492                .expect("writing to Vec cannot fail");
1493            error_exit_code(&error)
1494        }
1495    };
1496    CliExecution {
1497        exit_code,
1498        stdout,
1499        stderr,
1500    }
1501}
1502
1503/// Whether the arguments ask for JSON, which a refused argument list cannot
1504/// say through the parsed `--json` flag.
1505fn requests_json(args: &[std::ffi::OsString]) -> bool {
1506    args.iter().any(|arg| arg == "--json")
1507}
1508
1509/// The finished execution of an argument list clap refused, or that asked for
1510/// help or the version: help and version print to stdout, any other refusal to
1511/// stderr, as one JSON error document when `json` is set.
1512fn argument_error_execution(error: &clap::Error, json: bool) -> CliExecution {
1513    let mut stdout = Vec::new();
1514    let mut stderr = Vec::new();
1515    if matches!(
1516        error.kind(),
1517        ErrorKind::DisplayHelp | ErrorKind::DisplayVersion
1518    ) {
1519        stdout = error.to_string().into_bytes();
1520    } else if json {
1521        write_json_error(
1522            &mut stderr,
1523            "GF_VALIDATION",
1524            &error.to_string(),
1525            JsonErrorDetails {
1526                source: "argument_parser",
1527                kind: clap_error_kind(error.kind()),
1528                semantic_code: None,
1529            },
1530            &[],
1531        )
1532        .expect("writing to Vec cannot fail");
1533    } else {
1534        stderr = error.to_string().into_bytes();
1535    }
1536    CliExecution {
1537        exit_code: error.exit_code(),
1538        stdout,
1539        stderr,
1540    }
1541}
1542
1543fn write_error(
1544    error: &graphforge_api::GfError,
1545    json: bool,
1546    output: &mut dyn Write,
1547    warnings: &[graphforge_api::CoreVersionWarning],
1548) -> io::Result<()> {
1549    if json {
1550        write_json_error(
1551            output,
1552            error.code(),
1553            &error.to_string(),
1554            JsonErrorDetails {
1555                source: "runtime",
1556                kind: runtime_error_kind(error),
1557                semantic_code: stable_semantic_code(error),
1558            },
1559            warnings,
1560        )
1561    } else {
1562        writeln!(output, "{}: {error}", error.code())
1563    }
1564}
1565
1566/// The one error document, carrying the warnings raised before the failure.
1567fn write_runtime_error(
1568    error: &CliRuntimeError,
1569    json: bool,
1570    output: &mut dyn Write,
1571    warnings: &[graphforge_api::CoreVersionWarning],
1572) -> io::Result<()> {
1573    match error {
1574        CliRuntimeError::Core(error) => write_error(error, json, output, warnings),
1575        CliRuntimeError::MultiOntology(error) if json => {
1576            #[derive(serde::Serialize)]
1577            struct Envelope<'a> {
1578                error: &'a graphforge_api::MultiOntologyError,
1579                #[serde(skip_serializing_if = "<[_]>::is_empty")]
1580                warnings: &'a [graphforge_api::CoreVersionWarning],
1581            }
1582            serde_json::to_writer(&mut *output, &Envelope { error, warnings })
1583                .map_err(io::Error::other)?;
1584            writeln!(output)
1585        }
1586        CliRuntimeError::MultiOntology(error) => {
1587            writeln!(output, "{}: {}", error.code, error.message)
1588        }
1589    }
1590}
1591
1592#[derive(Clone, Copy)]
1593struct JsonErrorDetails<'a> {
1594    source: &'static str,
1595    kind: &'static str,
1596    semantic_code: Option<&'a str>,
1597}
1598
1599fn write_json_error(
1600    output: &mut dyn Write,
1601    code: &'static str,
1602    message: &str,
1603    details: JsonErrorDetails<'_>,
1604    warnings: &[graphforge_api::CoreVersionWarning],
1605) -> io::Result<()> {
1606    let warnings = if warnings.is_empty() {
1607        String::new()
1608    } else {
1609        format!(
1610            ",\"warnings\":{}",
1611            serde_json::to_string(warnings).map_err(io::Error::other)?
1612        )
1613    };
1614    let code = serde_json::to_string(code).map_err(io::Error::other)?;
1615    let message = serde_json::to_string(message).map_err(io::Error::other)?;
1616    let source = serde_json::to_string(details.source).map_err(io::Error::other)?;
1617    let kind = serde_json::to_string(details.kind).map_err(io::Error::other)?;
1618    if let Some(semantic_code) = details.semantic_code {
1619        let semantic_code = serde_json::to_string(semantic_code).map_err(io::Error::other)?;
1620        writeln!(
1621            output,
1622            "{{\"error\":{{\"code\":{code},\"message\":{message},\"details\":{{\"source\":{source},\"kind\":{kind},\"semantic_code\":{semantic_code}}}}}{warnings}}}"
1623        )
1624    } else {
1625        writeln!(
1626            output,
1627            "{{\"error\":{{\"code\":{code},\"message\":{message},\"details\":{{\"source\":{source},\"kind\":{kind}}}}}{warnings}}}"
1628        )
1629    }
1630}
1631
1632fn stable_semantic_code(error: &graphforge_api::GfError) -> Option<&str> {
1633    match error.code() {
1634        "GF_CANCELLED" => return Some("lifecycle.cancelled"),
1635        "GF_RESOURCE_LIMIT" => return Some("resource.bytes"),
1636        "GF_TRANSACTION_CONFLICT" => return Some("inventory.generation_conflict"),
1637        _ => {}
1638    }
1639    let message = match error {
1640        graphforge_api::GfError::Validation(message)
1641        | graphforge_api::GfError::Execution(message)
1642        | graphforge_api::GfError::Storage(message)
1643        | graphforge_api::GfError::Ontology(message) => message.as_str(),
1644        _ => return None,
1645    };
1646    let candidate = message.split_once(':')?.0;
1647    if candidate.contains('.')
1648        && candidate
1649            .bytes()
1650            .all(|byte| byte.is_ascii_lowercase() || byte == b'.' || byte == b'_')
1651    {
1652        return Some(candidate);
1653    }
1654    match candidate {
1655        "Cancelled" => Some("lifecycle.cancelled"),
1656        "LimitExceeded" => Some("resource.bytes"),
1657        "UnsupportedFuture" => Some("interchange.unsupported_future"),
1658        "DigestMismatch" | "DuplicateEntry" | "InvalidStructure" => Some("interchange.integrity"),
1659        "ConcurrentMutation" => Some("inventory.generation_conflict"),
1660        "Incompatible" => Some("interchange.selection"),
1661        "Io" | "InvalidPath" => Some("interchange.io"),
1662        _ if message.contains("dependency-blocked") => Some("dependency.in_use"),
1663        _ if message.contains("selector is ambiguous") => Some("resolution.ambiguous"),
1664        _ if message.contains("not found") || message.contains("is absent") => {
1665            Some("inventory.not_found")
1666        }
1667        _ if message.contains("generation is stale")
1668            || message.contains("fingerprint is stale") =>
1669        {
1670            Some("inventory.generation_conflict")
1671        }
1672        _ => None,
1673    }
1674}
1675
1676const fn clap_error_kind(kind: ErrorKind) -> &'static str {
1677    match kind {
1678        ErrorKind::InvalidValue => "invalid_value",
1679        ErrorKind::UnknownArgument => "unknown_argument",
1680        ErrorKind::InvalidSubcommand => "invalid_subcommand",
1681        ErrorKind::NoEquals => "missing_equals",
1682        ErrorKind::ValueValidation => "value_validation",
1683        ErrorKind::TooManyValues => "too_many_values",
1684        ErrorKind::TooFewValues => "too_few_values",
1685        ErrorKind::WrongNumberOfValues => "wrong_number_of_values",
1686        ErrorKind::ArgumentConflict => "argument_conflict",
1687        ErrorKind::MissingRequiredArgument => "missing_required_argument",
1688        ErrorKind::MissingSubcommand => "missing_subcommand",
1689        ErrorKind::DisplayHelp => "display_help",
1690        ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand => "display_help_on_missing_input",
1691        ErrorKind::DisplayVersion => "display_version",
1692        ErrorKind::Io => "io",
1693        ErrorKind::Format => "format",
1694        _ => "other",
1695    }
1696}
1697
1698const fn runtime_error_kind(error: &graphforge_api::GfError) -> &'static str {
1699    match error {
1700        graphforge_api::GfError::NotImplemented(_) => "not_implemented",
1701        graphforge_api::GfError::Parse { .. } => "parse",
1702        graphforge_api::GfError::Bind { .. } => "bind",
1703        graphforge_api::GfError::LoweringExecution(_) | graphforge_api::GfError::Execution(_) => {
1704            "execution"
1705        }
1706        graphforge_api::GfError::Lowering(error) => error.fault_domain(),
1707        graphforge_api::GfError::Algorithm(error) => error.fault_domain(),
1708        graphforge_api::GfError::BindValidation { .. } | graphforge_api::GfError::Validation(_) => {
1709            "validation"
1710        }
1711        graphforge_api::GfError::BindPlan { .. } | graphforge_api::GfError::Plan(_) => "plan",
1712        graphforge_api::GfError::Provider { .. } => "provider",
1713        graphforge_api::GfError::Storage(_) => "storage",
1714        graphforge_api::GfError::Project { .. } => "project",
1715        graphforge_api::GfError::Api { .. } => "api",
1716        graphforge_api::GfError::Lifecycle(_) => "lifecycle",
1717        graphforge_api::GfError::Ontology(_) => "ontology",
1718    }
1719}
1720
1721fn error_exit_code(error: &CliRuntimeError) -> i32 {
1722    match error {
1723        CliRuntimeError::Core(error) if error.code() == "GF_VALIDATION" => 2,
1724        CliRuntimeError::Core(graphforge_api::GfError::Storage(_)) => 3,
1725        CliRuntimeError::MultiOntology(error) if error.code == "GF_VALIDATION" => 2,
1726        // Portable I/O, unsupported filesystems, and insufficient target
1727        // storage all use the storage exit class regardless of input source.
1728        CliRuntimeError::MultiOntology(error)
1729            if error.code == "GF_UNSUPPORTED_FILESYSTEM"
1730                || error.code == "GF_STORAGE"
1731                || error
1732                    .diagnostics
1733                    .iter()
1734                    .any(|diagnostic| diagnostic.code == "storage.insufficient_space") =>
1735        {
1736            3
1737        }
1738        _ => 1,
1739    }
1740}
1741
1742/// Parse the arguments with the research help text attached.
1743fn parse_cli<I, T>(args: I) -> Result<Cli, clap::Error>
1744where
1745    I: IntoIterator<Item = T>,
1746    T: Into<std::ffi::OsString> + Clone,
1747{
1748    use clap::FromArgMatches as _;
1749    Cli::from_arg_matches(&research_help::command().try_get_matches_from(args)?)
1750}
1751
1752/// Stream process output directly and terminate with the native CLI exit status.
1753pub fn run_process() {
1754    let args: Vec<std::ffi::OsString> = std::env::args_os().collect();
1755    let cli = match parse_cli(&args) {
1756        Ok(cli) => cli,
1757        // Help and the version keep clap's own styled output; a refusal
1758        // under `--json` is the one JSON error document `execute` gives.
1759        Err(error) if !requests_json(&args) || !error.use_stderr() => error.exit(),
1760        Err(error) => {
1761            let refused = argument_error_execution(&error, true);
1762            let _ = io::stderr().write_all(&refused.stderr);
1763            std::process::exit(refused.exit_code);
1764        }
1765    };
1766    let json = cli.json;
1767    let mut output = io::stdout().lock();
1768    hub_publish::allow_device_flow();
1769    hub_clone::attach_to_process();
1770    let mut stderr = io::stderr();
1771    let mut diagnostics = Diagnostics::new(json, &mut stderr);
1772    let result = run(cli, &mut output, &mut diagnostics);
1773    let warnings = diagnostics.collected();
1774    drop(diagnostics);
1775    match result {
1776        Ok(exit_code) if exit_code != 0 => {
1777            let _ = output.flush();
1778            std::process::exit(exit_code);
1779        }
1780        Ok(_) => {}
1781        Err(error) => {
1782            let _ = output.flush();
1783            write_runtime_error(&error, json, &mut stderr.lock(), &warnings)
1784                .expect("write CLI stderr");
1785            std::process::exit(error_exit_code(&error));
1786        }
1787    }
1788}
1789
1790#[cfg(test)]
1791mod tests {
1792    use super::*;
1793    use std::fs;
1794    use tempfile::tempdir;
1795
1796    fn write_loader_manifest(root: &Path, paths: &[String]) {
1797        fs::write(
1798            root.join("manifest.json"),
1799            serde_json::to_vec(&serde_json::json!({
1800                "files": paths.iter().map(|path| serde_json::json!({"path": path})).collect::<Vec<_>>()
1801            }))
1802            .unwrap(),
1803        )
1804        .unwrap();
1805    }
1806
1807    #[test]
1808    fn bounded_file_and_skill_entry_validation_fail_before_payload_use() {
1809        let root = tempdir().unwrap();
1810        let file = root.path().join("skill.md");
1811        fs::write(&file, b"abcd").unwrap();
1812        assert_eq!(read_bounded_file(&file, 4, "bounded").unwrap(), b"abcd");
1813        assert!(matches!(
1814            read_bounded_file(&file, 3, "bounded"),
1815            Err(graphforge_api::GfError::Validation(message)) if message == "bounded"
1816        ));
1817        assert!(matches!(
1818            read_bounded_file(root.path(), 100, "regular"),
1819            Err(graphforge_api::GfError::Validation(message)) if message == "regular"
1820        ));
1821        assert!(matches!(
1822            read_bounded_file(&root.path().join("absent"), 100, "missing"),
1823            Err(graphforge_api::GfError::Storage(_))
1824        ));
1825
1826        assert!(matches!(
1827            load_skill_file(root.path(), &serde_json::json!({})),
1828            Err(graphforge_api::GfError::Validation(message))
1829                if message == "project skill file path is required"
1830        ));
1831        for path in ["", "../escape", "/absolute"] {
1832            assert!(matches!(
1833                load_skill_file(root.path(), &serde_json::json!({"path": path})),
1834                Err(graphforge_api::GfError::Validation(_))
1835            ));
1836        }
1837        assert!(matches!(
1838            load_skill_file(
1839                root.path(),
1840                &serde_json::json!({"path": "missing/skill.md"})
1841            ),
1842            Err(graphforge_api::GfError::Storage(_))
1843        ));
1844    }
1845
1846    #[cfg(unix)]
1847    #[test]
1848    fn wave11_skill_bundle_rejects_linked_components_nonfiles_and_entry_overflow() {
1849        use std::os::unix::fs::symlink;
1850
1851        let external = tempdir().unwrap();
1852        fs::write(external.path().join("SKILL.md"), b"external").unwrap();
1853        let root = tempdir().unwrap();
1854        symlink(external.path(), root.path().join("linked")).unwrap();
1855        assert!(matches!(
1856            load_skill_file(
1857                root.path(),
1858                &serde_json::json!({"path": "linked/SKILL.md"})
1859            ),
1860            Err(graphforge_api::GfError::Validation(message))
1861                if message.contains("must not contain symlinks")
1862        ));
1863        assert_eq!(
1864            fs::read(external.path().join("SKILL.md")).unwrap(),
1865            b"external"
1866        );
1867
1868        let root = tempdir().unwrap();
1869        fs::create_dir(root.path().join("directory.md")).unwrap();
1870        assert!(matches!(
1871            load_skill_file(
1872                root.path(),
1873                &serde_json::json!({"path": "directory.md"})
1874            ),
1875            Err(graphforge_api::GfError::Validation(message))
1876                if message.contains("must be a real file")
1877        ));
1878
1879        let root = tempdir().unwrap();
1880        let paths = (0..=MAX_SKILL_BUNDLE_FILES)
1881            .map(|index| format!("skill-{index}.md"))
1882            .collect::<Vec<_>>();
1883        write_loader_manifest(root.path(), &paths);
1884        assert!(matches!(
1885            load_skill_bundle(root.path()),
1886            Err(graphforge_api::GfError::Validation(message))
1887                if message.contains("exceeds file bound")
1888        ));
1889
1890        let root = tempdir().unwrap();
1891        fs::create_dir(root.path().join("manifest.json")).unwrap();
1892        assert!(matches!(
1893            load_skill_bundle(root.path()),
1894            Err(graphforge_api::GfError::Validation(message))
1895                if message.contains("manifest must be a real file")
1896        ));
1897
1898        let root = tempdir().unwrap();
1899        fs::File::create(root.path().join("manifest.json"))
1900            .unwrap()
1901            .set_len(MAX_SKILL_MANIFEST_BYTES + 1)
1902            .unwrap();
1903        assert!(matches!(
1904            load_skill_bundle(root.path()),
1905            Err(graphforge_api::GfError::Validation(message))
1906                if message.contains("manifest exceeds byte bound")
1907        ));
1908    }
1909
1910    #[test]
1911    fn wave11_portable_and_preview_output_contracts_cover_plain_json_and_write_failure() {
1912        struct FailWrite;
1913        impl Write for FailWrite {
1914            fn write(&mut self, _buffer: &[u8]) -> io::Result<usize> {
1915                Err(io::Error::other("closed output"))
1916            }
1917            fn flush(&mut self) -> io::Result<()> {
1918                Ok(())
1919            }
1920        }
1921
1922        let source = Uuid::from_u128(1);
1923        let generation = Uuid::from_u128(2);
1924        let preview = RevertCheckpointPreview {
1925            checkpoint_uuid: Uuid::from_u128(3),
1926            source_generation_uuid: source,
1927            source_manifest_sha256: "11".repeat(32),
1928            current_generation_uuid: generation,
1929            warnings: Vec::new(),
1930        };
1931        for json in [false, true] {
1932            let mut output = Vec::new();
1933            write_revert_preview(&preview, json, &mut output).unwrap();
1934            assert!(!output.is_empty());
1935            assert!(matches!(
1936                write_revert_preview(&preview, json, &mut FailWrite),
1937                Err(graphforge_api::GfError::Execution(_))
1938            ));
1939        }
1940    }
1941
1942    #[test]
1943    fn wave11_reusable_execution_separates_plain_parse_and_runtime_failures() {
1944        let parse = execute(["launcher", "unknown-command"]);
1945        assert_eq!(parse.exit_code, 2);
1946        assert!(parse.stdout.is_empty());
1947        assert!(
1948            String::from_utf8(parse.stderr)
1949                .unwrap()
1950                .contains("unrecognized subcommand")
1951        );
1952
1953        let root = tempdir().unwrap();
1954        let runtime = execute([
1955            "launcher",
1956            "--project",
1957            root.path().to_str().unwrap(),
1958            "checkpoint",
1959            "create",
1960            "snapshot",
1961            "--idempotency-key",
1962            "not-a-uuid",
1963        ]);
1964        assert_ne!(runtime.exit_code, 0);
1965        assert!(runtime.stdout.is_empty());
1966        assert!(
1967            String::from_utf8(runtime.stderr)
1968                .unwrap()
1969                .starts_with("GF_")
1970        );
1971    }
1972
1973    #[test]
1974    fn telemetry_command_projects_the_rust_owned_disabled_lifecycle() {
1975        let execution = execute(["gf", "telemetry"]);
1976        assert_eq!(execution.exit_code, 0);
1977        assert!(execution.stderr.is_empty());
1978        let output: serde_json::Value = serde_json::from_slice(&execution.stdout).unwrap();
1979        assert_eq!(output["semantic_contract_version"], 1);
1980        assert_eq!(output["scope"], "io.graphforge.engine");
1981        assert_eq!(output["mode"], "disabled");
1982        assert_eq!(output["flush"], "disabled");
1983        assert_eq!(output["shutdown"], "disabled");
1984    }
1985
1986    #[test]
1987    fn reusable_execution_normalizes_identity_and_captures_structured_errors() {
1988        let version = execute(["arbitrary-launcher", "--version"]);
1989        assert_eq!(version.exit_code, 0);
1990        assert_eq!(
1991            String::from_utf8(version.stdout).expect("UTF-8 version"),
1992            format!("graphforge {}\n", env!("CARGO_PKG_VERSION"))
1993        );
1994        assert!(version.stderr.is_empty());
1995
1996        let invalid = execute(["another-launcher", "--json", "unknown-command"]);
1997        assert_eq!(invalid.exit_code, 2);
1998        assert!(invalid.stdout.is_empty());
1999        let error: serde_json::Value =
2000            serde_json::from_slice(&invalid.stderr).expect("structured CLI error");
2001        assert_eq!(error["error"]["code"], "GF_VALIDATION");
2002        assert_eq!(
2003            error["error"]["details"],
2004            serde_json::json!({
2005                "source": "argument_parser",
2006                "kind": "invalid_subcommand"
2007            })
2008        );
2009        assert!(
2010            String::from_utf8(invalid.stderr.clone())
2011                .unwrap()
2012                .starts_with("{\"error\":{\"code\":\"GF_VALIDATION\",\"message\":")
2013        );
2014        assert!(
2015            error["error"]["message"]
2016                .as_str()
2017                .expect("error message")
2018                .contains("Usage: graphforge")
2019        );
2020    }
2021
2022    #[test]
2023    fn runtime_json_errors_include_stable_safe_details_without_changing_message() {
2024        let cases = [
2025            (
2026                graphforge_api::GfError::Validation("invalid repository input".into()),
2027                "GF_VALIDATION",
2028                "validation",
2029                2,
2030            ),
2031            (
2032                graphforge_api::GfError::Storage("unavailable".into()),
2033                "GF_IO",
2034                "storage",
2035                3,
2036            ),
2037        ];
2038        for (error, code, kind, exit_code) in cases {
2039            let message = error.to_string();
2040            let mut output = Vec::new();
2041            write_error(&error, true, &mut output, &[]).unwrap();
2042            let serialized = String::from_utf8(output.clone()).unwrap();
2043            assert!(
2044                serialized.starts_with(&format!("{{\"error\":{{\"code\":\"{code}\",\"message\":"))
2045            );
2046            assert!(
2047                serialized.find("\"message\":").unwrap() < serialized.find("\"details\":").unwrap()
2048            );
2049            let value: serde_json::Value = serde_json::from_slice(&output).unwrap();
2050            assert_eq!(value["error"]["code"], code);
2051            assert_eq!(value["error"]["message"], message);
2052            assert_eq!(
2053                value["error"]["details"],
2054                serde_json::json!({"source": "runtime", "kind": kind})
2055            );
2056            assert_eq!(error_exit_code(&CliRuntimeError::Core(error)), exit_code);
2057        }
2058    }
2059
2060    #[test]
2061    fn runtime_json_preserves_stable_semantic_code() {
2062        let error = graphforge_api::GfError::Validation(
2063            "dependency.in_use: exact module has bounded dependants".into(),
2064        );
2065        let mut output = Vec::new();
2066        write_error(&error, true, &mut output, &[]).unwrap();
2067        let value: serde_json::Value = serde_json::from_slice(&output).unwrap();
2068        assert_eq!(
2069            value["error"]["details"]["semantic_code"],
2070            "dependency.in_use"
2071        );
2072        assert_eq!(
2073            value["error"]["message"],
2074            "validation error: dependency.in_use: exact module has bounded dependants"
2075        );
2076    }
2077
2078    #[test]
2079    fn revert_requires_reason_and_idempotency_key() {
2080        let missing_reason = Cli::try_parse_from([
2081            "gf",
2082            "--project",
2083            "/tmp/project",
2084            "checkpoint",
2085            "revert",
2086            "before-change",
2087            "--idempotency-key",
2088            "00000000-0000-0000-0000-000000000001",
2089        ]);
2090        assert!(missing_reason.is_err());
2091
2092        let missing_key = Cli::try_parse_from([
2093            "gf",
2094            "--project",
2095            "/tmp/project",
2096            "checkpoint",
2097            "revert",
2098            "before-change",
2099            "--reason",
2100            "undo invalid import",
2101        ]);
2102        assert!(missing_key.is_err());
2103
2104        let preview = Cli::try_parse_from([
2105            "gf",
2106            "--project",
2107            "/tmp/project",
2108            "revert",
2109            "before-change",
2110            "--preview",
2111        ])
2112        .expect("preview does not require mutation identity");
2113        assert!(matches!(
2114            preview.command,
2115            Some(Command::Revert(RevertArgs { preview: true, .. }))
2116        ));
2117    }
2118
2119    #[test]
2120    fn create_and_delete_require_idempotency_keys() {
2121        for command in ["create", "delete"] {
2122            assert!(
2123                Cli::try_parse_from([
2124                    "gf",
2125                    "--project",
2126                    "/tmp/project",
2127                    "checkpoint",
2128                    command,
2129                    "before-change",
2130                ])
2131                .is_err()
2132            );
2133        }
2134    }
2135
2136    #[test]
2137    fn diff_disambiguates_current_from_a_checkpoint_named_current() {
2138        assert!(matches!(
2139            selector(Some("current".into()), false, "from").unwrap(),
2140            CheckpointSelector::Named(name) if name == "current"
2141        ));
2142        assert!(matches!(
2143            selector(None, true, "to").unwrap(),
2144            CheckpointSelector::Current
2145        ));
2146    }
2147
2148    #[test]
2149    fn canonical_uuid_rejects_noncanonical_text() {
2150        assert!(canonical_uuid("not-an-id").is_err());
2151        assert!(canonical_uuid("00000000-0000-0000-0000-00000000000A").is_err());
2152        assert!(canonical_uuid("00000000-0000-0000-0000-000000000001").is_ok());
2153    }
2154
2155    #[test]
2156    fn open_accepts_only_a_name_and_trailing_read_command() {
2157        let cli = Cli::try_parse_from([
2158            "gf",
2159            "--project",
2160            "/tmp/project",
2161            "checkpoint",
2162            "open",
2163            "before-change",
2164            "--",
2165            "MATCH",
2166            "(n)",
2167            "RETURN",
2168            "n",
2169        ])
2170        .expect("valid checkpoint read command");
2171        let Some(Command::Checkpoint {
2172            command: CheckpointCommand::Open(args),
2173        }) = cli.command
2174        else {
2175            panic!("expected checkpoint open command");
2176        };
2177        assert_eq!(args.name, "before-change");
2178        assert_eq!(args.query.join(" "), "MATCH (n) RETURN n");
2179    }
2180
2181    #[test]
2182    fn show_accepts_exactly_one_checkpoint_name() {
2183        let cli = Cli::try_parse_from([
2184            "gf",
2185            "--project",
2186            "/tmp/project",
2187            "checkpoint",
2188            "show",
2189            "before-change",
2190        ])
2191        .expect("valid checkpoint show command");
2192        assert!(matches!(
2193            cli.command,
2194            Some(Command::Checkpoint {
2195                command: CheckpointCommand::Show(ShowArgs { name })
2196            }) if name == "before-change"
2197        ));
2198    }
2199
2200    #[test]
2201    fn repository_commands_use_project_dir_and_explicit_remove_confirmation() {
2202        assert!(Cli::try_parse_from(["gf", "--project-dir", "/tmp/repo", "init"]).is_ok());
2203        assert!(
2204            Cli::try_parse_from(["gf", "--project-dir", "/tmp/repo", "config", "resolve"]).is_ok()
2205        );
2206        assert!(
2207            Cli::try_parse_from(["gf", "--project-dir", "/tmp/repo", "sync", "--check",]).is_ok()
2208        );
2209        assert!(
2210            Cli::try_parse_from([
2211                "gf",
2212                "--project-dir",
2213                "/tmp/repo",
2214                "sync",
2215                "--check",
2216                "--idempotency-key",
2217                "41414141-4141-4141-4141-414141414141",
2218            ])
2219            .is_err()
2220        );
2221        assert!(
2222            Cli::try_parse_from([
2223                "gf",
2224                "--project-dir",
2225                "/tmp/repo",
2226                "sync",
2227                "--actor-uuid",
2228                "42424242-4242-4242-4242-424242424242",
2229            ])
2230            .is_err()
2231        );
2232        let cli = Cli::try_parse_from(["gf", "--project-dir", "/tmp/repo", "remove"]).unwrap();
2233        assert!(matches!(
2234            cli.command,
2235            Some(Command::Remove(RemoveArgs { yes: false }))
2236        ));
2237    }
2238
2239    #[test]
2240    fn export_requires_exactly_one_generation_selector() {
2241        let base = ["gf", "--project", "/tmp/project", "export"];
2242        assert!(
2243            Cli::try_parse_from(base.into_iter().chain(["--output", "/tmp/out.gfpb"])).is_err()
2244        );
2245        assert!(
2246            Cli::try_parse_from(base.into_iter().chain([
2247                "--current",
2248                "--checkpoint",
2249                "before-change",
2250                "--output",
2251                "/tmp/out.gfpb",
2252            ]))
2253            .is_err()
2254        );
2255        assert!(
2256            Cli::try_parse_from(
2257                base.into_iter()
2258                    .chain(["--current", "--output", "/tmp/out.gfpb",])
2259            )
2260            .is_ok()
2261        );
2262        assert!(
2263            Cli::try_parse_from(base.into_iter().chain([
2264                "--checkpoint",
2265                "before-change",
2266                "--output",
2267                "/tmp/out.gfpb",
2268            ]))
2269            .is_ok()
2270        );
2271    }
2272
2273    #[cfg(unix)]
2274    #[test]
2275    fn packaged_skill_loader_rejects_a_manifest_symlink() {
2276        let root = tempdir().unwrap();
2277        fs::write(root.path().join("real-manifest.json"), br#"{"files":[]}"#).unwrap();
2278        std::os::unix::fs::symlink(
2279            root.path().join("real-manifest.json"),
2280            root.path().join("manifest.json"),
2281        )
2282        .unwrap();
2283        let error = load_skill_bundle(root.path()).err().unwrap();
2284        assert!(
2285            error
2286                .to_string()
2287                .contains("packaged skill manifest must be a real file")
2288        );
2289    }
2290
2291    #[test]
2292    fn packaged_skill_loader_rejects_non_file_and_oversized_manifests() {
2293        let root = tempdir().unwrap();
2294        fs::create_dir(root.path().join("manifest.json")).unwrap();
2295        assert!(
2296            load_skill_bundle(root.path())
2297                .err()
2298                .unwrap()
2299                .to_string()
2300                .contains("packaged skill manifest must be a real file")
2301        );
2302
2303        let root = tempdir().unwrap();
2304        let manifest = fs::File::create(root.path().join("manifest.json")).unwrap();
2305        manifest.set_len(MAX_SKILL_MANIFEST_BYTES + 1).unwrap();
2306        assert!(
2307            load_skill_bundle(root.path())
2308                .err()
2309                .unwrap()
2310                .to_string()
2311                .contains("packaged skill manifest exceeds byte bound")
2312        );
2313    }
2314
2315    #[test]
2316    fn packaged_skill_loader_bounds_paths_files_and_total_payload() {
2317        let root = tempdir().unwrap();
2318        write_loader_manifest(root.path(), &["x".repeat(MAX_SKILL_PATH_BYTES + 1)]);
2319        assert!(
2320            load_skill_bundle(root.path())
2321                .err()
2322                .unwrap()
2323                .to_string()
2324                .contains("project skill file path exceeds byte bound")
2325        );
2326
2327        let root = tempdir().unwrap();
2328        let path = "graphforge-bootstrap/large.md".to_owned();
2329        fs::create_dir(root.path().join("graphforge-bootstrap")).unwrap();
2330        fs::File::create(root.path().join(&path))
2331            .unwrap()
2332            .set_len(MAX_SKILL_FILE_BYTES + 1)
2333            .unwrap();
2334        write_loader_manifest(root.path(), std::slice::from_ref(&path));
2335        assert!(
2336            load_skill_bundle(root.path())
2337                .err()
2338                .unwrap()
2339                .to_string()
2340                .contains("packaged project skill exceeds per-file byte bound")
2341        );
2342
2343        let root = tempdir().unwrap();
2344        fs::create_dir(root.path().join("graphforge-bootstrap")).unwrap();
2345        let paths = (0..3)
2346            .map(|index| format!("graphforge-bootstrap/{index}.md"))
2347            .collect::<Vec<_>>();
2348        for path in &paths {
2349            fs::File::create(root.path().join(path))
2350                .unwrap()
2351                .set_len(3 * 1024 * 1024)
2352                .unwrap();
2353        }
2354        write_loader_manifest(root.path(), &paths);
2355        assert!(
2356            load_skill_bundle(root.path())
2357                .err()
2358                .unwrap()
2359                .to_string()
2360                .contains("packaged project skill bundle exceeds total byte bound")
2361        );
2362    }
2363
2364    #[test]
2365    fn packaged_skill_loader_accepts_exact_manifest_and_rejects_malformed_shapes() {
2366        let root = tempdir().unwrap();
2367        fs::create_dir(root.path().join("graphforge-bootstrap")).unwrap();
2368        fs::write(root.path().join("graphforge-bootstrap/SKILL.md"), b"skill").unwrap();
2369        write_loader_manifest(root.path(), &["graphforge-bootstrap/SKILL.md".into()]);
2370        let loaded = load_skill_bundle(root.path()).unwrap();
2371        assert_eq!(loaded.files.len(), 1);
2372        assert_eq!(loaded.files[0].path, "graphforge-bootstrap/SKILL.md");
2373        assert_eq!(loaded.files[0].bytes, b"skill");
2374
2375        let root = tempdir().unwrap();
2376        fs::write(root.path().join("manifest.json"), b"not json").unwrap();
2377        assert!(matches!(
2378            load_skill_bundle(root.path()),
2379            Err(graphforge_api::GfError::Validation(_))
2380        ));
2381
2382        let root = tempdir().unwrap();
2383        fs::write(root.path().join("manifest.json"), br"{}").unwrap();
2384        assert!(matches!(
2385            load_skill_bundle(root.path()),
2386            Err(graphforge_api::GfError::Validation(_))
2387        ));
2388
2389        let root = tempdir().unwrap();
2390        fs::write(root.path().join("manifest.json"), br#"{"files":[{}]}"#).unwrap();
2391        assert!(matches!(
2392            load_skill_bundle(root.path()),
2393            Err(graphforge_api::GfError::Validation(_))
2394        ));
2395
2396        let root = tempdir().unwrap();
2397        fs::write(
2398            root.path().join("manifest.json"),
2399            br#"{"files":[{"path":"../escape"}]}"#,
2400        )
2401        .unwrap();
2402        assert!(matches!(
2403            load_skill_bundle(root.path()),
2404            Err(graphforge_api::GfError::Validation(_))
2405        ));
2406
2407        let file = tempfile::NamedTempFile::new().unwrap();
2408        assert!(matches!(
2409            load_skill_bundle(file.path()),
2410            Err(graphforge_api::GfError::Validation(_))
2411        ));
2412        assert!(matches!(
2413            read_bounded_file(root.path(), 10, "not a file"),
2414            Err(graphforge_api::GfError::Validation(_))
2415        ));
2416    }
2417
2418    #[test]
2419    fn reusable_execution_covers_default_info_and_runtime_error_vocabulary() {
2420        let default = execute(std::iter::empty::<&str>());
2421        assert_eq!(default.exit_code, 0);
2422        assert_eq!(
2423            default.stdout,
2424            "GraphForge — use --help for options\n".as_bytes()
2425        );
2426
2427        let info = execute(["graphforge", "--info"]);
2428        assert_eq!(info.exit_code, 0);
2429        assert!(
2430            String::from_utf8(info.stdout)
2431                .unwrap()
2432                .starts_with("graphforge ")
2433        );
2434
2435        let cases = [
2436            (
2437                graphforge_api::GfError::NotImplemented("test"),
2438                "not_implemented",
2439            ),
2440            (graphforge_api::GfError::Plan("test".into()), "plan"),
2441            (
2442                graphforge_api::GfError::Execution("test".into()),
2443                "execution",
2444            ),
2445            (
2446                graphforge_api::GfError::Provider {
2447                    class: "transport".into(),
2448                    provider: "provider".into(),
2449                    model: "model".into(),
2450                },
2451                "provider",
2452            ),
2453            (
2454                graphforge_api::GfError::Lifecycle("test".into()),
2455                "lifecycle",
2456            ),
2457            (graphforge_api::GfError::Ontology("test".into()), "ontology"),
2458        ];
2459        for (error, expected) in cases {
2460            assert_eq!(runtime_error_kind(&error), expected);
2461            let mut output = Vec::new();
2462            write_error(&error, false, &mut output, &[]).unwrap();
2463            assert!(!output.is_empty());
2464            assert_eq!(error_exit_code(&CliRuntimeError::Core(error)), 1);
2465        }
2466    }
2467
2468    #[test]
2469    fn no_skills_init_does_not_load_the_distribution_bundle() {
2470        let project = tempdir().unwrap();
2471        let missing_bundle = project.path().join("missing-bundle");
2472        let result = execute([
2473            "graphforge".to_owned(),
2474            "--project-dir".to_owned(),
2475            project.path().to_string_lossy().into_owned(),
2476            "--skills-bundle-dir".to_owned(),
2477            missing_bundle.to_string_lossy().into_owned(),
2478            "init".to_owned(),
2479            "--no-skills".to_owned(),
2480        ]);
2481        assert_eq!(
2482            result.exit_code,
2483            0,
2484            "{}",
2485            String::from_utf8_lossy(&result.stderr)
2486        );
2487        assert!(!project.path().join(".agents").exists());
2488        let validate = execute([
2489            "graphforge".to_owned(),
2490            "--project-dir".to_owned(),
2491            project.path().to_string_lossy().into_owned(),
2492            "--skills-bundle-dir".to_owned(),
2493            missing_bundle.to_string_lossy().into_owned(),
2494            "config".to_owned(),
2495            "validate".to_owned(),
2496        ]);
2497        assert_eq!(
2498            validate.exit_code,
2499            0,
2500            "{}",
2501            String::from_utf8_lossy(&validate.stderr)
2502        );
2503
2504        let remove = execute([
2505            "graphforge".to_owned(),
2506            "--project-dir".to_owned(),
2507            project.path().to_string_lossy().into_owned(),
2508            "--skills-bundle-dir".to_owned(),
2509            missing_bundle.to_string_lossy().into_owned(),
2510            "skills".to_owned(),
2511            "remove".to_owned(),
2512        ]);
2513        assert_eq!(
2514            remove.exit_code,
2515            0,
2516            "{}",
2517            String::from_utf8_lossy(&remove.stderr)
2518        );
2519    }
2520
2521    #[test]
2522    fn repository_commands_execute_through_json_and_plain_dispatch() {
2523        let project = tempdir().unwrap();
2524        let root = project.path().to_string_lossy().into_owned();
2525        let init = execute([
2526            "graphforge".to_owned(),
2527            "--json".to_owned(),
2528            "--project-dir".to_owned(),
2529            root.clone(),
2530            "init".to_owned(),
2531            "--no-skills".to_owned(),
2532        ]);
2533        assert_eq!(
2534            init.exit_code,
2535            0,
2536            "{}",
2537            String::from_utf8_lossy(&init.stderr)
2538        );
2539        let init_json: serde_json::Value = serde_json::from_slice(&init.stdout).unwrap();
2540        assert_eq!(init_json["root"], ".");
2541
2542        for tail in [
2543            vec!["config", "resolve"],
2544            vec!["config", "validate"],
2545            vec!["sync", "--check"],
2546        ] {
2547            let mut args = vec![
2548                "graphforge".to_owned(),
2549                "--json".to_owned(),
2550                "--project-dir".to_owned(),
2551                root.clone(),
2552            ];
2553            args.extend(tail.into_iter().map(str::to_owned));
2554            let result = execute(args);
2555            assert!(
2556                result.exit_code == 0 || result.exit_code == OUT_OF_SYNC_EXIT_CODE,
2557                "{}",
2558                String::from_utf8_lossy(&result.stderr)
2559            );
2560            assert!(serde_json::from_slice::<serde_json::Value>(&result.stdout).is_ok());
2561        }
2562
2563        let remove = execute([
2564            "graphforge".to_owned(),
2565            "--project-dir".to_owned(),
2566            root,
2567            "remove".to_owned(),
2568            "--yes".to_owned(),
2569        ]);
2570        assert_eq!(
2571            remove.exit_code,
2572            0,
2573            "{}",
2574            String::from_utf8_lossy(&remove.stderr)
2575        );
2576        assert_eq!(remove.stdout, b"ok\n");
2577    }
2578
2579    #[test]
2580    #[allow(clippy::too_many_lines)]
2581    fn checkpoint_commands_execute_end_to_end_through_the_reusable_cli() {
2582        let project = tempdir().unwrap();
2583        let path = project.path().join("state");
2584        fs::create_dir(&path).unwrap();
2585        let path = path.to_string_lossy().into_owned();
2586        let invoke = |tail: &[&str]| {
2587            let mut args = vec![
2588                "graphforge".to_owned(),
2589                "--json".to_owned(),
2590                "--project".to_owned(),
2591                path.clone(),
2592            ];
2593            args.extend(tail.iter().map(|value| (*value).to_owned()));
2594            execute(args)
2595        };
2596        let create_id = Uuid::now_v7().to_string();
2597        let create = invoke(&[
2598            "checkpoint",
2599            "create",
2600            "baseline",
2601            "--description",
2602            "before change",
2603            "--idempotency-key",
2604            &create_id,
2605        ]);
2606        assert_eq!(
2607            create.exit_code,
2608            0,
2609            "{}",
2610            String::from_utf8_lossy(&create.stderr)
2611        );
2612
2613        for command in [
2614            vec!["checkpoint", "list", "--limit", "10"],
2615            vec!["checkpoint", "show", "baseline"],
2616            vec![
2617                "checkpoint",
2618                "open",
2619                "baseline",
2620                "--",
2621                "RETURN",
2622                "1",
2623                "AS",
2624                "value",
2625            ],
2626            vec![
2627                "checkpoint",
2628                "diff",
2629                "--from",
2630                "baseline",
2631                "--to-current",
2632                "--scope",
2633                "summary",
2634                "--detail",
2635                "summary",
2636            ],
2637            vec!["checkpoint", "revert", "baseline", "--preview"],
2638        ] {
2639            let result = invoke(&command);
2640            assert_eq!(
2641                result.exit_code,
2642                0,
2643                "command={command:?}: {}",
2644                String::from_utf8_lossy(&result.stderr)
2645            );
2646            assert!(!result.stdout.is_empty());
2647        }
2648
2649        for scope in [
2650            "graph",
2651            "ontology",
2652            "configuration",
2653            "capabilities",
2654            "provenance",
2655            "knowledge",
2656            "epistemic",
2657            "all",
2658        ] {
2659            let result = invoke(&[
2660                "checkpoint",
2661                "diff",
2662                "--from",
2663                "baseline",
2664                "--to-current",
2665                "--scope",
2666                scope,
2667                "--detail",
2668                "records",
2669            ]);
2670            assert_eq!(
2671                result.exit_code,
2672                0,
2673                "scope={scope}: {}",
2674                String::from_utf8_lossy(&result.stderr)
2675            );
2676        }
2677
2678        let revert_id = Uuid::now_v7().to_string();
2679        let revert = invoke(&[
2680            "checkpoint",
2681            "revert",
2682            "baseline",
2683            "--reason",
2684            "coverage contract",
2685            "--idempotency-key",
2686            &revert_id,
2687            "--yes",
2688        ]);
2689        assert_eq!(
2690            revert.exit_code,
2691            0,
2692            "{}",
2693            String::from_utf8_lossy(&revert.stderr)
2694        );
2695
2696        let envelope = project.path().join("baseline.gfpb");
2697        let envelope_text = envelope.to_string_lossy().into_owned();
2698        let export = invoke(&[
2699            "export",
2700            "--checkpoint",
2701            "baseline",
2702            "--output",
2703            &envelope_text,
2704        ]);
2705        assert_eq!(
2706            export.exit_code,
2707            0,
2708            "{}",
2709            String::from_utf8_lossy(&export.stderr)
2710        );
2711        assert!(envelope.is_file());
2712
2713        let imported_path = project.path().join("imported");
2714        fs::create_dir(&imported_path).unwrap();
2715        let imported = imported_path.to_string_lossy().into_owned();
2716        let import_id = Uuid::now_v7().to_string();
2717        let import = execute([
2718            "graphforge".to_owned(),
2719            "--json".to_owned(),
2720            "--project".to_owned(),
2721            imported,
2722            "import".to_owned(),
2723            "--input".to_owned(),
2724            envelope_text,
2725            "--idempotency-key".to_owned(),
2726            import_id,
2727        ]);
2728        assert_eq!(
2729            import.exit_code,
2730            0,
2731            "{}",
2732            String::from_utf8_lossy(&import.stderr)
2733        );
2734
2735        let delete_id = Uuid::now_v7().to_string();
2736        let delete = invoke(&[
2737            "checkpoint",
2738            "delete",
2739            "baseline",
2740            "--idempotency-key",
2741            &delete_id,
2742        ]);
2743        assert_eq!(
2744            delete.exit_code,
2745            0,
2746            "{}",
2747            String::from_utf8_lossy(&delete.stderr)
2748        );
2749    }
2750
2751    #[test]
2752    fn storage_attribution_json_is_closed_sanitized_and_reopen_stable() {
2753        let project = tempdir().unwrap();
2754        let path = project.path().join("state");
2755        fs::create_dir(&path).unwrap();
2756        let result = execute([
2757            "graphforge".to_owned(),
2758            "--json".to_owned(),
2759            "--project".to_owned(),
2760            path.to_string_lossy().into_owned(),
2761            "storage-attribution".to_owned(),
2762        ]);
2763        assert_eq!(
2764            result.exit_code,
2765            0,
2766            "{}",
2767            String::from_utf8_lossy(&result.stderr)
2768        );
2769        let json: serde_json::Value = serde_json::from_slice(&result.stdout).unwrap();
2770        assert_eq!(json["contract"], "graphforge-storage-attribution-command/1");
2771        assert_eq!(
2772            json["storage"]["contract"],
2773            "graphforge-storage-attribution/1"
2774        );
2775        assert_eq!(json["reopen_agrees"], true);
2776        assert_eq!(
2777            json["storage"]["categories"].as_object().unwrap().len(),
2778            graphforge_api::ArtifactCategory::ALL.len()
2779        );
2780        // #1389: the reopen phase now carries its own closed per-phase I/O
2781        // attribution, in the shape construction already emits.
2782        let application_io = json["application_io"].as_object().unwrap();
2783        assert_eq!(application_io.len(), 2);
2784        let phases = application_io["phases"].as_object().unwrap();
2785        assert_eq!(
2786            phases.len(),
2787            graphforge_api::StorageIoPhase::LIFECYCLE.len()
2788        );
2789        assert!(phases.contains_key("read_path_scan"));
2790        assert!(phases.contains_key("hydration_verification"));
2791        for field in [
2792            "read_bytes",
2793            "write_bytes",
2794            "read_calls",
2795            "write_calls",
2796            "object_count",
2797            "block_count",
2798            "fsync_calls",
2799        ] {
2800            let expected: u64 = phases
2801                .values()
2802                .map(|row| row[field].as_u64().unwrap())
2803                .sum();
2804            assert_eq!(
2805                application_io["totals"][field].as_u64().unwrap(),
2806                expected,
2807                "{field} does not reconcile"
2808            );
2809        }
2810        fn assert_sanitized(value: &serde_json::Value) {
2811            match value {
2812                serde_json::Value::Object(object) => {
2813                    for (key, value) in object {
2814                        assert!(
2815                            !matches!(
2816                                key.as_str(),
2817                                "uuid"
2818                                    | "path"
2819                                    | "generation_uuid"
2820                                    | "generation_manifest_sha256"
2821                                    | "physical_identity_allocated_bytes"
2822                                    | "provider_id"
2823                                    | "resource_id"
2824                                    | "credential"
2825                                    | "credentials"
2826                                    | "secret"
2827                            ),
2828                            "sensitive evidence key: {key}"
2829                        );
2830                        assert_sanitized(value);
2831                    }
2832                }
2833                serde_json::Value::Array(values) => {
2834                    values.iter().for_each(assert_sanitized);
2835                }
2836                serde_json::Value::String(value) => {
2837                    assert!(Uuid::parse_str(value).is_err());
2838                    assert!(!Path::new(value).is_absolute());
2839                }
2840                _ => {}
2841            }
2842        }
2843        assert_sanitized(&json);
2844        let encoded = String::from_utf8(result.stdout).unwrap();
2845        assert!(!encoded.contains("generation_uuid"));
2846        assert!(!encoded.contains("sha256"));
2847        assert!(!encoded.contains(path.to_string_lossy().as_ref()));
2848    }
2849
2850    #[test]
2851    fn clap_error_vocabulary_is_total_and_stable() {
2852        let cases = [
2853            (ErrorKind::InvalidValue, "invalid_value"),
2854            (ErrorKind::UnknownArgument, "unknown_argument"),
2855            (ErrorKind::InvalidSubcommand, "invalid_subcommand"),
2856            (ErrorKind::NoEquals, "missing_equals"),
2857            (ErrorKind::ValueValidation, "value_validation"),
2858            (ErrorKind::TooManyValues, "too_many_values"),
2859            (ErrorKind::TooFewValues, "too_few_values"),
2860            (ErrorKind::WrongNumberOfValues, "wrong_number_of_values"),
2861            (ErrorKind::ArgumentConflict, "argument_conflict"),
2862            (
2863                ErrorKind::MissingRequiredArgument,
2864                "missing_required_argument",
2865            ),
2866            (ErrorKind::MissingSubcommand, "missing_subcommand"),
2867            (ErrorKind::DisplayHelp, "display_help"),
2868            (
2869                ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand,
2870                "display_help_on_missing_input",
2871            ),
2872            (ErrorKind::DisplayVersion, "display_version"),
2873            (ErrorKind::Io, "io"),
2874            (ErrorKind::Format, "format"),
2875        ];
2876        for (kind, token) in cases {
2877            assert_eq!(clap_error_kind(kind), token);
2878        }
2879    }
2880
2881    #[test]
2882    fn selector_requires_exactly_one_source_and_preserves_named_current() {
2883        assert!(selector(None, false, "from").is_err());
2884        assert!(selector(Some("named".into()), true, "from").is_err());
2885        assert!(matches!(
2886            selector(Some("current".into()), false, "from").unwrap(),
2887            CheckpointSelector::Named(value) if value == "current"
2888        ));
2889        assert!(matches!(
2890            selector(None, true, "from").unwrap(),
2891            CheckpointSelector::Current
2892        ));
2893    }
2894}
2895
2896#[cfg(test)]
2897mod command_retirement_tests;
2898
2899#[cfg(test)]
2900mod result_output_tests;