Skip to main content

type_bridge_cli/
lib.rs

1//! `type-bridge` — the V2 workspace command-line interface.
2//!
3//! `schema check`, `schema generate`, `migration make`, and `migration
4//! plan`, and rollback preview run without any network I/O. `migration apply`,
5//! `migration rollback --execute`, `migration verify`, `migration adopt`, and
6//! `migration upgrade-profile` connect through one named workspace
7//! environment: credentials stay symbolic environment references resolved
8//! only at command time, and application requires the environment's
9//! explicit `migrate: true` opt-in.
10//!
11//! The crate is a library plus a thin binary so the exact same command
12//! surface ships both as the standalone `type-bridge` executable and
13//! in-process inside the Python wheel via [`run_cli`].
14
15#![deny(missing_docs)]
16
17use std::collections::BTreeSet;
18use std::ffi::OsString;
19use std::fs;
20use std::path::{Component, Path, PathBuf};
21
22use clap::{Parser, Subcommand, ValueEnum};
23use type_bridge_contract::diagnostic::{Diagnostic, DiagnosticDetailValue};
24#[cfg(test)]
25use type_bridge_schema::SystemSchemaSourceService;
26use type_bridge_schema_migration::MigrationGenerationOutcome;
27use type_bridge_schema_migration_typedb::execution_capability_vocabulary;
28use type_bridge_workspace::{
29    ConfigOrigin, ExtensionRegistryService, ExtensionRequirement, SecretReference,
30    SecretReferenceService, TypeBridgeConfigSpec, TypeBridgeWorkspace, TypeBridgeWorkspaceError,
31    TypeBridgeWorkspaceServices, WorkspaceDirectoryAuthority, WorkspaceEnvironment, WorkspaceRoot,
32    WorkspaceServiceError, WorkspaceTransportPolicy, c_symbol_prefix_for_app_label,
33};
34
35mod build_identity {
36    include!(concat!(env!("OUT_DIR"), "/cli_build_identity.rs"));
37}
38
39#[derive(Parser)]
40#[command(
41    name = "type-bridge",
42    version = build_identity::CLI_VERSION,
43    about = "TypeBridge V2 workspace commands"
44)]
45struct Cli {
46    /// Path to the workspace manifest.
47    #[arg(long, global = true, default_value = "typebridge.yaml")]
48    manifest: PathBuf,
49    #[command(subcommand)]
50    command: Command,
51}
52
53#[derive(Subcommand)]
54enum Command {
55    /// Schema-source commands.
56    Schema {
57        #[command(subcommand)]
58        command: SchemaCommand,
59    },
60    /// Canonical migration commands.
61    Migration {
62        #[command(subcommand)]
63        command: MigrationCommand,
64    },
65}
66
67#[derive(Subcommand)]
68enum SchemaCommand {
69    /// Parse and resolve the schema sources without network I/O.
70    Check,
71    /// Generate the configured binding projections from the canonical schema.
72    Generate,
73    /// Export canonical declared-schema bytes for low-level V2 tooling.
74    ExportDeclared {
75        /// Workspace-relative destination for the canonical JSON artifact.
76        #[arg(long, default_value = "declared-schema.json")]
77        output: PathBuf,
78    },
79}
80
81#[derive(Subcommand)]
82enum MigrationCommand {
83    /// Author the next canonical migration toward the schema sources.
84    Make {
85        /// Descriptive migration name; the ordinal prefix is allocated.
86        #[arg(long)]
87        name: String,
88        /// Closed backfill-intent YAML inside the configured migration directory.
89        #[arg(long)]
90        backfill_intent: Option<PathBuf>,
91    },
92    /// Order the committed chain and report each manifest's safety class.
93    Plan,
94    /// Apply the committed chain to one named environment.
95    Apply {
96        /// The manifest environment to apply against.
97        #[arg(long)]
98        environment: String,
99        /// Approve one destructive migration by compound id (app/name).
100        #[arg(long = "approve")]
101        approvals: Vec<String>,
102    },
103    /// Verify the migration state triad against one named environment.
104    Verify {
105        /// The manifest environment to verify against.
106        #[arg(long)]
107        environment: String,
108    },
109    /// Preview or explicitly execute rollback of named applied migrations.
110    Rollback {
111        /// The manifest environment whose exact database pair is targeted.
112        #[arg(long)]
113        environment: String,
114        /// Remove one exact compound migration identity (app/name); repeat as needed.
115        #[arg(long = "remove", required = true)]
116        removals: Vec<String>,
117        /// Approve one destructive rollback by compound id (app/name).
118        #[arg(long = "approve")]
119        approvals: Vec<String>,
120        /// Execute the previewed rollback; omission is provider-free preview only.
121        #[arg(long)]
122        execute: bool,
123        /// Select stable human or machine-readable output.
124        #[arg(long, value_enum, default_value_t = RollbackOutput::Text)]
125        output: RollbackOutput,
126    },
127    /// Adopt a completed archived V1 history as the canonical genesis.
128    Adopt {
129        /// The manifest environment holding the migrated v1 database.
130        #[arg(long)]
131        environment: String,
132        /// Directory containing the completed archived migration files.
133        #[arg(long)]
134        archive_directory: PathBuf,
135        /// Migration name recorded for the zero-operation bridge manifest.
136        #[arg(long, default_value = "0000_archive_frontier")]
137        name: String,
138    },
139    /// Move the history to the workspace's newer TypeDB line at a profile bridge.
140    UpgradeProfile {
141        /// The manifest environment whose moved database pair records the bridge.
142        #[arg(long)]
143        environment: String,
144        /// The semantic profile to move to; must equal the workspace profile.
145        #[arg(long)]
146        to: String,
147        /// Descriptive bridge name; the ordinal prefix is allocated
148        /// [default: profile_upgrade_typedb_<version>].
149        #[arg(long)]
150        name: Option<String>,
151    },
152}
153
154#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
155enum RollbackOutput {
156    Text,
157    Json,
158}
159
160/// Symbolic secret references stay unresolved during offline commands.
161struct DeferSecrets;
162
163impl SecretReferenceService for DeferSecrets {
164    fn validate_reference(
165        &self,
166        _reference: &SecretReference,
167    ) -> Result<(), WorkspaceServiceError> {
168        Ok(())
169    }
170}
171
172/// No extension handlers ship with the CLI yet; requirements fail closed.
173struct NoExtensions;
174
175impl ExtensionRegistryService for NoExtensions {
176    fn validate_requirement(
177        &self,
178        _requirement: &ExtensionRequirement,
179    ) -> Result<(), WorkspaceServiceError> {
180        Err(WorkspaceServiceError::new(
181            "extension_handlers_unavailable_in_cli",
182        ))
183    }
184}
185
186/// Run the CLI over process-style arguments (`argv[0]` included).
187///
188/// Returns the process exit code. All output goes to the process stdout
189/// and stderr exactly as the standalone binary would print it: `--help`
190/// and `--version` exit 0, argument errors exit 2, command failures
191/// print `error: ...` and exit 1.
192pub fn run_cli<I, T>(arguments: I) -> i32
193where
194    I: IntoIterator<Item = T>,
195    T: Into<OsString> + Clone,
196{
197    let cli = match Cli::try_parse_from(arguments) {
198        Ok(cli) => cli,
199        Err(error) => {
200            let _ = error.print();
201            return if error.use_stderr() { 2 } else { 0 };
202        }
203    };
204    match run(&cli) {
205        Ok(()) => 0,
206        Err(message) => {
207            eprintln!("error: {message}");
208            1
209        }
210    }
211}
212
213fn run(cli: &Cli) -> Result<(), String> {
214    let workspace = load_workspace(&cli.manifest)?;
215    match &cli.command {
216        Command::Schema {
217            command: SchemaCommand::Check,
218        } => {
219            println!(
220                "schema sources are valid\n  declared identity: {}\n  managed semantics: {}",
221                workspace
222                    .declared_schema()
223                    .declared_identity_fingerprint()
224                    .as_fingerprint()
225                    .digest()
226                    .to_hex(),
227                workspace
228                    .managed_state()
229                    .managed_semantic_schema()
230                    .as_fingerprint()
231                    .digest()
232                    .to_hex(),
233            );
234            Ok(())
235        }
236        Command::Schema {
237            command: SchemaCommand::Generate,
238        } => run_schema_generate(&workspace),
239        Command::Schema {
240            command: SchemaCommand::ExportDeclared { output },
241        } => run_schema_export_declared(&workspace, output),
242        Command::Migration { command } => match command {
243            MigrationCommand::Make {
244                name,
245                backfill_intent,
246            } => {
247                let directory = workspace.ensure_migration_directory().map_err(display)?;
248                if let Some(intent) = backfill_intent {
249                    let generated = workspace
250                        .author_backfill_migration_in(&directory, name, intent)
251                        .map_err(display_workspace)?;
252                    let path = directory.display_path().join(generated.file_name());
253                    println!(
254                        "wrote {}\n  safety: {:?}\n  preview: {}",
255                        path.display(),
256                        generated.manifest().safety(),
257                        path.with_file_name(generated.preview_file_name()).display(),
258                    );
259                    return Ok(());
260                }
261                match workspace
262                    .migration_make_in(&directory, name)
263                    .map_err(display_workspace)?
264                {
265                    MigrationGenerationOutcome::UpToDate => {
266                        println!("history already reaches the desired schema");
267                    }
268                    MigrationGenerationOutcome::Generated(generated) => {
269                        workspace
270                            .write_generated_migration_in(&directory, &generated)
271                            .map_err(display_workspace)?;
272                        let path = directory.display_path().join(generated.file_name());
273                        println!(
274                            "wrote {}\n  safety: {:?}\n  preview: {}",
275                            path.display(),
276                            generated.manifest().safety(),
277                            path.with_file_name(generated.preview_file_name()).display(),
278                        );
279                    }
280                }
281                Ok(())
282            }
283            MigrationCommand::Apply {
284                environment,
285                approvals,
286            } => run_connected(
287                &workspace,
288                environment,
289                ConnectedAction::Apply {
290                    approvals: approvals.clone(),
291                },
292            ),
293            MigrationCommand::Verify { environment } => {
294                run_connected(&workspace, environment, ConnectedAction::Verify)
295            }
296            MigrationCommand::Rollback {
297                environment,
298                removals,
299                approvals,
300                execute,
301                output,
302            } => run_migration_rollback(
303                &workspace,
304                environment,
305                removals,
306                approvals,
307                *execute,
308                *output,
309            ),
310            MigrationCommand::Adopt {
311                environment,
312                archive_directory,
313                name,
314            } => run_connected(
315                &workspace,
316                environment,
317                ConnectedAction::Adopt {
318                    archive_directory: archive_directory.clone(),
319                    name: name.clone(),
320                },
321            ),
322            MigrationCommand::UpgradeProfile {
323                environment,
324                to,
325                name,
326            } => run_connected(
327                &workspace,
328                environment,
329                ConnectedAction::UpgradeProfile {
330                    to: to.clone(),
331                    name: name.clone(),
332                },
333            ),
334            MigrationCommand::Plan => {
335                let directory = workspace.open_migration_directory().map_err(display)?;
336                let plan = workspace
337                    .migration_plan_in(&directory, &BTreeSet::new())
338                    .map_err(display_workspace)?;
339                if plan.is_empty() {
340                    println!("no committed migrations");
341                    return Ok(());
342                }
343                for entry in plan {
344                    println!(
345                        "{}/{}  safety={:?}  reversible={}",
346                        entry.id().app_label().as_str(),
347                        entry.id().name().as_str(),
348                        entry.safety(),
349                        entry.reversible(),
350                    );
351                }
352                Ok(())
353            }
354        },
355    }
356}
357
358fn run_migration_rollback(
359    workspace: &TypeBridgeWorkspace,
360    environment: &str,
361    removals: &[String],
362    approvals: &[String],
363    execute: bool,
364    output: RollbackOutput,
365) -> Result<(), String> {
366    if workspace.config().environment(environment).is_none() {
367        return Err(format!(
368            "unknown environment {environment:?}; rollback requires an exact workspace environment binding"
369        ));
370    }
371    let directory = workspace.open_migration_directory().map_err(display)?;
372    let graph = workspace
373        .discover_migrations_in(&directory)
374        .map_err(display_workspace)?;
375    let removals = parse_migration_ids(&graph, removals, "rollback removal")?;
376    let _ = bind_rollback_approvals(&graph, approvals)?;
377    let applied = graph
378        .manifests()
379        .map(|(id, _)| id.clone())
380        .collect::<BTreeSet<_>>();
381    let lowering =
382        type_bridge_schema_migration::SchemaLoweringBinding::for_context(workspace.delta_context())
383            .map_err(display)?;
384    let plan = type_bridge_schema_migration::build_verified_migration_rollback_preview(
385        &graph,
386        &applied,
387        &removals,
388        workspace.delta_context(),
389        &lowering,
390    )
391    .map_err(display)?;
392    render_rollback_preview(environment, &plan, execute, output)?;
393    if !execute {
394        return Ok(());
395    }
396    run_connected(
397        workspace,
398        environment,
399        ConnectedAction::Rollback {
400            removals,
401            approvals: approvals.to_vec(),
402        },
403    )
404}
405
406fn render_rollback_preview(
407    environment: &str,
408    plan: &type_bridge_schema_migration::VerifiedMigrationRollbackPlan,
409    execute: bool,
410    output: RollbackOutput,
411) -> Result<(), String> {
412    let order = plan
413        .rollbacks()
414        .iter()
415        .map(|rollback| {
416            format!(
417                "{}/{}",
418                rollback.manifest().id().app_label().as_str(),
419                rollback.manifest().id().name().as_str()
420            )
421        })
422        .collect::<Vec<_>>();
423    let target = plan
424        .remaining_applied()
425        .iter()
426        .map(|id| format!("{}/{}", id.app_label().as_str(), id.name().as_str()))
427        .collect::<Vec<_>>();
428    let safety = plan
429        .rollbacks()
430        .iter()
431        .map(|rollback| rollback_safety_wire(rollback.rollback_safety()).to_owned())
432        .collect::<Vec<_>>();
433    let plan_identity = plan
434        .rollbacks()
435        .iter()
436        .map(|rollback| rollback.digest().to_hex())
437        .collect::<Vec<_>>()
438        .join(":");
439    let reverse_backfills = plan
440        .rollbacks()
441        .iter()
442        .map(|rollback| rollback.backfills().len())
443        .sum::<usize>();
444    match output {
445        RollbackOutput::Text => println!(
446            "rollback preview\n  environment: {environment}\n  basis: committed-history\n  plan identity: {plan_identity}\n  order: {}\n  target applied: {}\n  safety: {}\n  reverse backfills: {reverse_backfills}\n  execution requested: {execute}",
447            order.join(", "),
448            target.join(", "),
449            safety.join(", "),
450        ),
451        RollbackOutput::Json => {
452            let strings = |values: &[String]| {
453                values
454                    .iter()
455                    .map(|value| format!("\"{value}\""))
456                    .collect::<Vec<_>>()
457                    .join(",")
458            };
459            println!(
460                "{{\"basis\":\"committed-history\",\"environment\":\"{environment}\",\"execute\":{execute},\"format\":\"typebridge.migration-rollback-preview/v1\",\"order\":[{}],\"plan_identity\":\"{plan_identity}\",\"reverse_backfills\":{reverse_backfills},\"safety\":[{}],\"target_applied\":[{}]}}",
461                strings(&order),
462                strings(&safety),
463                strings(&target),
464            );
465        }
466    }
467    Ok(())
468}
469
470fn rollback_safety_wire(safety: type_bridge_schema::SafetyClass) -> &'static str {
471    match safety {
472        type_bridge_schema::SafetyClass::FormalOnly => "formal_only",
473        type_bridge_schema::SafetyClass::SchemaMetadata => "schema_metadata",
474        type_bridge_schema::SafetyClass::Additive => "additive",
475        type_bridge_schema::SafetyClass::Conditional => "conditional",
476        type_bridge_schema::SafetyClass::BackfillRequired => "backfill_required",
477        type_bridge_schema::SafetyClass::Destructive => "destructive",
478        type_bridge_schema::SafetyClass::Opaque => "opaque",
479        type_bridge_schema::SafetyClass::Unsupported => "unsupported",
480    }
481}
482
483fn load_workspace(manifest: &PathBuf) -> Result<TypeBridgeWorkspace, String> {
484    let manifest = fs::canonicalize(manifest)
485        .map_err(|error| format!("cannot resolve {}: {error}", manifest.display()))?;
486    let root = manifest
487        .parent()
488        .ok_or_else(|| "workspace manifest has no parent directory".to_owned())?;
489    let file_name = manifest
490        .file_name()
491        .and_then(|name| name.to_str())
492        .ok_or_else(|| "workspace manifest has no UTF-8 file name".to_owned())?;
493    let root = WorkspaceRoot::new(root).map_err(display)?;
494    let source = WorkspaceDirectoryAuthority::open(root.clone()).map_err(display)?;
495    let origin = ConfigOrigin::new(root, file_name, "type-bridge cli").map_err(display)?;
496    // Read at most the canonical document ceiling plus one byte: an
497    // oversized manifest fails with a stable message before its full
498    // content is ever allocated.
499    let limit = type_bridge_contract::limits::MAX_CANONICAL_BYTES;
500    let captured = source
501        .capture_relative_file(Path::new(file_name), limit)
502        .map_err(|error| format!("cannot read {}: {error}", manifest.display()))?;
503    let bytes = captured.bytes();
504    if bytes.len() > limit {
505        return Err(format!(
506            "{} exceeds the 16 MiB manifest ceiling",
507            manifest.display()
508        ));
509    }
510    let located = TypeBridgeConfigSpec::from_yaml_bytes(bytes, origin).map_err(display)?;
511
512    let available = execution_capability_vocabulary().map_err(display)?;
513    let secrets = DeferSecrets;
514    let extensions = NoExtensions;
515    let services = TypeBridgeWorkspaceServices::new(&source, &secrets, &extensions, &available);
516    // Services borrow locally, so the workspace is constructed in this scope.
517    TypeBridgeWorkspace::from_located_config(located, &services).map_err(display)
518}
519
520fn display(error: impl std::fmt::Display) -> String {
521    error.to_string()
522}
523
524/// Render an offline workspace failure with its diagnostic's `hint`.
525///
526/// History refusals such as `migration_history_profile_upgrade_required`
527/// carry the command that resolves them as a `hint` detail, which the plain
528/// `Display` projection omits.
529fn display_workspace(error: TypeBridgeWorkspaceError) -> String {
530    match error.contract() {
531        Some(diagnostic) => with_hint(error.to_string(), diagnostic),
532        None => error.to_string(),
533    }
534}
535
536/// Render an offline contract diagnostic with its `hint` detail.
537fn display_diagnostic(diagnostic: Diagnostic) -> String {
538    with_hint(diagnostic.to_string(), &diagnostic)
539}
540
541fn with_hint(rendered: String, diagnostic: &Diagnostic) -> String {
542    match diagnostic.details().get("hint") {
543        Some(DiagnosticDetailValue::Text(hint)) => format!("{rendered}\n  hint: {hint}"),
544        _ => rendered,
545    }
546}
547
548/// Render one secure lifecycle failure after credentials have been resolved.
549///
550/// Provider errors are allowed to echo request metadata, including
551/// credentials. Retain only the runtime's structurally credential-safe
552/// TLS/version projection; every other error collapses to an operation code
553/// and drops its source.
554fn sanitize_connected_error(
555    context: String,
556    code: &'static str,
557    error: type_bridge_orm::SecureConnectError,
558) -> String {
559    match error.credential_safe_diagnostic() {
560        Some(diagnostic) => format!("{context}: {diagnostic}"),
561        None => format!("{context} [{code}]; inspect provider logs"),
562    }
563}
564
565/// Render a database operation failure after credentials have been resolved.
566///
567/// Unlike secure connection errors, ordinary ORM errors have no closed safe
568/// projection and may contain provider-controlled request metadata.
569fn sanitize_connected_orm_error(
570    context: String,
571    code: &'static str,
572    _error: type_bridge_orm::OrmError,
573) -> String {
574    format!("{context} [{code}]; inspect provider logs")
575}
576
577/// Schema export happens after credentials have been resolved, so no raw ORM
578/// error or source chain may cross the CLI boundary.
579fn sanitize_schema_export_error(_error: type_bridge_orm::OrmError) -> String {
580    "cannot export the managed schema [typedb_schema_export_failed]; inspect provider logs"
581        .to_owned()
582}
583
584/// Render a non-success migration outcome without exposing diagnostic details.
585///
586/// TypeDB adapters retain provider text in `Diagnostic` details for trusted
587/// programmatic inspection. Its `Display` surface intentionally omits those
588/// details, while derived `Debug` includes them, so every post-credential CLI
589/// path must use this closed projection.
590fn sanitize_migration_execution_outcome(
591    context: &str,
592    outcome: type_bridge_schema_migration::MigrationExecutionOutcome,
593) -> String {
594    use type_bridge_schema_migration::{
595        MigrationExecutionOutcome as Outcome, MigrationExecutionPosition as Position,
596    };
597
598    let render_position = |position| match position {
599        Position::TransactionGroup(ordinal) => format!("transaction group {ordinal}"),
600        Position::BackfillStep(ordinal) => format!("backfill step {ordinal}"),
601        Position::ManifestCheckpoint => "manifest checkpoint".to_owned(),
602    };
603    match outcome {
604        Outcome::Applied { .. } => format!("{context}: applied"),
605        Outcome::RetrySafe {
606            migration_id,
607            position,
608            diagnostic,
609        } => format!(
610            "{context}: retry-safe at {}/{} ({position}): {diagnostic}",
611            migration_id.app_label().as_str(),
612            migration_id.name().as_str(),
613            position = render_position(position),
614        ),
615        Outcome::RequiresExplicitRecovery {
616            migration_id,
617            position,
618            diagnostic,
619        } => format!(
620            "{context}: explicit recovery required at {}/{} ({position}): {diagnostic}",
621            migration_id.app_label().as_str(),
622            migration_id.name().as_str(),
623            position = render_position(position),
624        ),
625    }
626}
627
628fn sanitize_migration_rollback_outcome(
629    outcome: type_bridge_schema_migration::MigrationRollbackOutcome,
630) -> String {
631    use type_bridge_schema_migration::MigrationRollbackOutcome as Outcome;
632    match outcome {
633        Outcome::RolledBack { .. } => "rollback completed".to_owned(),
634        Outcome::RetrySafe {
635            migration_id,
636            step_ordinal,
637            diagnostic,
638        } => format!(
639            "rollback may be retried at {}/{} step {} [{}]",
640            migration_id.app_label().as_str(),
641            migration_id.name().as_str(),
642            step_ordinal,
643            diagnostic.code().as_str(),
644        ),
645        Outcome::RequiresExplicitRecovery {
646            migration_id,
647            step_ordinal,
648            diagnostic,
649        } => format!(
650            "rollback requires explicit recovery at {}/{} step {} [{}]",
651            migration_id.app_label().as_str(),
652            migration_id.name().as_str(),
653            step_ordinal,
654            diagnostic.code().as_str(),
655        ),
656    }
657}
658
659/// Generate every configured binding projection from the canonical schema.
660///
661/// The resolved workspace schema is projected per configured target with
662/// each shipped emitter's handler and code-resource evidence — the same
663/// path the codegen acceptance fixtures pin — and emitted
664/// deterministically. The complete generation is prepared beneath the
665/// retained workspace authority and committed as one rollback-verified batch,
666/// with schema authority last; files not produced by an emitter are never
667/// touched or deleted.
668fn run_schema_generate(workspace: &TypeBridgeWorkspace) -> Result<(), String> {
669    run_schema_generate_with(workspace, |target, resolved, authority| {
670        generate_binding_package(
671            target,
672            resolved,
673            authority,
674            workspace.config().app_label(),
675            workspace.config().type_name_overrides(target),
676        )
677    })
678}
679
680fn generate_binding_package(
681    target: type_bridge_contract::projection::BindingTarget,
682    resolved: &type_bridge_schema::ResolvedSchema,
683    authority: &type_bridge_schema::VerifiedSchemaAuthority,
684    app_label: &type_bridge_contract::migration::MigrationAppLabel,
685    type_names: &[type_bridge_contract::projection::TypeNameOverride],
686) -> Result<type_bridge_schema_codegen::GeneratedPackage, String> {
687    use type_bridge_contract::projection::{BindingTarget, ProjectionConfig};
688    use type_bridge_schema::project;
689    use type_bridge_schema_codegen::{CEmitter, PythonEmitter, RustEmitter, TypeScriptEmitter};
690
691    let configure = |mut config: ProjectionConfig| -> Result<ProjectionConfig, String> {
692        for item in type_names {
693            config = config
694                .with_type_name_override(item.type_id().clone(), item.name().as_str())
695                .map_err(display)?;
696        }
697        Ok(config)
698    };
699
700    match target {
701        BindingTarget::Python => {
702            let emitter = PythonEmitter::new();
703            let handlers = emitter.generator_handlers_for(resolved);
704            let resources = emitter.code_resources_for(resolved).map_err(display)?;
705            let projection = project(
706                resolved,
707                BindingTarget::Python,
708                &configure(ProjectionConfig::python())?,
709                &handlers,
710                &resources,
711            )
712            .map_err(display)?;
713            emitter.emit(&projection, authority)
714        }
715        BindingTarget::TypeScript => {
716            let emitter = TypeScriptEmitter::new();
717            let handlers = emitter.generator_handlers_for(resolved);
718            let resources = emitter.code_resources_for(resolved).map_err(display)?;
719            let projection = project(
720                resolved,
721                BindingTarget::TypeScript,
722                &configure(ProjectionConfig::typescript())?,
723                &handlers,
724                &resources,
725            )
726            .map_err(display)?;
727            emitter.emit(&projection, authority)
728        }
729        BindingTarget::Rust => {
730            let emitter = RustEmitter::new();
731            let handlers = emitter.generator_handlers_for(resolved);
732            let resources = emitter.code_resources_for(resolved).map_err(display)?;
733            let projection = project(
734                resolved,
735                BindingTarget::Rust,
736                &configure(ProjectionConfig::rust())?,
737                &handlers,
738                &resources,
739            )
740            .map_err(display)?;
741            emitter.emit(&projection, authority)
742        }
743        BindingTarget::C => {
744            let emitter = CEmitter::new();
745            let handlers = emitter.generator_handlers_for(resolved);
746            let resources = emitter.code_resources_for(resolved).map_err(display)?;
747            let config = configure(ProjectionConfig::c(c_symbol_prefix_for_app_label(
748                app_label,
749            )))?;
750            let projection = project(resolved, BindingTarget::C, &config, &handlers, &resources)
751                .map_err(display)?;
752            emitter.emit(&projection, authority)
753        }
754        _ => {
755            return Err(format!(
756                "schema generation does not support binding target {}",
757                target.as_str()
758            ));
759        }
760    }
761    .map_err(display)
762}
763
764fn run_schema_generate_with(
765    workspace: &TypeBridgeWorkspace,
766    mut generate: impl FnMut(
767        type_bridge_contract::projection::BindingTarget,
768        &type_bridge_schema::ResolvedSchema,
769        &type_bridge_schema::VerifiedSchemaAuthority,
770    ) -> Result<type_bridge_schema_codegen::GeneratedPackage, String>,
771) -> Result<(), String> {
772    use type_bridge_schema::{build_schema_authority, encode_schema_authority};
773
774    let outputs = workspace.config().outputs();
775    let authority_output = workspace.config().schema_authority_output();
776    if outputs.is_empty() && authority_output.is_none() {
777        return Err(
778            "no generated outputs configured; add bindings.<target>.output or \
779             artifacts.schema-authority.output to the manifest"
780                .into(),
781        );
782    }
783
784    let resolved = workspace.resolved_schema();
785    let migration_directory = workspace.ensure_migration_directory().map_err(display)?;
786    let migration_history = workspace
787        .migration_history_bundle_in(&migration_directory)
788        .map_err(display)?;
789    let authority = build_schema_authority(
790        workspace.declared_schema(),
791        workspace.required_capabilities(),
792        workspace.delta_context(),
793    )
794    .map_err(display)?;
795    let authority_bytes = encode_schema_authority(&authority);
796
797    // Finish every pure projection before mutating any output. A target-level
798    // generation failure therefore cannot publish an earlier language from a
799    // different semantic attempt.
800    let mut packages = Vec::with_capacity(outputs.len());
801    for (&target, directory) in outputs {
802        let package = generate(target, resolved, &authority)?
803            .with_migration_history_bundle(&migration_history)
804            .map_err(display)?;
805        packages.push((target, directory, package));
806    }
807
808    // Build one workspace-relative batch without touching the filesystem. The
809    // workspace authority prevalidates every destination and prepares every
810    // flushed same-directory temporary before it publishes in this order. The
811    // final server authority is deliberately appended last.
812    let workspace_root = workspace.output_root()?;
813    let mut generated_files = Vec::new();
814    let mut generated_packages = Vec::with_capacity(packages.len());
815    for (target, directory, package) in &packages {
816        let display_root = workspace_root.display_path().join(directory.as_path());
817        let file_count = package.files().len();
818        for (path, bytes) in package.files() {
819            let relative = std::path::Path::new(path);
820            validate_generated_relative_path(relative)?;
821            generated_files.push((directory.as_path().join(relative), bytes.as_slice()));
822        }
823        generated_packages.push((*target, display_root, file_count));
824    }
825    let prepared_authority = authority_output
826        .map(|output| {
827            let path = output.as_path();
828            let _file_name = path
829                .file_name()
830                .ok_or_else(|| "schema-authority output has no file name".to_owned())?;
831            Ok::<_, String>(path.to_path_buf())
832        })
833        .transpose()?;
834
835    if let Some(relative) = &prepared_authority {
836        generated_files.push((relative.clone(), authority_bytes.as_slice()));
837    }
838    workspace_root.write_atomic_batch(
839        generated_files
840            .iter()
841            .map(|(path, bytes)| (path.as_path(), *bytes)),
842    )?;
843
844    for (target, display_root, file_count) in generated_packages {
845        println!(
846            "generated {} file(s) for {} into {}",
847            file_count,
848            target.as_str(),
849            display_root.display(),
850        );
851    }
852    if let Some(relative) = prepared_authority {
853        println!(
854            "generated schema authority at {}\n  authority identity: {}",
855            workspace_root.display_path().join(relative).display(),
856            authority.authority_fingerprint().digest().to_hex(),
857        );
858    }
859    Ok(())
860}
861
862#[cfg(test)]
863mod schema_generation_atomicity_tests {
864    use std::collections::BTreeMap;
865    use std::env;
866    use std::fs::OpenOptions;
867    use std::io::Write as _;
868
869    use super::*;
870    use serde_json::json;
871    use sha2::{Digest as _, Sha256};
872    use type_bridge_contract::codec::to_canonical_json;
873    use type_bridge_contract::projection::BindingTarget;
874
875    const ARTIFACT_OUTPUT_ENV: &str = "TYPE_BRIDGE_SDK_MODELS_ATOMIC_GENERATION_OUTPUT";
876    const ARTIFACT_SOURCE_PATH: &str = "type-bridge-core/crates/cli/src/lib.rs";
877    const ARTIFACT_FORMAT: &str = "typebridge.sdk-models-artifact-observation/v1";
878    const MAX_ARTIFACT_BYTES: usize = 64 * 1024;
879
880    fn publish_atomic_generation_observation(observation: serde_json::Value) {
881        let Some(output) = env::var_os(ARTIFACT_OUTPUT_ENV) else {
882            return;
883        };
884        let output = PathBuf::from(output);
885        assert!(
886            output.is_absolute(),
887            "{ARTIFACT_OUTPUT_ENV} must be absolute"
888        );
889        let parent = output
890            .parent()
891            .expect("atomic-generation artifact path has a parent");
892        let parent_metadata =
893            fs::symlink_metadata(parent).expect("atomic-generation artifact parent is inspectable");
894        assert!(
895            parent_metadata.is_dir() && !parent_metadata.file_type().is_symlink(),
896            "atomic-generation artifact parent must be a real directory"
897        );
898        let source = include_bytes!("lib.rs");
899        let artifact = json!({
900            "format": ARTIFACT_FORMAT,
901            "semantic_profile": "typedb-3.12.1/v1",
902            "producer": {
903                "id": "type-bridge-cli.sdk-models-atomic-multibinding-artifact",
904                "source": {
905                    "path": ARTIFACT_SOURCE_PATH,
906                    "sha256": format!("{:x}", Sha256::digest(source)),
907                },
908                "test_id": "schema_generation_atomicity_tests::injected_c_emitter_failure_preserves_all_four_ordered_packages",
909            },
910            "result": {
911                "observation_ref": "atomic_multibinding_generation",
912                "outcome": "passed",
913                "proof_kind": "artifact",
914                "observation": observation,
915            },
916        });
917        let mut bytes =
918            to_canonical_json(&artifact).expect("atomic-generation artifact encodes canonically");
919        bytes.push(b'\n');
920        assert!(
921            bytes.len() <= MAX_ARTIFACT_BYTES,
922            "atomic-generation artifact exceeds {MAX_ARTIFACT_BYTES} bytes"
923        );
924        let mut destination = OpenOptions::new()
925            .write(true)
926            .create_new(true)
927            .open(&output)
928            .expect("atomic-generation artifact destination must be new");
929        if let Err(error) = destination
930            .write_all(&bytes)
931            .and_then(|()| destination.sync_all())
932        {
933            drop(destination);
934            let _ = fs::remove_file(&output);
935            panic!("atomic-generation artifact publication failed: {error}");
936        }
937    }
938
939    fn snapshot(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
940        let mut files = BTreeMap::new();
941        let mut directories = vec![root.to_path_buf()];
942        while let Some(directory) = directories.pop() {
943            for entry in fs::read_dir(&directory).expect("generated directory reads") {
944                let path = entry.expect("generated entry reads").path();
945                if path.is_dir() {
946                    directories.push(path);
947                } else {
948                    files.insert(
949                        path.strip_prefix(root)
950                            .expect("generated path is beneath its root")
951                            .to_path_buf(),
952                        fs::read(path).expect("generated file reads"),
953                    );
954                }
955            }
956        }
957        files
958    }
959
960    fn write_workspace(root: &Path, source: &str) -> PathBuf {
961        fs::create_dir_all(root.join("schema/fragments")).expect("schema directory creates");
962        fs::create_dir_all(root.join("migrations/v2")).expect("migration directory creates");
963        fs::write(
964            root.join("typebridge.yaml"),
965            "format: typebridge.workspace/v1\n\
966             schema:\n  root: schema/schema.yaml\n  ownership: exclusive\n  managed-scope: ordered-atomic\n\
967             compatibility:\n  semantic-profile: typedb-3.12.1/v1\n\
968             migrations:\n  directory: migrations/v2\n  app-label: ordered_atomic\n\
969             bindings:\n  python:\n    output: generated/python\n  typescript:\n    output: generated/typescript\n  rust:\n    output: generated/rust\n  c:\n    output: generated/c\n\
970             artifacts:\n  schema-authority:\n    output: generated/schema-authority.json\n",
971        )
972        .expect("manifest writes");
973        fs::write(
974            root.join("schema/schema.yaml"),
975            "format: typebridge.schema-set/v1\nsources: [fragments/*.yaml]\n",
976        )
977        .expect("schema set writes");
978        fs::write(root.join("schema/fragments/model.yaml"), source).expect("schema writes");
979        root.join("typebridge.yaml")
980    }
981
982    #[test]
983    fn workspace_type_names_resolve_collisions_in_generated_packages() {
984        let directory = tempfile::tempdir().unwrap();
985        let root = directory.path();
986        let manifest = write_workspace(
987            root,
988            "format: typebridge.schema/v2\nattributes:\n  powertrain_ref: { value: string }\nentities:\n  Powertrain:\n    owns:\n      powertrain_ref: { card: 1 }\n",
989        );
990        let workspace = load_workspace(&manifest).unwrap();
991        assert!(run_schema_generate(&workspace).is_err());
992        let original = fs::read_to_string(&manifest).unwrap();
993        let mut configured = original;
994        for target in ["python", "typescript", "rust", "c"] {
995            let output = format!("output: generated/{target}");
996            configured = configured.replace(&output, &format!("{output}\n    type-names:\n      attribute:\n        powertrain_ref: PowertrainReferenceValue"));
997        }
998        fs::write(&manifest, configured).unwrap();
999        let workspace = load_workspace(&manifest).unwrap();
1000        run_schema_generate(&workspace).unwrap();
1001        let models = fs::read_to_string(root.join("generated/typescript/src/models.ts")).unwrap();
1002        assert!(models.contains("PowertrainReferenceValue"));
1003        assert!(models.contains("powertrain_ref"));
1004        let first = snapshot(&root.join("generated"));
1005        run_schema_generate(&workspace).unwrap();
1006        assert_eq!(first, snapshot(&root.join("generated")));
1007    }
1008
1009    #[test]
1010    fn injected_c_emitter_failure_preserves_all_four_ordered_packages() {
1011        let directory = tempfile::tempdir().expect("workspace directory");
1012        let root = directory.path();
1013        let manifest = write_workspace(
1014            root,
1015            "format: typebridge.schema/v2\n\
1016             attributes:\n  identifier: { value: string }\n  tag: { value: string }\n\
1017             entities:\n  person:\n    owns:\n      identifier: { key: true }\n      tag: { card: { min: 0, max: 3 }, ordered: true, distinct: true }\n\
1018             relations:\n  group:\n    relates:\n      member: { card: { min: 0, max: 3 }, ordered: true, distinct: true }\n\
1019             plays:\n  person:\n    group:\n      member: { card: { min: 0, max: 1 } }\n",
1020        );
1021        let accepted = load_workspace(&manifest).expect("ordered workspace loads");
1022        run_schema_generate(&accepted).expect("ordered packages generate");
1023
1024        let accepted_trees = ["python", "typescript", "rust", "c"]
1025            .map(|target| (target, snapshot(&root.join("generated").join(target))));
1026        let expected_history = accepted
1027            .migration_history_bundle_bytes()
1028            .expect("canonical migration history bundle");
1029        for (target, tree) in &accepted_trees {
1030            assert_eq!(
1031                tree.get(std::path::Path::new(
1032                    type_bridge_schema_codegen::MIGRATION_HISTORY_BUNDLE_RESOURCE,
1033                )),
1034                Some(&expected_history),
1035                "{target} package must embed the byte-identical canonical history bundle",
1036            );
1037        }
1038        let accepted_authority =
1039            fs::read(root.join("generated/schema-authority.json")).expect("authority reads");
1040
1041        run_schema_generate(&accepted).expect("identical ordered packages regenerate");
1042        for (target, accepted_tree) in &accepted_trees {
1043            assert_eq!(
1044                &snapshot(&root.join("generated").join(target)),
1045                accepted_tree,
1046                "{target} destination changed after deterministic regeneration",
1047            );
1048        }
1049        assert_eq!(
1050            fs::read(root.join("generated/schema-authority.json")).expect("authority rereads"),
1051            accepted_authority,
1052            "schema authority changed after deterministic regeneration",
1053        );
1054
1055        fs::write(
1056            root.join("schema/fragments/model.yaml"),
1057            "format: typebridge.schema/v2\n\
1058             attributes:\n  identifier: { value: string }\n  tag: { value: string }\n  title: { value: string }\n\
1059             entities:\n  person:\n    owns:\n      identifier: { key: true }\n      tag: { card: { min: 0, max: 4 }, ordered: true, distinct: true }\n      title: { card: 1 }\n\
1060             relations:\n  group:\n    relates:\n      member: { card: { min: 0, max: 4 }, ordered: true, distinct: true }\n\
1061             plays:\n  person:\n    group:\n      member: { card: { min: 0, max: 1 } }\n",
1062        )
1063        .expect("changed schema writes");
1064        let changed = load_workspace(&manifest).expect("changed ordered workspace loads");
1065        let mut attempted = Vec::new();
1066        let error = run_schema_generate_with(&changed, |target, resolved, authority| {
1067            attempted.push(target);
1068            if target == BindingTarget::C {
1069                return Err("injected C emitter failure".to_owned());
1070            }
1071            generate_binding_package(
1072                target,
1073                resolved,
1074                authority,
1075                changed.config().app_label(),
1076                changed.config().type_name_overrides(target),
1077            )
1078        })
1079        .expect_err("injected C emitter failure rejects the transaction");
1080        assert_eq!(error, "injected C emitter failure");
1081        assert_eq!(
1082            attempted,
1083            vec![
1084                BindingTarget::Python,
1085                BindingTarget::TypeScript,
1086                BindingTarget::Rust,
1087                BindingTarget::C,
1088            ],
1089            "the injected failure did not occur after the three earlier packages prepared",
1090        );
1091
1092        for (target, accepted_tree) in &accepted_trees {
1093            assert_eq!(
1094                snapshot(&root.join("generated").join(target)),
1095                *accepted_tree,
1096                "{target} destination changed after the injected C emitter failure",
1097            );
1098        }
1099        assert_eq!(
1100            fs::read(root.join("generated/schema-authority.json")).expect("authority rereads"),
1101            accepted_authority,
1102            "schema authority changed after the injected C emitter failure",
1103        );
1104
1105        publish_atomic_generation_observation(json!({
1106            "targets": ["python", "typescript", "rust", "c"],
1107            "common_authority_identity": {
1108                "schema_source_equal": true,
1109                "semantic_profile": "typedb-3.12.1/v1",
1110                "semantic_fingerprint_equal": true,
1111                "resource_ledger_equal": true,
1112            },
1113            "package_identities_distinct": true,
1114            "generated_sidecars": [],
1115            "no_sidecar_runtime_dependency": true,
1116            "deterministic_rerun": {
1117                "byte_identical": true,
1118                "published_targets": accepted_trees.len(),
1119            },
1120            "injected_failure": {
1121                "failed_target": "c",
1122                "published_targets": 0,
1123                "previous_outputs_unchanged": true,
1124                "staging_artifacts_remaining": 0,
1125            },
1126        }));
1127    }
1128}
1129
1130/// Export canonical declared bytes for explicitly low-level V2 tooling.
1131fn run_schema_export_declared(
1132    workspace: &TypeBridgeWorkspace,
1133    output: &Path,
1134) -> Result<(), String> {
1135    use type_bridge_contract::schema::encode_declared_schema;
1136
1137    validate_declared_output_path(output)?;
1138    let root = workspace.output_root()?;
1139    let parent = root.open_beneath(output.parent().unwrap_or_else(|| std::path::Path::new("")))?;
1140    let file_name = output
1141        .file_name()
1142        .ok_or_else(|| "declared-schema output has no file name".to_owned())?;
1143    let destination = parent.display_path().join(file_name);
1144    let bytes = encode_declared_schema(workspace.declared_schema()).map_err(display)?;
1145    parent.write_atomic(file_name, &bytes)?;
1146    println!(
1147        "wrote canonical declared schema to {}\n  declared identity: {}",
1148        destination.display(),
1149        workspace
1150            .declared_schema()
1151            .declared_identity_fingerprint()
1152            .as_fingerprint()
1153            .digest()
1154            .to_hex(),
1155    );
1156    Ok(())
1157}
1158
1159fn validate_declared_output_path(output: &Path) -> Result<(), String> {
1160    let Some(portable) = output.to_str() else {
1161        return Err("declared-schema output must be valid UTF-8".into());
1162    };
1163    let invalid_spelling = portable.is_empty()
1164        || portable.contains(['\\', ':', '\0'])
1165        || portable.bytes().any(|byte| byte.is_ascii_control())
1166        || portable
1167            .split('/')
1168            .any(|segment| segment.is_empty() || matches!(segment, "." | ".."));
1169    let invalid_components = output.is_absolute()
1170        || output
1171            .components()
1172            .any(|component| !matches!(component, Component::Normal(_)));
1173    if invalid_spelling || invalid_components {
1174        return Err("declared-schema output must be a confined portable workspace path".into());
1175    }
1176    if output.extension().and_then(|extension| extension.to_str()) != Some("json") {
1177        return Err("declared-schema output must end in lowercase .json".into());
1178    }
1179    Ok(())
1180}
1181
1182fn validate_generated_relative_path(path: &std::path::Path) -> Result<(), String> {
1183    if path.as_os_str().is_empty()
1184        || path
1185            .components()
1186            .any(|component| !matches!(component, std::path::Component::Normal(_)))
1187    {
1188        return Err(format!(
1189            "generated output path {:?} is not a confined relative file",
1190            path
1191        ));
1192    }
1193    Ok(())
1194}
1195
1196enum ConnectedAction {
1197    Apply {
1198        approvals: Vec<String>,
1199    },
1200    Verify,
1201    Rollback {
1202        removals: BTreeSet<type_bridge_contract::migration::MigrationId>,
1203        approvals: Vec<String>,
1204    },
1205    Adopt {
1206        archive_directory: PathBuf,
1207        name: String,
1208    },
1209    UpgradeProfile {
1210        to: String,
1211        name: Option<String>,
1212    },
1213}
1214
1215fn secure_connect_options(
1216    environment: &WorkspaceEnvironment,
1217) -> type_bridge_orm::SecureConnectOptions {
1218    let tls_mode = match environment.transport_policy() {
1219        WorkspaceTransportPolicy::Disabled => type_bridge_orm::TlsMode::Disabled,
1220        WorkspaceTransportPolicy::NativeRoots => type_bridge_orm::TlsMode::NativeRoots,
1221        WorkspaceTransportPolicy::CustomRootCa(root_ca) => {
1222            type_bridge_orm::TlsMode::CustomRootCa(root_ca.as_path().to_path_buf())
1223        }
1224    };
1225    let mut options = type_bridge_orm::SecureConnectOptions {
1226        tls_mode,
1227        ..type_bridge_orm::SecureConnectOptions::default()
1228    };
1229    if let Some(port) = environment.http_port() {
1230        options.http_port = port;
1231    }
1232    options
1233}
1234
1235fn preflight_secure_connect_options(
1236    workspace: &TypeBridgeWorkspace,
1237    environment_name: &str,
1238) -> Result<type_bridge_orm::PreparedSecureConnectOptions, String> {
1239    let environment = workspace
1240        .config()
1241        .environment(environment_name)
1242        .ok_or_else(|| {
1243            format!("environment {environment_name:?} is not owned by this workspace")
1244        })?;
1245    let options = secure_connect_options(environment);
1246    match workspace
1247        .capture_environment_custom_root_ca(environment_name)
1248        .map_err(display)?
1249    {
1250        Some(bytes) => options
1251            .prepare_transport_from_captured_custom_root(bytes)
1252            .map_err(display),
1253        None => options.prepare_transport().map_err(display),
1254    }
1255}
1256
1257fn run_connected(
1258    workspace: &TypeBridgeWorkspace,
1259    environment: &str,
1260    action: ConnectedAction,
1261) -> Result<(), String> {
1262    let runtime = tokio::runtime::Runtime::new()
1263        .map_err(|error| format!("cannot start the async runtime: {error}"))?;
1264    runtime.block_on(run_connected_async(workspace, environment, action))
1265}
1266
1267async fn run_connected_async(
1268    workspace: &TypeBridgeWorkspace,
1269    environment_name: &str,
1270    action: ConnectedAction,
1271) -> Result<(), String> {
1272    let config = workspace.config();
1273    let Some(environment) = config.environment(environment_name) else {
1274        let known = config
1275            .environments()
1276            .keys()
1277            .cloned()
1278            .collect::<Vec<_>>()
1279            .join(", ");
1280        return Err(format!(
1281            "unknown environment {environment_name:?}; the manifest declares: [{known}]"
1282        ));
1283    };
1284    if matches!(
1285        &action,
1286        ConnectedAction::Apply { .. }
1287            | ConnectedAction::Rollback { .. }
1288            | ConnectedAction::Adopt { .. }
1289            | ConnectedAction::UpgradeProfile { .. }
1290    ) && !environment.migrate()
1291    {
1292        return Err(format!(
1293            "environment {environment_name:?} is not opted into migration \
1294            application; set `migrate: true` in the manifest to allow it"
1295        ));
1296    }
1297    // Only the profiles paired with an exact server run connected migrations;
1298    // the provider rechecks the negotiated server against this pair.
1299    type_bridge_schema_migration_typedb::require_supported_migration_profile(
1300        config.semantic_profile(),
1301    )
1302    .map_err(display)?;
1303    environment
1304        .requirements()
1305        .ensure_supported_by(&execution_capability_vocabulary().map_err(display)?)
1306        .map_err(display)?;
1307    if let ConnectedAction::UpgradeProfile { to, .. } = &action {
1308        require_profile_upgrade_target(config.semantic_profile(), to)?;
1309    }
1310
1311    // Validate the name and capture one immutable archive-history authority
1312    // before creating the canonical directory or resolving credentials.
1313    let prepared_adoption = match &action {
1314        ConnectedAction::Adopt {
1315            archive_directory,
1316            name,
1317        } => Some(prepare_archive_adoption(
1318            workspace,
1319            archive_directory,
1320            name,
1321        )?),
1322        ConnectedAction::Apply { .. }
1323        | ConnectedAction::Rollback { .. }
1324        | ConnectedAction::Verify
1325        | ConnectedAction::UpgradeProfile { .. } => None,
1326    };
1327
1328    // Retain one descriptor-backed authority for the whole connected action.
1329    // Adoption alone may create missing real directory components; apply and
1330    // verify remain fail-closed and non-creating here.
1331    let migration_directory = if matches!(&action, ConnectedAction::Adopt { .. }) {
1332        workspace.ensure_migration_directory().map_err(display)?
1333    } else {
1334        workspace.open_migration_directory().map_err(display)?
1335    };
1336    // Ordinary connected operations reject an incomplete adoption pair before
1337    // credentials, network I/O, or database creation. Adoption itself is the
1338    // sole recovery path permitted to observe and complete an exact orphan.
1339    // A profile upgrade discovers the older-profile history ordinary
1340    // discovery refuses, and publishes its bridge offline before connecting.
1341    let ordinary_graph = match &action {
1342        ConnectedAction::Apply { .. }
1343        | ConnectedAction::Rollback { .. }
1344        | ConnectedAction::Verify => Some(
1345            workspace
1346                .discover_migrations_in(&migration_directory)
1347                .map_err(display_workspace)?,
1348        ),
1349        ConnectedAction::Adopt { .. } | ConnectedAction::UpgradeProfile { .. } => None,
1350    };
1351    let profile_bridge = match &action {
1352        ConnectedAction::UpgradeProfile { name, .. } => Some(publish_profile_upgrade_bridge(
1353            workspace,
1354            &migration_directory,
1355            name.as_deref(),
1356        )?),
1357        ConnectedAction::Apply { .. }
1358        | ConnectedAction::Rollback { .. }
1359        | ConnectedAction::Verify
1360        | ConnectedAction::Adopt { .. } => None,
1361    };
1362    // Approval syntax, membership, safety, and digest binding are local
1363    // authority checks. Resolve them before credentials, network I/O, or
1364    // database creation; the runner re-discovers and rechecks the bound
1365    // manifest at execution time.
1366    let prepared_approvals = match &action {
1367        ConnectedAction::Apply { approvals } => Some(bind_approvals(
1368            ordinary_graph
1369                .as_ref()
1370                .ok_or_else(|| "internal apply history was not retained".to_owned())?,
1371            approvals,
1372        )?),
1373        ConnectedAction::Rollback { approvals, .. } => Some(bind_rollback_approvals(
1374            ordinary_graph
1375                .as_ref()
1376                .ok_or_else(|| "internal rollback history was not retained".to_owned())?,
1377            approvals,
1378        )?),
1379        ConnectedAction::Verify
1380        | ConnectedAction::Adopt { .. }
1381        | ConnectedAction::UpgradeProfile { .. } => None,
1382    };
1383
1384    // Resolve and snapshot the complete transport policy before reading either
1385    // credential. Every later connect call clones this prepared handle, so no
1386    // custom-root path is reopened after secret resolution.
1387    let options = preflight_secure_connect_options(workspace, environment_name)?;
1388    let username = resolve_credential(environment.username())?;
1389    let password = resolve_credential(environment.password())?;
1390    let journal_name =
1391        type_bridge_schema_migration_typedb::derived_journal_database_name(environment.database());
1392    // `verify` is observational: it must never create the managed or
1393    // journal database (a typoed environment name would otherwise
1394    // materialize two databases). `adopt` requires the migrated v1 managed
1395    // database to already exist — bootstrapping an empty one would
1396    // guarantee a broken adoption — while its journal companion is new by
1397    // definition. Only migration-gated actions may bootstrap anything.
1398    let managed_requires_existing = match &action {
1399        ConnectedAction::Verify => Some(
1400            "`migration verify` is read-only and never creates databases \
1401             — apply migrations to this environment first",
1402        ),
1403        ConnectedAction::Adopt { .. } => {
1404            Some("`migration adopt` cutover requires the migrated v1 database to already exist")
1405        }
1406        ConnectedAction::UpgradeProfile { .. } => Some(
1407            "`migration upgrade-profile` requires the database moved to the new TypeDB server \
1408             to already exist",
1409        ),
1410        ConnectedAction::Apply { .. } | ConnectedAction::Rollback { .. } => None,
1411    };
1412    // The upgrade records into the ledger moved with the managed database; an
1413    // empty journal could never stand at the bridge parent.
1414    let journal_requires_existing = match &action {
1415        ConnectedAction::Verify => {
1416            Some("`migration verify` is read-only and never creates databases")
1417        }
1418        ConnectedAction::UpgradeProfile { .. } => Some(
1419            "`migration upgrade-profile` requires the migration journal moved with the \
1420             managed database",
1421        ),
1422        ConnectedAction::Apply { .. }
1423        | ConnectedAction::Rollback { .. }
1424        | ConnectedAction::Adopt { .. } => None,
1425    };
1426    // A TypeDB connection is server-scoped: binding a database name does not
1427    // require that database to exist. Negotiate and gate both pair members
1428    // before checking or creating either database, then retain both handles
1429    // through migration.
1430    let managed = std::sync::Arc::new(
1431        type_bridge_orm::Database::connect_prepared_secure_with_options(
1432            environment.uri(),
1433            environment.database(),
1434            &username,
1435            &password,
1436            options.clone(),
1437        )
1438        .await
1439        .map_err(|error| {
1440            sanitize_connected_error(
1441                "cannot connect the managed database".to_owned(),
1442                "typedb_database_connect_failed",
1443                error,
1444            )
1445        })?,
1446    );
1447    let journal = std::sync::Arc::new(
1448        type_bridge_orm::Database::connect_prepared_secure_with_options(
1449            environment.uri(),
1450            &journal_name,
1451            &username,
1452            &password,
1453            options,
1454        )
1455        .await
1456        .map_err(|error| {
1457            sanitize_connected_error(
1458                "cannot connect the journal database".to_owned(),
1459                "typedb_database_connect_failed",
1460                error,
1461            )
1462        })?,
1463    );
1464    type_bridge_schema_migration_typedb::require_supported_migration_execution_binding(
1465        &managed,
1466        &journal,
1467        workspace.delta_context(),
1468    )
1469    .map_err(display)?;
1470
1471    if let Some(reason) = managed_requires_existing {
1472        let exists = managed.database_exists().await.map_err(|error| {
1473            sanitize_connected_orm_error(
1474                format!("cannot check database {:?}", environment.database()),
1475                "typedb_database_exists_failed",
1476                error,
1477            )
1478        })?;
1479        if !exists {
1480            return Err(format!(
1481                "database {:?} does not exist; {reason}",
1482                environment.database()
1483            ));
1484        }
1485    } else {
1486        managed.create_database().await.map_err(|error| {
1487            sanitize_connected_orm_error(
1488                format!("cannot ensure database {:?}", environment.database()),
1489                "typedb_database_ensure_failed",
1490                error,
1491            )
1492        })?;
1493    }
1494
1495    // Adoption's live-schema comparison and complete pair publication precede
1496    // journal creation. Publication is bridge-first under the canonical
1497    // authoring lock, rolls back files created by a failed attempt, and accepts
1498    // exact orphan pieces so interrupted attempts remain adopt-only resumable.
1499    let adoption_files = if let Some(prepared) = prepared_adoption.as_ref() {
1500        verify_prepared_adoption_live(&managed, prepared).await?;
1501        Some(publish_prepared_adoption(
1502            workspace,
1503            &migration_directory,
1504            prepared,
1505        )?)
1506    } else {
1507        None
1508    };
1509
1510    if let Some(reason) = journal_requires_existing {
1511        let exists = journal.database_exists().await.map_err(|error| {
1512            sanitize_connected_orm_error(
1513                format!("cannot check database {journal_name:?}"),
1514                "typedb_database_exists_failed",
1515                error,
1516            )
1517        })?;
1518        if !exists {
1519            return Err(format!(
1520                "database {journal_name:?} does not exist; {reason}"
1521            ));
1522        }
1523    } else {
1524        journal.create_database().await.map_err(|error| {
1525            sanitize_connected_orm_error(
1526                format!("cannot ensure database {journal_name:?}"),
1527                "typedb_database_ensure_failed",
1528                error,
1529            )
1530        })?;
1531    }
1532
1533    let genesis = workspace
1534        .migration_genesis_in(&migration_directory)
1535        .map_err(display)?;
1536    let lowering =
1537        type_bridge_schema_migration::SchemaLoweringBinding::for_context(workspace.delta_context())
1538            .map_err(display)?;
1539    let runner = type_bridge_schema_migration_typedb::TypeDbMigrationRunner::new(
1540        managed,
1541        journal,
1542        genesis.clone(),
1543        workspace.delta_context().clone(),
1544        lowering,
1545        config.migration_policy().clone(),
1546    );
1547    let holder =
1548        type_bridge_schema_migration::LeaseHolderId::new("type-bridge-cli").map_err(display)?;
1549    let directory = migration_directory.directory();
1550
1551    match action {
1552        ConnectedAction::Apply { .. } => {
1553            let approvals = prepared_approvals
1554                .as_deref()
1555                .ok_or_else(|| "internal apply approvals were not retained".to_owned())?;
1556            let outcome = runner
1557                .apply_in(
1558                    directory,
1559                    &type_bridge_schema_migration::MigrationApplyTarget::DefaultHead,
1560                    &holder,
1561                    approvals,
1562                )
1563                .await
1564                .map_err(display)?;
1565            match outcome {
1566                type_bridge_schema_migration_typedb::MigrationDirectoryApplyOutcome::UpToDate => {
1567                    println!("applied ledger already reaches the committed head");
1568                    Ok(())
1569                }
1570                type_bridge_schema_migration_typedb::MigrationDirectoryApplyOutcome::Executed(
1571                    type_bridge_schema_migration::MigrationExecutionOutcome::Applied { .. },
1572                ) => {
1573                    println!("applied the committed chain");
1574                    Ok(())
1575                }
1576                type_bridge_schema_migration_typedb::MigrationDirectoryApplyOutcome::Executed(
1577                    outcome,
1578                ) => Err(sanitize_migration_execution_outcome(
1579                    "apply did not complete",
1580                    outcome,
1581                )),
1582            }
1583        }
1584        ConnectedAction::Rollback { removals, .. } => {
1585            let approvals = prepared_approvals
1586                .as_deref()
1587                .ok_or_else(|| "internal rollback approvals were not retained".to_owned())?;
1588            match runner
1589                .rollback_in(directory, &removals, &holder, approvals)
1590                .await
1591                .map_err(display)?
1592            {
1593                type_bridge_schema_migration_typedb::MigrationDirectoryRollbackOutcome::UpToDate => {
1594                    println!("requested migrations are already absent from the applied ledger");
1595                    Ok(())
1596                }
1597                type_bridge_schema_migration_typedb::MigrationDirectoryRollbackOutcome::Executed(
1598                    type_bridge_schema_migration::MigrationRollbackOutcome::RolledBack { .. },
1599                ) => {
1600                    println!("rolled back the requested migrations");
1601                    Ok(())
1602                }
1603                type_bridge_schema_migration_typedb::MigrationDirectoryRollbackOutcome::Executed(
1604                    outcome,
1605                ) => Err(sanitize_migration_rollback_outcome(outcome)),
1606            }
1607        }
1608        ConnectedAction::Verify => {
1609            let report = runner
1610                .verify_in(directory, Some(workspace.declared_schema()))
1611                .await
1612                .map_err(display)?;
1613            if report.is_clean() {
1614                println!(
1615                    "migration state is coherent\n  applied frontier: {}",
1616                    report
1617                        .applied_frontier()
1618                        .iter()
1619                        .map(|id| format!("{}/{}", id.app_label().as_str(), id.name().as_str()))
1620                        .collect::<Vec<_>>()
1621                        .join(", "),
1622                );
1623                Ok(())
1624            } else {
1625                for finding in report.findings() {
1626                    eprintln!("drift: {finding:?}");
1627                }
1628                Err(format!("{} drift finding(s)", report.findings().len()))
1629            }
1630        }
1631        ConnectedAction::Adopt { .. } => {
1632            let bridge_display_path = adoption_files
1633                .ok_or_else(|| "internal adoption preflight state was not retained".to_owned())?;
1634            let prepared = prepared_adoption
1635                .as_ref()
1636                .ok_or_else(|| "internal adoption authority was not retained".to_owned())?;
1637            let outcome = runner
1638                .import_verified_legacy_frontier_in(
1639                    &prepared.history,
1640                    &prepared.reconstructed,
1641                    directory,
1642                    &holder,
1643                )
1644                .await;
1645            match outcome {
1646                Ok(
1647                    type_bridge_schema_migration_typedb::MigrationDirectoryApplyOutcome::UpToDate,
1648                ) => {
1649                    println!("archive history is already adopted; the bridged ledger is current");
1650                    Ok(())
1651                }
1652                Ok(
1653                    type_bridge_schema_migration_typedb::MigrationDirectoryApplyOutcome::Executed(
1654                        type_bridge_schema_migration::MigrationExecutionOutcome::Applied { .. },
1655                    ),
1656                ) => {
1657                    println!(
1658                        "adopted the archive history\n  genesis: {}\n  bridge: {}",
1659                        migration_directory
1660                            .display_path()
1661                            .join(type_bridge_schema_compat::ADOPTED_GENESIS_FILE_NAME)
1662                            .display(),
1663                        bridge_display_path.display(),
1664                    );
1665                    Ok(())
1666                }
1667                Ok(
1668                    type_bridge_schema_migration_typedb::MigrationDirectoryApplyOutcome::Executed(
1669                        outcome,
1670                    ),
1671                ) => Err(sanitize_migration_execution_outcome(
1672                    "adoption checkpoint did not complete",
1673                    outcome,
1674                )),
1675                Err(error) => Err(display(error)),
1676            }
1677        }
1678        ConnectedAction::UpgradeProfile { .. } => {
1679            let bridge = profile_bridge
1680                .ok_or_else(|| "internal profile bridge was not retained".to_owned())?;
1681            match runner
1682                .upgrade_profile_in(directory, &holder)
1683                .await
1684                .map_err(display)?
1685            {
1686                type_bridge_schema_migration_typedb::MigrationDirectoryApplyOutcome::UpToDate => {
1687                    println!(
1688                        "profile bridge {} is already recorded",
1689                        migration_id_text(&bridge.id)
1690                    );
1691                    Ok(())
1692                }
1693                type_bridge_schema_migration_typedb::MigrationDirectoryApplyOutcome::Executed(
1694                    type_bridge_schema_migration::MigrationExecutionOutcome::Applied { .. },
1695                ) => {
1696                    println!(
1697                        "recorded profile bridge {}\n  semantic profile: {}",
1698                        migration_id_text(&bridge.id),
1699                        config.semantic_profile().as_str(),
1700                    );
1701                    Ok(())
1702                }
1703                type_bridge_schema_migration_typedb::MigrationDirectoryApplyOutcome::Executed(
1704                    outcome,
1705                ) => Err(sanitize_migration_execution_outcome(
1706                    "profile upgrade did not complete",
1707                    outcome,
1708                )),
1709            }
1710        }
1711    }
1712}
1713
1714fn migration_id_text(id: &type_bridge_contract::migration::MigrationId) -> String {
1715    format!("{}/{}", id.app_label().as_str(), id.name().as_str())
1716}
1717
1718/// Check `--to` before history discovery, file writes or credentials.
1719///
1720/// The command never edits `typebridge.yaml`: the user moves
1721/// `compatibility.semantic-profile` first, and `--to` repeats it so a stale
1722/// workspace cannot record a bridge to the wrong line.
1723fn require_profile_upgrade_target(
1724    workspace_profile: &type_bridge_contract::fingerprint::SemanticProfileId,
1725    to: &str,
1726) -> Result<(), String> {
1727    let target = type_bridge_contract::fingerprint::SemanticProfileId::new(to).map_err(display)?;
1728    type_bridge_schema_migration_typedb::require_supported_migration_profile(&target)
1729        .map_err(display)?;
1730    if &target != workspace_profile {
1731        let diagnostic = Diagnostic::new(
1732            type_bridge_contract::diagnostic::DiagnosticCategory::InvalidContract,
1733            type_bridge_contract::diagnostic::DiagnosticCode::new(
1734                "migration_upgrade_profile_target_not_workspace_profile",
1735            )
1736            .expect("static diagnostic code"),
1737            format!(
1738                "--to {} is not the workspace semantic profile {}",
1739                target.as_str(),
1740                workspace_profile.as_str()
1741            ),
1742        )
1743        .with_detail(
1744            "hint",
1745            format!(
1746                "set `compatibility.semantic-profile: {}` in the workspace manifest first",
1747                target.as_str()
1748            ),
1749        );
1750        return Err(display_diagnostic(diagnostic));
1751    }
1752    Ok(())
1753}
1754
1755/// The profile-upgrade bridge the connected step records.
1756struct ProfileUpgradeBridge {
1757    id: type_bridge_contract::migration::MigrationId,
1758}
1759
1760/// Author and publish the profile-upgrade bridge, or find the one present.
1761///
1762/// Discovery, authoring and publication run under the canonical authoring
1763/// lock, so the bridge can never continue a stale head. The bridge's
1764/// identity follows `migration make`: the next ordinal prefix and `name`.
1765/// A file created here is removed again when the published history does
1766/// not replay-verify. An already bridged history publishes nothing, so a
1767/// retry after a failed connection reuses the committed bridge.
1768fn publish_profile_upgrade_bridge(
1769    workspace: &TypeBridgeWorkspace,
1770    migration_directory: &type_bridge_workspace::MigrationDirectoryAuthority,
1771    name: Option<&str>,
1772) -> Result<ProfileUpgradeBridge, String> {
1773    let directory = migration_directory.directory();
1774    let _lock = directory.try_acquire_authoring_lock().map_err(|error| {
1775        if error.kind() == std::io::ErrorKind::WouldBlock {
1776            "profile upgrade conflicts with another canonical history publisher".to_owned()
1777        } else {
1778            format!("cannot lock canonical migration publication: {error}")
1779        }
1780    })?;
1781    let genesis = workspace
1782        .migration_genesis_in(migration_directory)
1783        .map_err(display_workspace)?;
1784    let (graph, from, parent) =
1785        match type_bridge_schema_migration::discover_history_for_profile_upgrade_in(
1786            directory,
1787            &genesis,
1788            workspace.delta_context(),
1789        )
1790        .map_err(display_diagnostic)?
1791        {
1792            type_bridge_schema_migration::MigrationProfileUpgrade::Bridged { bridge, .. } => {
1793                return Ok(ProfileUpgradeBridge { id: bridge });
1794            }
1795            type_bridge_schema_migration::MigrationProfileUpgrade::Pending {
1796                graph,
1797                from,
1798                parent,
1799            } => (graph, from, parent),
1800        };
1801    let base_name = match name {
1802        Some(name) => name.to_owned(),
1803        None => default_profile_bridge_name(workspace.config().semantic_profile())?,
1804    };
1805    let id = type_bridge_contract::migration::MigrationId::new(
1806        workspace.config().app_label().as_str(),
1807        type_bridge_schema_migration::allocate_migration_name(&graph, &base_name),
1808    )
1809    .map_err(display)?;
1810    let parent_schema = graph
1811        .manifest(&parent)
1812        .ok_or_else(|| "internal profile bridge parent is not in the history".to_owned())?
1813        .target_schema();
1814    let draft = type_bridge_schema_migration::SchemaMigrationDraft::profile_bridge(
1815        id.clone(),
1816        parent,
1817        from,
1818    )
1819    .map_err(display)?;
1820    let bridge = type_bridge_schema_migration::build_verified_manifest(
1821        draft,
1822        (parent_schema, workspace.delta_context()),
1823    )
1824    .map_err(display)?;
1825    let bytes = type_bridge_schema_migration::encode_verified_manifest(&bridge).map_err(display)?;
1826    let file_name = format!("{}.tbmigration.json", id.name().as_str());
1827    let created = publish_authority(directory, &file_name, &bytes)?;
1828    if let Err(error) = workspace.discover_migrations_in(migration_directory) {
1829        let primary = display_workspace(error);
1830        if !created {
1831            return Err(primary);
1832        }
1833        return Err(
1834            match directory
1835                .remove_file(file_name.as_ref())
1836                .and_then(|()| directory.sync_all())
1837            {
1838                Ok(()) => primary,
1839                Err(cleanup) => {
1840                    format!("{primary}; cannot remove newly published profile bridge: {cleanup}")
1841                }
1842            },
1843        );
1844    }
1845    println!(
1846        "wrote {}",
1847        migration_directory
1848            .display_path()
1849            .join(&file_name)
1850            .display()
1851    );
1852    Ok(ProfileUpgradeBridge { id })
1853}
1854
1855/// `profile_upgrade_typedb_3_13_6` for `typedb-3.13.6/v1`.
1856fn default_profile_bridge_name(
1857    profile: &type_bridge_contract::fingerprint::SemanticProfileId,
1858) -> Result<String, String> {
1859    let profile = type_bridge_schema_migration::MigrationProfile::for_semantic_profile(profile)
1860        .ok_or_else(|| format!("{} is not a migration profile", profile.as_str()))?;
1861    Ok(format!(
1862        "profile_upgrade_typedb_{}",
1863        profile.provider_version().replace('.', "_")
1864    ))
1865}
1866
1867struct PreparedArchiveAdoption {
1868    history: type_bridge_migration::LegacyAdoptionHistory,
1869    reconstructed: type_bridge_migration::VerifiedLegacyHead,
1870    authority: type_bridge_schema_compat::AdoptedGenesisAuthority,
1871    bridge: type_bridge_schema_migration::VerifiedSchemaMigrationManifest,
1872    bridge_name: String,
1873    bridge_bytes: Vec<u8>,
1874}
1875
1876/// Validate and derive every filesystem authority from one retained archive
1877/// history capture. This function performs no canonical-directory writes.
1878fn prepare_archive_adoption(
1879    workspace: &TypeBridgeWorkspace,
1880    archive_directory: &std::path::Path,
1881    name: &str,
1882) -> Result<PreparedArchiveAdoption, String> {
1883    // Validate the caller-controlled name before loading history or creating
1884    // the configured canonical directory.
1885    let migration_name =
1886        type_bridge_contract::migration::MigrationName::new(name.to_owned()).map_err(display)?;
1887    let bridge_name = format!("{}.tbmigration.json", migration_name.as_str());
1888    let history =
1889        type_bridge_migration::load_adoption_history(archive_directory).map_err(|error| {
1890            format!("archive migration directory failed the checked adoption loader: {error}")
1891        })?;
1892    let reconstructed = type_bridge_migration::reconstruct_legacy_head(&history)
1893        .map_err(|error| format!("archive head reconstruction failed: {error}"))?;
1894    let authority = type_bridge_schema_compat::parse_adopted_genesis_authority(
1895        type_bridge_contract::schema::DocumentId::new("legacy-head-snapshot.typeql")
1896            .map_err(display)?,
1897        reconstructed.schema_typeql(),
1898    )
1899    .map_err(display)?;
1900    let frontier = type_bridge_schema_migration_typedb::extract_legacy_frontier(history.graph())
1901        .map_err(display)?;
1902    let applied_set =
1903        type_bridge_schema_migration_typedb::extract_legacy_applied_set_digest(history.graph())
1904            .map_err(display)?;
1905    let id = type_bridge_contract::migration::MigrationId::from_components(
1906        type_bridge_contract::migration::MigrationAppLabel::new(
1907            workspace.config().app_label().as_str().to_owned(),
1908        )
1909        .map_err(display)?,
1910        migration_name,
1911    );
1912    let bridge = type_bridge_schema_migration::build_legacy_frontier_bridge(
1913        id,
1914        frontier,
1915        applied_set,
1916        authority.declared(),
1917        workspace.delta_context(),
1918    )
1919    .map_err(display)?;
1920    let bridge_bytes =
1921        type_bridge_schema_migration::encode_verified_manifest(&bridge).map_err(display)?;
1922    history
1923        .require_unchanged_head(&reconstructed)
1924        .map_err(|error| {
1925            format!("archive migration directory changed during adoption preparation: {error}")
1926        })?;
1927    Ok(PreparedArchiveAdoption {
1928        history,
1929        reconstructed,
1930        authority,
1931        bridge,
1932        bridge_name,
1933        bridge_bytes,
1934    })
1935}
1936
1937/// Compare the live managed schema with the prepared immutable head without
1938/// using live state as publication authority.
1939async fn verify_prepared_adoption_live(
1940    managed: &type_bridge_orm::Database,
1941    prepared: &PreparedArchiveAdoption,
1942) -> Result<(), String> {
1943    let export = managed
1944        .schema_text()
1945        .await
1946        .map_err(sanitize_schema_export_error)?;
1947    prepared
1948        .history
1949        .require_unchanged_head(&prepared.reconstructed)
1950        .map_err(|error| format!("archive adoption history changed during live export: {error}"))?;
1951    let expected_internal = type_bridge_schema_compat::released_typeql_to_declared_projection(
1952        type_bridge_contract::schema::DocumentId::new("managed-fence-schema.typeql")
1953            .map_err(display)?,
1954        type_bridge_schema_migration_typedb::MANAGED_FENCE_SCHEMA_TYPEQL,
1955    )
1956    .map_err(display)?;
1957    let live = type_bridge_schema_compat::parse_adopted_genesis_authority_with_internal(
1958        type_bridge_contract::schema::DocumentId::new("legacy-live-head.typeql")
1959            .map_err(display)?,
1960        &export,
1961        Some(&expected_internal),
1962    )
1963    .map_err(display)?;
1964    if live.legacy_identity() != prepared.authority.legacy_identity()
1965        || live.declared().declared_identity_fingerprint()
1966            != prepared
1967                .authority
1968                .declared()
1969                .declared_identity_fingerprint()
1970        || live.released_extension_identity() != prepared.authority.released_extension_identity()
1971    {
1972        return Err(
1973            "live managed schema differs from the independently verified archive-head snapshot"
1974                .to_owned(),
1975        );
1976    }
1977    Ok(())
1978}
1979
1980/// Publish the bridge/genesis pair under the shared authoring lock.
1981///
1982/// The prospective complete graph is replay-verified before publication. The
1983/// bridge is made visible first, so ordinary readers fail closed during the
1984/// short incomplete interval. Exact pre-existing orphan pieces are retained
1985/// and completed; only files created by this attempt are rolled back.
1986fn publish_prepared_adoption(
1987    workspace: &TypeBridgeWorkspace,
1988    migration_directory: &type_bridge_workspace::MigrationDirectoryAuthority,
1989    prepared: &PreparedArchiveAdoption,
1990) -> Result<PathBuf, String> {
1991    publish_prepared_adoption_with_after_bridge(workspace, migration_directory, prepared, || {})
1992}
1993
1994fn publish_prepared_adoption_with_after_bridge<F>(
1995    workspace: &TypeBridgeWorkspace,
1996    migration_directory: &type_bridge_workspace::MigrationDirectoryAuthority,
1997    prepared: &PreparedArchiveAdoption,
1998    after_bridge: F,
1999) -> Result<PathBuf, String>
2000where
2001    F: FnOnce(),
2002{
2003    let directory = migration_directory.directory();
2004    let _lock = directory.try_acquire_authoring_lock().map_err(|error| {
2005        if error.kind() == std::io::ErrorKind::WouldBlock {
2006            "migration adoption conflicts with another canonical history publisher".to_owned()
2007        } else {
2008            format!("cannot lock canonical migration publication: {error}")
2009        }
2010    })?;
2011    let genesis_name = type_bridge_schema_compat::ADOPTED_GENESIS_FILE_NAME;
2012    let genesis_bytes = prepared.reconstructed.schema_typeql().as_bytes();
2013    let mut bridge_created = false;
2014    let mut genesis_created = false;
2015    let mut after_bridge = Some(after_bridge);
2016
2017    let publication = (|| -> Result<(), String> {
2018        if let Some(existing) = read_existing_authority(directory, genesis_name)?
2019            && existing != genesis_bytes
2020        {
2021            return Err(format!(
2022                "{genesis_name} already exists but differs from the verified archive-head snapshot"
2023            ));
2024        }
2025        let bridge_already_published =
2026            if let Some(existing) = read_existing_authority(directory, &prepared.bridge_name)? {
2027                if existing != prepared.bridge_bytes {
2028                    return Err(format!(
2029                        "{} already exists with different authority bytes",
2030                        prepared.bridge_name
2031                    ));
2032                }
2033                true
2034            } else {
2035                false
2036            };
2037
2038        let (current, evidence) =
2039            type_bridge_schema_migration::discover_verified_migration_chain_with_evidence_in(
2040                directory,
2041                prepared.authority.declared(),
2042                workspace.delta_context(),
2043            )
2044            .map_err(display)?;
2045        let prospective = if current.manifest(prepared.bridge.id()).is_some() {
2046            current
2047        } else {
2048            let manifests = current
2049                .manifests()
2050                .map(|(_, manifest)| manifest.clone())
2051                .chain(std::iter::once(prepared.bridge.clone()))
2052                .collect::<Vec<_>>();
2053            type_bridge_schema_migration::MigrationHistoryGraph::from_verified(manifests)
2054                .map_err(display)?
2055        };
2056        type_bridge_schema_migration::require_adoption_authority_pair(&prospective, true)
2057            .map_err(display)?;
2058        evidence.require_unchanged(directory).map_err(display)?;
2059        prepared
2060            .history
2061            .require_unchanged_head(&prepared.reconstructed)
2062            .map_err(|error| {
2063                format!("archive adoption history changed before pair publication: {error}")
2064            })?;
2065
2066        if !bridge_already_published {
2067            bridge_created =
2068                publish_authority(directory, &prepared.bridge_name, &prepared.bridge_bytes)?;
2069        }
2070        if let Some(after_bridge) = after_bridge.take() {
2071            after_bridge();
2072        }
2073        prepared
2074            .history
2075            .require_unchanged_head(&prepared.reconstructed)
2076            .map_err(|error| {
2077                format!("archive adoption history changed before genesis publication: {error}")
2078            })?;
2079        genesis_created = publish_authority(directory, genesis_name, genesis_bytes)?;
2080        prepared
2081            .history
2082            .require_unchanged_head(&prepared.reconstructed)
2083            .map_err(|error| {
2084                format!("archive adoption history changed after pair publication: {error}")
2085            })?;
2086        workspace
2087            .discover_migrations_in(migration_directory)
2088            .map_err(display)?;
2089        Ok(())
2090    })();
2091
2092    if let Err(error) = publication {
2093        return Err(rollback_adoption_publication(
2094            directory,
2095            &prepared.bridge_name,
2096            bridge_created,
2097            genesis_created,
2098            error,
2099        ));
2100    }
2101    Ok(migration_directory
2102        .display_path()
2103        .join(&prepared.bridge_name))
2104}
2105
2106fn rollback_adoption_publication(
2107    directory: &type_bridge_schema_migration::MigrationDirectory,
2108    bridge_name: &str,
2109    bridge_created: bool,
2110    genesis_created: bool,
2111    primary: String,
2112) -> String {
2113    let mut cleanup_errors = Vec::new();
2114    if genesis_created
2115        && let Err(error) =
2116            directory.remove_file(type_bridge_schema_compat::ADOPTED_GENESIS_FILE_NAME.as_ref())
2117    {
2118        cleanup_errors.push(format!("cannot remove newly published genesis: {error}"));
2119    }
2120    if bridge_created && let Err(error) = directory.remove_file(bridge_name.as_ref()) {
2121        cleanup_errors.push(format!("cannot remove newly published bridge: {error}"));
2122    }
2123    if (bridge_created || genesis_created)
2124        && let Err(error) = directory.sync_all()
2125    {
2126        cleanup_errors.push(format!("cannot flush adoption rollback: {error}"));
2127    }
2128    if cleanup_errors.is_empty() {
2129        primary
2130    } else {
2131        format!(
2132            "{primary}; adoption publication rollback failed: {}",
2133            cleanup_errors.join("; ")
2134        )
2135    }
2136}
2137
2138/// Publish immutable authority from a unique, flushed same-directory temp.
2139///
2140/// Hard-link publication is atomic and no-replace. An existing final name is
2141/// accepted only when its bounded bytes are identical, allowing a retry to
2142/// recover after publication succeeded but the caller did not observe it. In
2143/// particular, a directory-sync error may be reported after the final link is
2144/// already durable; that exact orphan is intentionally left for the same
2145/// adoption command to recognize and complete on retry.
2146fn publish_authority(
2147    directory: &type_bridge_schema_migration::MigrationDirectory,
2148    name: &str,
2149    bytes: &[u8],
2150) -> Result<bool, String> {
2151    use std::io::Write;
2152    if let Some(existing) = read_existing_authority(directory, name)? {
2153        if existing == bytes {
2154            return Ok(false);
2155        }
2156        return Err(format!(
2157            "{name} already exists with different authority bytes"
2158        ));
2159    }
2160    let mut temporary = None;
2161    for attempt in 0..128_u64 {
2162        let candidate = unique_authority_temporary_name(name, attempt);
2163        match directory.create_new(candidate.as_ref()) {
2164            Ok(mut file) => {
2165                if let Err(error) = file.write_all(bytes).and_then(|()| file.sync_all()) {
2166                    let _ = directory.remove_file(candidate.as_ref());
2167                    return Err(format!("cannot write {candidate}: {error}"));
2168                }
2169                temporary = Some(candidate);
2170                break;
2171            }
2172            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
2173            Err(error) => {
2174                return Err(format!("cannot create {candidate}: {error}"));
2175            }
2176        }
2177    }
2178    let temporary = temporary.ok_or_else(|| {
2179        format!("cannot allocate a unique temporary authority file beside {name}")
2180    })?;
2181    let publication = directory.hard_link(temporary.as_ref(), name.as_ref());
2182    match publication {
2183        Ok(()) => {
2184            if let Err(error) = directory.sync_all() {
2185                let _ = directory.remove_file(temporary.as_ref());
2186                return Err(format!("cannot flush migration directory: {error}"));
2187            }
2188            let _ = directory.remove_file(temporary.as_ref());
2189            directory
2190                .sync_all()
2191                .map_err(|error| format!("cannot flush migration directory: {error}"))?;
2192            Ok(true)
2193        }
2194        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
2195            let _ = directory.remove_file(temporary.as_ref());
2196            let existing = read_existing_authority(directory, name)?
2197                .ok_or_else(|| format!("{name} disappeared during no-replace publication"))?;
2198            if existing == bytes {
2199                Ok(false)
2200            } else {
2201                Err(format!(
2202                    "{name} was concurrently published with different authority bytes"
2203                ))
2204            }
2205        }
2206        Err(error) => {
2207            let _ = directory.remove_file(temporary.as_ref());
2208            Err(format!("cannot publish {name}: {error}"))
2209        }
2210    }
2211}
2212
2213fn read_existing_authority(
2214    directory: &type_bridge_schema_migration::MigrationDirectory,
2215    name: &str,
2216) -> Result<Option<Vec<u8>>, String> {
2217    use std::io::Read;
2218    let file = match directory.open_regular_readonly(name.as_ref()) {
2219        Ok(file) => file,
2220        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
2221        Err(error) => return Err(format!("cannot read {name}: {error}")),
2222    };
2223    let limit = type_bridge_contract::limits::MAX_CANONICAL_BYTES;
2224    let mut bytes = Vec::new();
2225    file.take(u64::try_from(limit).unwrap_or(u64::MAX).saturating_add(1))
2226        .read_to_end(&mut bytes)
2227        .map_err(|error| format!("cannot read {name}: {error}"))?;
2228    if bytes.len() > limit {
2229        return Err(format!("{name} exceeds the 16 MiB authority ceiling"));
2230    }
2231    Ok(Some(bytes))
2232}
2233
2234fn unique_authority_temporary_name(name: &str, attempt: u64) -> String {
2235    use std::sync::atomic::{AtomicU64, Ordering};
2236    static NEXT_AUTHORITY_TEMPORARY: AtomicU64 = AtomicU64::new(1);
2237    let nonce = NEXT_AUTHORITY_TEMPORARY.fetch_add(1, Ordering::Relaxed);
2238    format!(".{name}.{}.{}.{}.tmp", std::process::id(), nonce, attempt)
2239}
2240
2241fn resolve_credential(
2242    reference: &type_bridge_workspace::SecretReference,
2243) -> Result<String, String> {
2244    std::env::var(reference.environment_variable()).map_err(|_| {
2245        format!(
2246            "credential environment variable {:?} is not set",
2247            reference.environment_variable()
2248        )
2249    })
2250}
2251
2252#[cfg(test)]
2253mod credential_error_redaction_tests {
2254    use super::*;
2255    use type_bridge_contract::diagnostic::{Diagnostic, DiagnosticCategory, DiagnosticCode};
2256    use type_bridge_typedb_runtime::RuntimeError;
2257
2258    const PROVIDER_TEXT: &str =
2259        "TB_ADDRESS_SECRET TB_USERNAME_SECRET TB_PASSWORD_SECRET TB_PROVIDER_SECRET";
2260    const SECRETS: [&str; 4] = [
2261        "TB_ADDRESS_SECRET",
2262        "TB_USERNAME_SECRET",
2263        "TB_PASSWORD_SECRET",
2264        "TB_PROVIDER_SECRET",
2265    ];
2266
2267    fn hostile_secure_error() -> type_bridge_orm::SecureConnectError {
2268        type_bridge_orm::SecureConnectError::Runtime(RuntimeError::Connection(
2269            PROVIDER_TEXT.to_owned(),
2270        ))
2271    }
2272
2273    #[test]
2274    fn connected_lifecycle_contexts_drop_hostile_provider_text() {
2275        for (context, code) in [
2276            (
2277                "cannot check database \"managed\"",
2278                "typedb_database_exists_failed",
2279            ),
2280            (
2281                "cannot ensure database \"managed\"",
2282                "typedb_database_ensure_failed",
2283            ),
2284            (
2285                "cannot connect the managed database",
2286                "typedb_database_connect_failed",
2287            ),
2288        ] {
2289            let sanitized =
2290                sanitize_connected_error(context.to_owned(), code, hostile_secure_error());
2291            let rendered = format!("{sanitized}\n{sanitized:?}");
2292            for secret in SECRETS {
2293                assert!(!rendered.contains(secret), "{secret}: {rendered}");
2294            }
2295            assert!(rendered.contains(context), "{rendered}");
2296            assert!(rendered.contains(code), "{rendered}");
2297        }
2298    }
2299
2300    #[test]
2301    fn connected_orm_lifecycle_contexts_drop_hostile_provider_text() {
2302        for (context, code) in [
2303            (
2304                "cannot check database \"managed\"",
2305                "typedb_database_exists_failed",
2306            ),
2307            (
2308                "cannot ensure database \"managed\"",
2309                "typedb_database_ensure_failed",
2310            ),
2311        ] {
2312            let sanitized = sanitize_connected_orm_error(
2313                context.to_owned(),
2314                code,
2315                type_bridge_orm::OrmError::Connection(PROVIDER_TEXT.to_owned()),
2316            );
2317            let rendered = format!("{sanitized}\n{sanitized:?}");
2318            for secret in SECRETS {
2319                assert!(!rendered.contains(secret), "{secret}: {rendered}");
2320            }
2321            assert!(rendered.contains(context), "{rendered}");
2322            assert!(rendered.contains(code), "{rendered}");
2323        }
2324    }
2325
2326    #[test]
2327    fn connected_lifecycle_preserves_only_typed_safe_diagnostics() {
2328        let sanitized = sanitize_connected_error(
2329            "cannot connect the managed database".to_owned(),
2330            "typedb_database_connect_failed",
2331            type_bridge_orm::SecureConnectError::DriverTlsConfiguration { band: 9 },
2332        );
2333        assert!(
2334            sanitized.contains("tls_driver_lowering_failed"),
2335            "{sanitized}"
2336        );
2337        assert!(sanitized.contains("driver band 9"), "{sanitized}");
2338        assert!(
2339            !sanitized.contains("typedb_database_connect_failed"),
2340            "{sanitized}"
2341        );
2342    }
2343
2344    #[test]
2345    fn schema_export_drops_hostile_orm_text_and_source() {
2346        let sanitized = sanitize_schema_export_error(type_bridge_orm::OrmError::Connection(
2347            PROVIDER_TEXT.into(),
2348        ));
2349        let rendered = format!("{sanitized}\n{sanitized:?}");
2350        for secret in SECRETS {
2351            assert!(!rendered.contains(secret), "{secret}: {rendered}");
2352        }
2353        assert!(
2354            rendered.contains("typedb_schema_export_failed"),
2355            "{rendered}"
2356        );
2357    }
2358
2359    #[test]
2360    fn migration_runner_display_omits_provider_details() {
2361        let diagnostic = Diagnostic::new(
2362            DiagnosticCategory::InvalidContract,
2363            DiagnosticCode::new("migration_provider_test_failed").expect("static code"),
2364            "migration provider operation failed",
2365        )
2366        .with_detail("provider", PROVIDER_TEXT);
2367        let error = type_bridge_schema_migration_typedb::MigrationDirectoryApplyError::Diagnostic(
2368            diagnostic,
2369        );
2370
2371        let rendered = display(error);
2372        for secret in SECRETS {
2373            assert!(!rendered.contains(secret), "{secret}: {rendered}");
2374        }
2375        assert!(
2376            rendered.contains("migration_provider_test_failed"),
2377            "{rendered}"
2378        );
2379    }
2380
2381    #[test]
2382    fn migration_outcome_projection_omits_provider_details_for_apply_and_adopt() {
2383        use type_bridge_contract::migration::MigrationId;
2384        use type_bridge_schema_migration::{MigrationExecutionOutcome, MigrationExecutionPosition};
2385
2386        let diagnostic = || {
2387            Diagnostic::new(
2388                DiagnosticCategory::InvalidContract,
2389                DiagnosticCode::new("migration_provider_test_failed").expect("static code"),
2390                "migration provider operation failed",
2391            )
2392            .with_detail("provider", PROVIDER_TEXT)
2393        };
2394        for context in [
2395            "apply did not complete",
2396            "adoption checkpoint did not complete",
2397        ] {
2398            for (outcome, expected_state, expected_position) in [
2399                (
2400                    MigrationExecutionOutcome::RetrySafe {
2401                        migration_id: MigrationId::new("example", "0001_initial")
2402                            .expect("migration id"),
2403                        position: MigrationExecutionPosition::TransactionGroup(7),
2404                        diagnostic: diagnostic(),
2405                    },
2406                    "retry-safe",
2407                    "transaction group 7",
2408                ),
2409                (
2410                    MigrationExecutionOutcome::RequiresExplicitRecovery {
2411                        migration_id: MigrationId::new("example", "0001_initial")
2412                            .expect("migration id"),
2413                        position: MigrationExecutionPosition::ManifestCheckpoint,
2414                        diagnostic: diagnostic(),
2415                    },
2416                    "explicit recovery required",
2417                    "manifest checkpoint",
2418                ),
2419            ] {
2420                let rendered = sanitize_migration_execution_outcome(context, outcome);
2421                for secret in SECRETS {
2422                    assert!(!rendered.contains(secret), "{secret}: {rendered}");
2423                }
2424                for expected in [
2425                    context,
2426                    expected_state,
2427                    "example/0001_initial",
2428                    expected_position,
2429                    "migration_provider_test_failed",
2430                    "migration provider operation failed",
2431                ] {
2432                    assert!(rendered.contains(expected), "{expected}: {rendered}");
2433                }
2434            }
2435        }
2436    }
2437}
2438
2439#[cfg(all(test, unix))]
2440mod output_authority_tests {
2441    use super::*;
2442    use std::os::unix::fs::symlink;
2443
2444    #[test]
2445    fn retained_output_authority_survives_component_swap_without_redirecting() {
2446        let workspace = tempfile::tempdir().expect("workspace directory");
2447        let outside = tempfile::tempdir().expect("outside directory");
2448        fs::create_dir_all(workspace.path().join("generated/python")).expect("output directory");
2449        let authority = WorkspaceDirectoryAuthority::open(
2450            WorkspaceRoot::new(fs::canonicalize(workspace.path()).expect("canonical workspace"))
2451                .expect("workspace root"),
2452        )
2453        .expect("workspace authority");
2454        let root = authority.output_root().expect("output authority");
2455        let output = root
2456            .open_beneath(Path::new("generated/python"))
2457            .expect("output authority");
2458
2459        let held = workspace.path().join("generated/python-held");
2460        fs::rename(workspace.path().join("generated/python"), &held)
2461            .expect("move retained output directory");
2462        symlink(outside.path(), workspace.path().join("generated/python"))
2463            .expect("redirect configured output path");
2464
2465        output
2466            .write_atomic("_models.py".as_ref(), b"retained authority")
2467            .expect("publication remains handle-relative");
2468        assert_eq!(
2469            fs::read(held.join("_models.py")).expect("retained output reads"),
2470            b"retained authority"
2471        );
2472        assert!(
2473            !outside.path().join("_models.py").exists(),
2474            "component replacement redirected output outside the workspace"
2475        );
2476    }
2477
2478    #[test]
2479    fn retained_output_root_survives_root_entry_swap_without_redirecting() {
2480        let workspace = tempfile::tempdir().expect("workspace directory");
2481        let outside = tempfile::tempdir().expect("outside directory");
2482        fs::create_dir_all(workspace.path().join("generated/python")).expect("output directory");
2483        let authority = WorkspaceDirectoryAuthority::open(
2484            WorkspaceRoot::new(fs::canonicalize(workspace.path()).expect("canonical workspace"))
2485                .expect("workspace root"),
2486        )
2487        .expect("workspace authority");
2488        let root = authority.output_root().expect("output authority");
2489        let held = workspace
2490            .path()
2491            .parent()
2492            .expect("temporary parent")
2493            .join(format!(
2494                "{}-retained",
2495                workspace
2496                    .path()
2497                    .file_name()
2498                    .expect("temporary name")
2499                    .to_string_lossy()
2500            ));
2501        fs::rename(workspace.path(), &held).expect("workspace root moves after validation");
2502        symlink(outside.path(), workspace.path()).expect("workspace name redirects outside");
2503
2504        let output = root
2505            .open_beneath(Path::new("generated/python"))
2506            .expect("output opens through retained root");
2507        output
2508            .write_atomic("_models.py".as_ref(), b"retained root authority")
2509            .expect("publication remains rooted in the retained handle");
2510        assert_eq!(
2511            fs::read(held.join("generated/python/_models.py")).expect("retained output reads"),
2512            b"retained root authority"
2513        );
2514        assert!(
2515            !outside.path().join("generated/python/_models.py").exists(),
2516            "root replacement redirected output outside the workspace"
2517        );
2518
2519        fs::remove_file(workspace.path()).expect("replacement symlink removes");
2520        fs::rename(&held, workspace.path()).expect("workspace restores for cleanup");
2521    }
2522}
2523
2524fn bind_approvals(
2525    graph: &type_bridge_schema_migration::MigrationHistoryGraph,
2526    approvals: &[String],
2527) -> Result<Vec<type_bridge_schema_migration::MigrationApplyApproval>, String> {
2528    if approvals.is_empty() {
2529        return Ok(Vec::new());
2530    }
2531    approvals
2532        .iter()
2533        .map(|compound| {
2534            let (app_label, name) = compound
2535                .split_once('/')
2536                .ok_or_else(|| format!("approval {compound:?} must be app-label/name"))?;
2537            let id = type_bridge_contract::migration::MigrationId::from_components(
2538                type_bridge_contract::migration::MigrationAppLabel::new(app_label.to_owned())
2539                    .map_err(display)?,
2540                type_bridge_contract::migration::MigrationName::new(name.to_owned())
2541                    .map_err(display)?,
2542            );
2543            let manifest = graph.manifest(&id).ok_or_else(|| {
2544                format!("approval target {compound:?} is not in the committed history")
2545            })?;
2546            type_bridge_schema_migration::MigrationApplyApproval::for_manifest(manifest)
2547                .map_err(display)
2548        })
2549        .collect()
2550}
2551
2552fn parse_migration_ids(
2553    graph: &type_bridge_schema_migration::MigrationHistoryGraph,
2554    values: &[String],
2555    kind: &str,
2556) -> Result<BTreeSet<type_bridge_contract::migration::MigrationId>, String> {
2557    let mut ids = BTreeSet::new();
2558    for compound in values {
2559        let (app_label, name) = compound
2560            .split_once('/')
2561            .ok_or_else(|| format!("{kind} {compound:?} must be app-label/name"))?;
2562        let id = type_bridge_contract::migration::MigrationId::from_components(
2563            type_bridge_contract::migration::MigrationAppLabel::new(app_label.to_owned())
2564                .map_err(display)?,
2565            type_bridge_contract::migration::MigrationName::new(name.to_owned())
2566                .map_err(display)?,
2567        );
2568        if graph.manifest(&id).is_none() {
2569            return Err(format!(
2570                "{kind} target {compound:?} is not in the committed history"
2571            ));
2572        }
2573        if !ids.insert(id) {
2574            return Err(format!("{kind} target {compound:?} is duplicated"));
2575        }
2576    }
2577    Ok(ids)
2578}
2579
2580fn bind_rollback_approvals(
2581    graph: &type_bridge_schema_migration::MigrationHistoryGraph,
2582    approvals: &[String],
2583) -> Result<Vec<type_bridge_schema_migration::MigrationApplyApproval>, String> {
2584    let ids = parse_migration_ids(graph, approvals, "rollback approval")?;
2585    let mut bound = Vec::new();
2586    for id in ids {
2587        let manifest = graph
2588            .manifest(&id)
2589            .ok_or_else(|| "internal rollback approval target disappeared".to_owned())?;
2590        for safety in [
2591            type_bridge_schema::SafetyClass::FormalOnly,
2592            type_bridge_schema::SafetyClass::SchemaMetadata,
2593            type_bridge_schema::SafetyClass::Additive,
2594            type_bridge_schema::SafetyClass::Conditional,
2595            type_bridge_schema::SafetyClass::Destructive,
2596            type_bridge_schema::SafetyClass::Opaque,
2597        ] {
2598            bound.push(
2599                type_bridge_schema_migration::MigrationApplyApproval::for_rollback(
2600                    manifest, safety,
2601                )
2602                .map_err(display)?,
2603            );
2604        }
2605    }
2606    Ok(bound)
2607}
2608
2609#[cfg(test)]
2610mod transport_option_tests {
2611    use super::*;
2612
2613    fn environment(policy: WorkspaceTransportPolicy) -> WorkspaceEnvironment {
2614        WorkspaceEnvironment::new(
2615            "typedb.example:1729",
2616            "example",
2617            SecretReference::environment("TYPEBRIDGE_TEST_USERNAME").expect("username reference"),
2618            SecretReference::environment("TYPEBRIDGE_TEST_PASSWORD").expect("password reference"),
2619        )
2620        .expect("environment")
2621        .with_transport_policy(policy)
2622    }
2623
2624    fn custom_root_workspace(root_bytes: &[u8]) -> (tempfile::TempDir, TypeBridgeWorkspace) {
2625        let directory = tempfile::tempdir().expect("workspace directory");
2626        fs::create_dir_all(directory.path().join("schema/fragments")).expect("schema directory");
2627        fs::create_dir_all(directory.path().join("migrations/v2")).expect("migration directory");
2628        fs::create_dir_all(directory.path().join("certs")).expect("certificate directory");
2629        fs::write(
2630            directory.path().join("schema/schema.yaml"),
2631            "format: typebridge.schema-set/v1\nsources: [fragments/*.yaml]\n",
2632        )
2633        .expect("schema set writes");
2634        fs::write(
2635            directory.path().join("schema/fragments/model.yaml"),
2636            "format: typebridge.schema/v2\nentities: {person: {}}\n",
2637        )
2638        .expect("schema writes");
2639        fs::write(directory.path().join("certs/root.pem"), root_bytes).expect("certificate writes");
2640        let manifest = directory.path().join("typebridge.yaml");
2641        fs::write(
2642            &manifest,
2643            "format: typebridge.workspace/v1\n\
2644             schema:\n  root: schema/schema.yaml\n  ownership: exclusive\n  managed-scope: tls-test\n\
2645             compatibility:\n  semantic-profile: typedb-3.12.1/v1\n\
2646             migrations:\n  directory: migrations/v2\n  app-label: tlstest\n\
2647             environments:\n  dev:\n    database: tls_test\n    uri: never-contact.invalid:1729\n    \
2648             tls: 'true'\n    tls-root-ca: certs/root.pem\n    credential:\n      username: \
2649             env:TYPEBRIDGE_TEST_USERNAME\n      password: env:TYPEBRIDGE_TEST_PASSWORD\n",
2650        )
2651        .expect("manifest writes");
2652        let workspace = load_workspace(&manifest).expect("custom-root workspace loads");
2653        (directory, workspace)
2654    }
2655
2656    #[test]
2657    fn workspace_transport_policy_maps_without_changing_plaintext_defaults() {
2658        let defaults = type_bridge_orm::SecureConnectOptions::default();
2659        let disabled = secure_connect_options(&environment(WorkspaceTransportPolicy::Disabled));
2660        assert_eq!(disabled.tls_mode, type_bridge_orm::TlsMode::Disabled);
2661        assert_eq!(disabled.http_port, defaults.http_port);
2662        assert_eq!(disabled.server_version, defaults.server_version);
2663
2664        let native = secure_connect_options(
2665            &environment(WorkspaceTransportPolicy::NativeRoots).with_http_port(9443),
2666        );
2667        assert_eq!(native.tls_mode, type_bridge_orm::TlsMode::NativeRoots);
2668        assert_eq!(native.http_port, 9443);
2669        assert_eq!(native.server_version, defaults.server_version);
2670    }
2671
2672    #[test]
2673    fn custom_root_mapping_preserves_the_validated_canonical_path() {
2674        let directory = tempfile::tempdir().expect("workspace directory");
2675        let canonical = fs::canonicalize(directory.path()).expect("canonical workspace");
2676        fs::create_dir_all(canonical.join("certs")).expect("certificate directory");
2677        fs::write(
2678            canonical.join("certs/root.pem"),
2679            b"not parsed at workspace boundary\n",
2680        )
2681        .expect("certificate writes");
2682        let root = WorkspaceRoot::new(canonical.clone()).expect("workspace root");
2683        let root_ca = type_bridge_workspace::WorkspaceRootCa::new(
2684            &root,
2685            "certs/root.pem",
2686            &SystemSchemaSourceService,
2687        )
2688        .expect("confined root CA");
2689
2690        let options = secure_connect_options(
2691            &environment(WorkspaceTransportPolicy::CustomRootCa(root_ca)).with_http_port(8443),
2692        );
2693        assert_eq!(
2694            options.tls_mode,
2695            type_bridge_orm::TlsMode::CustomRootCa(canonical.join("certs/root.pem"))
2696        );
2697        assert_eq!(options.http_port, 8443);
2698    }
2699
2700    #[test]
2701    fn malformed_custom_root_fails_transport_preflight_before_credentials_are_needed() {
2702        let (_directory, workspace) = custom_root_workspace(b"definitely not a certificate\n");
2703
2704        let error = preflight_secure_connect_options(&workspace, "dev")
2705            .expect_err("PEM parsing must happen before credential resolution");
2706        assert!(error.contains("tls_custom_root_ca_invalid_pem"), "{error}");
2707        assert!(!error.contains("TYPEBRIDGE_TEST_USERNAME"), "{error}");
2708        assert!(!error.contains("TYPEBRIDGE_TEST_PASSWORD"), "{error}");
2709    }
2710
2711    #[cfg(unix)]
2712    #[test]
2713    fn workspace_root_swap_to_outside_symlink_is_rejected_at_transport_preflight() {
2714        use std::os::unix::fs::symlink;
2715
2716        let (directory, workspace) = custom_root_workspace(b"initial regular root\n");
2717        let outside = tempfile::tempdir().expect("outside directory");
2718        let configured = directory.path().join("certs/root.pem");
2719
2720        let outside_root = outside.path().join("malicious.pem");
2721        fs::write(
2722            &outside_root,
2723            include_bytes!("../../core/tests/fixtures/valid-root.pem"),
2724        )
2725        .expect("write outside replacement root");
2726        fs::remove_file(&configured).expect("remove validated confined root");
2727        symlink(&outside_root, &configured).expect("install outside symlink after validation");
2728
2729        let error = preflight_secure_connect_options(&workspace, "dev")
2730            .expect_err("retained workspace paths must never follow a replacement symlink");
2731        assert!(error.contains("tls_custom_root_ca_unreadable"), "{error}");
2732        assert!(!error.contains("tls_custom_root_ca_invalid_pem"), "{error}");
2733    }
2734
2735    #[cfg(unix)]
2736    #[test]
2737    fn real_directory_root_replacement_cannot_substitute_custom_trust() {
2738        let (directory, workspace) =
2739            custom_root_workspace(include_bytes!("../../core/tests/fixtures/valid-root.pem"));
2740        let configured_root = directory.path().to_path_buf();
2741        let held_root = configured_root.with_extension("retained-custom-root-ca");
2742        fs::rename(&configured_root, &held_root).expect("move retained workspace root");
2743        fs::create_dir_all(configured_root.join("certs")).expect("replacement root creates");
2744        fs::write(
2745            configured_root.join("certs/root.pem"),
2746            b"attacker-controlled replacement is not a certificate\n",
2747        )
2748        .expect("replacement root writes");
2749
2750        let preflight = preflight_secure_connect_options(&workspace, "dev");
2751
2752        fs::remove_dir_all(&configured_root).expect("replacement root removes");
2753        fs::rename(&held_root, &configured_root).expect("retained root restores");
2754        preflight.expect("transport must use the CA under the retained original root");
2755    }
2756}
2757
2758#[cfg(test)]
2759mod rollback_cli_contract_tests {
2760    use super::*;
2761
2762    #[test]
2763    fn rollback_grammar_requires_environment_and_explicit_removal() {
2764        assert!(Cli::try_parse_from(["type-bridge", "migration", "rollback"]).is_err());
2765        assert!(
2766            Cli::try_parse_from([
2767                "type-bridge",
2768                "migration",
2769                "rollback",
2770                "--environment",
2771                "live",
2772            ])
2773            .is_err()
2774        );
2775        let cli = Cli::try_parse_from([
2776            "type-bridge",
2777            "migration",
2778            "rollback",
2779            "--environment",
2780            "live",
2781            "--remove",
2782            "example/0002_contract",
2783            "--remove",
2784            "example/0001_expand",
2785            "--approve",
2786            "example/0002_contract",
2787            "--output",
2788            "json",
2789        ])
2790        .expect("explicit preview grammar parses");
2791        let Command::Migration {
2792            command:
2793                MigrationCommand::Rollback {
2794                    environment,
2795                    removals,
2796                    approvals,
2797                    execute,
2798                    output,
2799                },
2800        } = cli.command
2801        else {
2802            panic!("rollback command parsed into another command")
2803        };
2804        assert_eq!(environment, "live");
2805        assert_eq!(removals.len(), 2);
2806        assert_eq!(approvals, ["example/0002_contract"]);
2807        assert!(!execute, "preview is the non-mutating default");
2808        assert_eq!(output, RollbackOutput::Json);
2809    }
2810
2811    #[test]
2812    fn rollback_execution_requires_an_explicit_flag() {
2813        let cli = Cli::try_parse_from([
2814            "type-bridge",
2815            "migration",
2816            "rollback",
2817            "--environment",
2818            "live",
2819            "--remove",
2820            "example/0002_contract",
2821            "--execute",
2822        ])
2823        .expect("explicit execution grammar parses");
2824        assert!(matches!(
2825            cli.command,
2826            Command::Migration {
2827                command: MigrationCommand::Rollback { execute: true, .. }
2828            }
2829        ));
2830    }
2831}
2832
2833#[cfg(test)]
2834mod migration_command_tests {
2835    use super::*;
2836
2837    fn write_workspace_manifest(root: &Path, semantic_profile: &str) -> PathBuf {
2838        fs::create_dir_all(root.join("schema/fragments")).expect("schema directory");
2839        fs::write(
2840            root.join("schema/schema.yaml"),
2841            "format: typebridge.schema-set/v1\nsources: [fragments/*.yaml]\n",
2842        )
2843        .expect("schema set writes");
2844        fs::write(
2845            root.join("schema/fragments/model.yaml"),
2846            "format: typebridge.schema/v2\nentities: {person: {}}\n",
2847        )
2848        .expect("schema writes");
2849        let manifest = root.join("typebridge.yaml");
2850        fs::write(
2851            &manifest,
2852            format!(
2853                "format: typebridge.workspace/v1\n\
2854                 schema:\n  root: schema/schema.yaml\n  ownership: exclusive\n  managed-scope: command-test\n\
2855                 compatibility:\n  semantic-profile: {semantic_profile}\n\
2856                 migrations:\n  directory: migrations/v2\n  app-label: commandtest\n\
2857                 environments:\n  dev:\n    database: command_test\n    uri: never-contact.invalid:1729\n    migrate: 'true'\n    credential:\n      username: env:TYPEBRIDGE_COMMAND_TEST_USERNAME\n      password: env:TYPEBRIDGE_COMMAND_TEST_PASSWORD\n"
2858            ),
2859        )
2860        .expect("manifest writes");
2861        manifest
2862    }
2863
2864    #[test]
2865    fn migration_make_creates_its_missing_authoring_directory() {
2866        let directory = tempfile::tempdir().expect("workspace directory");
2867        let manifest = write_workspace_manifest(directory.path(), "typedb-3.11.5/v1");
2868        let migration_directory = directory.path().join("migrations/v2");
2869        assert!(!migration_directory.exists());
2870
2871        run(&Cli {
2872            manifest,
2873            command: Command::Migration {
2874                command: MigrationCommand::Make {
2875                    name: "initial".to_owned(),
2876                    backfill_intent: None,
2877                },
2878            },
2879        })
2880        .expect("migration make creates and publishes into its authoring directory");
2881
2882        assert!(
2883            migration_directory
2884                .join("0001_initial.tbmigration.json")
2885                .is_file()
2886        );
2887        assert!(migration_directory.join("0001_initial.typeql").is_file());
2888    }
2889
2890    #[test]
2891    fn migration_make_accepts_a_confined_backfill_intent() {
2892        let directory = tempfile::tempdir().expect("workspace directory");
2893        let manifest = write_workspace_manifest(directory.path(), "typedb-3.11.5/v1");
2894        fs::write(
2895            directory.path().join("schema/fragments/model.yaml"),
2896            "format: typebridge.schema/v2\nattributes:\n  display-name: { value: string }\n  legacy-name: { value: string }\n  person-id: { value: string }\nentities:\n  person:\n    owns:\n      display-name: {}\n      legacy-name: {}\n      person-id: { key: true }\n",
2897        )
2898        .expect("backfill schema writes");
2899        let initial = Cli {
2900            manifest: manifest.clone(),
2901            command: Command::Migration {
2902                command: MigrationCommand::Make {
2903                    name: "initial".to_owned(),
2904                    backfill_intent: None,
2905                },
2906            },
2907        };
2908        run(&initial).expect("initial migration");
2909        fs::write(
2910            directory.path().join("migrations/v2/copy-name.backfill.yaml"),
2911            "format: typebridge.migration-backfill-intent/v1\ncopy-attribute:\n  owner-kind: entity\n  owner: person\n  source: legacy-name\n  destination: display-name\n  partition-key: person-id\n  batch-rows: 128\n  reverse: remove-equal-copied-destination\n",
2912        )
2913        .expect("backfill intent writes");
2914
2915        run(&Cli {
2916            manifest,
2917            command: Command::Migration {
2918                command: MigrationCommand::Make {
2919                    name: "copy-name".to_owned(),
2920                    backfill_intent: Some(PathBuf::from("copy-name.backfill.yaml")),
2921                },
2922            },
2923        })
2924        .expect("backfill migration authors");
2925
2926        assert!(
2927            directory
2928                .path()
2929                .join("migrations/v2/0002_copy-name.tbmigration.json")
2930                .is_file()
2931        );
2932    }
2933
2934    fn connected_actions(directory: &Path) -> [ConnectedAction; 3] {
2935        [
2936            ConnectedAction::Apply {
2937                approvals: Vec::new(),
2938            },
2939            ConnectedAction::Verify,
2940            ConnectedAction::Adopt {
2941                archive_directory: directory.join("missing-archive"),
2942                name: "0000_archive_frontier".to_owned(),
2943            },
2944        ]
2945    }
2946
2947    #[test]
2948    fn unsupported_execution_profile_rejects_before_credentials_or_filesystem_mutation() {
2949        // A workspace on a query-only profile (3.11.5) never reaches setup.
2950        let profile = "typedb-3.11.5/v1";
2951        let directory = tempfile::tempdir().expect("workspace directory");
2952        let manifest = write_workspace_manifest(directory.path(), profile);
2953        let workspace = load_workspace(&manifest).expect("workspace loads");
2954
2955        for action in connected_actions(directory.path()) {
2956            let error = run_connected(&workspace, "dev", action)
2957                .expect_err("every connected migration operation uses a paired profile");
2958
2959            assert!(
2960                error.contains("migration_typedb_semantic_profile_unsupported"),
2961                "{error}"
2962            );
2963            assert!(error.contains(profile), "{error}");
2964            assert!(error.contains("typedb-3.12.1/v1"), "{error}");
2965            assert!(error.contains("typedb-3.13.6/v1"), "{error}");
2966            assert!(
2967                !error.contains("credential environment variable")
2968                    && !error.contains("cannot connect")
2969                    && !error.contains("cannot check database"),
2970                "profile gate ran after external setup: {error}"
2971            );
2972        }
2973        assert!(
2974            !directory.path().join("migrations/v2").exists(),
2975            "profile rejection must not create the migration directory"
2976        );
2977    }
2978
2979    #[test]
2980    fn paired_execution_profiles_pass_the_profile_gate() {
2981        for profile in ["typedb-3.12.1/v1", "typedb-3.13.6/v1"] {
2982            let directory = tempfile::tempdir().expect("workspace directory");
2983            let manifest = write_workspace_manifest(directory.path(), profile);
2984            let workspace = load_workspace(&manifest).expect("workspace loads");
2985
2986            for action in connected_actions(directory.path()) {
2987                // The fixture has no migration directory or archive, so each
2988                // action stops at the directory step after the profile gate.
2989                let error = run_connected(&workspace, "dev", action)
2990                    .expect_err("the fixture cannot complete a connected operation");
2991                assert!(
2992                    !error.contains("migration_typedb_semantic_profile_unsupported"),
2993                    "{profile} must pass the profile gate: {error}"
2994                );
2995                assert!(error.contains("migration directory"), "{error}");
2996            }
2997        }
2998    }
2999
3000    const OLD_PROFILE: &str = "typedb-3.12.1/v1";
3001    const NEW_PROFILE: &str = "typedb-3.13.6/v1";
3002
3003    /// A workspace whose one-migration history was authored on `history`
3004    /// and whose manifest now names `workspace_profile`.
3005    fn profiled_history(
3006        history: &str,
3007        workspace_profile: &str,
3008    ) -> (tempfile::TempDir, PathBuf, TypeBridgeWorkspace) {
3009        let directory = tempfile::tempdir().expect("workspace directory");
3010        let manifest = write_workspace_manifest(directory.path(), history);
3011        run(&Cli {
3012            manifest: manifest.clone(),
3013            command: Command::Migration {
3014                command: MigrationCommand::Make {
3015                    name: "initial".to_owned(),
3016                    backfill_intent: None,
3017                },
3018            },
3019        })
3020        .expect("the history authors on its own profile");
3021        write_workspace_manifest(directory.path(), workspace_profile);
3022        let workspace = load_workspace(&manifest).expect("workspace loads");
3023        (directory, manifest, workspace)
3024    }
3025
3026    fn upgrade(to: &str, name: Option<&str>) -> ConnectedAction {
3027        ConnectedAction::UpgradeProfile {
3028            to: to.to_owned(),
3029            name: name.map(str::to_owned),
3030        }
3031    }
3032
3033    fn canonical_files(directory: &Path) -> Vec<String> {
3034        let mut names = fs::read_dir(directory.join("migrations/v2"))
3035            .expect("migration directory lists")
3036            .map(|entry| {
3037                entry
3038                    .expect("migration entry")
3039                    .file_name()
3040                    .to_string_lossy()
3041                    .into_owned()
3042            })
3043            .filter(|name| name.ends_with(".tbmigration.json"))
3044            .collect::<Vec<_>>();
3045        names.sort();
3046        names
3047    }
3048
3049    fn assert_before_credentials(error: &str) {
3050        assert!(
3051            !error.contains("credential environment variable") && !error.contains("cannot connect"),
3052            "the refusal ran after external setup: {error}"
3053        );
3054    }
3055
3056    #[test]
3057    fn upgrade_profile_grammar_requires_environment_and_target() {
3058        assert!(
3059            Cli::try_parse_from([
3060                "type-bridge",
3061                "migration",
3062                "upgrade-profile",
3063                "--to",
3064                NEW_PROFILE,
3065            ])
3066            .is_err()
3067        );
3068        assert!(
3069            Cli::try_parse_from([
3070                "type-bridge",
3071                "migration",
3072                "upgrade-profile",
3073                "--environment",
3074                "live",
3075            ])
3076            .is_err()
3077        );
3078        let cli = Cli::try_parse_from([
3079            "type-bridge",
3080            "migration",
3081            "upgrade-profile",
3082            "--environment",
3083            "live",
3084            "--to",
3085            NEW_PROFILE,
3086            "--name",
3087            "line-313",
3088        ])
3089        .expect("explicit upgrade grammar parses");
3090        let Command::Migration {
3091            command:
3092                MigrationCommand::UpgradeProfile {
3093                    environment,
3094                    to,
3095                    name,
3096                },
3097        } = cli.command
3098        else {
3099            panic!("upgrade-profile parsed into another command")
3100        };
3101        assert_eq!(environment, "live");
3102        assert_eq!(to, NEW_PROFILE);
3103        assert_eq!(name.as_deref(), Some("line-313"));
3104
3105        let help = <Cli as clap::CommandFactory>::command()
3106            .find_subcommand_mut("migration")
3107            .expect("migration command")
3108            .render_help()
3109            .to_string();
3110        assert!(help.contains("upgrade-profile"), "{help}");
3111    }
3112
3113    #[test]
3114    fn upgrade_profile_refuses_targets_before_credentials_or_writes() {
3115        let (directory, _, workspace) = profiled_history(OLD_PROFILE, NEW_PROFILE);
3116        let before = canonical_files(directory.path());
3117
3118        let unknown = run_connected(&workspace, "dev", upgrade("typedb-9.9.9/v1", None))
3119            .expect_err("an unknown target is refused");
3120        assert!(
3121            unknown.contains("migration_typedb_semantic_profile_unsupported"),
3122            "{unknown}"
3123        );
3124        assert_before_credentials(&unknown);
3125
3126        let stale = run_connected(&workspace, "dev", upgrade(OLD_PROFILE, None))
3127            .expect_err("a target other than the workspace profile is refused");
3128        assert!(
3129            stale.contains("migration_upgrade_profile_target_not_workspace_profile"),
3130            "{stale}"
3131        );
3132        assert!(
3133            stale.contains("hint: set `compatibility.semantic-profile: typedb-3.12.1/v1`"),
3134            "{stale}"
3135        );
3136        assert_before_credentials(&stale);
3137
3138        let (same_directory, _, same) = profiled_history(OLD_PROFILE, OLD_PROFILE);
3139        let error = run_connected(&same, "dev", upgrade(OLD_PROFILE, None))
3140            .expect_err("a history on the workspace profile is refused");
3141        assert!(
3142            error.contains("migration_upgrade_profile_same_profile"),
3143            "{error}"
3144        );
3145        assert_before_credentials(&error);
3146        assert_eq!(
3147            canonical_files(same_directory.path()),
3148            ["0001_initial.tbmigration.json"]
3149        );
3150
3151        let (down_directory, _, down) = profiled_history(NEW_PROFILE, OLD_PROFILE);
3152        let error = run_connected(&down, "dev", upgrade(OLD_PROFILE, None))
3153            .expect_err("a history on a newer profile is refused");
3154        assert!(
3155            error.contains("migration_upgrade_profile_downgrade"),
3156            "{error}"
3157        );
3158        assert_before_credentials(&error);
3159        assert_eq!(
3160            canonical_files(down_directory.path()),
3161            ["0001_initial.tbmigration.json"]
3162        );
3163
3164        assert_eq!(canonical_files(directory.path()), before);
3165    }
3166
3167    #[test]
3168    fn unbridged_older_history_names_upgrade_profile_in_its_refusal() {
3169        let (_directory, manifest, workspace) = profiled_history(OLD_PROFILE, NEW_PROFILE);
3170        let hint = "hint: run `migration upgrade-profile --to typedb-3.13.6/v1`";
3171
3172        let plan = run(&Cli {
3173            manifest,
3174            command: Command::Migration {
3175                command: MigrationCommand::Plan,
3176            },
3177        })
3178        .expect_err("plan refuses an unbridged older history");
3179        assert!(
3180            plan.contains("migration_history_profile_upgrade_required"),
3181            "{plan}"
3182        );
3183        assert!(plan.contains(hint), "{plan}");
3184
3185        for action in [
3186            ConnectedAction::Apply {
3187                approvals: Vec::new(),
3188            },
3189            ConnectedAction::Verify,
3190        ] {
3191            let error = run_connected(&workspace, "dev", action)
3192                .expect_err("connected commands refuse an unbridged older history");
3193            assert!(error.contains(hint), "{error}");
3194            assert_before_credentials(&error);
3195        }
3196    }
3197
3198    #[test]
3199    fn upgrade_profile_publishes_the_bridge_once_before_connecting() {
3200        let (directory, manifest, workspace) = profiled_history(OLD_PROFILE, NEW_PROFILE);
3201        let bridge = directory
3202            .path()
3203            .join("migrations/v2/0002_profile_upgrade_typedb_3_13_6.tbmigration.json");
3204
3205        let error = run_connected(&workspace, "dev", upgrade(NEW_PROFILE, None))
3206            .expect_err("the fixture has no credentials");
3207        assert!(error.contains("credential environment variable"), "{error}");
3208        let published = fs::read(&bridge).expect("the bridge is published before connecting");
3209
3210        // The bridged history is ordinary again; a retry reuses the bridge.
3211        let plan = workspace
3212            .migration_plan_in(
3213                &workspace
3214                    .open_migration_directory()
3215                    .expect("migration directory"),
3216                &BTreeSet::new(),
3217            )
3218            .expect("the bridged history plans under the new profile");
3219        assert_eq!(plan.len(), 2);
3220        assert!(!plan[1].reversible());
3221        let error = run_connected(&workspace, "dev", upgrade(NEW_PROFILE, Some("again")))
3222            .expect_err("the fixture has no credentials");
3223        assert!(error.contains("credential environment variable"), "{error}");
3224        assert_eq!(
3225            canonical_files(directory.path()),
3226            [
3227                "0001_initial.tbmigration.json",
3228                "0002_profile_upgrade_typedb_3_13_6.tbmigration.json",
3229            ]
3230        );
3231        assert_eq!(fs::read(&bridge).expect("bridge"), published);
3232
3233        // The next authored migration continues after the bridge.
3234        fs::write(
3235            directory.path().join("schema/fragments/model.yaml"),
3236            "format: typebridge.schema/v2\nentities: {person: {}, company: {}}\n",
3237        )
3238        .expect("schema evolves");
3239        run(&Cli {
3240            manifest,
3241            command: Command::Migration {
3242                command: MigrationCommand::Make {
3243                    name: "company".to_owned(),
3244                    backfill_intent: None,
3245                },
3246            },
3247        })
3248        .expect("make continues after the bridge");
3249        assert!(
3250            directory
3251                .path()
3252                .join("migrations/v2/0003_company.tbmigration.json")
3253                .is_file()
3254        );
3255    }
3256
3257    #[test]
3258    fn upgrade_profile_names_the_bridge_like_make() {
3259        let (directory, _, workspace) = profiled_history(OLD_PROFILE, NEW_PROFILE);
3260        let error = run_connected(&workspace, "dev", upgrade(NEW_PROFILE, Some("line-313")))
3261            .expect_err("the fixture has no credentials");
3262        assert!(error.contains("credential environment variable"), "{error}");
3263        assert_eq!(
3264            canonical_files(directory.path()),
3265            [
3266                "0001_initial.tbmigration.json",
3267                "0002_line-313.tbmigration.json",
3268            ]
3269        );
3270
3271        let (directory, _, workspace) = profiled_history(OLD_PROFILE, NEW_PROFILE);
3272        let error = run_connected(&workspace, "dev", upgrade(NEW_PROFILE, Some("Bad Name")))
3273            .expect_err("an invalid name is refused");
3274        assert!(
3275            !error.contains("credential environment variable"),
3276            "{error}"
3277        );
3278        assert_eq!(
3279            canonical_files(directory.path()),
3280            ["0001_initial.tbmigration.json"]
3281        );
3282    }
3283}
3284
3285#[cfg(test)]
3286mod adoption_file_tests {
3287    use super::*;
3288    use sha2::{Digest as _, Sha256};
3289
3290    const LEGACY_SCHEMA: &str = "define\nentity person;\n";
3291
3292    fn adoption_workspace() -> (tempfile::TempDir, TypeBridgeWorkspace) {
3293        let directory = tempfile::tempdir().expect("workspace directory");
3294        fs::create_dir_all(directory.path().join("schema/fragments")).expect("schema directory");
3295        fs::write(
3296            directory.path().join("schema/schema.yaml"),
3297            "format: typebridge.schema-set/v1\nsources: [fragments/*.yaml]\n",
3298        )
3299        .expect("schema set writes");
3300        fs::write(
3301            directory.path().join("schema/fragments/model.yaml"),
3302            "format: typebridge.schema/v2\nentities: {person: {}}\n",
3303        )
3304        .expect("schema writes");
3305        let manifest = directory.path().join("typebridge.yaml");
3306        fs::write(
3307            &manifest,
3308            "format: typebridge.workspace/v1\n\
3309             schema:\n  root: schema/schema.yaml\n  ownership: exclusive\n  managed-scope: adoption-test\n\
3310             compatibility:\n  semantic-profile: typedb-3.12.1/v1\n\
3311             migrations:\n  directory: migrations/v2\n  app-label: smoke\n\
3312             environments:\n  dev:\n    database: adoption_test\n    uri: never-contact.invalid:1729\n    migrate: 'true'\n    credential:\n      username: env:TYPEBRIDGE_TEST_USERNAME\n      password: env:TYPEBRIDGE_TEST_PASSWORD\n",
3313        )
3314        .expect("manifest writes");
3315        let workspace = load_workspace(&manifest).expect("workspace loads");
3316        (directory, workspace)
3317    }
3318
3319    fn write_legacy_fixture(root: &Path) -> PathBuf {
3320        let directory = root.join("migrations/legacy");
3321        fs::create_dir_all(&directory).expect("legacy directory");
3322        let name = "0001_initial";
3323        let python_source = "class Migration:\n    operations = []\n";
3324        let checksum = type_bridge_migration::migration_file_checksum(python_source);
3325        let source_sha256 = format!("{:x}", Sha256::digest(python_source.as_bytes()));
3326        let schema_hash = format!("{:x}", Sha256::digest(LEGACY_SCHEMA.as_bytes()));
3327        fs::write(directory.join(format!("{name}.py")), python_source)
3328            .expect("legacy source writes");
3329        let adoption = type_bridge_migration::LegacyAdoptionMetadata::new(
3330            "legacy",
3331            name,
3332            Vec::new(),
3333            checksum,
3334            source_sha256,
3335            type_bridge_migration::LegacySchemaEffect::Snapshot,
3336            type_bridge_migration::MigrationDependencySpec {
3337                app_label: "legacy".to_owned(),
3338                migration_name: name.to_owned(),
3339            },
3340            schema_hash.clone(),
3341        )
3342        .expect("legacy adoption metadata");
3343        fs::write(
3344            directory.join(format!("{name}.adoption.json")),
3345            serde_json::to_vec_pretty(&adoption).expect("metadata encodes"),
3346        )
3347        .expect("metadata writes");
3348        let snapshot = directory.join("snapshots/v0001");
3349        fs::create_dir_all(&snapshot).expect("snapshot directory");
3350        fs::write(snapshot.join("schema.tql"), LEGACY_SCHEMA).expect("snapshot schema writes");
3351        fs::write(
3352            snapshot.join("snapshot.json"),
3353            serde_json::to_vec_pretty(&serde_json::json!({
3354                "version": "v0001",
3355                "source_migration": name,
3356                "schema_hash": schema_hash,
3357                "file_hashes": {"schema.tql": schema_hash},
3358                "type_bridge_version": "1.5.11",
3359                "type_bridge_core_version": "1.5.11"
3360            }))
3361            .expect("snapshot manifest encodes"),
3362        )
3363        .expect("snapshot manifest writes");
3364        directory
3365    }
3366
3367    #[test]
3368    fn authority_publication_is_atomic_no_replace_and_resumable() {
3369        let directory = tempfile::tempdir().expect("directory");
3370        let authority =
3371            type_bridge_schema_migration::MigrationDirectory::open_ambient(directory.path())
3372                .expect("directory authority");
3373        let name = "adopted-genesis.typeql";
3374        let path = directory.path().join("adopted-genesis.typeql");
3375        assert!(
3376            publish_authority(&authority, name, b"define\nentity person;\n")
3377                .expect("first publish")
3378        );
3379        assert!(
3380            !publish_authority(&authority, name, b"define\nentity person;\n")
3381                .expect("identical recovery")
3382        );
3383        assert!(publish_authority(&authority, name, b"define\nentity company;\n").is_err());
3384        assert_eq!(
3385            fs::read(&path).expect("authority reads"),
3386            b"define\nentity person;\n"
3387        );
3388        assert!(
3389            fs::read_dir(directory.path())
3390                .expect("directory reads")
3391                .all(|entry| !entry
3392                    .expect("entry")
3393                    .file_name()
3394                    .to_string_lossy()
3395                    .ends_with(".tmp"))
3396        );
3397    }
3398
3399    #[cfg(unix)]
3400    #[test]
3401    fn authority_publication_rejects_final_symlink() {
3402        use std::os::unix::fs::symlink;
3403
3404        let directory = tempfile::tempdir().expect("directory");
3405        let outside = directory.path().join("outside");
3406        fs::write(&outside, b"untouched").expect("outside writes");
3407        let path = directory.path().join("adopted-genesis.typeql");
3408        symlink(&outside, &path).expect("symlink");
3409        let authority =
3410            type_bridge_schema_migration::MigrationDirectory::open_ambient(directory.path())
3411                .expect("directory authority");
3412
3413        assert!(publish_authority(&authority, "adopted-genesis.typeql", b"replacement").is_err());
3414        assert_eq!(fs::read(&outside).expect("outside reads"), b"untouched");
3415    }
3416
3417    #[test]
3418    fn invalid_adoption_name_creates_no_canonical_directory() {
3419        let (directory, workspace) = adoption_workspace();
3420        let missing_archive = directory.path().join("missing-legacy");
3421        let error = run_connected(
3422            &workspace,
3423            "dev",
3424            ConnectedAction::Adopt {
3425                archive_directory: missing_archive,
3426                name: String::new(),
3427            },
3428        )
3429        .expect_err("invalid name fails before history or network access");
3430        assert!(error.contains("migration"), "{error}");
3431        assert!(
3432            !directory.path().join("migrations/v2").exists(),
3433            "bad-name validation must not create canonical filesystem state"
3434        );
3435    }
3436
3437    #[test]
3438    fn invalid_apply_approvals_fail_before_credentials_or_network() {
3439        let (directory, workspace) = adoption_workspace();
3440        fs::create_dir_all(directory.path().join("migrations/v2")).expect("canonical directory");
3441
3442        for (approval, expected) in [
3443            ("not-a-compound-id", "must be app-label/name"),
3444            ("smoke/0001_missing", "is not in the committed history"),
3445        ] {
3446            let error = run_connected(
3447                &workspace,
3448                "dev",
3449                ConnectedAction::Apply {
3450                    approvals: vec![approval.to_owned()],
3451                },
3452            )
3453            .expect_err("invalid approval is rejected by local authority");
3454            assert!(error.contains(expected), "{approval}: {error}");
3455            assert!(
3456                !error.contains("credential")
3457                    && !error.contains("connect")
3458                    && !error.contains("database"),
3459                "approval validation ran after external setup: {error}"
3460            );
3461        }
3462    }
3463
3464    #[test]
3465    fn adoption_retry_completes_either_exact_orphan_direction() {
3466        for orphan in ["genesis", "bridge"] {
3467            let (directory, workspace) = adoption_workspace();
3468            let legacy = write_legacy_fixture(directory.path());
3469            let prepared = prepare_archive_adoption(&workspace, &legacy, "0000_archive_frontier")
3470                .expect("adoption prepares");
3471            let migration_directory = workspace
3472                .ensure_migration_directory()
3473                .expect("canonical directory");
3474            match orphan {
3475                "genesis" => {
3476                    publish_authority(
3477                        migration_directory.directory(),
3478                        type_bridge_schema_compat::ADOPTED_GENESIS_FILE_NAME,
3479                        prepared.reconstructed.schema_typeql().as_bytes(),
3480                    )
3481                    .expect("genesis orphan publishes");
3482                }
3483                "bridge" => {
3484                    publish_authority(
3485                        migration_directory.directory(),
3486                        &prepared.bridge_name,
3487                        &prepared.bridge_bytes,
3488                    )
3489                    .expect("bridge orphan publishes");
3490                }
3491                _ => unreachable!(),
3492            }
3493
3494            publish_prepared_adoption(&workspace, &migration_directory, &prepared)
3495                .expect("adoption retry completes the exact orphan");
3496            workspace
3497                .discover_migrations_in(&migration_directory)
3498                .expect("completed adoption pair discovers");
3499            assert!(
3500                migration_directory
3501                    .display_path()
3502                    .join(type_bridge_schema_compat::ADOPTED_GENESIS_FILE_NAME)
3503                    .is_file()
3504            );
3505            assert!(
3506                migration_directory
3507                    .display_path()
3508                    .join(&prepared.bridge_name)
3509                    .is_file()
3510            );
3511        }
3512    }
3513
3514    #[test]
3515    fn legacy_history_race_after_bridge_rolls_back_new_publication() {
3516        let (directory, workspace) = adoption_workspace();
3517        let legacy = write_legacy_fixture(directory.path());
3518        let prepared = prepare_archive_adoption(&workspace, &legacy, "0000_archive_frontier")
3519            .expect("adoption prepares");
3520        let migration_directory = workspace
3521            .ensure_migration_directory()
3522            .expect("canonical directory");
3523        let legacy_source = legacy.join("0001_initial.py");
3524
3525        let error = publish_prepared_adoption_with_after_bridge(
3526            &workspace,
3527            &migration_directory,
3528            &prepared,
3529            || {
3530                fs::write(
3531                    &legacy_source,
3532                    "class Migration:\n    operations = ['changed']\n",
3533                )
3534                .expect("race mutation writes");
3535            },
3536        )
3537        .expect_err("legacy authority race aborts pair publication");
3538        assert!(error.contains("changed"), "{error}");
3539        assert!(
3540            !migration_directory
3541                .display_path()
3542                .join(&prepared.bridge_name)
3543                .exists(),
3544            "new bridge is rolled back"
3545        );
3546        assert!(
3547            !migration_directory
3548                .display_path()
3549                .join(type_bridge_schema_compat::ADOPTED_GENESIS_FILE_NAME)
3550                .exists(),
3551            "genesis is never published after the race"
3552        );
3553    }
3554}