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