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