Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
36 changes: 20 additions & 16 deletions crates/workflow-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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!(
Expand Down
194 changes: 194 additions & 0 deletions crates/workflow-cli/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
2 changes: 1 addition & 1 deletion crates/workflow-core/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18973,7 +18973,7 @@ fn successful_governance_decision_authority_receipt_proof(
}))
}

fn governance_decision_receipt_commitment<T: Serialize>(
pub(crate) fn governance_decision_receipt_commitment<T: Serialize>(
domain: &'static str,
value: &T,
) -> Result<SpecContentHash, WorkflowOsError> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -168,7 +172,8 @@ pub trait GovernanceDecisionAuthorityReceiptRecordStore {
) -> Result<Option<PersistedGovernanceDecisionAuthorityReceiptRecord>, 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.
Expand All @@ -179,13 +184,28 @@ static TEMP_FILE_SEQUENCE: AtomicU64 = AtomicU64::new(0);
#[derive(Clone, Eq, PartialEq)]
pub struct LocalGovernanceDecisionAuthorityReceiptRecordStore {
root: PathBuf,
local_state: Option<crate::LocalStateBackend>,
}

impl LocalGovernanceDecisionAuthorityReceiptRecordStore {
/// Creates a local receipt-record store rooted at the supplied directory.
#[must_use]
pub fn new(root: impl Into<PathBuf>) -> 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<PathBuf>) -> 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.
Expand Down Expand Up @@ -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<GovernanceDecisionAuthorityReceiptWriteOutcome, WorkflowOsError> {
Expand All @@ -245,6 +261,20 @@ impl GovernanceDecisionAuthorityReceiptRecordStore
Err(error) => Err(error),
}
}
}

impl GovernanceDecisionAuthorityReceiptRecordStore
for LocalGovernanceDecisionAuthorityReceiptRecordStore
{
fn write_governance_decision_authority_receipt(
&self,
receipt: &GovernanceDecisionAuthorityReceipt,
) -> Result<GovernanceDecisionAuthorityReceiptWriteOutcome, WorkflowOsError> {
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,
Expand Down Expand Up @@ -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 _;
Expand Down
Loading
Loading