From 56b255a7c652938f9ff34cecbcb488670f8e0e85 Mon Sep 17 00:00:00 2001 From: Ryan Segar Date: Sun, 29 Nov 2026 01:25:29 -0800 Subject: [PATCH] Preserve authority receipt evidence across SQLite migration --- ROADMAP.md | 4 + crates/workflow-cli/src/main.rs | 36 ++-- crates/workflow-cli/tests/cli.rs | 194 ++++++++++++++++++ crates/workflow-core/src/executor.rs | 2 +- .../governance_decision_authority_receipt.rs | 19 ++ ...rnance_decision_authority_receipt_store.rs | 46 ++++- crates/workflow-core/src/sqlite_state.rs | 102 +++++++++ crates/workflow-core/src/state.rs | 7 +- .../src/state/migration_inventory.rs | 100 ++++++++- crates/workflow-core/src/state_migration.rs | 93 +++++++-- .../tests/state_migration_inventory.rs | 4 +- .../tests/state_migration_plan.rs | 45 ++-- ...EIPT_PRESERVING_SQLITE_MIGRATION_REPORT.md | 47 +++++ docs/user-guide/current-product-contract.md | 8 + 14 files changed, 637 insertions(+), 70 deletions(-) create mode 100644 docs/concepts/RECEIPT_PRESERVING_SQLITE_MIGRATION_REPORT.md diff --git a/ROADMAP.md b/ROADMAP.md index 77e53074..585a55b8 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -106,6 +106,10 @@ and bounded diagnostics without path or payload disclosure. Recheck filesystem, SQLite, shared PostgreSQL, hosted recovery and fresh checkout; check whether the shared and hosted stores preserve the same receipt family coherently. +See the [receipt-preserving migration implementation report](docs/concepts/RECEIPT_PRESERVING_SQLITE_MIGRATION_REPORT.md). +The attempted release remains denied. Verify the correction in the replacement +candidate's independent downstream rerun before reconsidering admission. + Separately queued from the same review: align root `AGENTS.md` with the actual local, hosted-alpha and narrow provider boundaries and add a product-surface truth check; guide the full inactive-draft lifecycle with diff --git a/crates/workflow-cli/src/main.rs b/crates/workflow-cli/src/main.rs index 1276fd41..7587e8c0 100644 --- a/crates/workflow-cli/src/main.rs +++ b/crates/workflow-cli/src/main.rs @@ -1973,27 +1973,26 @@ fn authoritative_governance_approve_command( report: inputs.report, local_check_reference: inputs.local_check_reference, }; - let receipt_store = LocalGovernanceDecisionAuthorityReceiptRecordStore::new( - invocation - .state_dir() - .join("governance-decision-authority-receipts"), - ); + let receipt_store = + LocalGovernanceDecisionAuthorityReceiptRecordStore::for_local_state(invocation.state_dir()); let projection_store = LocalApprovalProofMarkerAuditProjectionStore::new( invocation .state_dir() .join("audit-projections") .join("approval-proof-markers"), )?; - let result = decide_selected_project_validation_approval_envelope( - &executor, - &store, - &profile, - &receipt_store, - &backend, - &backend, - &projection_store, - request, - )?; + let result = backend.with_shared_writer_guard(|| { + decide_selected_project_validation_approval_envelope( + &executor, + &store, + &profile, + &receipt_store, + &backend, + &backend, + &projection_store, + request, + ) + })?; let presentation = if result.run().snapshot.status == WorkflowRunStatus::WaitingForApproval { Some(persist_authoritative_governance_approval_presentation( invocation, @@ -3815,7 +3814,12 @@ fn state_activate_sqlite_command( "state migration verification receipt is invalid", ) })?; - let backend = SqliteStateBackend::activate_verified_migration(destination, &receipt)?; + let source = LocalStateBackend::for_inspection(invocation.state_dir()); + let backend = SqliteStateBackend::activate_verified_migration_with_source( + destination, + &receipt, + &source, + )?; let health = backend.health_check()?; if invocation.json { println!( diff --git a/crates/workflow-cli/tests/cli.rs b/crates/workflow-cli/tests/cli.rs index 22c199fd..80e8b37a 100644 --- a/crates/workflow-cli/tests/cli.rs +++ b/crates/workflow-cli/tests/cli.rs @@ -7902,6 +7902,200 @@ fn doctor_state_does_not_create_missing_state_root() { assert!(!state_root.exists()); } +#[test] +#[allow(clippy::too_many_lines)] +fn scaffolded_approval_authority_receipt_survives_sqlite_migration() { + let project = TestProject::new("scaffolded-receipt-migration"); + let initialized = workflow_os(&project, &["init-repo-governance", "--agent", "codex"]); + assert!(initialized.status.success(), "{}", stderr(&initialized)); + let first_run = workflow_os(&project, &["first-run", "--write-report-artifact"]); + assert!(first_run.status.success(), "{}", stderr(&first_run)); + + let waiting = workflow_os( + &project, + &[ + "--mock-all-local-skills", + "run", + "local/first-run-governance", + ], + ); + assert!(waiting.status.success(), "{}", stderr(&waiting)); + let run = run_id(&waiting); + let aggregate = approval_id(&waiting); + let approve = |id: &str| { + workflow_os( + &project, + &[ + "--mock-all-local-skills", + "approve", + &run, + id, + "--actor", + "user/migration-review", + "--reason", + "Verify migration of generated approval evidence", + ], + ) + }; + let waiting_for_step = approve(&aggregate); + assert!( + waiting_for_step.status.success(), + "{}", + stderr(&waiting_for_step) + ); + let step = approval_id(&waiting_for_step); + assert_ne!(step, aggregate); + let completed = approve(&step); + assert!(completed.status.success(), "{}", stderr(&completed)); + assert!(stdout(&completed).contains("artifact: persisted")); + let run_id = WorkflowRunId::new(&run).expect("governed run ID"); + let report_id = WorkReportId::new(format!("report/{run}")).expect("governed report ID"); + let source = LocalStateBackend::for_inspection(project.state_root()); + let events = source.read_events(&run_id).expect("source events"); + let artifact = source + .read_work_report_artifact(&run_id, &report_id) + .expect("source report reads") + .expect("source report exists"); + + let database = project.path().join("migrated.sqlite3"); + let receipt = project.path().join("migration-receipt.json"); + let stage = |receipt: &Path| { + workflow_os( + &project, + &[ + "state", + "migrate-sqlite", + "--destination", + database.to_str().expect("database path"), + "--receipt-output", + receipt.to_str().expect("receipt path"), + "--migration-id", + "migration/scaffolded", + "--destination-id", + "sqlite/scaffolded", + "--verified-by", + "user/migration-review", + "--incompatible-older-writers-stopped", + ], + ) + }; + let record_file = first_json_file_under( + &project + .state_root() + .join("governance-decision-authority-receipts"), + ) + .expect("receipt produced by approval"); + let record_bytes = fs::read(&record_file).expect("read authoritatively generated receipt"); + let address = record_file.with_file_name("zzz-private-wrong-address.json"); + fs::rename(&record_file, &address).expect("move only the test receipt"); + let wrong_address = stage(&receipt); + assert!(!wrong_address.status.success()); + let diagnostic = stderr(&wrong_address); + assert!(diagnostic.contains("governance_decision_authority_receipts")); + assert!(diagnostic.contains("malformed_storage_address")); + assert!(!diagnostic.contains("zzz-private-wrong-address")); + assert!(!diagnostic.contains(project.path().to_str().expect("test path"))); + fs::rename(&address, &record_file).expect("restore the test receipt"); + fs::copy(&record_file, &address).expect("duplicate the test receipt"); + let duplicate = stage(&receipt); + assert!(!duplicate.status.success()); + assert!(stderr(&duplicate).contains("duplicate_identity")); + fs::remove_file(&address).expect("remove test duplicate"); + assert!(!database.exists()); + + source + .with_shared_writer_guard(|| { + let contended = stage(&receipt); + assert!(!contended.status.success()); + assert!(stderr(&contended).contains("state.migration.source.quiescence_contended")); + Ok(()) + }) + .expect("source writer guard"); + let staged = stage(&receipt); + assert!(staged.status.success(), "{}", stderr(&staged)); + assert!(stdout(&staged).contains("migration_status: verified_inactive")); + let verification: serde_json::Value = + serde_json::from_slice(&fs::read(&receipt).expect("read migration receipt")) + .expect("parse migration receipt"); + let receipt_family = verification["record_counts"] + .as_array() + .expect("migration family counts") + .iter() + .find(|entry| entry["family"] == "governance_decision_authority_receipts") + .expect("verification binds the authority receipt family"); + assert_eq!(receipt_family["count"], 1); + assert!(receipt_family["digest"].is_string()); + + let verification_bytes = fs::read(&receipt).expect("original receipt"); + fs::remove_file(&receipt).expect("simulate lost receipt output"); + let resumed = stage(&receipt); + assert!(resumed.status.success(), "{}", stderr(&resumed)); + assert_eq!( + fs::read(&receipt).expect("recovered verification receipt"), + verification_bytes, + ); + let verification_receipt = + serde_json::from_value(verification).expect("migration receipt models"); + assert_eq!( + SqliteStateBackend::activate_verified_migration(&database, &verification_receipt) + .expect_err("receipt-bearing migration requires its companion") + .code(), + "state.migration.companion.required" + ); + + let activate = || { + workflow_os( + &project, + &[ + "state", + "activate-sqlite", + "--destination", + database.to_str().expect("database path"), + "--receipt", + receipt.to_str().expect("receipt path"), + ], + ) + }; + let mut different_bytes = record_bytes.clone(); + different_bytes.push(b'\n'); + fs::write(&record_file, &different_bytes).expect("change the test companion after staging"); + let rejected = activate(); + assert!(!rejected.status.success()); + assert!(stderr(&rejected).contains("state.migration.companion.changed")); + assert!(SqliteStateBackend::open(&database).is_err()); + fs::write(&record_file, &record_bytes).expect("restore exact companion bytes"); + + let activated = activate(); + assert!(activated.status.success(), "{}", stderr(&activated)); + let backend = SqliteStateBackend::open(&database).expect("activated SQLite database"); + assert!(backend.health_check().expect("destination health").healthy); + assert_eq!( + backend.read_events(&run_id).expect("migrated events"), + events + ); + assert_eq!( + backend + .read_work_report_artifact(&run_id, &report_id) + .expect("migrated report reads"), + Some(artifact), + ); + let expected: workflow_core::PersistedGovernanceDecisionAuthorityReceiptRecord = + serde_json::from_slice(&record_bytes).expect("original receipt record"); + let recovered = backend + .read_retained_governance_decision_authority_receipt(&source, expected.receipt_id()) + .expect("verified recovery") + .expect("receipt retained"); + assert_eq!(recovered, expected); + fs::write(&record_file, &different_bytes).expect("change test companion after activation"); + assert_eq!( + backend + .read_retained_governance_decision_authority_receipt(&source, expected.receipt_id()) + .expect_err("drift must block recovery") + .code(), + "state.migration.companion.changed", + ); +} + #[test] fn state_migration_cli_stages_inactive_then_explicitly_activates() { let project = TestProject::new("state-migration"); diff --git a/crates/workflow-core/src/executor.rs b/crates/workflow-core/src/executor.rs index 4aaa6209..be21e7f6 100644 --- a/crates/workflow-core/src/executor.rs +++ b/crates/workflow-core/src/executor.rs @@ -18973,7 +18973,7 @@ fn successful_governance_decision_authority_receipt_proof( })) } -fn governance_decision_receipt_commitment( +pub(crate) fn governance_decision_receipt_commitment( domain: &'static str, value: &T, ) -> Result { diff --git a/crates/workflow-core/src/governance_decision_authority_receipt.rs b/crates/workflow-core/src/governance_decision_authority_receipt.rs index d80d4450..20cf1e79 100644 --- a/crates/workflow-core/src/governance_decision_authority_receipt.rs +++ b/crates/workflow-core/src/governance_decision_authority_receipt.rs @@ -472,6 +472,25 @@ impl UnverifiedGovernanceDecisionAuthorityReceipt { &self.record.receipt_commitment } + pub(crate) fn matches_approval_event(&self, event: &crate::WorkflowRunEvent) -> bool { + let crate::WorkflowRunEventKind::ApprovalGranted(decision) = &event.kind else { + return false; + }; + let Some(marker) = &decision.proof_marker else { + return false; + }; + event.event_id == self.record.approval_decision_event_id + && event.run_id == self.record.run_id + && event.workflow_id == self.record.workflow_id + && event.timestamp == self.record.issued_at + && decision.approval_id == self.record.approval_reference_id.as_str() + && crate::executor::governance_decision_receipt_commitment( + "workflow-os/governance-decision-authority-receipt/approval-proof-marker/v1", + marker, + ) + .is_ok_and(|hash| hash == self.record.approval_proof_marker_commitment) + } + /// Returns the claimed explicitly non-authorizing effect. #[must_use] pub const fn effect(&self) -> GovernanceDecisionAuthorityReceiptEffect { diff --git a/crates/workflow-core/src/governance_decision_authority_receipt_store.rs b/crates/workflow-core/src/governance_decision_authority_receipt_store.rs index f7020f3c..5e43bd74 100644 --- a/crates/workflow-core/src/governance_decision_authority_receipt_store.rs +++ b/crates/workflow-core/src/governance_decision_authority_receipt_store.rs @@ -26,6 +26,10 @@ pub struct PersistedGovernanceDecisionAuthorityReceiptRecord { } impl PersistedGovernanceDecisionAuthorityReceiptRecord { + pub(crate) fn matches_approval_event(&self, event: &crate::WorkflowRunEvent) -> bool { + self.claim.matches_approval_event(event) + } + /// Validates deterministic receipt identity and commitment consistency. /// /// # Errors @@ -168,7 +172,8 @@ pub trait GovernanceDecisionAuthorityReceiptRecordStore { ) -> Result, WorkflowOsError>; } -const RECEIPT_RECORDS_DIR: &str = "records"; +pub(crate) const RECEIPT_RECORDS_DIR: &str = "records"; +pub(crate) const RECEIPT_STATE_DIR: &str = "governance-decision-authority-receipts"; static TEMP_FILE_SEQUENCE: AtomicU64 = AtomicU64::new(0); /// Local create-only persistence for governance decision authority receipts. @@ -179,13 +184,28 @@ static TEMP_FILE_SEQUENCE: AtomicU64 = AtomicU64::new(0); #[derive(Clone, Eq, PartialEq)] pub struct LocalGovernanceDecisionAuthorityReceiptRecordStore { root: PathBuf, + local_state: Option, } impl LocalGovernanceDecisionAuthorityReceiptRecordStore { /// Creates a local receipt-record store rooted at the supplied directory. #[must_use] pub fn new(root: impl Into) -> Self { - Self { root: root.into() } + Self { + root: root.into(), + local_state: None, + } + } + + /// Uses the canonical receipt directory and cooperates with filesystem + /// migration's exclusive writer guard. + #[must_use] + pub fn for_local_state(state_root: impl Into) -> Self { + let state_root = state_root.into(); + Self { + root: state_root.join(RECEIPT_STATE_DIR), + local_state: Some(crate::LocalStateBackend::for_inspection(state_root)), + } } /// Returns the configured store root. @@ -218,12 +238,8 @@ impl LocalGovernanceDecisionAuthorityReceiptRecordStore { } Ok(GovernanceDecisionAuthorityReceiptWriteOutcome::AlreadyExists) } -} -impl GovernanceDecisionAuthorityReceiptRecordStore - for LocalGovernanceDecisionAuthorityReceiptRecordStore -{ - fn write_governance_decision_authority_receipt( + fn persist( &self, receipt: &GovernanceDecisionAuthorityReceipt, ) -> Result { @@ -245,6 +261,20 @@ impl GovernanceDecisionAuthorityReceiptRecordStore Err(error) => Err(error), } } +} + +impl GovernanceDecisionAuthorityReceiptRecordStore + for LocalGovernanceDecisionAuthorityReceiptRecordStore +{ + fn write_governance_decision_authority_receipt( + &self, + receipt: &GovernanceDecisionAuthorityReceipt, + ) -> Result { + match &self.local_state { + Some(state) => state.with_shared_writer_guard(|| self.persist(receipt)), + None => self.persist(receipt), + } + } fn read_governance_decision_authority_receipt( &self, @@ -381,7 +411,7 @@ fn unique_temp_path(path: &Path) -> PathBuf { temp_path } -fn encoded_id_file_name(value: &str) -> String { +pub(crate) fn encoded_id_file_name(value: &str) -> String { let mut encoded = String::with_capacity(value.len() * 2 + 5); for byte in value.as_bytes() { use std::fmt::Write as _; diff --git a/crates/workflow-core/src/sqlite_state.rs b/crates/workflow-core/src/sqlite_state.rs index 34dbc04e..8e1d892e 100644 --- a/crates/workflow-core/src/sqlite_state.rs +++ b/crates/workflow-core/src/sqlite_state.rs @@ -41,6 +41,11 @@ use crate::{ WorkflowOsError, WorkflowOsErrorKind, WorkflowRun, WorkflowRunEvent, WorkflowRunId, WorkflowRunSnapshot, }; +use crate::{ + GovernanceDecisionAuthorityReceiptId, GovernanceDecisionAuthorityReceiptRecordStore, + LocalGovernanceDecisionAuthorityReceiptRecordStore, LocalStateBackend, + PersistedGovernanceDecisionAuthorityReceiptRecord, StateMigrationRecordFamily, +}; const ADAPTER_SCHEMA_VERSION: u32 = 10; const LIVE_AUTHORITY_PREVIOUS_SCHEMA_VERSION: u32 = 11; @@ -381,6 +386,12 @@ pub struct StateMigrationVerificationReceipt { } impl StateMigrationVerificationReceipt { + fn authority_receipt_count(&self) -> Option<&StateMigrationRecordCount> { + self.record_counts.iter().find(|entry| { + entry.family() == StateMigrationRecordFamily::GovernanceDecisionAuthorityReceipts + }) + } + /// Returns the exact migration-attempt fingerprint. #[must_use] pub const fn attempt_fingerprint(&self) -> &StateMigrationDigest { @@ -1193,6 +1204,43 @@ impl SqliteStateBackend { database_path: impl Into, receipt: &StateMigrationVerificationReceipt, ) -> Result { + Self::activate_verified_migration_inner(database_path, receipt, None) + } + + /// Activates a verified migration with its original filesystem companion. + /// Receipt-free migrations do not read or require the source. + /// + /// # Errors + /// + /// Fails closed when receipt-bearing source evidence or inactive destination + /// state no longer matches the persisted staging verification. + pub fn activate_verified_migration_with_source( + database_path: impl Into, + receipt: &StateMigrationVerificationReceipt, + source: &LocalStateBackend, + ) -> Result { + Self::activate_verified_migration_inner(database_path, receipt, Some(source)) + } + + fn activate_verified_migration_inner( + database_path: impl Into, + receipt: &StateMigrationVerificationReceipt, + source: Option<&LocalStateBackend>, + ) -> Result { + let _source_guard = if receipt.authority_receipt_count().is_some() { + let source = source.ok_or_else(companion_required)?; + let guard = source.try_acquire_exclusive_migration_guard()?; + let inventory = guard.inspect_migration_inventory()?; + if !inventory.is_migration_compatible() + || inventory.source_fingerprint() != Some(&receipt.source_fingerprint) + || inventory.record_counts() != receipt.record_counts() + { + return Err(companion_changed()); + } + Some(guard) + } else { + None + }; let backend = Self { database_path: database_path.into(), busy_timeout: DEFAULT_BUSY_TIMEOUT, @@ -1263,6 +1311,46 @@ impl SqliteStateBackend { Self::open(backend.database_path) } + /// Reads retained authority evidence bound to a verified migration and + /// the corresponding event in the ready database. This never grants authority. + /// + /// # Errors + /// + /// Fails closed if no verified companion exists, its family digest or + /// count changes, or the referenced approval event no longer matches. + pub fn read_retained_governance_decision_authority_receipt( + &self, + source: &LocalStateBackend, + id: &GovernanceDecisionAuthorityReceiptId, + ) -> Result, WorkflowOsError> { + let connection = self.existing_read_only_connection()?; + if read_migration_state(&connection)? != MIGRATION_STATE_READY { + return Err(companion_required()); + } + let receipt = Self::read_receipt_payload(&connection)?; + let expected = receipt + .authority_receipt_count() + .ok_or_else(companion_required)?; + let guard = source.try_acquire_exclusive_migration_guard()?; + let inventory = guard.inspect_migration_inventory()?; + if !inventory.is_migration_compatible() || !inventory.record_counts().contains(expected) { + return Err(companion_changed()); + } + let store = + LocalGovernanceDecisionAuthorityReceiptRecordStore::for_local_state(source.root()); + let record = store.read_governance_decision_authority_receipt(id)?; + if let Some(record) = &record { + if !self + .read_events(record.run_id())? + .iter() + .any(|event| record.matches_approval_event(event)) + { + return Err(companion_changed()); + } + } + Ok(record) + } + /// Opens or creates an opt-in local `SQLite` state database. /// /// # Errors @@ -4718,6 +4806,20 @@ fn verification_failed() -> WorkflowOsError { ) } +fn companion_required() -> WorkflowOsError { + migration_runtime_error( + "companion.required", + "migration requires the retained governance decision authority receipt companion", + ) +} + +fn companion_changed() -> WorkflowOsError { + migration_runtime_error( + "companion.changed", + "retained governance decision authority receipt evidence failed verification", + ) +} + fn migration_runtime_error(suffix: &str, message: &str) -> WorkflowOsError { WorkflowOsError::new( crate::WorkflowOsErrorKind::InvalidState, diff --git a/crates/workflow-core/src/state.rs b/crates/workflow-core/src/state.rs index 1e044345..423fd495 100644 --- a/crates/workflow-core/src/state.rs +++ b/crates/workflow-core/src/state.rs @@ -937,7 +937,12 @@ impl LocalStateBackend { }) } - fn with_shared_writer_guard( + /// Keeps a cooperating logical write out of an exclusive migration window. + /// + /// # Errors + /// + /// Returns a guard acquisition or operation error. + pub fn with_shared_writer_guard( &self, operation: impl FnOnce() -> Result, ) -> Result { diff --git a/crates/workflow-core/src/state/migration_inventory.rs b/crates/workflow-core/src/state/migration_inventory.rs index 79ff7134..1cb4b57f 100644 --- a/crates/workflow-core/src/state/migration_inventory.rs +++ b/crates/workflow-core/src/state/migration_inventory.rs @@ -1,5 +1,6 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fs; +use std::io::Read as _; use std::path::{Path, PathBuf}; use serde::de::DeserializeOwned; @@ -10,13 +11,17 @@ use super::{ encode_key, read_json, ApprovalPresentationIdRecord, EventIdRecord, IdempotencyResult, LocalStateBackend, LocalStateIssueSeverity, LockLease, ProjectStateRecord, SideEffectIdRecord, }; +use crate::governance_decision_authority_receipt_store::{ + encoded_id_file_name, RECEIPT_RECORDS_DIR, RECEIPT_STATE_DIR, +}; use crate::immutable_run_bundle_store::{ GOVERNANCE_ASSESSMENT_BINDINGS_DIR, LOCAL_CHECK_EVIDENCE_ASSURANCE_PROJECTIONS_DIR, MANIFESTS_DIR, }; use crate::{ AdapterRuntimeAuditRecord, AdapterRuntimeObservabilityRecord, ApprovalPresentationRecord, - ApprovalRequest, LocalImmutableRunBundleStore, PolicyAuditRecord, SideEffectRecord, + ApprovalRequest, EventLogStore, LocalImmutableRunBundleStore, + PersistedGovernanceDecisionAuthorityReceiptRecord, PolicyAuditRecord, SideEffectRecord, StateMigrationCompatibilityFinding, StateMigrationDigest, StateMigrationFindingCode, StateMigrationFindingSeverity, StateMigrationInventory, StateMigrationRecordCount, StateMigrationRecordFamily, WorkReportArtifactRecord, WorkflowOsError, WorkflowRunEvent, @@ -25,6 +30,7 @@ use crate::{ const IMMUTABLE_BUNDLE_CONTENT_DIRS: [&str; 2] = ["definition-records", "local-check-declaration-set-records"]; +const MAX_AUTHORITY_RECEIPT_BYTES: u64 = 64 * 1024; #[derive(Clone)] struct FamilyAccumulator { @@ -93,9 +99,16 @@ impl LocalStateBackend { /// result itself cannot be constructed. #[allow(clippy::too_many_lines)] pub fn inspect_migration_inventory(&self) -> Result { + let receipt_family = StateMigrationRecordFamily::GovernanceDecisionAuthorityReceipts; + let receipt_root_present = !self + .root() + .join(RECEIPT_STATE_DIR) + .symlink_metadata() + .is_err_and(|error| error.kind() == std::io::ErrorKind::NotFound); let mut accumulators = StateMigrationRecordFamily::all() .iter() .copied() + .filter(|family| *family != receipt_family || receipt_root_present) .map(|family| (family, FamilyAccumulator::new(family))) .collect::>(); let mut findings = Vec::new(); @@ -252,6 +265,9 @@ impl LocalStateBackend { |_| None, ); self.scan_immutable_bundles(&mut accumulators, &mut findings); + if receipt_root_present { + self.scan_governance_receipts(&mut accumulators, &mut findings); + } self.validate_side_effect_indexes(&mut accumulators, &mut findings); self.validate_approval_presentation_indexes(&mut accumulators, &mut findings); @@ -263,7 +279,7 @@ impl LocalStateBackend { accumulators: &mut BTreeMap, findings: &mut Vec, ) { - const KNOWN_ROOTS: [&str; 14] = [ + const KNOWN_ROOTS: [&str; 15] = [ "events", "event_ids", "snapshots", @@ -278,6 +294,7 @@ impl LocalStateBackend { "side_effects", "approval_presentations", "immutable-run-bundles", + RECEIPT_STATE_DIR, ]; let Some(entries) = directory_entries(self.root(), findings, None) else { invalidate_all(accumulators); @@ -297,7 +314,9 @@ impl LocalStateBackend { classify_unknown_entry(&entry, findings); continue; } - validate_expected_directory(&entry, findings, None); + if name != RECEIPT_STATE_DIR { + validate_expected_directory(&entry, findings, None); + } } Self::inspect_group_root( &self.root().join("side_effects"), @@ -539,6 +558,81 @@ impl LocalStateBackend { } } + fn scan_governance_receipts( + &self, + accumulators: &mut BTreeMap, + findings: &mut Vec, + ) { + let family = StateMigrationRecordFamily::GovernanceDecisionAuthorityReceipts; + let accumulator = family_accumulator(accumulators, family); + let root = self.root().join(RECEIPT_STATE_DIR); + let initial_findings = findings.len(); + let Some(entries) = directory_entries(&root, findings, Some(family)) else { + accumulator.invalidate(); + return; + }; + let mut event_ids = BTreeSet::new(); + for directory in entries { + if file_name(&directory).as_deref() != Some(RECEIPT_RECORDS_DIR) { + malformed_address(accumulator, findings, family); + continue; + } + let Some(paths) = directory_entries(&directory, findings, Some(family)) else { + continue; + }; + for path in paths { + accumulator.discovered(); + if !is_regular_file(&path, findings, Some(family)) { + continue; + } + let mut bytes = Vec::new(); + if fs::File::open(&path) + .and_then(|file| { + file.take(MAX_AUTHORITY_RECEIPT_BYTES + 1) + .read_to_end(&mut bytes) + }) + .is_err() + || bytes.len() as u64 > MAX_AUTHORITY_RECEIPT_BYTES + { + invalid_record(accumulator, findings, family); + continue; + } + let Ok(record) = serde_json::from_slice::< + PersistedGovernanceDecisionAuthorityReceiptRecord, + >(&bytes) else { + invalid_record(accumulator, findings, family); + continue; + }; + if !event_ids.insert(record.approval_decision_event_id().clone()) { + duplicate_identity(accumulator, findings, family); + continue; + } + let address = encoded_id_file_name(record.receipt_id().as_str()); + if file_name(&path).as_deref() != Some(address.as_str()) { + malformed_address(accumulator, findings, family); + continue; + } + if !self.read_events(record.run_id()).is_ok_and(|events| { + events + .iter() + .any(|event| record.matches_approval_event(event)) + }) { + push_finding( + findings, + StateMigrationFindingSeverity::Blocker, + StateMigrationFindingCode::IndexInconsistent, + Some(family), + ); + continue; + } + accumulator.update_opaque(&address, &bytes); + } + } + if findings.len() != initial_findings { + accumulator.invalidate(); + } + } + fn scan_immutable_bundles( &self, accumulators: &mut BTreeMap, diff --git a/crates/workflow-core/src/state_migration.rs b/crates/workflow-core/src/state_migration.rs index 55d5a84c..8738d24c 100644 --- a/crates/workflow-core/src/state_migration.rs +++ b/crates/workflow-core/src/state_migration.rs @@ -77,6 +77,8 @@ migration_identifier!( pub enum StateMigrationPlanVersion { /// Initial filesystem-to-SQLite staging plan. V1, + /// Staging plan that binds the authority receipt companion. + V2, } /// Version of the read-only state-migration inventory contract. @@ -85,6 +87,8 @@ pub enum StateMigrationPlanVersion { pub enum StateMigrationInventoryVersion { /// Initial filesystem inventory and compatibility contract. V1, + /// Inventory that includes the authority receipt companion. + V2, } /// Version of the cooperating local-filesystem writer protocol. @@ -452,10 +456,12 @@ pub enum StateMigrationRecordFamily { SideEffectIdIndexes, /// Companion immutable run-bundle files retained outside `SQLite` schema v1. ImmutableRunBundles, + /// Point-in-time approval evidence retained as a verified companion. + GovernanceDecisionAuthorityReceipts, } impl StateMigrationRecordFamily { - const ALL: [Self; 16] = [ + const ALL: [Self; 17] = [ Self::WorkflowEvents, Self::EventIdIndexes, Self::RunSnapshots, @@ -472,6 +478,7 @@ impl StateMigrationRecordFamily { Self::SideEffectRecords, Self::SideEffectIdIndexes, Self::ImmutableRunBundles, + Self::GovernanceDecisionAuthorityReceipts, ]; /// Returns every inventory family in stable order. @@ -480,6 +487,15 @@ impl StateMigrationRecordFamily { &Self::ALL } + /// Returns the families represented by the specified inventory version. + #[must_use] + pub fn for_inventory_version(version: StateMigrationInventoryVersion) -> &'static [Self] { + match version { + StateMigrationInventoryVersion::V1 => &Self::ALL[..Self::ALL.len() - 1], + StateMigrationInventoryVersion::V2 => Self::all(), + } + } + /// Returns the required migration disposition for this family. #[must_use] pub const fn disposition(self) -> StateMigrationDisposition { @@ -499,7 +515,9 @@ impl StateMigrationRecordFamily { | Self::ApprovalPresentationIdIndexes | Self::SideEffectIdIndexes => StateMigrationDisposition::ProjectionRebuild, Self::LocalLocks => StateMigrationDisposition::EphemeralExclude, - Self::ImmutableRunBundles => StateMigrationDisposition::CompanionPreserve, + Self::ImmutableRunBundles | Self::GovernanceDecisionAuthorityReceipts => { + StateMigrationDisposition::CompanionPreserve + } } } @@ -521,6 +539,7 @@ impl StateMigrationRecordFamily { Self::SideEffectRecords => "side_effect_records", Self::SideEffectIdIndexes => "side_effect_id_indexes", Self::ImmutableRunBundles => "immutable_run_bundles", + Self::GovernanceDecisionAuthorityReceipts => "governance_decision_authority_receipts", } } } @@ -796,7 +815,14 @@ impl StateMigrationInventory { .iter() .map(StateMigrationRecordCount::family) .collect::>(); - let expected = StateMigrationRecordFamily::all() + let receipt_family = StateMigrationRecordFamily::GovernanceDecisionAuthorityReceipts; + let with_receipts = families.contains(&receipt_family); + let version = if with_receipts { + StateMigrationInventoryVersion::V2 + } else { + StateMigrationInventoryVersion::V1 + }; + let expected = StateMigrationRecordFamily::for_inventory_version(version) .iter() .copied() .collect::>(); @@ -818,11 +844,11 @@ impl StateMigrationInventory { .iter() .all(|finding| finding.severity() != StateMigrationFindingSeverity::Blocker); let source_fingerprint = - derive_source_fingerprint(&record_counts, &findings, quiescence_required); + derive_source_fingerprint(version, &record_counts, &findings, quiescence_required); let migration_compatible = healthy && source_fingerprint.is_some(); Ok(Self { - version: StateMigrationInventoryVersion::V1, + version, source_backend: DurableStateBackendKind::LocalFilesystemPreview, record_counts, findings, @@ -956,10 +982,16 @@ impl StateMigrationSource { /// or has no complete source fingerprint. pub fn from_inventory(inventory: &StateMigrationInventory) -> Result { if !inventory.is_migration_compatible() { - return Err(migration_error( - "source.incompatible", - "state migration source inventory is not compatible", - )); + let finding = inventory + .findings() + .iter() + .find(|finding| finding.severity() == StateMigrationFindingSeverity::Blocker) + .and_then(|finding| serde_json::to_string(finding).ok()); + let message = finding.map_or_else( + || "state migration source inventory is not compatible".to_owned(), + |finding| format!("state migration source inventory is not compatible: {finding}"), + ); + return Err(migration_error("source.incompatible", &message)); } let source_fingerprint = inventory.source_fingerprint().cloned().ok_or_else(|| { migration_error( @@ -1348,13 +1380,17 @@ impl StateMigrationPlan { source: StateMigrationSource, destination: StateMigrationDestination, ) -> Self { - let steps = canonical_plan_steps(); + let version = match source.inventory_version() { + StateMigrationInventoryVersion::V1 => StateMigrationPlanVersion::V1, + StateMigrationInventoryVersion::V2 => StateMigrationPlanVersion::V2, + }; + let steps = canonical_plan_steps(version); let verification_requirements = StateMigrationVerificationRequirement::all().to_vec(); let plan_fingerprint = - derive_plan_fingerprint(&migration_id, &source, &destination, &steps); + derive_plan_fingerprint(version, &migration_id, &source, &destination, &steps); Self { migration_id, - version: StateMigrationPlanVersion::V1, + version, source, destination, plan_fingerprint, @@ -1710,22 +1746,28 @@ const PLAN_FAMILY_ORDER: [StateMigrationRecordFamily; 16] = [ StateMigrationRecordFamily::ImmutableRunBundles, ]; -fn canonical_plan_steps() -> Vec { +fn canonical_plan_steps(version: StateMigrationPlanVersion) -> Vec { PLAN_FAMILY_ORDER .iter() + .copied() + .chain( + (version == StateMigrationPlanVersion::V2) + .then_some(StateMigrationRecordFamily::GovernanceDecisionAuthorityReceipts), + ) .zip(1_u16..) - .map(|(family, sequence)| StateMigrationPlanStep::new(sequence, *family)) + .map(|(family, sequence)| StateMigrationPlanStep::new(sequence, family)) .collect() } fn derive_plan_fingerprint( + version: StateMigrationPlanVersion, migration_id: &StateMigrationId, source: &StateMigrationSource, destination: &StateMigrationDestination, steps: &[StateMigrationPlanStep], ) -> StateMigrationDigest { let mut hasher = Sha256::new(); - hash_field(&mut hasher, "plan_version", "v1"); + hash_field(&mut hasher, "plan_version", plan_version_label(version)); hash_field(&mut hasher, "migration_id", migration_id.as_str()); hash_field( &mut hasher, @@ -1758,6 +1800,13 @@ fn derive_plan_fingerprint( StateMigrationDigest::from_hasher(hasher) } +const fn plan_version_label(version: StateMigrationPlanVersion) -> &'static str { + match version { + StateMigrationPlanVersion::V1 => "v1", + StateMigrationPlanVersion::V2 => "v2", + } +} + fn derive_attempt_fingerprint(attempt: &StateMigrationAttempt) -> StateMigrationDigest { let mut hasher = Sha256::new(); hash_field(&mut hasher, "attempt_version", "v1"); @@ -1765,9 +1814,7 @@ fn derive_attempt_fingerprint(attempt: &StateMigrationAttempt) -> StateMigration hash_field( &mut hasher, "plan_version", - match attempt.plan_version { - StateMigrationPlanVersion::V1 => "v1", - }, + plan_version_label(attempt.plan_version), ); hash_field( &mut hasher, @@ -1822,6 +1869,7 @@ fn derive_attempt_fingerprint(attempt: &StateMigrationAttempt) -> StateMigration } fn derive_source_fingerprint( + version: StateMigrationInventoryVersion, records: &[StateMigrationRecordCount], findings: &[StateMigrationCompatibilityFinding], quiescence_required: bool, @@ -1835,7 +1883,14 @@ fn derive_source_fingerprint( } let mut hasher = Sha256::new(); - hash_field(&mut hasher, "version", "v1"); + hash_field( + &mut hasher, + "version", + match version { + StateMigrationInventoryVersion::V1 => "v1", + StateMigrationInventoryVersion::V2 => "v2", + }, + ); hash_field( &mut hasher, "quiescence_required", diff --git a/crates/workflow-core/tests/state_migration_inventory.rs b/crates/workflow-core/tests/state_migration_inventory.rs index 35e9e36f..621559c4 100644 --- a/crates/workflow-core/tests/state_migration_inventory.rs +++ b/crates/workflow-core/tests/state_migration_inventory.rs @@ -127,7 +127,7 @@ fn absent_source_is_inspected_without_creating_files() { assert!(inventory.source_fingerprint().is_some()); assert_eq!( inventory.record_counts().len(), - StateMigrationRecordFamily::all().len() + StateMigrationRecordFamily::for_inventory_version(inventory.version()).len() ); assert!(!fixture.root.exists(), "inspection must remain read-only"); } @@ -172,7 +172,7 @@ fn known_state_has_complete_classification_and_path_independent_fingerprint() { .count(), 1 ); - for family in StateMigrationRecordFamily::all() { + for family in StateMigrationRecordFamily::for_inventory_version(first_inventory.version()) { assert_eq!( first_inventory .record_count(*family) diff --git a/crates/workflow-core/tests/state_migration_plan.rs b/crates/workflow-core/tests/state_migration_plan.rs index 4049db2a..ade46ae0 100644 --- a/crates/workflow-core/tests/state_migration_plan.rs +++ b/crates/workflow-core/tests/state_migration_plan.rs @@ -7,28 +7,30 @@ use std::collections::BTreeSet; use workflow_core::{ DurableStateBackendKind, StateMigrationDestinationId, StateMigrationDestinationPosture, StateMigrationDigest, StateMigrationDisposition, StateMigrationFindingCode, - StateMigrationFindingSeverity, StateMigrationId, StateMigrationInventory, StateMigrationPlan, - StateMigrationPlanVersion, StateMigrationRecordCount, StateMigrationRecordFamily, - StateMigrationResumePolicy, StateMigrationVerificationRequirement, + StateMigrationFindingSeverity, StateMigrationId, StateMigrationInventory, + StateMigrationInventoryVersion, StateMigrationPlan, StateMigrationPlanVersion, + StateMigrationRecordCount, StateMigrationRecordFamily, StateMigrationResumePolicy, + StateMigrationVerificationRequirement, }; fn inventory_with_digest(seed: char) -> StateMigrationInventory { - let records = StateMigrationRecordFamily::all() - .iter() - .copied() - .map(|family| { - StateMigrationRecordCount::new( - family, - family.disposition(), - 0, - Some( - StateMigrationDigest::new(seed.to_string().repeat(64)) - .expect("valid family digest"), - ), - ) - .expect("valid family record") - }) - .collect(); + let records = + StateMigrationRecordFamily::for_inventory_version(StateMigrationInventoryVersion::V1) + .iter() + .copied() + .map(|family| { + StateMigrationRecordCount::new( + family, + family.disposition(), + 0, + Some( + StateMigrationDigest::new(seed.to_string().repeat(64)) + .expect("valid family digest"), + ), + ) + .expect("valid family record") + }) + .collect(); StateMigrationInventory::new(records, Vec::new(), true).expect("compatible inventory") } @@ -177,7 +179,10 @@ fn every_family_appears_once_in_deterministic_dependency_order() { let unique = actual.iter().copied().collect::>(); assert_eq!(actual, expected); - assert_eq!(unique.len(), StateMigrationRecordFamily::all().len()); + assert_eq!( + unique.len(), + StateMigrationRecordFamily::for_inventory_version(StateMigrationInventoryVersion::V1).len() + ); for (sequence, step) in (1_u16..).zip(plan.steps()) { assert_eq!(step.sequence(), sequence); assert_eq!(step.disposition(), step.family().disposition()); diff --git a/docs/concepts/RECEIPT_PRESERVING_SQLITE_MIGRATION_REPORT.md b/docs/concepts/RECEIPT_PRESERVING_SQLITE_MIGRATION_REPORT.md new file mode 100644 index 00000000..b2316b94 --- /dev/null +++ b/docs/concepts/RECEIPT_PRESERVING_SQLITE_MIGRATION_REPORT.md @@ -0,0 +1,47 @@ +# Receipt-Preserving SQLite Migration + +This fixes the local migration blocker reproduced after a scaffolded +approval-governed run. It does not readmit or publish a preview artifact. + +## Disposition + +Keep governance-decision authority receipts in the source filesystem as +explicit, verified companion evidence. SQLite imports the ordered run +events and WorkReport as before. An unverified serialized claim does not +become a trusted receipt or acquire authority by passing migration. + +Receipt-bearing inventories and plans use V2. The family hash covers the +exact stored address and bytes. Inventory checks the receipt's deterministic +identity and commitment and matches its run, workflow, approval reference, +event, timestamp and proof-marker commitment to the durable grant. Invalid, +unaddressable and duplicate records fail closed. The migration receipt retains +family counts and digests, not evidence payloads or source paths. + +The CLI holds the shared filesystem writer guard across the approval operation +that can create this receipt. Staging uses the existing exclusive guard and +source recheck. Receipt-bearing activation also requires the original verified +filesystem state, as selected by the same project and state directory. +Post-activation evidence lookup checks the retained family commitment against +the persisted migration receipt and matches the migrated SQLite grant event. +Receipt-free inventory/plan fingerprints and existing V1 activation remain +unchanged. No SQLite schema change or move of the filesystem state is required. + +## Verification + +The adopter regression scaffolds a project, persists first-run evidence, +grants both approvals, and migrates the completed report and event history. +It checks migration and activation, exact retry after receipt output loss, +companion presence, byte drift before and after activation, duplicate and +wrong-address refusal, bounded diagnostics, writer contention, and evidence +recovery without a new grant. Existing migration model and CLI tests retain +the pre-approval and legacy cases. PostgreSQL and hosted-specific receipt +contracts are distinct; this change neither maps these local approval +records to those contracts nor changes their storage. Their existing +conformance and recovery CI jobs remain required. + +Governed by `dg/blocker` run `run-1795943812285920000-2`, approval +`approval/run-1795943812285920000-2/fix-approved`, presentation +`presentation/2011b26d28fa0fb6`. The executor performed code and documentation +edits, validation, and delivery outside the mock dogfood handlers. The +[preview denial](0.4.0-preview.1_SCOPED_CANDIDATE_TRANSFER_REPORT.md#exact-pair-admission-decision) +remains binding for the old candidate pair. diff --git a/docs/user-guide/current-product-contract.md b/docs/user-guide/current-product-contract.md index 870b121a..5a5a15d8 100644 --- a/docs/user-guide/current-product-contract.md +++ b/docs/user-guide/current-product-contract.md @@ -274,6 +274,14 @@ Use `state upgrade-sqlite` for an existing ready V9 SQLite database. A verified inactive V9 migration still requires `state activate-sqlite` with its original receipt; activation upgrades it atomically without rewriting the receipt. +For receipt-bearing filesystem migrations, keep the original filesystem state +at staging and activation. Pass the same project and, if overridden, the same +`--state-dir` to both commands. Migration binds the authority receipt family +to its verification result and checks its exact contents again at activation. +Keep that state as the verified companion for later evidence reads; the +receipts are not imported as SQLite runtime authority. The original V1 +migration format remains supported for receipt-free sources. + Advanced Core compositions, hosted operations, and provider-write proof paths are not all exposed as stable CLI commands.