diff --git a/epiphany-core/src/bin/epiphany-verse-query.rs b/epiphany-core/src/bin/epiphany-verse-query.rs index 3c060df9..4c3fbb0c 100644 --- a/epiphany-core/src/bin/epiphany-verse-query.rs +++ b/epiphany-core/src/bin/epiphany-verse-query.rs @@ -425,7 +425,6 @@ fn run_cli() -> Result<()> { } "swarm-brake" | "brake" => { require_query_bootstrap(&args)?; - let context = query_epiphany_local_verse_context(&args.store, args.runtime_id.clone())?; let created_at_utc = Utc::now().to_rfc3339(); let status = args @@ -1022,106 +1021,10 @@ fn run_cli() -> Result<()> { ); } "bifrost-artifact-acceptance" | "artifact-acceptance" => { - if args.artifact_ref.is_some() - || args.public_proof_id.is_some() - || args.result_ref.is_some() - || args.review_receipts.is_some() - || args.ledger_entry_id.is_some() - || args.receipt_id.is_some() - || args.receipt_status.is_some() - || args.source_agent_id.is_some() - { - anyhow::bail!( - "bifrost-artifact-acceptance inspects a pending request only; Maintainer owns acceptance decisions and Bifrost owns accounting fields" - ); - } - - require_query_bootstrap(&args)?; - - let (_, map_entries) = load_repo_work_map_entries(&args)?; - let map_entry = latest_repo_work_map_entry_for_family( - &map_entries, - "repo.artifact_acceptance_request", - ) - .context( - "bifrost-artifact-acceptance requires a repo.artifact_acceptance_request map entry", - )?; - println!( - "{}", - serde_json::to_string_pretty(&json!({ - "schemaVersion": "epiphany.local_verse_bifrost_artifact_acceptance.v0", - "status": "pending-maintainer-bifrost", - "store": args.store, - "runtimeId": args.runtime_id, - "receiptId": null, - "item": map_entry.item, - "sourceWorkspace": map_entry.workspace, - "sourceBranch": map_entry.branch, - "commitSha": map_entry.commit_sha, - "changedPaths": map_entry.changed_paths, - "artifactRef": null, - "publicProofRef": null, - "ledgerEntryId": null, - "reviewReceiptIds": [], - "acceptedBy": null, - "responseOwner": "Maintainer", - "commands": { - "swarmOverview": WRAPPER_OVERVIEW_COMMAND, - "bifrostArtifactAcceptance": WRAPPER_BIFROST_ARTIFACT_ACCEPTANCE_COMMAND, - "bifrostLedger": WRAPPER_BIFROST_LEDGER_COMMAND - }, - "privateStateExposed": false, - }))? - ); + anyhow::bail!("historical-only: canonical frontier workflow required") } "bifrost-metrics" | "metrics-receipt" => { - if args.artifact_ref.is_some() - || args.verification_receipts.is_some() - || args.review_receipts.is_some() - || args.credit_receipt_ids.is_some() - || args.public_proof_id.is_some() - || args.result_ref.is_some() - || args.receipt_summary.is_some() - || args.receipt_id.is_some() - || args.receipt_status.is_some() - { - anyhow::bail!( - "bifrost-metrics inspects a pending request only; Bifrost owns accounting fields and Maintainer owns review-load evidence" - ); - } - - require_query_bootstrap(&args)?; - - let (_, map_entries) = load_repo_work_map_entries(&args)?; - let map_entry = - latest_repo_work_map_entry_for_family(&map_entries, "repo.metrics_request") - .context("bifrost-metrics requires a repo.metrics_request map entry")?; - println!( - "{}", - serde_json::to_string_pretty(&json!({ - "schemaVersion": "epiphany.local_verse_bifrost_metrics.v0", - "status": "pending-bifrost-maintainer", - "store": args.store, - "runtimeId": args.runtime_id, - "receiptId": null, - "item": map_entry.item, - "sourceWorkspace": map_entry.workspace, - "sourceBranch": map_entry.branch, - "artifactAcceptanceReceiptId": null, - "modelSpendReceiptIds": [], - "reviewLoadReceiptIds": [], - "creditReadbackReceiptIds": [], - "publicProofRef": null, - "metricsSummary": null, - "responseOwner": "Bifrost", - "commands": { - "swarmOverview": WRAPPER_OVERVIEW_COMMAND, - "bifrostMetrics": WRAPPER_BIFROST_METRICS_COMMAND, - "bifrostLedger": WRAPPER_BIFROST_LEDGER_COMMAND - }, - "privateStateExposed": false, - }))? - ); + anyhow::bail!("historical-only: canonical frontier workflow required") } "bifrost-ledger" | "publication-ledger" => { let report = load_bifrost_ledger_report(&args)?; @@ -3560,6 +3463,8 @@ struct RepoWorkOverviewRow { #[derive(Clone, Serialize)] #[serde(rename_all = "camelCase")] struct RepoWorkMapRow { + status: String, + reason: String, map_entry_id: String, workspace: String, item: String, @@ -4757,13 +4662,14 @@ fn repo_work_overview_row(overview: &EpiphanyCultMeshRepoWorkOverviewEntry) -> R workspace: overview.workspace.clone(), item: overview.item.clone(), branch: overview.branch.clone(), - current_gate: overview.current_gate.clone(), - blocker: overview.blocker.clone(), - next_safe_move: overview.next_safe_move.clone(), + current_gate: "historical-only".to_string(), + blocker: "canonical-frontier-workflow-required".to_string(), + next_safe_move: "Canonical frontier workflow required; historical record grants no action." + .to_string(), changed_path_count: overview.changed_paths.len(), commit_sha: overview.commit_sha.clone(), soul_verdict: overview.soul_verdict.clone(), - publication_status: overview.publication_status.clone(), + publication_status: "historical-only".to_string(), sync_status: overview.sync_status.clone(), proof_bundle_ref: overview.proof_bundle_ref.clone(), private_state_exposed: overview.private_state_exposed, @@ -4799,19 +4705,22 @@ fn repo_work_map_rows( fn repo_work_map_row(entry: &EpiphanyCultMeshRepoWorkMapEntry) -> RepoWorkMapRow { RepoWorkMapRow { + status: "historical-only".to_string(), + reason: "canonical frontier workflow required".to_string(), map_entry_id: entry.map_entry_id.clone(), workspace: entry.workspace.clone(), item: entry.item.clone(), branch: entry.branch.clone(), changed_path_count: entry.changed_paths.len(), commit_sha: entry.commit_sha.clone(), - safe_action_family: entry.safe_action_family.clone(), - modeling_summary: entry.modeling_summary.clone(), + safe_action_family: format!("historical:{}", entry.safe_action_family), + modeling_summary: "Historical record only; canonical frontier workflow required." + .to_string(), soul_verdict_receipt_id: entry.soul_verdict_receipt_id.clone(), mind_gateway_review_id: entry.mind_gateway_review_id.clone(), mind_state_commit_receipt_id: entry.mind_state_commit_receipt_id.clone(), - publication_gate: entry.publication_gate.clone(), - durable_state_admitted: entry.durable_state_admitted, + publication_gate: "historical-only".to_string(), + durable_state_admitted: false, source_store_path: entry.source_store_path.clone(), private_state_exposed: entry.private_state_exposed, } @@ -4849,19 +4758,19 @@ fn repo_work_map_semantic_rows( } fn repo_work_map_semantic_row(entry: &EpiphanyCultMeshRepoWorkMapEntry) -> RepoWorkMapSemanticRow { - let (stage, stage_owner) = repo_work_stage_for_family(&entry.safe_action_family); RepoWorkMapSemanticRow { item: entry.item.clone(), branch: entry.branch.clone(), - stage, - stage_owner, - publication_gate: entry.publication_gate.clone(), - gate_owner: repo_work_gate_owner(&entry.publication_gate), - safe_action_family: entry.safe_action_family.clone(), + stage: "historical-only".to_string(), + stage_owner: "none".to_string(), + publication_gate: "historical-only".to_string(), + gate_owner: "none".to_string(), + safe_action_family: format!("historical:{}", entry.safe_action_family), changed_path_count: entry.changed_paths.len(), latest_commit_sha: entry.commit_sha.clone(), latest_mind_state_commit_receipt_id: entry.mind_state_commit_receipt_id.clone(), - modeling_summary: entry.modeling_summary.clone(), + modeling_summary: "Historical record only; canonical frontier workflow required." + .to_string(), sight_only: true, private_state_exposed: entry.private_state_exposed, } @@ -5408,9 +5317,10 @@ fn repo_work_public_proof_row( workspace: proof.workspace.clone(), item: proof.item.clone(), branch: proof.branch.clone(), - current_gate: proof.current_gate.clone(), - blocker: proof.blocker.clone(), - next_safe_move: proof.next_safe_move.clone(), + current_gate: "historical-only".to_string(), + blocker: "canonical-frontier-workflow-required".to_string(), + next_safe_move: "Canonical frontier workflow required; historical record grants no action." + .to_string(), changed_path_count: proof.changed_paths.len(), commit_sha: proof.commit_sha.clone(), soul_verdict: proof.soul_verdict.clone(), @@ -5460,18 +5370,18 @@ fn repo_work_readiness_row( readiness_id: report.readiness_id.clone(), workspace: report.workspace.clone(), item: report.item.clone(), - status: report.status.clone(), - missing_required_count: report.missing_required_count, - satisfied_required_count: report.satisfied_required_count, + status: "historical-only".to_string(), + missing_required_count: 1, + satisfied_required_count: 0, readiness_receipt_ref: report.readiness_receipt_ref.clone(), overview_receipt_ref: report.overview_receipt_ref.clone(), proof_bundle_id: report.proof_bundle_id.clone(), - missing_kinds: report.missing_kinds.clone(), - sight_only: report.sight_only, - readiness_approval_authorized: report.readiness_approval_authorized, - publication_authorized: report.publication_authorized, - service_lifecycle_authority: report.service_lifecycle_authority, - hands_action_authorized: report.hands_action_authorized, + missing_kinds: vec!["canonical-frontier-workflow-required".to_string()], + sight_only: true, + readiness_approval_authorized: false, + publication_authorized: false, + service_lifecycle_authority: false, + hands_action_authorized: false, private_state_exposed: report.private_state_exposed, } } @@ -6125,21 +6035,6 @@ fn load_repo_work_map_entries( Ok((latest_repo_work_map_entry, repo_work_map_entries)) } -fn latest_repo_work_map_entry_for_family( - entries: &[EpiphanyCultMeshRepoWorkMapEntry], - family: &str, -) -> Option { - entries - .iter() - .filter(|entry| entry.safe_action_family == family) - .max_by(|left, right| { - left.admitted_at - .cmp(&right.admitted_at) - .then_with(|| left.map_entry_id.cmp(&right.map_entry_id)) - }) - .cloned() -} - fn load_repo_work_public_proofs( args: &Args, ) -> Result<( @@ -6447,19 +6342,19 @@ fn load_swarm_overview_report(args: &Args) -> Result { let (repo_work_map_semantic_rows, repo_work_map_semantic_tui_rows) = repo_work_map_semantic_rows(&repo_work_map_entries); let (repo_work_map_family_lens_rows, repo_work_map_family_lens_tui_rows) = - repo_work_map_family_lens_rows(&repo_work_map_entries); + repo_work_map_family_lens_rows(&[]); let (repo_work_map_path_lens_rows, repo_work_map_path_lens_tui_rows) = - repo_work_map_path_lens_rows(&repo_work_map_entries); + repo_work_map_path_lens_rows(&[]); let (repo_work_map_branch_lens_rows, repo_work_map_branch_lens_tui_rows) = - repo_work_map_branch_lens_rows(&repo_work_map_entries); + repo_work_map_branch_lens_rows(&[]); let (repo_work_map_stage_lens_rows, repo_work_map_stage_lens_tui_rows) = - repo_work_map_stage_lens_rows(&repo_work_map_entries); + repo_work_map_stage_lens_rows(&[]); let (repo_work_map_gate_lens_rows, repo_work_map_gate_lens_tui_rows) = - repo_work_map_gate_lens_rows(&repo_work_map_entries); + repo_work_map_gate_lens_rows(&[]); let (repo_work_map_closure_rows, repo_work_map_closure_tui_rows) = - repo_work_map_closure_rows(&repo_work_map_entries); + repo_work_map_closure_rows(&[]); let (repo_work_map_acceptance_rows, repo_work_map_acceptance_tui_rows) = - repo_work_map_acceptance_rows(&repo_work_map_entries); + repo_work_map_acceptance_rows(&[]); let (repo_work_public_proof_rows, repo_work_public_proof_tui_rows) = repo_work_public_proof_rows(&repo_work_public_proofs); let (repo_work_readiness_rows, repo_work_readiness_tui_rows) = @@ -6476,9 +6371,9 @@ fn load_swarm_overview_report(args: &Args) -> Result { &service_lifecycle_attention_rows, &service_execution_failed_check_rows, &service_execution_runbook_actions, - &repo_work_overviews, - &repo_work_public_proofs, - &repo_work_readiness_reports, + &[], + &[], + &[], ); let private_state_exposed = daemon_report .rows @@ -6542,13 +6437,13 @@ fn load_swarm_overview_report(args: &Args) -> Result { .map(|entry| entry.map_entry_id.clone()); let latest_repo_work_gate = latest_repo_work_overview .as_ref() - .map(|overview| overview.current_gate.clone()); + .map(|_| "historical-only".to_string()); let latest_repo_work_blocker = latest_repo_work_overview .as_ref() - .map(|overview| overview.blocker.clone()); - let latest_repo_work_next_safe_move = latest_repo_work_overview - .as_ref() - .map(|overview| overview.next_safe_move.clone()); + .map(|_| "canonical-frontier-workflow-required".to_string()); + let latest_repo_work_next_safe_move = latest_repo_work_overview.as_ref().map(|_| { + "Canonical frontier workflow required; historical record grants no action.".to_string() + }); let latest_repo_work_public_proof = latest_repo_work_public_proof .as_ref() .map(|proof| proof.public_proof_id.clone()); @@ -7740,8 +7635,6 @@ fn load_bifrost_ledger_report(args: &Args) -> Result { &args.store, args.runtime_id.clone(), )?; - let repo_work_map_entries = - load_epiphany_cultmesh_repo_work_map_entries(&args.store, args.runtime_id.clone())?; Ok(bifrost_ledger_report( arrival_latest_intent.as_ref(), arrival_latest_publication.as_ref(), @@ -7751,7 +7644,7 @@ fn load_bifrost_ledger_report(args: &Args) -> Result { arrival_latest_metrics.as_ref(), arrival_latest_feedback.as_ref(), latest_consensus.as_ref(), - &repo_work_map_entries, + &[], )) } @@ -7768,7 +7661,7 @@ fn bifrost_ledger_report( arrival_latest_metrics: Option<&EpiphanyCultMeshBifrostMetricsReceiptEntry>, arrival_latest_feedback: Option<&EpiphanyCultMeshBifrostCollaborationFeedbackEntry>, latest_consensus: Option<&EpiphanyCultMeshImaginationConsensusReceiptEntry>, - repo_work_map_entries: &[EpiphanyCultMeshRepoWorkMapEntry], + _repo_work_map_entries: &[EpiphanyCultMeshRepoWorkMapEntry], ) -> BifrostLedgerReport { let mut rows = Vec::new(); let mut tui_rows = Vec::new(); @@ -7934,7 +7827,6 @@ fn bifrost_ledger_report( arrival_latest_metrics, arrival_latest_feedback, latest_consensus, - repo_work_map_entries, ); let closed_accounting_row_count = accounting_rows .iter() @@ -7983,13 +7875,7 @@ fn bifrost_ledger_report( arrival_latest_feedback_id: arrival_latest_feedback .map(|feedback| feedback.feedback_id.clone()), latest_consensus_receipt_id: latest_consensus.map(|receipt| receipt.receipt_id.clone()), - repo_work_accounting_request_count: repo_work_map_entries - .iter() - .filter(|entry| { - entry.safe_action_family == "repo.artifact_acceptance_request" - || entry.safe_action_family == "repo.metrics_request" - }) - .count(), + repo_work_accounting_request_count: 0, private_state_exposed, } } @@ -8029,7 +7915,6 @@ fn bifrost_accounting_rows( arrival_latest_metrics: Option<&EpiphanyCultMeshBifrostMetricsReceiptEntry>, arrival_latest_feedback: Option<&EpiphanyCultMeshBifrostCollaborationFeedbackEntry>, latest_consensus: Option<&EpiphanyCultMeshImaginationConsensusReceiptEntry>, - repo_work_map_entries: &[EpiphanyCultMeshRepoWorkMapEntry], ) -> (Vec, Vec) { let mut rows = Vec::new(); let mut tui_rows = Vec::new(); @@ -8157,15 +8042,9 @@ fn bifrost_accounting_rows( push_artifact_acceptance_accounting_row( &mut rows, &mut tui_rows, - repo_work_map_entries, arrival_latest_artifact_acceptance, ); - push_metrics_accounting_row( - &mut rows, - &mut tui_rows, - repo_work_map_entries, - arrival_latest_metrics, - ); + push_metrics_accounting_row(&mut rows, &mut tui_rows, arrival_latest_metrics); let matching_consensus = arrival_latest_feedback.and_then(|feedback| { latest_consensus.filter(|receipt| receipt.feedback_id == feedback.feedback_id) @@ -8222,44 +8101,18 @@ fn bifrost_accounting_rows( fn push_artifact_acceptance_accounting_row( rows: &mut Vec, tui_rows: &mut Vec, - repo_work_map_entries: &[EpiphanyCultMeshRepoWorkMapEntry], latest_receipt: Option<&EpiphanyCultMeshBifrostArtifactAcceptanceReceiptEntry>, ) { - let matching = repo_work_map_entries - .iter() - .filter(|entry| entry.safe_action_family == "repo.artifact_acceptance_request") - .collect::>(); - let latest_request = matching.iter().copied().max_by(|left, right| { - left.admitted_at - .cmp(&right.admitted_at) - .then_with(|| left.map_entry_id.cmp(&right.map_entry_id)) - }); - let request_private = latest_request - .map(|entry| entry.private_state_exposed) - .unwrap_or(false); let receipt_private = latest_receipt .map(|receipt| receipt.private_state_exposed) .unwrap_or(false); let review_receipt_count = latest_receipt .map(|receipt| receipt.maintainer_review_receipt_ids.len()) - .or_else(|| { - latest_request.map(|entry| { - [ - &entry.soul_verdict_receipt_id, - &entry.mind_gateway_review_id, - &entry.mind_state_commit_receipt_id, - ] - .iter() - .filter(|receipt| !receipt.trim().is_empty() && receipt.as_str() != "none") - .count() - }) - }) .unwrap_or(0); let public_artifact_count = latest_receipt .map(|receipt| receipt.changed_paths.len()) - .or_else(|| latest_request.map(|entry| entry.changed_paths.len())) .unwrap_or(0); - let private = request_private || receipt_private; + let private = receipt_private; let receipt_proof_complete = latest_receipt .map(|receipt| { !receipt.artifact_ref.trim().is_empty() @@ -8278,13 +8131,12 @@ fn push_artifact_acceptance_accounting_row( lane: "artifact-acceptance-request".to_string(), owner: "Bifrost".to_string(), status: bifrost_accounting_status( - false, - latest_request.is_some() || latest_receipt.is_some(), + receipt_proof_complete, + latest_receipt.is_some(), private, ), closure: format!( - "request={} acceptance={} requestIdentity=missing receiptProof={} review={} artifacts={}", - present_word(latest_request.is_some()), + "acceptance={} receiptProof={} review={} artifacts={}", present_word(latest_receipt.is_some()), if receipt_proof_complete { "complete" @@ -8296,23 +8148,12 @@ fn push_artifact_acceptance_accounting_row( ), ledger_entry_id: latest_receipt .map(|receipt| receipt.bifrost_ledger_entry_id.clone()) - .or_else(|| latest_request.map(|entry| entry.publication_gate.clone())) .unwrap_or_else(|| "none".to_string()), latest_receipt_id: latest_receipt .map(|receipt| receipt.receipt_id.clone()) - .or_else(|| latest_request.map(|entry| entry.mind_state_commit_receipt_id.clone())) .unwrap_or_else(|| "none".to_string()), public_ref: latest_receipt .map(|receipt| receipt.public_proof_ref.clone()) - .or_else(|| { - latest_request.map(|entry| { - if entry.commit_sha.trim().is_empty() || entry.commit_sha == "none" { - entry.branch.clone() - } else { - entry.commit_sha.clone() - } - }) - }) .unwrap_or_else(|| "none".to_string()), review_receipt_count, credit_receipt_count: 0, @@ -8325,21 +8166,8 @@ fn push_artifact_acceptance_accounting_row( fn push_metrics_accounting_row( rows: &mut Vec, tui_rows: &mut Vec, - repo_work_map_entries: &[EpiphanyCultMeshRepoWorkMapEntry], latest_receipt: Option<&EpiphanyCultMeshBifrostMetricsReceiptEntry>, ) { - let matching = repo_work_map_entries - .iter() - .filter(|entry| entry.safe_action_family == "repo.metrics_request") - .collect::>(); - let latest_request = matching.iter().copied().max_by(|left, right| { - left.admitted_at - .cmp(&right.admitted_at) - .then_with(|| left.map_entry_id.cmp(&right.map_entry_id)) - }); - let request_private = latest_request - .map(|entry| entry.private_state_exposed) - .unwrap_or(false); let receipt_private = latest_receipt .map(|receipt| receipt.private_state_exposed) .unwrap_or(false); @@ -8352,28 +8180,9 @@ fn push_metrics_accounting_row( let credit_count = latest_receipt .map(|receipt| receipt.credit_readback_receipt_ids.len()) .unwrap_or(0); - let public_artifact_count = latest_receipt - .map(|_| 1) - .or_else(|| latest_request.map(|entry| entry.changed_paths.len())) - .unwrap_or(0); - let request_review_count = latest_request - .map(|entry| { - [ - &entry.soul_verdict_receipt_id, - &entry.mind_gateway_review_id, - &entry.mind_state_commit_receipt_id, - ] - .iter() - .filter(|receipt| !receipt.trim().is_empty() && receipt.as_str() != "none") - .count() - }) - .unwrap_or(0); - let review_receipt_count = if latest_receipt.is_some() { - model_spend_count + review_load_count - } else { - request_review_count - }; - let private = request_private || receipt_private; + let public_artifact_count = latest_receipt.map(|_| 1).unwrap_or(0); + let review_receipt_count = model_spend_count + review_load_count; + let private = receipt_private; let receipt_proof_complete = latest_receipt .map(|receipt| { !receipt.artifact_acceptance_receipt_id.trim().is_empty() @@ -8418,13 +8227,12 @@ fn push_metrics_accounting_row( lane: "metrics-request".to_string(), owner: "Bifrost".to_string(), status: bifrost_accounting_status( - false, - latest_request.is_some() || latest_receipt.is_some(), + receipt_proof_complete, + latest_receipt.is_some(), private, ), closure: format!( - "request={} metrics={} requestIdentity=missing receiptProof={} modelSpend={} reviewLoad={} credit={}", - present_word(latest_request.is_some()), + "metrics={} receiptProof={} modelSpend={} reviewLoad={} credit={}", present_word(latest_receipt.is_some()), if receipt_proof_complete { "complete" @@ -8435,24 +8243,14 @@ fn push_metrics_accounting_row( review_load_count, credit_count ), - ledger_entry_id: latest_request - .map(|entry| entry.publication_gate.clone()) + ledger_entry_id: latest_receipt + .map(|receipt| receipt.artifact_acceptance_receipt_id.clone()) .unwrap_or_else(|| "none".to_string()), latest_receipt_id: latest_receipt .map(|receipt| receipt.receipt_id.clone()) - .or_else(|| latest_request.map(|entry| entry.mind_state_commit_receipt_id.clone())) .unwrap_or_else(|| "none".to_string()), public_ref: latest_receipt .map(|receipt| receipt.public_proof_ref.clone()) - .or_else(|| { - latest_request.map(|entry| { - if entry.commit_sha.trim().is_empty() || entry.commit_sha == "none" { - entry.branch.clone() - } else { - entry.commit_sha.clone() - } - }) - }) .unwrap_or_else(|| "none".to_string()), review_receipt_count, credit_receipt_count: credit_count, @@ -10056,7 +9854,6 @@ mod lifecycle_projection_tests { None, None, None, - &[], ); assert_eq!(matching[0].status, "closed"); @@ -10071,7 +9868,6 @@ mod lifecycle_projection_tests { None, None, None, - &[], ); assert_eq!(mismatched[0].status, "open"); assert!(mismatched[0].closure.contains("publication=missing")); @@ -10091,7 +9887,6 @@ mod lifecycle_projection_tests { None, Some(&feedback), Some(&matching_consensus), - &[], ); assert_eq!(matching.last().unwrap().status, "closed"); @@ -10105,7 +9900,6 @@ mod lifecycle_projection_tests { None, Some(&feedback), Some(&unrelated_consensus), - &[], ); let row = mismatched.last().unwrap(); assert_eq!(row.status, "open"); @@ -10114,48 +9908,33 @@ mod lifecycle_projection_tests { } #[test] - fn request_accounting_stays_open_without_typed_receipt_identity() { - let old_private = repo_request("repo.artifact_acceptance_request", "old", true); - let mut current = repo_request("repo.artifact_acceptance_request", "current", false); - current.admitted_at = "2026-07-13T01:00:00Z".to_string(); + fn receipt_accounting_ignores_historical_repo_work_requests() { + let historical = repo_request("repo.artifact_acceptance_request", "old", true); let artifact = artifact_receipt(); - let mut rows = Vec::new(); - let mut tui = Vec::new(); - push_artifact_acceptance_accounting_row( - &mut rows, - &mut tui, - &[old_private, current], - Some(&artifact), - ); - assert_eq!(rows[0].status, "open"); - assert!(rows[0].closure.contains("requestIdentity=missing")); - assert!(rows[0].closure.contains("receiptProof=complete")); - assert!(!rows[0].private_state_exposed); - - let request = repo_request("repo.metrics_request", "metrics", false); let metrics = metrics_receipt(); - rows.clear(); - tui.clear(); - push_metrics_accounting_row( - &mut rows, - &mut tui, - std::slice::from_ref(&request), + let (rows, _) = bifrost_accounting_rows( + None, + None, + None, + None, + Some(&artifact), Some(&metrics), + None, + None, ); - assert_eq!(rows[0].status, "open"); - assert!(rows[0].closure.contains("requestIdentity=missing")); - assert!(rows[0].closure.contains("receiptProof=complete")); + assert_eq!(rows.iter().filter(|row| row.status == "closed").count(), 2); + assert!( + rows.iter() + .any(|row| row.lane == "artifact-acceptance-request") + ); + assert!(rows.iter().any(|row| row.lane == "metrics-request")); + assert!(historical.private_state_exposed); let mut incomplete_metrics = metrics_receipt(); incomplete_metrics.token_summary_ref = None; - rows.clear(); - tui.clear(); - push_metrics_accounting_row( - &mut rows, - &mut tui, - std::slice::from_ref(&request), - Some(&incomplete_metrics), - ); + let mut rows = Vec::new(); + let mut tui = Vec::new(); + push_metrics_accounting_row(&mut rows, &mut tui, Some(&incomplete_metrics)); assert_eq!(rows[0].status, "open"); assert!(rows[0].closure.contains("receiptProof=incomplete")); } diff --git a/epiphany-core/src/bin/epiphany-work.rs b/epiphany-core/src/bin/epiphany-work.rs index 1398481e..9b05beb5 100644 --- a/epiphany-core/src/bin/epiphany-work.rs +++ b/epiphany-core/src/bin/epiphany-work.rs @@ -1,114 +1,8 @@ -use anyhow::Context; -use anyhow::Result; -use anyhow::anyhow; -use chrono::DateTime; -use chrono::Utc; -use epiphany_core::EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID; -use epiphany_core::EPIPHANY_CULTMESH_REPO_WORK_MAP_ENTRY_LATEST_KEY; -use epiphany_core::EPIPHANY_CULTMESH_REPO_WORK_MAP_ENTRY_SCHEMA_VERSION; -use epiphany_core::EPIPHANY_CULTMESH_REPO_WORK_OVERVIEW_SCHEMA_VERSION; -use epiphany_core::EPIPHANY_CULTMESH_REPO_WORK_PUBLIC_PROOF_SCHEMA_VERSION; -use epiphany_core::EPIPHANY_CULTMESH_REPO_WORK_READINESS_SCHEMA_VERSION; -use epiphany_core::EPIPHANY_CULTMESH_WEKSA_LOWERING_RECEIPT_SCHEMA_VERSION; -use epiphany_core::EpiphanyCultMeshIdunnAftercareAuditReceiptEntry; -use epiphany_core::EpiphanyCultMeshIdunnDeploymentReceiptEntry; -use epiphany_core::EpiphanyCultMeshRepoWorkMapEntry; -use epiphany_core::EpiphanyCultMeshRepoWorkOverviewEntry; -use epiphany_core::EpiphanyCultMeshRepoWorkPublicProofEntry; -use epiphany_core::EpiphanyCultMeshRepoWorkReadinessEntry; -use epiphany_core::EpiphanyCultMeshWeksaLoweringReceiptEntry; -use epiphany_core::EpiphanyRepoWorkModelingLaunchDocument; -use epiphany_core::EpiphanyWorkerLaunchDocument; -use epiphany_core::HANDS_ACTION_INTENT_SCHEMA_VERSION; -use epiphany_core::HANDS_COMMAND_RECEIPT_TYPE; -use epiphany_core::HANDS_COMMIT_RECEIPT_TYPE; -use epiphany_core::HANDS_PATCH_RECEIPT_TYPE; -use epiphany_core::HandsActionIntent; -use epiphany_core::MIND_GATEWAY_REVIEW_SCHEMA_VERSION; -use epiphany_core::MindGatewayDecision; -use epiphany_core::MindGatewayReview; -use epiphany_core::PersonaMemoryCacheConfig; -use epiphany_core::REPO_WORK_HANDS_GRANT_SCHEMA_VERSION; -use epiphany_core::REPO_WORK_MAP_ENTRY_SCHEMA_VERSION; -use epiphany_core::REPO_WORK_MODELING_OUTPUT_CONTRACT_ID; -use epiphany_core::REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION; -use epiphany_core::REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION; -use epiphany_core::RepoWorkHandsGrant; -use epiphany_core::RepoWorkMapEntry; -use epiphany_core::RepoWorkModelingRequest; -use epiphany_core::RepoWorkModelingRoute; -use epiphany_core::RepoWorkPlanAdoptionDecision; -use epiphany_core::RuntimeSpineHeartbeatJobOptions; -use epiphany_core::RuntimeSpineInitOptions; -use epiphany_core::SOUL_VERDICT_RECEIPT_SCHEMA_VERSION; -use epiphany_core::SoulVerdictReceipt; -use epiphany_core::WeksaInterlinguaInput; -use epiphany_core::WeksaSpeakerContext; -use epiphany_core::advance_repo_work_modeling_route; -use epiphany_core::build_weksa_interlingua_packet; -use epiphany_core::build_weksa_target_lowering_request; -use epiphany_core::commit_initial_repo_work_modeling_route; -use epiphany_core::commit_repo_work_hands_grant; -use epiphany_core::commit_repo_work_map_admission; -use epiphany_core::default_launch_organ_contract; -use epiphany_core::hands_action_review_for_intent; -use epiphany_core::hands_command_receipt_for_review; -use epiphany_core::hands_commit_receipt_for_review; -use epiphany_core::hands_patch_receipt_for_review; -use epiphany_core::initialize_runtime_spine; -use epiphany_core::load_agent_memory_entry_for_role; -use epiphany_core::load_epiphany_cultmesh_idunn_aftercare_audit_receipt; -use epiphany_core::load_epiphany_cultmesh_idunn_deployment_receipt; -use epiphany_core::load_epiphany_cultmesh_repo_work_overviews; -use epiphany_core::load_epiphany_cultmesh_swarm_brake; -use epiphany_core::load_latest_epiphany_cultmesh_idunn_aftercare_audit_receipt; -use epiphany_core::load_latest_epiphany_cultmesh_idunn_deployment_receipt; -use epiphany_core::load_latest_epiphany_cultmesh_repo_work_overview; -use epiphany_core::memory_graph_from_agent_memories; -use epiphany_core::mind_state_commit_receipt; -use epiphany_core::open_runtime_spine_heartbeat_job; -use epiphany_core::plan_memory_graph_context_cut; -use epiphany_core::put_hands_action_intent; -use epiphany_core::put_hands_action_review; -use epiphany_core::put_hands_command_receipt; -use epiphany_core::put_hands_commit_receipt; -use epiphany_core::put_hands_patch_receipt; -use epiphany_core::put_soul_verdict_receipt; -use epiphany_core::put_substrate_gate_repo_access_grant_receipt; -use epiphany_core::record_weksa_target_lowering_receipt; -use epiphany_core::render_persona_memory_recall_with_cache; -use epiphany_core::runtime_hands_action_intent; -use epiphany_core::runtime_hands_action_review; -use epiphany_core::runtime_hands_commit_receipt; -use epiphany_core::runtime_job_snapshot; -use epiphany_core::runtime_repo_work_hands_grant; -use epiphany_core::runtime_repo_work_map_entry; -use epiphany_core::runtime_repo_work_modeling_finding; -use epiphany_core::runtime_repo_work_modeling_request; -use epiphany_core::runtime_repo_work_modeling_route; -use epiphany_core::runtime_repo_work_plan_adoption_review; -use epiphany_core::substrate_gate_repo_work_planning_grant; -use epiphany_core::validate_hands_action_authority; -use epiphany_core::write_epiphany_cultmesh_repo_work_map_entry; -use epiphany_core::write_epiphany_cultmesh_repo_work_overview; -use epiphany_core::write_epiphany_cultmesh_repo_work_public_proof; -use epiphany_core::write_epiphany_cultmesh_repo_work_readiness; -use epiphany_core::write_epiphany_cultmesh_weksa_lowering_receipt; -use epiphany_state_model::EpiphanyMemoryContextQuery; -use epiphany_state_model::EpiphanyMemoryProfile; -use serde_json::Value; -use serde_json::json; -use sha2::Digest; -use sha2::Sha256; -use std::env; -use std::fs; -use std::path::Path; -use std::path::PathBuf; -use std::process::Command; +use anyhow::{Result, anyhow}; +use serde_json::{Value, json}; +use std::{env, path::PathBuf}; -#[path = "epiphany_work/closure_contracts.rs"] -mod closure_contracts; -use closure_contracts::*; +const HISTORICAL_REASON: &str = "canonical frontier workflow required"; fn main() -> Result<()> { let mut args = env::args().skip(1); @@ -116,14543 +10,97 @@ fn main() -> Result<()> { print_usage(); std::process::exit(2); }; + let parsed = parse_legacy_args(args)?; let result = match command.as_str() { - "accept" => run_accept(parse_accept_args(args)?), - "persona-intake" | "intake" | "repo-persona-intake" => { - run_persona_intake(parse_persona_intake_args(args)?) + "overview" | "proof-bundle" | "status" => run_overview(parsed)?, + "accept" | "derive-plan" | "imagine" | "plan-from-pressure" | "plan" | "run" | "adopt" + | "promote" | "execute" | "exec" | "verify" | "soul-verify" | "close" | "closure" + | "verify-close" | "readiness" | "readiness-report" | "mvp-readiness" | "export-proof" + | "public-proof" | "tick" | "pulse" | "schedule" | "queue-run" | "run-queue" + | "queue-tick" | "scheduler-run" | "serve" | "loop" | "daemon" => { + return Err(canonical_frontier_required(&command)); } - "derive-plan" | "imagine" | "plan-from-pressure" => { - run_derive_plan(parse_derive_plan_args(args)?) - } - "plan" => run_plan(parse_plan_args(args)?), - "run" => run_work(parse_run_args(args)?), - "adopt" | "promote" => run_adopt(parse_adopt_args(args)?), - "execute" | "exec" => run_execute(parse_execute_args(args)?), - "verify" | "soul-verify" => run_verify(parse_close_args(args)?), - "close" | "closure" | "verify-close" => run_close(parse_close_args(args)?), - "revise-modeling" | "modeling-retry" => { - run_revise_modeling(parse_revise_modeling_args(args)?) - } - "overview" | "proof-bundle" | "status" => run_overview(parse_overview_args(args)?), - "readiness" | "readiness-report" | "mvp-readiness" => { - run_readiness(parse_readiness_args(args)?) - } - "deployment-config-audit" | "audit-deployment-config" | "idunn-deployment-audit" => { - run_deployment_config_audit(parse_deployment_config_audit_args(args)?) - } - "deployment-execution-runbook" | "idunn-deployment-runbook" | "deployment-push-runbook" => { - run_deployment_execution_runbook(parse_deployment_execution_runbook_args(args)?) - } - "deployment-aftercare-audit" | "idunn-aftercare-audit" | "deployment-receipt-audit" => { - run_deployment_aftercare_audit(parse_deployment_aftercare_audit_args(args)?) - } - "export-proof" | "public-proof" => run_export_proof(parse_export_proof_args(args)?), - "tick" | "pulse" | "schedule" => run_tick(parse_tick_args(args)?), - "queue-run" | "run-queue" | "queue-tick" | "scheduler-run" => { - run_queue(parse_queue_args(args)?) - } - "serve" | "loop" | "daemon" => run_serve(parse_serve_args(args)?), - other => Err(anyhow!("unknown epiphany-work command {other:?}")), - }?; + other => return Err(anyhow!("unknown epiphany-work command {other:?}")), + }; println!("{}", serde_json::to_string_pretty(&result)?); Ok(()) } -#[derive(Clone, Debug)] -struct AcceptArgs { - workspace: PathBuf, - epiphany_root: PathBuf, - source: String, - item: String, - summary: Option, - topic: Option, - local_verse_store: Option, - artifact_dir: Option, - runtime_id: Option, - online_receipt: Option, - eve_connection_receipt_id: Option, - public_discussion_refs: Vec, - candidate_action_refs: Vec, -} - -#[derive(Clone, Debug)] -struct PersonaIntakeArgs { - workspace: PathBuf, - epiphany_root: PathBuf, - item: String, - message: String, - topic: Option, - local_verse_store: Option, - artifact_dir: Option, - runtime_id: Option, - online_receipt: Option, - mood: String, -} - -#[derive(Clone, Debug)] -struct RunArgs { - workspace: PathBuf, - epiphany_root: PathBuf, +#[derive(Debug, Default)] +struct LegacyArgs { + workspace: Option, item: Option, - accept_receipt: Option, - runtime_store: Option, - artifact_dir: Option, - requested_paths: Vec, } -#[derive(Clone, Debug)] -struct PlanArgs { - workspace: PathBuf, - item: Option, - accept_receipt: Option, - artifact_dir: Option, - objective: String, - plan_summary: String, - command: String, - changed_paths: Vec, - commit_message: String, - adoption_evidence_refs: Vec, - verification_asks: Vec, - stop_conditions: Vec, - rollback_hints: Vec, -} - -#[derive(Clone, Debug)] -struct DerivePlanArgs { - workspace: PathBuf, - item: Option, - accept_receipt: Option, - artifact_dir: Option, - target_path: Option, - action_family: String, - model_ref: Option, - model_authored: bool, - action_summary: Option, - verification_asks: Vec, - stop_conditions: Vec, - escalation_reasons: Vec, - assumptions: Vec, - constraints: Vec, - non_goals: Vec, - open_questions: Vec, - decision_points: Vec, - evidence_needs: Vec, -} - -#[derive(Clone, Debug)] -struct PlanReceiptInputs { - objective: String, - plan_summary: String, - command: String, - changed_paths: Vec, - commit_message: String, - adoption_evidence_refs: Vec, - verification_asks: Vec, - stop_conditions: Vec, - rollback_hints: Vec, - derivation: Option, -} - -#[derive(Clone, Debug)] -struct AdoptArgs { - workspace: PathBuf, - item: Option, - run_receipt: Option, - plan_receipt: Option, - runtime_store: Option, - artifact_dir: Option, - mind_review_id: String, -} - -#[derive(Clone, Debug)] -struct ExecuteArgs { - workspace: PathBuf, - epiphany_root: PathBuf, - item: Option, - adopt_receipt: Option, - plan_receipt: Option, - runtime_store: Option, - artifact_dir: Option, - command: Option, - changed_paths: Vec, - commit_message: Option, - summary: Option, -} - -#[derive(Clone, Debug)] -struct CloseArgs { - workspace: PathBuf, - item: Option, - execute_receipt: Option, - runtime_store: Option, - artifact_dir: Option, -} - -#[derive(Clone, Debug)] -struct ReviseModelingArgs { - workspace: PathBuf, - item: String, - runtime_store: Option, - rationale: String, - review_ref: String, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum ClosurePhase { - SoulOnly, - Full, -} - -#[derive(Clone, Debug)] -struct OverviewArgs { - workspace: PathBuf, - item: Option, - accept_receipt: Option, - artifact_dir: Option, - write_receipt: bool, -} - -#[derive(Clone, Debug)] -struct ReadinessArgs { - workspace: PathBuf, - item: Option, - accept_receipt: Option, - artifact_dir: Option, - public_proof: Option, - idunn_lifecycle_receipt: Option, - tool_directory_receipt: Option, - deployment_aftercare_audit_receipt_ref: Option, - write_receipt: bool, -} - -#[derive(Clone, Debug)] -struct DeploymentConfigAuditArgs { - workspace: PathBuf, - artifact_dir: Option, - write_receipt: bool, -} - -#[derive(Clone, Debug)] -struct DeploymentExecutionRunbookArgs { - workspace: PathBuf, - artifact_dir: Option, - remote: String, - write_receipt: bool, -} - -#[derive(Clone, Debug)] -struct DeploymentAftercareAuditArgs { - workspace: PathBuf, - artifact_dir: Option, - local_verse_store: Option, - runtime_id: String, - runbook_receipt: Option, - idunn_deployment_receipt_ref: Option, - aftercare_audit_receipt_ref: Option, - write_receipt: bool, -} - -#[derive(Clone, Debug)] -struct ExportProofArgs { - workspace: PathBuf, - item: Option, - accept_receipt: Option, - artifact_dir: Option, - output: Option, - local_verse_store: Option, - runtime_id: String, -} - -#[derive(Clone, Debug)] -struct TickArgs { - workspace: PathBuf, - epiphany_root: PathBuf, - item: Option, - local_verse_store: Option, - artifact_dir: Option, - runtime_store: Option, - cooldown_seconds: u64, - active_timeout_seconds: u64, - dry_run: bool, -} - -#[derive(Clone, Debug)] -struct QueueArgs { - workspace: PathBuf, - epiphany_root: PathBuf, - local_verse_store: Option, - artifact_dir: Option, - runtime_store: Option, - runtime_id: String, - max_items: u64, - cooldown_seconds: u64, - active_timeout_seconds: u64, - dry_run: bool, -} - -#[derive(Clone, Debug)] -struct ServeArgs { - tick: TickArgs, - scheduler_id: String, - loop_interval_seconds: u64, - max_iterations: u64, -} - -fn parse_accept_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut epiphany_root = None; - let mut source = None; - let mut item = None; - let mut summary = None; - let mut topic = None; - let mut local_verse_store = None; - let mut artifact_dir = None; - let mut runtime_id = None; - let mut online_receipt = None; - let mut eve_connection_receipt_id = None; - let mut public_discussion_refs = Vec::new(); - let mut candidate_action_refs = Vec::new(); - +fn parse_legacy_args(args: impl Iterator) -> Result { + let mut parsed = LegacyArgs::default(); let mut args = args.peekable(); while let Some(arg) = args.next() { match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--epiphany-root" => epiphany_root = Some(take_path(&mut args, "--epiphany-root")?), - "--from" => source = Some(take_string(&mut args, "--from")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--summary" => summary = Some(take_string(&mut args, "--summary")?), - "--topic" => topic = Some(take_string(&mut args, "--topic")?), - "--local-verse-store" | "--store" => { - local_verse_store = Some(take_path(&mut args, "--local-verse-store")?); + "--workspace" => { + parsed.workspace = Some(PathBuf::from(required_value(&mut args, &arg)?)) } - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--runtime-id" => runtime_id = Some(take_string(&mut args, "--runtime-id")?), - "--online-receipt" => online_receipt = Some(take_path(&mut args, "--online-receipt")?), - "--eve-connection-receipt-id" => { - eve_connection_receipt_id = - Some(take_string(&mut args, "--eve-connection-receipt-id")?); - } - "--public-discussion-ref" | "--public-ref" => { - public_discussion_refs.push(take_string(&mut args, "--public-discussion-ref")?); - } - "--candidate-action-ref" | "--candidate-ref" => { - candidate_action_refs.push(take_string(&mut args, "--candidate-action-ref")?); - } - other => return Err(anyhow!("unexpected accept argument {other:?}")), - } - } - let source = source.context("missing --from persona-or-bifrost")?; - if !matches!( - source.as_str(), - "persona" | "bifrost" | "persona-or-bifrost" - ) { - return Err(anyhow!( - "--from must be persona, bifrost, or persona-or-bifrost" - )); - } - Ok(AcceptArgs { - workspace: workspace.context("missing --workspace")?, - epiphany_root: epiphany_root - .unwrap_or(env::current_dir().context("failed to resolve current directory")?), - source, - item: item.context("missing --item")?, - summary, - topic, - local_verse_store, - artifact_dir, - runtime_id, - online_receipt, - eve_connection_receipt_id, - public_discussion_refs, - candidate_action_refs, - }) -} - -fn parse_persona_intake_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut epiphany_root = None; - let mut item = None; - let mut message = None; - let mut topic = None; - let mut local_verse_store = None; - let mut artifact_dir = None; - let mut runtime_id = None; - let mut online_receipt = None; - let mut mood = "attentive".to_string(); - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--epiphany-root" => epiphany_root = Some(take_path(&mut args, "--epiphany-root")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--message" | "--content" | "--persona-input" => { - message = Some(take_string(&mut args, "--message")?); - } - "--topic" => topic = Some(take_string(&mut args, "--topic")?), - "--local-verse-store" | "--store" => { - local_verse_store = Some(take_path(&mut args, "--local-verse-store")?); - } - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--runtime-id" => runtime_id = Some(take_string(&mut args, "--runtime-id")?), - "--online-receipt" => online_receipt = Some(take_path(&mut args, "--online-receipt")?), - "--mood" => mood = take_string(&mut args, "--mood")?, - other => return Err(anyhow!("unexpected persona-intake argument {other:?}")), - } - } - Ok(PersonaIntakeArgs { - workspace: workspace.context("missing --workspace")?, - epiphany_root: epiphany_root - .unwrap_or(env::current_dir().context("failed to resolve current directory")?), - item: item.context("missing --item")?, - message: message.context("missing --message")?, - topic, - local_verse_store, - artifact_dir, - runtime_id, - online_receipt, - mood, - }) -} - -fn parse_run_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut epiphany_root = None; - let mut item = None; - let mut accept_receipt = None; - let mut runtime_store = None; - let mut artifact_dir = None; - let mut requested_paths = Vec::new(); - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--epiphany-root" => epiphany_root = Some(take_path(&mut args, "--epiphany-root")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--accept-receipt" => accept_receipt = Some(take_path(&mut args, "--accept-receipt")?), - "--runtime-store" => runtime_store = Some(take_path(&mut args, "--runtime-store")?), - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--path" | "--requested-path" => { - requested_paths.push(take_string(&mut args, "--requested-path")?); - } - other => return Err(anyhow!("unexpected run argument {other:?}")), - } - } - Ok(RunArgs { - workspace: workspace.context("missing --workspace")?, - epiphany_root: epiphany_root - .unwrap_or(env::current_dir().context("failed to resolve current directory")?), - item, - accept_receipt, - runtime_store, - artifact_dir, - requested_paths, - }) -} - -fn parse_plan_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut item = None; - let mut accept_receipt = None; - let mut artifact_dir = None; - let mut objective = None; - let mut plan_summary = None; - let mut command = None; - let mut changed_paths = Vec::new(); - let mut commit_message = None; - let mut adoption_evidence_refs = Vec::new(); - let mut verification_asks = Vec::new(); - let mut stop_conditions = Vec::new(); - let mut rollback_hints = Vec::new(); - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--accept-receipt" => accept_receipt = Some(take_path(&mut args, "--accept-receipt")?), - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--objective" => objective = Some(take_string(&mut args, "--objective")?), - "--plan-summary" | "--summary" => { - plan_summary = Some(take_string(&mut args, "--plan-summary")?); - } - "--command" => command = Some(take_string(&mut args, "--command")?), - "--changed-path" | "--path" | "--requested-path" => { - changed_paths.push(take_string(&mut args, "--changed-path")?); - } - "--commit-message" => { - commit_message = Some(take_string(&mut args, "--commit-message")?); - } - "--adoption-evidence-ref" | "--evidence-ref" => { - adoption_evidence_refs.push(take_string(&mut args, "--adoption-evidence-ref")?); - } - "--verification-ask" => { - verification_asks.push(take_string(&mut args, "--verification-ask")?); - } - "--stop-condition" => { - stop_conditions.push(take_string(&mut args, "--stop-condition")?); - } - "--rollback-hint" => { - rollback_hints.push(take_string(&mut args, "--rollback-hint")?); - } - other => return Err(anyhow!("unexpected plan argument {other:?}")), - } - } - if changed_paths.is_empty() { - return Err(anyhow!( - "plan requires at least one --changed-path for the future Hands gate" - )); - } - Ok(PlanArgs { - workspace: workspace.context("missing --workspace")?, - item, - accept_receipt, - artifact_dir, - objective: objective.context("missing --objective")?, - plan_summary: plan_summary.context("missing --plan-summary")?, - command: command.context("missing --command")?, - changed_paths, - commit_message: commit_message.context("missing --commit-message")?, - adoption_evidence_refs: if adoption_evidence_refs.is_empty() { - vec!["imagination.plan:operator-reviewed".to_string()] - } else { - adoption_evidence_refs - }, - verification_asks: if verification_asks.is_empty() { - vec!["Soul verifies the declared changed paths and command artifacts.".to_string()] - } else { - verification_asks - }, - stop_conditions: if stop_conditions.is_empty() { - vec!["Stop if the command exits nonzero or changes paths outside the plan.".to_string()] - } else { - stop_conditions - }, - rollback_hints, - }) -} - -fn parse_derive_plan_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut item = None; - let mut accept_receipt = None; - let mut artifact_dir = None; - let mut target_path = None; - let mut action_family = "append-worklog".to_string(); - let mut model_ref = None; - let mut model_authored = false; - let mut action_summary = None; - let mut verification_asks = Vec::new(); - let mut stop_conditions = Vec::new(); - let mut escalation_reasons = Vec::new(); - let mut assumptions = Vec::new(); - let mut constraints = Vec::new(); - let mut non_goals = Vec::new(); - let mut open_questions = Vec::new(); - let mut decision_points = Vec::new(); - let mut evidence_needs = Vec::new(); - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--accept-receipt" => accept_receipt = Some(take_path(&mut args, "--accept-receipt")?), - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--target-path" | "--changed-path" | "--path" => { - target_path = Some(take_string(&mut args, "--target-path")?); - } - "--action-family" | "--family" | "--mode" => { - action_family = take_string(&mut args, "--action-family")?; - } - "--model-ref" | "--imagination-ref" => { - model_ref = Some(take_string(&mut args, "--model-ref")?); - } - "--model-authored" => model_authored = true, - "--action-summary" | "--action-item-summary" => { - action_summary = Some(take_string(&mut args, "--action-summary")?); - } - "--verification-ask" => { - verification_asks.push(take_string(&mut args, "--verification-ask")?); - } - "--stop-condition" => { - stop_conditions.push(take_string(&mut args, "--stop-condition")?); - } - "--escalation-reason" => { - escalation_reasons.push(take_string(&mut args, "--escalation-reason")?); - } - "--assumption" | "--planning-assumption" => { - assumptions.push(take_string(&mut args, "--assumption")?); - } - "--constraint" | "--planning-constraint" => { - constraints.push(take_string(&mut args, "--constraint")?); - } - "--non-goal" | "--nongoal" => { - non_goals.push(take_string(&mut args, "--non-goal")?); - } - "--open-question" => { - open_questions.push(take_string(&mut args, "--open-question")?); - } - "--decision-point" => { - decision_points.push(take_string(&mut args, "--decision-point")?); - } - "--evidence-need" | "--evidence-needed" => { - evidence_needs.push(take_string(&mut args, "--evidence-need")?); - } - other => return Err(anyhow!("unexpected derive-plan argument {other:?}")), - } - } - Ok(DerivePlanArgs { - workspace: workspace.context("missing --workspace")?, - item, - accept_receipt, - artifact_dir, - target_path, - action_family, - model_ref, - model_authored, - action_summary, - verification_asks, - stop_conditions, - escalation_reasons, - assumptions, - constraints, - non_goals, - open_questions, - decision_points, - evidence_needs, - }) -} - -fn parse_adopt_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut item = None; - let mut run_receipt = None; - let mut plan_receipt = None; - let mut runtime_store = None; - let mut artifact_dir = None; - let mut mind_review_id = None; - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--run-receipt" => run_receipt = Some(take_path(&mut args, "--run-receipt")?), - "--from-plan" | "--plan-receipt" => { - plan_receipt = Some(take_path(&mut args, "--from-plan")?); - } - "--runtime-store" => runtime_store = Some(take_path(&mut args, "--runtime-store")?), - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--mind-review-id" => { - mind_review_id = Some(take_string(&mut args, "--mind-review-id")?) - } - other => return Err(anyhow!("unexpected adopt argument {other:?}")), - } - } - Ok(AdoptArgs { - workspace: workspace.context("missing --workspace")?, - item, - run_receipt, - plan_receipt, - runtime_store, - artifact_dir, - mind_review_id: mind_review_id.context("adopt requires --mind-review-id")?, - }) -} - -fn parse_execute_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut epiphany_root = None; - let mut item = None; - let mut adopt_receipt = None; - let mut plan_receipt = None; - let mut runtime_store = None; - let mut artifact_dir = None; - let mut command = None; - let mut changed_paths = Vec::new(); - let mut commit_message = None; - let mut summary = None; - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--epiphany-root" => epiphany_root = Some(take_path(&mut args, "--epiphany-root")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--adopt-receipt" => adopt_receipt = Some(take_path(&mut args, "--adopt-receipt")?), - "--from-plan" | "--plan-receipt" => { - plan_receipt = Some(take_path(&mut args, "--from-plan")?); - } - "--runtime-store" => runtime_store = Some(take_path(&mut args, "--runtime-store")?), - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--command" => command = Some(take_string(&mut args, "--command")?), - "--changed-path" | "--path" => { - changed_paths.push(take_string(&mut args, "--changed-path")?); - } - "--commit-message" => { - commit_message = Some(take_string(&mut args, "--commit-message")?) - } - "--summary" => summary = Some(take_string(&mut args, "--summary")?), - other => return Err(anyhow!("unexpected execute argument {other:?}")), - } - } - if changed_paths.is_empty() && plan_receipt.is_none() { - return Err(anyhow!( - "execute requires at least one --changed-path or --from-plan scoped by the approved Hands gate" - )); - } - Ok(ExecuteArgs { - workspace: workspace.context("missing --workspace")?, - epiphany_root: epiphany_root - .unwrap_or(env::current_dir().context("failed to resolve current directory")?), - item, - adopt_receipt, - plan_receipt, - runtime_store, - artifact_dir, - command, - changed_paths, - commit_message, - summary, - }) -} - -fn parse_close_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut item = None; - let mut execute_receipt = None; - let mut runtime_store = None; - let mut artifact_dir = None; - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--execute-receipt" | "--from-execute" => { - execute_receipt = Some(take_path(&mut args, "--execute-receipt")?); - } - "--runtime-store" => runtime_store = Some(take_path(&mut args, "--runtime-store")?), - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - other => return Err(anyhow!("unexpected close argument {other:?}")), - } - } - Ok(CloseArgs { - workspace: workspace.context("missing --workspace")?, - item, - execute_receipt, - runtime_store, - artifact_dir, - }) -} - -fn parse_revise_modeling_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut item = None; - let mut runtime_store = None; - let mut rationale = None; - let mut review_ref = None; - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--runtime-store" => runtime_store = Some(take_path(&mut args, "--runtime-store")?), - "--rationale" => rationale = Some(take_string(&mut args, "--rationale")?), - "--review-ref" => review_ref = Some(take_string(&mut args, "--review-ref")?), - other => return Err(anyhow!("unexpected revise-modeling argument {other:?}")), - } - } - Ok(ReviseModelingArgs { - workspace: workspace.context("missing --workspace")?, - item: item.context("missing --item")?, - runtime_store, - rationale: rationale.context("missing --rationale")?, - review_ref: review_ref.context("missing --review-ref")?, - }) -} - -fn parse_overview_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut item = None; - let mut accept_receipt = None; - let mut artifact_dir = None; - let mut write_receipt = true; - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--accept-receipt" => accept_receipt = Some(take_path(&mut args, "--accept-receipt")?), - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--no-write" | "--read-only" => write_receipt = false, - other => return Err(anyhow!("unexpected overview argument {other:?}")), - } - } - Ok(OverviewArgs { - workspace: workspace.context("missing --workspace")?, - item, - accept_receipt, - artifact_dir, - write_receipt, - }) -} - -fn parse_readiness_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut item = None; - let mut accept_receipt = None; - let mut artifact_dir = None; - let mut public_proof = None; - let mut idunn_lifecycle_receipt = None; - let mut tool_directory_receipt = None; - let mut deployment_aftercare_audit_receipt_ref = None; - let mut write_receipt = true; - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--accept-receipt" => accept_receipt = Some(take_path(&mut args, "--accept-receipt")?), - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--public-proof" | "--public-proof-ref" => { - public_proof = Some(take_path(&mut args, "--public-proof")?); - } - "--idunn-lifecycle-receipt" | "--service-lifecycle-receipt" => { - idunn_lifecycle_receipt = Some(take_path(&mut args, "--idunn-lifecycle-receipt")?); - } - "--tool-directory-receipt" | "--tool-directory-ref" => { - tool_directory_receipt = Some(take_path(&mut args, "--tool-directory-receipt")?); - } - "--deployment-aftercare-audit-receipt-ref" | "--deployment-aftercare-receipt-ref" => { - deployment_aftercare_audit_receipt_ref = Some(take_string( - &mut args, - "--deployment-aftercare-audit-receipt-ref", - )?); - } - "--no-write" | "--read-only" => write_receipt = false, - other => return Err(anyhow!("unexpected readiness argument {other:?}")), - } - } - Ok(ReadinessArgs { - workspace: workspace.context("missing --workspace")?, - item, - accept_receipt, - artifact_dir, - public_proof, - idunn_lifecycle_receipt, - tool_directory_receipt, - deployment_aftercare_audit_receipt_ref, - write_receipt, - }) -} - -fn parse_deployment_config_audit_args( - args: impl Iterator, -) -> Result { - let mut workspace = None; - let mut artifact_dir = None; - let mut write_receipt = true; - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--no-write" | "--read-only" => write_receipt = false, - other => { - return Err(anyhow!( - "unexpected deployment-config-audit argument {other:?}" - )); - } - } - } - Ok(DeploymentConfigAuditArgs { - workspace: workspace.context("missing --workspace")?, - artifact_dir, - write_receipt, - }) -} - -fn parse_deployment_execution_runbook_args( - args: impl Iterator, -) -> Result { - let mut workspace = None; - let mut artifact_dir = None; - let mut remote = "origin".to_string(); - let mut write_receipt = true; - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--remote" => remote = take_string(&mut args, "--remote")?, - "--no-write" | "--read-only" => write_receipt = false, - other => { - return Err(anyhow!( - "unexpected deployment-execution-runbook argument {other:?}" - )); - } - } - } - Ok(DeploymentExecutionRunbookArgs { - workspace: workspace.context("missing --workspace")?, - artifact_dir, - remote, - write_receipt, - }) -} - -fn parse_deployment_aftercare_audit_args( - args: impl Iterator, -) -> Result { - let mut workspace = None; - let mut artifact_dir = None; - let mut local_verse_store = None; - let mut runtime_id = "repo-swarm-local".to_string(); - let mut runbook_receipt = None; - let mut idunn_deployment_receipt_ref = None; - let mut aftercare_audit_receipt_ref = None; - let mut write_receipt = true; - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--local-verse-store" | "--store" => { - local_verse_store = Some(take_path(&mut args, "--local-verse-store")?); - } - "--runtime-id" => runtime_id = take_string(&mut args, "--runtime-id")?, - "--runbook-receipt" => { - runbook_receipt = Some(take_path(&mut args, "--runbook-receipt")?) - } - "--idunn-deployment-receipt-ref" | "--deployment-receipt-ref" => { - idunn_deployment_receipt_ref = - Some(take_string(&mut args, "--idunn-deployment-receipt-ref")?) - } - "--aftercare-audit-receipt-ref" | "--aftercare-receipt-ref" => { - aftercare_audit_receipt_ref = - Some(take_string(&mut args, "--aftercare-audit-receipt-ref")?) - } - "--no-write" | "--read-only" => write_receipt = false, - other => { - return Err(anyhow!( - "unexpected deployment-aftercare-audit argument {other:?}" - )); - } - } - } - Ok(DeploymentAftercareAuditArgs { - workspace: workspace.context("missing --workspace")?, - artifact_dir, - local_verse_store, - runtime_id, - runbook_receipt, - idunn_deployment_receipt_ref, - aftercare_audit_receipt_ref, - write_receipt, - }) -} - -fn parse_export_proof_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut item = None; - let mut accept_receipt = None; - let mut artifact_dir = None; - let mut output = None; - let mut local_verse_store = None; - let mut runtime_id = "repo-swarm-local".to_string(); - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--accept-receipt" => accept_receipt = Some(take_path(&mut args, "--accept-receipt")?), - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--output" | "--export-path" => output = Some(take_path(&mut args, "--output")?), - "--local-verse-store" | "--store" => { - local_verse_store = Some(take_path(&mut args, "--local-verse-store")?); - } - "--runtime-id" => runtime_id = take_string(&mut args, "--runtime-id")?, - other => return Err(anyhow!("unexpected export-proof argument {other:?}")), - } - } - Ok(ExportProofArgs { - workspace: workspace.context("missing --workspace")?, - item, - accept_receipt, - artifact_dir, - output, - local_verse_store, - runtime_id, - }) -} - -fn parse_tick_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut epiphany_root = None; - let mut item = None; - let mut local_verse_store = None; - let mut artifact_dir = None; - let mut runtime_store = None; - let mut cooldown_seconds = 0_u64; - let mut active_timeout_seconds = 900_u64; - let mut dry_run = false; - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--epiphany-root" => epiphany_root = Some(take_path(&mut args, "--epiphany-root")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--local-verse-store" | "--store" => { - local_verse_store = Some(take_path(&mut args, "--local-verse-store")?); - } - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--runtime-store" => runtime_store = Some(take_path(&mut args, "--runtime-store")?), - "--cooldown-seconds" => { - cooldown_seconds = take_u64(&mut args, "--cooldown-seconds")?; - } - "--active-timeout-seconds" => { - active_timeout_seconds = take_u64(&mut args, "--active-timeout-seconds")?; - } - "--dry-run" | "--no-execute" => dry_run = true, - other => return Err(anyhow!("unexpected tick argument {other:?}")), - } - } - Ok(TickArgs { - workspace: workspace.context("missing --workspace")?, - epiphany_root: epiphany_root - .unwrap_or(env::current_dir().context("failed to resolve current directory")?), - item, - local_verse_store, - artifact_dir, - runtime_store, - cooldown_seconds, - active_timeout_seconds, - dry_run, - }) -} - -fn parse_serve_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut epiphany_root = None; - let mut item = None; - let mut local_verse_store = None; - let mut artifact_dir = None; - let mut runtime_store = None; - let mut cooldown_seconds = 30_u64; - let mut active_timeout_seconds = 900_u64; - let mut dry_run = false; - let mut scheduler_id = "epiphany-repo-work-scheduler".to_string(); - let mut loop_interval_seconds = 30_u64; - let mut max_iterations = 0_u64; - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--epiphany-root" => epiphany_root = Some(take_path(&mut args, "--epiphany-root")?), - "--item" => item = Some(take_string(&mut args, "--item")?), - "--local-verse-store" | "--store" => { - local_verse_store = Some(take_path(&mut args, "--local-verse-store")?); - } - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--runtime-store" => runtime_store = Some(take_path(&mut args, "--runtime-store")?), - "--cooldown-seconds" => { - cooldown_seconds = take_u64(&mut args, "--cooldown-seconds")?; - } - "--active-timeout-seconds" => { - active_timeout_seconds = take_u64(&mut args, "--active-timeout-seconds")?; - } - "--scheduler-id" => scheduler_id = take_string(&mut args, "--scheduler-id")?, - "--loop-interval-seconds" | "--serve-interval-seconds" => { - loop_interval_seconds = take_u64(&mut args, "--loop-interval-seconds")?; - } - "--max-iterations" => { - max_iterations = take_u64(&mut args, "--max-iterations")?; - } - "--dry-run" | "--no-execute" => dry_run = true, - other => return Err(anyhow!("unexpected serve argument {other:?}")), - } - } - Ok(ServeArgs { - tick: TickArgs { - workspace: workspace.context("missing --workspace")?, - epiphany_root: epiphany_root - .unwrap_or(env::current_dir().context("failed to resolve current directory")?), - item, - local_verse_store, - artifact_dir, - runtime_store, - cooldown_seconds, - active_timeout_seconds, - dry_run, - }, - scheduler_id, - loop_interval_seconds, - max_iterations, - }) -} - -fn parse_queue_args(args: impl Iterator) -> Result { - let mut workspace = None; - let mut epiphany_root = None; - let mut local_verse_store = None; - let mut artifact_dir = None; - let mut runtime_store = None; - let mut runtime_id = "repo-swarm-local".to_string(); - let mut max_items = 1_u64; - let mut cooldown_seconds = 0_u64; - let mut active_timeout_seconds = 900_u64; - let mut dry_run = false; - - let mut args = args.peekable(); - while let Some(arg) = args.next() { - match arg.as_str() { - "--workspace" => workspace = Some(take_path(&mut args, "--workspace")?), - "--epiphany-root" => epiphany_root = Some(take_path(&mut args, "--epiphany-root")?), - "--local-verse-store" | "--store" => { - local_verse_store = Some(take_path(&mut args, "--local-verse-store")?); - } - "--artifact-dir" => artifact_dir = Some(take_path(&mut args, "--artifact-dir")?), - "--runtime-store" => runtime_store = Some(take_path(&mut args, "--runtime-store")?), - "--runtime-id" => runtime_id = take_string(&mut args, "--runtime-id")?, - "--max-items" => max_items = take_u64(&mut args, "--max-items")?, - "--cooldown-seconds" => { - cooldown_seconds = take_u64(&mut args, "--cooldown-seconds")?; - } - "--active-timeout-seconds" => { - active_timeout_seconds = take_u64(&mut args, "--active-timeout-seconds")?; - } - "--dry-run" | "--no-execute" => dry_run = true, - other => return Err(anyhow!("unexpected queue-run argument {other:?}")), - } - } - Ok(QueueArgs { - workspace: workspace.context("missing --workspace")?, - epiphany_root: epiphany_root - .unwrap_or(env::current_dir().context("failed to resolve current directory")?), - local_verse_store, - artifact_dir, - runtime_store, - runtime_id, - max_items, - cooldown_seconds, - active_timeout_seconds, - dry_run, - }) -} - -fn run_accept(args: AcceptArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let epiphany_root = args - .epiphany_root - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.epiphany_root.display()))?; - let manifest_path = epiphany_root.join("epiphany-core").join("Cargo.toml"); - if !manifest_path.exists() { - return Err(anyhow!( - "could not find epiphany-core manifest at {}", - manifest_path.display() - )); - } - let online_receipt_path = args.online_receipt.unwrap_or_else(|| { - workspace - .join(".epiphany") - .join("swarm-online") - .join("repo-swarm-online-receipt.json") - }); - let online_receipt = read_json(&online_receipt_path).with_context( - || "repo swarm online receipt is required; run epiphany-swarm online first", - )?; - let local_verse_store = args.local_verse_store.unwrap_or_else(|| { - path_from_json(&online_receipt, &["localVerseStore"]) - .unwrap_or_else(|| workspace.join(".epiphany").join("local-verse.ccmp")) - }); - let runtime_id = args.runtime_id.unwrap_or_else(|| { - string_from_json(&online_receipt, &["runtimeId"]) - .unwrap_or_else(|| "repo-swarm-local".to_string()) - }); - let artifact_dir = args - .artifact_dir - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - - let item_slug = sanitize(&args.item); - let source_kind = if args.source == "persona-or-bifrost" { - "persona" - } else { - args.source.as_str() - }; - let topic = args - .topic - .unwrap_or_else(|| format!("repo-work-item-{item_slug}")); - let summary = args.summary.unwrap_or_else(|| { - format!( - "Accepted repo work item {} from {} for Imagination consensus discovery.", - args.item, source_kind - ) - }); - let public_refs = if args.public_discussion_refs.is_empty() { - vec![format!("repo-work://{runtime_id}/{item_slug}")] - } else { - args.public_discussion_refs - }; - let candidate_refs = if args.candidate_action_refs.is_empty() { - vec![format!("candidate-action://{runtime_id}/{item_slug}")] - } else { - args.candidate_action_refs - }; - let feedback_id = format!("repo-work-feedback-{item_slug}"); - let consensus_receipt_id = format!("repo-work-consensus-{item_slug}"); - let eve_connection_receipt_id = args - .eve_connection_receipt_id - .unwrap_or_else(|| format!("repo-work-eve-connection-{item_slug}")); - let (source_persona_id, source_cluster_id, public_room_id) = match source_kind { - "bifrost" => ( - "gamecult.Bifrost".to_string(), - "gamecult.cluster.bifrost".to_string(), - "gamecult-local/bifrost/work-items".to_string(), - ), - _ => ( - "epiphany.Persona".to_string(), - "epiphany.cluster.persona".to_string(), - "epiphany-global/collaboration".to_string(), - ), - }; - let mut verse_args = vec![ - "collaboration-feedback".to_string(), - "--store".to_string(), - local_verse_store.display().to_string(), - "--runtime-id".to_string(), - runtime_id.clone(), - "--feedback-id".to_string(), - feedback_id.clone(), - "--receipt-id".to_string(), - consensus_receipt_id.clone(), - "--source-persona-id".to_string(), - source_persona_id, - "--source-cluster-id".to_string(), - source_cluster_id, - "--public-room-id".to_string(), - public_room_id, - "--eve-connection-receipt-id".to_string(), - eve_connection_receipt_id, - "--collaboration-topic".to_string(), - topic.clone(), - "--feedback-summary".to_string(), - summary.clone(), - "--consensus-packet-ref".to_string(), - format!("gamecult-local/imagination/consensus-packets/{feedback_id}"), - ]; - for public_ref in &public_refs { - verse_args.extend(["--public-discussion-ref".to_string(), public_ref.clone()]); - } - for candidate_ref in &candidate_refs { - verse_args.extend(["--candidate-action-ref".to_string(), candidate_ref.clone()]); - } - let feedback = cargo_json(&manifest_path, "epiphany-verse-query", &verse_args)?; - let receipt = json!({ - "schemaVersion": "epiphany.repo_work_accept_receipt.v0", - "createdAt": Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - "workspace": workspace, - "runtimeId": runtime_id, - "localVerseStore": local_verse_store, - "onlineReceiptPath": online_receipt_path, - "source": source_kind, - "item": args.item, - "topic": topic, - "summary": summary, - "feedback": { - "feedbackId": feedback["feedbackId"], - "consensusReceiptId": feedback["consensusReceiptId"], - "requestedConsensusRoute": feedback["requestedConsensusRoute"], - "consensusPacketRef": feedback["consensusPacketRef"], - "adoptionGate": feedback["adoptionGate"], - "publicDiscussionRefs": feedback["publicDiscussionRefs"], - "candidateActionRefs": feedback["candidateActionRefs"], - "privateStateIncluded": feedback["privateStateIncluded"], - "privateStateExposed": feedback["privateStateExposed"], - }, - "authority": { - "status": "accepted-for-imagination-consensus", - "handsAuthorityGranted": false, - "durableStateAdmitted": false, - "publicationAuthorized": false, - "nextGate": "mind.review_then_bifrost_adoption" - }, - "nextSafeMove": "Run epiphany-work run --workspace after Imagination/Self/Mind gates adopt a concrete action plan." - }); - let receipt_path = artifact_dir.join(format!("work-accept-{item_slug}.json")); - write_json(&receipt_path, &receipt)?; - Ok(json!({ - "schemaVersion": "epiphany.repo_work_accept.v0", - "status": "accepted-for-imagination-consensus", - "workspace": receipt["workspace"], - "runtimeId": receipt["runtimeId"], - "localVerseStore": receipt["localVerseStore"], - "receiptPath": receipt_path, - "source": receipt["source"], - "item": receipt["item"], - "feedback": receipt["feedback"], - "authority": receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": receipt["nextSafeMove"], - })) -} - -fn run_persona_intake(args: PersonaIntakeArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let epiphany_root = args - .epiphany_root - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.epiphany_root.display()))?; - let manifest_path = epiphany_root.join("epiphany-core").join("Cargo.toml"); - if !manifest_path.exists() { - return Err(anyhow!( - "could not find epiphany-core manifest at {}", - manifest_path.display() - )); - } - let online_receipt_path = args.online_receipt.clone().unwrap_or_else(|| { - workspace - .join(".epiphany") - .join("swarm-online") - .join("repo-swarm-online-receipt.json") - }); - let online_receipt = read_json(&online_receipt_path).with_context( - || "repo swarm online receipt is required; run epiphany-swarm online first", - )?; - let local_verse_store = args.local_verse_store.clone().unwrap_or_else(|| { - path_from_json(&online_receipt, &["localVerseStore"]) - .unwrap_or_else(|| workspace.join(".epiphany").join("local-verse.ccmp")) - }); - let state_dir = path_from_json(&online_receipt, &["stateDir"]) - .unwrap_or_else(|| workspace.join(".epiphany").join("state")); - let agent_store = state_dir.join("agents.msgpack"); - let runtime_id = args.runtime_id.clone().unwrap_or_else(|| { - string_from_json(&online_receipt, &["runtimeId"]) - .unwrap_or_else(|| "repo-swarm-local".to_string()) - }); - let artifact_dir = args - .artifact_dir - .clone() - .unwrap_or_else(|| workspace.join(".epiphany").join("persona-intake")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - - let item_slug = sanitize(&args.item); - let persona = cargo_json( - &manifest_path, - "epiphany-persona-discord", - &[ - "bubble".to_string(), - "--artifact-dir".to_string(), - artifact_dir.display().to_string(), - "--cultmesh-store".to_string(), - local_verse_store.display().to_string(), - "--runtime-id".to_string(), - runtime_id.clone(), - "--content".to_string(), - args.message.clone(), - "--source".to_string(), - "epiphany/Persona/repo-intake".to_string(), - "--mood".to_string(), - args.mood.clone(), - ], - )?; - let speech_audit = persona - .get("speechAudit") - .cloned() - .unwrap_or_else(|| json!({})); - let audit_id = string_from_json(&speech_audit, &["auditId"]) - .unwrap_or_else(|| format!("persona-speech-audit-{item_slug}")); - let bubble_path = string_from_json(&persona, &["bubblePath"]).unwrap_or_default(); - let content_fingerprint = - string_from_json(&speech_audit, &["contentFingerprint"]).unwrap_or_default(); - let topic = args - .topic - .clone() - .unwrap_or_else(|| format!("repo-persona-intake-{item_slug}")); - let summary = compact_text(&args.message, 480); - let memory_recall = - record_repo_persona_intake_memory_recall(&agent_store, &item_slug, &args.message); - let public_ref = format!("eve://epiphany/persona#repo-intake/{item_slug}/{audit_id}"); - let candidate_ref = format!("candidate-action://{runtime_id}/{item_slug}/{audit_id}"); - let weksa = record_repo_persona_intake_weksa( - &local_verse_store, - &runtime_id, - &item_slug, - &audit_id, - &args.message, - &public_ref, - )?; - let accept = run_accept(AcceptArgs { - workspace: workspace.clone(), - epiphany_root: epiphany_root.clone(), - source: "persona".to_string(), - item: args.item.clone(), - summary: Some(summary.clone()), - topic: Some(topic.clone()), - local_verse_store: Some(local_verse_store.clone()), - artifact_dir: Some(workspace.join(".epiphany").join("work")), - runtime_id: Some(runtime_id.clone()), - online_receipt: Some(online_receipt_path.clone()), - eve_connection_receipt_id: Some(format!("repo-persona-intake-eve-{item_slug}")), - public_discussion_refs: vec![public_ref.clone()], - candidate_action_refs: vec![candidate_ref.clone()], - })?; - let receipt = json!({ - "schemaVersion": "epiphany.repo_persona_intake_receipt.v0", - "createdAt": Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - "workspace": workspace, - "runtimeId": runtime_id, - "localVerseStore": local_verse_store, - "onlineReceiptPath": online_receipt_path, - "source": "persona", - "item": args.item, - "topic": topic, - "messageSummary": summary, - "persona": { - "bubblePath": bubble_path, - "speechAudit": speech_audit, - "contentFingerprint": content_fingerprint, - "publicDiscussionRef": public_ref, - "candidateActionRef": candidate_ref, - "memoryRecall": memory_recall, - "weksa": weksa - }, - "accept": accept, - "authority": { - "status": "accepted-for-imagination-consensus", - "personaSpeechAudited": true, - "handsAuthorityGranted": false, - "durableStateAdmitted": false, - "publicationAuthorized": false, - "privateStateExposed": false - }, - "nextSafeMove": "Run epiphany-work derive-plan --workspace --item after Imagination forms a concrete safe-family plan." - }); - let receipt_path = workspace - .join(".epiphany") - .join("work") - .join(format!("work-persona-intake-{item_slug}.json")); - write_json(&receipt_path, &receipt)?; - Ok(json!({ - "schemaVersion": "epiphany.repo_persona_intake.v0", - "status": "accepted-for-imagination-consensus", - "workspace": receipt["workspace"], - "runtimeId": receipt["runtimeId"], - "localVerseStore": receipt["localVerseStore"], - "receiptPath": receipt_path, - "item": receipt["item"], - "speechAuditId": audit_id, - "memoryRecallStatus": receipt["persona"]["memoryRecall"]["status"], - "memoryRecallCacheStatus": receipt["persona"]["memoryRecall"]["cacheStatus"], - "memoryRecallHitCount": receipt["persona"]["memoryRecall"]["hitCount"], - "interpreterDynamicRecallStatus": receipt["persona"]["memoryRecall"]["interpreterDynamicRecall"]["status"], - "interpreterDynamicRecallCacheStatus": receipt["persona"]["memoryRecall"]["interpreterDynamicRecall"]["cacheStatus"], - "interpreterDynamicRecallHitCount": receipt["persona"]["memoryRecall"]["interpreterDynamicRecall"]["hitCount"], - "weksaLoweringReceiptId": receipt["persona"]["weksa"]["receiptId"], - "bubblePath": receipt["persona"]["bubblePath"], - "acceptReceiptPath": accept["receiptPath"], - "feedback": accept["feedback"], - "authority": receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": receipt["nextSafeMove"], - })) -} - -fn record_repo_persona_intake_memory_recall( - agent_store: &Path, - item_slug: &str, - message: &str, -) -> Value { - let entry = match load_agent_memory_entry_for_role(agent_store, "Persona") { - Ok(Some(entry)) => entry, - Ok(None) => { - return json!({ - "schemaVersion": "epiphany.persona_memory_cache.v0", - "status": "unavailable", - "cacheStatus": "persona-memory-missing", - "identityId": "epiphany.Persona", - "roleId": "Persona", - "chunkCount": 0, - "hitCount": 0, - "renderedRecall": "- semantic Persona memory recall unavailable: Persona memory entry is missing", - "warnings": ["Persona memory entry is missing"], - "privateStateExposed": false, - }); - } - Err(error) => { - return json!({ - "schemaVersion": "epiphany.persona_memory_cache.v0", - "status": "unavailable", - "cacheStatus": "persona-memory-load-failed", - "identityId": "epiphany.Persona", - "roleId": "Persona", - "chunkCount": 0, - "hitCount": 0, - "renderedRecall": format!("- semantic Persona memory recall unavailable: {}", compact_text(&format!("{error:#}"), 320)), - "warnings": [format!("Persona memory load failed: {}", compact_text(&format!("{error:#}"), 240))], - "privateStateExposed": false, - }); - } - }; - - let query = format!("Repo Persona intake {item_slug}\n{message}"); - let graph = memory_graph_from_agent_memories( - "repo-persona-intake-memory", - std::slice::from_ref(&entry), - ); - let fallback = plan_memory_graph_context_cut( - &graph, - &EpiphanyMemoryContextQuery { - id: format!("repo-persona-intake-{item_slug}"), - profile: Some(EpiphanyMemoryProfile::RoleSelf), - domain_ids: Vec::new(), - node_ids: Vec::new(), - edge_ids: Vec::new(), - text: Some(query.clone()), - budget: Some(8), - }, - ); - let mut config = PersonaMemoryCacheConfig::from_env(); - config.qdrant_timeout_ms = config.qdrant_timeout_ms.min(1_000); - config.ollama_timeout_ms = config.ollama_timeout_ms.min(1_000); - let recall = render_persona_memory_recall_with_cache( - &entry, - format!("{}#Persona", agent_store.display()), - &query, - 8, - Some(&fallback), - &config, - ); - let synthetic_persona_prompt = format!( - "Repo Persona intake message:\n{}\n\nInitial semantic memory recall:\n{}", - message, recall.rendered_recall - ); - let dynamic_recall = epiphany_core::render_dynamic_persona_memory_recall_for_output( - &entry, - format!("{}#Persona", agent_store.display()), - &synthetic_persona_prompt, - message, - &recall.rendered_recall, - 8, - Some(&fallback), - &config, - ); - - json!({ - "schemaVersion": recall.schema_version, - "status": recall.status, - "cacheStatus": recall.cache_status, - "identityId": recall.identity_id, - "roleId": recall.role_id, - "chunkCount": recall.chunk_count, - "hitCount": recall.hit_count, - "renderedRecall": recall.rendered_recall, - "interpreterDynamicRecall": { - "schemaVersion": dynamic_recall.schema_version, - "status": dynamic_recall.status, - "cacheStatus": dynamic_recall.cache_status, - "identityId": dynamic_recall.identity_id, - "roleId": dynamic_recall.role_id, - "chunkCount": dynamic_recall.chunk_count, - "hitCount": dynamic_recall.hit_count, - "renderedRecall": dynamic_recall.rendered_recall, - "warnings": dynamic_recall.warnings, - "queryBasis": "candidate-say-meaning", - "authority": { - "scaffoldedFromOperatorMessage": true, - "fullAutonomousPersonaTurn": false, - "durableStateAdmitted": false, - "publicationAuthorized": false, - "privateStateExposed": false - }, - "privateStateExposed": dynamic_recall.private_state_exposed - }, - "warnings": recall.warnings, - "privateStateExposed": recall.private_state_exposed, - }) -} - -fn record_repo_persona_intake_weksa( - local_verse_store: &Path, - runtime_id: &str, - item_slug: &str, - audit_id: &str, - message: &str, - public_ref: &str, -) -> Result { - let audit_slug = sanitize(audit_id); - let packet_id = format!("weksa-packet-repo-intake-{item_slug}-{audit_slug}"); - let request_id = format!("weksa-lower-repo-intake-{item_slug}-{audit_slug}"); - let receipt_id = format!("weksa-lowering-repo-intake-{item_slug}-{audit_slug}"); - let delivery_surface = "eve://epiphany/persona"; - let target_language = "en"; - let target_register = "repo-public-intake"; - let packet = build_weksa_interlingua_packet(WeksaInterlinguaInput { - packet_id: packet_id.clone(), - source_interpreter_ref: format!("persona-intake:{runtime_id}:{item_slug}:{audit_slug}"), - source_speech_audit_ref: audit_id.to_string(), - speaker: WeksaSpeakerContext { - persona_id: "epiphany.Persona".to_string(), - display_name: "Epiphany".to_string(), - source_surface: delivery_surface.to_string(), - source_language: "en".to_string(), - utterance_state_ref: "state/agents.msgpack#Persona:utterance-state".to_string(), - }, - meaning: message.to_string(), - speech_act: "repo-intake-say".to_string(), - delivery_register: target_register.to_string(), - target_audience: "repo-public-room".to_string(), - safety_notes: vec![ - "Do not claim Hands, Bifrost, publication, merge, deployment, or service lifecycle authority.".to_string(), - "Do not expose private worker thought, raw result payloads, or private Verse state.".to_string(), - ], - })?; - let request = build_weksa_target_lowering_request( - request_id.clone(), - packet, - target_language, - target_register, - delivery_surface, - )?; - let receipt = record_weksa_target_lowering_receipt( - &request, - receipt_id.clone(), - message.to_string(), - "repo-persona-intake-local-text-lowering", - )?; - let lowered_text_preview = compact_text(&receipt.lowered_text, 480); - let cultmesh_receipt = EpiphanyCultMeshWeksaLoweringReceiptEntry { - schema_version: EPIPHANY_CULTMESH_WEKSA_LOWERING_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: receipt.receipt_id.clone(), - runtime_id: runtime_id.to_string(), - verse_id: EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID.to_string(), - packet_id: receipt.packet_id.clone(), - request_id: receipt.request_id.clone(), - persona_agent_id: request.packet.speaker.persona_id.clone(), - target_language: receipt.target_language.clone(), - target_register: receipt.target_register.clone(), - delivery_surface: receipt.delivery_surface.clone(), - lowering_method: receipt.lowering_method.clone(), - transport_authority: receipt.transport_authority.clone(), - publication_authorized: false, - lowered_text_ref: public_ref.to_string(), - lowered_text_preview, - created_at_utc: Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - private_state_exposed: false, - notes: vec![ - "Repo Persona intake routed public SAY through Weksa interlingua/lowering before any mouth transport publication.".to_string(), - ], - }; - write_epiphany_cultmesh_weksa_lowering_receipt(local_verse_store, cultmesh_receipt)?; - - Ok(json!({ - "schemaVersion": "epiphany.repo_persona_intake_weksa.v0", - "packetSchemaVersion": request.packet.schema_version, - "requestSchemaVersion": request.schema_version, - "receiptSchemaVersion": receipt.schema_version, - "cultmeshSchemaVersion": EPIPHANY_CULTMESH_WEKSA_LOWERING_RECEIPT_SCHEMA_VERSION, - "packetId": packet_id, - "requestId": request_id, - "receiptId": receipt_id, - "sourceSpeechAuditRef": audit_id, - "targetLanguage": receipt.target_language, - "targetRegister": receipt.target_register, - "deliverySurface": receipt.delivery_surface, - "loweringMethod": receipt.lowering_method, - "transportAuthority": receipt.transport_authority, - "loweredTextRef": public_ref, - "modelRequired": request.model_required, - "publicationAuthorized": false, - "privateStateExposed": false, - })) -} - -fn run_work(args: RunArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let _epiphany_root = args - .epiphany_root - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.epiphany_root.display()))?; - let accept_receipt_path = - resolve_accept_receipt(&workspace, args.item.as_deref(), args.accept_receipt)?; - let accept_receipt = read_json(&accept_receipt_path)?; - let online_receipt_path = path_from_json(&accept_receipt, &["onlineReceiptPath"]) - .unwrap_or_else(|| { - workspace - .join(".epiphany") - .join("swarm-online") - .join("repo-swarm-online-receipt.json") - }); - let online_receipt = read_json(&online_receipt_path) - .with_context(|| "repo swarm online receipt is required before work run")?; - let runtime_id = string_from_json(&accept_receipt, &["runtimeId"]) - .or_else(|| string_from_json(&online_receipt, &["runtimeId"])) - .unwrap_or_else(|| "repo-swarm-local".to_string()); - let state_dir = path_from_json(&online_receipt, &["stateDir"]) - .unwrap_or_else(|| workspace.join(".epiphany").join("state")); - let runtime_store = args - .runtime_store - .unwrap_or_else(|| state_dir.join("runtime-spine.msgpack")); - let artifact_dir = args - .artifact_dir - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - if let Some(parent) = runtime_store.parent() { - fs::create_dir_all(parent)?; - } - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - initialize_runtime_spine( - &runtime_store, - RuntimeSpineInitOptions { - runtime_id: runtime_id.clone(), - display_name: format!("Repo swarm runtime for {}", workspace.display()), - created_at: now.clone(), - }, - )?; - - let item = accept_receipt - .get("item") - .and_then(Value::as_str) - .unwrap_or("work-item") - .to_string(); - let item_slug = sanitize(&item); - let requested_paths = if args.requested_paths.is_empty() { - vec![".".to_string()] - } else { - args.requested_paths - }; - let run_id = format!("repo-work-run-{item_slug}"); - let runtime_job_id = format!("{run_id}-job"); - let substrate_grant_id = format!("{run_id}-substrate-grant"); - let intent_id = format!("{run_id}-hands-intent"); - let review_id = format!("{run_id}-hands-review"); - - let substrate_grant = substrate_gate_repo_work_planning_grant( - substrate_grant_id.clone(), - runtime_job_id.clone(), - requested_paths.clone(), - now.clone(), - ); - put_substrate_gate_repo_access_grant_receipt(&runtime_store, &substrate_grant)?; - - let intent = HandsActionIntent { - schema_version: HANDS_ACTION_INTENT_SCHEMA_VERSION.to_string(), - intent_id: intent_id.clone(), - runtime_job_id: runtime_job_id.clone(), - binding_id: "repo-work-runner".to_string(), - role: "epiphany-hands".to_string(), - authority_scope: "repo.branch_local_work".to_string(), - requested_action: "runAcceptedWorkItem".to_string(), - requested_paths: requested_paths.clone(), - substrate_gate_grant_receipt_id: substrate_grant_id.clone(), - requested_at: now.clone(), - contract: "Repo work run intent converts accepted Persona/Bifrost pressure into a bounded Hands gate; this gate is not mutation authority until reviewed as approved.".to_string(), - }; - put_hands_action_intent(&runtime_store, &intent)?; - - let review = hands_action_review_for_intent( - review_id.clone(), - &intent, - "queued-for-adoption".to_string(), - vec!["plan".to_string()], - vec![ - "Accepted work item has entered Imagination consensus discovery.".to_string(), - "Hands mutation remains blocked until Imagination/Self/Mind adopt a concrete plan and approve this gate.".to_string(), - ], - now.clone(), - ); - put_hands_action_review(&runtime_store, &review)?; - - let gate = json!({ - "intentId": intent_id, - "reviewId": review_id, - "runtimeJobId": runtime_job_id, - "substrateGateGrantReceiptId": substrate_grant_id, - "decision": review.decision, - "allowedOperations": review.allowed_operations, - "recordPassCommand": format!( - "epiphany-hands-action --store {} record-pass --intent-id {} --review-id {} --summary --changed-path --command --exit-code --commit-sha ", - runtime_store.display(), - intent.intent_id, - review.review_id - ) - }); - let receipt = json!({ - "schemaVersion": "epiphany.repo_work_run_receipt.v0", - "createdAt": now, - "workspace": workspace, - "runtimeId": runtime_id, - "runtimeStore": runtime_store, - "acceptReceiptPath": accept_receipt_path, - "onlineReceiptPath": online_receipt_path, - "item": item, - "status": "queued-for-adoption", - "authority": { - "handsAuthorityGranted": false, - "durableStateAdmitted": false, - "publicationAuthorized": false, - "mutationBlockedBy": "hands.review.decision != approved", - "nextGate": "imagination.self.mind.adoption" - }, - "handsActionGate": gate, - "nextSafeMove": "Promote this queued gate only after Imagination/Self/Mind adopt a concrete plan; epiphany-hands-action will refuse record-pass until the Hands review decision is approved." - }); - let receipt_path = artifact_dir.join(format!("work-run-{item_slug}.json")); - write_json(&receipt_path, &receipt)?; - Ok(json!({ - "schemaVersion": "epiphany.repo_work_run.v0", - "status": "queued-for-adoption", - "workspace": receipt["workspace"], - "runtimeId": receipt["runtimeId"], - "runtimeStore": receipt["runtimeStore"], - "receiptPath": receipt_path, - "item": receipt["item"], - "handsActionGate": receipt["handsActionGate"], - "authority": receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": receipt["nextSafeMove"], - })) -} - -fn run_plan(args: PlanArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let accept_receipt_path = - resolve_accept_receipt(&workspace, args.item.as_deref(), args.accept_receipt)?; - let accept_receipt = read_json(&accept_receipt_path)?; - let artifact_dir = args - .artifact_dir - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - - write_plan_receipt( - workspace, - accept_receipt_path, - &accept_receipt, - artifact_dir, - PlanReceiptInputs { - objective: args.objective, - plan_summary: args.plan_summary, - command: args.command, - changed_paths: args.changed_paths, - commit_message: args.commit_message, - adoption_evidence_refs: args.adoption_evidence_refs, - verification_asks: args.verification_asks, - stop_conditions: args.stop_conditions, - rollback_hints: args.rollback_hints, - derivation: None, - }, - ) -} - -fn run_derive_plan(args: DerivePlanArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let accept_receipt_path = - resolve_accept_receipt(&workspace, args.item.as_deref(), args.accept_receipt)?; - let accept_receipt = read_json(&accept_receipt_path)?; - let artifact_dir = args - .artifact_dir - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - - let item = accept_receipt - .get("item") - .and_then(Value::as_str) - .unwrap_or("work-item") - .to_string(); - let summary = accept_receipt - .get("summary") - .and_then(Value::as_str) - .unwrap_or("Accepted repo work item."); - let source = accept_receipt - .get("source") - .and_then(Value::as_str) - .unwrap_or("persona"); - let objective = format!( - "Respond to {source} work item {item}: {}", - compact_line(summary) - ); - let mut evidence_refs = vec![format!("accept-receipt:{}", accept_receipt_path.display())]; - if let Some(consensus_id) = - string_from_json(&accept_receipt, &["feedback", "consensusReceiptId"]) - { - evidence_refs.push(format!("imagination-consensus:{consensus_id}")); - } - let model_ref = args.model_ref; - let model_authored = args.model_authored || model_ref.is_some(); - if let Some(model_ref) = model_ref.as_ref() { - evidence_refs.push(format!("imagination-model:{model_ref}")); - } else { - evidence_refs.push(format!( - "imagination-derivation:deterministic-{}.v0", - normalize_action_family(&args.action_family)? - )); - } - let mut derived_plan = derive_safe_plan_family(DeriveSafePlanInput { - action_family: &args.action_family, - target_path: args.target_path.as_deref(), - item: &item, - summary, - source, - accept_receipt: &accept_receipt, - model_ref: model_ref.as_deref(), - model_authored, - })?; - let action_verification_asks = if args.verification_asks.is_empty() { - derived_plan.verification_asks.clone() - } else { - args.verification_asks - }; - let action_stop_conditions = if args.stop_conditions.is_empty() { - vec![ - "Stop if the command exits nonzero or changes paths outside the derived plan." - .to_string(), - ] - } else { - args.stop_conditions - }; - let action_escalation_reasons = if args.escalation_reasons.is_empty() { - vec![ - "Escalate if the accepted pressure requires paths outside the requested safe family." - .to_string(), - "Escalate if the work needs publication, merge, service lifecycle, elevation, or cross-repo authority.".to_string(), - ] - } else { - args.escalation_reasons - }; - let planning_facets = PlanningFacets::for_derive_plan( - source, - &derived_plan.safe_action_family, - &derived_plan.target_path, - args.assumptions, - args.constraints, - args.non_goals, - args.open_questions, - args.decision_points, - args.evidence_needs, - ); - let action_item_summary = args - .action_summary - .unwrap_or_else(|| derived_plan.plan_summary.clone()); - let action_items = write_imagination_action_items_receipt( - &artifact_dir, - &workspace, - &accept_receipt_path, - &accept_receipt, - ImaginationActionItemReceiptInputs { - item: &item, - source, - summary, - derive_plan_mode: &normalize_action_family(&args.action_family)?, - safe_action_family: &derived_plan.safe_action_family, - requested_paths: vec![derived_plan.target_path.clone()], - action_summary: &action_item_summary, - verification_asks: action_verification_asks.clone(), - stop_conditions: action_stop_conditions.clone(), - escalation_reasons: action_escalation_reasons, - rollback_hints: derived_plan.rollback_hints.clone(), - planning_facets: planning_facets.clone(), - model_ref: model_ref.as_deref(), - model_authored, - }, - )?; - let action_items_receipt_id = string_from_json(&action_items, &["receiptId"]) - .unwrap_or_else(|| format!("repo-work-action-items-{}", sanitize(&item))); - evidence_refs.push(format!( - "imagination-action-items:{action_items_receipt_id}" - )); - derived_plan.derivation["actionItemReceipt"] = json!({ - "receiptId": action_items_receipt_id, - "receiptPath": action_items["receiptPath"], - "schemaVersion": action_items["schemaVersion"], - "status": action_items["status"], - "modelAuthored": model_authored, - "safeActionFamily": derived_plan.safe_action_family, - "requestedPaths": [derived_plan.target_path.clone()], - "verificationAsks": action_verification_asks.clone(), - "planningFacets": planning_facets.to_json(), - }); - - write_plan_receipt( - workspace, - accept_receipt_path, - &accept_receipt, - artifact_dir, - PlanReceiptInputs { - objective, - plan_summary: derived_plan.plan_summary, - command: derived_plan.command, - changed_paths: vec![derived_plan.target_path.clone()], - commit_message: derived_plan.commit_message, - adoption_evidence_refs: evidence_refs, - verification_asks: action_verification_asks, - stop_conditions: action_stop_conditions, - rollback_hints: derived_plan.rollback_hints, - derivation: Some(derived_plan.derivation), - }, - ) -} - -struct DeriveSafePlanInput<'a> { - action_family: &'a str, - target_path: Option<&'a str>, - item: &'a str, - summary: &'a str, - source: &'a str, - accept_receipt: &'a Value, - model_ref: Option<&'a str>, - model_authored: bool, -} - -struct DerivedSafePlan { - safe_action_family: String, - target_path: String, - plan_summary: String, - command: String, - commit_message: String, - verification_asks: Vec, - rollback_hints: Vec, - derivation: Value, -} - -fn derive_safe_plan_family(input: DeriveSafePlanInput<'_>) -> Result { - let action_family = normalize_action_family(input.action_family)?; - match action_family.as_str() { - "append-worklog" => derive_append_worklog_plan(input, &action_family), - "planning-note" => derive_planning_note_plan(input, &action_family), - "checklist-note" => derive_checklist_note_plan(input, &action_family), - "section-note" | "markdown-section" | "section-update" => { - derive_section_note_plan(input, &action_family) - } - "repo-status-section" | "status-section" | "readme-status" => { - derive_repo_status_section_plan(input, &action_family) - } - "task-card" | "action-card" | "plan-card" => derive_task_card_plan(input, &action_family), - "repo-tool-request" - | "tool-request" - | "daemon-tool-request" - | "repo-daemon-tool-request" => derive_repo_tool_request_plan(input, &action_family), - "repo-collaboration-policy" | "collaboration-policy" | "repo-collab-policy" => { - derive_repo_collaboration_policy_plan(input, &action_family) - } - "repo-collaboration-topic" | "collaboration-topic" | "eve-collaboration" => { - derive_repo_collaboration_topic_plan(input, &action_family) - } - "repo-consensus-brief" | "consensus-brief" | "imagination-consensus" => { - derive_repo_consensus_brief_plan(input, &action_family) - } - "repo-interpreter-brief" | "interpreter-brief" | "mind-interpreter-brief" => { - derive_repo_interpreter_brief_plan(input, &action_family) - } - "repo-objective-draft" | "objective-draft" | "imagination-objective" => { - derive_repo_objective_draft_plan(input, &action_family) - } - "repo-adoption-request" | "adoption-request" | "mind-adoption-request" => { - derive_repo_adoption_request_plan(input, &action_family) - } - "repo-scheduling-request" | "scheduling-request" | "self-scheduling-request" => { - derive_repo_scheduling_request_plan(input, &action_family) - } - "repo-work-order" | "work-order" | "hands-work-order" => { - derive_repo_work_order_plan(input, &action_family) - } - "repo-verification-request" | "verification-request" | "soul-verification-request" => { - derive_repo_verification_request_plan(input, &action_family) - } - "repo-publication-request" | "publication-request" | "bifrost-publication-request" => { - derive_repo_publication_request_plan(input, &action_family) - } - "repo-sync-request" | "sync-request" | "upstream-sync-request" => { - derive_repo_sync_request_plan(input, &action_family) - } - "repo-maintainer-review-request" | "maintainer-review-request" | "review-request" => { - derive_repo_maintainer_review_request_plan(input, &action_family) - } - "repo-pr-request" | "pr-request" | "pull-request-request" | "github-pr-request" => { - derive_repo_pr_request_plan(input, &action_family) - } - "repo-credit-request" | "credit-request" | "bifrost-credit-request" => { - derive_repo_credit_request_plan(input, &action_family) - } - "repo-artifact-acceptance-request" - | "artifact-acceptance-request" - | "accepted-artifact-request" => { - derive_repo_artifact_acceptance_request_plan(input, &action_family) - } - "repo-metrics-request" | "metrics-request" | "accounting-request" => { - derive_repo_metrics_request_plan(input, &action_family) - } - "repo-readiness-review-request" | "readiness-review-request" | "mvp-readiness-request" => { - derive_repo_readiness_review_request_plan(input, &action_family) - } - "repo-doctrine-update-request" - | "doctrine-update-request" - | "agents-update-request" - | "repo-agents-request" => derive_repo_doctrine_update_request_plan(input, &action_family), - "repo-secret-policy-request" - | "secret-policy-request" - | "security-policy-request" - | "repo-security-request" => derive_repo_secret_policy_request_plan(input, &action_family), - "repo-dependency-policy-request" - | "dependency-policy-request" - | "dependency-policy" - | "supply-chain-policy-request" - | "repo-supply-chain-request" => { - derive_repo_dependency_policy_request_plan(input, &action_family) - } - "repo-deployment-config" - | "deployment-config" - | "idunn-deployment-config" - | "repo-deploy-config" => derive_repo_deployment_config_plan(input, &action_family), - "repo-deployment-request" - | "deployment-request" - | "idunn-deployment-request" - | "repo-deploy-request" => derive_repo_deployment_request_plan(input, &action_family), - other => Err(anyhow!( - "unsupported derive-plan action family {other:?}; supported families are append-worklog, planning-note, checklist-note, section-note, repo-status-section, task-card, repo-tool-request, repo-collaboration-policy, repo-collaboration-topic, repo-consensus-brief, repo-interpreter-brief, repo-objective-draft, repo-adoption-request, repo-scheduling-request, repo-work-order, repo-verification-request, repo-publication-request, repo-sync-request, repo-maintainer-review-request, repo-pr-request, repo-credit-request, repo-artifact-acceptance-request, repo-metrics-request, repo-readiness-review-request, repo-doctrine-update-request, repo-secret-policy-request, repo-dependency-policy-request, repo-deployment-config, and repo-deployment-request" - )), - } -} - -fn derive_append_worklog_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let target_path = - validate_plan_target_path(input.target_path.unwrap_or("EPIPHANY_WORKLOG.md"))?; - let worklog_line = format!( - "- {} [{}]: {}", - Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - input.item, - compact_line(input.summary) - ); - let command = format!( - "Add-Content -LiteralPath {} -Value {}", - powershell_single_quoted(&target_path), - powershell_single_quoted(&worklog_line) - ); - Ok(DerivedSafePlan { - safe_action_family: "repo.append_worklog".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a safe append-only worklog update from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Record repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the worklog path changed and the appended line matches the accepted pressure.".to_string(), - ], - rollback_hints: vec![ - "Remove the appended worklog line if the pressure was misinterpreted.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.append_worklog"), - }) -} - -fn derive_planning_note_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let default_target = format!("notes/epiphany-work/{}.md", sanitize(input.item)); - let target_path = validate_plan_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let lines = vec![ - format!("# Epiphany Work Note: {}", compact_line(input.item)), - String::new(), - format!("- Created: {}", Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)), - format!("- Source: {}", compact_line(input.source)), - format!("- Summary: {}", compact_line(input.summary)), - format!("- Candidate action refs: {}", compact_join(&candidate_refs)), - format!("- Public discussion refs: {}", compact_join(&public_refs)), - String::new(), - "## Imagination Plan".to_string(), - String::new(), - "- Safe action family: planning-note".to_string(), - "- Intended consequence: preserve a concrete planning note for Self adoption and later Hands work.".to_string(), - "- Authority seal: this note is branch-local planning cargo, not publication, merge, or durable Mind admission.".to_string(), - String::new(), - ]; - let command = powershell_append_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.markdown_planning_note".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a contained markdown planning note from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add planning note for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the planning note path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies no paths outside the declared planning note changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated planning note if the accepted pressure was misinterpreted.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.markdown_planning_note"), - }) -} - -fn derive_checklist_note_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let default_target = format!("notes/epiphany-work/{}-checklist.md", sanitize(input.item)); - let target_path = validate_plan_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let lines = vec![ - format!("# Epiphany Work Checklist: {}", compact_line(input.item)), - String::new(), - format!( - "- Created: {}", - Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) - ), - format!("- Source: {}", compact_line(input.source)), - format!("- Summary: {}", compact_line(input.summary)), - format!("- Candidate action refs: {}", compact_join(&candidate_refs)), - format!("- Public discussion refs: {}", compact_join(&public_refs)), - String::new(), - "## Checklist".to_string(), - String::new(), - "- [ ] Confirm the accepted pressure is represented without private-state leakage." - .to_string(), - "- [ ] Identify the branch-local files that a later Hands pass may lawfully change." - .to_string(), - "- [ ] Name the Soul check that would prove the next implementation pass.".to_string(), - "- [ ] Escalate to Bifrost/Mind instead of mutating publication, merge, service, or cross-repo state.".to_string(), - String::new(), - "## Authority".to_string(), - String::new(), - "- Safe action family: checklist-note".to_string(), - "- Intended consequence: preserve an operator-safe checklist for Self and later Hands work.".to_string(), - "- Authority seal: this checklist is branch-local planning cargo, not execution authority.".to_string(), - String::new(), - ]; - let command = powershell_append_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.checklist_note".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a contained markdown checklist from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add checklist note for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the checklist note path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies checklist items preserve branch-local scope and do not grant publication, merge, service, or cross-repo authority.".to_string(), - "Soul verifies no paths outside the declared checklist note changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated checklist note if the accepted pressure was misinterpreted.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.checklist_note"), - }) -} - -fn derive_section_note_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!("notes/epiphany-work/{item_slug}-section.md"); - let target_path = validate_markdown_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let section_name = format!("epiphany:{item_slug}"); - let start_marker = format!(""); - let end_marker = format!(""); - let lines = vec![ - start_marker.clone(), - format!("## Epiphany Managed Section: {}", compact_line(input.item)), - String::new(), - format!( - "- Updated: {}", - Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) - ), - format!("- Source: {}", compact_line(input.source)), - format!("- Summary: {}", compact_line(input.summary)), - format!("- Candidate action refs: {}", compact_join(&candidate_refs)), - format!("- Public discussion refs: {}", compact_join(&public_refs)), - String::new(), - "### Proposed Branch-Local Consequence".to_string(), - String::new(), - "- Convert the accepted pressure into a bounded repo-local documentation section." - .to_string(), - "- Preserve the section markers so later Imagination passes update this same surface instead of appending duplicate state.".to_string(), - "- Escalate if the work requires code mutation, publication, merge, service lifecycle, elevation, or cross-repo authority.".to_string(), - String::new(), - "### Verification".to_string(), - String::new(), - "- Soul verifies only the declared markdown path changed.".to_string(), - "- Soul verifies the managed section contains the accepted pressure summary and both Epiphany section markers.".to_string(), - String::new(), - "### Authority".to_string(), - String::new(), - "- Safe action family: section-note".to_string(), - "- Section id: ".to_string() + §ion_name, - "- Authority seal: this is branch-local documentation cargo, not durable Mind admission or publication.".to_string(), - end_marker.clone(), - String::new(), - ]; - let command = powershell_replace_managed_section_command( - &target_path, - &start_marker, - &end_marker, - &lines, - ); - Ok(DerivedSafePlan { - safe_action_family: "repo.markdown_managed_section".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a bounded managed markdown section from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Update managed section for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the managed markdown section path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies both Epiphany section markers are present so later runs update the same bounded section.".to_string(), - "Soul verifies no paths outside the declared markdown section target changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the managed section between its Epiphany markers if the accepted pressure was misinterpreted.".to_string(), - "Restore the prior marked section from git if a later section update regressed the note.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.markdown_managed_section"), - }) -} - -fn derive_repo_status_section_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let target_path = validate_markdown_target_path(input.target_path.unwrap_or("README.md"))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let section_name = format!("epiphany-status:{item_slug}"); - let start_marker = format!(""); - let end_marker = format!(""); - let lines = vec![ - start_marker.clone(), - format!("## Epiphany Status: {}", compact_line(input.item)), - String::new(), - format!( - "- Updated: {}", - Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true) - ), - format!("- Source: {}", compact_line(input.source)), - format!("- Summary: {}", compact_line(input.summary)), - format!("- Candidate action refs: {}", compact_join(&candidate_refs)), - format!("- Public discussion refs: {}", compact_join(&public_refs)), - String::new(), - "### Repo-Visible Consequence".to_string(), - String::new(), - "- Publish an operator-safe status section inside the owned repo Body.".to_string(), - "- Keep the section bounded by Epiphany status markers so later passes update the same surface instead of duplicating it.".to_string(), - "- Escalate if the accepted pressure requires code mutation, publication, merge, deployment, service lifecycle, elevation, or cross-repo authority.".to_string(), - String::new(), - "### Verification".to_string(), - String::new(), - "- Soul verifies only the declared README/status markdown path changed.".to_string(), - "- Soul verifies the status section contains the accepted pressure summary and both Epiphany status markers.".to_string(), - "- Soul verifies the section preserves private-state and publication seals.".to_string(), - String::new(), - "### Authority".to_string(), - String::new(), - "- Safe action family: repo-status-section".to_string(), - "- Section id: ".to_string() + §ion_name, - "- Branch local only: true".to_string(), - "- Publication authorized: false".to_string(), - "- Merge authorized: false".to_string(), - "- Service lifecycle authority: false".to_string(), - "- Cross-repo mutation: false".to_string(), - "- Private state exposed: false".to_string(), - end_marker.clone(), - String::new(), - ]; - let command = powershell_replace_managed_section_command( - &target_path, - &start_marker, - &end_marker, - &lines, - ); - Ok(DerivedSafePlan { - safe_action_family: "repo.status_section".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a repo-visible status section from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Update repo status section for work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo status section path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies both Epiphany status markers are present so later runs update the same bounded section.".to_string(), - "Soul verifies no paths outside the declared status section target changed.".to_string(), - "Soul verifies the section does not grant publication, merge, service lifecycle, elevation, cross-repo mutation, or private-state exposure.".to_string(), - ], - rollback_hints: vec![ - "Remove the managed status section between its Epiphany markers if the accepted pressure was misinterpreted.".to_string(), - "Restore the prior marked status section from git if a later status update regressed the repo-facing surface.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.status_section"), - }) -} - -fn derive_task_card_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!("notes/epiphany-work/{item_slug}-task-card.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let lines = vec![ - "# Epiphany repo work task card.".to_string(), - "# Branch-local planning cargo; not publication, merge, service, or cross-repo authority." - .to_string(), - format!("schema_version = {}", toml_basic_string("epiphany.repo_work_task_card.v0")), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.task_card") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[scope]".to_string(), - format!("target_path = {}", toml_basic_string(&target_path)), - "branch_local_only = true".to_string(), - "requires_epiphany_branch = true".to_string(), - String::new(), - "[next_action]".to_string(), - "owner = \"Self\"".to_string(), - "gate = \"Mind\"".to_string(), - "summary = \"Adopt one bounded task card before Hands lowers an executable command.\"" - .to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the task card path changed and contains the accepted pressure summary.\"," - .to_string(), - " \"Soul verifies the task card preserves branch-local authority seals and does not grant publication, merge, service lifecycle, elevation, or cross-repo authority.\"," - .to_string(), - " \"Soul verifies no paths outside the declared task card changed.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the task card if the accepted pressure was misinterpreted.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.task_card".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a structured task card from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add task card for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the task card path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the structured task card preserves branch-local scope and all authority seals.".to_string(), - "Soul verifies no paths outside the declared task card changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated task card if the accepted pressure was misinterpreted.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.task_card"), - }) -} - -fn derive_repo_tool_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/tool-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-tool-request:{item_slug}"); - let requester_body = format!("repo:{item_slug}"); - let intent_contract = "epiphany.cultmesh.daemon_tool_invocation_intent.v0"; - let receipt_contract = "epiphany.cultmesh.daemon_tool_invocation_receipt.v0"; - let lines = vec![ - "# Epiphany repo daemon tool request.".to_string(), - "# Branch-local request cargo; CultMesh carries intent and receipts, host daemons own execution.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_tool_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.tool_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - format!("requester_body = {}", toml_basic_string(&requester_body)), - "routing_owner = \"Self\"".to_string(), - "pressure_source = \"Persona\"".to_string(), - "target_directory = \"gamecult-local/daemon-tool-directory\"".to_string(), - "target_capability = \"daemon-tool-capability:selected-by-review\"".to_string(), - "operation = \"submitTypedToolIntent\"".to_string(), - String::new(), - "[cultmesh]".to_string(), - format!( - "intent_contract = {}", - toml_basic_string(intent_contract) - ), - format!( - "receipt_contract = {}", - toml_basic_string(receipt_contract) - ), - "host_daemon_owns_execution = true".to_string(), - "requester_owns_execution = false".to_string(), - "requires_host_liveness_ready = true".to_string(), - "requires_cultmesh_receipts = true".to_string(), - String::new(), - "[odin]".to_string(), - "discoverable = true".to_string(), - "preserves_provider_ownership = true".to_string(), - "private_verse_passthrough = false".to_string(), - String::new(), - "[authority]".to_string(), - "direct_tool_execution = false".to_string(), - "arbitrary_shell_authority = false".to_string(), - "hands_action_authority = false".to_string(), - "state_commit_authority = false".to_string(), - "publication_authority = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authority = false".to_string(), - "private_verse_rummaging = false".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the tool request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names CultMesh intent and receipt contracts without executing the tool.\",".to_string(), - " \"Soul verifies host daemon ownership, Odin provider ownership, and private-state seals remain intact.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the repo tool request if the accepted pressure was misderived or targets the wrong daemon capability.\"]".to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.tool_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a daemon-hosted tool request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add repo tool request for work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo tool request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request names CultMesh typed invocation contracts while leaving execution with host daemons.".to_string(), - "Soul verifies no execution, lifecycle, publication, cross-body, or private-rummaging authority was granted.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated repo tool request if the accepted pressure was misinterpreted or targets the wrong daemon capability.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.tool_request"), - }) -} - -fn derive_repo_collaboration_policy_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = ".epiphany/collaboration-policy.toml".to_string(); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let surface_id = format!("eve://epiphany/repo/{item_slug}/collaboration-policy"); - let feedback_route = format!("imagination://repo/{item_slug}/consensus-discovery"); - let lines = vec![ - "# Epiphany repo collaboration policy.".to_string(), - "# Branch-local policy cargo; it describes collaboration law without granting action authority.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_collaboration_policy.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.collaboration_policy") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[policy]".to_string(), - "status = \"proposed\"".to_string(), - "authoring_owner = \"Imagination\"".to_string(), - "required_reviewers = [\"Persona\", \"Mind\"]".to_string(), - "policy_admitted = false".to_string(), - "publication_owner = \"Bifrost\"".to_string(), - String::new(), - "[body]".to_string(), - format!("domain = {}", toml_basic_string(&format!("repo:{item_slug}"))), - "provider_owns_truth = true".to_string(), - "renderer_owns_truth = false".to_string(), - String::new(), - "[verses]".to_string(), - "private = \"epiphany-internal\"".to_string(), - "local = \"gamecult-local\"".to_string(), - "public = \"epiphany-global\"".to_string(), - "private_state_may_leave_repo = false".to_string(), - "public_projection_allowed = true".to_string(), - "local_projection_allowed = true".to_string(), - "odin_discoverable = true".to_string(), - String::new(), - "[eve]".to_string(), - format!("surface = {}", toml_basic_string(&surface_id)), - "compact_tui_required = true".to_string(), - "connection_receipt_required = true".to_string(), - "supported_actions = [\"read-queue\", \"discuss\", \"submit-feedback\"]".to_string(), - String::new(), - "[persona]".to_string(), - "public_discussion_allowed = true".to_string(), - "human_discussion_allowed = true".to_string(), - "peer_persona_discussion_allowed = true".to_string(), - "speech_audit_required = true".to_string(), - "feedback_must_route_to_imagination = true".to_string(), - String::new(), - "[imagination]".to_string(), - format!("feedback_route = {}", toml_basic_string(&feedback_route)), - "consensus_required_before_adoption = true".to_string(), - "candidate_actions_non_authoritative = true".to_string(), - "mind_adoption_required = true".to_string(), - "bifrost_publication_required = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "direct_hands_authority = false".to_string(), - "direct_mind_state_commit = false".to_string(), - "direct_publication_authority = false".to_string(), - "direct_merge_authority = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authority = false".to_string(), - "private_verse_rummaging = false".to_string(), - "requires_cultmesh_receipts = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the collaboration policy path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the policy names private/local/public Verse boundaries, Odin discovery, Eve connection receipts, Persona discussion, and Imagination feedback routing without granting action authority.\",".to_string(), - " \"Soul verifies no paths outside the declared collaboration policy changed.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the collaboration policy if the accepted pressure was misderived.\"]".to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.collaboration_policy".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a repo collaboration policy from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add repo collaboration policy for work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo collaboration policy path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the policy names Verse boundaries, Odin/Eve discovery, Persona discussion, and Imagination consensus routing while denying Hands, Mind, publication, merge, service, and cross-body authority.".to_string(), - "Soul verifies no paths outside the declared collaboration policy changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated repo collaboration policy if the accepted pressure was misinterpreted.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.collaboration_policy"), - }) -} - -fn derive_repo_collaboration_topic_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/collaboration-topics/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let topic_id = format!("repo-collaboration:{item_slug}"); - let public_room = format!("epiphany-global/persona-collaboration/{item_slug}"); - let eve_surface = format!("eve://epiphany/repo/{item_slug}/collaboration"); - let consensus_route = format!("imagination://repo/{item_slug}/consensus-discovery"); - let lines = vec![ - "# Epiphany repo collaboration topic.".to_string(), - "# Branch-local discussion cargo; not adoption, action, publication, or private-state authority.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_collaboration_topic.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.collaboration_topic") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[topic]".to_string(), - format!("id = {}", toml_basic_string(&topic_id)), - "status = \"proposed\"".to_string(), - "authoring_owner = \"Imagination\"".to_string(), - "discussion_owner = \"Persona\"".to_string(), - "publication_owner = \"Bifrost\"".to_string(), - format!("requested_public_room = {}", toml_basic_string(&public_room)), - format!("requested_eve_surface = {}", toml_basic_string(&eve_surface)), - "public_room_published = false".to_string(), - "eve_surface_published = false".to_string(), - "provider_receipt_required = true".to_string(), - "persona_discussion_allowed = true".to_string(), - "human_discussion_allowed = true".to_string(), - "agent_friendly_tui = true".to_string(), - String::new(), - "[imagination]".to_string(), - format!("consensus_route = {}", toml_basic_string(&consensus_route)), - "consensus_required_before_action = true".to_string(), - "candidate_actions_are_non_authoritative = true".to_string(), - "mind_adoption_required = true".to_string(), - "bifrost_publication_required = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "adoption_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the collaboration topic path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the topic names a public room, Eve surface, and Imagination consensus route without granting action authority.\",".to_string(), - " \"Soul verifies no paths outside the declared collaboration topic changed.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the collaboration topic manifest if the accepted pressure was misderived.\"]".to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.collaboration_topic".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a repo collaboration topic from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add collaboration topic for work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo collaboration topic path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the topic routes public Persona/human discussion to Imagination consensus without granting Hands, Mind, publication, merge, service, or cross-body authority.".to_string(), - "Soul verifies no paths outside the declared collaboration topic changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated collaboration topic manifest if the accepted pressure was misinterpreted.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.collaboration_topic"), - }) -} - -fn derive_repo_consensus_brief_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/consensus-briefs/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let brief_id = format!("repo-consensus:{item_slug}"); - let topic_ref = public_refs - .first() - .cloned() - .unwrap_or_else(|| format!("epiphany-global/persona-collaboration/{item_slug}")); - let recommended_family = "repo.task_card"; - let lines = vec![ - "# Epiphany repo consensus brief.".to_string(), - "# Branch-local Imagination cargo; not objective adoption, Hands authority, or publication." - .to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_consensus_brief.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.consensus_brief") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[consensus]".to_string(), - format!("id = {}", toml_basic_string(&brief_id)), - format!("topic_ref = {}", toml_basic_string(&topic_ref)), - "status = \"draft\"".to_string(), - "converged = false".to_string(), - "conflicts_remaining = true".to_string(), - "requires_additional_public_feedback = true".to_string(), - format!( - "recommended_next_safe_family = {}", - toml_basic_string(recommended_family) - ), - String::new(), - "[imagination]".to_string(), - "role = \"consensus-discovery\"".to_string(), - "candidate_actions_non_authoritative = true".to_string(), - "may_emit_action_items_receipt = true".to_string(), - "must_preserve_public_refs = true".to_string(), - "must_not_read_private_verses = true".to_string(), - String::new(), - "[inputs]".to_string(), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - "feedback_source = \"Persona public discussion\"".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "objective_adoption_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "mind_adoption_required = true".to_string(), - "bifrost_publication_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the consensus brief path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies candidate actions remain non-authoritative and require Mind/Bifrost gates before consequence.\",".to_string(), - " \"Soul verifies no paths outside the declared consensus brief changed.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the consensus brief if the public feedback was misderived.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.consensus_brief".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a repo consensus brief from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add consensus brief for work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo consensus brief path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the brief keeps candidate actions non-authoritative and requires Mind/Bifrost gates before consequence.".to_string(), - "Soul verifies no paths outside the declared consensus brief changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated consensus brief if the public feedback was misinterpreted.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.consensus_brief"), - }) -} - -fn derive_repo_interpreter_brief_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/interpreter-briefs/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let brief_id = format!("repo-interpreter-brief:{item_slug}"); - let candidate_families = vec![ - "repo.consensus_brief".to_string(), - "repo.objective_draft".to_string(), - "repo.adoption_request".to_string(), - "repo.work_order".to_string(), - "repo.verification_request".to_string(), - "repo.publication_request".to_string(), - ]; - let lines = vec![ - "# Epiphany repo interpreter brief.".to_string(), - "# Branch-local Mind interpretation cargo; not objective adoption, scheduling, Hands authority, or publication.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_interpreter_brief.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.interpreter_brief") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "deployment_execution_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[interpreter]".to_string(), - format!("id = {}", toml_basic_string(&brief_id)), - "status = \"awaiting-mind-interpretation\"".to_string(), - "authoring_owner = \"Imagination\"".to_string(), - "requested_interpreter = \"Mind\"".to_string(), - "interpretation_admitted = false".to_string(), - "purpose = \"public-pressure-to-action-semantics\"".to_string(), - "requires_consensus_readback = true".to_string(), - "requires_safe_family_choice = true".to_string(), - "requires_requested_paths = true".to_string(), - "requires_verification_asks = true".to_string(), - "requires_evidence_needs = true".to_string(), - "candidate_actions_non_authoritative = true".to_string(), - String::new(), - "[inputs]".to_string(), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - "private_worker_transcripts_allowed = false".to_string(), - "raw_result_payloads_allowed = false".to_string(), - String::new(), - "[semantic_checks]".to_string(), - "intent_summary_required = true".to_string(), - "scope_boundary_required = true".to_string(), - "requested_paths_required = true".to_string(), - "verification_required = true".to_string(), - "evidence_required = true".to_string(), - "rollback_required = true".to_string(), - "non_goals_required = true".to_string(), - "open_questions_required = true".to_string(), - "consensus_alignment_required = true".to_string(), - String::new(), - "[allowed_outputs]".to_string(), - format!("candidate_safe_families = {}", toml_array(&candidate_families)), - "may_request_replanning = true".to_string(), - "may_request_more_consensus = true".to_string(), - "may_adopt_objective = false".to_string(), - "may_schedule_work = false".to_string(), - "may_touch_substrate = false".to_string(), - "may_publish = false".to_string(), - "may_deploy = false".to_string(), - String::new(), - "[required_gates]".to_string(), - "imagination_consensus_required = true".to_string(), - "mind_review_required = true".to_string(), - "soul_source_grounding_required = true".to_string(), - "bifrost_publication_review_required = true".to_string(), - "hands_receipt_required_before_state_change = true".to_string(), - "substrate_receipt_required_before_mutation = true".to_string(), - "idunn_receipt_required_before_deployment = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "direct_state_commit_authorized = false".to_string(), - "objective_adoption_authorized = false".to_string(), - "self_scheduling_authorized = false".to_string(), - "substrate_access_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "shell_command_authorized = false".to_string(), - "commit_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "deployment_execution_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_worker_transcripts_allowed = false".to_string(), - "raw_result_payloads_allowed = false".to_string(), - "private_state_exposed = false".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the interpreter brief path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies Imagination authored a non-authoritative request for Mind interpretation.\",".to_string(), - " \"Soul verifies semantic checks, required gates, and authority denials are present.\",".to_string(), - " \"Soul verifies no paths outside the declared interpreter brief changed.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the interpreter brief if Imagination misrepresented the consensus or the semantic checks are incomplete.\"]".to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.interpreter_brief".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a request for Mind interpretation from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add interpreter brief for work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo interpreter brief path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the brief keeps interpretation non-authoritative and requires consensus, semantic checks, Mind review, Soul grounding, and downstream receipts.".to_string(), - "Soul verifies no paths outside the declared interpreter brief changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated interpreter brief if Imagination misrepresented the consensus.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.interpreter_brief"), - }) -} - -fn derive_repo_objective_draft_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/objective-drafts/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let draft_id = format!("repo-objective:{item_slug}"); - let lines = vec![ - "# Epiphany repo Objective Draft.".to_string(), - "# Branch-local Imagination cargo; not an adopted objective or Hands command." - .to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_objective_draft.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.objective_draft") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[draft]".to_string(), - format!("id = {}", toml_basic_string(&draft_id)), - "status = \"review-required\"".to_string(), - "owner = \"Imagination\"".to_string(), - "adoption_gate = \"Mind\"".to_string(), - "scheduler_gate = \"Self\"".to_string(), - "publication_gate = \"Bifrost\"".to_string(), - "objective_adopted = false".to_string(), - String::new(), - "[objective]".to_string(), - format!("title = {}", toml_basic_string(&compact_line(input.item))), - format!("statement = {}", toml_basic_string(&compact_line(input.summary))), - "scope = \"repo-local branch work proposal\"".to_string(), - "preferred_next_safe_family = \"repo.task_card\"".to_string(), - String::new(), - "[acceptance]".to_string(), - "criteria = [".to_string(), - " \"Mind explicitly accepts or rejects this Objective Draft before Self schedules it.\",".to_string(), - " \"Self schedules only after Mind adoption and a safe-family action plan exist.\",".to_string(), - " \"Hands acts only through a later receipt-backed plan and declared path scope.\",".to_string(), - " \"Bifrost gates publication, credit, and upstream-main sync.\"".to_string(), - "]".to_string(), - String::new(), - "[inputs]".to_string(), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - "consensus_brief_required = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "objective_adoption_authorized = false".to_string(), - "self_scheduling_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "mind_adoption_required = true".to_string(), - "bifrost_publication_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the Objective Draft path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the draft is review-required and not adopted.\",".to_string(), - " \"Soul verifies no paths outside the declared Objective Draft changed.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the Objective Draft if the consensus was misderived.\"]".to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.objective_draft".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a repo Objective Draft from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add Objective Draft for work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo Objective Draft path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the draft remains review-required, unadopted, and gated by Mind/Self/Bifrost before consequence.".to_string(), - "Soul verifies no paths outside the declared Objective Draft changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated Objective Draft if the consensus was misinterpreted.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.objective_draft"), - }) -} - -fn derive_repo_adoption_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/adoption-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-adoption-request:{item_slug}"); - let objective_draft_ref = format!(".epiphany/objective-drafts/{item_slug}.toml"); - let lines = vec![ - "# Epiphany repo adoption request.".to_string(), - "# Branch-local Mind review cargo; not state admission or scheduling authority.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_adoption_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.adoption_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-mind-review\"".to_string(), - "requested_decision = \"adopt-or-refuse-objective-draft\"".to_string(), - format!( - "objective_draft_ref = {}", - toml_basic_string(&objective_draft_ref) - ), - "mind_review_required = true".to_string(), - "mind_state_commit_required = true".to_string(), - "self_scheduling_after_mind_only = true".to_string(), - String::new(), - "[decision_contract]".to_string(), - "allowed_verdicts = [\"adopted\", \"refused\", \"needs-more-consensus\"]".to_string(), - "requires_review_finding = true".to_string(), - "requires_receipt = \"epiphany.mind.gateway_review\"".to_string(), - "requires_commit_receipt_if_adopted = \"epiphany.mind.state_commit_receipt\"".to_string(), - "does_not_modify_state = true".to_string(), - String::new(), - "[inputs]".to_string(), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - "objective_draft_required = true".to_string(), - "consensus_brief_required = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "objective_adoption_authorized = false".to_string(), - "state_commit_authorized = false".to_string(), - "self_scheduling_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the adoption request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request is awaiting Mind review and cannot commit state by itself.\",".to_string(), - " \"Soul verifies no paths outside the declared adoption request changed.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the adoption request if the Objective Draft should not be reviewed yet.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.adoption_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a Mind adoption request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add adoption request for work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo adoption request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request awaits Mind review and does not authorize state commit, scheduling, Hands action, publication, or cross-body mutation.".to_string(), - "Soul verifies no paths outside the declared adoption request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated adoption request if the Objective Draft is not ready for Mind review.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.adoption_request"), - }) -} - -fn derive_repo_scheduling_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/scheduling-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-scheduling-request:{item_slug}"); - let objective_draft_ref = format!(".epiphany/objective-drafts/{item_slug}.toml"); - let adoption_request_ref = format!(".epiphany/adoption-requests/{item_slug}.toml"); - let lines = vec![ - "# Epiphany repo scheduling request.".to_string(), - "# Branch-local Self queue cargo; inert until Mind adoption receipts exist.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_scheduling_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.scheduling_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-mind-adoption\"".to_string(), - "requested_scheduler = \"Self\"".to_string(), - format!( - "objective_draft_ref = {}", - toml_basic_string(&objective_draft_ref) - ), - format!( - "adoption_request_ref = {}", - toml_basic_string(&adoption_request_ref) - ), - "mind_adoption_receipt_required = true".to_string(), - "self_may_schedule_after_mind_only = true".to_string(), - "queue_run_allowed_after_adoption = true".to_string(), - String::new(), - "[queue]".to_string(), - "target_gate = \"repo-work-queue\"".to_string(), - "preferred_next_safe_family = \"repo.task_card\"".to_string(), - "max_items_per_pulse = 1".to_string(), - "requires_epiphany_branch = true".to_string(), - "publish_blocker = \"bifrost-publication-missing\"".to_string(), - String::new(), - "[required_receipts]".to_string(), - "mind_review = \"epiphany.mind.gateway_review\"".to_string(), - "mind_commit = \"epiphany.mind.state_commit_receipt\"".to_string(), - "expected_self_receipt = \"epiphany.repo_work_queue_selection.v0\"".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "self_scheduling_authorized = false".to_string(), - "queue_mutation_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "mind_adoption_required = true".to_string(), - "bifrost_publication_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the scheduling request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request awaits Mind adoption before Self may schedule.\",".to_string(), - " \"Soul verifies the request grants no queue mutation, Hands action, publication, or cross-body authority.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the scheduling request if Mind has not adopted the Objective Draft.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.scheduling_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a Self scheduling request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add scheduling request for work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo scheduling request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request awaits Mind adoption and does not authorize queue mutation, Hands action, publication, or cross-body mutation.".to_string(), - "Soul verifies no paths outside the declared scheduling request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated scheduling request if the Objective Draft is not adopted by Mind.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.scheduling_request"), - }) -} - -fn derive_repo_work_order_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/work-orders/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let work_order_id = format!("repo-work-order:{item_slug}"); - let objective_draft_ref = format!(".epiphany/objective-drafts/{item_slug}.toml"); - let adoption_request_ref = format!(".epiphany/adoption-requests/{item_slug}.toml"); - let scheduling_request_ref = format!(".epiphany/scheduling-requests/{item_slug}.toml"); - let lines = vec![ - "# Epiphany repo work order request.".to_string(), - "# Branch-local Hands intent cargo; not a command, patch, or commit.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_work_order.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.work_order") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[work_order]".to_string(), - format!("id = {}", toml_basic_string(&work_order_id)), - "status = \"awaiting-hands-review\"".to_string(), - "requested_owner = \"Hands\"".to_string(), - "requested_effect = \"branch-local-implementation\"".to_string(), - "implementation_intent = \"prepare a reviewable branch-local change from the adopted objective\"".to_string(), - "subgoal = \"derive the smallest coherent implementation slice that satisfies the accepted pressure\"".to_string(), - String::new(), - "[antecedents]".to_string(), - format!( - "objective_draft_ref = {}", - toml_basic_string(&objective_draft_ref) - ), - format!( - "adoption_request_ref = {}", - toml_basic_string(&adoption_request_ref) - ), - format!( - "scheduling_request_ref = {}", - toml_basic_string(&scheduling_request_ref) - ), - "mind_adoption_required = true".to_string(), - "self_queue_selection_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "substrate_gate = \"epiphany.substrate_gate.grant\"".to_string(), - "hands_intent = \"epiphany.hands.action_intent\"".to_string(), - "hands_review = \"epiphany.hands.action_review\"".to_string(), - "hands_patch = \"epiphany.hands.patch_receipt\"".to_string(), - "hands_command = \"epiphany.hands.command_receipt\"".to_string(), - "hands_commit = \"epiphany.hands.commit_receipt\"".to_string(), - "soul_verdict = \"epiphany.soul.verification_verdict\"".to_string(), - "mind_commit = \"epiphany.mind.state_commit_receipt\"".to_string(), - String::new(), - "[scope]".to_string(), - "branch_required = true".to_string(), - "allowed_branch_prefix = \"epiphany/\"".to_string(), - "requested_paths = [\"README.md\", \"notes/epiphany-work/\"]".to_string(), - "max_changed_paths = 3".to_string(), - "requires_reviewable_diff = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "substrate_access_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "shell_command_authorized = false".to_string(), - "commit_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "bifrost_publication_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the work order path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the work order awaits Hands review and grants no substrate, shell, commit, or publication authority.\",".to_string(), - " \"Soul verifies the requested scope is branch-local, bounded, and receipt-backed.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the work order if the adopted objective is not ready for Hands review.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.work_order".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a Hands work-order request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add work order for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo work order path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the work order awaits Hands review and does not authorize substrate access, shell commands, commits, publication, or cross-body mutation.".to_string(), - "Soul verifies no paths outside the declared work order changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated work order if the accepted pressure is not ready for Hands review.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.work_order"), - }) -} - -fn derive_repo_verification_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/verification-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-verification-request:{item_slug}"); - let work_order_ref = format!(".epiphany/work-orders/{item_slug}.toml"); - let lines = vec![ - "# Epiphany repo verification request.".to_string(), - "# Branch-local Soul request cargo; not a verdict or Mind admission.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_verification_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.verification_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "soul_verdict_granted = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-soul-review\"".to_string(), - "requested_owner = \"Soul\"".to_string(), - "requested_effect = \"verify-branch-local-hands-work\"".to_string(), - format!("work_order_ref = {}", toml_basic_string(&work_order_ref)), - "verification_scope = \"declared changed paths, Hands receipts, and visible repo diff\"" - .to_string(), - String::new(), - "[antecedents]".to_string(), - "substrate_gate_required = true".to_string(), - "hands_intent_required = true".to_string(), - "hands_review_required = true".to_string(), - "hands_patch_required = true".to_string(), - "hands_command_required = true".to_string(), - "hands_commit_required = true".to_string(), - "work_order_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "hands_patch = \"epiphany.hands.patch_receipt\"".to_string(), - "hands_command = \"epiphany.hands.command_receipt\"".to_string(), - "hands_commit = \"epiphany.hands.commit_receipt\"".to_string(), - "soul_verdict = \"epiphany.soul.verification_verdict\"".to_string(), - "closure_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "mind_review = \"epiphany.mind.gateway_review\"".to_string(), - "mind_commit = \"epiphany.mind.state_commit_receipt\"".to_string(), - String::new(), - "[checks]".to_string(), - "required = [".to_string(), - " \"declared-paths-match-commit\",".to_string(), - " \"hands-receipts-present\",".to_string(), - " \"visible-diff-supports-summary\",".to_string(), - " \"no-private-state-exposure\",".to_string(), - " \"publication-remains-gated\"".to_string(), - "]".to_string(), - "model_verdict_allowed = true".to_string(), - "failure_blocks_mind_admission = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "soul_verdict_authorized = false".to_string(), - "state_commit_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "rerun_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "bifrost_publication_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the verification request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names required Hands evidence but does not itself grant a verdict.\",".to_string(), - " \"Soul verifies the request grants no rerun, state commit, publication, or cross-body authority.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the verification request if no Hands consequence is ready for Soul review.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.verification_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a Soul verification request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add verification request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo verification request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request names required Hands evidence and closure checks without authorizing a verdict, rerun, state commit, publication, or cross-body mutation.".to_string(), - "Soul verifies no paths outside the declared verification request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated verification request if there is no Hands consequence ready for Soul review.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.verification_request"), - }) -} - -fn derive_repo_publication_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/publication-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-publication-request:{item_slug}"); - let verification_request_ref = format!(".epiphany/verification-requests/{item_slug}.toml"); - let lines = vec![ - "# Epiphany repo publication request.".to_string(), - "# Branch-local Bifrost request cargo; not publication, merge, or sync authority.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_publication_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.publication_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "credit_authorized = false".to_string(), - "durable_state_admitted = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-bifrost-review\"".to_string(), - "requested_owner = \"Bifrost\"".to_string(), - "requested_effect = \"publish-redacted-proof-and-route-maintainer-review\"".to_string(), - format!( - "verification_request_ref = {}", - toml_basic_string(&verification_request_ref) - ), - "publication_scope = \"redacted public proof, maintainer review, credit ledger, and upstream-main sync proof\"".to_string(), - String::new(), - "[antecedents]".to_string(), - "closure_review_required = true".to_string(), - "soul_verdict_required = true".to_string(), - "mind_commit_required = true".to_string(), - "public_proof_export_required = true".to_string(), - "private_state_redaction_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "closure_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "soul_verdict = \"epiphany.soul.verification_verdict\"".to_string(), - "mind_commit = \"epiphany.mind.state_commit_receipt\"".to_string(), - "public_proof = \"epiphany.repo_work_public_proof_bundle.v0\"".to_string(), - "bifrost_publication = \"gamecult.bifrost.public_proof_publication_receipt.v0\"" - .to_string(), - "github_publication = \"gamecult.github.publication_receipt.v0\"".to_string(), - "credit_ledger = \"gamecult.bifrost.credit_receipt.v0\"".to_string(), - "upstream_sync = \"epiphany.repo_work_upstream_main_sync.v0\"".to_string(), - String::new(), - "[public_export]".to_string(), - "redacted_only = true".to_string(), - "raw_receipts_allowed = false".to_string(), - "private_paths_allowed = false".to_string(), - "worker_thought_allowed = false".to_string(), - "operator_context_allowed = false".to_string(), - "credit_required = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "bifrost_publication_authorized = false".to_string(), - "github_publication_authorized = false".to_string(), - "credit_ledger_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "maintainer_review_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the publication request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names public proof and Bifrost receipt requirements without authorizing publication.\",".to_string(), - " \"Soul verifies raw receipts, private paths, worker thought, and operator context remain excluded from public export.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the publication request if the work is not ready for Bifrost review.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.publication_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a Bifrost publication request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add publication request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo publication request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request requires redacted public proof and Bifrost/GitHub/credit/upstream receipts without authorizing publication, merge, sync, service lifecycle, or cross-body mutation.".to_string(), - "Soul verifies no paths outside the declared publication request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated publication request if the work is not ready for Bifrost review.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.publication_request"), - }) -} - -fn derive_repo_sync_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/sync-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-sync-request:{item_slug}"); - let publication_request_ref = format!(".epiphany/publication-requests/{item_slug}.toml"); - let lines = vec![ - "# Epiphany repo upstream-main sync request.".to_string(), - "# Branch-local sync proof request cargo; not merge, push, or sync authority.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_sync_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.sync_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "merge_authorized = false".to_string(), - "push_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "durable_state_admitted = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-upstream-main-proof\"".to_string(), - "proof_owner = \"Bifrost\"".to_string(), - "requested_effect = \"prove-published-commit-contained-by-upstream-main\"".to_string(), - format!( - "publication_request_ref = {}", - toml_basic_string(&publication_request_ref) - ), - "sync_scope = \"prove maintainer-reviewed published commit is contained by upstream main\"" - .to_string(), - String::new(), - "[antecedents]".to_string(), - "publication_receipt_required = true".to_string(), - "github_publication_required = true".to_string(), - "maintainer_review_required = true".to_string(), - "credit_ledger_required = true".to_string(), - "public_proof_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "bifrost_publication = \"gamecult.bifrost.public_proof_publication_receipt.v0\"" - .to_string(), - "github_publication = \"gamecult.github.publication_receipt.v0\"".to_string(), - "maintainer_review = \"gamecult.maintainer.review_receipt.v0\"".to_string(), - "credit_ledger = \"gamecult.bifrost.credit_receipt.v0\"".to_string(), - "upstream_sync = \"epiphany.repo_work_upstream_main_sync.v0\"".to_string(), - "ancestry_proof = \"git.merge_base_is_ancestor\"".to_string(), - String::new(), - "[sync_proof]".to_string(), - "target_ref = \"origin/main\"".to_string(), - "requires_fetch_before_check = true".to_string(), - "requires_merge_base_ancestor_check = true".to_string(), - "requires_clean_public_proof_readback = true".to_string(), - "records_upstream_main_sha = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "merge_authorized = false".to_string(), - "push_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "github_publication_authorized = false".to_string(), - "credit_ledger_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "bifrost_upstream_proof_required = true".to_string(), - "maintainer_review_receipt_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the sync request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names upstream-main ancestry proof without authorizing merge, push, or sync.\",".to_string(), - " \"Soul verifies maintainer review and publication receipts are required before any upstream proof is accepted.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the sync request if Bifrost publication or maintainer review has not happened.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.sync_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived an upstream-main sync proof request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add sync request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo sync request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request requires publication, maintainer review, credit, and ancestry proof receipts without authorizing merge, push, sync, service lifecycle, or cross-body mutation.".to_string(), - "Soul verifies no paths outside the declared sync request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated sync request if the work is not ready for upstream-main proof.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.sync_request"), - }) -} - -fn derive_repo_maintainer_review_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/review-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-maintainer-review-request:{item_slug}"); - let verification_request_ref = format!(".epiphany/verification-requests/{item_slug}.toml"); - let publication_request_ref = format!(".epiphany/publication-requests/{item_slug}.toml"); - let lines = vec![ - "# Epiphany repo maintainer review request.".to_string(), - "# Branch-local human review cargo; not approval, merge, or publication authority." - .to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_maintainer_review_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.maintainer_review_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "maintainer_approval_granted = false".to_string(), - "merge_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "durable_state_admitted = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-maintainer-review\"".to_string(), - "requested_owner = \"Maintainer\"".to_string(), - "requested_effect = \"review-redacted-proof-and-branch-diff\"".to_string(), - format!( - "verification_request_ref = {}", - toml_basic_string(&verification_request_ref) - ), - format!( - "publication_request_ref = {}", - toml_basic_string(&publication_request_ref) - ), - "review_scope = \"changed paths, closure proof, public proof bundle, and Bifrost credit context\"" - .to_string(), - String::new(), - "[antecedents]".to_string(), - "closure_review_required = true".to_string(), - "soul_verdict_required = true".to_string(), - "mind_commit_required = true".to_string(), - "public_proof_required = true".to_string(), - "bifrost_publication_request_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "closure_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "soul_verdict = \"epiphany.soul.verification_verdict\"".to_string(), - "mind_commit = \"epiphany.mind.state_commit_receipt\"".to_string(), - "public_proof = \"epiphany.repo_work_public_proof_bundle.v0\"".to_string(), - "maintainer_review = \"gamecult.maintainer.review_receipt.v0\"".to_string(), - "bifrost_publication = \"gamecult.bifrost.public_proof_publication_receipt.v0\"" - .to_string(), - String::new(), - "[review_packet]".to_string(), - "requires_reviewer_identity = true".to_string(), - "requires_review_verdict = true".to_string(), - "allowed_verdicts = [\"approved\", \"changes-requested\", \"rejected\", \"needs-human-context\"]" - .to_string(), - "requires_changed_path_list = true".to_string(), - "requires_public_proof_ref = true".to_string(), - "requires_private_state_redaction_check = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "maintainer_approval_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "push_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "maintainer_response_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the maintainer review request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names reviewer identity, verdict, changed paths, and redacted proof requirements without approving or merging.\",".to_string(), - " \"Soul verifies the request grants no publication, sync, Hands, service lifecycle, or cross-body authority.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the maintainer review request if the work is not ready for human review.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.maintainer_review_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a maintainer review request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add maintainer review request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo maintainer review request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request requires reviewer identity, verdict, changed paths, redacted proof, and private-state redaction without authorizing approval, merge, publication, sync, service lifecycle, or cross-body mutation.".to_string(), - "Soul verifies no paths outside the declared maintainer review request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated maintainer review request if the work is not ready for human review.".to_string(), - ], - derivation: plan_derivation_receipt( - input, - action_family, - "repo.maintainer_review_request", - ), - }) -} - -fn derive_repo_pr_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/pr-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-pr-request:{item_slug}"); - let maintainer_review_request_ref = format!(".epiphany/review-requests/{item_slug}.toml"); - let publication_request_ref = format!(".epiphany/publication-requests/{item_slug}.toml"); - let sync_request_ref = format!(".epiphany/sync-requests/{item_slug}.toml"); - let lines = vec![ - "# Epiphany repo pull request request.".to_string(), - "# Branch-local GitHub/Bifrost request cargo; not push, PR, merge, or sync authority." - .to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_pr_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.pr_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "github_pr_authorized = false".to_string(), - "branch_push_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "durable_state_admitted = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-pr-publication-review\"".to_string(), - "routing_owner = \"Self\"".to_string(), - "publication_owner = \"Bifrost\"".to_string(), - "execution_owner = \"Hands\"".to_string(), - "provider = \"GitHub\"".to_string(), - "provider_receipt_required = true".to_string(), - "requested_effect = \"open-or-update-review-pr-from-redacted-proof-and-maintainer-context\"" - .to_string(), - format!( - "maintainer_review_request_ref = {}", - toml_basic_string(&maintainer_review_request_ref) - ), - format!( - "publication_request_ref = {}", - toml_basic_string(&publication_request_ref) - ), - format!("sync_request_ref = {}", toml_basic_string(&sync_request_ref)), - "pr_scope = \"branch diff, redacted public proof, maintainer review, Bifrost credit context, and upstream-main follow-up\"" - .to_string(), - String::new(), - "[antecedents]".to_string(), - "closure_review_required = true".to_string(), - "soul_verdict_required = true".to_string(), - "mind_commit_required = true".to_string(), - "public_proof_required = true".to_string(), - "maintainer_review_required = true".to_string(), - "bifrost_publication_required = true".to_string(), - "credit_ledger_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "closure_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "soul_verdict = \"epiphany.soul.verification_verdict\"".to_string(), - "mind_commit = \"epiphany.mind.state_commit_receipt\"".to_string(), - "public_proof = \"epiphany.repo_work_public_proof_bundle.v0\"".to_string(), - "maintainer_review = \"gamecult.maintainer.review_receipt.v0\"".to_string(), - "bifrost_publication = \"gamecult.bifrost.public_proof_publication_receipt.v0\"" - .to_string(), - "credit_ledger = \"gamecult.bifrost.credit_receipt.v0\"".to_string(), - "pr_publication = \"gamecult.github.pull_request_publication_receipt.v0\"" - .to_string(), - String::new(), - "[pr_packet]".to_string(), - "base_ref = \"origin/main\"".to_string(), - "requires_branch_name = true".to_string(), - "requires_title = true".to_string(), - "requires_body = true".to_string(), - "requires_changed_path_list = true".to_string(), - "requires_public_proof_ref = true".to_string(), - "requires_maintainer_review_ref = true".to_string(), - "requires_credit_ref = true".to_string(), - "requires_private_state_redaction_check = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "github_pr_authorized = false".to_string(), - "branch_push_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "maintainer_review_required = true".to_string(), - "bifrost_publication_gate_required = true".to_string(), - "hands_execution_required = true".to_string(), - "github_provider_receipt_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the PR request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names PR packet requirements without authorizing branch push, PR publication, merge, or sync.\",".to_string(), - " \"Soul verifies maintainer review, public proof, Bifrost publication, and credit receipts are required before any GitHub PR action.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the PR request if the work is not ready for GitHub/Bifrost publication review.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.pr_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a GitHub PR request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add PR request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo PR request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request requires maintainer review, redacted public proof, Bifrost publication, credit, and PR packet fields without authorizing push, PR publication, merge, sync, service lifecycle, or cross-body mutation.".to_string(), - "Soul verifies no paths outside the declared PR request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated PR request if the work is not ready for GitHub/Bifrost publication review.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.pr_request"), - }) -} - -fn derive_repo_credit_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/credit-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-credit-request:{item_slug}"); - let publication_request_ref = format!(".epiphany/publication-requests/{item_slug}.toml"); - let maintainer_review_request_ref = format!(".epiphany/review-requests/{item_slug}.toml"); - let pr_request_ref = format!(".epiphany/pr-requests/{item_slug}.toml"); - let lines = vec![ - "# Epiphany repo Bifrost credit request.".to_string(), - "# Branch-local credit ledger request cargo; not credit, publication, PR, merge, or sync authority." - .to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_credit_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.credit_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "credit_ledger_authorized = false".to_string(), - "bifrost_publication_authorized = false".to_string(), - "github_pr_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "durable_state_admitted = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-bifrost-credit-review\"".to_string(), - "requested_owner = \"Bifrost\"".to_string(), - "requested_effect = \"record-credit-for-redacted-proof-and-accepted-artifact\"" - .to_string(), - format!( - "publication_request_ref = {}", - toml_basic_string(&publication_request_ref) - ), - format!( - "maintainer_review_request_ref = {}", - toml_basic_string(&maintainer_review_request_ref) - ), - format!("pr_request_ref = {}", toml_basic_string(&pr_request_ref)), - "credit_scope = \"authorship, maintainer review, accepted artifact, public proof, and Bifrost ledger readback\"" - .to_string(), - String::new(), - "[antecedents]".to_string(), - "closure_review_required = true".to_string(), - "soul_verdict_required = true".to_string(), - "mind_commit_required = true".to_string(), - "public_proof_required = true".to_string(), - "maintainer_review_required = true".to_string(), - "accepted_artifact_required = true".to_string(), - "authorship_context_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "closure_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "soul_verdict = \"epiphany.soul.verification_verdict\"".to_string(), - "mind_commit = \"epiphany.mind.state_commit_receipt\"".to_string(), - "public_proof = \"epiphany.repo_work_public_proof_bundle.v0\"".to_string(), - "maintainer_review = \"gamecult.maintainer.review_receipt.v0\"".to_string(), - "accepted_artifact = \"gamecult.artifact.acceptance_receipt.v0\"".to_string(), - "credit_ledger = \"gamecult.bifrost.credit_receipt.v0\"".to_string(), - "credit_readback = \"gamecult.bifrost.credit_readback_receipt.v0\"".to_string(), - String::new(), - "[credit_packet]".to_string(), - "requires_author_identity = true".to_string(), - "requires_reviewer_identity = true".to_string(), - "requires_accepted_artifact_ref = true".to_string(), - "requires_public_proof_ref = true".to_string(), - "requires_changed_path_list = true".to_string(), - "requires_credit_ledger_target = true".to_string(), - "requires_private_state_redaction_check = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "credit_ledger_authorized = false".to_string(), - "bifrost_publication_authorized = false".to_string(), - "github_pr_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "bifrost_credit_authority_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the credit request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names authorship, reviewer, accepted artifact, public proof, and redaction requirements without authorizing credit ledger writes.\",".to_string(), - " \"Soul verifies no publication, PR, merge, sync, Hands, service lifecycle, or cross-body authority is granted.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the credit request if the artifact has not been accepted or credited by Bifrost.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.credit_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a Bifrost credit request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add credit request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo credit request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request requires authorship, maintainer review, accepted artifact, public proof, credit ledger, and readback receipts without authorizing credit, publication, PR, merge, sync, service lifecycle, or cross-body mutation.".to_string(), - "Soul verifies no paths outside the declared credit request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated credit request if the artifact is not ready for Bifrost credit review.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.credit_request"), - }) -} - -fn derive_repo_artifact_acceptance_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/artifact-acceptance-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-artifact-acceptance-request:{item_slug}"); - let verification_request_ref = format!(".epiphany/verification-requests/{item_slug}.toml"); - let maintainer_review_request_ref = format!(".epiphany/review-requests/{item_slug}.toml"); - let publication_request_ref = format!(".epiphany/publication-requests/{item_slug}.toml"); - let lines = vec![ - "# Epiphany repo artifact acceptance request.".to_string(), - "# Branch-local accepted-artifact request cargo; not acceptance, credit, publication, PR, merge, or sync authority.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_artifact_acceptance_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.artifact_acceptance_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "artifact_acceptance_authorized = false".to_string(), - "credit_ledger_authorized = false".to_string(), - "github_pr_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "durable_state_admitted = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-artifact-acceptance-review\"".to_string(), - "routing_owner = \"Self\"".to_string(), - "acceptance_owner = \"Maintainer\"".to_string(), - "accounting_owner = \"Bifrost\"".to_string(), - "acceptance_receipt_required = true".to_string(), - "requested_effect = \"record-accepted-artifact-for-reviewed-branch-work\"".to_string(), - format!( - "verification_request_ref = {}", - toml_basic_string(&verification_request_ref) - ), - format!( - "maintainer_review_request_ref = {}", - toml_basic_string(&maintainer_review_request_ref) - ), - format!( - "publication_request_ref = {}", - toml_basic_string(&publication_request_ref) - ), - "acceptance_scope = \"changed paths, Hands commit, Soul closure, maintainer review, public proof, and accepted artifact readback\"" - .to_string(), - String::new(), - "[antecedents]".to_string(), - "closure_review_required = true".to_string(), - "soul_verdict_required = true".to_string(), - "mind_commit_required = true".to_string(), - "public_proof_required = true".to_string(), - "maintainer_review_required = true".to_string(), - "hands_commit_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "closure_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "soul_verdict = \"epiphany.soul.verification_verdict\"".to_string(), - "mind_commit = \"epiphany.mind.state_commit_receipt\"".to_string(), - "public_proof = \"epiphany.repo_work_public_proof_bundle.v0\"".to_string(), - "maintainer_review = \"gamecult.maintainer.review_receipt.v0\"".to_string(), - "hands_commit = \"epiphany.hands.commit_receipt\"".to_string(), - "accepted_artifact = \"gamecult.artifact.acceptance_receipt.v0\"".to_string(), - String::new(), - "[artifact_packet]".to_string(), - "requires_artifact_ref = true".to_string(), - "requires_commit_sha = true".to_string(), - "requires_changed_path_list = true".to_string(), - "requires_review_verdict = true".to_string(), - "requires_public_proof_ref = true".to_string(), - "requires_acceptance_rationale = true".to_string(), - "requires_private_state_redaction_check = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "artifact_acceptance_authorized = false".to_string(), - "credit_ledger_authorized = false".to_string(), - "github_pr_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "maintainer_acceptance_authority_required = true".to_string(), - "bifrost_accounting_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the artifact acceptance request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names artifact, commit, changed paths, review, proof, and rationale requirements without authorizing artifact acceptance.\",".to_string(), - " \"Soul verifies no credit, publication, PR, merge, sync, Hands, service lifecycle, or cross-body authority is granted.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the artifact acceptance request if the work has not been reviewed as an accepted artifact.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.artifact_acceptance_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived an artifact acceptance request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add artifact acceptance request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo artifact acceptance request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request requires artifact, commit, changed paths, review verdict, public proof, and acceptance rationale without authorizing acceptance, credit, publication, PR, merge, sync, service lifecycle, or cross-body mutation.".to_string(), - "Soul verifies no paths outside the declared artifact acceptance request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated artifact acceptance request if the work is not ready for maintainer/Bifrost artifact acceptance review.".to_string(), - ], - derivation: plan_derivation_receipt( - input, - action_family, - "repo.artifact_acceptance_request", - ), - }) -} - -fn derive_repo_metrics_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/metrics-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-metrics-request:{item_slug}"); - let publication_request_ref = format!(".epiphany/publication-requests/{item_slug}.toml"); - let credit_request_ref = format!(".epiphany/credit-requests/{item_slug}.toml"); - let artifact_acceptance_request_ref = - format!(".epiphany/artifact-acceptance-requests/{item_slug}.toml"); - let lines = vec![ - "# Epiphany repo metrics request.".to_string(), - "# Branch-local accounting request cargo; not spend, review, credit, publication, PR, merge, or sync authority.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_metrics_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.metrics_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "metrics_ledger_authorized = false".to_string(), - "spend_authorized = false".to_string(), - "review_load_authorized = false".to_string(), - "credit_ledger_authorized = false".to_string(), - "github_pr_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "durable_state_admitted = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-metrics-review\"".to_string(), - "routing_owner = \"Self\"".to_string(), - "accounting_owner = \"Bifrost\"".to_string(), - "review_evidence_owner = \"Maintainer\"".to_string(), - "spend_receipt_required = true".to_string(), - "review_load_receipt_required = true".to_string(), - "requested_effect = \"record-compute-review-and-artifact-accounting\"".to_string(), - format!( - "publication_request_ref = {}", - toml_basic_string(&publication_request_ref) - ), - format!("credit_request_ref = {}", toml_basic_string(&credit_request_ref)), - format!( - "artifact_acceptance_request_ref = {}", - toml_basic_string(&artifact_acceptance_request_ref) - ), - "metrics_scope = \"model spend, review load, accepted artifact, public proof, and credit readback\"" - .to_string(), - String::new(), - "[antecedents]".to_string(), - "closure_review_required = true".to_string(), - "soul_verdict_required = true".to_string(), - "mind_commit_required = true".to_string(), - "public_proof_required = true".to_string(), - "accepted_artifact_required = true".to_string(), - "credit_request_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "closure_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "soul_verdict = \"epiphany.soul.verification_verdict\"".to_string(), - "mind_commit = \"epiphany.mind.state_commit_receipt\"".to_string(), - "public_proof = \"epiphany.repo_work_public_proof_bundle.v0\"".to_string(), - "accepted_artifact = \"gamecult.artifact.acceptance_receipt.v0\"".to_string(), - "model_spend = \"gamecult.metrics.model_spend_receipt.v0\"".to_string(), - "review_load = \"gamecult.metrics.review_load_receipt.v0\"".to_string(), - "credit_readback = \"gamecult.bifrost.credit_readback_receipt.v0\"".to_string(), - String::new(), - "[metrics_packet]".to_string(), - "requires_model_call_count = true".to_string(), - "requires_token_summary = true".to_string(), - "requires_cost_availability_status = true".to_string(), - "requires_review_duration = true".to_string(), - "requires_review_event_count = true".to_string(), - "requires_accepted_artifact_ref = true".to_string(), - "requires_public_proof_ref = true".to_string(), - "requires_credit_readback_ref = true".to_string(), - "requires_private_state_redaction_check = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "metrics_ledger_authorized = false".to_string(), - "spend_authorized = false".to_string(), - "review_load_authorized = false".to_string(), - "credit_ledger_authorized = false".to_string(), - "github_pr_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "hands_action_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "bifrost_accounting_required = true".to_string(), - "maintainer_review_evidence_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the metrics request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names model spend, review load, accepted artifact, public proof, credit readback, and redaction requirements without authorizing ledger writes.\",".to_string(), - " \"Soul verifies no publication, PR, merge, sync, Hands, service lifecycle, or cross-body authority is granted.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the metrics request if the work is not ready for Bifrost/maintainer accounting review.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.metrics_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a repo metrics request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add metrics request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo metrics request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request requires model spend, review load, accepted artifact, public proof, and credit readback receipts without authorizing metrics ledger writes, spend, review-load mutation, publication, PR, merge, sync, service lifecycle, or cross-body mutation.".to_string(), - "Soul verifies no paths outside the declared metrics request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated metrics request if the work is not ready for accounting review.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.metrics_request"), - }) -} - -fn derive_repo_readiness_review_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/readiness-reviews/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-readiness-review-request:{item_slug}"); - let lines = vec![ - "# Epiphany repo MVP readiness review request.".to_string(), - "# Branch-local readiness review cargo; not publication, merge, deployment, service, or state authority.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_readiness_review_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.readiness_review_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "readiness_approved = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "deployment_authority = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-mvp-readiness-review\"".to_string(), - "routing_owner = \"Self\"".to_string(), - "required_reviewers = [\"Maintainer\", \"Soul\", \"Mind\", \"Bifrost\"]".to_string(), - "readiness_approval_owner = \"Maintainer\"".to_string(), - "requested_effect = \"review-redacted-repo-swarm-mvp-proof-bundle\"".to_string(), - "readiness_scope = \"fresh repo init, online swarm, Persona intake, Imagination planning, Self queue-run, Hands branch work, Soul closure, Modeling map update, Mind admission, Bifrost public proof, upstream-main sync, Idunn lifecycle, global tool directory, and private-state redaction\"".to_string(), - "maintainer_readiness_acceptance_required = true".to_string(), - "bifrost_publication_review_required = true".to_string(), - String::new(), - "[antecedents]".to_string(), - "repo_init_required = true".to_string(), - "swarm_online_required = true".to_string(), - "persona_intake_required = true".to_string(), - "imagination_plan_required = true".to_string(), - "self_queue_run_required = true".to_string(), - "hands_commit_required = true".to_string(), - "soul_closure_required = true".to_string(), - "modeling_map_update_required = true".to_string(), - "mind_admission_required = true".to_string(), - "public_proof_required = true".to_string(), - "bifrost_publication_required = true".to_string(), - "upstream_main_sync_required = true".to_string(), - "idunn_lifecycle_readiness_required = true".to_string(), - "tool_directory_readiness_required = true".to_string(), - "private_state_redaction_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "repo_init = \"epiphany.repo_swarm_init_receipt.v0\"".to_string(), - "swarm_online = \"epiphany.repo_swarm_online_receipt.v0\"".to_string(), - "persona_speech_audit = \"epiphany.persona_speech_audit.v0\"".to_string(), - "imagination_action_items = \"epiphany.repo_work_imagination_action_items_receipt.v0\"".to_string(), - "queue_run = \"epiphany.repo_work_queue_run_receipt.v0\"".to_string(), - "hands_commit = \"epiphany.hands.commit_receipt\"".to_string(), - "closure_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "soul_verdict = \"epiphany.soul.verification_verdict\"".to_string(), - "modeling_map = \"epiphany.repo_work_map_entry.v0\"".to_string(), - "mind_commit = \"epiphany.mind.state_commit_receipt\"".to_string(), - "public_proof = \"epiphany.repo_work_public_proof_bundle.v0\"".to_string(), - "bifrost_publication = \"gamecult.bifrost.public_proof_publication_receipt.v0\"".to_string(), - "upstream_sync = \"epiphany.repo_work_upstream_sync_receipt.v0\"".to_string(), - "idunn_lifecycle = \"epiphany.repo_work_service_audit.v0\"".to_string(), - "tool_directory = \"epiphany.cultmesh.daemon_tool_directory.v0\"".to_string(), - String::new(), - "[readiness_packet]".to_string(), - "requires_proof_bundle_ref = true".to_string(), - "requires_changed_path_list = true".to_string(), - "requires_branch_name = true".to_string(), - "requires_upstream_main_ref = true".to_string(), - "requires_public_proof_ref = true".to_string(), - "requires_bifrost_ledger_ref = true".to_string(), - "requires_idunn_lifecycle_ref = true".to_string(), - "requires_tool_directory_ref = true".to_string(), - "requires_redaction_report = true".to_string(), - "requires_reviewer_identity = true".to_string(), - "allowed_verdicts = [\"ready\", \"ready-with-caveats\", \"not-ready\", \"needs-human-review\"]".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "readiness_approval_authorized = false".to_string(), - "durable_state_commit_authorized = false".to_string(), - "publication_authorized = false".to_string(), - "bifrost_publication_authorized = false".to_string(), - "github_pr_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "upstream_sync_authorized = false".to_string(), - "deployment_authority = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "hands_action_authorized = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "maintainer_review_required = true".to_string(), - "soul_verification_required = true".to_string(), - "mind_admission_required = true".to_string(), - "bifrost_publication_review_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the readiness review request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names init, online, Persona, Imagination, Self, Hands, Soul, Modeling, Mind, Bifrost, upstream-main, Idunn, tool-directory, and redaction proof requirements.\",".to_string(), - " \"Soul verifies the request grants no readiness approval, state commit, publication, PR, merge, sync, deployment, service lifecycle, Hands, cross-body, or private Verse authority.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the readiness review request if the proof bundle is not ready for maintainer/Soul/Mind/Bifrost review.\"]".to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.readiness_review_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived an MVP readiness review request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add readiness review request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo readiness review request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request requires a redacted proof bundle with repo init, online swarm, Persona, Imagination, Self, Hands, Soul, Modeling, Mind, Bifrost, upstream-main, Idunn, tool-directory, and redaction receipts without authorizing readiness approval, state commit, publication, merge, deployment, service lifecycle, or cross-body mutation.".to_string(), - "Soul verifies no paths outside the declared readiness review request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated readiness review request if the proof bundle is not ready for review.".to_string(), - ], - derivation: plan_derivation_receipt( - input, - action_family, - "repo.readiness_review_request", - ), - }) -} - -fn derive_repo_doctrine_update_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/doctrine-update-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-doctrine-update-request:{item_slug}"); - let doctrine_target = "AGENTS.md"; - let lines = vec![ - "# Epiphany repo doctrine update request.".to_string(), - "# Branch-local governance request cargo; not direct doctrine mutation authority.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_doctrine_update_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.doctrine_update_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "doctrine_mutation_authorized = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-doctrine-review\"".to_string(), - "routing_owner = \"Self\"".to_string(), - "required_reviewers = [\"Maintainer\", \"Mind\", \"Soul\"]".to_string(), - "doctrine_admission_owner = \"Mind\"".to_string(), - "mutation_owner = \"Hands\"".to_string(), - "requested_effect = \"review-repo-agent-doctrine-update\"".to_string(), - format!("doctrine_target = {}", toml_basic_string(doctrine_target)), - "change_surface = \"repo-local agent instructions and operating doctrine\"".to_string(), - "requires_source_grounding = true".to_string(), - "maintainer_review_required = true".to_string(), - String::new(), - "[antecedents]".to_string(), - "persona_or_human_feedback_required = true".to_string(), - "imagination_plan_required = true".to_string(), - "mind_adoption_required = true".to_string(), - "soul_review_required = true".to_string(), - "maintainer_review_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "imagination_plan = \"epiphany.repo_work_imagination_action_items_receipt.v0\"" - .to_string(), - "mind_adoption = \"epiphany.repo_work_plan_adoption_review.v0\"".to_string(), - "soul_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "maintainer_review = \"gamecult.maintainer.review_receipt.v0\"".to_string(), - "hands_commit = \"epiphany.hands.commit_receipt\"".to_string(), - String::new(), - "[doctrine_packet]".to_string(), - "requires_current_doctrine_ref = true".to_string(), - "requires_proposed_change_summary = true".to_string(), - "requires_invariant_impact = true".to_string(), - "requires_rehydration_impact = true".to_string(), - "requires_rollback_plan = true".to_string(), - "requires_private_state_redaction_check = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "direct_doctrine_mutation_authority = false".to_string(), - "direct_hands_authority = false".to_string(), - "direct_mind_state_commit = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "maintainer_review_required = true".to_string(), - "mind_admission_required = true".to_string(), - "hands_receipts_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the doctrine update request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names AGENTS.md as review target and requires source grounding, Mind adoption, Soul review, maintainer review, and rollback planning before doctrine mutation.\",".to_string(), - " \"Soul verifies no direct doctrine, Hands, publication, merge, service lifecycle, cross-body, or private Verse authority is granted.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the doctrine update request if the proposed doctrine change is not ready for review.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.doctrine_update_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a repo doctrine update request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add doctrine update request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo doctrine update request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request names AGENTS.md review scope, source grounding, Mind adoption, Soul review, maintainer review, rollback planning, and no direct doctrine mutation authority.".to_string(), - "Soul verifies no paths outside the declared doctrine update request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated doctrine update request if the proposed doctrine change is not ready for review.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.doctrine_update_request"), - }) -} - -fn derive_repo_secret_policy_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/security/secret-policy-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-secret-policy-request:{item_slug}"); - let lines = vec![ - "# Epiphany repo secret policy request.".to_string(), - "# Branch-local security request cargo; not secret access, write-permission, or publication authority.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_secret_policy_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.secret_policy_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "secret_access_authorized = false".to_string(), - "write_permission_authorized = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-security-review\"".to_string(), - "routing_owner = \"Self\"".to_string(), - "required_reviewers = [\"Maintainer\", \"Soul\", \"Mind\", \"Bifrost\"]".to_string(), - "policy_admission_owner = \"Mind\"".to_string(), - "requested_effect = \"review-repo-secret-and-write-permission-policy\"".to_string(), - "security_scope = \"secrets, credentials, write permissions, public/private export, and deployment authority\"".to_string(), - "requires_secret_inventory_without_values = true".to_string(), - "requires_write_permission_scope = true".to_string(), - "requires_public_private_export_boundary = true".to_string(), - String::new(), - "[antecedents]".to_string(), - "source_grounding_required = true".to_string(), - "soul_review_required = true".to_string(), - "mind_adoption_required = true".to_string(), - "maintainer_review_required = true".to_string(), - "bifrost_publication_review_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "source_grounding = \"epiphany.eyes.evidence_packet\"".to_string(), - "soul_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "mind_adoption = \"epiphany.repo_work_plan_adoption_review.v0\"".to_string(), - "maintainer_review = \"gamecult.maintainer.review_receipt.v0\"".to_string(), - "bifrost_publication_review = \"gamecult.bifrost.publication_review_receipt.v0\"" - .to_string(), - String::new(), - "[security_packet]".to_string(), - "requires_secret_locations_without_values = true".to_string(), - "requires_credential_owner = true".to_string(), - "requires_write_scope_matrix = true".to_string(), - "requires_public_export_redaction_rules = true".to_string(), - "requires_deployment_authority_owner = true".to_string(), - "requires_incident_rollback_plan = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "direct_secret_access_authority = false".to_string(), - "secret_value_materialization = false".to_string(), - "write_permission_authority = false".to_string(), - "deployment_authority = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "maintainer_security_review_required = true".to_string(), - "soul_security_verification_required = true".to_string(), - "mind_policy_admission_required = true".to_string(), - "bifrost_publication_review_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the secret policy request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names secret locations without values, credential ownership, write-permission scope, public/private export boundaries, deployment authority ownership, and rollback planning.\",".to_string(), - " \"Soul verifies no secret access, write permission, deployment, publication, merge, service lifecycle, cross-body, or private Verse authority is granted.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the secret policy request if it is not ready for Maintainer review, Soul verification, Mind admission, and Bifrost publication review.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.secret_policy_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a repo secret policy request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add secret policy request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo secret policy request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request names secret-location-without-values, credential ownership, write scope, public/private export boundaries, deployment authority ownership, rollback planning, and no direct secret or write authority.".to_string(), - "Soul verifies no paths outside the declared secret policy request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated secret policy request if the security review is not ready.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.secret_policy_request"), - }) -} - -fn derive_repo_dependency_policy_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/dependency-policy-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-dependency-policy-request:{item_slug}"); - let lines = vec![ - "# Epiphany repo dependency policy request.".to_string(), - "# Branch-local supply-chain policy request cargo; not package install, lockfile mutation, network fetch, CI mutation, deployment, or publication authority.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_dependency_policy_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.dependency_policy_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "dependency_update_authorized = false".to_string(), - "package_install_authorized = false".to_string(), - "lockfile_mutation_authorized = false".to_string(), - "network_fetch_authorized = false".to_string(), - "ci_mutation_authorized = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "deployment_authority = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-dependency-policy-review\"".to_string(), - "routing_owner = \"Self\"".to_string(), - "required_reviewers = [\"Maintainer\", \"Soul\", \"Mind\", \"Bifrost\"]".to_string(), - "policy_admission_owner = \"Mind\"".to_string(), - "requested_effect = \"review-repo-dependency-and-supply-chain-policy\"".to_string(), - "dependency_scope = \"dependency manifests, lockfiles, package-manager commands, vendored code, update cadence, license posture, vulnerability review, and provenance requirements\"".to_string(), - "requires_manifest_inventory = true".to_string(), - "requires_lockfile_policy = true".to_string(), - "requires_package_manager_command_review = true".to_string(), - "requires_network_fetch_policy = true".to_string(), - "requires_vulnerability_review = true".to_string(), - "requires_license_review = true".to_string(), - "requires_rollback_plan = true".to_string(), - String::new(), - "[antecedents]".to_string(), - "source_grounding_required = true".to_string(), - "eyes_evidence_required = true".to_string(), - "soul_review_required = true".to_string(), - "mind_adoption_required = true".to_string(), - "maintainer_review_required = true".to_string(), - "bifrost_publication_review_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "source_grounding = \"epiphany.eyes.evidence_packet\"".to_string(), - "soul_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "mind_adoption = \"epiphany.repo_work_plan_adoption_review.v0\"".to_string(), - "maintainer_review = \"gamecult.maintainer.review_receipt.v0\"".to_string(), - "bifrost_publication_review = \"gamecult.bifrost.publication_review_receipt.v0\"" - .to_string(), - "dependency_audit = \"gamecult.supply_chain.dependency_audit_receipt.v0\"" - .to_string(), - String::new(), - "[dependency_packet]".to_string(), - "requires_manifest_paths = true".to_string(), - "requires_lockfile_paths = true".to_string(), - "requires_package_manager_commands = true".to_string(), - "requires_vulnerability_sources = true".to_string(), - "requires_license_constraints = true".to_string(), - "requires_vendored_code_policy = true".to_string(), - "requires_update_cadence = true".to_string(), - "requires_private_state_redaction_check = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "direct_dependency_update_authority = false".to_string(), - "direct_package_install_authority = false".to_string(), - "direct_lockfile_mutation_authority = false".to_string(), - "direct_network_fetch_authority = false".to_string(), - "direct_ci_mutation_authority = false".to_string(), - "direct_hands_authority = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "deployment_authority = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "maintainer_dependency_review_required = true".to_string(), - "soul_dependency_verification_required = true".to_string(), - "mind_policy_admission_required = true".to_string(), - "bifrost_publication_review_required = true".to_string(), - "supply_chain_audit_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the dependency policy request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names manifest inventory, lockfile policy, package-manager command review, network fetch policy, vulnerability review, license review, vendored-code policy, update cadence, and rollback planning.\",".to_string(), - " \"Soul verifies no direct dependency update, package install, lockfile mutation, network fetch, CI mutation, Hands, publication, merge, deployment, service lifecycle, cross-body, or private Verse authority is granted.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the dependency policy request if it is not ready for Maintainer review, Soul verification, Mind admission, Bifrost publication review, and supply-chain audit.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.dependency_policy_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a repo dependency policy request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add dependency policy request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo dependency policy request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request names manifest inventory, lockfile policy, package-manager command review, network fetch policy, vulnerability review, license review, vendored-code policy, update cadence, rollback planning, and no direct dependency/package/network/CI authority.".to_string(), - "Soul verifies no paths outside the declared dependency policy request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated dependency policy request if the supply-chain review is not ready.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.dependency_policy_request"), - }) -} - -fn derive_repo_deployment_request_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let item_slug = sanitize(input.item); - let default_target = format!(".epiphany/deployment-requests/{item_slug}.toml"); - let target_path = validate_toml_target_path(input.target_path.unwrap_or(&default_target))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request_id = format!("repo-deployment-request:{item_slug}"); - let lines = vec![ - "# Epiphany repo deployment request.".to_string(), - "# Branch-local deployment request cargo; Idunn owns deployment execution.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_deployment_request.v0") - ), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.deployment_request") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "operator_authored_shell_details = false".to_string(), - "hands_authority_granted = false".to_string(), - "deployment_authority = false".to_string(), - "ssh_authority = false".to_string(), - "git_push_authority = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[request]".to_string(), - format!("id = {}", toml_basic_string(&request_id)), - "status = \"awaiting-idunn-review\"".to_string(), - "routing_owner = \"Self\"".to_string(), - "required_reviewers = [\"Maintainer\", \"Soul\", \"Mind\", \"Bifrost\"]".to_string(), - "execution_owner = \"Idunn\"".to_string(), - "requested_effect = \"review-repo-deployment-trigger-and-script\"".to_string(), - "deployment_trigger = \"git-push-observed-by-idunn\"".to_string(), - "deployment_surface = \"reviewed repo deployment script or runbook\"".to_string(), - "requires_explicit_deployment_policy = true".to_string(), - "requires_idunn_receipt = true".to_string(), - "requires_aftercare_audit = true".to_string(), - String::new(), - "[antecedents]".to_string(), - "source_grounding_required = true".to_string(), - "mind_adoption_required = true".to_string(), - "soul_review_required = true".to_string(), - "maintainer_review_required = true".to_string(), - "secret_policy_review_required = true".to_string(), - "bifrost_publication_review_required = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "source_grounding = \"epiphany.eyes.evidence_packet\"".to_string(), - "mind_adoption = \"epiphany.repo_work_plan_adoption_review.v0\"".to_string(), - "soul_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "maintainer_review = \"gamecult.maintainer.review_receipt.v0\"".to_string(), - "secret_policy = \"epiphany.repo_secret_policy_request.v0\"".to_string(), - "bifrost_publication_review = \"gamecult.bifrost.publication_review_receipt.v0\"" - .to_string(), - "idunn_deployment = \"gamecult.idunn.deployment_receipt.v0\"".to_string(), - "aftercare_audit = \"gamecult.idunn.deployment_aftercare_audit.v0\"".to_string(), - String::new(), - "[deployment_packet]".to_string(), - "requires_target_environment = true".to_string(), - "requires_watched_ref = true".to_string(), - "requires_source_commit_sha = true".to_string(), - "requires_deployment_script_ref = true".to_string(), - "requires_script_hash = true".to_string(), - "requires_script_review_ref = true".to_string(), - "requires_host_access_policy_ref = true".to_string(), - "requires_secret_policy_ref = true".to_string(), - "requires_rollback_plan = true".to_string(), - "requires_aftercare_checks = true".to_string(), - String::new(), - "[authority]".to_string(), - "branch_local_only = true".to_string(), - "direct_deployment_authority = false".to_string(), - "direct_ssh_authority = false".to_string(), - "direct_git_push_authority = false".to_string(), - "direct_service_lifecycle_authority = false".to_string(), - "direct_hands_authority = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "idunn_deployment_authority_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the deployment request path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the request names git-push-triggered Idunn ownership, deployment script review, host access policy, secret policy, rollback, aftercare audit, and Idunn deployment receipts.\",".to_string(), - " \"Soul verifies no direct SSH, deployment, git push, service lifecycle, publication, merge, Hands, cross-body, or private Verse authority is granted.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove the deployment request if the deployment path is not ready for Idunn review.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.deployment_request".to_string(), - target_path, - plan_summary: format!( - "Imagination derived a repo deployment request from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add deployment request for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo deployment request path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the request names Idunn-owned git-push-triggered deployment, script review, host access policy, secret policy, rollback, aftercare, and no direct deployment/SSH/push authority.".to_string(), - "Soul verifies no paths outside the declared deployment request changed.".to_string(), - ], - rollback_hints: vec![ - "Remove the generated deployment request if the deployment review is not ready.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.deployment_request"), - }) -} - -fn derive_repo_deployment_config_plan( - input: DeriveSafePlanInput<'_>, - action_family: &str, -) -> Result { - let target_path = - validate_toml_target_path(input.target_path.unwrap_or(".epiphany/deployment.toml"))?; - let candidate_refs = - string_array_from_json(input.accept_receipt, &["feedback", "candidateActionRefs"]); - let public_refs = - string_array_from_json(input.accept_receipt, &["feedback", "publicDiscussionRefs"]); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let deployment_id = format!("repo-deployment-config:{}", sanitize(input.item)); - let lines = vec![ - "# Epiphany repo deployment config.".to_string(), - "# Branch-local configuration cargo; Idunn owns deployment execution.".to_string(), - format!( - "schema_version = {}", - toml_basic_string("epiphany.repo_deployment_config.v0") - ), - format!("id = {}", toml_basic_string(&deployment_id)), - format!("item = {}", toml_basic_string(input.item)), - format!("created_at = {}", toml_basic_string(&now)), - format!("source = {}", toml_basic_string(input.source)), - format!("summary = {}", toml_basic_string(&compact_line(input.summary))), - format!( - "safe_action_family = {}", - toml_basic_string("repo.deployment_config") - ), - format!("model_authored = {}", input.model_authored), - format!( - "model_ref = {}", - toml_basic_string(input.model_ref.unwrap_or("deterministic-fallback")) - ), - "hands_authority_granted = false".to_string(), - "deployment_authority = false".to_string(), - "ssh_authority = false".to_string(), - "git_push_authority = false".to_string(), - "service_lifecycle_authority = false".to_string(), - "durable_state_admitted = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "cross_repo_mutation = false".to_string(), - "private_state_exposed = false".to_string(), - format!("candidate_action_refs = {}", toml_array(&candidate_refs)), - format!("public_discussion_refs = {}", toml_array(&public_refs)), - String::new(), - "[deployment]".to_string(), - "enabled = false".to_string(), - "owner = \"Idunn\"".to_string(), - "trigger = \"git-push-observed-by-idunn\"".to_string(), - "target_environment = \"review-required\"".to_string(), - "watched_ref = \"refs/heads/main\"".to_string(), - "deployment_script_ref = \"deploy/idunn-deploy.ps1\"".to_string(), - "deployment_script_hash_required = true".to_string(), - "deployment_script_review_required = true".to_string(), - "host_access_policy_ref_required = true".to_string(), - "secret_policy_ref = \".epiphany/security/secret-policy.toml\"".to_string(), - "secret_values_embedded = false".to_string(), - "rollback_plan_ref_required = true".to_string(), - "aftercare_checks_required = true".to_string(), - "idunn_receipt_required = true".to_string(), - "aftercare_audit_required = true".to_string(), - String::new(), - "[cultmesh]".to_string(), - "local_verse = \"gamecult-local\"".to_string(), - "capability_family = \"gamecult.idunn.deployment\"".to_string(), - "intent_contract = \"gamecult.idunn.deployment_intent.v0\"".to_string(), - "receipt_contract = \"gamecult.idunn.deployment_receipt.v0\"".to_string(), - "aftercare_contract = \"gamecult.idunn.deployment_aftercare_audit.v0\"".to_string(), - "daemon_owns_execution = true".to_string(), - String::new(), - "[required_receipts]".to_string(), - "mind_adoption = \"epiphany.repo_work_plan_adoption_review.v0\"".to_string(), - "soul_review = \"epiphany.repo_work_closure_review.v0\"".to_string(), - "maintainer_review = \"gamecult.maintainer.review_receipt.v0\"".to_string(), - "secret_policy = \"epiphany.repo_secret_policy_request.v0\"".to_string(), - "idunn_deployment = \"gamecult.idunn.deployment_receipt.v0\"".to_string(), - "aftercare_audit = \"gamecult.idunn.deployment_aftercare_audit.v0\"".to_string(), - String::new(), - "[authority]".to_string(), - "configuration_only = true".to_string(), - "direct_deployment_authority = false".to_string(), - "direct_ssh_authority = false".to_string(), - "direct_git_push_authority = false".to_string(), - "direct_service_lifecycle_authority = false".to_string(), - "direct_hands_authority = false".to_string(), - "publication_authorized = false".to_string(), - "merge_authorized = false".to_string(), - "cross_body_mutation_authorized = false".to_string(), - "private_verse_rummaging = false".to_string(), - "idunn_deployment_authority_required = true".to_string(), - String::new(), - "[verification]".to_string(), - "asks = [".to_string(), - " \"Soul verifies the deployment config path changed and contains the accepted pressure summary.\",".to_string(), - " \"Soul verifies the config names git-push-observed-by-Idunn trigger, script review/hash, secret policy, rollback, aftercare, and Idunn receipt contracts.\",".to_string(), - " \"Soul verifies this config is disabled until reviewed and grants no direct deployment, SSH, git push, service lifecycle, publication, merge, Hands, cross-body, or private Verse authority.\"".to_string(), - "]".to_string(), - String::new(), - "[rollback]".to_string(), - "hints = [\"Remove or disable the deployment config if the Idunn deployment path is not ready.\"]" - .to_string(), - String::new(), - ]; - let command = powershell_set_lines_command(&target_path, &lines); - Ok(DerivedSafePlan { - safe_action_family: "repo.deployment_config".to_string(), - target_path, - plan_summary: format!( - "Imagination derived an Idunn-facing repo deployment config from accepted {} pressure.", - input.source - ), - command, - commit_message: format!("Add deployment config for repo work item {}", input.item), - verification_asks: vec![ - "Soul verifies the repo deployment config path changed and contains the accepted pressure summary.".to_string(), - "Soul verifies the config names git-push-observed-by-Idunn trigger, script review/hash, secret policy, rollback, aftercare, Idunn receipts, and no direct deployment/SSH/push authority.".to_string(), - "Soul verifies no paths outside the declared deployment config changed.".to_string(), - ], - rollback_hints: vec![ - "Remove or disable the generated deployment config if Idunn review is not ready.".to_string(), - ], - derivation: plan_derivation_receipt(input, action_family, "repo.deployment_config"), - }) -} - -fn closure_family_assertions( - workspace: &Path, - commit_sha: &str, - execute_receipt: &Value, - item: &str, -) -> Result<(Value, bool)> { - let Some(plan_receipt_path) = path_from_json(execute_receipt, &["planReceiptPath"]) else { - return Ok(( - json!({ - "status": "failed", - "reason": "execute receipt has no planReceiptPath", - "assertions": [] - }), - false, - )); - }; - let plan_receipt = read_json_if_exists(&plan_receipt_path)?.unwrap_or(Value::Null); - if plan_receipt.is_null() { - return Ok(( - json!({ - "status": "failed", - "reason": "plan receipt path is missing", - "planReceiptPath": plan_receipt_path, - "assertions": [] - }), - false, - )); - } - let safe_family = string_from_json(&plan_receipt, &["derivation", "safeActionFamily"]) - .unwrap_or_else(|| "manual-or-unknown".to_string()); - let presentation_only = matches!( - safe_family.as_str(), - "repo.append_worklog" - | "repo.markdown_planning_note" - | "repo.checklist_note" - | "repo.markdown_managed_section" - | "repo.status_section" - | "repo.task_card" - ); - let target_paths = first_plan_action(&plan_receipt) - .map(|action| string_array_field(action, "changedPaths")) - .unwrap_or_else(|| string_array_from_json(execute_receipt, &["changedPaths"])); - let target_path = target_paths.first().cloned().unwrap_or_default(); - if target_path.is_empty() { - return Ok(( - json!({ - "status": "failed", - "safeActionFamily": safe_family, - "reason": "plan and execute receipts have no target changed path", - "assertions": [] - }), - false, - )); - } - let summary = string_from_json(&plan_receipt, &["derivation", "inputPressure", "summary"]) - .or_else(|| string_from_json(&plan_receipt, &["objective"])) - .unwrap_or_else(|| item.to_string()); - let compact_summary = compact_line(&summary); - let committed_content = read_committed_file(workspace, commit_sha, &target_path)?; - let mut assertions = Vec::new(); - push_assertion( - &mut assertions, - "target-blob-present", - committed_content.is_some(), - format!("Committed target {target_path} exists at {commit_sha}."), - ); - let content = committed_content.unwrap_or_default(); - match safe_family.as_str() { - "repo.append_worklog" - | "repo.markdown_planning_note" - | "repo.checklist_note" - | "repo.markdown_managed_section" - | "repo.status_section" - | "repo.task_card" => { - push_assertion( - &mut assertions, - "presentation-only-family", - true, - "Presentation formatting carries no closure authority; committed target/path evidence remains authoritative.".to_string(), - ); - } - "repo.tool_request" => { - let request = parse_repo_tool_request(&content).ok(); - push_assertion( - &mut assertions, - "tool-request-schema-present", - request - .as_ref() - .is_some_and(RepoToolRequest::has_canonical_identity), - "Committed tool request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "tool-request-family-present", - request - .as_ref() - .is_some_and(RepoToolRequest::has_canonical_identity), - "Committed tool request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "tool-request-summary-present", - request - .as_ref() - .is_some_and(|request| request.summary == compact_summary), - "Committed tool request contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "tool-request-section-present", - request - .as_ref() - .is_some_and(RepoToolRequest::has_request_contract), - "Committed tool request names the daemon tool directory and typed intent operation." - .to_string(), - ); - push_assertion( - &mut assertions, - "tool-request-cultmesh-contracts", - request - .as_ref() - .is_some_and(RepoToolRequest::has_cultmesh_contract), - "Committed tool request names typed CultMesh contracts, host liveness, and host execution ownership.".to_string(), - ); - push_assertion( - &mut assertions, - "tool-request-odin-provider-ownership", - request - .as_ref() - .is_some_and(RepoToolRequest::has_odin_contract), - "Committed tool request preserves Odin discovery and provider ownership boundaries." - .to_string(), - ); - push_assertion( - &mut assertions, - "tool-request-authority-seals", - request - .as_ref() - .is_some_and(RepoToolRequest::has_authority_seals), - "Committed tool request denies direct execution, shell, Hands, state, publication, lifecycle, cross-body, and private-rummaging authority.".to_string(), - ); - push_assertion( - &mut assertions, - "tool-request-private-seal", - request - .as_ref() - .is_some_and(|request| !request.private_state_exposed), - "Committed tool request preserves the private-state seal.".to_string(), - ); - } - "repo.collaboration_policy" => { - let policy = parse_repo_collaboration_policy(&content).ok(); - push_assertion( - &mut assertions, - "collaboration-policy-schema-present", - policy - .as_ref() - .is_some_and(RepoCollaborationPolicy::has_canonical_identity), - "Committed collaboration policy carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-policy-family-present", - policy - .as_ref() - .is_some_and(RepoCollaborationPolicy::has_canonical_identity), - "Committed collaboration policy carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-policy-summary-present", - policy - .as_ref() - .is_some_and(|value| value.summary == compact_summary), - "Committed collaboration policy contains the accepted pressure summary." - .to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-policy-body-truth", - policy - .as_ref() - .is_some_and(RepoCollaborationPolicy::preserves_provider_truth) - && policy - .as_ref() - .is_some_and(RepoCollaborationPolicy::remains_proposal), - "Committed collaboration policy preserves provider ownership.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-policy-verse-boundaries", - policy.as_ref().is_some_and(RepoCollaborationPolicy::has_verse_boundaries), - "Committed collaboration policy names private/local/public Verse boundaries and Odin discovery.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-policy-eve-connection", - policy - .as_ref() - .is_some_and(RepoCollaborationPolicy::has_eve_request), - "Committed collaboration policy names the Eve connection contract.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-policy-persona-feedback", - policy.as_ref().is_some_and(RepoCollaborationPolicy::has_persona_route), - "Committed collaboration policy routes Persona/human/peer feedback through audited public discussion.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-policy-imagination-route", - policy.as_ref().is_some_and(RepoCollaborationPolicy::has_imagination_route), - "Committed collaboration policy routes feedback to Imagination before Mind/Bifrost gates.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-policy-authority-seals", - policy.as_ref().is_some_and(RepoCollaborationPolicy::has_authority_seals), - "Committed collaboration policy denies direct action/state/publication/service/cross-body authority.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-policy-private-seal", - policy - .as_ref() - .is_some_and(|value| !value.private_state_exposed), - "Committed collaboration policy preserves the private-state seal.".to_string(), - ); - } - "repo.collaboration_topic" => { - let topic = parse_repo_collaboration_topic(&content).ok(); - push_assertion( - &mut assertions, - "collaboration-topic-schema-present", - topic - .as_ref() - .is_some_and(RepoCollaborationTopic::has_canonical_identity), - "Committed collaboration topic carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-topic-family-present", - topic - .as_ref() - .is_some_and(RepoCollaborationTopic::has_canonical_identity), - "Committed collaboration topic carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-topic-summary-present", - topic - .as_ref() - .is_some_and(|value| value.summary == compact_summary), - "Committed collaboration topic contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-topic-public-surface", - topic - .as_ref() - .is_some_and(RepoCollaborationTopic::remains_unpublished_proposal), - "Committed collaboration topic names public discussion and Eve surfaces." - .to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-topic-imagination-route", - topic.as_ref().is_some_and(RepoCollaborationTopic::has_imagination_route), - "Committed collaboration topic routes feedback to Imagination consensus before adoption.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-topic-authority-seals", - topic.as_ref().is_some_and(RepoCollaborationTopic::has_authority_seals), - "Committed collaboration topic denies action, publication, cross-body, and private-rummaging authority.".to_string(), - ); - push_assertion( - &mut assertions, - "collaboration-topic-private-seal", - topic - .as_ref() - .is_some_and(|value| !value.private_state_exposed), - "Committed collaboration topic preserves the private-state seal.".to_string(), - ); - } - "repo.consensus_brief" => { - let brief = parse_repo_consensus_brief(&content).ok(); - push_assertion( - &mut assertions, - "consensus-brief-schema-present", - brief - .as_ref() - .is_some_and(RepoConsensusBrief::has_canonical_identity), - "Committed consensus brief carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "consensus-brief-family-present", - brief - .as_ref() - .is_some_and(RepoConsensusBrief::has_canonical_identity), - "Committed consensus brief carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "consensus-brief-summary-present", - brief - .as_ref() - .is_some_and(|value| value.summary == compact_summary), - "Committed consensus brief contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "consensus-brief-draft-state", - brief - .as_ref() - .is_some_and(RepoConsensusBrief::remains_unconverged_draft), - "Committed consensus brief remains a draft requiring review.".to_string(), - ); - push_assertion( - &mut assertions, - "consensus-brief-imagination-route", - brief.as_ref().is_some_and(RepoConsensusBrief::has_imagination_route), - "Committed consensus brief routes through Imagination without private Verse rummaging.".to_string(), - ); - push_assertion( - &mut assertions, - "consensus-brief-inputs-present", - brief - .as_ref() - .is_some_and(RepoConsensusBrief::has_input_contract), - "Committed consensus brief preserves public feedback and candidate-action inputs." - .to_string(), - ); - push_assertion( - &mut assertions, - "consensus-brief-authority-seals", - brief.as_ref().is_some_and(RepoConsensusBrief::has_authority_seals), - "Committed consensus brief denies adoption/action/publication/cross-body authority and requires Mind/Bifrost gates.".to_string(), - ); - push_assertion( - &mut assertions, - "consensus-brief-private-seal", - brief - .as_ref() - .is_some_and(|value| !value.private_state_exposed), - "Committed consensus brief preserves the private-state seal.".to_string(), - ); - } - "repo.interpreter_brief" => { - let brief = parse_repo_interpreter_brief(&content).ok(); - push_assertion( - &mut assertions, - "interpreter-brief-schema-present", - brief - .as_ref() - .is_some_and(RepoInterpreterBrief::has_canonical_identity), - "Committed interpreter brief carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "interpreter-brief-family-present", - brief - .as_ref() - .is_some_and(RepoInterpreterBrief::has_canonical_identity), - "Committed interpreter brief carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "interpreter-brief-summary-present", - brief - .as_ref() - .is_some_and(|value| value.summary == compact_summary), - "Committed interpreter brief contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "interpreter-brief-draft-state", - brief.as_ref().is_some_and(RepoInterpreterBrief::is_imagination_request_for_mind), - "Committed interpreter brief remains an Imagination-authored request for Mind interpretation." - .to_string(), - ); - push_assertion( - &mut assertions, - "interpreter-brief-semantic-checks", - brief - .as_ref() - .is_some_and(RepoInterpreterBrief::has_semantic_checks), - "Committed interpreter brief names semantic checks before action adoption." - .to_string(), - ); - push_assertion( - &mut assertions, - "interpreter-brief-allowed-outputs", - brief.as_ref().is_some_and(RepoInterpreterBrief::has_allowed_outputs), - "Committed interpreter brief limits outputs to candidate families or more planning." - .to_string(), - ); - push_assertion( - &mut assertions, - "interpreter-brief-gates", - brief.as_ref().is_some_and(RepoInterpreterBrief::has_required_gates), - "Committed interpreter brief names consensus, Mind, Soul, Bifrost, Hands, Substrate, and Idunn gates." - .to_string(), - ); - push_assertion( - &mut assertions, - "interpreter-brief-authority-seals", - brief.as_ref().is_some_and(RepoInterpreterBrief::has_authority_seals), - "Committed interpreter brief denies state/adoption/scheduling/substrate/action/shell/commit/publication/deployment/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "interpreter-brief-private-seal", - brief - .as_ref() - .is_some_and(|value| !value.private_state_exposed) - && brief - .as_ref() - .is_some_and(RepoInterpreterBrief::has_authority_seals), - "Committed interpreter brief preserves private-state and transcript seals." - .to_string(), - ); - } - "repo.objective_draft" => { - let draft = parse_repo_objective_draft(&content).ok(); - push_assertion( - &mut assertions, - "objective-draft-schema-present", - draft - .as_ref() - .is_some_and(RepoObjectiveDraft::has_canonical_identity), - "Committed Objective Draft carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "objective-draft-family-present", - draft - .as_ref() - .is_some_and(RepoObjectiveDraft::has_canonical_identity), - "Committed Objective Draft carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "objective-draft-summary-present", - draft - .as_ref() - .is_some_and(|value| value.summary == compact_summary), - "Committed Objective Draft contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "objective-draft-review-state", - draft - .as_ref() - .is_some_and(RepoObjectiveDraft::remains_imagination_draft), - "Committed Objective Draft remains review-required and unadopted.".to_string(), - ); - push_assertion( - &mut assertions, - "objective-draft-acceptance-criteria", - draft - .as_ref() - .is_some_and(RepoObjectiveDraft::has_acceptance_contract), - "Committed Objective Draft names acceptance criteria and downstream gates." - .to_string(), - ); - push_assertion( - &mut assertions, - "objective-draft-inputs-present", - draft.as_ref().is_some_and(RepoObjectiveDraft::has_input_contract), - "Committed Objective Draft preserves discussion/action refs and requires consensus." - .to_string(), - ); - push_assertion( - &mut assertions, - "objective-draft-authority-seals", - draft.as_ref().is_some_and(RepoObjectiveDraft::has_authority_seals), - "Committed Objective Draft denies adoption/scheduling/action/publication/cross-body authority and requires Mind/Bifrost gates.".to_string(), - ); - push_assertion( - &mut assertions, - "objective-draft-private-seal", - draft - .as_ref() - .is_some_and(|value| !value.private_state_exposed), - "Committed Objective Draft preserves the private-state seal.".to_string(), - ); - } - "repo.adoption_request" => { - let request = parse_repo_adoption_request(&content).ok(); - push_assertion( - &mut assertions, - "adoption-request-schema-present", - request - .as_ref() - .is_some_and(RepoAdoptionRequest::has_canonical_identity), - "Committed adoption request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "adoption-request-family-present", - request - .as_ref() - .is_some_and(RepoAdoptionRequest::has_canonical_identity), - "Committed adoption request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "adoption-request-summary-present", - request - .as_ref() - .is_some_and(|value| value.summary == compact_summary), - "Committed adoption request contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "adoption-request-awaits-mind", - request.as_ref().is_some_and(RepoAdoptionRequest::awaits_mind_review), - "Committed adoption request waits for Mind review before state or scheduling consequence.".to_string(), - ); - push_assertion( - &mut assertions, - "adoption-request-decision-contract", - request.as_ref().is_some_and(RepoAdoptionRequest::has_decision_contract), - "Committed adoption request names the Mind decision contract without modifying state.".to_string(), - ); - push_assertion( - &mut assertions, - "adoption-request-inputs-present", - request.as_ref().is_some_and(RepoAdoptionRequest::has_input_contract), - "Committed adoption request preserves public inputs and requires draft/consensus antecedents.".to_string(), - ); - push_assertion( - &mut assertions, - "adoption-request-authority-seals", - request.as_ref().is_some_and(RepoAdoptionRequest::has_authority_seals), - "Committed adoption request denies adoption/state/scheduling/action/publication/cross-body authority.".to_string(), - ); - push_assertion( - &mut assertions, - "adoption-request-private-seal", - request - .as_ref() - .is_some_and(|value| !value.private_state_exposed), - "Committed adoption request preserves the private-state seal.".to_string(), - ); - } - "repo.scheduling_request" => { - let request = parse_repo_scheduling_request(&content).ok(); - push_assertion( - &mut assertions, - "scheduling-request-schema-present", - request - .as_ref() - .is_some_and(RepoSchedulingRequest::has_canonical_identity), - "Committed scheduling request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "scheduling-request-family-present", - request - .as_ref() - .is_some_and(RepoSchedulingRequest::has_canonical_identity), - "Committed scheduling request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "scheduling-request-summary-present", - request - .as_ref() - .is_some_and(|value| value.summary == compact_summary), - "Committed scheduling request contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "scheduling-request-awaits-mind-adoption", - request.as_ref().is_some_and(RepoSchedulingRequest::awaits_mind_adoption), - "Committed scheduling request waits for Mind adoption before Self queue consequence.".to_string(), - ); - push_assertion( - &mut assertions, - "scheduling-request-queue-contract", - request - .as_ref() - .is_some_and(RepoSchedulingRequest::has_bounded_queue_contract), - "Committed scheduling request names a bounded queue pulse contract.".to_string(), - ); - push_assertion( - &mut assertions, - "scheduling-request-receipt-contract", - request.as_ref().is_some_and(RepoSchedulingRequest::has_receipt_contract), - "Committed scheduling request requires Mind receipts and names the later Self receipt.".to_string(), - ); - push_assertion( - &mut assertions, - "scheduling-request-authority-seals", - request.as_ref().is_some_and(RepoSchedulingRequest::has_authority_seals), - "Committed scheduling request denies scheduling/queue/action/publication/cross-body authority and requires Mind/Bifrost gates.".to_string(), - ); - push_assertion( - &mut assertions, - "scheduling-request-private-seal", - request - .as_ref() - .is_some_and(|value| !value.private_state_exposed), - "Committed scheduling request preserves the private-state seal.".to_string(), - ); - } - "repo.work_order" => { - let work_order = parse_repo_work_order(&content).ok(); - push_assertion( - &mut assertions, - "work-order-schema-present", - work_order - .as_ref() - .is_some_and(RepoWorkOrder::has_canonical_identity), - "Committed work order carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "work-order-family-present", - work_order - .as_ref() - .is_some_and(RepoWorkOrder::has_canonical_identity), - "Committed work order carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "work-order-summary-present", - work_order - .as_ref() - .is_some_and(|value| value.summary == compact_summary), - "Committed work order contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "work-order-awaits-hands-review", - work_order - .as_ref() - .is_some_and(RepoWorkOrder::awaits_hands_review), - "Committed work order waits for Hands review before implementation consequence." - .to_string(), - ); - push_assertion( - &mut assertions, - "work-order-antecedents-present", - work_order - .as_ref() - .is_some_and(RepoWorkOrder::has_antecedent_contract), - "Committed work order preserves adoption and scheduling antecedents.".to_string(), - ); - push_assertion( - &mut assertions, - "work-order-receipt-contract", - work_order - .as_ref() - .is_some_and(RepoWorkOrder::has_receipt_contract), - "Committed work order names the Substrate/Hands/Soul/Mind receipt chain." - .to_string(), - ); - push_assertion( - &mut assertions, - "work-order-scope-bounded", - work_order - .as_ref() - .is_some_and(RepoWorkOrder::has_bounded_scope), - "Committed work order scopes later action to bounded branch-local reviewable work." - .to_string(), - ); - push_assertion( - &mut assertions, - "work-order-authority-seals", - work_order.as_ref().is_some_and(RepoWorkOrder::has_authority_seals), - "Committed work order denies substrate/shell/commit/action/publication/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "work-order-private-seal", - work_order - .as_ref() - .is_some_and(|value| !value.private_state_exposed), - "Committed work order preserves the private-state seal.".to_string(), - ); - } - "repo.verification_request" => { - let request = parse_repo_verification_request(&content).ok(); - push_assertion( - &mut assertions, - "verification-request-schema-present", - request - .as_ref() - .is_some_and(RepoVerificationRequest::has_canonical_identity), - "Committed verification request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "verification-request-family-present", - request - .as_ref() - .is_some_and(RepoVerificationRequest::has_canonical_identity), - "Committed verification request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "verification-request-summary-present", - request - .as_ref() - .is_some_and(|request| request.summary == compact_summary), - "Committed verification request contains the accepted pressure summary." - .to_string(), - ); - push_assertion( - &mut assertions, - "verification-request-awaits-soul-review", - request - .as_ref() - .is_some_and(RepoVerificationRequest::awaits_soul_review), - "Committed verification request waits for Soul review before proof consequence." - .to_string(), - ); - push_assertion( - &mut assertions, - "verification-request-antecedents-present", - request - .as_ref() - .is_some_and(RepoVerificationRequest::has_antecedent_contract), - "Committed verification request requires Substrate and Hands antecedents." - .to_string(), - ); - push_assertion( - &mut assertions, - "verification-request-receipt-contract", - request - .as_ref() - .is_some_and(RepoVerificationRequest::has_receipt_contract), - "Committed verification request names Hands/Soul/closure/Mind receipt chain." - .to_string(), - ); - push_assertion( - &mut assertions, - "verification-request-checks-present", - request - .as_ref() - .is_some_and(RepoVerificationRequest::has_check_contract), - "Committed verification request names the closure checks that Soul should run." - .to_string(), - ); - push_assertion( - &mut assertions, - "verification-request-authority-seals", - request.as_ref().is_some_and(RepoVerificationRequest::has_authority_seals), - "Committed verification request denies verdict/state/action/rerun/publication/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "verification-request-private-seal", - request - .as_ref() - .is_some_and(|request| !request.private_state_exposed), - "Committed verification request preserves the private-state seal.".to_string(), - ); - } - "repo.publication_request" => { - let request = parse_repo_publication_request(&content).ok(); - push_assertion( - &mut assertions, - "publication-request-schema-present", - request - .as_ref() - .is_some_and(RepoPublicationRequest::has_canonical_identity), - "Committed publication request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "publication-request-family-present", - request - .as_ref() - .is_some_and(RepoPublicationRequest::has_canonical_identity), - "Committed publication request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "publication-request-summary-present", - request - .as_ref() - .is_some_and(|request| request.summary == compact_summary), - "Committed publication request contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "publication-request-awaits-bifrost-review", - request - .as_ref() - .is_some_and(RepoPublicationRequest::awaits_bifrost_review), - "Committed publication request waits for Bifrost review before public consequence." - .to_string(), - ); - push_assertion( - &mut assertions, - "publication-request-antecedents-present", - request.as_ref().is_some_and(RepoPublicationRequest::has_antecedent_contract), - "Committed publication request requires closure, Soul, Mind, and redacted proof antecedents." - .to_string(), - ); - push_assertion( - &mut assertions, - "publication-request-receipt-contract", - request.as_ref().is_some_and(RepoPublicationRequest::has_receipt_contract), - "Committed publication request names the Bifrost/GitHub/credit/upstream receipt chain." - .to_string(), - ); - push_assertion( - &mut assertions, - "publication-request-redaction-contract", - request - .as_ref() - .is_some_and(RepoPublicationRequest::has_redaction_contract), - "Committed publication request preserves the public export redaction contract." - .to_string(), - ); - push_assertion( - &mut assertions, - "publication-request-authority-seals", - request.as_ref().is_some_and(RepoPublicationRequest::has_authority_seals), - "Committed publication request denies publication/credit/merge/sync/action/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "publication-request-private-seal", - request - .as_ref() - .is_some_and(|request| !request.private_state_exposed), - "Committed publication request preserves the private-state seal.".to_string(), - ); - } - "repo.sync_request" => { - let request = parse_repo_sync_request(&content).ok(); - push_assertion( - &mut assertions, - "sync-request-schema-present", - request - .as_ref() - .is_some_and(RepoSyncRequest::has_canonical_identity), - "Committed sync request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "sync-request-family-present", - request - .as_ref() - .is_some_and(RepoSyncRequest::has_canonical_identity), - "Committed sync request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "sync-request-summary-present", - request - .as_ref() - .is_some_and(|request| request.summary == compact_summary), - "Committed sync request contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "sync-request-awaits-upstream-proof", - request - .as_ref() - .is_some_and(RepoSyncRequest::awaits_upstream_proof), - "Committed sync request waits for upstream-main proof instead of performing sync." - .to_string(), - ); - push_assertion( - &mut assertions, - "sync-request-antecedents-present", - request.as_ref().is_some_and(RepoSyncRequest::has_antecedent_contract), - "Committed sync request requires publication, maintainer review, credit, and proof antecedents." - .to_string(), - ); - push_assertion( - &mut assertions, - "sync-request-receipt-contract", - request.as_ref().is_some_and(RepoSyncRequest::has_receipt_contract), - "Committed sync request names publication, review, credit, sync, and ancestry proof receipts." - .to_string(), - ); - push_assertion( - &mut assertions, - "sync-request-proof-contract", - request - .as_ref() - .is_some_and(RepoSyncRequest::has_proof_contract), - "Committed sync request names the upstream-main ancestry proof contract." - .to_string(), - ); - push_assertion( - &mut assertions, - "sync-request-authority-seals", - request.as_ref().is_some_and(RepoSyncRequest::has_authority_seals), - "Committed sync request denies merge/push/sync/publication/credit/action/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "sync-request-private-seal", - request - .as_ref() - .is_some_and(|request| !request.private_state_exposed), - "Committed sync request preserves the private-state seal.".to_string(), - ); - } - "repo.maintainer_review_request" => { - let request = parse_repo_maintainer_review_request(&content).ok(); - push_assertion( - &mut assertions, - "maintainer-review-request-schema-present", - request - .as_ref() - .is_some_and(RepoMaintainerReviewRequest::has_canonical_identity), - "Committed maintainer review request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "maintainer-review-request-family-present", - request - .as_ref() - .is_some_and(RepoMaintainerReviewRequest::has_canonical_identity), - "Committed maintainer review request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "maintainer-review-request-summary-present", - request - .as_ref() - .is_some_and(|request| request.summary == compact_summary), - "Committed maintainer review request contains the accepted pressure summary." - .to_string(), - ); - push_assertion( - &mut assertions, - "maintainer-review-request-awaits-review", - request - .as_ref() - .is_some_and(RepoMaintainerReviewRequest::awaits_review), - "Committed maintainer review request waits for human review before consequence." - .to_string(), - ); - push_assertion( - &mut assertions, - "maintainer-review-request-antecedents-present", - request.as_ref().is_some_and(RepoMaintainerReviewRequest::has_antecedent_contract), - "Committed maintainer review request requires closure, Soul, Mind, proof, and Bifrost request antecedents." - .to_string(), - ); - push_assertion( - &mut assertions, - "maintainer-review-request-receipt-contract", - request.as_ref().is_some_and(RepoMaintainerReviewRequest::has_receipt_contract), - "Committed maintainer review request names closure, proof, maintainer, and Bifrost receipts." - .to_string(), - ); - push_assertion( - &mut assertions, - "maintainer-review-request-review-packet", - request.as_ref().is_some_and(RepoMaintainerReviewRequest::has_review_packet), - "Committed maintainer review request names reviewer identity, verdict, changed path, proof, and redaction requirements." - .to_string(), - ); - push_assertion( - &mut assertions, - "maintainer-review-request-authority-seals", - request.as_ref().is_some_and(RepoMaintainerReviewRequest::has_authority_seals), - "Committed maintainer review request denies approval/merge/push/publication/sync/action/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "maintainer-review-request-private-seal", - request - .as_ref() - .is_some_and(|request| !request.private_state_exposed), - "Committed maintainer review request preserves the private-state seal.".to_string(), - ); - } - "repo.pr_request" => { - let request = parse_repo_pr_request(&content).ok(); - push_assertion( - &mut assertions, - "pr-request-schema-present", - request - .as_ref() - .is_some_and(RepoPrRequest::has_canonical_identity), - "Committed PR request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "pr-request-family-present", - request - .as_ref() - .is_some_and(RepoPrRequest::has_canonical_identity), - "Committed PR request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "pr-request-summary-present", - request - .as_ref() - .is_some_and(|request| request.summary == compact_summary), - "Committed PR request contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "pr-request-awaits-publication-review", - request - .as_ref() - .is_some_and(RepoPrRequest::awaits_owned_review), - "Committed PR request separates Self routing, Bifrost publication, Hands execution, and GitHub provider outcome." - .to_string(), - ); - push_assertion( - &mut assertions, - "pr-request-antecedents-present", - request.as_ref().is_some_and(RepoPrRequest::has_antecedent_contract), - "Committed PR request requires closure, Soul, Mind, proof, review, Bifrost, and credit antecedents." - .to_string(), - ); - push_assertion( - &mut assertions, - "pr-request-receipt-contract", - request.as_ref().is_some_and(RepoPrRequest::has_receipt_contract), - "Committed PR request names closure, proof, review, Bifrost, credit, and PR publication receipts." - .to_string(), - ); - push_assertion( - &mut assertions, - "pr-request-packet-contract", - request.as_ref().is_some_and(RepoPrRequest::has_packet_contract), - "Committed PR request names branch, title/body, path, proof, review, credit, and redaction requirements." - .to_string(), - ); - push_assertion( - &mut assertions, - "pr-request-authority-seals", - request.as_ref().is_some_and(RepoPrRequest::has_authority_seals), - "Committed PR request denies PR/push/merge/publication/sync/action/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "pr-request-private-seal", - request - .as_ref() - .is_some_and(|request| !request.private_state_exposed), - "Committed PR request preserves the private-state seal.".to_string(), - ); - } - "repo.credit_request" => { - let request = parse_repo_credit_request(&content).ok(); - push_assertion( - &mut assertions, - "credit-request-schema-present", - request - .as_ref() - .is_some_and(RepoCreditRequest::has_canonical_identity), - "Committed credit request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "credit-request-family-present", - request - .as_ref() - .is_some_and(RepoCreditRequest::has_canonical_identity), - "Committed credit request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "credit-request-summary-present", - request - .as_ref() - .is_some_and(|request| request.summary == compact_summary), - "Committed credit request contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "credit-request-awaits-bifrost-review", - request - .as_ref() - .is_some_and(RepoCreditRequest::awaits_bifrost_review), - "Committed credit request waits for Bifrost credit review before consequence." - .to_string(), - ); - push_assertion( - &mut assertions, - "credit-request-antecedents-present", - request.as_ref().is_some_and(RepoCreditRequest::has_antecedent_contract), - "Committed credit request requires closure, Soul, Mind, proof, review, accepted artifact, and authorship antecedents." - .to_string(), - ); - push_assertion( - &mut assertions, - "credit-request-receipt-contract", - request.as_ref().is_some_and(RepoCreditRequest::has_receipt_contract), - "Committed credit request names closure, proof, review, accepted artifact, ledger, and readback receipts." - .to_string(), - ); - push_assertion( - &mut assertions, - "credit-request-packet-contract", - request.as_ref().is_some_and(RepoCreditRequest::has_credit_packet), - "Committed credit request names author, reviewer, artifact, proof, path, ledger, and redaction requirements." - .to_string(), - ); - push_assertion( - &mut assertions, - "credit-request-authority-seals", - request.as_ref().is_some_and(RepoCreditRequest::has_authority_seals), - "Committed credit request denies credit/publication/PR/merge/sync/action/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "credit-request-private-seal", - request - .as_ref() - .is_some_and(|request| !request.private_state_exposed), - "Committed credit request preserves the private-state seal.".to_string(), - ); - } - "repo.artifact_acceptance_request" => { - let request = parse_repo_artifact_acceptance_request(&content).ok(); - push_assertion( - &mut assertions, - "artifact-acceptance-request-schema-present", - request - .as_ref() - .is_some_and(RepoArtifactAcceptanceRequest::has_canonical_identity), - "Committed artifact acceptance request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "artifact-acceptance-request-family-present", - request - .as_ref() - .is_some_and(RepoArtifactAcceptanceRequest::has_canonical_identity), - "Committed artifact acceptance request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "artifact-acceptance-request-summary-present", - request - .as_ref() - .is_some_and(|request| request.summary == compact_summary), - "Committed artifact acceptance request contains the accepted pressure summary." - .to_string(), - ); - push_assertion( - &mut assertions, - "artifact-acceptance-request-awaits-review", - request - .as_ref() - .is_some_and(RepoArtifactAcceptanceRequest::awaits_owned_review), - "Committed artifact acceptance request waits for maintainer/Bifrost review before consequence." - .to_string(), - ); - push_assertion( - &mut assertions, - "artifact-acceptance-request-antecedents-present", - request - .as_ref() - .is_some_and(RepoArtifactAcceptanceRequest::has_antecedent_contract), - "Committed artifact acceptance request requires closure, Soul, Mind, proof, review, and Hands commit antecedents." - .to_string(), - ); - push_assertion( - &mut assertions, - "artifact-acceptance-request-receipt-contract", - request - .as_ref() - .is_some_and(RepoArtifactAcceptanceRequest::has_receipt_contract), - "Committed artifact acceptance request names closure, proof, review, Hands commit, and accepted artifact receipts." - .to_string(), - ); - push_assertion( - &mut assertions, - "artifact-acceptance-request-packet-contract", - request - .as_ref() - .is_some_and(RepoArtifactAcceptanceRequest::has_artifact_packet), - "Committed artifact acceptance request names artifact, commit, path, review, proof, rationale, and redaction requirements." - .to_string(), - ); - push_assertion( - &mut assertions, - "artifact-acceptance-request-authority-seals", - request - .as_ref() - .is_some_and(RepoArtifactAcceptanceRequest::has_authority_seals), - "Committed artifact acceptance request denies acceptance/credit/PR/merge/publication/sync/action/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "artifact-acceptance-request-private-seal", - request - .as_ref() - .is_some_and(|request| !request.private_state_exposed), - "Committed artifact acceptance request preserves the private-state seal." - .to_string(), - ); - } - "repo.metrics_request" => { - let request = parse_repo_metrics_request(&content).ok(); - push_assertion( - &mut assertions, - "metrics-request-schema-present", - request - .as_ref() - .is_some_and(RepoMetricsRequest::has_canonical_identity), - "Committed metrics request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "metrics-request-family-present", - request - .as_ref() - .is_some_and(RepoMetricsRequest::has_canonical_identity), - "Committed metrics request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "metrics-request-summary-present", - request - .as_ref() - .is_some_and(|request| request.summary == compact_summary), - "Committed metrics request contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "metrics-request-awaits-review", - request - .as_ref() - .is_some_and(RepoMetricsRequest::awaits_owned_review), - "Committed metrics request waits for Bifrost/maintainer review before consequence." - .to_string(), - ); - push_assertion( - &mut assertions, - "metrics-request-antecedents-present", - request - .as_ref() - .is_some_and(RepoMetricsRequest::has_antecedent_contract), - "Committed metrics request requires closure, Soul, Mind, proof, accepted artifact, and credit request antecedents." - .to_string(), - ); - push_assertion( - &mut assertions, - "metrics-request-receipt-contract", - request - .as_ref() - .is_some_and(RepoMetricsRequest::has_receipt_contract), - "Committed metrics request names closure, proof, artifact, spend, review-load, and credit readback receipts." - .to_string(), - ); - push_assertion( - &mut assertions, - "metrics-request-packet-contract", - request - .as_ref() - .is_some_and(RepoMetricsRequest::has_metrics_packet), - "Committed metrics request names model-call, cost, review-load, artifact, proof, credit, and redaction requirements." - .to_string(), - ); - push_assertion( - &mut assertions, - "metrics-request-authority-seals", - request - .as_ref() - .is_some_and(RepoMetricsRequest::has_authority_seals), - "Committed metrics request denies metrics/spend/review/credit/PR/merge/publication/sync/action/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "metrics-request-private-seal", - request - .as_ref() - .is_some_and(|request| !request.private_state_exposed), - "Committed metrics request preserves the private-state seal.".to_string(), - ); - } - "repo.readiness_review_request" => { - let request = parse_repo_readiness_review_request(&content).ok(); - push_assertion( - &mut assertions, - "readiness-review-request-schema-present", - request - .as_ref() - .is_some_and(RepoReadinessReviewRequest::has_canonical_identity), - "Committed readiness review request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "readiness-review-request-family-present", - request - .as_ref() - .is_some_and(RepoReadinessReviewRequest::has_canonical_identity), - "Committed readiness review request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "readiness-review-request-summary-present", - request - .as_ref() - .is_some_and(|value| value.summary == compact_summary), - "Committed readiness review request contains the accepted pressure summary." - .to_string(), - ); - push_assertion( - &mut assertions, - "readiness-review-request-awaits-review", - request.as_ref().is_some_and(RepoReadinessReviewRequest::has_coherent_routing), - "Committed readiness review request waits for maintainer/Soul/Mind/Bifrost review before consequence." - .to_string(), - ); - push_assertion( - &mut assertions, - "readiness-review-request-antecedents-present", - request - .as_ref() - .is_some_and(RepoReadinessReviewRequest::has_antecedent_contract), - "Committed readiness review request requires all repo-swarm MVP organ proofs." - .to_string(), - ); - push_assertion( - &mut assertions, - "readiness-review-request-receipt-contract", - request - .as_ref() - .is_some_and(RepoReadinessReviewRequest::has_receipt_contract), - "Committed readiness review request names the MVP proof receipt contract." - .to_string(), - ); - push_assertion( - &mut assertions, - "readiness-review-request-packet-contract", - request.as_ref().is_some_and(RepoReadinessReviewRequest::has_packet_contract), - "Committed readiness review request names proof bundle, branch, upstream, Bifrost, Idunn, tool, redaction, reviewer, and verdict requirements." - .to_string(), - ); - push_assertion( - &mut assertions, - "readiness-review-request-authority-seals", - request.as_ref().is_some_and(RepoReadinessReviewRequest::has_authority_seals), - "Committed readiness review request denies readiness/state/publication/PR/merge/sync/deploy/service/Hands/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "readiness-review-request-private-seal", - request - .as_ref() - .is_some_and(|value| !value.private_state_exposed), - "Committed readiness review request preserves the private-state seal.".to_string(), - ); - } - "repo.doctrine_update_request" => { - let request = parse_repo_doctrine_update_request(&content).ok(); - push_assertion( - &mut assertions, - "doctrine-update-request-schema-present", - request - .as_ref() - .is_some_and(RepoDoctrineUpdateRequest::has_canonical_identity), - "Committed doctrine update request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "doctrine-update-request-family-present", - request - .as_ref() - .is_some_and(RepoDoctrineUpdateRequest::has_canonical_identity), - "Committed doctrine update request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "doctrine-update-request-summary-present", - request - .as_ref() - .is_some_and(|value| value.summary == compact_summary), - "Committed doctrine update request contains the accepted pressure summary." - .to_string(), - ); - push_assertion( - &mut assertions, - "doctrine-update-request-awaits-review", - request.as_ref().is_some_and(RepoDoctrineUpdateRequest::has_coherent_routing), - "Committed doctrine update request waits for Mind/maintainer review before doctrine consequence." - .to_string(), - ); - push_assertion( - &mut assertions, - "doctrine-update-request-antecedents-present", - request.as_ref().is_some_and(RepoDoctrineUpdateRequest::has_antecedent_contract), - "Committed doctrine update request requires feedback, Imagination, Mind, Soul, and maintainer antecedents." - .to_string(), - ); - push_assertion( - &mut assertions, - "doctrine-update-request-receipt-contract", - request.as_ref().is_some_and(RepoDoctrineUpdateRequest::has_receipt_contract), - "Committed doctrine update request names Imagination, Mind, Soul, maintainer, and Hands receipts." - .to_string(), - ); - push_assertion( - &mut assertions, - "doctrine-update-request-packet-contract", - request.as_ref().is_some_and(RepoDoctrineUpdateRequest::has_packet_contract), - "Committed doctrine update request names doctrine diff, invariant, rehydration, rollback, and redaction requirements." - .to_string(), - ); - push_assertion( - &mut assertions, - "doctrine-update-request-authority-seals", - request.as_ref().is_some_and(RepoDoctrineUpdateRequest::has_authority_seals), - "Committed doctrine update request denies doctrine/action/state/publication/service/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "doctrine-update-request-private-seal", - request - .as_ref() - .is_some_and(|value| !value.private_state_exposed), - "Committed doctrine update request preserves the private-state seal.".to_string(), - ); - } - "repo.secret_policy_request" => { - let parsed = parse_repo_secret_policy_request(&content); - let request = parsed.as_ref().ok(); - push_assertion( - &mut assertions, - "secret-policy-request-typed-toml", - parsed.is_ok(), - match parsed.as_ref() { - Ok(_) => "Committed secret policy request parses as typed TOML.".to_string(), - Err(error) => { - format!("Committed secret policy request parse failed: {error:#}") - } - }, - ); - push_assertion( - &mut assertions, - "secret-policy-request-schema-present", - request.is_some_and(RepoSecretPolicyRequest::has_canonical_identity), - "Committed secret policy request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "secret-policy-request-family-present", - request.is_some_and(RepoSecretPolicyRequest::has_canonical_identity), - "Committed secret policy request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "secret-policy-request-summary-present", - request.is_some_and(|request| request.summary == compact_summary), - "Committed secret policy request contains the accepted pressure summary." - .to_string(), - ); - push_assertion( - &mut assertions, - "secret-policy-request-awaits-review", - request.is_some_and(RepoSecretPolicyRequest::awaits_security_review), - "Committed secret policy request waits for security review before consequence." - .to_string(), - ); - push_assertion( - &mut assertions, - "secret-policy-request-antecedents-present", - request.is_some_and(RepoSecretPolicyRequest::has_review_antecedents), - "Committed secret policy request requires source grounding, Soul, Mind, maintainer, and Bifrost review antecedents." - .to_string(), - ); - push_assertion( - &mut assertions, - "secret-policy-request-receipt-contract", - request.is_some_and(RepoSecretPolicyRequest::has_receipt_contract), - "Committed secret policy request names Eyes, Soul, Mind, maintainer, and Bifrost review receipts." - .to_string(), - ); - push_assertion( - &mut assertions, - "secret-policy-request-packet-contract", - request.is_some_and(RepoSecretPolicyRequest::has_security_packet_contract), - "Committed secret policy request names secret-location, credential-owner, write-scope, export, deployment, and rollback requirements." - .to_string(), - ); - push_assertion( - &mut assertions, - "secret-policy-request-authority-seals", - request.is_some_and(RepoSecretPolicyRequest::has_authority_seals), - "Committed secret policy request denies secret/write/deployment/publication/service/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "secret-policy-request-private-seal", - request.is_some_and(|request| !request.private_state_exposed), - "Committed secret policy request preserves the private-state seal.".to_string(), - ); - } - "repo.dependency_policy_request" => { - let parsed = parse_repo_dependency_policy_request(&content); - let request = parsed.as_ref().ok(); - push_assertion( - &mut assertions, - "dependency-policy-request-typed-toml", - parsed.is_ok(), - match parsed.as_ref() { - Ok(_) => { - "Committed dependency policy request parses as typed TOML.".to_string() - } - Err(error) => { - format!("Committed dependency policy request parse failed: {error:#}") - } - }, - ); - push_assertion( - &mut assertions, - "dependency-policy-request-schema-present", - request.is_some_and(RepoDependencyPolicyRequest::has_canonical_identity), - "Committed dependency policy request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "dependency-policy-request-family-present", - request.is_some_and(RepoDependencyPolicyRequest::has_canonical_identity), - "Committed dependency policy request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "dependency-policy-request-summary-present", - request.is_some_and(|request| request.summary == compact_summary), - "Committed dependency policy request contains the accepted pressure summary." - .to_string(), - ); - push_assertion( - &mut assertions, - "dependency-policy-request-awaits-review", - request.is_some_and(RepoDependencyPolicyRequest::awaits_review), - "Committed dependency policy request waits for Maintainer review, Soul verification, Mind admission, Bifrost publication review, and supply-chain audit before consequence." - .to_string(), - ); - push_assertion( - &mut assertions, - "dependency-policy-request-antecedents-present", - request.is_some_and(RepoDependencyPolicyRequest::has_antecedents), - "Committed dependency policy request requires Eyes, Soul, Mind, maintainer, and Bifrost antecedents." - .to_string(), - ); - push_assertion( - &mut assertions, - "dependency-policy-request-receipt-contract", - request.is_some_and(RepoDependencyPolicyRequest::has_receipt_contract), - "Committed dependency policy request names Eyes, Soul, Mind, maintainer, Bifrost, and dependency-audit receipts." - .to_string(), - ); - push_assertion( - &mut assertions, - "dependency-policy-request-packet-contract", - request.is_some_and(RepoDependencyPolicyRequest::has_packet_contract), - "Committed dependency policy request names manifest, lockfile, package-manager, vulnerability, license, vendored-code, update cadence, and redaction requirements." - .to_string(), - ); - push_assertion( - &mut assertions, - "dependency-policy-request-authority-seals", - request.is_some_and(RepoDependencyPolicyRequest::has_authority_seals), - "Committed dependency policy request denies dependency/package/lockfile/network/CI/action/publication/service/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "dependency-policy-request-private-seal", - request.is_some_and(|request| !request.private_state_exposed), - "Committed dependency policy request preserves the private-state seal.".to_string(), - ); - } - "repo.deployment_request" => { - let parsed = parse_repo_deployment_request(&content); - let request = parsed.as_ref().ok(); - push_assertion( - &mut assertions, - "deployment-request-typed-toml", - parsed.is_ok(), - match parsed.as_ref() { - Ok(_) => "Committed deployment request parses as typed TOML.".to_string(), - Err(error) => format!("Committed deployment request parse failed: {error:#}"), - }, - ); - push_assertion( - &mut assertions, - "deployment-request-schema-present", - request.is_some_and(RepoDeploymentRequest::has_canonical_identity), - "Committed deployment request carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "deployment-request-family-present", - request.is_some_and(RepoDeploymentRequest::has_canonical_identity), - "Committed deployment request carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "deployment-request-summary-present", - request.is_some_and(|request| request.summary == compact_summary), - "Committed deployment request contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "deployment-request-awaits-idunn-review", - request.is_some_and(RepoDeploymentRequest::awaits_idunn_review), - "Committed deployment request waits for Idunn/maintainer review before deployment consequence." - .to_string(), - ); - push_assertion( - &mut assertions, - "deployment-request-antecedents-present", - request.is_some_and(RepoDeploymentRequest::has_antecedents), - "Committed deployment request requires Eyes, Mind, Soul, maintainer, secret-policy, and Bifrost antecedents." - .to_string(), - ); - push_assertion( - &mut assertions, - "deployment-request-receipt-contract", - request.is_some_and(RepoDeploymentRequest::has_receipt_contract), - "Committed deployment request names Eyes, Mind, Soul, maintainer, secret-policy, Idunn deployment, and aftercare receipts." - .to_string(), - ); - push_assertion( - &mut assertions, - "deployment-request-packet-contract", - request.is_some_and(RepoDeploymentRequest::has_packet_contract), - "Committed deployment request names environment, git ref, script review, host policy, secret policy, rollback, and aftercare requirements." - .to_string(), - ); - push_assertion( - &mut assertions, - "deployment-request-authority-seals", - request.is_some_and(RepoDeploymentRequest::has_authority_seals), - "Committed deployment request denies deployment/SSH/push/service/action/publication/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "deployment-request-private-seal", - request.is_some_and(|request| !request.private_state_exposed), - "Committed deployment request preserves the private-state seal.".to_string(), - ); - } - "repo.deployment_config" => { - let parsed = parse_repo_deployment_config(&content); - let config = parsed.as_ref().ok(); - push_assertion( - &mut assertions, - "deployment-config-typed-toml", - parsed.is_ok(), - match parsed.as_ref() { - Ok(_) => "Committed deployment config parses as typed TOML.".to_string(), - Err(error) => format!("Committed deployment config parse failed: {error:#}"), - }, - ); - push_assertion( - &mut assertions, - "deployment-config-schema-present", - config.is_some_and(|config| config.has_canonical_identity()), - "Committed deployment config carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-family-present", - config.is_some_and(|config| config.has_canonical_identity()), - "Committed deployment config carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-summary-present", - config.is_some_and(|config| config.summary == compact_summary), - "Committed deployment config contains the accepted pressure summary.".to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-idunn-trigger", - config.is_some_and(|config| config.has_idunn_trigger_contract()), - "Committed deployment config names disabled Idunn git-push trigger, reviewed script/hash, policy, rollback, and aftercare requirements." - .to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-cultmesh-contract", - config.is_some_and(|config| config.has_cultmesh_contract()), - "Committed deployment config routes deployment through Idunn CultMesh contracts." - .to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-receipt-contract", - config.is_some_and(|config| config.has_required_receipt_contract()), - "Committed deployment config names Mind, Soul, maintainer, secret-policy, Idunn deployment, and aftercare receipts." - .to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-authority-seals", - config.is_some_and(|config| config.has_authority_seals()), - "Committed deployment config denies deployment/SSH/push/service/action/publication/cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-private-seal", - config.is_some_and(|config| !config.private_state_exposed), - "Committed deployment config preserves the private-state seal.".to_string(), - ); - } - _ => { - return Ok(( - json!({ - "status": "skipped", - "safeActionFamily": safe_family, - "targetPath": target_path, - "reason": "safe family is manual or has no deterministic closure assertions", - "assertions": assertions - }), - true, - )); - } - } - let passed = assertions - .iter() - .all(|assertion| assertion.get("passed").and_then(Value::as_bool) == Some(true)); - Ok(( - json!({ - "status": if passed { "passed" } else { "failed" }, - "safeActionFamily": safe_family, - "presentationOnly": presentation_only, - "targetPath": target_path, - "planReceiptPath": plan_receipt_path, - "assertions": assertions - }), - passed, - )) -} - -fn push_assertion(assertions: &mut Vec, id: &str, passed: bool, summary: String) { - assertions.push(json!({ - "assertionId": id, - "passed": passed, - "summary": summary, - })); -} - -fn closure_mind_adoption_review(execute_receipt: &Value) -> Result<(Value, bool)> { - let Some(adopt_receipt_path) = path_from_json(execute_receipt, &["adoptReceiptPath"]) else { - return Ok(( - json!({ - "schemaVersion": "epiphany.repo_work_mind_adoption_closure_review.v0", - "status": "failed", - "reason": "execute receipt has no adoptReceiptPath", - "assertions": [] - }), - false, - )); - }; - let adopt_receipt = read_json_if_exists(&adopt_receipt_path)?.unwrap_or(Value::Null); - if adopt_receipt.is_null() { - return Ok(( - json!({ - "schemaVersion": "epiphany.repo_work_mind_adoption_closure_review.v0", - "status": "failed", - "reason": "adopt receipt path is missing", - "adoptReceiptPath": adopt_receipt_path, - "assertions": [] - }), - false, - )); - } - let runtime_store = path_from_json(execute_receipt, &["runtimeStore"]) - .or_else(|| path_from_json(&adopt_receipt, &["runtimeStore"])); - let mind_review_id = string_from_json(&adopt_receipt, &["mindReviewId"]); - let hands_grant_id = string_from_json(&adopt_receipt, &["handsGrantId"]); - let (Some(runtime_store), Some(mind_review_id), Some(hands_grant_id)) = - (runtime_store, mind_review_id, hands_grant_id) - else { - return Ok(( - json!({ - "schemaVersion": "epiphany.repo_work_mind_adoption_closure_review.v0", - "status": "failed", - "reason": "adopt receipt does not bind runtime-spine Mind review and Hands grant ids", - "adoptReceiptPath": adopt_receipt_path, - "assertions": [] - }), - false, - )); - }; - let mind = runtime_repo_work_plan_adoption_review(&runtime_store, &mind_review_id)?; - let grant = runtime_repo_work_hands_grant(&runtime_store, &hands_grant_id)?; - let mut assertions = Vec::new(); - push_assertion( - &mut assertions, - "typed-mind-review-present", - mind.is_some(), - "Runtime-spine contains the typed Mind adoption review.".to_string(), - ); - push_assertion( - &mut assertions, - "typed-hands-grant-present", - grant.is_some(), - "Runtime-spine contains the typed Hands grant derived from Mind adoption.".to_string(), - ); - if let (Some(mind), Some(grant)) = (mind.as_ref(), grant.as_ref()) { - let mind_sha256 = format!("{:x}", Sha256::digest(serde_json::to_vec(mind)?)); - let approved = - runtime_hands_action_review(&runtime_store, &grant.approved_hands_review_id)?; - push_assertion( - &mut assertions, - "mind-review-adopts-exact-plan", - mind.schema_version == epiphany_core::REPO_WORK_PLAN_ADOPTION_REVIEW_SCHEMA_VERSION - && mind.decision == RepoWorkPlanAdoptionDecision::Adopt - && !mind.private_state_exposed, - "Typed Mind review adopts one sealed immutable plan binding.".to_string(), - ); - push_assertion( - &mut assertions, - "hands-grant-binds-mind-review", - grant.schema_version == REPO_WORK_HANDS_GRANT_SCHEMA_VERSION - && grant.adoption_review_id == mind.review_id - && grant.adoption_review_sha256 == mind_sha256 - && grant.workspace_identity == mind.workspace_identity - && grant.plan_id == mind.plan_id - && grant.plan_sha256 == mind.plan_sha256 - && grant.run_receipt_sha256 == mind.run_receipt_sha256 - && grant.changed_paths == mind.changed_paths - && !grant.private_state_exposed, - "Typed Hands grant exactly binds the persisted Mind review and plan/run identity." - .to_string(), - ); - push_assertion( - &mut assertions, - "approved-hands-review-bound", - approved.as_ref().is_some_and(|review| { - review.review_id == grant.approved_hands_review_id - && review.intent_id == grant.hands_intent_id - && review.decision == "approved" - && review.allowed_operations == grant.allowed_operations - }), - "Approved Hands review is the review named by the typed grant.".to_string(), - ); - push_assertion( - &mut assertions, - "execute-receipt-binds-adoption-chain", - execute_receipt_binds_adoption_chain(execute_receipt, mind, grant), - "Execute receipt is cross-bound to the same workspace, plan, run, action, Hands, and Substrate authority chain." - .to_string(), - ); - } - - let passed = assertions - .iter() - .all(|assertion| assertion.get("passed").and_then(Value::as_bool) == Some(true)); - Ok(( - json!({ - "schemaVersion": "epiphany.repo_work_mind_adoption_closure_review.v0", - "status": if passed { "passed" } else { "failed" }, - "adoptReceiptPath": adopt_receipt_path, - "runtimeStore": runtime_store, - "mindReviewId": mind_review_id, - "handsGrantId": hands_grant_id, - "assertions": assertions, - "privateStateExposed": false - }), - passed, - )) -} - -fn execute_receipt_binds_adoption_chain( - execute_receipt: &Value, - mind: &epiphany_core::RepoWorkPlanAdoptionReview, - grant: &RepoWorkHandsGrant, -) -> bool { - let execute_workspace = path_from_json(execute_receipt, &["workspace"]) - .and_then(|path| path.canonicalize().ok()) - .map(|path| normalize_path_for_receipt(&path)); - let execute_plan_path = path_from_json(execute_receipt, &["planReceiptPath"]) - .and_then(|path| path.canonicalize().ok()) - .map(|path| normalize_path_for_receipt(&path)); - execute_workspace.as_deref() == Some(grant.workspace_identity.as_str()) - && string_from_json(execute_receipt, &["item"]).as_deref() == Some(grant.item.as_str()) - && execute_plan_path.as_deref() == Some(grant.plan_receipt_path.as_str()) - && string_from_json(execute_receipt, &["adoptionAuthority", "mindReviewId"]).as_deref() - == Some(mind.review_id.as_str()) - && string_from_json(execute_receipt, &["adoptionAuthority", "handsGrantId"]).as_deref() - == Some(grant.grant_id.as_str()) - && string_from_json(execute_receipt, &["adoptionAuthority", "planId"]).as_deref() - == Some(grant.plan_id.as_str()) - && string_from_json(execute_receipt, &["adoptionAuthority", "planSha256"]).as_deref() - == Some(grant.plan_sha256.as_str()) - && string_from_json(execute_receipt, &["adoptionAuthority", "runReceiptPath"]).as_deref() - == Some(grant.run_receipt_path.as_str()) - && string_from_json(execute_receipt, &["adoptionAuthority", "runReceiptSha256"]).as_deref() - == Some(grant.run_receipt_sha256.as_str()) - && string_from_json(execute_receipt, &["adoptionAuthority", "actionId"]).as_deref() - == Some(grant.action_id.as_str()) - && string_from_json(execute_receipt, &["adoptionAuthority", "handsIntentId"]).as_deref() - == Some(grant.hands_intent_id.as_str()) - && string_from_json( - execute_receipt, - &["adoptionAuthority", "approvedHandsReviewId"], - ) - .as_deref() - == Some(grant.approved_hands_review_id.as_str()) - && string_from_json( - execute_receipt, - &["adoptionAuthority", "substrateGrantReceiptId"], - ) - .as_deref() - == Some(grant.substrate_grant_receipt_id.as_str()) - && string_array_from_json(execute_receipt, &["changedPaths"]) == grant.changed_paths - && string_from_json(execute_receipt, &["command"]).as_deref() - == Some(grant.action_command.as_str()) -} - -fn record_repo_work_map_admission( - runtime_store: &Path, - item: &str, - branch: &str, - changed_paths: Vec, - commit_sha: &str, - closure_review: &Value, - modeling_summary: &str, - modeling_finding_receipt_id: &str, - modeling_route_id: &str, - modeling_generation: u64, - soul_verdict_receipt_id: &str, - mind_gateway_review_id: &str, - mind_state_commit_receipt_id: &str, - execute_receipt_path: &Path, - closure_review_path: &Path, - closure_receipt_path: &Path, - mind_review: &MindGatewayReview, - mind_commit: &epiphany_core::MindStateCommitReceipt, -) -> Result { - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let safe_action_family = - string_from_json(closure_review, &["familyAssertions", "safeActionFamily"]) - .unwrap_or_else(|| "manual-or-unknown".to_string()); - let entry = RepoWorkMapEntry { - schema_version: REPO_WORK_MAP_ENTRY_SCHEMA_VERSION.to_string(), - map_entry_id: format!("repo-work-map-{}", sanitize(item)), - admitted_at: now.clone(), - item: item.to_string(), - branch: branch.to_string(), - changed_paths, - commit_sha: commit_sha.to_string(), - safe_action_family, - modeling_summary: modeling_summary.to_string(), - modeling_finding_receipt_id: modeling_finding_receipt_id.to_string(), - soul_verdict_receipt_id: soul_verdict_receipt_id.to_string(), - mind_gateway_review_id: mind_gateway_review_id.to_string(), - mind_state_commit_receipt_id: mind_state_commit_receipt_id.to_string(), - execute_receipt_path: normalize_path_for_receipt(execute_receipt_path), - closure_review_path: normalize_path_for_receipt(closure_review_path), - closure_receipt_path: normalize_path_for_receipt(closure_receipt_path), - publication_gate: "Bifrost".to_string(), - durable_state_admitted: true, - private_state_exposed: false, - modeling_route_id: modeling_route_id.to_string(), - modeling_generation, - }; - commit_repo_work_map_admission(runtime_store, &entry, mind_review, mind_commit)?; - runtime_repo_work_map_entry(runtime_store, &entry.map_entry_id)? - .ok_or_else(|| anyhow!("committed repo-work map entry could not be reread")) -} - -fn resolve_local_verse_store_from_execute_receipt( - workspace: &Path, - execute_receipt: &Value, -) -> Result> { - if let Some(store) = path_from_json(execute_receipt, &["localVerseStore"]) - .or_else(|| path_from_json(execute_receipt, &["localVerseStorePath"])) - { - return Ok(Some(store)); - } - let Some(adopt_receipt_path) = path_from_json(execute_receipt, &["adoptReceiptPath"]) else { - return Ok(None); - }; - let adopt_receipt = read_json(&adopt_receipt_path)?; - if let Some(store) = path_from_json(&adopt_receipt, &["localVerseStore"]) - .or_else(|| path_from_json(&adopt_receipt, &["localVerseStorePath"])) - { - return Ok(Some(store)); - } - let Some(run_receipt_path) = path_from_json(&adopt_receipt, &["runReceiptPath"]) else { - return Ok(None); - }; - let run_receipt = read_json(&run_receipt_path)?; - if let Some(store) = path_from_json(&run_receipt, &["localVerseStore"]) - .or_else(|| path_from_json(&run_receipt, &["localVerseStorePath"])) - { - return Ok(Some(store)); - } - let Some(online_receipt_path) = path_from_json(&run_receipt, &["onlineReceiptPath"]) else { - return Ok(None); - }; - let online_receipt = read_json(&online_receipt_path)?; - Ok(path_from_json(&online_receipt, &["localVerseStore"]) - .or_else(|| path_from_json(&online_receipt, &["localVerseStorePath"])) - .or_else(|| Some(workspace.join(".epiphany").join("local-verse.ccmp")))) -} - -fn project_repo_work_map_entry_to_local_verse( - local_verse_store: &Path, - runtime_id: &str, - workspace: &Path, - source_store_path: &Path, - entry: &RepoWorkMapEntry, -) -> Result { - let item_slug = sanitize(&entry.item); - let commit_short = short_commit(&entry.commit_sha); - let tui_rows = vec![ - format!("item {}", entry.item), - format!("branch {}", entry.branch), - format!("commit {}", entry.commit_sha), - format!("family {}", entry.safe_action_family), - format!("modeling {}", entry.modeling_finding_receipt_id), - format!("modelingRoute {}", entry.modeling_route_id), - format!("modelingGeneration {}", entry.modeling_generation), - format!("mind {}", entry.mind_state_commit_receipt_id), - format!("publicationGate {}", entry.publication_gate), - "private false".to_string(), - ]; - let map_entry = EpiphanyCultMeshRepoWorkMapEntry { - schema_version: EPIPHANY_CULTMESH_REPO_WORK_MAP_ENTRY_SCHEMA_VERSION.to_string(), - runtime_id: runtime_id.to_string(), - verse_id: EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID.to_string(), - map_entry_id: format!("repo-work-map-{item_slug}"), - admitted_at: entry.admitted_at.clone(), - mirrored_at: Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - workspace: workspace.display().to_string(), - item: entry.item.clone(), - branch: entry.branch.clone(), - changed_paths: entry.changed_paths.clone(), - commit_sha: entry.commit_sha.clone(), - safe_action_family: entry.safe_action_family.clone(), - modeling_summary: entry.modeling_summary.clone(), - modeling_finding_receipt_id: entry.modeling_finding_receipt_id.clone(), - modeling_route_id: entry.modeling_route_id.clone(), - modeling_generation: entry.modeling_generation, - soul_verdict_receipt_id: entry.soul_verdict_receipt_id.clone(), - mind_gateway_review_id: entry.mind_gateway_review_id.clone(), - mind_state_commit_receipt_id: entry.mind_state_commit_receipt_id.clone(), - publication_gate: entry.publication_gate.clone(), - durable_state_admitted: entry.durable_state_admitted, - source_store_path: normalize_path_for_receipt(source_store_path), - tui_rows: vec![format!( - "REPO-WORK-MAP | item={} | branch={} | commit={} | family={} | mind={} | gate={} | private=false", - entry.item, - entry.branch, - commit_short, - entry.safe_action_family, - entry.mind_state_commit_receipt_id, - entry.publication_gate - )] - .into_iter() - .chain(tui_rows) - .collect(), - private_state_exposed: false, - notes: vec![ - "Repo work map entry is compact local Verse sight over Mind-admitted durable state; raw worker thoughts and receipt payload bodies remain sealed.".to_string(), - "Downstream consumers may project this row; the projection grants no scheduling, publication, merge, service lifecycle, deployment, or cross-repo mutation authority.".to_string(), - ], - }; - write_epiphany_cultmesh_repo_work_map_entry(local_verse_store, map_entry) -} - -fn repo_work_map_entry_json(entry: &RepoWorkMapEntry) -> Value { - json!({ - "schemaVersion": entry.schema_version, - "mapEntryId": entry.map_entry_id, - "admittedAt": entry.admitted_at, - "item": entry.item, - "branch": entry.branch, - "changedPaths": entry.changed_paths, - "commitSha": entry.commit_sha, - "safeActionFamily": entry.safe_action_family, - "modelingSummary": entry.modeling_summary, - "modelingFindingReceiptId": entry.modeling_finding_receipt_id, - "modelingRouteId": entry.modeling_route_id, - "modelingGeneration": entry.modeling_generation, - "soulVerdictReceiptId": entry.soul_verdict_receipt_id, - "mindGatewayReviewId": entry.mind_gateway_review_id, - "mindStateCommitReceiptId": entry.mind_state_commit_receipt_id, - "executeReceiptPath": entry.execute_receipt_path, - "closureReviewPath": entry.closure_review_path, - "closureReceiptPath": entry.closure_receipt_path, - "publicationGate": entry.publication_gate, - "durableStateAdmitted": entry.durable_state_admitted, - "privateStateExposed": entry.private_state_exposed, - }) -} - -fn short_commit(commit_sha: &str) -> String { - commit_sha.chars().take(12).collect::() -} - -fn closure_verification_source_grounding_review( - declared_changed_paths: &[String], - verification_stdout: &[u8], - verification_stderr: &[u8], - commit_stat: &str, - required: bool, -) -> (Value, bool) { - let stdout_text = String::from_utf8_lossy(verification_stdout); - let stderr_text = String::from_utf8_lossy(verification_stderr); - let verification_output = format!("{stdout_text}\n{stderr_text}"); - let output_lower = verification_output.to_ascii_lowercase(); - let commit_stat_lower = commit_stat.to_ascii_lowercase(); - let mut path_rows = Vec::new(); - for path in declared_changed_paths { - let path_lower = path.to_ascii_lowercase(); - let slash_variant = path_lower.replace('\\', "/"); - let backslash_variant = path_lower.replace('/', "\\"); - let mentioned_in_verification_output = output_lower.contains(&slash_variant) - || output_lower.contains(&backslash_variant) - || output_lower.contains(&path_lower); - let present_in_commit_stat = commit_stat_lower.contains(&slash_variant) - || commit_stat_lower.contains(&backslash_variant) - || commit_stat_lower.contains(&path_lower); - path_rows.push(json!({ - "path": path, - "mentionedInVerificationOutput": mentioned_in_verification_output, - "presentInCommitStat": present_in_commit_stat, - "passed": mentioned_in_verification_output && present_in_commit_stat - })); - } - let all_paths_mentioned = !declared_changed_paths.is_empty() - && path_rows - .iter() - .all(|row| row.get("passed").and_then(Value::as_bool) == Some(true)); - let passed = !required || all_paths_mentioned; - let status = if all_paths_mentioned { - "passed" - } else if required { - "failed" - } else { - "informational" - }; - ( - json!({ - "schemaVersion": "epiphany.repo_work_verification_source_grounding_review.v0", - "status": status, - "passed": passed, - "required": required, - "declaredPathCount": declared_changed_paths.len(), - "allDeclaredPathsMentionedByVerificationOutput": all_paths_mentioned, - "pathRows": path_rows, - "reason": if all_paths_mentioned { - "verification output and commit stat cite every declared changed path" - } else if required { - "source-grounded closure required verification output to cite every declared changed path" - } else { - "verification output did not cite every declared changed path; recorded as advisory source-grounding signal" - } - }), - passed, - ) -} - -fn read_committed_file( - workspace: &Path, - commit_sha: &str, - repo_path: &str, -) -> Result> { - let spec = format!("{commit_sha}:{repo_path}"); - let output = Command::new("git") - .arg("-C") - .arg(workspace) - .args(["show", &spec]) - .output() - .with_context(|| format!("failed to run git show {spec}"))?; - if output.status.success() { - Ok(Some(String::from_utf8_lossy(&output.stdout).to_string())) - } else { - Ok(None) - } -} - -fn plan_derivation_receipt(input: DeriveSafePlanInput<'_>, mode: &str, safe_family: &str) -> Value { - json!({ - "schemaVersion": "epiphany.repo_work_plan_derivation.v0", - "mode": mode, - "safeActionFamily": safe_family, - "owner": "Imagination", - "router": "Self", - "inputPressure": { - "source": input.source, - "summary": input.summary, - "candidateActionRefs": input.accept_receipt["feedback"]["candidateActionRefs"], - "publicDiscussionRefs": input.accept_receipt["feedback"]["publicDiscussionRefs"], - }, - "operatorAuthoredShellDetails": false, - "modelAuthored": input.model_authored, - "modelRef": input.model_ref, - "deterministicQuarantine": true, - "authoritySeal": { - "branchLocalOnly": true, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthority": false, - "crossRepoMutation": false, - "privateStateExposed": false - }, - "nextUpgrade": "deepen model-authored Imagination action items while keeping Hands command lowering inside allowlisted safe families" - }) -} - -struct ImaginationActionItemReceiptInputs<'a> { - item: &'a str, - source: &'a str, - summary: &'a str, - derive_plan_mode: &'a str, - safe_action_family: &'a str, - requested_paths: Vec, - action_summary: &'a str, - verification_asks: Vec, - stop_conditions: Vec, - escalation_reasons: Vec, - rollback_hints: Vec, - planning_facets: PlanningFacets, - model_ref: Option<&'a str>, - model_authored: bool, -} - -#[derive(Clone, Debug)] -struct PlanningFacets { - assumptions: Vec, - constraints: Vec, - non_goals: Vec, - open_questions: Vec, - decision_points: Vec, - evidence_needs: Vec, -} - -impl PlanningFacets { - fn for_derive_plan( - source: &str, - safe_action_family: &str, - target_path: &str, - assumptions: Vec, - constraints: Vec, - non_goals: Vec, - open_questions: Vec, - decision_points: Vec, - evidence_needs: Vec, - ) -> Self { - Self { - assumptions: default_if_empty( - assumptions, - vec![format!( - "Accepted {source} pressure can be represented by safe family {safe_action_family}." - )], - ), - constraints: default_if_empty( - constraints, - vec![ - format!("Hands may only change the requested path {target_path}."), - "Publication, merge, service lifecycle, elevation, cross-repo mutation, and private-state exposure remain outside this plan.".to_string(), - ], - ), - non_goals: default_if_empty( - non_goals, - vec![ - "Do not convert model-authored planning text into arbitrary shell authority.".to_string(), - "Do not admit durable Mind state without the later Mind gate.".to_string(), - ], - ), - open_questions: default_if_empty( - open_questions, - vec!["Does Self/Mind accept this candidate as the next branch-local move?".to_string()], - ), - decision_points: default_if_empty( - decision_points, - vec![ - "Self/Mind may adopt this action item, ask Imagination for a narrower plan, or route it to Bifrost/Maintainer review.".to_string(), - ], - ), - evidence_needs: default_if_empty( - evidence_needs, - vec![ - "Soul needs the derived plan receipt, changed-path proof, safe-family closure assertions, and private-state seal before closure.".to_string(), - ], - ), - } - } - - fn to_json(&self) -> Value { - json!({ - "assumptions": self.assumptions, - "constraints": self.constraints, - "nonGoals": self.non_goals, - "openQuestions": self.open_questions, - "decisionPoints": self.decision_points, - "evidenceNeeds": self.evidence_needs, - "handsCommandAuthority": false, - "durableStateAuthority": false, - "privateStateExposed": false - }) - } -} - -fn write_imagination_action_items_receipt( - artifact_dir: &Path, - workspace: &Path, - accept_receipt_path: &Path, - accept_receipt: &Value, - inputs: ImaginationActionItemReceiptInputs<'_>, -) -> Result { - if inputs.requested_paths.is_empty() { - return Err(anyhow!( - "Imagination action-item receipts require at least one requested path" - )); - } - let normalized_paths = normalize_paths(inputs.requested_paths.clone()); - let item_slug = sanitize(inputs.item); - let receipt_id = format!("repo-work-action-items-{item_slug}"); - let action_item_id = format!("{receipt_id}-action-1"); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let planning_facets = inputs.planning_facets.to_json(); - let receipt = json!({ - "schemaVersion": "epiphany.repo_work_imagination_action_items_receipt.v0", - "createdAt": now, - "workspace": workspace, - "acceptReceiptPath": accept_receipt_path, - "receiptId": receipt_id, - "item": inputs.item, - "status": "proposed-for-self-mind-review", - "owner": "Imagination", - "router": "Self", - "stateGate": "Mind", - "inputPressure": { - "source": inputs.source, - "summary": inputs.summary, - "feedbackId": accept_receipt["feedback"]["feedbackId"], - "consensusReceiptId": accept_receipt["feedback"]["consensusReceiptId"], - "candidateActionRefs": accept_receipt["feedback"]["candidateActionRefs"], - "publicDiscussionRefs": accept_receipt["feedback"]["publicDiscussionRefs"] - }, - "model": { - "modelAuthored": inputs.model_authored, - "modelRef": inputs.model_ref, - "deterministicFallback": !inputs.model_authored, - "operatorAuthoredShellDetails": false - }, - "actionItems": [{ - "actionItemId": action_item_id, - "status": "candidate", - "derivePlanMode": inputs.derive_plan_mode, - "safeActionFamily": inputs.safe_action_family, - "requestedPaths": normalized_paths, - "summary": inputs.action_summary, - "intendedConsequence": inputs.action_summary, - "verificationAsks": inputs.verification_asks, - "stopConditions": inputs.stop_conditions, - "escalationReasons": inputs.escalation_reasons, - "rollbackHints": inputs.rollback_hints, - "planningFacets": planning_facets, - "handsCommandDerived": false - }], - "authority": { - "handsAuthorityGranted": false, - "durableStateAdmitted": false, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthority": false, - "crossRepoMutation": false, - "privateStateExposed": false, - "nextGate": "self.mind.adoption_then_plan_derivation" - }, - "privateStateExposed": false, - "nextSafeMove": "Self/Mind may adopt one Imagination action item, then derive a Hands plan through an allowlisted safe family." - }); - let receipt_path = artifact_dir.join(format!("work-action-items-{item_slug}.json")); - write_json(&receipt_path, &receipt)?; - Ok(json!({ - "schemaVersion": receipt["schemaVersion"], - "status": receipt["status"], - "workspace": receipt["workspace"], - "receiptPath": receipt_path, - "receiptId": receipt["receiptId"], - "item": receipt["item"], - "actionItems": receipt["actionItems"], - "model": receipt["model"], - "authority": receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": receipt["nextSafeMove"], - })) -} - -fn write_plan_receipt( - workspace: PathBuf, - accept_receipt_path: PathBuf, - accept_receipt: &Value, - artifact_dir: PathBuf, - inputs: PlanReceiptInputs, -) -> Result { - let item = accept_receipt - .get("item") - .and_then(Value::as_str) - .unwrap_or("work-item") - .to_string(); - let item_slug = sanitize(&item); - let normalized_paths = normalize_paths(inputs.changed_paths.clone()); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let plan_id = format!("repo-work-plan-{item_slug}"); - let action_id = format!("{plan_id}-action-1"); - let mut plan_receipt = json!({ - "schemaVersion": "epiphany.repo_work_action_plan_receipt.v0", - "createdAt": now, - "workspace": workspace, - "acceptReceiptPath": accept_receipt_path, - "item": item, - "planId": plan_id, - "status": "planned-for-self-adoption", - "planner": { - "owner": "Imagination", - "router": "Self", - "stateGate": "Mind" - }, - "objective": inputs.objective, - "planSummary": inputs.plan_summary, - "adoptionEvidenceRefs": inputs.adoption_evidence_refs, - "actions": [{ - "actionId": action_id, - "kind": "repo.branch_local_command", - "command": inputs.command, - "changedPaths": normalized_paths, - "commitMessage": inputs.commit_message, - "verificationAsks": inputs.verification_asks, - "stopConditions": inputs.stop_conditions, - "rollbackHints": inputs.rollback_hints - }], - "authority": { - "handsAuthorityGranted": false, - "durableStateAdmitted": false, - "publicationAuthorized": false, - "nextGate": "self.mind.adoption_then_hands" - }, - "privateStateExposed": false, - "nextSafeMove": "Run epiphany-work adopt --from-plan after Self/Mind accept this Imagination action plan." - }); - if let Some(derivation) = inputs.derivation { - plan_receipt["derivation"] = derivation; - } - let receipt_path = artifact_dir.join(format!("work-plan-{item_slug}.json")); - write_json(&receipt_path, &plan_receipt)?; - Ok(json!({ - "schemaVersion": "epiphany.repo_work_plan.v0", - "status": plan_receipt["status"], - "workspace": plan_receipt["workspace"], - "receiptPath": receipt_path, - "item": plan_receipt["item"], - "planId": plan_receipt["planId"], - "objective": plan_receipt["objective"], - "action": plan_receipt["actions"][0], - "derivation": plan_receipt.get("derivation").cloned().unwrap_or(Value::Null), - "authority": plan_receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": plan_receipt["nextSafeMove"], - })) -} - -fn run_adopt(args: AdoptArgs) -> Result { - let workspace = args.workspace.canonicalize()?; - ensure_git_repo(&workspace)?; - let run_path = - resolve_run_receipt(&workspace, args.item.as_deref(), args.run_receipt)?.canonicalize()?; - let plan_path = args - .plan_receipt - .ok_or_else(|| anyhow!("adopt requires --from-plan"))? - .canonicalize()?; - let run = read_json(&run_path)?; - let plan = read_json(&plan_path)?; - let store = args - .runtime_store - .or_else(|| path_from_json(&run, &["runtimeStore"])) - .unwrap_or_else(|| workspace.join(".epiphany/state/runtime-spine.msgpack")); - let gate = run - .get("handsActionGate") - .ok_or_else(|| anyhow!("run receipt has no handsActionGate"))?; - let intent_id = - string_from_value(gate, "intentId").ok_or_else(|| anyhow!("run gate has no intentId"))?; - let queued_id = - string_from_value(gate, "reviewId").ok_or_else(|| anyhow!("run gate has no reviewId"))?; - let intent = runtime_hands_action_intent(&store, &intent_id)? - .ok_or_else(|| anyhow!("missing Hands intent"))?; - let queued = runtime_hands_action_review(&store, &queued_id)? - .ok_or_else(|| anyhow!("missing queued Hands review"))?; - if queued.intent_id != intent.intent_id || queued.decision != "queued-for-adoption" { - return Err(anyhow!("invalid queued Hands review")); - } - let mind = runtime_repo_work_plan_adoption_review(&store, &args.mind_review_id)? - .ok_or_else(|| anyhow!("missing typed Mind adoption review {}", args.mind_review_id))?; - if mind.decision != RepoWorkPlanAdoptionDecision::Adopt { - return Err(anyhow!("Mind did not adopt this plan")); - } - let workspace_id = normalize_path_for_receipt(&workspace); - let item = string_from_json(&run, &["item"]).ok_or_else(|| anyhow!("run has no item"))?; - let plan_schema = string_from_json(&plan, &["schemaVersion"]) - .ok_or_else(|| anyhow!("plan has no schemaVersion"))?; - if plan_schema != "epiphany.repo_work_action_plan_receipt.v0" { - return Err(anyhow!("unsupported repo-work plan schema {plan_schema}")); - } - let plan_id = - string_from_json(&plan, &["planId"]).ok_or_else(|| anyhow!("plan has no planId"))?; - let action = first_plan_action(&plan).ok_or_else(|| anyhow!("plan has no action"))?; - let action_id = - string_from_value(action, "actionId").ok_or_else(|| anyhow!("action has no actionId"))?; - let action_command = - string_from_value(action, "command").ok_or_else(|| anyhow!("action has no command"))?; - let action_commit_message = string_from_value(action, "commitMessage") - .ok_or_else(|| anyhow!("action has no commitMessage"))?; - let raw_paths = string_array_field(action, "changedPaths"); - let paths = strict_repo_work_paths(raw_paths)?; - let plan_hash = file_sha256(&plan_path)?; - let run_hash = file_sha256(&run_path)?; - let plan_path_id = normalize_path_for_receipt(&plan_path); - let run_path_id = normalize_path_for_receipt(&run_path); - if mind.workspace_identity != workspace_id - || mind.item != item - || mind.plan_schema_version != plan_schema - || mind.plan_id != plan_id - || mind.plan_sha256 != plan_hash - || mind.run_receipt_sha256 != run_hash - || mind.plan_receipt_path != plan_path_id - || mind.run_receipt_path != run_path_id - || mind.hands_intent_id != intent.intent_id - || mind.queued_hands_review_id != queued.review_id - || mind.substrate_grant_receipt_id != intent.substrate_gate_grant_receipt_id - || mind.action_id != action_id - || mind.action_command != action_command - || mind.action_commit_message != action_commit_message - || mind.changed_paths != paths - { - return Err(anyhow!( - "Mind review does not exactly bind current plan/run bytes and authority chain" - )); - } - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let approved_id = format!("{}-approved-by-{}", queued.review_id, mind.review_id); - let operations = vec!["patch".into(), "command".into(), "commit".into()]; - let mut approved = hands_action_review_for_intent( - approved_id.clone(), - &intent, - "approved".into(), - operations.clone(), - vec![format!("Mind review {}", mind.review_id)], - now.clone(), - ); - approved.required_receipts = vec![ - HANDS_PATCH_RECEIPT_TYPE.into(), - HANDS_COMMAND_RECEIPT_TYPE.into(), - HANDS_COMMIT_RECEIPT_TYPE.into(), - ]; - let grant_id = format!("repo-work-hands-grant-{}", mind.review_id); - let grant = RepoWorkHandsGrant { - schema_version: REPO_WORK_HANDS_GRANT_SCHEMA_VERSION.into(), - grant_id: grant_id.clone(), - adoption_review_id: mind.review_id.clone(), - adoption_review_sha256: format!("{:x}", Sha256::digest(serde_json::to_vec(&mind)?)), - workspace_identity: workspace_id.clone(), - item: item.clone(), - plan_id: plan_id.clone(), - plan_sha256: plan_hash.clone(), - run_receipt_sha256: run_hash.clone(), - plan_receipt_path: plan_path_id, - run_receipt_path: run_path_id, - hands_intent_id: intent.intent_id.clone(), - queued_hands_review_id: queued.review_id.clone(), - approved_hands_review_id: approved_id.clone(), - substrate_grant_receipt_id: intent.substrate_gate_grant_receipt_id.clone(), - action_id, - action_command, - action_commit_message, - allowed_operations: operations, - changed_paths: paths, - granted_at: now.clone(), - private_state_exposed: false, - }; - commit_repo_work_hands_grant(&store, &grant, &approved)?; - let dir = args - .artifact_dir - .unwrap_or_else(|| workspace.join(".epiphany/work")); - fs::create_dir_all(&dir)?; - let receipt_path = dir.join(format!("work-adopt-{}.json", sanitize(&item))); - let receipt = json!({"schemaVersion":"epiphany.repo_work_adoption_receipt.v1","createdAt":now, - "workspace":workspace_id,"runtimeStore":store,"runReceiptPath":run_path,"runReceiptSha256":run_hash, - "planReceiptPath":plan_path,"planId":plan_id,"planSha256":plan_hash,"item":item, - "status":"approved-for-branch-local-hands-action","mindReviewId":mind.review_id,"handsGrantId":grant_id, - "handsActionGate":{"intentId":intent.intent_id,"queuedReviewId":queued.review_id,"reviewId":approved_id, - "substrateGateGrantReceiptId":intent.substrate_gate_grant_receipt_id}, - "authority":{"handsAuthorityGranted":true,"publicationAuthorized":false,"publicationGate":"Bifrost"},"privateStateExposed":false}); - write_json(&receipt_path, &receipt)?; - Ok( - json!({"schemaVersion":"epiphany.repo_work_adoption.v1","status":receipt["status"],"workspace":receipt["workspace"], - "runtimeStore":receipt["runtimeStore"],"receiptPath":receipt_path,"item":receipt["item"],"mindReviewId":receipt["mindReviewId"], - "handsGrantId":receipt["handsGrantId"],"handsActionGate":receipt["handsActionGate"],"authority":receipt["authority"],"privateStateExposed":false}), - ) -} -fn run_execute(args: ExecuteArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let _epiphany_root = args - .epiphany_root - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.epiphany_root.display()))?; - let adopt_receipt_path = - resolve_adopt_receipt(&workspace, args.item.as_deref(), args.adopt_receipt)?; - let adopt_receipt = read_json(&adopt_receipt_path)?; - let plan_receipt_path = if let Some(path) = args.plan_receipt { - Some(path) - } else { - path_from_json(&adopt_receipt, &["planReceiptPath"]) - }; - let plan_receipt = if let Some(path) = plan_receipt_path.as_ref() { - Some(read_json(path)?) - } else { - None - }; - let runtime_store = args.runtime_store.unwrap_or_else(|| { - path_from_json(&adopt_receipt, &["runtimeStore"]).unwrap_or_else(|| { - workspace - .join(".epiphany") - .join("state") - .join("runtime-spine.msgpack") - }) - }); - let artifact_dir = args - .artifact_dir - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - let gate = adopt_receipt - .get("handsActionGate") - .ok_or_else(|| anyhow!("adopt receipt has no handsActionGate"))?; - let intent_id = gate - .get("intentId") - .and_then(Value::as_str) - .ok_or_else(|| anyhow!("adopt receipt handsActionGate has no intentId"))?; - let review_id = gate - .get("reviewId") - .and_then(Value::as_str) - .ok_or_else(|| anyhow!("adopt receipt handsActionGate has no reviewId"))?; - let intent = runtime_hands_action_intent(&runtime_store, intent_id)? - .ok_or_else(|| anyhow!("runtime-spine has no Hands intent {intent_id}"))?; - let review = runtime_hands_action_review(&runtime_store, review_id)? - .ok_or_else(|| anyhow!("runtime-spine has no Hands review {review_id}"))?; - let grant_id = string_from_json(&adopt_receipt, &["handsGrantId"]) - .ok_or_else(|| anyhow!("adopt receipt has no typed Hands grant id"))?; - let mind_review_id = string_from_json(&adopt_receipt, &["mindReviewId"]) - .ok_or_else(|| anyhow!("adopt receipt has no typed Mind review id"))?; - let grant = runtime_repo_work_hands_grant(&runtime_store, &grant_id)? - .ok_or_else(|| anyhow!("runtime-spine has no repo-work Hands grant {grant_id}"))?; - let mind = runtime_repo_work_plan_adoption_review(&runtime_store, &mind_review_id)? - .ok_or_else(|| anyhow!("runtime-spine has no Mind adoption review {mind_review_id}"))?; - if mind.decision != RepoWorkPlanAdoptionDecision::Adopt - || grant.adoption_review_id != mind.review_id - || grant.approved_hands_review_id != review.review_id - || grant.hands_intent_id != intent.intent_id - || grant.workspace_identity != normalize_path_for_receipt(&workspace) - || grant.adoption_review_sha256 - != format!("{:x}", Sha256::digest(serde_json::to_vec(&mind)?)) - { - return Err(anyhow!( - "execute authority is not bound to its typed Mind review and Hands grant" - )); - } - let plan_path = plan_receipt_path - .as_ref() - .ok_or_else(|| anyhow!("execute requires the exact reviewed plan receipt"))?; - let run_path = path_from_json(&adopt_receipt, &["runReceiptPath"]) - .ok_or_else(|| anyhow!("adopt receipt has no reviewed run receipt path"))?; - let canonical_plan_path = plan_path.canonicalize()?; - let canonical_run_path = run_path.canonicalize()?; - if file_sha256(plan_path)? != grant.plan_sha256 - || file_sha256(&run_path)? != grant.run_receipt_sha256 - || normalize_path_for_receipt(&canonical_plan_path) != grant.plan_receipt_path - || normalize_path_for_receipt(&canonical_run_path) != grant.run_receipt_path - { - return Err(anyhow!( - "reviewed plan or run receipt bytes changed after Mind adoption" - )); - } - ensure_hands_review_allows(&intent, &review, "patch")?; - ensure_hands_review_allows(&intent, &review, "command")?; - ensure_hands_review_allows(&intent, &review, "commit")?; - let planned_action = plan_receipt.as_ref().and_then(first_plan_action).cloned(); - let command = if let Some(command) = args.command { - command - } else if let Some(action) = planned_action.as_ref() { - string_from_value(action, "command").ok_or_else(|| anyhow!("plan action has no command"))? - } else { - return Err(anyhow!("missing --command or --from-plan")); - }; - let changed_paths = if args.changed_paths.is_empty() { - if let Some(action) = planned_action.as_ref() { - string_array_field(action, "changedPaths") - } else { - Vec::new() - } - } else { - args.changed_paths - }; - if strict_repo_work_paths(changed_paths.clone())? != grant.changed_paths { - return Err(anyhow!( - "execute changed paths differ from the typed Hands grant scope" - )); - } - if changed_paths.is_empty() { - return Err(anyhow!( - "execute requires at least one changed path from --changed-path or --from-plan" - )); - } - let commit_message = if let Some(message) = args.commit_message { - message - } else if let Some(action) = planned_action.as_ref() { - string_from_value(action, "commitMessage") - .ok_or_else(|| anyhow!("plan action has no commitMessage"))? - } else { - return Err(anyhow!("missing --commit-message or --from-plan")); - }; - let plan = plan_receipt - .as_ref() - .ok_or_else(|| anyhow!("execute requires reviewed plan"))?; - let item = string_from_json(&adopt_receipt, &["item"]) - .ok_or_else(|| anyhow!("adopt receipt has no item"))?; - let action = planned_action - .as_ref() - .ok_or_else(|| anyhow!("reviewed plan has no action"))?; - if string_from_json(plan, &["schemaVersion"]).as_deref() - != Some("epiphany.repo_work_action_plan_receipt.v0") - || string_from_json(plan, &["planId"]).as_deref() != Some(grant.plan_id.as_str()) - || item != grant.item - || mind.item != grant.item - || mind.plan_receipt_path != grant.plan_receipt_path - || mind.run_receipt_path != grant.run_receipt_path - || mind.action_id != grant.action_id - || string_from_value(action, "actionId").as_deref() != Some(grant.action_id.as_str()) - || command != grant.action_command - || commit_message != grant.action_commit_message - || intent.requested_paths != grant.changed_paths - || grant.queued_hands_review_id - != string_from_json(&adopt_receipt, &["handsActionGate", "queuedReviewId"]) - .unwrap_or_default() - || grant.substrate_grant_receipt_id != intent.substrate_gate_grant_receipt_id - { - return Err(anyhow!( - "execute inputs or authority bindings differ from the reviewed action" - )); - } - validate_paths_within_gate(&intent, &changed_paths)?; - for operation in ["patch", "command", "commit"] { - validate_hands_action_authority( - &runtime_store, - &intent.intent_id, - &review.review_id, - &intent.runtime_job_id, - operation, - &changed_paths, - &grant.substrate_grant_receipt_id, - )?; - } - let branch = git_output(&workspace, &["branch", "--show-current"])?; - if !branch.starts_with("epiphany/") { - return Err(anyhow!( - "execute requires an epiphany/* work branch; current branch is {branch:?}" - )); - } - - let item_slug = sanitize(&item); - let stdout_artifact = artifact_dir.join(format!("work-execute-{item_slug}.stdout.log")); - let stderr_artifact = artifact_dir.join(format!("work-execute-{item_slug}.stderr.log")); - let execution = Command::new("powershell") - .arg("-NoProfile") - .arg("-Command") - .arg(&command) - .current_dir(&workspace) - .output() - .with_context(|| format!("failed to execute command in {}", workspace.display()))?; - fs::write(&stdout_artifact, &execution.stdout) - .with_context(|| format!("failed to write {}", stdout_artifact.display()))?; - fs::write(&stderr_artifact, &execution.stderr) - .with_context(|| format!("failed to write {}", stderr_artifact.display()))?; - let exit_code = execution - .status - .code() - .map(|code| code.to_string()) - .unwrap_or_else(|| "terminated-by-signal".to_string()); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let summary = args - .summary - .unwrap_or_else(|| format!("Executed approved repo work item {item} on branch {branch}.")); - let command_receipt_id = format!("repo-work-execute-{item_slug}-hands-command"); - let command_receipt = hands_command_receipt_for_review( - command_receipt_id, - &intent, - &review, - command.clone(), - exit_code.clone(), - normalize_path_for_receipt(&stdout_artifact), - normalize_path_for_receipt(&stderr_artifact), - summary.clone(), - now.clone(), - ); - put_hands_command_receipt(&runtime_store, &command_receipt)?; - if !execution.status.success() { - let failed_receipt = json!({ - "schemaVersion": "epiphany.repo_work_execute_receipt.v0", - "createdAt": now, - "workspace": workspace, - "runtimeStore": runtime_store, - "adoptReceiptPath": adopt_receipt_path, - "item": item, - "status": "command-failed", - "branch": branch, - "changedPaths": changed_paths, - "planReceiptPath": plan_receipt_path, - "commandReceiptId": command_receipt.receipt_id, - "exitCode": command_receipt.exit_code, - "stdoutArtifact": command_receipt.stdout_artifact, - "stderrArtifact": command_receipt.stderr_artifact, - "privateStateExposed": false, - }); - let receipt_path = artifact_dir.join(format!("work-execute-{item_slug}.json")); - write_json(&receipt_path, &failed_receipt)?; - return Ok(json!({ - "schemaVersion": "epiphany.repo_work_execute.v0", - "status": failed_receipt["status"], - "workspace": failed_receipt["workspace"], - "receiptPath": receipt_path, - "item": failed_receipt["item"], - "handsReceipts": { - "commandReceiptId": failed_receipt["commandReceiptId"] - }, - "privateStateExposed": false, - "nextSafeMove": "Inspect command artifacts and either rerun execution after a new adoption review or record a failure review." - })); - } - - let normalized_paths = normalize_paths(changed_paths.clone()); - let patch_receipt_id = format!("repo-work-execute-{item_slug}-hands-patch"); - let patch_receipt = hands_patch_receipt_for_review( - patch_receipt_id, - &intent, - &review, - normalized_paths.clone(), - summary.clone(), - now.clone(), - ); - put_hands_patch_receipt(&runtime_store, &patch_receipt)?; - git_add_paths(&workspace, &normalized_paths)?; - ensure_staged_changes(&workspace)?; - git_commit(&workspace, &commit_message)?; - let commit_sha = git_output(&workspace, &["rev-parse", "HEAD"])?; - let commit_receipt_id = format!("repo-work-execute-{item_slug}-hands-commit"); - let commit_receipt = hands_commit_receipt_for_review( - commit_receipt_id, - &intent, - &review, - commit_sha, - branch.clone(), - normalized_paths.clone(), - summary.clone(), - Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - ); - put_hands_commit_receipt(&runtime_store, &commit_receipt)?; - - let execute_receipt = json!({ - "schemaVersion": "epiphany.repo_work_execute_receipt.v0", - "createdAt": now, - "workspace": workspace, - "runtimeStore": runtime_store, - "adoptReceiptPath": adopt_receipt_path, - "planReceiptPath": plan_receipt_path, - "item": item, - "status": "branch-local-commit-recorded", - "branch": branch, - "changedPaths": normalized_paths, - "command": command_receipt.command, - "exitCode": command_receipt.exit_code, - "stdoutArtifact": command_receipt.stdout_artifact, - "stderrArtifact": command_receipt.stderr_artifact, - "handsReceipts": { - "patchReceiptId": patch_receipt.receipt_id, - "commandReceiptId": command_receipt.receipt_id, - "commitReceiptId": commit_receipt.receipt_id, - "commitSha": commit_receipt.commit_sha - }, - "adoptionAuthority": { - "mindReviewId": mind.review_id, - "handsGrantId": grant.grant_id, - "planId": grant.plan_id, - "planSha256": grant.plan_sha256, - "runReceiptPath": grant.run_receipt_path, - "runReceiptSha256": grant.run_receipt_sha256, - "actionId": grant.action_id, - "handsIntentId": grant.hands_intent_id, - "approvedHandsReviewId": grant.approved_hands_review_id, - "substrateGrantReceiptId": grant.substrate_grant_receipt_id - }, - "authority": { - "branchLocalCommitCreated": true, - "publicationAuthorized": false, - "durableStateAdmitted": false, - "privateStateExposed": false - }, - "privateStateExposed": false, - "nextSafeMove": "Route Soul verification and Mind review, then submit a Bifrost publication intent through the owning integration." - }); - let receipt_path = artifact_dir.join(format!("work-execute-{item_slug}.json")); - write_json(&receipt_path, &execute_receipt)?; - Ok(json!({ - "schemaVersion": "epiphany.repo_work_execute.v0", - "status": execute_receipt["status"], - "workspace": execute_receipt["workspace"], - "runtimeStore": execute_receipt["runtimeStore"], - "receiptPath": receipt_path, - "item": execute_receipt["item"], - "branch": execute_receipt["branch"], - "changedPaths": execute_receipt["changedPaths"], - "handsReceipts": execute_receipt["handsReceipts"], - "authority": execute_receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": execute_receipt["nextSafeMove"], - })) -} - -fn run_verify(args: CloseArgs) -> Result { - run_closure_pipeline(args, ClosurePhase::SoulOnly) -} - -fn run_revise_modeling(args: ReviseModelingArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let item_slug = sanitize(&args.item); - let close_path = work_receipt_path(&workspace, "close", &args.item); - let close = read_json(&close_path)?; - if close.get("status").and_then(Value::as_str) != Some("awaiting-modeling") { - return Err(anyhow!( - "revise-modeling requires an awaiting-modeling closure projection" - )); - } - let runtime_store = args - .runtime_store - .or_else(|| path_from_json(&close, &["runtimeStore"])) - .ok_or_else(|| anyhow!("awaiting-modeling closure has no runtime store"))?; - let route_id = format!("repo-work-modeling-route-{item_slug}"); - let current = runtime_repo_work_modeling_route(&runtime_store, &route_id)? - .ok_or_else(|| anyhow!("typed Modeling route {route_id:?} is missing"))?; - let current_request = runtime_repo_work_modeling_request(&runtime_store, ¤t.request_id)? - .ok_or_else(|| anyhow!("current Modeling request is missing"))?; - let previous_finding_id = format!("{}-finding", current.request_id); - let previous_finding = - runtime_repo_work_modeling_finding(&runtime_store, &previous_finding_id)? - .ok_or_else(|| anyhow!("revise-modeling requires the current typed finding"))?; - if previous_finding - .verdict - .trim() - .eq_ignore_ascii_case("passed") - { - return Err(anyhow!( - "passing Modeling truth cannot be revised into a retry" - )); - } - let generation = current.generation.saturating_add(1); - let request_id = format!("repo-work-close-{item_slug}-modeling-request-g{generation}"); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let request = RepoWorkModelingRequest { - schema_version: REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION.to_string(), - request_id: request_id.clone(), - item: current.item.clone(), - requester: "mind".to_string(), - soul_verdict_receipt_id: current_request.soul_verdict_receipt_id.clone(), - commit_sha: current_request.commit_sha.clone(), - changed_paths: current_request.changed_paths.clone(), - instruction: format!( - "Re-model the same Soul-verified consequence after reviewed correction {}. Previous finding {} said: {}. Review rationale: {}", - args.review_ref, - previous_finding.receipt_id, - compact_line(&previous_finding.finding), - compact_line(&args.rationale) - ), - requested_at: now.clone(), - private_state_exposed: false, - contract: "Mind-reviewed next generation of one immutable repo-work Modeling route; preserves the Soul-verified consequence and previous finding." - .to_string(), - }; - let gateway_id = format!("repo-work-modeling-route-{item_slug}-g{generation}-mind-review"); - let review = MindGatewayReview { - schema_version: MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(), - gateway_id: gateway_id.clone(), - source_kind: "repo_work_modeling_revision".to_string(), - source_role_id: "mind".to_string(), - decision: MindGatewayDecision::Accept, - allowed_effects: vec!["repoWork.modelingRoute".to_string()], - refused_effects: vec![ - "repoWork.map".to_string(), - "publication".to_string(), - "merge".to_string(), - "handsAction".to_string(), - ], - reasons: vec![ - format!("Reviewed correction reference: {}.", args.review_ref), - format!("Previous immutable verdict: {}.", previous_finding.verdict), - args.rationale.clone(), - ], - contract: "Mind review advances only the current Modeling request generation; it admits no map, publication, merge, or Hands effect." - .to_string(), - }; - let route = RepoWorkModelingRoute { - schema_version: REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION.to_string(), - route_id: current.route_id.clone(), - item: current.item.clone(), - generation, - request_id: request.request_id.clone(), - previous_finding_receipt_id: previous_finding.receipt_id.clone(), - authority_owner: "mind".to_string(), - authority_witness_id: review.gateway_id.clone(), - updated_at: now, - private_state_exposed: false, - contract: "Sole current-generation pointer for repo-work Modeling; older requests and findings remain immutable evidence." - .to_string(), - }; - let route = advance_repo_work_modeling_route(&runtime_store, &request, &route, &review)?; - Ok(json!({ - "schemaVersion": REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION, - "status": "modeling-route-advanced", - "workspace": workspace, - "item": route.item, - "routeId": route.route_id, - "generation": route.generation, - "requestId": route.request_id, - "previousFindingReceiptId": route.previous_finding_receipt_id, - "mindReviewId": route.authority_witness_id, - "reviewRef": args.review_ref, - "privateStateExposed": false, - "nextSafeMove": "Pulse the scheduler to launch the reviewed Modeling generation through Idunn." - })) -} - -fn run_close(args: CloseArgs) -> Result { - run_closure_pipeline(args, ClosurePhase::Full) -} - -fn run_closure_pipeline(args: CloseArgs, phase: ClosurePhase) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let execute_receipt_path = - resolve_execute_receipt(&workspace, args.item.as_deref(), args.execute_receipt)?; - let execute_receipt = read_json(&execute_receipt_path)?; - if execute_receipt.get("status").and_then(Value::as_str) != Some("branch-local-commit-recorded") - { - return Err(anyhow!( - "close requires a branch-local-commit-recorded execute receipt" - )); - } - let runtime_store = args.runtime_store.unwrap_or_else(|| { - path_from_json(&execute_receipt, &["runtimeStore"]).unwrap_or_else(|| { - workspace - .join(".epiphany") - .join("state") - .join("runtime-spine.msgpack") - }) - }); - let artifact_dir = args - .artifact_dir - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - let item = execute_receipt - .get("item") - .and_then(Value::as_str) - .unwrap_or("work-item") - .to_string(); - let item_slug = sanitize(&item); - let commit_sha = string_from_json(&execute_receipt, &["handsReceipts", "commitSha"]) - .ok_or_else(|| anyhow!("execute receipt has no handsReceipts.commitSha"))?; - let patch_receipt_id = string_from_json(&execute_receipt, &["handsReceipts", "patchReceiptId"]) - .ok_or_else(|| anyhow!("execute receipt has no handsReceipts.patchReceiptId"))?; - let command_receipt_id = - string_from_json(&execute_receipt, &["handsReceipts", "commandReceiptId"]) - .ok_or_else(|| anyhow!("execute receipt has no handsReceipts.commandReceiptId"))?; - let commit_receipt_id = - string_from_json(&execute_receipt, &["handsReceipts", "commitReceiptId"]) - .ok_or_else(|| anyhow!("execute receipt has no handsReceipts.commitReceiptId"))?; - let commit_receipt = runtime_hands_commit_receipt(&runtime_store, &commit_receipt_id)? - .ok_or_else(|| anyhow!("runtime-spine has no Hands commit receipt {commit_receipt_id}"))?; - if commit_receipt.commit_sha != commit_sha { - return Err(anyhow!( - "execute receipt commit sha does not match runtime Hands commit receipt" - )); - } - let verification_command = format!("git show --stat --oneline {commit_sha}"); - let stdout_artifact = artifact_dir.join(format!("work-close-{item_slug}.stdout.log")); - let stderr_artifact = artifact_dir.join(format!("work-close-{item_slug}.stderr.log")); - let verification = Command::new("powershell") - .arg("-NoProfile") - .arg("-Command") - .arg(&verification_command) - .current_dir(&workspace) - .output() - .with_context(|| { - format!( - "failed to run closure verification in {}", - workspace.display() - ) - })?; - fs::write(&stdout_artifact, &verification.stdout) - .with_context(|| format!("failed to write {}", stdout_artifact.display()))?; - fs::write(&stderr_artifact, &verification.stderr) - .with_context(|| format!("failed to write {}", stderr_artifact.display()))?; - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let declared_changed_paths = - sorted_normalized_paths(string_array_from_json(&execute_receipt, &["changedPaths"])); - let actual_changed_paths = sorted_normalized_paths( - git_output( - &workspace, - &[ - "diff-tree", - "--no-commit-id", - "--name-only", - "-r", - &commit_sha, - ], - )? - .lines() - .map(ToString::to_string) - .collect(), - ); - let path_scope_matched = declared_changed_paths == actual_changed_paths; - let commit_stat = git_output(&workspace, &["show", "--stat", "--oneline", &commit_sha])?; - let (verification_source_grounding, verification_source_grounded) = - closure_verification_source_grounding_review( - &declared_changed_paths, - &verification.stdout, - &verification.stderr, - &commit_stat, - true, - ); - let verification_output_mentions_changed_paths = bool_from_json( - &verification_source_grounding, - &["allDeclaredPathsMentionedByVerificationOutput"], - ) - .unwrap_or(false); - let (family_assertions, family_assertions_passed) = - closure_family_assertions(&workspace, &commit_sha, &execute_receipt, &item)?; - let (mind_adoption_review, mind_adoption_passed) = - closure_mind_adoption_review(&execute_receipt)?; - let model_closure_review = json!({ - "schemaVersion": "epiphany.repo_work_model_closure_review.v0", - "status": "deferred-to-typed-modeling", - "passed": false, - "required": true, - "source": "runtime-spine Modeling finding", - "callerEchoAccepted": false, - "privateStateExposed": false - }); - let closure_review_id = format!("repo-work-close-{item_slug}-closure-review"); - let closure_review_path = artifact_dir.join(format!("work-close-{item_slug}-review.json")); - let closure_review = json!({ - "schemaVersion": "epiphany.repo_work_closure_review.v0", - "createdAt": now, - "workspace": workspace, - "receiptId": closure_review_id, - "item": item, - "owner": "Soul", - "stateGate": "Mind", - "executeReceiptPath": execute_receipt_path, - "runtimeStore": runtime_store, - "handsReceipts": { - "patchReceiptId": patch_receipt_id, - "commandReceiptId": command_receipt_id, - "commitReceiptId": commit_receipt_id, - "commitSha": commit_sha - }, - "verification": { - "command": verification_command, - "exitCode": verification.status.code(), - "stdoutArtifact": normalize_path_for_receipt(&stdout_artifact), - "stderrArtifact": normalize_path_for_receipt(&stderr_artifact), - "passed": verification.status.success() - }, - "sourceGrounding": { - "declaredChangedPaths": declared_changed_paths, - "actualChangedPaths": actual_changed_paths, - "pathScopeMatched": path_scope_matched, - "commitStat": compact_multiline(&commit_stat), - "commitReceiptMatchedExecuteReceipt": true, - "verificationOutputMentionsChangedPaths": verification_output_mentions_changed_paths, - "sourceGroundingRequired": true, - "mindAdoptionPassed": mind_adoption_passed, - "familyAssertionsPassed": family_assertions_passed, - "modelClosurePassed": false - }, - "verificationSourceGrounding": verification_source_grounding, - "mindAdoptionReview": mind_adoption_review, - "familyAssertions": family_assertions, - "modelingReview": { - "modelAuthored": false, - "modelRef": Value::Null, - "deterministicFallback": false, - "source": "runtime-spine Modeling finding", - "callerEchoAccepted": false, - "operatorAuthoredShellDetails": false, - "summary": "Modeling truth is resolved from the runtime-spine finding, not caller text.", - "closureReview": model_closure_review - }, - "authoritySeal": { - "branchLocalOnly": true, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthority": false, - "crossRepoMutation": false, - "privateStateExposed": false - }, - "privateStateExposed": false, - "nextSafeMove": "Soul may pass closure only when verification succeeds, actual git changed paths match the Hands-declared path scope, the accepted Mind adoption proof is present, safe-family assertions pass for known Imagination families, and any supplied or required model-authored closure verdict passes." - }); - write_json(&closure_review_path, &closure_review)?; - let soul_verification_passed = verification.status.success() - && path_scope_matched - && verification_source_grounded - && mind_adoption_passed - && family_assertions_passed; - let soul_verdict_id = format!("repo-work-close-{item_slug}-soul-verdict"); - let soul_summary = if soul_verification_passed { - format!("Soul verified branch-local commit {commit_sha} for repo work item {item}.") - } else if !path_scope_matched { - format!( - "Soul verification failed for branch-local commit {commit_sha}: actual changed paths did not match declared Hands path scope." - ) - } else if !verification_source_grounded { - format!( - "Soul verification failed for branch-local commit {commit_sha}: verification output did not cite every declared changed path." - ) - } else if !mind_adoption_passed { - format!( - "Soul verification failed for branch-local commit {commit_sha}: Mind adoption proof did not pass." - ) - } else if !family_assertions_passed { - format!( - "Soul verification failed for branch-local commit {commit_sha}: safe-family assertions did not pass." - ) - } else { - format!("Soul verification failed for branch-local commit {commit_sha}.") - }; - let mut evidence_ids = vec![ - patch_receipt_id.clone(), - command_receipt_id.clone(), - commit_receipt_id.clone(), - normalize_path_for_receipt(&stdout_artifact), - normalize_path_for_receipt(&stderr_artifact), - normalize_path_for_receipt(&closure_review_path), - ]; - evidence_ids.extend(declared_changed_paths.clone()); - let mut soul_verdict = SoulVerdictReceipt { - schema_version: SOUL_VERDICT_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: soul_verdict_id.clone(), - source_result_id: format!("repo-work-execute-{item_slug}"), - source_job_id: format!("repo-work-close-{item_slug}"), - verdict: if soul_verification_passed { - "passed".to_string() - } else { - "failed".to_string() - }, - summary: soul_summary.clone(), - evidence_ids: evidence_ids.clone(), - risks: if soul_verification_passed { - Vec::new() - } else if !path_scope_matched { - vec![ - "Closure refused because actual git changed paths differ from Hands-declared scope." - .to_string(), - ] - } else if !verification_source_grounded { - vec![ - "Closure refused because the verification output did not cite every declared changed path while source grounding was required." - .to_string(), - ] - } else if !mind_adoption_passed { - vec![ - "Closure refused because the Mind adoption decision was missing, tampered, or non-affirmative." - .to_string(), - ] - } else if !family_assertions_passed { - vec![ - "Closure refused because the committed content did not satisfy known safe-family assertions." - .to_string(), - ] - } else { - vec!["Closure verification command failed; publication remains blocked.".to_string()] - }, - emitted_at: now.clone(), - contract: "Soul verdict for repo-work closure; verifies the Hands patch/command/commit consequence before Modeling/Mind closure and Bifrost publication.".to_string(), - }; - if let Some(existing) = - epiphany_core::runtime_soul_verdict_receipt(&runtime_store, &soul_verdict.receipt_id)? - { - soul_verdict.emitted_at = existing.emitted_at.clone(); - if soul_verdict != existing { - return Err(anyhow!( - "closure retry conflicts with immutable Soul verdict receipt" - )); - } - soul_verdict = existing; - } else { - put_soul_verdict_receipt(&runtime_store, &soul_verdict)?; - } - - let closure_receipt_path = artifact_dir.join(format!("work-close-{item_slug}.json")); - if !soul_verification_passed { - let failed_receipt = json!({ - "schemaVersion": "epiphany.repo_work_closure_receipt.v0", - "createdAt": now, - "workspace": workspace, - "runtimeStore": runtime_store, - "executeReceiptPath": execute_receipt_path, - "item": item, - "status": "verification-failed", - "soul": { - "verdictReceiptId": soul_verdict.receipt_id, - "verdict": soul_verdict.verdict, - "summary": soul_verdict.summary, - "stdoutArtifact": normalize_path_for_receipt(&stdout_artifact), - "stderrArtifact": normalize_path_for_receipt(&stderr_artifact), - "closureReviewReceiptId": closure_review_id, - "closureReviewPath": normalize_path_for_receipt(&closure_review_path) - }, - "closureReview": closure_review, - "authority": { - "branchLocalOnly": true, - "publicationGateSatisfied": false, - "durableStateAdmitted": false, - "privateStateExposed": false - }, - "privateStateExposed": false, - "nextSafeMove": "Repair or re-run branch-local work, then close again before publication." - }); - write_json(&closure_receipt_path, &failed_receipt)?; - return Ok(json!({ - "schemaVersion": "epiphany.repo_work_closure.v0", - "status": failed_receipt["status"], - "workspace": failed_receipt["workspace"], - "receiptPath": closure_receipt_path, - "item": failed_receipt["item"], - "soul": failed_receipt["soul"], - "closureReview": failed_receipt["closureReview"], - "authority": failed_receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": failed_receipt["nextSafeMove"], - })); - } - - let modeling_route_id = format!("repo-work-modeling-route-{item_slug}"); - let (modeling_request, modeling_route) = if phase == ClosurePhase::Full { - let route = runtime_repo_work_modeling_route(&runtime_store, &modeling_route_id)? - .ok_or_else(|| anyhow!("closure requires the typed Modeling route"))?; - let request = runtime_repo_work_modeling_request(&runtime_store, &route.request_id)? - .ok_or_else(|| anyhow!("closure requires the current typed Modeling request"))?; - (request, route) - } else { - let modeling_request_id = format!("repo-work-close-{item_slug}-modeling-request"); - let mut request = RepoWorkModelingRequest { - schema_version: REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION.to_string(), - request_id: modeling_request_id.clone(), - item: item.clone(), - requester: "self".to_string(), - soul_verdict_receipt_id: soul_verdict.receipt_id.clone(), - commit_sha: commit_sha.clone(), - changed_paths: declared_changed_paths.clone(), - instruction: "Model the Soul-verified consequence and return a bounded repo-map finding; do not admit state or route the next action.".to_string(), - requested_at: Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - private_state_exposed: false, - contract: "Self-to-Modeling request over a passing Soul verdict; Self may route but cannot author the result.".to_string(), - }; - if let Some(existing) = - runtime_repo_work_modeling_request(&runtime_store, &modeling_request_id)? - { - request.requested_at = existing.requested_at.clone(); - if request != existing { - return Err(anyhow!( - "closure retry conflicts with immutable Modeling request" - )); - } - request = existing; - } - let mut route = RepoWorkModelingRoute { - schema_version: REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION.to_string(), - route_id: modeling_route_id.clone(), - item: item.clone(), - generation: 0, - request_id: request.request_id.clone(), - previous_finding_receipt_id: String::new(), - authority_owner: "soul".to_string(), - authority_witness_id: soul_verdict.receipt_id.clone(), - updated_at: Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - private_state_exposed: false, - contract: "Current repo-work Modeling generation; generation zero is established atomically with its Soul-backed request, and later movement requires Mind review." - .to_string(), - }; - if let Some(existing) = - runtime_repo_work_modeling_route(&runtime_store, &modeling_route_id)? - { - route.updated_at = existing.updated_at.clone(); - } - let route = commit_initial_repo_work_modeling_route(&runtime_store, &request, &route)?; - (request, route) - }; - if phase == ClosurePhase::SoulOnly { - let awaiting_receipt = json!({ - "schemaVersion": "epiphany.repo_work_closure_receipt.v0", - "createdAt": now, - "workspace": workspace, - "runtimeStore": runtime_store, - "executeReceiptPath": execute_receipt_path, - "item": item, - "status": "awaiting-modeling", - "soul": { - "verdictReceiptId": soul_verdict.receipt_id, - "verdict": soul_verdict.verdict, - "summary": soul_verdict.summary, - "closureReviewReceiptId": closure_review_id, - "closureReviewPath": normalize_path_for_receipt(&closure_review_path) - }, - "closureReview": closure_review, - "modeling": { - "requestId": modeling_request.request_id, - "routeId": modeling_route.route_id, - "generation": modeling_route.generation, - "requester": modeling_request.requester, - "findingReceiptId": Value::Null - }, - "authority": { - "owner": "Self", - "routedSoulResult": true, - "authoredModelingFinding": false, - "publicationGateSatisfied": false, - "durableStateAdmitted": false, - "privateStateExposed": false - }, - "privateStateExposed": false, - "nextSafeMove": "Route the typed request to Modeling and resume closure only with its matching finding." - }); - write_json(&closure_receipt_path, &awaiting_receipt)?; - return Ok(awaiting_receipt); - } - let modeling_finding_receipt_id = format!("{}-finding", modeling_request.request_id); - let modeling_finding = - runtime_repo_work_modeling_finding(&runtime_store, &modeling_finding_receipt_id)? - .ok_or_else(|| { - anyhow!( - "closure requires the persisted Modeling finding {}; caller-authored echoes are not accepted", - modeling_finding_receipt_id - ) - })?; - if modeling_finding.soul_verdict_receipt_id != soul_verdict.receipt_id - || modeling_finding.commit_sha != commit_sha - || modeling_finding.changed_paths != declared_changed_paths - || modeling_finding.verdict.trim().to_ascii_lowercase() != "passed" - { - return Err(anyhow!( - "persisted Modeling finding does not match Soul-verified consequence" - )); - } - let gateway_id = format!("repo-work-close-{item_slug}-mind-review"); - let mind_review = MindGatewayReview { - schema_version: MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(), - gateway_id: gateway_id.clone(), - source_kind: "repo_work_closure".to_string(), - source_role_id: "modeling".to_string(), - decision: MindGatewayDecision::Accept, - allowed_effects: vec![ - "repoWorkClosure".to_string(), - "modelingFinding".to_string(), - "publicationGate".to_string(), - ], - refused_effects: Vec::new(), - reasons: vec![ - "Soul passed the branch-local Hands consequence.".to_string(), - format!("Mind reread typed Modeling finding {}.", modeling_finding.receipt_id), - "Mind admits closure metadata only; Bifrost still gates publication and merge.".to_string(), - ], - contract: "Mind review for repo-work closure; admits the verified Modeling summary and publication gate without granting merge or service authority.".to_string(), - }; - let mind_commit_id = format!("repo-work-close-{item_slug}-mind-commit"); - let mind_commit = mind_state_commit_receipt( - mind_commit_id.clone(), - &mind_review, - 0, - vec![ - "repoWork.closure".to_string(), - "repoWork.modelingFinding".to_string(), - "repoWork.map".to_string(), - ], - Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - ); - let branch = git_output(&workspace, &["branch", "--show-current"])?; - let repo_map_entry = record_repo_work_map_admission( - &runtime_store, - &item, - &branch, - declared_changed_paths.clone(), - &commit_sha, - &closure_review, - &modeling_finding.summary, - &modeling_finding.receipt_id, - &modeling_route.route_id, - modeling_route.generation, - &soul_verdict.receipt_id, - &mind_review.gateway_id, - &mind_commit.receipt_id, - &execute_receipt_path, - &closure_review_path, - &closure_receipt_path, - &mind_review, - &mind_commit, - )?; - let runtime_id = string_from_json(&execute_receipt, &["runtimeId"]) - .unwrap_or_else(|| "repo-swarm-local".to_string()); - let local_verse_store = - resolve_local_verse_store_from_execute_receipt(&workspace, &execute_receipt)?; - let repo_map_local_verse_projection = if let Some(local_verse_store) = - local_verse_store.as_ref() - { - let written = project_repo_work_map_entry_to_local_verse( - local_verse_store, - &runtime_id, - &workspace, - &runtime_store, - &repo_map_entry, - )?; - json!({ - "projected": true, - "localVerseStore": normalize_path_for_receipt(local_verse_store), - "documentType": "epiphany.cultmesh.repo_work_map_entry", - "schemaVersion": written.schema_version, - "mapEntryId": written.map_entry_id, - "latestKey": EPIPHANY_CULTMESH_REPO_WORK_MAP_ENTRY_LATEST_KEY, - "tuiRows": written.tui_rows, - "privateStateExposed": written.private_state_exposed - }) - } else { - json!({ - "projected": false, - "reason": "local Verse store could not be resolved from execute/adopt/run/online receipts", - "privateStateExposed": false - }) - }; - - let closure_receipt = json!({ - "schemaVersion": "epiphany.repo_work_closure_receipt.v0", - "createdAt": now, - "workspace": workspace, - "runtimeStore": runtime_store, - "executeReceiptPath": execute_receipt_path, - "item": item, - "status": "closed", - "handsReceipts": { - "patchReceiptId": patch_receipt_id, - "commandReceiptId": command_receipt_id, - "commitReceiptId": commit_receipt_id, - "commitSha": commit_sha - }, - "soul": { - "verdictReceiptId": soul_verdict.receipt_id, - "verdict": soul_verdict.verdict, - "summary": soul_verdict.summary, - "stdoutArtifact": normalize_path_for_receipt(&stdout_artifact), - "stderrArtifact": normalize_path_for_receipt(&stderr_artifact), - "closureReviewReceiptId": closure_review_id, - "closureReviewPath": normalize_path_for_receipt(&closure_review_path) - }, - "closureReview": closure_review, - "modeling": { - "requestId": modeling_request.request_id, - "findingReceiptId": modeling_finding.receipt_id, - "summary": modeling_finding.summary, - "changedPaths": execute_receipt["changedPaths"], - "commitSha": execute_receipt["handsReceipts"]["commitSha"], - "source": "runtime-spine Modeling finding", - "modelAuthored": true - }, - "mind": { - "gatewayReviewId": mind_review.gateway_id, - "stateCommitReceiptId": mind_commit.receipt_id, - "stateRevision": mind_commit.state_revision, - "changedFields": mind_commit.changed_fields, - "repoMapStorePath": normalize_path_for_receipt(&runtime_store), - "repoMapEntry": repo_work_map_entry_json(&repo_map_entry), - "repoMapLocalVerseProjection": repo_map_local_verse_projection - }, - "authority": { - "branchLocalOnly": true, - "publicationGateSatisfied": true, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthorized": false, - "crossRepoMutationAuthorized": false, - "durableStateAdmitted": true, - "privateStateExposed": false - }, - "privateStateExposed": false, - "nextSafeMove": "Submit a Bifrost publication intent through the owning integration; merge remains gated by provider-authored maintainer evidence." - }); - write_json(&closure_receipt_path, &closure_receipt)?; - Ok(json!({ - "schemaVersion": "epiphany.repo_work_closure.v0", - "status": closure_receipt["status"], - "workspace": closure_receipt["workspace"], - "runtimeStore": closure_receipt["runtimeStore"], - "receiptPath": closure_receipt_path, - "item": closure_receipt["item"], - "handsReceipts": closure_receipt["handsReceipts"], - "soul": closure_receipt["soul"], - "closureReview": closure_receipt["closureReview"], - "modeling": closure_receipt["modeling"], - "mind": closure_receipt["mind"], - "authority": closure_receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": closure_receipt["nextSafeMove"], - })) -} - -fn run_overview(args: OverviewArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let artifact_dir = args - .artifact_dir - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - - let accept_receipt_path = - resolve_accept_receipt(&workspace, args.item.as_deref(), args.accept_receipt)?; - let accept_receipt = read_json(&accept_receipt_path)?; - let runtime_id = string_from_json(&accept_receipt, &["runtimeId"]) - .unwrap_or_else(|| "repo-swarm-local".to_string()); - let local_verse_store = path_from_json(&accept_receipt, &["localVerseStore"]) - .or_else(|| path_from_json(&accept_receipt, &["localVerseStorePath"])); - let item = accept_receipt - .get("item") - .and_then(Value::as_str) - .unwrap_or("work-item") - .to_string(); - let item_slug = sanitize(&item); - - let plan_receipt_path = work_receipt_path(&workspace, "plan", &item); - let run_receipt_path = work_receipt_path(&workspace, "run", &item); - let adopt_receipt_path = work_receipt_path(&workspace, "adopt", &item); - let execute_receipt_path = work_receipt_path(&workspace, "execute", &item); - let close_receipt_path = work_receipt_path(&workspace, "close", &item); - let close_review_receipt_path = - artifact_dir.join(format!("work-close-{item_slug}-review.json")); - let overview_receipt_path = artifact_dir.join(format!("work-overview-{item_slug}.json")); - - let plan_receipt = read_json_if_exists(&plan_receipt_path)?; - let run_receipt = read_json_if_exists(&run_receipt_path)?; - let adopt_receipt = read_json_if_exists(&adopt_receipt_path)?; - let execute_receipt = read_json_if_exists(&execute_receipt_path)?; - let close_receipt = read_json_if_exists(&close_receipt_path)?; - - let branch = git_output(&workspace, &["rev-parse", "--abbrev-ref", "HEAD"])?; - let commit_sha = execute_receipt - .as_ref() - .and_then(|receipt| string_from_json(receipt, &["handsReceipts", "commitSha"])); - let changed_paths = execute_receipt - .as_ref() - .map(|receipt| string_array_from_json(receipt, &["changedPaths"])) - .or_else(|| { - plan_receipt.as_ref().and_then(|receipt| { - first_plan_action(receipt).map(|action| string_array_field(action, "changedPaths")) - }) - }) - .unwrap_or_default(); - let closure_status = close_receipt - .as_ref() - .and_then(|receipt| receipt.get("status").and_then(Value::as_str)) - .unwrap_or("missing"); - let soul_verdict = close_receipt - .as_ref() - .and_then(|receipt| string_from_json(receipt, &["soul", "verdict"])) - .unwrap_or_else(|| "missing".to_string()); - let publication_status = "provider-evidence-not-resolved"; - let sync_status = "provider-evidence-not-resolved"; - let (gate, blocker, next_safe_move) = repo_work_overview_gate( - plan_receipt.as_ref(), - run_receipt.as_ref(), - adopt_receipt.as_ref(), - execute_receipt.as_ref(), - close_receipt.as_ref(), - ); - let public_discussion_refs = - string_array_from_json(&accept_receipt, &["feedback", "publicDiscussionRefs"]); - let candidate_action_refs = - string_array_from_json(&accept_receipt, &["feedback", "candidateActionRefs"]); - let feedback_id = string_from_json(&accept_receipt, &["feedback", "feedbackId"]) - .unwrap_or_else(|| "missing".to_string()); - let consensus_receipt_id = - string_from_json(&accept_receipt, &["feedback", "consensusReceiptId"]) - .unwrap_or_else(|| "missing".to_string()); - let consensus_route = - string_from_json(&accept_receipt, &["feedback", "requestedConsensusRoute"]) - .unwrap_or_else(|| "missing".to_string()); - let consensus_packet_ref = - string_from_json(&accept_receipt, &["feedback", "consensusPacketRef"]) - .unwrap_or_else(|| "missing".to_string()); - let adoption_gate = string_from_json(&accept_receipt, &["feedback", "adoptionGate"]) - .unwrap_or_else(|| "missing".to_string()); - let plan_action_item = plan_receipt - .as_ref() - .and_then(|receipt| receipt.get("derivation")) - .and_then(|value| value.get("actionItemReceipt")); - let plan_action_item_receipt_id = plan_action_item - .and_then(|value| value.get("receiptId")) - .and_then(Value::as_str) - .unwrap_or("missing") - .to_string(); - let plan_safe_action_family = plan_action_item - .and_then(|value| value.get("safeActionFamily")) - .and_then(Value::as_str) - .unwrap_or("missing") - .to_string(); - let plan_model_authored = plan_action_item - .and_then(|value| value.get("modelAuthored")) - .and_then(Value::as_bool) - .unwrap_or(false); - let intake_consensus_readback = json!({ - "schemaVersion": "epiphany.repo_work_intake_consensus_readback.v0", - "owner": "Self", - "handoffRoute": "Persona->Imagination", - "item": item, - "feedbackId": feedback_id, - "consensusReceiptId": consensus_receipt_id, - "requestedConsensusRoute": consensus_route, - "consensusPacketRef": consensus_packet_ref, - "adoptionGate": adoption_gate, - "publicDiscussionRefs": public_discussion_refs, - "publicDiscussionRefCount": public_discussion_refs.len(), - "candidateActionRefs": candidate_action_refs, - "candidateActionRefCount": candidate_action_refs.len(), - "planActionItemsReceiptId": plan_action_item_receipt_id, - "planSafeActionFamily": plan_safe_action_family, - "planModelAuthored": plan_model_authored, - "handsAuthorityGranted": false, - "durableStateAdmitted": false, - "publicationAuthorized": false, - "privateStateExposed": false - }); - let tui_rows = vec![ - format!("item {item}"), - format!("branch {branch}"), - format!("gate {gate}"), - format!("blocker {blocker}"), - format!("next {next_safe_move}"), - format!( - "CONSENSUS | feedback={} | receipt={} | route={} | publicRefs={} | candidates={} | planFamily={} | modelAuthored={} | private=false", - intake_consensus_readback["feedbackId"] - .as_str() - .unwrap_or("missing"), - intake_consensus_readback["consensusReceiptId"] - .as_str() - .unwrap_or("missing"), - intake_consensus_readback["requestedConsensusRoute"] - .as_str() - .unwrap_or("missing"), - intake_consensus_readback["publicDiscussionRefCount"] - .as_u64() - .unwrap_or(0), - intake_consensus_readback["candidateActionRefCount"] - .as_u64() - .unwrap_or(0), - intake_consensus_readback["planSafeActionFamily"] - .as_str() - .unwrap_or("missing"), - intake_consensus_readback["planModelAuthored"] - .as_bool() - .unwrap_or(false), - ), - format!("closure {closure_status} soul {soul_verdict}"), - format!("publication {publication_status} sync {sync_status}"), - "private false".to_string(), - ]; - let receipt_refs = repo_work_existing_receipt_refs(&[ - ("accept", &accept_receipt_path), - ("plan", &plan_receipt_path), - ("run", &run_receipt_path), - ("adopt", &adopt_receipt_path), - ("execute", &execute_receipt_path), - ("close-review", &close_review_receipt_path), - ("close", &close_receipt_path), - ]); - let changed_paths_for_entry = changed_paths.clone(); - let commit_sha_for_entry = commit_sha.clone().unwrap_or_default(); - - let receipt_chain = repo_work_receipt_state( - &accept_receipt_path, - &plan_receipt_path, - &run_receipt_path, - &adopt_receipt_path, - &execute_receipt_path, - &close_receipt_path, - ); - let proof_artifacts = repo_work_proof_artifact_rows(&[ - ("accept", &accept_receipt_path), - ("plan", &plan_receipt_path), - ("run", &run_receipt_path), - ("adopt", &adopt_receipt_path), - ("execute", &execute_receipt_path), - ("close-review", &close_review_receipt_path), - ("close", &close_receipt_path), - ])?; - let proof_publication_rows = Vec::::new(); - let proof_bundle_tui_rows = repo_work_proof_bundle_tui_rows( - &item, - &branch, - gate, - blocker, - closure_status, - publication_status, - sync_status, - proof_artifacts - .iter() - .filter(|row| row.get("artifactStatus").and_then(Value::as_str) == Some("present")) - .count(), - ); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let now_for_entry = now.clone(); - let proof_bundle = json!({ - "schemaVersion": "epiphany.repo_work_proof_bundle.v0", - "bundleId": format!("repo-work-proof-bundle-{item_slug}"), - "generatedAt": now, - "workspace": workspace, - "item": item, - "branch": branch, - "currentGate": gate, - "blocker": blocker, - "nextSafeMove": next_safe_move, - "acceptReceiptPath": accept_receipt_path, - "planReceiptPath": existing_path_value(&plan_receipt_path), - "runReceiptPath": existing_path_value(&run_receipt_path), - "adoptReceiptPath": existing_path_value(&adopt_receipt_path), - "executeReceiptPath": existing_path_value(&execute_receipt_path), - "closeReviewReceiptPath": existing_path_value(&close_review_receipt_path), - "closeReceiptPath": existing_path_value(&close_receipt_path), - "changedPaths": changed_paths, - "commitSha": commit_sha, - "intakeConsensus": intake_consensus_readback, - "soulVerdict": soul_verdict, - "mindStateCommitReceiptId": close_receipt.as_ref().and_then(|receipt| string_from_json(receipt, &["mind", "stateCommitReceiptId"])), - "bifrostPublicationReceiptId": null, - "githubPublicationReceiptId": null, - "upstreamMainSynced": false, - "artifactRows": proof_artifacts, - "publicationRows": proof_publication_rows, - "tuiRows": proof_bundle_tui_rows, - "privateStateExposed": false - }); - let rows = json!([ - {"key": "item", "value": item, "status": "current"}, - {"key": "branch", "value": branch, "status": "current"}, - {"key": "gate", "value": gate, "status": if blocker == "none" { "ready" } else { "blocked" }}, - {"key": "blocker", "value": blocker, "status": if blocker == "none" { "clear" } else { "attention" }}, - {"key": "consensus", "value": proof_bundle["intakeConsensus"]["consensusReceiptId"], "status": proof_bundle["intakeConsensus"]["requestedConsensusRoute"]}, - {"key": "closure", "value": closure_status, "status": closure_status}, - {"key": "publication", "value": publication_status, "status": publication_status}, - {"key": "sync", "value": sync_status, "status": sync_status}, - {"key": "private", "value": "false", "status": "sealed"} - ]); - let receipt = json!({ - "schemaVersion": "epiphany.repo_work_overview_receipt.v0", - "createdAt": now, - "workspace": workspace, - "item": item, - "branch": branch, - "currentGate": gate, - "blocker": blocker, - "nextSafeMove": next_safe_move, - "receiptChain": receipt_chain, - "proofBundle": proof_bundle, - "intakeConsensus": proof_bundle["intakeConsensus"], - "rows": rows, - "authority": { - "owner": "Eyes", - "sightOnly": true, - "branchLocalOnly": false, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthorized": false, - "crossRepoMutationAuthorized": false, - "privateStateExposed": false - }, - "privateStateExposed": false - }); - if args.write_receipt { - write_json(&overview_receipt_path, &receipt)?; - } - let mut verse_projection = Value::Null; - if args.write_receipt { - if let Some(store) = local_verse_store.as_ref() { - let entry = EpiphanyCultMeshRepoWorkOverviewEntry { - schema_version: EPIPHANY_CULTMESH_REPO_WORK_OVERVIEW_SCHEMA_VERSION.to_string(), - runtime_id: runtime_id.clone(), - verse_id: EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID.to_string(), - overview_id: format!("repo-work-overview-{item_slug}"), - generated_at: now_for_entry, - workspace: workspace.display().to_string(), - item: item.clone(), - branch: branch.clone(), - current_gate: gate.to_string(), - blocker: blocker.to_string(), - next_safe_move: next_safe_move.to_string(), - changed_paths: changed_paths_for_entry.clone(), - commit_sha: commit_sha_for_entry.clone(), - soul_verdict: soul_verdict.to_string(), - publication_status: publication_status.to_string(), - sync_status: sync_status.to_string(), - receipt_refs: receipt_refs.clone(), - tui_rows: tui_rows.clone(), - proof_bundle_ref: overview_receipt_path.display().to_string(), - private_state_exposed: false, - notes: vec![ - "Repo work overview is compact local Verse sight; raw worker thoughts and receipt payload bodies remain sealed.".to_string(), - "Persona/public feedback and candidate-action refs are shown only as compact Imagination consensus readback; adoption still requires Mind and Bifrost gates.".to_string(), - "downstream Eve lowerers may project these rows, but they do not own scheduling, publication, merge, service lifecycle, or cross-repo mutation.".to_string(), - ], - }; - let written = write_epiphany_cultmesh_repo_work_overview(store, entry)?; - verse_projection = json!({ - "localVerseStore": store, - "documentType": "epiphany.cultmesh.repo_work_overview", - "overviewId": written.overview_id, - "latestKey": "gamecult-local/repo-work-overview/latest", - "tuiRows": written.tui_rows, - "privateStateExposed": written.private_state_exposed - }); - } - } - Ok(json!({ - "schemaVersion": "epiphany.repo_work_overview.v0", - "status": "overview-ready", - "workspace": receipt["workspace"], - "item": receipt["item"], - "branch": receipt["branch"], - "currentGate": receipt["currentGate"], - "blocker": receipt["blocker"], - "nextSafeMove": receipt["nextSafeMove"], - "receiptPath": if args.write_receipt { Value::String(overview_receipt_path.display().to_string()) } else { Value::Null }, - "proofBundle": receipt["proofBundle"], - "intakeConsensus": receipt["intakeConsensus"], - "rows": receipt["rows"], - "verseProjection": verse_projection, - "authority": receipt["authority"], - "privateStateExposed": false - })) -} - -fn run_readiness(args: ReadinessArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let artifact_dir = args - .artifact_dir - .clone() - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - - let overview = run_overview(OverviewArgs { - workspace: workspace.clone(), - item: args.item.clone(), - accept_receipt: args.accept_receipt.clone(), - artifact_dir: Some(artifact_dir.clone()), - write_receipt: args.write_receipt, - })?; - let item = overview - .get("item") - .and_then(Value::as_str) - .unwrap_or("work-item") - .to_string(); - let item_slug = sanitize(&item); - let accept_receipt_path = resolve_accept_receipt(&workspace, Some(&item), args.accept_receipt)?; - let plan_receipt_path = work_receipt_path(&workspace, "plan", &item); - let execute_receipt_path = work_receipt_path(&workspace, "execute", &item); - let close_receipt_path = work_receipt_path(&workspace, "close", &item); - let queue_run_receipt_path = artifact_dir.join("work-queue-run.json"); - let init_receipt_path = workspace - .join(".epiphany") - .join("repo-init") - .join("repo-swarm-init-receipt.json"); - let online_receipt_path = workspace - .join(".epiphany") - .join("swarm-online") - .join("repo-swarm-online-receipt.json"); - let public_proof_path = args.public_proof.unwrap_or_else(|| { - workspace - .join(".epiphany") - .join("public") - .join("proof-bundles") - .join(format!("repo-work-public-proof-{item_slug}.json")) - }); - let readiness_receipt_path = artifact_dir.join(format!("work-readiness-{item_slug}.json")); - let accept_receipt = read_json(&accept_receipt_path)?; - let runtime_id = string_from_json(&accept_receipt, &["runtimeId"]) - .unwrap_or_else(|| "repo-swarm-local".to_string()); - let local_verse_store = path_from_json(&accept_receipt, &["localVerseStore"]) - .or_else(|| path_from_json(&accept_receipt, &["localVerseStorePath"])); - - let close_receipt = read_json_if_exists(&close_receipt_path)?; - let close_status = close_receipt - .as_ref() - .and_then(|receipt| receipt.get("status").and_then(Value::as_str)); - let soul_passed = close_receipt - .as_ref() - .and_then(|receipt| string_from_json(receipt, &["soul", "verdict"])) - .as_deref() - == Some("passed"); - let modeling_map_admitted = close_receipt - .as_ref() - .and_then(|receipt| bool_from_json(receipt, &["authority", "durableStateAdmitted"])) - .unwrap_or(false) - || close_receipt - .as_ref() - .and_then(|receipt| string_from_json(receipt, &["mind", "stateCommitReceiptId"])) - .is_some(); - - let mut rows = vec![ - readiness_path_row( - "repo-init", - "Self", - "epiphany.repo_swarm_init_receipt.v0", - &init_receipt_path, - init_receipt_path.exists(), - "Fresh repo was initialized as an Epiphany Body.", - )?, - readiness_path_row( - "swarm-online", - "Self", - "epiphany.repo_swarm_online_receipt.v0", - &online_receipt_path, - online_receipt_path.exists(), - "Repo-local swarm published compact CultMesh sight.", - )?, - readiness_path_row( - "persona-intake", - "Persona/Imagination", - "epiphany.repo_work_accept_receipt.v0", - &accept_receipt_path, - accept_receipt_path.exists(), - "Persona or Bifrost pressure was accepted without Hands authority.", - )?, - readiness_path_row( - "imagination-plan", - "Imagination", - "epiphany.repo_work_action_plan_receipt.v0", - &plan_receipt_path, - plan_receipt_path.exists(), - "Imagination produced action-item/plan cargo.", - )?, - readiness_path_row( - "self-queue-run", - "Self", - "epiphany.repo_work_queue_run_receipt.v0", - &queue_run_receipt_path, - queue_run_receipt_path.exists(), - "Self queue-run pulse selected or advanced repo work.", - )?, - readiness_path_row( - "hands-branch-work", - "Hands", - "epiphany.repo_work_execute_receipt.v0", - &execute_receipt_path, - execute_receipt_path.exists(), - "Hands executed branch-local work with receipts.", - )?, - readiness_path_row( - "soul-closure", - "Soul", - "epiphany.repo_work_closure_receipt.v0", - &close_receipt_path, - close_status == Some("closed") && soul_passed, - "Soul passed closure for the Hands consequence.", - )?, - readiness_path_row( - "modeling-mind-admission", - "Modeling/Mind", - "epiphany.mind.state_commit_receipt", - &close_receipt_path, - modeling_map_admitted, - "Modeling map update was admitted through Mind.", - )?, - readiness_path_row( - "public-proof", - "Bifrost", - "epiphany.repo_work_public_proof_bundle.v0", - &public_proof_path, - public_proof_path.exists(), - "Redacted public proof bundle exists.", - )?, - readiness_missing_row( - "bifrost-publication", - "Bifrost", - "provider-authored publication receipts", - "Wait for Bifrost and the GitHub publication adapter; legacy local publish aggregates are not authority.", - ), - readiness_missing_row( - "upstream-main-sync", - "Bifrost/GitHub/Maintainer", - "provider-authored merge evidence + Git ancestry", - "Wait for provider-authored merge evidence, then inspect upstream ancestry; legacy local sync aggregates are not authority.", - ), - ]; - let default_idunn_lifecycle_receipt = artifact_dir.join("repo-work-service-audit.json"); - let idunn_lifecycle_path = args.idunn_lifecycle_receipt.as_ref().or_else(|| { - if default_idunn_lifecycle_receipt.exists() { - Some(&default_idunn_lifecycle_receipt) - } else { - None - } - }); - if let Some(path) = idunn_lifecycle_path { - rows.push(idunn_lifecycle_readiness_row(path)?); - } else { - rows.push(readiness_missing_row( - "idunn-lifecycle", - "Idunn", - "epiphany.repo_work_service_audit.v0", - "Supply --idunn-lifecycle-receipt or run repo-work-service-audit into the repo work artifact directory.", - )); - } - if let Some(receipt_ref) = args.deployment_aftercare_audit_receipt_ref.as_ref() { - let readiness_store = local_verse_store - .clone() - .unwrap_or_else(|| workspace.join(".epiphany").join("local-verse.ccmp")); - let receipt = if receipt_ref.trim().is_empty() || receipt_ref.trim() == "latest" { - load_latest_epiphany_cultmesh_idunn_aftercare_audit_receipt( - &readiness_store, - runtime_id.clone(), - )? - } else { - load_epiphany_cultmesh_idunn_aftercare_audit_receipt( - &readiness_store, - runtime_id.clone(), - receipt_ref, - )? - }; - if let Some(receipt) = receipt { - let status_ok = receipt.status == "complete"; - let deployment = load_epiphany_cultmesh_idunn_deployment_receipt( - &readiness_store, - runtime_id.clone(), - &receipt.deployment_receipt_id, - )?; - let current_commit = git_output(&workspace, &["rev-parse", "HEAD"])?; - let runbook = - read_json_if_exists(&artifact_dir.join("deployment-execution-runbook.json"))?; - let runbook_watched_ref = runbook - .as_ref() - .and_then(|value| string_from_json(value, &["watchedRef"])); - let runbook_commit = runbook - .as_ref() - .and_then(|value| string_from_json(value, &["currentCommit"])); - let deployment_chain_ok = deployment.as_ref().is_some_and(|deployment| { - idunn_deployment_aftercare_chain_valid( - deployment, - &receipt, - &runtime_id, - ¤t_commit, - runbook_watched_ref.as_deref(), - runbook_commit.as_deref(), - ) - }); - let satisfied = receipt.schema_version - == "gamecult.idunn.deployment_aftercare_audit.v0" - && status_ok - && receipt.runtime_id == runtime_id - && receipt.verse_id == EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID - && !receipt.private_state_exposed; - let satisfied = satisfied && deployment_chain_ok; - rows.push(json!({ - "kind": "deployment-aftercare", - "owner": "Idunn", - "verifier": "Soul", - "requiredSchema": "gamecult.idunn.deployment_aftercare_audit.v0", - "evidenceRef": receipt_ref, - "artifactStatus": "cultmesh", - "schemaVersion": receipt.schema_version, - "documentStatus": receipt.status, - "source": "cultmesh", - "localVerseStore": readiness_store.display().to_string(), - "runtimeId": runtime_id.clone(), - "receiptId": receipt.receipt_id, - "deploymentReceiptId": receipt.deployment_receipt_id, - "underlyingDeploymentReceiptResolved": deployment.is_some(), - "underlyingDeploymentChainValid": deployment_chain_ok, - "auditRef": receipt.audit_ref, - "satisfied": satisfied, - "status": if satisfied { "satisfied" } else { "missing" }, - "note": "Readiness re-resolved and validated the typed Idunn deployment and aftercare chain from repo-local CultMesh sight.", - "deploymentAuthority": false, - "gitPushAuthority": false, - "serviceLifecycleAuthority": false, - "privateStateExposed": receipt.private_state_exposed - })); - } else { - rows.push(readiness_missing_row( - "deployment-aftercare", - "Idunn", - "gamecult.idunn.deployment_aftercare_audit.v0", - "Supply --deployment-aftercare-audit-receipt-ref after Idunn records deployment aftercare in the repo-local Verse.", - )); - } - } else { - rows.push(readiness_missing_row( - "deployment-aftercare", - "Idunn", - "gamecult.idunn.deployment_aftercare_audit.v0 + gamecult.idunn.deployment_receipt.v0", - "Supply --deployment-aftercare-audit-receipt-ref after Idunn records the bound deployment and aftercare chain in the repo-local Verse.", - )); - } - let default_tool_directory_receipt = artifact_dir.join("tool-directory.json"); - let tool_directory_path = args.tool_directory_receipt.as_ref().or_else(|| { - if default_tool_directory_receipt.exists() { - Some(&default_tool_directory_receipt) - } else { - None - } - }); - if let Some(path) = tool_directory_path { - rows.push(tool_directory_readiness_row(path)?); - } else { - rows.push(readiness_missing_row( - "tool-directory", - "Odin", - "epiphany.cultmesh.daemon_tool_directory.v0", - "Supply --tool-directory-receipt or run tool-directory sight into the repo work artifact directory.", - )); - } - rows.push(json!({ - "kind": "private-state-redaction", - "owner": "Soul", - "publicationReviewOwner": "Bifrost", - "requiredSchema": "epiphany.private_state_redaction_report.v0", - "evidenceRef": overview["proofBundle"].get("bundleId").cloned().unwrap_or(Value::String("missing".to_string())), - "satisfied": overview - .get("privateStateExposed") - .and_then(Value::as_bool) - .map(|exposed| !exposed) - .unwrap_or(false), - "status": if overview.get("privateStateExposed").and_then(Value::as_bool) == Some(false) { "satisfied" } else { "missing" }, - "note": "Readiness sight observed privateStateExposed=false on overview/proof-bundle projection." - })); - - let missing_rows = rows - .iter() - .filter(|row| row.get("satisfied").and_then(Value::as_bool) != Some(true)) - .count(); - let satisfied_rows = rows.len().saturating_sub(missing_rows); - let missing_kinds = rows - .iter() - .filter(|row| row.get("satisfied").and_then(Value::as_bool) != Some(true)) - .filter_map(|row| row.get("kind").and_then(Value::as_str)) - .map(str::to_string) - .collect::>(); - let verdict = if missing_rows == 0 { - "ready" - } else { - "not-ready" - }; - let next_safe_move = if missing_rows == 0 { - "Route this sight receipt to Maintainer/Soul/Mind/Bifrost review; readiness approval is still external to this command." - } else { - "Complete the missing readiness rows, then rerun epiphany-work readiness before asking for review." - }; - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let readiness_tui_rows = vec![ - format!( - "REPO-WORK-READINESS | item={} | status={} | missing={} | satisfied={} | receipt={} | approvalAuth=false | publicationAuth=false | serviceAuth=false | handsAuth=false | private=false", - item, - verdict, - missing_rows, - satisfied_rows, - readiness_receipt_path.display() - ), - format!( - "REPO-WORK-READINESS-GAPS | item={} | missingKinds={} | next={} | private=false", - item, - if missing_kinds.is_empty() { - "none".to_string() - } else { - missing_kinds.join(",") - }, - next_safe_move - ), - ]; - let receipt = json!({ - "schemaVersion": "epiphany.repo_work_readiness_report.v0", - "createdAt": now, - "workspace": workspace, - "item": item, - "status": verdict, - "verdict": verdict, - "missingRequiredCount": missing_rows, - "overviewReceiptPath": overview["receiptPath"], - "proofBundleId": overview["proofBundle"]["bundleId"], - "rows": rows, - "allowedVerdicts": ["ready", "ready-with-caveats", "not-ready", "needs-human-review"], - "authority": { - "owner": "Soul", - "requiredReviewers": ["Maintainer", "Soul", "Mind", "Bifrost"], - "readinessApprovalOwner": "Maintainer", - "publicationReviewOwner": "Bifrost", - "sightOnly": true, - "readinessApprovalAuthorized": false, - "durableStateCommitAuthorized": false, - "publicationAuthorized": false, - "bifrostPublicationAuthorized": false, - "githubPrAuthorized": false, - "mergeAuthorized": false, - "upstreamSyncAuthorized": false, - "deploymentAuthority": false, - "serviceLifecycleAuthority": false, - "handsActionAuthorized": false, - "crossBodyMutationAuthorized": false, - "privateVerseRummaging": false, - "privateStateExposed": false - }, - "privateStateExposed": false, - "nextSafeMove": next_safe_move - }); - if args.write_receipt { - write_json(&readiness_receipt_path, &receipt)?; - } - let mut verse_projection = Value::Null; - if args.write_receipt { - if let Some(store) = local_verse_store.as_ref() { - let entry = EpiphanyCultMeshRepoWorkReadinessEntry { - schema_version: EPIPHANY_CULTMESH_REPO_WORK_READINESS_SCHEMA_VERSION.to_string(), - runtime_id: runtime_id.clone(), - verse_id: EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID.to_string(), - readiness_id: format!("repo-work-readiness-{item_slug}"), - generated_at: now.clone(), - workspace: workspace.display().to_string(), - item: item.clone(), - status: verdict.to_string(), - missing_required_count: missing_rows as u32, - satisfied_required_count: satisfied_rows as u32, - readiness_receipt_ref: readiness_receipt_path.display().to_string(), - overview_receipt_ref: overview["receiptPath"] - .as_str() - .unwrap_or("missing") - .to_string(), - proof_bundle_id: overview["proofBundle"]["bundleId"] - .as_str() - .unwrap_or("missing") - .to_string(), - missing_kinds: missing_kinds.clone(), - tui_rows: readiness_tui_rows.clone(), - sight_only: true, - readiness_approval_authorized: false, - publication_authorized: false, - service_lifecycle_authority: false, - hands_action_authorized: false, - private_state_exposed: false, - notes: vec![ - "Repo work readiness is reviewable sight only; Maintainer/Soul/Mind/Bifrost own any readiness approval.".to_string(), - "Bifrost owns publication gates; Hands performs bounded PR actions; GitHub supplies provider receipts; Idunn owns service lifecycle.".to_string(), - "Downstream consumers may project these rows without scheduling, publication, merge, deployment, service lifecycle, cross-body mutation, or private Verse authority.".to_string(), - ], - }; - let written = write_epiphany_cultmesh_repo_work_readiness(store, entry)?; - verse_projection = json!({ - "localVerseStore": store, - "documentType": "epiphany.cultmesh.repo_work_readiness", - "readinessId": written.readiness_id, - "latestKey": "gamecult-local/repo-work-readiness/latest", - "tuiRows": written.tui_rows, - "privateStateExposed": written.private_state_exposed - }); - } - } - Ok(json!({ - "schemaVersion": "epiphany.repo_work_readiness.v0", - "status": verdict, - "workspace": receipt["workspace"], - "item": receipt["item"], - "receiptPath": if args.write_receipt { Value::String(readiness_receipt_path.display().to_string()) } else { Value::Null }, - "missingRequiredCount": missing_rows, - "rows": receipt["rows"], - "verseProjection": verse_projection, - "authority": receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": receipt["nextSafeMove"] - })) -} - -fn run_deployment_config_audit(args: DeploymentConfigAuditArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let artifact_dir = args - .artifact_dir - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - - let config_path = workspace.join(".epiphany").join("deployment.toml"); - let receipt_path = artifact_dir.join("deployment-config-audit.json"); - let generated_at = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let mut assertions = Vec::new(); - let mut parsed_config = None; - - if config_path.exists() { - let config_text = fs::read_to_string(&config_path) - .with_context(|| format!("failed to read {}", config_path.display()))?; - match parse_repo_deployment_config(&config_text) { - Ok(config) => { - push_assertion( - &mut assertions, - "deployment-config-typed-toml", - true, - "Deployment config parses as the typed TOML contract.".to_string(), - ); - parsed_config = Some(config); - } - Err(error) => push_assertion( - &mut assertions, - "deployment-config-typed-toml", - false, - format!("Deployment config parse failed: {error:#}"), - ), - } - push_assertion( - &mut assertions, - "deployment-config-schema-present", - parsed_config.as_ref().is_some_and(|config| { - config.schema_version == "epiphany.repo_deployment_config.v0" - }), - "Deployment config carries the schema version.".to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-family-present", - parsed_config - .as_ref() - .is_some_and(|config| config.safe_action_family == "repo.deployment_config"), - "Deployment config carries the safe action family.".to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-idunn-trigger", - parsed_config.as_ref().is_some_and(|config| { - let deployment = &config.deployment; - !deployment.enabled - && deployment.owner == "Idunn" - && deployment.trigger == "git-push-observed-by-idunn" - && deployment.watched_ref == "refs/heads/main" - && deployment.deployment_script_ref == "deploy/idunn-deploy.ps1" - && deployment.deployment_script_hash_required - && deployment.deployment_script_review_required - && deployment.host_access_policy_ref_required - && !deployment.secret_values_embedded - && deployment.rollback_plan_ref_required - && deployment.aftercare_checks_required - && deployment.idunn_receipt_required - && deployment.aftercare_audit_required - }), - "Deployment config names disabled Idunn git-push trigger, reviewed script/hash, policy, rollback, and aftercare requirements." - .to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-cultmesh-contract", - parsed_config.as_ref().is_some_and(|config| { - let cultmesh = &config.cultmesh; - cultmesh.local_verse == "gamecult-local" - && cultmesh.capability_family == "gamecult.idunn.deployment" - && cultmesh.intent_contract == "gamecult.idunn.deployment_intent.v0" - && cultmesh.receipt_contract == "gamecult.idunn.deployment_receipt.v0" - && cultmesh.aftercare_contract == "gamecult.idunn.deployment_aftercare_audit.v0" - && cultmesh.daemon_owns_execution - }), - "Deployment config routes execution through Idunn CultMesh contracts.".to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-receipt-contract", - parsed_config.as_ref().is_some_and(|config| { - let receipts = &config.required_receipts; - receipts.mind_adoption == "epiphany.repo_work_plan_adoption_review.v0" - && receipts.soul_review == "epiphany.repo_work_closure_review.v0" - && receipts.maintainer_review == "gamecult.maintainer.review_receipt.v0" - && receipts.secret_policy == "epiphany.repo_secret_policy_request.v0" - && receipts.idunn_deployment == "gamecult.idunn.deployment_receipt.v0" - && receipts.aftercare_audit - == "gamecult.idunn.deployment_aftercare_audit.v0" - }), - "Deployment config names Mind, Soul, maintainer, secret-policy, Idunn deployment, and aftercare receipts." - .to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-authority-seals", - parsed_config.as_ref().is_some_and(|config| { - let authority = &config.authority; - authority.configuration_only - && !authority.direct_deployment_authority - && !authority.direct_ssh_authority - && !authority.direct_git_push_authority - && !authority.direct_service_lifecycle_authority - && !authority.direct_hands_authority - && !authority.publication_authorized - && !authority.merge_authorized - && !authority.cross_body_mutation_authorized - && !authority.private_verse_rummaging - && authority.idunn_deployment_authority_required - }), - "Deployment config denies deployment, SSH, git-push, service lifecycle, Hands, publication, merge, and cross-body authority." - .to_string(), - ); - push_assertion( - &mut assertions, - "deployment-config-private-seal", - parsed_config - .as_ref() - .is_some_and(|config| !config.private_state_exposed), - "Deployment config preserves the private-state seal.".to_string(), - ); - } else { - push_assertion( - &mut assertions, - "deployment-config-present", - false, - format!("Deployment config missing at {}", config_path.display()), - ); - } - - let all_passed = assertions - .iter() - .all(|assertion| assertion.get("passed").and_then(Value::as_bool) == Some(true)); - let status = if all_passed { - "ready-for-idunn-review" - } else if config_path.exists() { - "invalid" - } else { - "missing" - }; - let daemon_owns_execution = all_passed - && parsed_config - .as_ref() - .is_some_and(|config| config.cultmesh.daemon_owns_execution); - let receipt = json!({ - "schemaVersion": "epiphany.repo_deployment_config_audit.v0", - "auditId": "repo-deployment-config-audit", - "generatedAt": generated_at, - "status": status, - "workspace": workspace, - "configPath": config_path, - "receiptPath": receipt_path, - "readyForIdunnReview": status == "ready-for-idunn-review", - "executionAuthorized": false, - "deploymentAuthority": false, - "sshAuthority": false, - "gitPushAuthority": false, - "serviceLifecycleAuthority": false, - "handsAuthority": false, - "publicationAuthorized": false, - "mergeAuthorized": false, - "crossBodyMutationAuthorized": false, - "daemonOwnsExecution": daemon_owns_execution, - "nextGate": if status == "ready-for-idunn-review" { - "idunn.review_deployment_config" - } else { - "repo.fix_deployment_config" - }, - "assertions": assertions, - "privateStateExposed": false - }); - if args.write_receipt { - write_json(&receipt_path, &receipt)?; - } - Ok(receipt) -} - -fn run_deployment_execution_runbook(args: DeploymentExecutionRunbookArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let artifact_dir = args - .artifact_dir - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - - let config_path = workspace.join(".epiphany").join("deployment.toml"); - let config_text = if config_path.exists() { - fs::read_to_string(&config_path) - .with_context(|| format!("failed to read {}", config_path.display()))? - } else { - String::new() - }; - let parsed_config = parse_repo_deployment_config(&config_text).ok(); - let watched_ref = parsed_config - .as_ref() - .map(|config| config.deployment.watched_ref.clone()) - .unwrap_or_else(|| "missing".to_string()); - let deployment_script_ref = parsed_config - .as_ref() - .map(|config| config.deployment.deployment_script_ref.clone()) - .unwrap_or_else(|| "missing".to_string()); - let current_branch = git_output(&workspace, &["rev-parse", "--abbrev-ref", "HEAD"])?; - let current_commit = git_output(&workspace, &["rev-parse", "HEAD"])?; - let generated_at = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let receipt_path = artifact_dir.join("deployment-execution-runbook.json"); - let runbook_dir = artifact_dir.join("idunn-deployment"); - let runbook_path = runbook_dir.join("idunn-git-push-runbook.ps1"); - let audit = run_deployment_config_audit(DeploymentConfigAuditArgs { - workspace: workspace.clone(), - artifact_dir: Some(artifact_dir.clone()), - write_receipt: args.write_receipt, - })?; - let ready_for_idunn = audit.get("readyForIdunnReview").and_then(Value::as_bool) == Some(true); - let push_command = format!("git push {} HEAD:{watched_ref}", args.remote); - let operator_execution_command = format!( - "powershell -ExecutionPolicy Bypass -File {} -Remote {}", - powershell_single_quoted(&runbook_path.display().to_string()), - powershell_single_quoted(&args.remote) - ); - let mut runbook_written = false; - let mut runbook_sha256 = Value::Null; - - if ready_for_idunn && args.write_receipt { - fs::create_dir_all(&runbook_dir) - .with_context(|| format!("failed to create {}", runbook_dir.display()))?; - let runbook = [ - "# schema_version = \"epiphany.repo_deployment_execution_runbook.v0\"".to_string(), - "# owner = \"Idunn\"".to_string(), - "# authority = \"explicit-operator-git-push\"".to_string(), - "# generated_by = \"epiphany-work deployment-execution-runbook\"".to_string(), - "param([string]$Remote = 'origin')".to_string(), - "$ErrorActionPreference = 'Stop'".to_string(), - format!("Set-Location -LiteralPath {}", powershell_single_quoted(&workspace.display().to_string())), - "Write-Host 'Epiphany Idunn deployment handoff: operator-owned git push.'".to_string(), - "Write-Host 'This runbook mutates the remote ref; run only with explicit operator authority.'".to_string(), - "git status --short".to_string(), - format!("git push $Remote HEAD:{watched_ref}"), - "Write-Host 'Aftercare: wait for Idunn deployment receipt and aftercare audit on CultMesh.'".to_string(), - "Write-Host 'Required receipts: gamecult.idunn.deployment_receipt.v0 and gamecult.idunn.deployment_aftercare_audit.v0.'".to_string(), - ] - .join("\n"); - fs::write(&runbook_path, runbook) - .with_context(|| format!("failed to write {}", runbook_path.display()))?; - runbook_written = true; - runbook_sha256 = json!(file_sha256(&runbook_path)?); - } - - let status = if ready_for_idunn { - "ready-for-operator-git-push" - } else { - "blocked-config-not-ready" - }; - let receipt = json!({ - "schemaVersion": "epiphany.repo_deployment_execution_runbook.v0", - "runbookId": "repo-idunn-git-push-runbook", - "generatedAt": generated_at, - "status": status, - "workspace": workspace, - "configPath": config_path, - "configAudit": audit, - "receiptPath": receipt_path, - "runbookPath": if runbook_written { json!(runbook_path) } else { Value::Null }, - "runbookSha256": runbook_sha256, - "runbookWritten": runbook_written, - "operatorExecutionCommand": if runbook_written { - json!(operator_execution_command) - } else { - Value::Null - }, - "gitPushCommand": push_command, - "remote": args.remote, - "watchedRef": watched_ref, - "currentBranch": current_branch, - "currentCommit": current_commit, - "deploymentScriptRef": deployment_script_ref, - "requiredIdunnReceipts": [ - "gamecult.idunn.deployment_receipt.v0", - "gamecult.idunn.deployment_aftercare_audit.v0" - ], - "requiresExplicitOperatorAuthority": true, - "mutatesRemoteWhenRun": true, - "executionAuthorized": false, - "deploymentAuthority": false, - "sshAuthority": false, - "gitPushAuthority": false, - "serviceLifecycleAuthority": false, - "handsAuthority": false, - "publicationAuthorized": false, - "mergeAuthorized": false, - "crossBodyMutationAuthorized": false, - "daemonOwnsExecution": true, - "privateStateExposed": false - }); - if args.write_receipt { - write_json(&receipt_path, &receipt)?; - } - Ok(receipt) -} - -fn run_deployment_aftercare_audit(args: DeploymentAftercareAuditArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let artifact_dir = args - .artifact_dir - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - - let receipt_path = artifact_dir.join("deployment-aftercare-audit.json"); - let runbook_receipt_path = args - .runbook_receipt - .unwrap_or_else(|| artifact_dir.join("deployment-execution-runbook.json")); - let local_verse_store = args - .local_verse_store - .unwrap_or_else(|| workspace.join(".epiphany").join("local-verse.ccmp")); - let idunn_deployment_receipt_ref = args.idunn_deployment_receipt_ref; - let aftercare_audit_receipt_ref = args.aftercare_audit_receipt_ref; - let runtime_id = args.runtime_id; - let local_verse_store_display = local_verse_store.display().to_string(); - let generated_at = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let mut assertions = Vec::new(); - - let runbook_receipt = read_json_if_exists(&runbook_receipt_path)?; - let runbook_ready = runbook_receipt.as_ref().is_some_and(|receipt| { - string_from_json(receipt, &["schemaVersion"]).as_deref() - == Some("epiphany.repo_deployment_execution_runbook.v0") - && string_from_json(receipt, &["status"]).as_deref() - == Some("ready-for-operator-git-push") - && bool_from_json(receipt, &["requiresExplicitOperatorAuthority"]) == Some(true) - && bool_from_json(receipt, &["mutatesRemoteWhenRun"]) == Some(true) - && bool_from_json(receipt, &["privateStateExposed"]) == Some(false) - }); - push_assertion( - &mut assertions, - "deployment-runbook-receipt-ready", - runbook_ready, - "Deployment execution runbook receipt is present, operator-owned, and ready for explicit git-push handoff." - .to_string(), - ); - - let idunn_deployment_receipt = if let Some(receipt_ref) = idunn_deployment_receipt_ref.as_ref() - { - if receipt_ref.trim().is_empty() || receipt_ref.trim() == "latest" { - load_latest_epiphany_cultmesh_idunn_deployment_receipt( - &local_verse_store, - runtime_id.clone(), - )? - } else { - load_epiphany_cultmesh_idunn_deployment_receipt( - &local_verse_store, - runtime_id.clone(), - receipt_ref, - )? - } - } else { - None - }; - - let aftercare_audit_receipt = if let Some(receipt_ref) = aftercare_audit_receipt_ref.as_ref() { - if receipt_ref.trim().is_empty() || receipt_ref.trim() == "latest" { - load_latest_epiphany_cultmesh_idunn_aftercare_audit_receipt( - &local_verse_store, - runtime_id.clone(), - )? - } else { - load_epiphany_cultmesh_idunn_aftercare_audit_receipt( - &local_verse_store, - runtime_id.clone(), - receipt_ref, - )? - } - } else { - None - }; - - let current_commit = git_output(&workspace, &["rev-parse", "HEAD"])?; - let runbook_watched_ref = runbook_receipt - .as_ref() - .and_then(|receipt| string_from_json(receipt, &["watchedRef"])); - let runbook_commit = runbook_receipt - .as_ref() - .and_then(|receipt| string_from_json(receipt, &["currentCommit"])); - let deployment_valid = idunn_deployment_receipt.as_ref().is_some_and(|receipt| { - receipt.schema_version == "gamecult.idunn.deployment_receipt.v0" - && receipt.status == "deployed" - && !receipt.receipt_id.trim().is_empty() - && !receipt.result_ref.trim().is_empty() - && receipt.runtime_id == runtime_id - && receipt.verse_id == EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID - && !receipt.private_state_exposed - && runbook_watched_ref.as_deref() == Some(receipt.watched_ref.as_str()) - && runbook_commit.as_deref() == Some(receipt.source_commit.as_str()) - && receipt.source_commit == current_commit - }); - push_assertion( - &mut assertions, - "idunn-deployment-receipt-chain-valid", - deployment_valid, - "CultMesh Idunn deployment receipt is bound to this runtime, local Verse, runbook watched ref, immutable source commit, and current HEAD." - .to_string(), - ); - let aftercare_valid = aftercare_audit_receipt.as_ref().is_some_and(|aftercare| { - idunn_deployment_receipt.as_ref().is_some_and(|deployment| { - idunn_deployment_aftercare_chain_valid( - deployment, - aftercare, - &runtime_id, - ¤t_commit, - runbook_watched_ref.as_deref(), - runbook_commit.as_deref(), - ) - }) - }); - push_assertion( - &mut assertions, - "idunn-aftercare-receipt-chain-valid", - aftercare_valid, - "CultMesh Idunn aftercare receipt is bound to the exact deployment receipt, runtime, local Verse, and deployed result ref." - .to_string(), - ); - - if idunn_deployment_receipt.is_none() { - push_assertion( - &mut assertions, - "idunn-deployment-receipt-present", - false, - "Typed Idunn deployment receipt was not resolved from the local Verse store." - .to_string(), - ); - } - if aftercare_audit_receipt.is_none() { - push_assertion( - &mut assertions, - "idunn-aftercare-audit-receipt-present", - false, - "Typed Idunn aftercare receipt was not resolved from the local Verse store." - .to_string(), - ); - } - - let idunn_deployment_summary = idunn_deployment_receipt.as_ref().map_or(Value::Null, |receipt| json!({ - "source": "cultmesh", "store": local_verse_store_display.clone(), "runtimeId": receipt.runtime_id, - "verseId": receipt.verse_id, "receiptRef": idunn_deployment_receipt_ref, "receiptId": receipt.receipt_id, - "schemaVersion": receipt.schema_version, "status": receipt.status, "trigger": receipt.trigger, - "watchedRef": receipt.watched_ref, "sourceCommit": receipt.source_commit, "resultRef": receipt.result_ref, - "privateStateExposed": receipt.private_state_exposed - })); - let aftercare_summary = aftercare_audit_receipt.as_ref().map_or(Value::Null, |receipt| json!({ - "source": "cultmesh", "store": local_verse_store_display.clone(), "runtimeId": receipt.runtime_id, - "verseId": receipt.verse_id, "receiptRef": aftercare_audit_receipt_ref, "receiptId": receipt.receipt_id, - "schemaVersion": receipt.schema_version, "status": receipt.status, "checkedRef": receipt.checked_ref, - "deploymentReceiptId": receipt.deployment_receipt_id, "auditRef": receipt.audit_ref, - "privateStateExposed": receipt.private_state_exposed - })); - - let all_passed = assertions - .iter() - .all(|assertion| assertion.get("passed").and_then(Value::as_bool) == Some(true)); - let status = if all_passed { - "complete" - } else if runbook_ready { - "awaiting-idunn-receipts" - } else { - "runbook-not-ready" - }; - let receipt = json!({ - "schemaVersion": "epiphany.repo_deployment_aftercare_audit.v0", - "auditId": "repo-deployment-aftercare-audit", - "generatedAt": generated_at, - "status": status, - "workspace": workspace, - "receiptPath": receipt_path, - "runbookReceiptPath": runbook_receipt_path, - "localVerseStore": local_verse_store_display, - "runtimeId": runtime_id, - "idunnDeploymentReceipt": idunn_deployment_summary, - "idunnAftercareAuditReceipt": aftercare_summary, - "deploymentComplete": status == "complete", - "requiresExplicitOperatorAuthority": false, - "mutatesRemoteWhenRun": false, - "executionAuthorized": false, - "deploymentAuthority": false, - "sshAuthority": false, - "gitPushAuthority": false, - "serviceLifecycleAuthority": false, - "handsAuthority": false, - "publicationAuthorized": false, - "mergeAuthorized": false, - "crossBodyMutationAuthorized": false, - "daemonOwnsExecution": true, - "assertions": assertions, - "privateStateExposed": false - }); - if args.write_receipt { - write_json(&receipt_path, &receipt)?; - } - Ok(receipt) -} - -fn idunn_deployment_aftercare_chain_valid( - deployment: &EpiphanyCultMeshIdunnDeploymentReceiptEntry, - aftercare: &EpiphanyCultMeshIdunnAftercareAuditReceiptEntry, - runtime_id: &str, - current_commit: &str, - runbook_watched_ref: Option<&str>, - runbook_commit: Option<&str>, -) -> bool { - deployment.schema_version == "gamecult.idunn.deployment_receipt.v0" - && deployment.status == "deployed" - && aftercare.schema_version == "gamecult.idunn.deployment_aftercare_audit.v0" - && aftercare.status == "complete" - && !deployment.receipt_id.trim().is_empty() - && !deployment.result_ref.trim().is_empty() - && !aftercare.receipt_id.trim().is_empty() - && !aftercare.audit_ref.trim().is_empty() - && deployment.runtime_id == runtime_id - && aftercare.runtime_id == runtime_id - && deployment.runtime_id == aftercare.runtime_id - && deployment.verse_id == EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID - && aftercare.verse_id == EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID - && deployment.verse_id == aftercare.verse_id - && aftercare.deployment_receipt_id == deployment.receipt_id - && aftercare.checked_ref == deployment.result_ref - && deployment.source_commit == current_commit - && runbook_commit == Some(deployment.source_commit.as_str()) - && runbook_watched_ref == Some(deployment.watched_ref.as_str()) - && !deployment.private_state_exposed - && !aftercare.private_state_exposed -} - -fn run_export_proof(args: ExportProofArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - let overview = run_overview(OverviewArgs { - workspace: workspace.clone(), - item: args.item, - accept_receipt: args.accept_receipt, - artifact_dir: args.artifact_dir.clone(), - write_receipt: true, - })?; - let proof_bundle = overview - .get("proofBundle") - .ok_or_else(|| anyhow!("overview did not return a proofBundle"))?; - let item = proof_bundle - .get("item") - .and_then(Value::as_str) - .unwrap_or("work-item") - .to_string(); - let item_slug = sanitize(&item); - let output = args.output.unwrap_or_else(|| { - workspace - .join(".epiphany") - .join("public") - .join("proof-bundles") - .join(format!("repo-work-public-proof-{item_slug}.json")) - }); - let public_bundle = repo_work_public_proof_bundle(&overview)?; - write_json(&output, &public_bundle)?; - let public_proof_sha256 = file_sha256(&output)?; - let local_verse_store = args - .local_verse_store - .unwrap_or_else(|| workspace.join(".epiphany").join("local-verse.ccmp")); - let artifact_row_count = public_bundle - .get("artifactRows") - .and_then(Value::as_array) - .map(|rows| rows.len()) - .unwrap_or(0); - let publication_row_count = public_bundle - .get("publicationRows") - .and_then(Value::as_array) - .map(|rows| rows.len()) - .unwrap_or(0); - let public_proof_tui_rows = repo_work_public_proof_tui_rows( - &public_bundle, - &output, - &public_proof_sha256, - artifact_row_count, - publication_row_count, - ); - let entry = EpiphanyCultMeshRepoWorkPublicProofEntry { - schema_version: EPIPHANY_CULTMESH_REPO_WORK_PUBLIC_PROOF_SCHEMA_VERSION.to_string(), - runtime_id: args.runtime_id.clone(), - verse_id: EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID.to_string(), - public_proof_id: format!("repo-work-public-proof-{item_slug}"), - generated_at: string_from_json(&public_bundle, &["generatedAt"]) - .unwrap_or_else(|| Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)), - workspace: workspace.display().to_string(), - item: item.clone(), - branch: string_from_json(&public_bundle, &["branch"]).unwrap_or_else(|| "unknown".to_string()), - current_gate: string_from_json(&public_bundle, &["currentGate"]) - .unwrap_or_else(|| "unknown".to_string()), - blocker: string_from_json(&public_bundle, &["blocker"]).unwrap_or_else(|| "none".to_string()), - next_safe_move: string_from_json(&public_bundle, &["nextSafeMove"]) - .unwrap_or_else(|| "none".to_string()), - changed_paths: public_bundle - .get("changedPaths") - .and_then(Value::as_array) - .map(|paths| { - paths - .iter() - .filter_map(Value::as_str) - .map(ToString::to_string) - .collect::>() - }) - .unwrap_or_default(), - commit_sha: string_from_json(&public_bundle, &["commitSha"]).unwrap_or_else(|| "none".to_string()), - soul_verdict: string_from_json(&public_bundle, &["soulVerdict"]).unwrap_or_else(|| "none".to_string()), - upstream_main_synced: public_bundle - .get("upstreamMainSynced") - .and_then(Value::as_bool) - .unwrap_or(false), - artifact_row_count: artifact_row_count as u32, - publication_row_count: publication_row_count as u32, - public_proof_ref: output.display().to_string(), - public_proof_sha256: public_proof_sha256.clone(), - tui_rows: public_proof_tui_rows, - private_state_exposed: false, - notes: vec![ - "Repo work public proof is a redacted local Verse index for public/Bifrost transport; raw receipt bodies, local receipt paths, worker thought, and private Verse contents remain sealed.".to_string(), - "Odin may discover this proof, but Bifrost still owns publication, labor ledger, credit, and public consequence.".to_string(), - ], - }; - let written_public_proof = - write_epiphany_cultmesh_repo_work_public_proof(&local_verse_store, entry)?; - let verse_projection = json!({ - "localVerseStore": local_verse_store, - "documentType": "epiphany.cultmesh.repo_work_public_proof", - "publicProofId": written_public_proof.public_proof_id, - "latestKey": "gamecult-local/repo-work-public-proof/latest", - "publicProofRef": written_public_proof.public_proof_ref, - "publicProofSha256": written_public_proof.public_proof_sha256, - "tuiRows": written_public_proof.tui_rows, - "privateStateExposed": written_public_proof.private_state_exposed - }); - Ok(json!({ - "schemaVersion": "epiphany.repo_work_public_proof_export.v0", - "status": "public-proof-exported", - "workspace": workspace, - "item": item, - "outputPath": output, - "outputSha256": public_proof_sha256, - "sourceOverviewReceiptPath": overview["receiptPath"], - "publicProofBundle": public_bundle, - "verseProjection": verse_projection, - "privateStateExposed": false, - "nextSafeMove": "Share the public proof bundle with maintainers or Bifrost; keep raw worker thoughts and local receipt bodies sealed." - })) -} - -fn run_serve(args: ServeArgs) -> Result { - if args.max_iterations == 0 && args.loop_interval_seconds == 0 { - return Err(anyhow!( - "unbounded repo-work serve mode requires --loop-interval-seconds greater than 0" - )); - } - - let workspace = args - .tick - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.tick.workspace.display()))?; - ensure_git_repo(&workspace)?; - let artifact_dir = args - .tick - .artifact_dir - .clone() - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - let accept_receipt_path = resolve_accept_receipt(&workspace, args.tick.item.as_deref(), None)?; - let accept_receipt = read_json(&accept_receipt_path)?; - let item = accept_receipt - .get("item") - .and_then(Value::as_str) - .unwrap_or("work-item") - .to_string(); - let item_slug = sanitize(&item); - let started_at = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let serve_mode = if args.max_iterations == 0 { - "unbounded-service" - } else { - "bounded-proof" - }; - let receipt_path = scheduler_serve_receipt_path(&artifact_dir, &item_slug); - let start_receipt = json!({ - "schemaVersion": "epiphany.repo_work_scheduler_serve_receipt.v0", - "createdAt": started_at, - "startedAt": started_at, - "completedAt": Value::Null, - "status": "serve-running", - "workspace": workspace, - "item": item, - "scheduler": { - "owner": "Self", - "schedulerId": args.scheduler_id, - "serveMode": serve_mode, - "pulseKind": "repo-work-local", - "oneStepPerPulse": true, - "loopIntervalSeconds": args.loop_interval_seconds, - "maxIterations": args.max_iterations, - "cooldownSeconds": args.tick.cooldown_seconds, - "activeTimeoutSeconds": args.tick.active_timeout_seconds, - "dryRun": args.tick.dry_run - }, - "iterations": 0, - "outputs": [], - "lastOutput": Value::Null, - "authority": { - "branchLocalOnly": true, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthorized": false, - "crossRepoMutationAuthorized": false, - "privateStateExposed": false - }, - "nextSafeMove": "Repo-work scheduler cadence is running; inspect per-pulse tick receipts for the durable trail." - }); - write_json(&receipt_path, &start_receipt)?; - - let mut outputs = Vec::new(); - let mut iteration = 0_u64; - let last_output = loop { - iteration = iteration.saturating_add(1); - let next_wake_utc = if args.max_iterations == 0 || iteration < args.max_iterations { - Some( - (Utc::now() + chrono::Duration::seconds(args.loop_interval_seconds as i64)) - .to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - ) - } else { - None - }; - let tick_output = run_tick(args.tick.clone())?; - let iteration_output = json!({ - "iteration": iteration, - "nextWakeUtc": next_wake_utc, - "tick": tick_output - }); - if args.max_iterations != 0 { - outputs.push(iteration_output.clone()); - } - if args.max_iterations != 0 && iteration >= args.max_iterations { - break iteration_output; - } - std::thread::sleep(std::time::Duration::from_secs(args.loop_interval_seconds)); - }; - - let completed_at = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let receipt = json!({ - "schemaVersion": "epiphany.repo_work_scheduler_serve_receipt.v0", - "createdAt": completed_at, - "startedAt": started_at, - "completedAt": completed_at, - "status": "serve-complete", - "workspace": workspace, - "item": item, - "scheduler": { - "owner": "Self", - "schedulerId": args.scheduler_id, - "serveMode": serve_mode, - "pulseKind": "repo-work-local", - "oneStepPerPulse": true, - "loopIntervalSeconds": args.loop_interval_seconds, - "maxIterations": args.max_iterations, - "cooldownSeconds": args.tick.cooldown_seconds, - "activeTimeoutSeconds": args.tick.active_timeout_seconds, - "dryRun": args.tick.dry_run - }, - "iterations": iteration, - "outputs": outputs, - "lastOutput": last_output, - "authority": { - "branchLocalOnly": true, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthorized": false, - "crossRepoMutationAuthorized": false, - "privateStateExposed": false - }, - "nextSafeMove": "Continue cadence only while repo-work receipts still identify a safe branch-local step; route Soul/Modeling/Mind closure after execution." - }); - write_json(&receipt_path, &receipt)?; - Ok(json!({ - "schemaVersion": "epiphany.repo_work_scheduler_serve.v0", - "status": "serve-complete", - "workspace": receipt["workspace"], - "item": receipt["item"], - "scheduler": receipt["scheduler"], - "iterations": receipt["iterations"], - "receiptPath": receipt_path, - "lastOutput": receipt["lastOutput"], - "authority": receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": receipt["nextSafeMove"], - })) -} - -fn run_queue(args: QueueArgs) -> Result { - if args.max_items == 0 { - return Err(anyhow!("queue-run requires --max-items greater than 0")); - } - - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let local_verse_store = args - .local_verse_store - .clone() - .unwrap_or_else(|| workspace.join(".epiphany").join("local-verse.ccmp")); - if !local_verse_store.exists() { - return Err(anyhow!( - "repo-work queue-run requires a local Verse store at {}; run epiphany-swarm online and epiphany-work overview first, or pass --local-verse-store", - local_verse_store.display() - )); - } - let artifact_dir = args - .artifact_dir - .clone() - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - - let (latest_repo_work_overview, repo_work_overviews) = - load_repo_work_overview_queue_from_store(&local_verse_store, &args.runtime_id)?; - let selected = repo_work_overviews - .iter() - .filter(|overview| overview_workspace_matches(overview, &workspace)) - .filter(|overview| repo_work_gate_is_tick_actionable(&overview.current_gate)) - .take(args.max_items as usize) - .cloned() - .collect::>(); - let queue_rows = repo_work_queue_selection_rows(&repo_work_overviews, &workspace); - let selected_rows = repo_work_queue_selection_rows(&selected, &workspace); - - let started_at = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let mut outputs = Vec::new(); - for overview in &selected { - let tick_output = run_tick(TickArgs { - workspace: workspace.clone(), - epiphany_root: args.epiphany_root.clone(), - item: Some(overview.item.clone()), - local_verse_store: Some(local_verse_store.clone()), - artifact_dir: Some(artifact_dir.clone()), - runtime_store: args.runtime_store.clone(), - cooldown_seconds: args.cooldown_seconds, - active_timeout_seconds: args.active_timeout_seconds, - dry_run: args.dry_run, - })?; - let refreshed_overview = if args.dry_run { - Value::Null - } else { - run_overview(OverviewArgs { - workspace: workspace.clone(), - item: Some(overview.item.clone()), - accept_receipt: None, - artifact_dir: Some(artifact_dir.clone()), - write_receipt: true, - })? - }; - outputs.push(json!({ - "item": overview.item, - "overviewId": overview.overview_id, - "gateBefore": overview.current_gate, - "blockerBefore": overview.blocker, - "tick": tick_output, - "refreshedOverview": refreshed_overview - })); - } - - let status = if selected.is_empty() { - "blocked-or-noop" - } else if args.dry_run { - "would-advance" - } else { - "advanced" - }; - let next_safe_move = if selected.is_empty() { - "No tick-actionable repo-work queue rows were found; inspect queue rows for plan, closure, publication, or sync gates." - } else if args.dry_run { - "Rerun queue-run without --dry-run to pulse the selected repo-work items." - } else { - "Inspect refreshed repo-work overview rows, then continue queue-run only while branch-local gates remain tick-actionable." - }; - let completed_at = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let receipt_path = artifact_dir.join("work-queue-run.json"); - let receipt = json!({ - "schemaVersion": "epiphany.repo_work_queue_run_receipt.v0", - "createdAt": completed_at, - "startedAt": started_at, - "completedAt": completed_at, - "status": status, - "workspace": workspace, - "localVerseStore": local_verse_store, - "runtimeId": args.runtime_id, - "latestRepoWorkOverview": latest_repo_work_overview.as_ref().map(|overview| overview.overview_id.clone()), - "queueCount": repo_work_overviews.len(), - "actionableCount": selected.len(), - "maxItems": args.max_items, - "dryRun": args.dry_run, - "queueRows": queue_rows, - "selectedRows": selected_rows, - "outputs": outputs, - "authority": { - "owner": "Self", - "selectionOnly": false, - "delegatesActuationTo": "epiphany.repo_work_scheduler_tick", - "branchLocalOnly": true, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthorized": false, - "crossRepoMutationAuthorized": false, - "privateStateExposed": false - }, - "nextSafeMove": next_safe_move, - "privateStateExposed": false - }); - write_json(&receipt_path, &receipt)?; - Ok(json!({ - "schemaVersion": "epiphany.repo_work_queue_run.v0", - "status": receipt["status"], - "workspace": receipt["workspace"], - "localVerseStore": receipt["localVerseStore"], - "runtimeId": receipt["runtimeId"], - "queueCount": receipt["queueCount"], - "actionableCount": receipt["actionableCount"], - "maxItems": receipt["maxItems"], - "dryRun": receipt["dryRun"], - "receiptPath": receipt_path, - "queueRows": receipt["queueRows"], - "selectedRows": receipt["selectedRows"], - "outputs": receipt["outputs"], - "authority": receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": receipt["nextSafeMove"], - })) -} - -fn repo_work_modeling_job_id(item_slug: &str, generation: u64) -> String { - format!("repo-work-modeling-{item_slug}-g{generation}") -} - -fn resolve_repo_work_model_runtime(epiphany_root: &Path) -> Result { - if let Some(configured) = env::var_os("EPIPHANY_MODEL_RUNTIME_BIN") { - let configured = PathBuf::from(configured); - return configured.canonicalize().with_context(|| { - format!( - "failed to resolve EPIPHANY_MODEL_RUNTIME_BIN {}", - configured.display() - ) - }); - } - let exe_name = if cfg!(windows) { - "epiphany-openai-runtime.exe" - } else { - "epiphany-openai-runtime" - }; - let mut candidates = Vec::new(); - if let Some(target) = env::var_os("CARGO_TARGET_DIR") { - candidates.push(PathBuf::from(target).join("debug").join(exe_name)); - } - candidates.push( - epiphany_root - .join("epiphany-openai-runtime") - .join("target") - .join("debug") - .join(exe_name), - ); - candidates.push(epiphany_root.join("target").join("debug").join(exe_name)); - candidates - .into_iter() - .find(|candidate| candidate.is_file()) - .ok_or_else(|| anyhow!("epiphany-openai-runtime binary is not built")) -} - -fn resolve_daemon_supervisor(epiphany_root: &Path) -> Result { - let exe_name = if cfg!(windows) { - "epiphany-daemon-supervisor.exe" - } else { - "epiphany-daemon-supervisor" - }; - let mut candidates = Vec::new(); - if let Some(target) = env::var_os("CARGO_TARGET_DIR") { - candidates.push(PathBuf::from(target).join("debug").join(exe_name)); - } - candidates.push( - epiphany_root - .join("epiphany-core") - .join("target") - .join("debug") - .join(exe_name), - ); - candidates.push(epiphany_root.join("target").join("debug").join(exe_name)); - candidates - .into_iter() - .find(|candidate| candidate.is_file()) - .ok_or_else(|| anyhow!("epiphany-daemon-supervisor binary is not built")) -} - -fn launch_repo_work_modeling_worker( - epiphany_root: &Path, - workspace: &Path, - artifact_dir: &Path, - runtime_store: &Path, - local_verse_store: &Path, - request: &RepoWorkModelingRequest, - item_slug: &str, - generation: u64, -) -> Result { - let job_id = repo_work_modeling_job_id(item_slug, generation); - let verified_diff = git_output( - workspace, - &[ - "show", - "--format=fuller", - "--stat", - "--patch", - &request.commit_sha, - ], - )?; - let verified_diff = verified_diff.chars().take(24_000).collect::(); - let document = EpiphanyWorkerLaunchDocument::RepoWorkModeling( - EpiphanyRepoWorkModelingLaunchDocument { - thread_id: format!("repo-work-{}", request.item), - request_id: request.request_id.clone(), - item: request.item.clone(), - soul_verdict_receipt_id: request.soul_verdict_receipt_id.clone(), - commit_sha: request.commit_sha.clone(), - changed_paths: request.changed_paths.clone(), - instruction: request.instruction.clone(), - dynamic_prompt_context: Some(format!( - "The request is immutable and already Soul-verified. Interpret commit {} across [{}]. Return a bounded finding only; Mind owns admission and Bifrost owns publication.\n\n\n{}\n", - request.commit_sha, - request.changed_paths.join(", "), - verified_diff - )), - }, - ); - let runtime_bin = resolve_repo_work_model_runtime(epiphany_root)?; - let supervisor_bin = resolve_daemon_supervisor(epiphany_root)?; - let required_document_types = [ - epiphany_core::REPO_WORK_MODELING_ROUTE_TYPE, - epiphany_core::REPO_WORK_MODELING_REQUEST_TYPE, - epiphany_core::REPO_WORK_MODELING_FINDING_TYPE, - epiphany_core::RUNTIME_WORKER_LAUNCH_REQUEST_TYPE, - ]; - let mut preflight_command = Command::new(&runtime_bin); - preflight_command - .arg("preflight") - .arg("--store") - .arg(runtime_store); - for document_type in required_document_types { - preflight_command - .arg("--require-document-type") - .arg(document_type); - } - let preflight_output = preflight_command.output().with_context(|| { - format!( - "failed to preflight Modeling runtime {}", - runtime_bin.display() - ) - })?; - if !preflight_output.status.success() { - return Err(anyhow!( - "Modeling runtime preflight refused launch before opening a job: {}", - String::from_utf8_lossy(&preflight_output.stderr) - )); - } - let preflight: Value = serde_json::from_slice(&preflight_output.stdout) - .context("Modeling runtime preflight did not emit JSON")?; - if preflight["schemaPreflightPassed"].as_bool() != Some(true) { - return Err(anyhow!("Modeling runtime schema preflight did not pass")); - } - let executable_sha256 = preflight["executableSha256"] - .as_str() - .filter(|value| !value.is_empty()) - .ok_or_else(|| anyhow!("Modeling runtime preflight omitted executable SHA-256"))? - .to_string(); - let schema_catalog_sha256 = preflight["schemaCatalogSha256"] - .as_str() - .filter(|value| !value.is_empty()) - .ok_or_else(|| anyhow!("Modeling runtime preflight omitted schema catalog SHA-256"))? - .to_string(); - let preflight_witness_id = preflight["preflightWitnessId"] - .as_str() - .filter(|value| !value.is_empty()) - .ok_or_else(|| anyhow!("Modeling runtime preflight omitted witness identity"))? - .to_string(); - let created_at = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - open_runtime_spine_heartbeat_job( - runtime_store, - RuntimeSpineHeartbeatJobOptions { - runtime_id: "repo-work-local".to_string(), - display_name: "Epiphany Repo Work".to_string(), - session_id: format!("repo-work-session-{item_slug}"), - objective: format!("Model Soul-verified repo work item {}.", request.item), - coordinator_note: "Self routes the typed request; Modeling owns the result." - .to_string(), - job_id: job_id.clone(), - role: "modeling".to_string(), - binding_id: "repo-work-modeling-worker".to_string(), - authority_scope: "epiphany.role.modeling.repo-work".to_string(), - instruction: "Act as Modeling. Interpret only the typed repo-work request and return the required bounded result. Do not claim Mind, Hands, publication, merge, or service authority." - .to_string(), - launch_document: document, - output_contract_id: REPO_WORK_MODELING_OUTPUT_CONTRACT_ID.to_string(), - organ_launch_contract: default_launch_organ_contract( - "epiphany.role.modeling.repo-work", - "repo-work-modeling", - REPO_WORK_MODELING_OUTPUT_CONTRACT_ID, - ), - created_at, - }, - )?; - let stdout_path = artifact_dir.join(format!("{job_id}.stdout.log")); - let stderr_path = artifact_dir.join(format!("{job_id}.stderr.log")); - let service_id = format!("idunn-{job_id}"); - let output = Command::new(&supervisor_bin) - .arg("service-launch") - .arg("--store") - .arg(local_verse_store) - .arg("--runtime-id") - .arg("repo-work-local") - .arg("--daemon-id") - .arg("epiphany-daemon-modeling") - .arg("--service-id") - .arg(&service_id) - .arg("--service-command") - .arg(&runtime_bin) - .arg("--service-arg") - .arg("run-worker") - .arg("--service-arg") - .arg("--store") - .arg("--service-arg") - .arg(runtime_store) - .arg("--service-arg") - .arg("--job-id") - .arg("--service-arg") - .arg(&job_id) - .arg("--service-arg") - .arg("--cwd") - .arg("--service-arg") - .arg(workspace) - .arg("--service-arg") - .arg("--max-runtime-seconds") - .arg("--service-arg") - .arg("300") - .arg("--cwd") - .arg(workspace) - .arg("--stdout-artifact") - .arg(&stdout_path) - .arg("--stderr-artifact") - .arg(&stderr_path) - .arg("--reason") - .arg(format!( - "Idunn launches typed repo-work Modeling job {job_id}." - )) - .output() - .with_context(|| { - format!( - "failed to invoke Idunn supervisor {}", - supervisor_bin.display() - ) - })?; - if !output.status.success() { - return Err(anyhow!( - "Idunn supervisor refused repo-work Modeling launch: {}", - String::from_utf8_lossy(&output.stderr) - )); - } - let lifecycle: Value = serde_json::from_slice(&output.stdout) - .context("Idunn supervisor did not emit its lifecycle receipt JSON")?; - Ok(json!({ - "jobId": job_id, - "processId": lifecycle["processId"], - "runtimeBin": runtime_bin, - "supervisorBin": supervisor_bin, - "lifecycleOwner": "Idunn", - "lifecycleReceiptId": lifecycle["receiptId"], - "serviceId": lifecycle["serviceId"], - "executableSha256": executable_sha256, - "schemaCatalogSha256": schema_catalog_sha256, - "preflightWitnessId": preflight_witness_id, - "requiredDocumentTypes": required_document_types, - "schemaPreflightPassed": true, - "stdoutArtifact": stdout_path, - "stderrArtifact": stderr_path, - "requestId": request.request_id, - "privateStateExposed": false - })) -} - -fn run_tick(args: TickArgs) -> Result { - let workspace = args - .workspace - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.workspace.display()))?; - ensure_git_repo(&workspace)?; - let epiphany_root = args - .epiphany_root - .canonicalize() - .with_context(|| format!("failed to resolve {}", args.epiphany_root.display()))?; - let artifact_dir = args - .artifact_dir - .clone() - .unwrap_or_else(|| workspace.join(".epiphany").join("work")); - fs::create_dir_all(&artifact_dir) - .with_context(|| format!("failed to create {}", artifact_dir.display()))?; - - let accept_receipt_path = resolve_accept_receipt(&workspace, args.item.as_deref(), None)?; - let accept_receipt = read_json(&accept_receipt_path)?; - let item = accept_receipt - .get("item") - .and_then(Value::as_str) - .unwrap_or("work-item") - .to_string(); - let item_slug = sanitize(&item); - let local_verse_store = args.local_verse_store.clone().or_else(|| { - path_from_json(&accept_receipt, &["localVerseStore"]) - .or_else(|| path_from_json(&accept_receipt, &["localVerseStorePath"])) - }); - - let plan_receipt_path = work_receipt_path(&workspace, "plan", &item); - let run_receipt_path = work_receipt_path(&workspace, "run", &item); - let adopt_receipt_path = work_receipt_path(&workspace, "adopt", &item); - let execute_receipt_path = work_receipt_path(&workspace, "execute", &item); - let close_receipt_path = work_receipt_path(&workspace, "close", &item); - - let before_receipts = repo_work_receipt_state( - &accept_receipt_path, - &plan_receipt_path, - &run_receipt_path, - &adopt_receipt_path, - &execute_receipt_path, - &close_receipt_path, - ); - - if let Some(brake_store) = local_verse_store.as_ref() { - if brake_store.exists() { - if let Some(brake) = load_epiphany_cultmesh_swarm_brake(brake_store, "epiphany-local")? - { - if brake.status == "engaged" { - let after_receipts = repo_work_receipt_state( - &accept_receipt_path, - &plan_receipt_path, - &run_receipt_path, - &adopt_receipt_path, - &execute_receipt_path, - &close_receipt_path, - ); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let receipt = json!({ - "schemaVersion": "epiphany.repo_work_scheduler_tick_receipt.v0", - "createdAt": now, - "workspace": workspace, - "item": item, - "localVerseStore": brake_store, - "scheduler": { - "owner": "Self", - "pulseKind": "repo-work-local", - "oneStepOnly": true, - "dryRun": args.dry_run - }, - "status": "refused-by-swarm-brake", - "action": "none", - "reason": format!( - "local Verse swarm brake engaged; scope={}; protected={}; affected={}; reason={}", - brake.scope, - brake.protected_surfaces.join(","), - brake.affected_clusters.join(","), - brake.reason - ), - "brake": { - "brakeId": brake.brake_id, - "status": brake.status, - "scope": brake.scope, - "reason": brake.reason, - "affectedClusters": brake.affected_clusters, - "protectedSurfaces": brake.protected_surfaces, - "privateStateExposed": brake.private_state_exposed - }, - "beforeReceipts": before_receipts, - "afterReceipts": after_receipts, - "advancedResult": Value::Null, - "authority": { - "branchLocalOnly": true, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthorized": false, - "crossRepoMutationAuthorized": false, - "privateStateExposed": false, - "mutationBlockedBy": "epiphany.cultmesh.swarm_brake" - }, - "nextSafeMove": "Release or narrow the local Verse swarm brake before repo-work scheduler mutation." - }); - let receipt_path = tick_receipt_path(&artifact_dir, &item_slug); - write_json(&receipt_path, &receipt)?; - return Ok(json!({ - "schemaVersion": "epiphany.repo_work_scheduler_tick.v0", - "status": receipt["status"], - "action": receipt["action"], - "workspace": receipt["workspace"], - "item": receipt["item"], - "receiptPath": receipt_path, - "reason": receipt["reason"], - "authority": receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": receipt["nextSafeMove"], - })); + "--item" => parsed.item = Some(required_value(&mut args, &arg)?), + flag if flag.starts_with("--") => { + if args.peek().is_some_and(|v| !v.starts_with("--")) { + args.next(); } } + positional => return Err(anyhow!("unexpected positional argument {positional:?}")), } } - - let active_receipt_path = tick_active_receipt_path(&artifact_dir, &item_slug); - let last_completed_receipt_path = tick_last_completed_receipt_path(&artifact_dir, &item_slug); - let mut recovered_active_turn = Value::Null; - - if active_receipt_path.exists() { - let active_receipt = read_json(&active_receipt_path)?; - let active_started_at = parse_utc_rfc3339(&active_receipt, "startedAt") - .or_else(|| parse_utc_rfc3339(&active_receipt, "createdAt")); - let active_age_seconds = active_started_at.map(seconds_since); - let active_is_stale = active_age_seconds - .map(|age| age >= args.active_timeout_seconds as i64) - .unwrap_or(false); - - if args.active_timeout_seconds == 0 || !active_is_stale { - let after_receipts = repo_work_receipt_state( - &accept_receipt_path, - &plan_receipt_path, - &run_receipt_path, - &adopt_receipt_path, - &execute_receipt_path, - &close_receipt_path, - ); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let receipt = json!({ - "schemaVersion": "epiphany.repo_work_scheduler_tick_receipt.v0", - "createdAt": now, - "workspace": workspace, - "item": item, - "localVerseStore": local_verse_store, - "scheduler": { - "owner": "Self", - "pulseKind": "repo-work-local", - "oneStepOnly": true, - "dryRun": args.dry_run, - "cooldownSeconds": args.cooldown_seconds, - "activeTimeoutSeconds": args.active_timeout_seconds - }, - "status": "refused-active-turn", - "action": "none", - "reason": "repo-work scheduler pulse already active for this work item", - "physiology": { - "activeReceiptPath": active_receipt_path, - "lastCompletedReceiptPath": last_completed_receipt_path, - "activeAgeSeconds": active_age_seconds, - "activeTimeoutSeconds": args.active_timeout_seconds, - "privateStateExposed": false - }, - "beforeReceipts": before_receipts, - "afterReceipts": after_receipts, - "advancedResult": Value::Null, - "authority": { - "branchLocalOnly": true, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthorized": false, - "crossRepoMutationAuthorized": false, - "privateStateExposed": false, - "mutationBlockedBy": "epiphany.repo_work_scheduler_active_turn" - }, - "nextSafeMove": "Wait for the active scheduler pulse to finish, or let the active-turn timeout recover a stale marker." - }); - let receipt_path = tick_receipt_path(&artifact_dir, &item_slug); - write_json(&receipt_path, &receipt)?; - return Ok(json!({ - "schemaVersion": "epiphany.repo_work_scheduler_tick.v0", - "status": receipt["status"], - "action": receipt["action"], - "workspace": receipt["workspace"], - "item": receipt["item"], - "receiptPath": receipt_path, - "reason": receipt["reason"], - "authority": receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": receipt["nextSafeMove"], - })); - } - - fs::remove_file(&active_receipt_path).with_context(|| { - format!( - "failed to clear stale active tick receipt {}", - active_receipt_path.display() - ) - })?; - recovered_active_turn = json!({ - "activeReceiptPath": active_receipt_path, - "activeAgeSeconds": active_age_seconds, - "activeTimeoutSeconds": args.active_timeout_seconds, - "recovered": true, - "privateStateExposed": false - }); - } - - if args.cooldown_seconds > 0 && last_completed_receipt_path.exists() { - let last_completed_receipt = read_json(&last_completed_receipt_path)?; - if let Some(last_created_at) = parse_utc_rfc3339(&last_completed_receipt, "createdAt") { - let elapsed_seconds = seconds_since(last_created_at); - if elapsed_seconds < args.cooldown_seconds as i64 { - let after_receipts = repo_work_receipt_state( - &accept_receipt_path, - &plan_receipt_path, - &run_receipt_path, - &adopt_receipt_path, - &execute_receipt_path, - &close_receipt_path, - ); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let receipt = json!({ - "schemaVersion": "epiphany.repo_work_scheduler_tick_receipt.v0", - "createdAt": now, - "workspace": workspace, - "item": item, - "localVerseStore": local_verse_store, - "scheduler": { - "owner": "Self", - "pulseKind": "repo-work-local", - "oneStepOnly": true, - "dryRun": args.dry_run, - "cooldownSeconds": args.cooldown_seconds, - "activeTimeoutSeconds": args.active_timeout_seconds - }, - "status": "refused-by-cooldown", - "action": "none", - "reason": format!( - "repo-work scheduler cooldown has not elapsed: {elapsed_seconds}s < {}s", - args.cooldown_seconds - ), - "physiology": { - "activeReceiptPath": active_receipt_path, - "lastCompletedReceiptPath": last_completed_receipt_path, - "elapsedSeconds": elapsed_seconds, - "cooldownSeconds": args.cooldown_seconds, - "privateStateExposed": false - }, - "beforeReceipts": before_receipts, - "afterReceipts": after_receipts, - "advancedResult": Value::Null, - "authority": { - "branchLocalOnly": true, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthorized": false, - "crossRepoMutationAuthorized": false, - "privateStateExposed": false, - "mutationBlockedBy": "epiphany.repo_work_scheduler_cooldown" - }, - "nextSafeMove": "Wait for scheduler cooldown to elapse before pulsing this work item again." - }); - let receipt_path = tick_receipt_path(&artifact_dir, &item_slug); - write_json(&receipt_path, &receipt)?; - return Ok(json!({ - "schemaVersion": "epiphany.repo_work_scheduler_tick.v0", - "status": receipt["status"], - "action": receipt["action"], - "workspace": receipt["workspace"], - "item": receipt["item"], - "receiptPath": receipt_path, - "reason": receipt["reason"], - "authority": receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": receipt["nextSafeMove"], - })); - } - } - } - - let active_started_at = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let active_marker = json!({ - "schemaVersion": "epiphany.repo_work_scheduler_tick_active.v0", - "createdAt": active_started_at, - "startedAt": active_started_at, - "workspace": workspace, - "item": item, - "scheduler": { - "owner": "Self", - "pulseKind": "repo-work-local", - "oneStepOnly": true, - "dryRun": args.dry_run, - "cooldownSeconds": args.cooldown_seconds, - "activeTimeoutSeconds": args.active_timeout_seconds - }, - "authority": { - "branchLocalOnly": true, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthorized": false, - "crossRepoMutationAuthorized": false, - "privateStateExposed": false - } - }); - write_json(&active_receipt_path, &active_marker)?; - - let mut action = "none".to_string(); - let status; - let reason; - let next_safe_move; - let mut advanced_result = Value::Null; - - if close_receipt_path.exists() - && read_json(&close_receipt_path)? - .get("status") - .and_then(Value::as_str) - == Some("closed") - { - action = "none".to_string(); - status = "noop".to_string(); - reason = "Soul/Modeling/Mind closure is recorded; scheduler stops before Bifrost publication authority".to_string(); - next_safe_move = - "Submit a Bifrost publication intent through the owning integration.".to_string(); - } else if close_receipt_path.exists() { - let partial_close = read_json(&close_receipt_path)?; - let runtime_store = args - .runtime_store - .clone() - .or_else(|| path_from_json(&partial_close, &["runtimeStore"])) - .ok_or_else(|| anyhow!("awaiting-modeling closure has no runtime store"))?; - let route_id = format!("repo-work-modeling-route-{item_slug}"); - let route = runtime_repo_work_modeling_route(&runtime_store, &route_id)? - .ok_or_else(|| anyhow!("typed Modeling route {route_id:?} is missing"))?; - let request = runtime_repo_work_modeling_request(&runtime_store, &route.request_id)? - .ok_or_else(|| anyhow!("current Modeling request {:?} is missing", route.request_id))?; - let finding_id = format!("{}-finding", request.request_id); - if let Some(finding) = runtime_repo_work_modeling_finding(&runtime_store, &finding_id)? { - if finding.verdict.trim().eq_ignore_ascii_case("passed") { - action = "admit-modeling".to_string(); - if args.dry_run { - status = "would-advance".to_string(); - reason = "a passing typed Modeling finding is ready for immutable Mind/map admission" - .to_string(); - next_safe_move = - "Rerun without --dry-run to resume closure through Mind admission." - .to_string(); - } else { - advanced_result = run_close(CloseArgs { - workspace: workspace.clone(), - item: Some(item.clone()), - execute_receipt: Some(execute_receipt_path.clone()), - runtime_store: Some(runtime_store.clone()), - artifact_dir: Some(artifact_dir.clone()), - })?; - status = advanced_result["status"] - .as_str() - .unwrap_or("closed") - .to_string(); - reason = "Mind admitted the matching model-authored finding and repo-work map" - .to_string(); - next_safe_move = "Stop before Bifrost publication authority.".to_string(); - } - } else { - action = "await-modeling-revision".to_string(); - status = "blocked".to_string(); - reason = format!( - "Modeling returned verdict {}; immutable request requires reviewed revision before another attempt", - finding.verdict - ); - next_safe_move = "Review the Modeling finding and create a new bounded work request; do not overwrite immutable evidence." - .to_string(); - } - } else { - let job_id = repo_work_modeling_job_id(&item_slug, route.generation); - match runtime_job_snapshot(&runtime_store, &job_id)? { - Some(snapshot) - if matches!( - snapshot.job.status, - epiphany_core::EpiphanyRuntimeJobStatus::Queued - | epiphany_core::EpiphanyRuntimeJobStatus::Running - ) => - { - action = "await-modeling".to_string(); - status = "waiting".to_string(); - reason = format!("Modeling worker job {job_id} is still active"); - next_safe_move = - "Wait for the Modeling runtime result; do not launch a duplicate job." - .to_string(); - } - Some(snapshot) => { - action = "await-modeling".to_string(); - status = "blocked".to_string(); - reason = format!( - "Modeling worker job {job_id} ended as {:?} without a typed finding", - snapshot.job.status - ); - next_safe_move = "Inspect the sealed worker stdout/stderr and runtime result before a reviewed retry." - .to_string(); - } - None if args.dry_run => { - action = "launch-modeling".to_string(); - status = "would-advance".to_string(); - reason = "typed Modeling request is ready for the existing worker runtime" - .to_string(); - advanced_result = json!({ - "schemaVersion": "epiphany.repo_work_modeling_launch_projection.v0", - "status": "launch-ready", - "routeId": route.route_id, - "generation": route.generation, - "requestId": request.request_id, - "jobId": job_id, - "preflightRequired": true, - "lifecycleOwner": "Idunn", - "privateStateExposed": false - }); - next_safe_move = - "Rerun without --dry-run to launch the repo-work Modeling worker." - .to_string(); - } - None => { - action = "launch-modeling".to_string(); - let lifecycle_store = local_verse_store - .clone() - .unwrap_or_else(|| workspace.join(".epiphany").join("local-verse.ccmp")); - advanced_result = launch_repo_work_modeling_worker( - &epiphany_root, - &workspace, - &artifact_dir, - &runtime_store, - &lifecycle_store, - &request, - &item_slug, - route.generation, - )?; - status = "modeling-launched".to_string(); - reason = - "Self routed the typed request to the existing model runtime".to_string(); - next_safe_move = - "Let a later scheduler pulse consume the typed Modeling finding." - .to_string(); - } - } - } - } else if execute_receipt_path.exists() { - action = "soul-verify".to_string(); - if args.dry_run { - status = "would-advance".to_string(); - reason = "executed work is ready for Soul verification".to_string(); - next_safe_move = "Rerun without --dry-run to verify the Hands consequence and emit the typed Modeling request." - .to_string(); - } else { - advanced_result = run_verify(CloseArgs { - workspace: workspace.clone(), - item: Some(item.clone()), - execute_receipt: Some(execute_receipt_path.clone()), - runtime_store: args.runtime_store.clone(), - artifact_dir: Some(artifact_dir.clone()), - })?; - status = advanced_result - .get("status") - .and_then(Value::as_str) - .unwrap_or("awaiting-modeling") - .to_string(); - reason = - "Soul verified the Hands consequence and Self routed the typed Modeling request" - .to_string(); - next_safe_move = - "Let the next scheduler pulse await or collect the matching Modeling finding." - .to_string(); - } - } else if adopt_receipt_path.exists() { - if !plan_receipt_path.exists() { - status = "blocked".to_string(); - reason = "adoption receipt exists but no matching plan receipt exists".to_string(); - next_safe_move = "Restore or pass a plan receipt before execution.".to_string(); - } else if args.dry_run { - action = "execute-from-plan".to_string(); - status = "would-advance".to_string(); - reason = "approved adoption and plan receipt exist".to_string(); - next_safe_move = - "Rerun without --dry-run to execute the adopted branch-local plan.".to_string(); - } else { - action = "execute-from-plan".to_string(); - advanced_result = run_execute(ExecuteArgs { - workspace: workspace.clone(), - epiphany_root: epiphany_root.clone(), - item: Some(item.clone()), - adopt_receipt: Some(adopt_receipt_path.clone()), - plan_receipt: Some(plan_receipt_path.clone()), - runtime_store: args.runtime_store.clone(), - artifact_dir: Some(artifact_dir.clone()), - command: None, - changed_paths: Vec::new(), - commit_message: None, - summary: Some(format!( - "Scheduler pulse executed adopted repo work item {item}." - )), - })?; - status = "advanced".to_string(); - reason = "executed approved branch-local plan through Hands".to_string(); - next_safe_move = - "Route Soul verification and Mind review before publication.".to_string(); - } - } else if run_receipt_path.exists() { - if !plan_receipt_path.exists() { - status = "blocked".to_string(); - reason = "run receipt exists but no matching plan receipt exists".to_string(); - next_safe_move = - "Write an Imagination/Self action plan before adopting Hands authority." - .to_string(); - } else { - action = "await-mind-review".to_string(); - status = "awaiting-mind-review".to_string(); - reason = "Self found a queued run and plan, but no typed Mind adoption review has granted authority".to_string(); - next_safe_move = "Mind must persist an exact epiphany.repo_work_plan_adoption_review.v0 receipt; the scheduler cannot manufacture its verdict.".to_string(); - } - } else if plan_receipt_path.exists() { - let plan_receipt = read_json(&plan_receipt_path)?; - let requested_paths = first_plan_action(&plan_receipt) - .map(|action| string_array_field(action, "changedPaths")) - .unwrap_or_default(); - if requested_paths.is_empty() { - status = "blocked".to_string(); - reason = "plan receipt has no changedPaths for the Substrate Gate".to_string(); - next_safe_move = - "Repair the plan receipt or write a new plan with changed paths.".to_string(); - } else if args.dry_run { - action = "run-from-plan".to_string(); - status = "would-advance".to_string(); - reason = "accepted item and plan receipt exist".to_string(); - next_safe_move = - "Rerun without --dry-run to open the queued Substrate Gate and Hands run packet." - .to_string(); - } else { - action = "run-from-plan".to_string(); - advanced_result = run_work(RunArgs { - workspace: workspace.clone(), - epiphany_root: epiphany_root.clone(), - item: Some(item.clone()), - accept_receipt: Some(accept_receipt_path.clone()), - runtime_store: args.runtime_store.clone(), - artifact_dir: Some(artifact_dir.clone()), - requested_paths, - })?; - status = "advanced".to_string(); - reason = - "opened queued Substrate Gate and Hands run packet from plan paths".to_string(); - next_safe_move = - "Run another scheduler pulse to adopt the plan into Hands authority.".to_string(); - } - } else { - status = "blocked".to_string(); - reason = "accepted work item has no matching action plan receipt".to_string(); - next_safe_move = - "Create an Imagination/Self plan receipt before scheduler can advance work." - .to_string(); - } - - let after_receipts = repo_work_receipt_state( - &accept_receipt_path, - &plan_receipt_path, - &run_receipt_path, - &adopt_receipt_path, - &execute_receipt_path, - &close_receipt_path, - ); - let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true); - let receipt = json!({ - "schemaVersion": "epiphany.repo_work_scheduler_tick_receipt.v0", - "createdAt": now, - "workspace": workspace, - "item": item, - "localVerseStore": local_verse_store, - "scheduler": { - "owner": "Self", - "pulseKind": "repo-work-local", - "oneStepOnly": true, - "dryRun": args.dry_run, - "cooldownSeconds": args.cooldown_seconds, - "activeTimeoutSeconds": args.active_timeout_seconds - }, - "status": status, - "action": action, - "reason": reason, - "physiology": { - "activeReceiptPath": active_receipt_path, - "lastCompletedReceiptPath": last_completed_receipt_path, - "recoveredActiveTurn": recovered_active_turn, - "cooldownSeconds": args.cooldown_seconds, - "activeTimeoutSeconds": args.active_timeout_seconds, - "privateStateExposed": false - }, - "beforeReceipts": before_receipts, - "afterReceipts": after_receipts, - "advancedResult": advanced_result, - "authority": { - "branchLocalOnly": true, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthorized": false, - "crossRepoMutationAuthorized": false, - "privateStateExposed": false - }, - "nextSafeMove": next_safe_move - }); - let receipt_path = tick_receipt_path(&artifact_dir, &item_slug); - write_json(&receipt_path, &receipt)?; - write_json(&last_completed_receipt_path, &receipt)?; - if active_receipt_path.exists() { - fs::remove_file(&active_receipt_path).with_context(|| { - format!( - "failed to clear active tick receipt {}", - active_receipt_path.display() - ) - })?; - } - Ok(json!({ - "schemaVersion": "epiphany.repo_work_scheduler_tick.v0", - "status": receipt["status"], - "action": receipt["action"], - "workspace": receipt["workspace"], - "item": receipt["item"], - "receiptPath": receipt_path, - "reason": receipt["reason"], - "authority": receipt["authority"], - "privateStateExposed": false, - "nextSafeMove": receipt["nextSafeMove"], - })) -} - -fn resolve_accept_receipt( - workspace: &Path, - item: Option<&str>, - explicit: Option, -) -> Result { - if let Some(path) = explicit { - return Ok(path); - } - let work_dir = workspace.join(".epiphany").join("work"); - if let Some(item) = item { - return Ok(work_dir.join(format!("work-accept-{}.json", sanitize(item)))); - } - let mut candidates = Vec::new(); - if work_dir.exists() { - for entry in fs::read_dir(&work_dir)? { - let entry = entry?; - let path = entry.path(); - let Some(name) = path.file_name().and_then(|name| name.to_str()) else { - continue; - }; - if name.starts_with("work-accept-") && name.ends_with(".json") { - let modified = entry.metadata()?.modified()?; - candidates.push((modified, path)); - } - } - } - candidates.sort_by_key(|(modified, _path)| *modified); - candidates - .pop() - .map(|(_modified, path)| path) - .ok_or_else(|| anyhow!("no work accept receipt found; run epiphany-work accept first or pass --accept-receipt")) -} - -fn resolve_run_receipt( - workspace: &Path, - item: Option<&str>, - explicit: Option, -) -> Result { - if let Some(path) = explicit { - return Ok(path); - } - let work_dir = workspace.join(".epiphany").join("work"); - if let Some(item) = item { - return Ok(work_dir.join(format!("work-run-{}.json", sanitize(item)))); - } - latest_receipt_in(&work_dir, "work-run-").ok_or_else(|| { - anyhow!("no work run receipt found; run epiphany-work run first or pass --run-receipt") - }) -} - -fn resolve_adopt_receipt( - workspace: &Path, - item: Option<&str>, - explicit: Option, -) -> Result { - if let Some(path) = explicit { - return Ok(path); - } - let work_dir = workspace.join(".epiphany").join("work"); - if let Some(item) = item { - return Ok(work_dir.join(format!("work-adopt-{}.json", sanitize(item)))); - } - latest_receipt_in(&work_dir, "work-adopt-").ok_or_else(|| { - anyhow!( - "no work adopt receipt found; run epiphany-work adopt first or pass --adopt-receipt" - ) - }) -} - -fn resolve_execute_receipt( - workspace: &Path, - item: Option<&str>, - explicit: Option, -) -> Result { - if let Some(path) = explicit { - return Ok(path); - } - let work_dir = workspace.join(".epiphany").join("work"); - if let Some(item) = item { - return Ok(work_dir.join(format!("work-execute-{}.json", sanitize(item)))); - } - latest_receipt_in(&work_dir, "work-execute-").ok_or_else(|| { - anyhow!( - "no work execute receipt found; run epiphany-work execute first or pass --execute-receipt" - ) - }) -} - -fn work_receipt_path(workspace: &Path, kind: &str, item: &str) -> PathBuf { - workspace - .join(".epiphany") - .join("work") - .join(format!("work-{kind}-{}.json", sanitize(item))) -} - -fn repo_work_receipt_state( - accept: &Path, - plan: &Path, - run: &Path, - adopt: &Path, - execute: &Path, - close: &Path, -) -> Value { - json!({ - "accept": receipt_path_state(accept), - "plan": receipt_path_state(plan), - "run": receipt_path_state(run), - "adopt": receipt_path_state(adopt), - "execute": receipt_path_state(execute), - "close": receipt_path_state(close), - }) -} - -fn receipt_path_state(path: &Path) -> Value { - json!({ - "path": path, - "exists": path.exists(), - }) -} - -fn existing_path_value(path: &Path) -> Value { - if path.exists() { - Value::String(path.display().to_string()) - } else { - Value::Null - } -} - -fn readiness_path_row( - kind: &str, - owner: &str, - required_schema: &str, - path: &Path, - satisfied: bool, - note: &str, -) -> Result { - let document = read_json_if_exists(path)?; - let schema_version = document - .as_ref() - .and_then(|value| string_from_json(value, &["schemaVersion"])) - .unwrap_or_else(|| "missing".to_string()); - let document_status = document - .as_ref() - .and_then(|value| string_from_json(value, &["status"])) - .unwrap_or_else(|| "missing".to_string()); - Ok(json!({ - "kind": kind, - "owner": owner, - "requiredSchema": required_schema, - "evidenceRef": existing_path_value(path), - "artifactStatus": if path.exists() { "present" } else { "missing" }, - "schemaVersion": schema_version, - "documentStatus": document_status, - "satisfied": satisfied, - "status": if satisfied { "satisfied" } else { "missing" }, - "note": note, - "privateStateExposed": false - })) -} - -fn readiness_missing_row(kind: &str, owner: &str, required_schema: &str, note: &str) -> Value { - json!({ - "kind": kind, - "owner": owner, - "requiredSchema": required_schema, - "evidenceRef": Value::Null, - "artifactStatus": "missing", - "schemaVersion": "missing", - "documentStatus": "missing", - "satisfied": false, - "status": "missing", - "note": note, - "privateStateExposed": false - }) -} - -fn idunn_lifecycle_readiness_row(path: &Path) -> Result { - let document = read_json_if_exists(path)?; - let schema_version = document - .as_ref() - .and_then(|value| string_from_json(value, &["schemaVersion"])) - .unwrap_or_else(|| "missing".to_string()); - let document_status = document - .as_ref() - .and_then(|value| string_from_json(value, &["status"])) - .unwrap_or_else(|| "missing".to_string()); - let plan_status = document - .as_ref() - .and_then(|value| string_from_json(value, &["planStatus"])) - .unwrap_or_else(|| "missing".to_string()); - let runbook_status = document - .as_ref() - .and_then(|value| string_from_json(value, &["runbookStatus"])) - .unwrap_or_else(|| "missing".to_string()); - let runbook_artifact_status = document - .as_ref() - .and_then(|value| string_from_json(value, &["runbookArtifactStatus"])) - .unwrap_or_else(|| "missing".to_string()); - let launch_status = document - .as_ref() - .and_then(|value| string_from_json(value, &["launchStatus"])) - .unwrap_or_else(|| "missing".to_string()); - let lifecycle_owner = document - .as_ref() - .and_then(|value| string_from_json(value, &["lifecycleOwner"])) - .unwrap_or_else(|| "missing".to_string()); - let hosted_body = document - .as_ref() - .and_then(|value| string_from_json(value, &["hostedBody"])) - .unwrap_or_else(|| "missing".to_string()); - let private_state_exposed = document - .as_ref() - .and_then(|value| bool_from_json(value, &["privateStateExposed"])) - .unwrap_or(true); - let missing_count = document - .as_ref() - .and_then(|value| value.get("missingChecks")) - .and_then(Value::as_array) - .map(Vec::len) - .unwrap_or(usize::MAX); - let failed_count = document - .as_ref() - .and_then(|value| value.get("failedChecks")) - .and_then(Value::as_array) - .map(Vec::len) - .unwrap_or(usize::MAX); - let satisfied = schema_version == "epiphany.repo_work_service_audit.v0" - && document_status == "complete" - && plan_status == "present" - && runbook_status == "present" - && runbook_artifact_status == "present" - && launch_status == "ok" - && lifecycle_owner == "Idunn" - && hosted_body == "repo-work" - && document - .as_ref() - .and_then(|value| bool_from_json(value, &["mutatesServiceManager"])) - == Some(false) - && document - .as_ref() - .and_then(|value| bool_from_json(value, &["requiresElevatedAuthority"])) - == Some(false) - && !private_state_exposed - && missing_count == 0 - && failed_count == 0; - - Ok(json!({ - "kind": "idunn-lifecycle", - "owner": "Idunn", - "requiredSchema": "epiphany.repo_work_service_audit.v0", - "evidenceRef": existing_path_value(path), - "artifactStatus": if path.exists() { "present" } else { "missing" }, - "schemaVersion": schema_version, - "documentStatus": document_status, - "planStatus": plan_status, - "runbookStatus": runbook_status, - "runbookArtifactStatus": runbook_artifact_status, - "launchStatus": launch_status, - "missingCheckCount": missing_count, - "failedCheckCount": failed_count, - "lifecycleOwner": lifecycle_owner, - "hostedBody": hosted_body, - "mutatesServiceManager": document - .as_ref() - .and_then(|value| bool_from_json(value, &["mutatesServiceManager"])) - .unwrap_or(true), - "requiresElevatedAuthority": document - .as_ref() - .and_then(|value| bool_from_json(value, &["requiresElevatedAuthority"])) - .unwrap_or(true), - "privateStateExposed": private_state_exposed, - "satisfied": satisfied, - "status": if satisfied { "satisfied" } else { "missing" }, - "note": "Idunn repo-work service audit proves the queue runner lifecycle path without service-manager mutation.", - "serviceLifecycleAuthority": false, - "deploymentAuthority": false, - "handsActionAuthorized": false - })) -} - -fn tool_directory_readiness_row(path: &Path) -> Result { - let document = read_json_if_exists(path)?; - let schema_version = document - .as_ref() - .and_then(|value| string_from_json(value, &["schemaVersion"])) - .unwrap_or_else(|| "missing".to_string()); - let document_status = document - .as_ref() - .and_then(|value| string_from_json(value, &["status"])) - .unwrap_or_else(|| "missing".to_string()); - let tool_count = document - .as_ref() - .and_then(|value| value.get("toolCount")) - .and_then(Value::as_u64) - .unwrap_or(0); - let host_ready_count = document - .as_ref() - .and_then(|value| value.get("hostReadyCount")) - .and_then(Value::as_u64) - .unwrap_or(0); - let host_attention_count = document - .as_ref() - .and_then(|value| value.get("hostAttentionCount")) - .and_then(Value::as_u64) - .unwrap_or(0); - let invariant_all_agents = document - .as_ref() - .and_then(|value| bool_from_json(value, &["invariants", "availableToAllAgents"])) - .unwrap_or(false); - let invariant_receipts = document - .as_ref() - .and_then(|value| bool_from_json(value, &["invariants", "requiresReceipt"])) - .unwrap_or(false); - let invariant_private = document - .as_ref() - .and_then(|value| bool_from_json(value, &["invariants", "privateStateExposed"])) - .unwrap_or(true); - let has_invoke_command = document - .as_ref() - .and_then(|value| string_from_json(value, &["invocationCommand"])) - .is_some_and(|command| command.contains("invoke-tool")); - let has_wrapper_command = document - .as_ref() - .and_then(|value| string_from_json(value, &["wrapperInvocationCommand"])) - .is_some_and(|command| command.contains("tool-invoke")); - let satisfied = schema_version == "epiphany.cultmesh.daemon_tool_directory.v0" - && document_status == "ok" - && tool_count > 0 - && host_ready_count > 0 - && host_attention_count == 0 - && invariant_all_agents - && invariant_receipts - && !invariant_private - && has_invoke_command - && has_wrapper_command; - - Ok(json!({ - "kind": "tool-directory", - "owner": "Odin", - "requiredSchema": "epiphany.cultmesh.daemon_tool_directory.v0", - "evidenceRef": existing_path_value(path), - "artifactStatus": if path.exists() { "present" } else { "missing" }, - "schemaVersion": schema_version, - "documentStatus": document_status, - "toolCount": tool_count, - "hostReadyCount": host_ready_count, - "hostAttentionCount": host_attention_count, - "availableToAllAgents": invariant_all_agents, - "requiresReceipt": invariant_receipts, - "hasInvocationCommand": has_invoke_command, - "hasWrapperInvocationCommand": has_wrapper_command, - "privateStateExposed": invariant_private, - "satisfied": satisfied, - "status": if satisfied { "satisfied" } else { "missing" }, - "note": "Odin tool-directory sight proves globally available daemon-hosted tools through typed intents and receipts.", - "toolExecutionAuthority": false, - "serviceLifecycleAuthority": false, - "privateVerseRummagingAuthorized": false - })) -} - -fn read_json_if_exists(path: &Path) -> Result> { - if path.exists() { - read_json(path).map(Some) - } else { - Ok(None) - } -} - -fn repo_work_existing_receipt_refs(receipts: &[(&str, &Path)]) -> Vec { - receipts - .iter() - .filter_map(|(kind, path)| { - if path.exists() { - Some(format!("{kind}:{}", path.display())) - } else { - None - } - }) - .collect() -} - -fn repo_work_proof_artifact_rows(receipts: &[(&str, &Path)]) -> Result> { - receipts - .iter() - .map(|(kind, path)| { - if !path.exists() { - return Ok(json!({ - "kind": kind, - "expectedPath": path.display().to_string(), - "path": Value::Null, - "artifactStatus": "missing", - "artifactSha256": "none", - "schemaVersion": "missing", - "documentStatus": "missing", - "privateStateExposed": false - })); - } - - let document = read_json(path).with_context(|| { - format!( - "failed to read proof artifact {} at {}", - kind, - path.display() - ) - })?; - let schema_version = string_from_json(&document, &["schemaVersion"]) - .unwrap_or_else(|| "unknown".to_string()); - let document_status = - string_from_json(&document, &["status"]).unwrap_or_else(|| "unknown".to_string()); - Ok(json!({ - "kind": kind, - "expectedPath": path.display().to_string(), - "path": existing_path_value(path), - "artifactStatus": "present", - "artifactSha256": file_sha256(path)?, - "schemaVersion": schema_version, - "documentStatus": document_status, - "privateStateExposed": false - })) - }) - .collect() -} - -fn repo_work_public_proof_bundle(overview: &Value) -> Result { - let proof = overview - .get("proofBundle") - .ok_or_else(|| anyhow!("overview did not include proofBundle"))?; - let artifact_rows = proof - .get("artifactRows") - .and_then(Value::as_array) - .map(|rows| { - rows.iter() - .map(repo_work_public_artifact_row) - .collect::>() - }) - .unwrap_or_default(); - let publication_rows = proof - .get("publicationRows") - .and_then(Value::as_array) - .cloned() - .unwrap_or_default(); - Ok(json!({ - "schemaVersion": "epiphany.repo_work_public_proof_bundle.v0", - "bundleId": proof["bundleId"], - "generatedAt": Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true), - "sourceProofGeneratedAt": proof["generatedAt"], - "item": proof["item"], - "branch": proof["branch"], - "currentGate": proof["currentGate"], - "blocker": proof["blocker"], - "nextSafeMove": proof["nextSafeMove"], - "changedPaths": proof["changedPaths"], - "commitSha": proof["commitSha"], - "soulVerdict": proof["soulVerdict"], - "mindStateCommitReceiptId": proof["mindStateCommitReceiptId"], - "bifrostPublicationReceiptId": proof["bifrostPublicationReceiptId"], - "githubPublicationReceiptId": proof["githubPublicationReceiptId"], - "upstreamMainSynced": proof["upstreamMainSynced"], - "artifactRows": artifact_rows, - "publicationRows": publication_rows, - "tuiRows": proof["tuiRows"], - "redaction": { - "rawReceiptBodiesIncluded": false, - "localReceiptPathsIncluded": false, - "rawWorkerThoughtIncluded": false, - "privateStateExposed": false - }, - "authority": { - "owner": "Eyes", - "sightOnly": true, - "publicationAuthorized": false, - "mergeAuthorized": false, - "serviceLifecycleAuthorized": false, - "crossRepoMutationAuthorized": false, - "privateStateExposed": false - }, - "privateStateExposed": false - })) -} - -fn repo_work_public_artifact_row(row: &Value) -> Value { - json!({ - "kind": row.get("kind").cloned().unwrap_or(Value::Null), - "artifactStatus": row.get("artifactStatus").cloned().unwrap_or(Value::Null), - "artifactSha256": row.get("artifactSha256").cloned().unwrap_or(Value::Null), - "schemaVersion": row.get("schemaVersion").cloned().unwrap_or(Value::Null), - "documentStatus": row.get("documentStatus").cloned().unwrap_or(Value::Null), - "privateStateExposed": false - }) -} - -fn repo_work_public_proof_tui_rows( - bundle: &Value, - output: &Path, - sha256: &str, - artifact_row_count: usize, - publication_row_count: usize, -) -> Vec { - vec![format!( - "PUBLIC-PROOF | item={} | gate={} | branch={} | commit={} | artifacts={} | publicationRows={} | upstreamMainSynced={} | proof={} | sha256={} | private=false", - string_from_json(bundle, &["item"]).unwrap_or_else(|| "unknown".to_string()), - string_from_json(bundle, &["currentGate"]).unwrap_or_else(|| "unknown".to_string()), - string_from_json(bundle, &["branch"]).unwrap_or_else(|| "unknown".to_string()), - string_from_json(bundle, &["commitSha"]).unwrap_or_else(|| "none".to_string()), - artifact_row_count, - publication_row_count, - bundle - .get("upstreamMainSynced") - .and_then(Value::as_bool) - .unwrap_or(false), - output.display(), - sha256 - )] -} - -fn repo_work_proof_bundle_tui_rows( - item: &str, - branch: &str, - gate: &str, - blocker: &str, - closure_status: &str, - publication_status: &str, - sync_status: &str, - present_artifact_count: usize, -) -> Vec { - vec![ - format!("PROOF | item={item} | gate={gate} | blocker={blocker} | private=false"), - format!( - "PROOF | branch={branch} | artifactsPresent={present_artifact_count} | closure={closure_status} | publication={publication_status} | sync={sync_status}" - ), - ] -} - -fn repo_work_overview_gate( - plan: Option<&Value>, - run: Option<&Value>, - adopt: Option<&Value>, - execute: Option<&Value>, - close: Option<&Value>, -) -> (&'static str, &'static str, &'static str) { - if close - .and_then(|receipt| receipt.get("status")) - .and_then(Value::as_str) - == Some("closed") - { - ( - "awaiting-publication", - "bifrost-publication-missing", - "Submit a Bifrost publication intent through the owning integration.", - ) - } else if close - .and_then(|receipt| receipt.get("status")) - .and_then(Value::as_str) - == Some("awaiting-modeling") - { - ( - "awaiting-modeling", - "modeling-finding-missing", - "Route the typed Modeling request and resume closure with its matching finding.", - ) - } else if close.is_some() { - ( - "verification-refused", - "soul-verdict-not-passed", - "Repair the Hands consequence or verification evidence before retrying Soul.", - ) - } else if execute.is_some() { - ( - "awaiting-closure", - "soul-modeling-mind-closure-missing", - "Run epiphany-work close before publication.", - ) - } else if adopt.is_some() { - ( - "ready-to-execute", - "none", - "Run epiphany-work execute --from-plan or pulse epiphany-work tick.", - ) - } else if run.is_some() { - ( - "ready-to-adopt", - "none", - "Run epiphany-work adopt --from-plan or pulse epiphany-work tick.", - ) - } else if plan.is_some() { - ( - "ready-to-run", - "none", - "Run epiphany-work run or pulse epiphany-work tick.", - ) - } else { - ( - "awaiting-plan", - "plan-receipt-missing", - "Run epiphany-work derive-plan or epiphany-work plan.", - ) - } -} - -fn load_repo_work_overview_queue_from_store( - store: &Path, - runtime_id: &str, -) -> Result<( - Option, - Vec, -)> { - let latest = load_latest_epiphany_cultmesh_repo_work_overview(store, runtime_id.to_string())?; - let mut overviews = load_epiphany_cultmesh_repo_work_overviews(store, runtime_id.to_string())?; - if let Some(latest_overview) = latest.as_ref() { - if !overviews - .iter() - .any(|overview| overview.overview_id == latest_overview.overview_id) - { - overviews.push(latest_overview.clone()); - overviews.sort_by(|a, b| { - b.generated_at - .cmp(&a.generated_at) - .then_with(|| a.overview_id.cmp(&b.overview_id)) - }); - } - } - Ok((latest, overviews)) -} - -fn repo_work_gate_is_tick_actionable(gate: &str) -> bool { - matches!( - gate, - "ready-to-run" | "ready-to-adopt" | "ready-to-execute" | "awaiting-closure" - ) -} - -fn overview_workspace_matches( - overview: &EpiphanyCultMeshRepoWorkOverviewEntry, - workspace: &Path, -) -> bool { - let overview_path = PathBuf::from(&overview.workspace); - overview_path - .canonicalize() - .map(|path| path == workspace) - .unwrap_or_else(|_| { - normalize_path_text(&overview.workspace) - == normalize_path_text(&workspace.display().to_string()) - }) -} - -fn normalize_path_text(value: &str) -> String { - value.replace('\\', "/").to_ascii_lowercase() -} - -fn repo_work_queue_selection_rows( - overviews: &[EpiphanyCultMeshRepoWorkOverviewEntry], - workspace: &Path, -) -> Vec { - overviews - .iter() - .map(|overview| { - let workspace_match = overview_workspace_matches(overview, workspace); - let tick_actionable = repo_work_gate_is_tick_actionable(&overview.current_gate); - json!({ - "overviewId": overview.overview_id, - "item": overview.item, - "branch": overview.branch, - "gate": overview.current_gate, - "blocker": overview.blocker, - "actionable": tick_actionable, - "workspaceMatch": workspace_match, - "nextSafeMove": overview.next_safe_move, - "privateStateExposed": overview.private_state_exposed, - }) - }) - .collect() -} - -fn latest_receipt_in(work_dir: &Path, prefix: &str) -> Option { - let mut candidates = Vec::new(); - if work_dir.exists() { - for entry in fs::read_dir(work_dir).ok()? { - let entry = entry.ok()?; - let path = entry.path(); - let name = path.file_name().and_then(|name| name.to_str())?; - if name.starts_with(prefix) && name.ends_with(".json") { - let modified = entry.metadata().ok()?.modified().ok()?; - candidates.push((modified, path)); - } - } - } - candidates.sort_by_key(|(modified, _path)| *modified); - candidates.pop().map(|(_modified, path)| path) -} - -fn ensure_hands_review_allows( - intent: &HandsActionIntent, - review: &epiphany_core::HandsActionReview, - operation: &str, -) -> Result<()> { - if review.intent_id != intent.intent_id { - return Err(anyhow!( - "Hands review {} belongs to {}, not {}", - review.review_id, - review.intent_id, - intent.intent_id - )); - } - if review.decision != "approved" { - return Err(anyhow!( - "Hands review {} decision is {}, not approved", - review.review_id, - review.decision - )); - } - if !review - .allowed_operations - .iter() - .any(|allowed| allowed == operation) - { - return Err(anyhow!( - "Hands review {} does not allow {operation}", - review.review_id - )); - } - Ok(()) -} - -fn validate_paths_within_gate(intent: &HandsActionIntent, paths: &[String]) -> Result<()> { - let requested = normalize_paths(intent.requested_paths.clone()); - for path in paths { - let normalized = normalize_path(path); - if requested.iter().any(|allowed| { - allowed == "." - || normalized == *allowed - || normalized.starts_with(&format!("{}/", allowed.trim_end_matches('/'))) - }) { - continue; - } - return Err(anyhow!( - "changed path {normalized:?} is outside approved Hands path scope {:?}", - requested - )); - } - Ok(()) -} - -fn normalize_paths(paths: Vec) -> Vec { - paths - .into_iter() - .map(|path| normalize_path(&path)) - .collect() -} - -fn normalize_path(path: &str) -> String { - let normalized = path.replace('\\', "/"); - let trimmed = normalized.trim(); - if trimmed.is_empty() { - ".".to_string() - } else { - trimmed.trim_start_matches("./").to_string() - } -} - -fn validate_plan_target_path(path: &str) -> Result { - let normalized = normalize_path(path); - if normalized == "." || normalized.is_empty() { - return Err(anyhow!("derived plan target path cannot be empty")); - } - if normalized.starts_with('/') - || normalized.contains(':') - || normalized - .split('/') - .any(|part| part == ".." || part.is_empty()) - { - return Err(anyhow!( - "derived plan target path {normalized:?} must be a clean repo-relative path" - )); - } - Ok(normalized) -} - -fn validate_markdown_target_path(path: &str) -> Result { - let normalized = validate_plan_target_path(path)?; - if !normalized - .rsplit('/') - .next() - .unwrap_or_default() - .ends_with(".md") - { - return Err(anyhow!( - "managed section target path {normalized:?} must be a markdown file" - )); - } - Ok(normalized) -} - -fn validate_toml_target_path(path: &str) -> Result { - let normalized = validate_plan_target_path(path)?; - if !normalized - .rsplit('/') - .next() - .unwrap_or_default() - .ends_with(".toml") - { - return Err(anyhow!( - "task card target path {normalized:?} must be a TOML file" - )); - } - Ok(normalized) -} - -fn normalize_action_family(value: &str) -> Result { - let normalized = value.trim().to_ascii_lowercase().replace('_', "-"); - if normalized.is_empty() { - return Err(anyhow!("derive-plan action family cannot be empty")); - } - Ok(normalized) -} - -fn compact_line(text: &str) -> String { - let compact = text - .split_whitespace() - .collect::>() - .join(" ") - .trim() - .to_string(); - let mut chars = compact.chars(); - let truncated = chars.by_ref().take(240).collect::(); - if chars.next().is_some() { - format!("{truncated}...") - } else { - compact - } -} - -fn compact_multiline(text: &str) -> Vec { - text.lines() - .map(compact_line) - .filter(|line| !line.is_empty()) - .take(40) - .collect() -} - -fn compact_join(values: &[String]) -> String { - if values.is_empty() { - "none".to_string() - } else { - values - .iter() - .map(|value| compact_line(value)) - .collect::>() - .join(", ") - } -} - -fn sorted_normalized_paths(paths: Vec) -> Vec { - let mut normalized = normalize_paths(paths) - .into_iter() - .filter(|path| path != ".") - .collect::>(); - normalized.sort(); - normalized.dedup(); - normalized -} - -fn strict_repo_work_paths(paths: Vec) -> Result> { - let original_count = paths.len(); - let normalized = sorted_normalized_paths(paths); - if normalized.len() != original_count - || normalized.iter().any(|path| { - Path::new(path).is_absolute() - || Path::new(path) - .components() - .any(|part| matches!(part, std::path::Component::ParentDir)) - }) - { - return Err(anyhow!( - "repo-work paths must be non-empty, unique, normalized relative paths without traversal" - )); - } - Ok(normalized) -} - -fn powershell_single_quoted(value: &str) -> String { - format!("'{}'", value.replace('\'', "''")) -} - -fn powershell_append_lines_command(target_path: &str, lines: &[String]) -> String { - let mut commands = vec![ - format!("$p = {}", powershell_single_quoted(target_path)), - "$d = Split-Path -Parent $p".to_string(), - "if ($d) { New-Item -ItemType Directory -Force -Path $d | Out-Null }".to_string(), - ]; - commands.extend(lines.iter().map(|line| { - format!( - "Add-Content -LiteralPath $p -Value {}", - powershell_single_quoted(line) - ) - })); - commands.join("; ") -} - -fn powershell_set_lines_command(target_path: &str, lines: &[String]) -> String { - let mut commands = vec![ - format!("$p = {}", powershell_single_quoted(target_path)), - "$d = Split-Path -Parent $p".to_string(), - "if ($d) { New-Item -ItemType Directory -Force -Path $d | Out-Null }".to_string(), - "$lines = @()".to_string(), - ]; - commands.extend( - lines - .iter() - .map(|line| format!("$lines += {}", powershell_single_quoted(line))), - ); - commands.push("Set-Content -LiteralPath $p -Value $lines".to_string()); - commands.join("; ") -} - -fn toml_basic_string(value: &str) -> String { - format!( - "\"{}\"", - value - .replace('\\', "\\\\") - .replace('"', "\\\"") - .replace('\n', "\\n") - .replace('\r', "\\r") - .replace('\t', "\\t") - ) -} - -fn toml_array(values: &[String]) -> String { - let entries = values - .iter() - .map(|value| toml_basic_string(&compact_line(value))) - .collect::>() - .join(", "); - format!("[{entries}]") -} - -fn powershell_replace_managed_section_command( - target_path: &str, - start_marker: &str, - end_marker: &str, - lines: &[String], -) -> String { - let section = lines.join("\n"); - [ - format!("$p = {}", powershell_single_quoted(target_path)), - "$d = Split-Path -Parent $p".to_string(), - "if ($d) { New-Item -ItemType Directory -Force -Path $d | Out-Null }".to_string(), - format!("$start = {}", powershell_single_quoted(start_marker)), - format!("$end = {}", powershell_single_quoted(end_marker)), - format!("$section = {}", powershell_single_quoted(§ion)), - "if (Test-Path -LiteralPath $p) { $content = Get-Content -LiteralPath $p -Raw } else { $content = '' }".to_string(), - "$pattern = '(?s)' + [regex]::Escape($start) + '.*?' + [regex]::Escape($end)" - .to_string(), - "if ($content -match $pattern) { $content = [regex]::Replace($content, $pattern, $section.Replace('$', '$$')) } elseif ($content.Trim().Length -gt 0) { $content = $content.TrimEnd() + [Environment]::NewLine + [Environment]::NewLine + $section } else { $content = $section }".to_string(), - "Set-Content -LiteralPath $p -Value $content".to_string(), - ] - .join("; ") -} - -fn normalize_path_for_receipt(path: &Path) -> String { - path.display().to_string().replace('\\', "/") -} - -fn git_output(workspace: &Path, args: &[&str]) -> Result { - let output = Command::new("git") - .arg("-C") - .arg(workspace) - .args(args) - .output() - .with_context(|| format!("failed to run git {}", args.join(" ")))?; - if !output.status.success() { - return Err(anyhow!( - "git {} failed: {}", - args.join(" "), - String::from_utf8_lossy(&output.stderr) - )); - } - Ok(String::from_utf8_lossy(&output.stdout).trim().to_string()) -} - -fn git_add_paths(workspace: &Path, paths: &[String]) -> Result<()> { - let mut command = Command::new("git"); - command.arg("-C").arg(workspace).arg("add").arg("--"); - for path in paths { - command.arg(path); - } - let output = command - .output() - .with_context(|| format!("failed to run git add in {}", workspace.display()))?; - if output.status.success() { - Ok(()) - } else { - Err(anyhow!( - "git add failed: {}", - String::from_utf8_lossy(&output.stderr) - )) - } -} - -fn ensure_staged_changes(workspace: &Path) -> Result<()> { - let output = Command::new("git") - .arg("-C") - .arg(workspace) - .args(["diff", "--cached", "--quiet"]) - .output() - .with_context(|| format!("failed to inspect staged diff in {}", workspace.display()))?; - if output.status.success() { - Err(anyhow!( - "execute staged no changed paths; refusing empty commit" - )) - } else { - Ok(()) - } -} - -fn git_commit(workspace: &Path, message: &str) -> Result<()> { - let output = Command::new("git") - .arg("-C") - .arg(workspace) - .args(["commit", "-m", message]) - .output() - .with_context(|| format!("failed to run git commit in {}", workspace.display()))?; - if output.status.success() { - Ok(()) - } else { - Err(anyhow!( - "git commit failed: {}", - String::from_utf8_lossy(&output.stderr) - )) - } -} - -fn cargo_json(manifest_path: &Path, bin_name: &str, args: &[String]) -> Result { - let output = Command::new("cargo") - .arg("run") - .arg("--quiet") - .arg("--manifest-path") - .arg(manifest_path) - .arg("--bin") - .arg(bin_name) - .arg("--") - .args(args) - .output() - .with_context(|| format!("failed to spawn cargo run --bin {bin_name}"))?; - if !output.status.success() { - return Err(anyhow!( - "cargo run --bin {bin_name} failed:\n{}", - String::from_utf8_lossy(&output.stderr) - )); - } - serde_json::from_slice(&output.stdout) - .with_context(|| format!("{bin_name} returned invalid JSON")) -} - -fn path_from_json(value: &Value, path: &[&str]) -> Option { - let mut cursor = value; - for segment in path { - cursor = cursor.get(*segment)?; - } - cursor.as_str().map(PathBuf::from) -} - -fn string_from_json(value: &Value, path: &[&str]) -> Option { - let mut cursor = value; - for segment in path { - cursor = cursor.get(*segment)?; - } - cursor.as_str().map(ToString::to_string) -} - -fn bool_from_json(value: &Value, path: &[&str]) -> Option { - let mut cursor = value; - for segment in path { - cursor = cursor.get(*segment)?; - } - cursor.as_bool() -} - -fn string_array_from_json(value: &Value, path: &[&str]) -> Vec { - let mut cursor = value; - for segment in path { - let Some(next) = cursor.get(*segment) else { - return Vec::new(); - }; - cursor = next; - } - cursor - .as_array() - .map(|items| { - items - .iter() - .filter_map(Value::as_str) - .map(ToString::to_string) - .collect() - }) - .unwrap_or_default() -} - -fn first_plan_action(plan: &Value) -> Option<&Value> { - plan.get("actions")?.as_array()?.first() -} - -fn string_from_value(value: &Value, field: &str) -> Option { - value.get(field)?.as_str().map(ToString::to_string) -} - -fn string_array_field(value: &Value, field: &str) -> Vec { - value - .get(field) - .and_then(Value::as_array) - .map(|items| { - items - .iter() - .filter_map(Value::as_str) - .map(ToString::to_string) - .collect() - }) - .unwrap_or_default() -} - -fn default_if_empty(values: Vec, defaults: Vec) -> Vec { - if values.is_empty() { defaults } else { values } -} - -#[cfg(test)] -mod authority_tests { - use super::*; - use epiphany_core::REPO_WORK_MODELING_FINDING_SCHEMA_VERSION; - use epiphany_core::RepoWorkModelingFinding; - use epiphany_core::put_repo_work_modeling_finding; - use tempfile::tempdir; - - fn deployment_config_fixture() -> String { - r#" -schema_version = "epiphany.repo_deployment_config.v0" -safe_action_family = "repo.deployment_config" -summary = "test summary" -private_state_exposed = false - -[deployment] -enabled = false -owner = "Idunn" -trigger = "git-push-observed-by-idunn" -watched_ref = "refs/heads/main" -deployment_script_ref = "deploy/idunn-deploy.ps1" -deployment_script_hash_required = true -deployment_script_review_required = true -host_access_policy_ref_required = true -secret_values_embedded = false -rollback_plan_ref_required = true -aftercare_checks_required = true -idunn_receipt_required = true -aftercare_audit_required = true - -[cultmesh] -local_verse = "gamecult-local" -capability_family = "gamecult.idunn.deployment" -intent_contract = "gamecult.idunn.deployment_intent.v0" -receipt_contract = "gamecult.idunn.deployment_receipt.v0" -aftercare_contract = "gamecult.idunn.deployment_aftercare_audit.v0" -daemon_owns_execution = true - -[required_receipts] -mind_adoption = "epiphany.repo_work_plan_adoption_review.v0" -soul_review = "epiphany.repo_work_closure_review.v0" -maintainer_review = "gamecult.maintainer.review_receipt.v0" -secret_policy = "epiphany.repo_secret_policy_request.v0" -idunn_deployment = "gamecult.idunn.deployment_receipt.v0" -aftercare_audit = "gamecult.idunn.deployment_aftercare_audit.v0" - -[authority] -configuration_only = true -direct_deployment_authority = false -direct_ssh_authority = false -direct_git_push_authority = false -direct_service_lifecycle_authority = false -direct_hands_authority = false -publication_authorized = false -merge_authorized = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -idunn_deployment_authority_required = true -"# - .to_string() - } - - #[test] - fn deployment_config_uses_typed_toml_not_comment_resemblance() { - let valid = parse_repo_deployment_config(&deployment_config_fixture()).unwrap(); - assert_eq!(valid.deployment.watched_ref, "refs/heads/main"); - assert!(!valid.authority.direct_git_push_authority); - - let counterfeit = deployment_config_fixture().replace( - "direct_git_push_authority = false", - "# direct_git_push_authority = false\ndirect_git_push_authority = true", - ); - let parsed = parse_repo_deployment_config(&counterfeit).unwrap(); - assert!(parsed.authority.direct_git_push_authority); - assert!(!parsed.has_authority_seals()); - - let missing_typed_field = deployment_config_fixture().replace( - "watched_ref = \"refs/heads/main\"\n", - "# watched_ref = \"refs/heads/main\"\n", - ); - assert!(parse_repo_deployment_config(&missing_typed_field).is_err()); - } - - fn idunn_deployment_fixture() -> EpiphanyCultMeshIdunnDeploymentReceiptEntry { - EpiphanyCultMeshIdunnDeploymentReceiptEntry { - schema_version: "gamecult.idunn.deployment_receipt.v0".to_string(), - receipt_id: "deployment-1".to_string(), - runtime_id: "repo-swarm-local".to_string(), - verse_id: EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID.to_string(), - status: "deployed".to_string(), - trigger: "git-push".to_string(), - watched_ref: "refs/heads/main".to_string(), - source_commit: "abc123".to_string(), - result_ref: "deploy/result/abc123".to_string(), - result_summary: "deployed".to_string(), - private_state_exposed: false, - notes: vec![], - } - } - - fn idunn_aftercare_fixture() -> EpiphanyCultMeshIdunnAftercareAuditReceiptEntry { - EpiphanyCultMeshIdunnAftercareAuditReceiptEntry { - schema_version: "gamecult.idunn.deployment_aftercare_audit.v0".to_string(), - receipt_id: "aftercare-1".to_string(), - runtime_id: "repo-swarm-local".to_string(), - verse_id: EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID.to_string(), - status: "complete".to_string(), - checked_ref: "deploy/result/abc123".to_string(), - deployment_receipt_id: "deployment-1".to_string(), - audit_ref: "audit/abc123".to_string(), - result_summary: "healthy".to_string(), - private_state_exposed: false, - notes: vec![], - } - } - - #[test] - fn deployment_aftercare_rejects_raw_response_files_and_cached_projection() { - for forbidden in ["--idunn-deployment-receipt", "--aftercare-audit-receipt"] { - assert!( - parse_deployment_aftercare_audit_args( - [ - "--workspace".to_string(), - ".".to_string(), - forbidden.to_string(), - "minimal-three-field-blob.json".to_string(), - ] - .into_iter() - ) - .is_err() - ); - } - assert!( - parse_readiness_args( - [ - "--workspace".to_string(), - ".".to_string(), - "--deployment-aftercare-audit-receipt".to_string(), - "cached-projection.json".to_string(), - ] - .into_iter() - ) - .is_err() - ); - } - - #[test] - fn deployment_aftercare_requires_the_conjunctively_bound_idunn_chain() { - let deployment = idunn_deployment_fixture(); - let aftercare = idunn_aftercare_fixture(); - let valid = - |deployment: &EpiphanyCultMeshIdunnDeploymentReceiptEntry, - aftercare: &EpiphanyCultMeshIdunnAftercareAuditReceiptEntry| { - idunn_deployment_aftercare_chain_valid( - deployment, - aftercare, - "repo-swarm-local", - "abc123", - Some("refs/heads/main"), - Some("abc123"), - ) - }; - assert!(valid(&deployment, &aftercare)); - - let mut forged = aftercare.clone(); - forged.deployment_receipt_id = "other-deployment".to_string(); - assert!(!valid(&deployment, &forged)); - forged = aftercare.clone(); - forged.checked_ref = "other-result".to_string(); - assert!(!valid(&deployment, &forged)); - forged = aftercare.clone(); - forged.runtime_id = "other-runtime".to_string(); - assert!(!valid(&deployment, &forged)); - forged = aftercare.clone(); - forged.verse_id = "other-verse".to_string(); - assert!(!valid(&deployment, &forged)); - - let mut forged_deployment = deployment.clone(); - forged_deployment.source_commit = "other-commit".to_string(); - assert!(!valid(&forged_deployment, &aftercare)); - forged_deployment = deployment.clone(); - forged_deployment.watched_ref = "refs/heads/other".to_string(); - assert!(!valid(&forged_deployment, &aftercare)); - forged_deployment = deployment.clone(); - forged_deployment.status = "complete".to_string(); - assert!(!valid(&forged_deployment, &aftercare)); - forged_deployment = deployment.clone(); - forged_deployment.receipt_id.clear(); - assert!(!valid(&forged_deployment, &aftercare)); - forged_deployment = deployment.clone(); - forged_deployment.result_ref.clear(); - assert!(!valid(&forged_deployment, &aftercare)); - - forged = aftercare.clone(); - forged.status = "passed".to_string(); - assert!(!valid(&deployment, &forged)); - forged = aftercare.clone(); - forged.receipt_id.clear(); - assert!(!valid(&deployment, &forged)); - forged = aftercare.clone(); - forged.audit_ref.clear(); - assert!(!valid(&deployment, &forged)); - } - - #[test] - fn deployment_closure_uses_the_typed_config_model() { - let source = include_str!("epiphany-work.rs"); - let start = source - .find("\"repo.deployment_config\" => {") - .expect("deployment closure branch"); - let end = source[start..] - .find("\n _ => {") - .map(|offset| start + offset) - .expect("end of deployment closure branch"); - let branch = &source[start..end]; - assert!(branch.contains("parse_repo_deployment_config")); - assert!(branch.contains("has_authority_seals")); - assert!(!branch.contains("content.contains")); - } - - fn secret_policy_fixture() -> String { - r#" -schema_version = "epiphany.repo_secret_policy_request.v0" -safe_action_family = "repo.secret_policy_request" -summary = "test summary" -private_state_exposed = false - -[request] -status = "awaiting-security-review" -routing_owner = "Self" -required_reviewers = ["Maintainer", "Soul", "Mind", "Bifrost"] -policy_admission_owner = "Mind" -requested_effect = "review-repo-secret-and-write-permission-policy" -requires_secret_inventory_without_values = true -requires_write_permission_scope = true -requires_public_private_export_boundary = true - -[antecedents] -source_grounding_required = true -soul_review_required = true -mind_adoption_required = true -maintainer_review_required = true -bifrost_publication_review_required = true - -[required_receipts] -source_grounding = "epiphany.eyes.evidence_packet" -soul_review = "epiphany.repo_work_closure_review.v0" -mind_adoption = "epiphany.repo_work_plan_adoption_review.v0" -maintainer_review = "gamecult.maintainer.review_receipt.v0" -bifrost_publication_review = "gamecult.bifrost.publication_review_receipt.v0" - -[security_packet] -requires_secret_locations_without_values = true -requires_credential_owner = true -requires_write_scope_matrix = true -requires_public_export_redaction_rules = true -requires_deployment_authority_owner = true -requires_incident_rollback_plan = true - -[authority] -direct_secret_access_authority = false -secret_value_materialization = false -write_permission_authority = false -deployment_authority = false -publication_authorized = false -merge_authorized = false -service_lifecycle_authority = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -maintainer_security_review_required = true -soul_security_verification_required = true -mind_policy_admission_required = true -bifrost_publication_review_required = true -"# - .to_string() - } - - #[test] - fn secret_policy_closure_refuses_comment_authority_seals() { - let valid = parse_repo_secret_policy_request(&secret_policy_fixture()).unwrap(); - assert!(valid.has_authority_seals()); - - let counterfeit = secret_policy_fixture().replace( - "direct_secret_access_authority = false", - "# direct_secret_access_authority = false\ndirect_secret_access_authority = true", - ); - let parsed = parse_repo_secret_policy_request(&counterfeit).unwrap(); - assert!(parsed.authority.direct_secret_access_authority); - assert!(!parsed.has_authority_seals()); - - let source = include_str!("epiphany-work.rs"); - let start = source - .find("\"repo.secret_policy_request\" => {") - .expect("secret policy closure branch"); - let end = source[start..] - .find("\n \"repo.dependency_policy_request\" => {") - .map(|offset| start + offset) - .expect("end of secret policy closure branch"); - let branch = &source[start..end]; - assert!(branch.contains("parse_repo_secret_policy_request")); - assert!(!branch.contains("content.contains")); - } - - fn dependency_policy_fixture() -> String { - r#" -schema_version = "epiphany.repo_dependency_policy_request.v0" -safe_action_family = "repo.dependency_policy_request" -summary = "test summary" -private_state_exposed = false -[request] -status = "awaiting-dependency-policy-review" -routing_owner = "Self" -required_reviewers = ["Maintainer", "Soul", "Mind", "Bifrost"] -policy_admission_owner = "Mind" -requested_effect = "review-repo-dependency-and-supply-chain-policy" -requires_manifest_inventory = true -requires_lockfile_policy = true -requires_package_manager_command_review = true -requires_network_fetch_policy = true -requires_vulnerability_review = true -requires_license_review = true -requires_rollback_plan = true -[antecedents] -source_grounding_required = true -eyes_evidence_required = true -soul_review_required = true -mind_adoption_required = true -maintainer_review_required = true -bifrost_publication_review_required = true -[required_receipts] -source_grounding = "epiphany.eyes.evidence_packet" -soul_review = "epiphany.repo_work_closure_review.v0" -mind_adoption = "epiphany.repo_work_plan_adoption_review.v0" -maintainer_review = "gamecult.maintainer.review_receipt.v0" -bifrost_publication_review = "gamecult.bifrost.publication_review_receipt.v0" -dependency_audit = "gamecult.supply_chain.dependency_audit_receipt.v0" -[dependency_packet] -requires_manifest_paths = true -requires_lockfile_paths = true -requires_package_manager_commands = true -requires_vulnerability_sources = true -requires_license_constraints = true -requires_vendored_code_policy = true -requires_update_cadence = true -requires_private_state_redaction_check = true -[authority] -direct_dependency_update_authority = false -direct_package_install_authority = false -direct_lockfile_mutation_authority = false -direct_network_fetch_authority = false -direct_ci_mutation_authority = false -direct_hands_authority = false -publication_authorized = false -merge_authorized = false -deployment_authority = false -service_lifecycle_authority = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -maintainer_dependency_review_required = true -soul_dependency_verification_required = true -mind_policy_admission_required = true -bifrost_publication_review_required = true -supply_chain_audit_required = true -"# - .to_string() - } - - #[test] - fn dependency_policy_closure_refuses_comment_authority_seals() { - let valid = parse_repo_dependency_policy_request(&dependency_policy_fixture()).unwrap(); - assert!(valid.has_authority_seals()); - let counterfeit = dependency_policy_fixture().replace( - "direct_package_install_authority = false", - "# direct_package_install_authority = false\ndirect_package_install_authority = true", - ); - let parsed = parse_repo_dependency_policy_request(&counterfeit).unwrap(); - assert!(parsed.authority.direct_package_install_authority); - assert!(!parsed.has_authority_seals()); - - let source = include_str!("epiphany-work.rs"); - let start = source - .find("\"repo.dependency_policy_request\" => {") - .expect("dependency policy closure branch"); - let end = source[start..] - .find("\n \"repo.deployment_request\" => {") - .map(|offset| start + offset) - .expect("end of dependency policy closure branch"); - let branch = &source[start..end]; - assert!(branch.contains("parse_repo_dependency_policy_request")); - assert!(!branch.contains("content.contains")); - } - - fn deployment_request_fixture() -> String { - r#" -schema_version = "epiphany.repo_deployment_request.v0" -safe_action_family = "repo.deployment_request" -summary = "test summary" -private_state_exposed = false -[request] -status = "awaiting-idunn-review" -routing_owner = "Self" -required_reviewers = ["Maintainer", "Soul", "Mind", "Bifrost"] -execution_owner = "Idunn" -requested_effect = "review-repo-deployment-trigger-and-script" -deployment_trigger = "git-push-observed-by-idunn" -requires_explicit_deployment_policy = true -requires_idunn_receipt = true -requires_aftercare_audit = true -[antecedents] -source_grounding_required = true -mind_adoption_required = true -soul_review_required = true -maintainer_review_required = true -secret_policy_review_required = true -bifrost_publication_review_required = true -[required_receipts] -source_grounding = "epiphany.eyes.evidence_packet" -mind_adoption = "epiphany.repo_work_plan_adoption_review.v0" -soul_review = "epiphany.repo_work_closure_review.v0" -maintainer_review = "gamecult.maintainer.review_receipt.v0" -secret_policy = "epiphany.repo_secret_policy_request.v0" -bifrost_publication_review = "gamecult.bifrost.publication_review_receipt.v0" -idunn_deployment = "gamecult.idunn.deployment_receipt.v0" -aftercare_audit = "gamecult.idunn.deployment_aftercare_audit.v0" -[deployment_packet] -requires_target_environment = true -requires_watched_ref = true -requires_source_commit_sha = true -requires_deployment_script_ref = true -requires_script_hash = true -requires_script_review_ref = true -requires_host_access_policy_ref = true -requires_secret_policy_ref = true -requires_rollback_plan = true -requires_aftercare_checks = true -[authority] -direct_deployment_authority = false -direct_ssh_authority = false -direct_git_push_authority = false -direct_service_lifecycle_authority = false -direct_hands_authority = false -publication_authorized = false -merge_authorized = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -idunn_deployment_authority_required = true -"# - .to_string() - } - - #[test] - fn deployment_request_closure_refuses_comment_authority_seals() { - let valid = parse_repo_deployment_request(&deployment_request_fixture()).unwrap(); - assert!(valid.has_authority_seals()); - let counterfeit = deployment_request_fixture().replace( - "direct_ssh_authority = false", - "# direct_ssh_authority = false\ndirect_ssh_authority = true", - ); - let parsed = parse_repo_deployment_request(&counterfeit).unwrap(); - assert!(parsed.authority.direct_ssh_authority); - assert!(!parsed.has_authority_seals()); - - let source = include_str!("epiphany-work.rs"); - let start = source - .find("\"repo.deployment_request\" => {") - .expect("deployment request closure branch"); - let end = source[start..] - .find("\n \"repo.deployment_config\" => {") - .map(|offset| start + offset) - .expect("end of deployment request closure branch"); - let branch = &source[start..end]; - assert!(branch.contains("parse_repo_deployment_request")); - assert!(!branch.contains("content.contains")); - } - - #[test] - fn queue_selection_rows_preserve_typed_scheduler_state() { - let overview = EpiphanyCultMeshRepoWorkOverviewEntry { - schema_version: epiphany_core::EPIPHANY_CULTMESH_REPO_WORK_OVERVIEW_SCHEMA_VERSION - .to_string(), - runtime_id: "test".to_string(), - verse_id: "gamecult-local".to_string(), - overview_id: "overview-1".to_string(), - generated_at: "2026-07-13T00:00:00Z".to_string(), - workspace: "E:/test".to_string(), - item: "item-1".to_string(), - branch: "main".to_string(), - current_gate: "ready-to-run".to_string(), - blocker: "none".to_string(), - next_safe_move: "run it".to_string(), - changed_paths: Vec::new(), - commit_sha: "none".to_string(), - soul_verdict: "pending".to_string(), - publication_status: "not-requested".to_string(), - sync_status: "local".to_string(), - receipt_refs: Vec::new(), - tui_rows: vec!["misleading display text".to_string()], - proof_bundle_ref: "none".to_string(), - private_state_exposed: false, - notes: Vec::new(), - }; - let rows = repo_work_queue_selection_rows(&[overview], Path::new("E:/test")); - assert!(rows[0].is_object()); - assert_eq!(rows[0]["item"], "item-1"); - assert_eq!(rows[0]["branch"], "main"); - assert_eq!(rows[0]["gate"], "ready-to-run"); - assert_eq!(rows[0]["actionable"], true); - assert_ne!(rows[0], "misleading display text"); - } - - #[test] - fn close_rejects_caller_authored_verification_and_modeling_authority() -> Result<()> { - for flag in [ - "--closure-model-ref", - "--closure-model-verdict", - "--closure-model-finding", - "--model-authored", - "--modeling-summary", - "--verification-command", - "--require-source-grounding", - "--verification-summary", - "--state-revision", - ] { - let error = parse_close_args([flag.to_string(), "counterfeit".to_string()].into_iter()) - .expect_err("legacy Modeling echo must be refused"); - assert!(error.to_string().contains("unexpected close argument")); - } - Ok(()) - } - - #[test] - fn scheduler_cannot_impersonate_modeling_or_mind() { - let source = include_str!("epiphany-work.rs"); - let tick_start = source.find("fn run_tick").expect("run_tick"); - let tick_end = source[tick_start..] - .find("#[cfg(test)]") - .map(|offset| tick_start + offset) - .unwrap_or(source.len()); - let tick = &source[tick_start..tick_end]; - assert!(tick.contains("run_verify(CloseArgs")); - assert!(tick.contains("run_close(CloseArgs")); - assert!(tick.contains("await-modeling")); - assert!(tick.contains("typed Modeling request")); - assert!(!tick.contains("put_repo_work_modeling_finding")); - assert!(!tick.contains("RepoWorkModelingFinding {")); - assert!(!tick.contains("commit_repo_work_map_admission")); - assert!(tick.find("runtime_repo_work_modeling_finding") < tick.find("run_close(CloseArgs")); - let production = source - .split("#[cfg(test)]") - .next() - .expect("production source before authority tests"); - assert!(!production.contains("put_repo_work_modeling_finding(")); - assert!(!production.contains(".spawn()")); - assert!(production.contains("epiphany-daemon-supervisor")); - assert!(production.contains("\"lifecycleOwner\": \"Idunn\"")); - assert!( - production.find("preflight_command.output()") - < production.find("open_runtime_spine_heartbeat_job(") - ); - assert!(production.contains("schemaPreflightPassed")); - assert!(!source.contains(&["RepoWork", "MapStore"].concat())); - assert!(!source.contains(&["repo-work-map", ".msgpack"].concat())); - } - - #[test] - fn repo_work_routing_cannot_author_mind_adoption_or_approve_hands_directly() { - let source = include_str!("epiphany-work.rs"); - let adopt_start = source.find("fn run_adopt").expect("run_adopt"); - let adopt_end = source[adopt_start..] - .find("\nfn run_execute") - .map(|offset| adopt_start + offset) - .expect("run_execute follows run_adopt"); - let adopt = &source[adopt_start..adopt_end]; - assert!(adopt.contains("runtime_repo_work_plan_adoption_review")); - assert!(adopt.contains("commit_repo_work_hands_grant")); - assert!(!adopt.contains("put_repo_work_plan_adoption_review")); - assert!(!adopt.contains("put_hands_action_review")); - assert!(!adopt.contains("RepoWorkPlanAdoptionReview {")); - assert!(!adopt.contains("mind_interpretation")); - assert!(!adopt.contains("\"owner\": \"Mind\"")); - - let tick_start = source.find("fn run_tick").expect("run_tick"); - let tick_end = source[tick_start..] - .find("\nfn resolve_accept_receipt") - .map(|offset| tick_start + offset) - .expect("receipt helpers follow run_tick"); - let tick = &source[tick_start..tick_end]; - assert!(!tick.contains("run_adopt(")); - assert!(!tick.contains("put_repo_work_plan_adoption_review")); - assert!(!tick.contains("RepoWorkPlanAdoptionReview {")); - } - - #[test] - fn closure_rejects_swapped_valid_adoption_chain() -> Result<()> { - let temp = tempdir()?; - let workspace = temp.path().canonicalize()?; - let plan_path = workspace.join("plan.json"); - write_json(&plan_path, &json!({"plan": true}))?; - let mind = epiphany_core::RepoWorkPlanAdoptionReview { - schema_version: epiphany_core::REPO_WORK_PLAN_ADOPTION_REVIEW_SCHEMA_VERSION.into(), - review_id: "mind-review-a".into(), - decision: RepoWorkPlanAdoptionDecision::Adopt, - workspace_identity: normalize_path_for_receipt(&workspace), - item: "item-a".into(), - plan_schema_version: "epiphany.repo_work_action_plan_receipt.v0".into(), - plan_id: "plan-a".into(), - plan_sha256: "a".repeat(64), - run_receipt_sha256: "b".repeat(64), - plan_receipt_path: normalize_path_for_receipt(&plan_path.canonicalize()?), - run_receipt_path: normalize_path_for_receipt(&workspace.join("run.json")), - hands_intent_id: "intent-a".into(), - queued_hands_review_id: "queued-a".into(), - substrate_grant_receipt_id: "substrate-a".into(), - action_id: "action-a".into(), - action_command: "cargo test --lib".into(), - action_commit_message: "Test adoption".into(), - changed_paths: vec!["src/lib.rs".into()], - reviewed_at: "2026-07-13T00:00:00Z".into(), - private_state_exposed: false, - }; - let grant = RepoWorkHandsGrant { - schema_version: REPO_WORK_HANDS_GRANT_SCHEMA_VERSION.into(), - grant_id: "grant-a".into(), - adoption_review_id: mind.review_id.clone(), - adoption_review_sha256: "c".repeat(64), - workspace_identity: mind.workspace_identity.clone(), - item: mind.item.clone(), - plan_id: mind.plan_id.clone(), - plan_sha256: mind.plan_sha256.clone(), - run_receipt_sha256: mind.run_receipt_sha256.clone(), - plan_receipt_path: mind.plan_receipt_path.clone(), - run_receipt_path: mind.run_receipt_path.clone(), - hands_intent_id: mind.hands_intent_id.clone(), - queued_hands_review_id: mind.queued_hands_review_id.clone(), - approved_hands_review_id: "approved-a".into(), - substrate_grant_receipt_id: mind.substrate_grant_receipt_id.clone(), - action_id: mind.action_id.clone(), - action_command: mind.action_command.clone(), - action_commit_message: mind.action_commit_message.clone(), - allowed_operations: vec!["patch".into(), "command".into(), "commit".into()], - changed_paths: mind.changed_paths.clone(), - granted_at: "2026-07-13T00:00:01Z".into(), - private_state_exposed: false, - }; - let execute = json!({ - "workspace": workspace, - "item": grant.item, - "planReceiptPath": plan_path, - "changedPaths": grant.changed_paths, - "command": grant.action_command, - "adoptionAuthority": { - "mindReviewId": mind.review_id, - "handsGrantId": grant.grant_id, - "planId": grant.plan_id, - "planSha256": grant.plan_sha256, - "runReceiptPath": grant.run_receipt_path, - "runReceiptSha256": grant.run_receipt_sha256, - "actionId": grant.action_id, - "handsIntentId": grant.hands_intent_id, - "approvedHandsReviewId": grant.approved_hands_review_id, - "substrateGrantReceiptId": grant.substrate_grant_receipt_id - } - }); - assert!(execute_receipt_binds_adoption_chain( - &execute, &mind, &grant - )); - let mut unrelated_mind = mind.clone(); - unrelated_mind.review_id = "mind-review-b".into(); - let mut unrelated_grant = grant.clone(); - unrelated_grant.grant_id = "grant-b".into(); - unrelated_grant.adoption_review_id = unrelated_mind.review_id.clone(); - assert!(!execute_receipt_binds_adoption_chain( - &execute, - &unrelated_mind, - &unrelated_grant - )); - Ok(()) - } - - #[test] - fn adopt_cli_rejects_removed_caller_authored_mind_rationale() { - let error = parse_adopt_args( - [ - "--workspace".to_string(), - ".".to_string(), - "--from-plan".to_string(), - "plan.json".to_string(), - "--mind-review-id".to_string(), - "mind-review-1".to_string(), - "--mind-adoption-rationale".to_string(), - "I, the caller, decree adoption.".to_string(), - ] - .into_iter(), - ) - .expect_err("caller-authored Mind rationale must remain deleted"); - assert!(error.to_string().contains("unexpected adopt argument")); - } - - #[test] - fn typed_closure_families_have_no_substring_authority() { - let source = include_str!("epiphany-work.rs"); - for family in [ - "repo.tool_request", - "repo.publication_request", - "repo.sync_request", - "repo.pr_request", - "repo.maintainer_review_request", - "repo.collaboration_policy", - "repo.collaboration_topic", - "repo.consensus_brief", - "repo.interpreter_brief", - "repo.objective_draft", - "repo.adoption_request", - "repo.scheduling_request", - "repo.work_order", - "repo.verification_request", - "repo.credit_request", - "repo.artifact_acceptance_request", - "repo.metrics_request", - "repo.readiness_review_request", - "repo.doctrine_update_request", - "repo.secret_policy_request", - "repo.dependency_policy_request", - "repo.deployment_config", - "repo.deployment_request", - ] { - let marker = format!("\"{family}\" => {{"); - let start = source - .find(&marker) - .unwrap_or_else(|| panic!("missing {family}")); - let remainder = &source[start + marker.len()..]; - let end = remainder.find("\n \"").unwrap_or(remainder.len()); - let branch = &remainder[..end]; - assert!( - !branch.contains("content.contains"), - "{family} closure regained substring authority" - ); - } - } - - #[test] - fn closure_has_no_substring_authority() { - let source = include_str!("epiphany-work.rs"); - let start = source - .find("fn closure_family_assertions(") - .expect("closure start"); - let end = source[start..] - .find("fn push_assertion(") - .map(|offset| start + offset) - .expect("closure end"); - assert!( - !source[start..end].contains("content.contains"), - "closure regained presentation substring authority" - ); - } - - #[test] - fn collaboration_policy_generator_owns_its_proposal_fields() { - let receipt = json!({"feedback": {"candidateActionRefs": [], "publicDiscussionRefs": []}}); - let plan = derive_safe_plan_family(DeriveSafePlanInput { - action_family: "repo-collaboration-policy", - target_path: None, - item: "policy-owner-test", - summary: "proposal", - source: "test", - accept_receipt: &receipt, - model_ref: Some("test-model"), - model_authored: true, - }) - .expect("collaboration policy plan derives"); - assert!(plan.command.contains("[policy]")); - assert!(plan.command.contains("authoring_owner")); - assert!(plan.command.contains("Imagination")); - assert!(plan.command.contains("policy_admitted = false")); - assert!(plan.command.contains("publication_owner")); - assert!(plan.command.contains("Bifrost")); - assert!( - derive_safe_plan_family(DeriveSafePlanInput { - action_family: "repo-manifest", - target_path: None, - item: "deleted-body-diorama", - summary: "deleted", - source: "test", - accept_receipt: &receipt, - model_ref: None, - model_authored: false, - }) - .is_err() - ); - } - - #[test] - fn doctrine_comment_cannot_counterfeit_hands_authority_seal() { - let text = r#" -schema_version = "epiphany.repo_doctrine_update_request.v0" -safe_action_family = "repo.doctrine_update_request" -summary = "summary" -private_state_exposed = false -[request] -status = "awaiting-doctrine-review" -routing_owner = "Self" -required_reviewers = ["Maintainer", "Mind", "Soul"] -doctrine_admission_owner = "Mind" -mutation_owner = "Hands" -requested_effect = "review-repo-agent-doctrine-update" -doctrine_target = "AGENTS.md" -requires_source_grounding = true -maintainer_review_required = true -[antecedents] -[required_receipts] -[doctrine_packet] -[authority] -direct_doctrine_mutation_authority = false -# direct_hands_authority = false -direct_hands_authority = true -"#; - let request = parse_repo_doctrine_update_request(text).expect("fixture is typed TOML"); - assert!(!request.has_authority_seals()); - } - - #[test] - fn modeling_finding_round_trips_and_refuses_private_state() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("runtime.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "modeling-test".to_string(), - display_name: "Modeling Test".to_string(), - created_at: "2026-07-12T00:00:00Z".to_string(), - }, - )?; - put_soul_verdict_receipt( - &store, - &SoulVerdictReceipt { - schema_version: SOUL_VERDICT_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "soul-1".to_string(), - source_result_id: "result-1".to_string(), - source_job_id: "job-1".to_string(), - verdict: "passed".to_string(), - summary: "verified".to_string(), - evidence_ids: Vec::new(), - risks: Vec::new(), - emitted_at: "2026-07-12T00:00:00Z".to_string(), - contract: "test".to_string(), - }, - )?; - let request = RepoWorkModelingRequest { - schema_version: REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION.to_string(), - request_id: "modeling-request-1".to_string(), - item: "item-1".to_string(), - requester: "self".to_string(), - soul_verdict_receipt_id: "soul-1".to_string(), - commit_sha: "abc123".to_string(), - changed_paths: vec!["README.md".to_string()], - instruction: "Model verified consequence.".to_string(), - requested_at: "2026-07-12T00:00:01Z".to_string(), - private_state_exposed: false, - contract: "test".to_string(), - }; - let route = RepoWorkModelingRoute { - schema_version: REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION.to_string(), - route_id: "modeling-route-1".to_string(), - item: request.item.clone(), - generation: 0, - request_id: request.request_id.clone(), - previous_finding_receipt_id: String::new(), - authority_owner: "soul".to_string(), - authority_witness_id: request.soul_verdict_receipt_id.clone(), - updated_at: "2026-07-12T00:00:01Z".to_string(), - private_state_exposed: false, - contract: "test".to_string(), - }; - commit_initial_repo_work_modeling_route(&store, &request, &route)?; - assert_eq!( - runtime_repo_work_modeling_route(&store, &route.route_id)?, - Some(route.clone()) - ); - let mut finding = RepoWorkModelingFinding { - schema_version: REPO_WORK_MODELING_FINDING_SCHEMA_VERSION.to_string(), - receipt_id: "modeling-finding-1".to_string(), - item: "item-1".to_string(), - model_ref: "model-job-1".to_string(), - soul_verdict_receipt_id: "soul-1".to_string(), - verdict: "passed".to_string(), - finding: "Verified consequence updates the repo map.".to_string(), - summary: "Map updated.".to_string(), - changed_paths: vec!["README.md".to_string()], - commit_sha: "abc123".to_string(), - emitted_at: "2026-07-12T00:00:01Z".to_string(), - private_state_exposed: true, - contract: "test".to_string(), - request_id: request.request_id.clone(), - }; - let mut unsolicited_finding = finding.clone(); - unsolicited_finding.receipt_id = "unsolicited-modeling-finding".to_string(); - unsolicited_finding.request_id = "missing-modeling-request".to_string(); - unsolicited_finding.private_state_exposed = false; - assert!(put_repo_work_modeling_finding(&store, &unsolicited_finding).is_err()); - assert!(put_repo_work_modeling_finding(&store, &finding).is_err()); - finding.private_state_exposed = false; - put_repo_work_modeling_finding(&store, &finding)?; - let mut conflicting_finding = finding.clone(); - conflicting_finding.summary = "different meaning".to_string(); - assert!(put_repo_work_modeling_finding(&store, &conflicting_finding).is_err()); - assert_eq!( - runtime_repo_work_modeling_finding(&store, &finding.receipt_id)?, - Some(finding.clone()) - ); - - let review = MindGatewayReview { - schema_version: MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(), - gateway_id: "mind-review-1".to_string(), - source_kind: "repo_work_closure".to_string(), - source_role_id: "modeling".to_string(), - decision: MindGatewayDecision::Accept, - allowed_effects: vec!["repoWork.map".to_string()], - refused_effects: Vec::new(), - reasons: vec!["typed Modeling finding reread".to_string()], - contract: "test".to_string(), - }; - let commit = mind_state_commit_receipt( - "mind-commit-1".to_string(), - &review, - 1, - vec!["repoWork.map".to_string()], - "2026-07-12T00:00:02Z".to_string(), - ); - let mut map = RepoWorkMapEntry { - schema_version: REPO_WORK_MAP_ENTRY_SCHEMA_VERSION.to_string(), - map_entry_id: "repo-work-map-item-1".to_string(), - admitted_at: "2026-07-12T00:00:02Z".to_string(), - item: finding.item.clone(), - branch: "test".to_string(), - changed_paths: finding.changed_paths.clone(), - commit_sha: finding.commit_sha.clone(), - safe_action_family: "repo.status_section".to_string(), - modeling_summary: "counterfeit".to_string(), - modeling_finding_receipt_id: finding.receipt_id.clone(), - soul_verdict_receipt_id: finding.soul_verdict_receipt_id.clone(), - mind_gateway_review_id: review.gateway_id.clone(), - mind_state_commit_receipt_id: commit.receipt_id.clone(), - execute_receipt_path: "execute.json".to_string(), - closure_review_path: "review.json".to_string(), - closure_receipt_path: "close.json".to_string(), - publication_gate: "Bifrost".to_string(), - durable_state_admitted: true, - private_state_exposed: false, - modeling_route_id: route.route_id.clone(), - modeling_generation: route.generation, - }; - assert!(commit_repo_work_map_admission(&store, &map, &review, &commit).is_err()); - assert!(epiphany_core::runtime_mind_gateway_review(&store, &review.gateway_id)?.is_none()); - assert!( - epiphany_core::runtime_mind_state_commit_receipt(&store, &commit.receipt_id)?.is_none() - ); - assert!(runtime_repo_work_map_entry(&store, &map.map_entry_id)?.is_none()); - - map.modeling_summary = finding.summary.clone(); - commit_repo_work_map_admission(&store, &map, &review, &commit)?; - let admitted = runtime_repo_work_map_entry(&store, &map.map_entry_id)?.unwrap(); - assert_eq!(admitted, map); - let mut retry = map.clone(); - retry.admitted_at = "2026-07-12T00:10:00Z".to_string(); - assert_eq!( - commit_repo_work_map_admission(&store, &retry, &review, &commit)?, - admitted - ); - retry.safe_action_family = "repo.task_card".to_string(); - assert!(commit_repo_work_map_admission(&store, &retry, &review, &commit).is_err()); - assert_eq!( - runtime_repo_work_map_entry(&store, &map.map_entry_id)?, - Some(map) - ); - Ok(()) - } - - #[test] - fn modeling_route_generation_requires_mind_and_preserves_previous() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("runtime.cc"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "modeling-route-test".to_string(), - display_name: "Modeling Route Test".to_string(), - created_at: "2026-07-12T00:00:00Z".to_string(), - }, - )?; - let soul = SoulVerdictReceipt { - schema_version: SOUL_VERDICT_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "route-soul-1".to_string(), - source_result_id: "result-1".to_string(), - source_job_id: "job-1".to_string(), - verdict: "passed".to_string(), - summary: "verified".to_string(), - evidence_ids: Vec::new(), - risks: Vec::new(), - emitted_at: "2026-07-12T00:00:00Z".to_string(), - contract: "test".to_string(), - }; - put_soul_verdict_receipt(&store, &soul)?; - let request0 = RepoWorkModelingRequest { - schema_version: REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION.to_string(), - request_id: "route-request-g0".to_string(), - item: "route-item".to_string(), - requester: "self".to_string(), - soul_verdict_receipt_id: soul.receipt_id.clone(), - commit_sha: "abc123".to_string(), - changed_paths: vec!["README.md".to_string()], - instruction: "Model consequence.".to_string(), - requested_at: "2026-07-12T00:00:01Z".to_string(), - private_state_exposed: false, - contract: "test".to_string(), - }; - let route0 = RepoWorkModelingRoute { - schema_version: REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION.to_string(), - route_id: "route-item-current".to_string(), - item: request0.item.clone(), - generation: 0, - request_id: request0.request_id.clone(), - previous_finding_receipt_id: String::new(), - authority_owner: "soul".to_string(), - authority_witness_id: soul.receipt_id.clone(), - updated_at: "2026-07-12T00:00:01Z".to_string(), - private_state_exposed: false, - contract: "test".to_string(), - }; - commit_initial_repo_work_modeling_route(&store, &request0, &route0)?; - let finding0 = RepoWorkModelingFinding { - schema_version: REPO_WORK_MODELING_FINDING_SCHEMA_VERSION.to_string(), - receipt_id: "route-request-g0-finding".to_string(), - item: request0.item.clone(), - model_ref: "model-1".to_string(), - soul_verdict_receipt_id: soul.receipt_id.clone(), - verdict: "needs-work".to_string(), - finding: "Need the verified diff.".to_string(), - summary: "Context incomplete.".to_string(), - changed_paths: request0.changed_paths.clone(), - commit_sha: request0.commit_sha.clone(), - emitted_at: "2026-07-12T00:00:02Z".to_string(), - private_state_exposed: false, - contract: "test".to_string(), - request_id: request0.request_id.clone(), - }; - put_repo_work_modeling_finding(&store, &finding0)?; - let stale_map_review = MindGatewayReview { - schema_version: MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(), - gateway_id: "stale-map-review".to_string(), - source_kind: "repo_work_closure".to_string(), - source_role_id: "modeling".to_string(), - decision: MindGatewayDecision::Accept, - allowed_effects: vec!["repoWork.map".to_string()], - refused_effects: Vec::new(), - reasons: vec!["attempt stale admission".to_string()], - contract: "test".to_string(), - }; - let stale_map_commit = mind_state_commit_receipt( - "stale-map-commit".to_string(), - &stale_map_review, - 1, - vec!["repoWork.map".to_string()], - "2026-07-12T00:00:02Z".to_string(), - ); - let stale_map = RepoWorkMapEntry { - schema_version: REPO_WORK_MAP_ENTRY_SCHEMA_VERSION.to_string(), - map_entry_id: "stale-map".to_string(), - admitted_at: "2026-07-12T00:00:02Z".to_string(), - item: request0.item.clone(), - branch: "test".to_string(), - changed_paths: request0.changed_paths.clone(), - commit_sha: request0.commit_sha.clone(), - safe_action_family: "repo.status_section".to_string(), - modeling_summary: finding0.summary.clone(), - modeling_finding_receipt_id: finding0.receipt_id.clone(), - soul_verdict_receipt_id: soul.receipt_id.clone(), - mind_gateway_review_id: stale_map_review.gateway_id.clone(), - mind_state_commit_receipt_id: stale_map_commit.receipt_id.clone(), - execute_receipt_path: "execute.json".to_string(), - closure_review_path: "review.json".to_string(), - closure_receipt_path: "close.json".to_string(), - publication_gate: "Bifrost".to_string(), - durable_state_admitted: true, - private_state_exposed: false, - modeling_route_id: route0.route_id.clone(), - modeling_generation: 0, - }; - assert!( - commit_repo_work_map_admission( - &store, - &stale_map, - &stale_map_review, - &stale_map_commit, - ) - .is_err() - ); - let review = MindGatewayReview { - schema_version: MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(), - gateway_id: "route-g1-mind-review".to_string(), - source_kind: "repo_work_modeling_revision".to_string(), - source_role_id: "mind".to_string(), - decision: MindGatewayDecision::Accept, - allowed_effects: vec!["repoWork.modelingRoute".to_string()], - refused_effects: vec!["repoWork.map".to_string()], - reasons: vec!["Reviewed missing context.".to_string()], - contract: "test".to_string(), - }; - let request1 = RepoWorkModelingRequest { - request_id: "route-request-g1".to_string(), - requester: "mind".to_string(), - instruction: "Re-model with reviewed context.".to_string(), - requested_at: "2026-07-12T00:00:03Z".to_string(), - ..request0.clone() - }; - let route1 = RepoWorkModelingRoute { - generation: 1, - request_id: request1.request_id.clone(), - previous_finding_receipt_id: finding0.receipt_id.clone(), - authority_owner: "mind".to_string(), - authority_witness_id: review.gateway_id.clone(), - updated_at: "2026-07-12T00:00:03Z".to_string(), - contract: "test generation one".to_string(), - ..route0.clone() - }; - advance_repo_work_modeling_route(&store, &request1, &route1, &review)?; - assert_eq!( - runtime_repo_work_modeling_route(&store, &route0.route_id)?, - Some(route1.clone()) - ); - assert_eq!( - runtime_repo_work_modeling_request(&store, &request0.request_id)?, - Some(request0) - ); - assert_eq!( - runtime_repo_work_modeling_finding(&store, &finding0.receipt_id)?, - Some(finding0) - ); - assert!(advance_repo_work_modeling_route(&store, &request1, &route1, &review).is_err()); - Ok(()) - } - - #[test] - fn public_revision_mouth_routes_scheduler_to_generation_one() -> Result<()> { - let temp = tempfile::tempdir()?; - let workspace = temp.path().join("repo"); - fs::create_dir_all(&workspace)?; - let git = Command::new("git") - .arg("init") - .arg("--quiet") - .arg(&workspace) - .status()?; - assert!(git.success()); - for args in [ - [ - "-C", - workspace.to_str().unwrap(), - "config", - "user.name", - "Epiphany Smoke", - ], - [ - "-C", - workspace.to_str().unwrap(), - "config", - "user.email", - "smoke@epiphany.invalid", - ], - ] { - assert!(Command::new("git").args(args).status()?.success()); - } - fs::write(workspace.join("README.md"), "# Process retry smoke\n")?; - assert!( - Command::new("git") - .args(["-C", workspace.to_str().unwrap(), "add", "README.md"]) - .status()? - .success() - ); - assert!( - Command::new("git") - .args([ - "-C", - workspace.to_str().unwrap(), - "commit", - "--quiet", - "-m", - "Seed process retry smoke", - ]) - .status()? - .success() - ); - let commit_sha = git_output(&workspace, &["rev-parse", "HEAD"])? - .trim() - .to_string(); - let artifact_dir = workspace.join(".epiphany").join("work"); - fs::create_dir_all(&artifact_dir)?; - let store = workspace.join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "process-retry-smoke".to_string(), - display_name: "Process Retry Smoke".to_string(), - created_at: "2026-07-12T00:00:00Z".to_string(), - }, - )?; - let soul = SoulVerdictReceipt { - schema_version: SOUL_VERDICT_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "process-retry-soul".to_string(), - source_result_id: "process-retry-result".to_string(), - source_job_id: "process-retry-job".to_string(), - verdict: "passed".to_string(), - summary: "Verified consequence.".to_string(), - evidence_ids: vec![commit_sha.clone()], - risks: Vec::new(), - emitted_at: "2026-07-12T00:00:00Z".to_string(), - contract: "test".to_string(), - }; - put_soul_verdict_receipt(&store, &soul)?; - let request0 = RepoWorkModelingRequest { - schema_version: REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION.to_string(), - request_id: "repo-work-close-process-retry-modeling-request-g0".to_string(), - item: "process-retry".to_string(), - requester: "self".to_string(), - soul_verdict_receipt_id: soul.receipt_id.clone(), - commit_sha, - changed_paths: vec!["README.md".to_string()], - instruction: "Model generation zero.".to_string(), - requested_at: "2026-07-12T00:00:01Z".to_string(), - private_state_exposed: false, - contract: "test".to_string(), - }; - let route0 = RepoWorkModelingRoute { - schema_version: REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION.to_string(), - route_id: "repo-work-modeling-route-process-retry".to_string(), - item: request0.item.clone(), - generation: 0, - request_id: request0.request_id.clone(), - previous_finding_receipt_id: String::new(), - authority_owner: "soul".to_string(), - authority_witness_id: soul.receipt_id.clone(), - updated_at: "2026-07-12T00:00:01Z".to_string(), - private_state_exposed: false, - contract: "test".to_string(), - }; - commit_initial_repo_work_modeling_route(&store, &request0, &route0)?; - let finding0 = RepoWorkModelingFinding { - schema_version: REPO_WORK_MODELING_FINDING_SCHEMA_VERSION.to_string(), - receipt_id: format!("{}-finding", request0.request_id), - item: request0.item.clone(), - model_ref: "runtime-generation-zero".to_string(), - soul_verdict_receipt_id: soul.receipt_id.clone(), - verdict: "needs-work".to_string(), - finding: "Reviewed context is required.".to_string(), - summary: "Generation zero incomplete.".to_string(), - changed_paths: request0.changed_paths.clone(), - commit_sha: request0.commit_sha.clone(), - emitted_at: "2026-07-12T00:00:02Z".to_string(), - private_state_exposed: false, - contract: "test".to_string(), - request_id: request0.request_id.clone(), - }; - put_repo_work_modeling_finding(&store, &finding0)?; - write_json( - &artifact_dir.join("work-accept-process-retry.json"), - &json!({ - "schemaVersion": "epiphany.repo_work_accept.v0", - "status": "accepted", - "item": "process-retry", - "privateStateExposed": false - }), - )?; - write_json( - &artifact_dir.join("work-close-process-retry.json"), - &json!({ - "schemaVersion": "epiphany.repo_work_closure_receipt.v0", - "status": "awaiting-modeling", - "item": "process-retry", - "runtimeStore": store, - "privateStateExposed": false - }), - )?; - - let revised = run_revise_modeling(ReviseModelingArgs { - workspace: workspace.clone(), - item: "process-retry".to_string(), - runtime_store: Some(store.clone()), - rationale: "The operator reviewed the missing context.".to_string(), - review_ref: "review://process-retry/g1".to_string(), - })?; - assert_eq!(revised["generation"], 1); - assert_eq!( - revised["requestId"], - "repo-work-close-process-retry-modeling-request-g1" - ); - - let tick = run_tick(TickArgs { - workspace: workspace.clone(), - epiphany_root: env::current_dir()?, - item: Some("process-retry".to_string()), - local_verse_store: None, - artifact_dir: Some(artifact_dir), - runtime_store: Some(store.clone()), - cooldown_seconds: 0, - active_timeout_seconds: 900, - dry_run: true, - })?; - let tick_receipt = read_json(Path::new(tick["receiptPath"].as_str().unwrap()))?; - assert_eq!(tick_receipt["action"], "launch-modeling"); - assert_eq!(tick_receipt["advancedResult"]["generation"], 1); - assert_eq!( - tick_receipt["advancedResult"]["requestId"], - "repo-work-close-process-retry-modeling-request-g1" - ); - assert_eq!( - tick_receipt["advancedResult"]["jobId"], - "repo-work-modeling-process-retry-g1" - ); - assert_eq!(tick_receipt["advancedResult"]["preflightRequired"], true); - assert_eq!(tick_receipt["advancedResult"]["lifecycleOwner"], "Idunn"); - assert_eq!( - runtime_repo_work_modeling_route(&store, &route0.route_id)? - .expect("current route") - .generation, - 1 - ); - if env::var_os("EPIPHANY_RUN_LIVE_MODELING_LAUNCH").is_some() { - let live_tick = run_tick(TickArgs { - workspace: workspace.clone(), - epiphany_root: env::current_dir()?, - item: Some("process-retry".to_string()), - local_verse_store: Some(workspace.join(".epiphany").join("local-verse.ccmp")), - artifact_dir: Some(workspace.join(".epiphany").join("work")), - runtime_store: Some(store.clone()), - cooldown_seconds: 0, - active_timeout_seconds: 900, - dry_run: false, - })?; - let live_receipt = read_json(Path::new(live_tick["receiptPath"].as_str().unwrap()))?; - assert_eq!(live_receipt["status"], "modeling-launched"); - assert_eq!(live_receipt["action"], "launch-modeling"); - assert_eq!( - live_receipt["advancedResult"]["requestId"], - tick_receipt["advancedResult"]["requestId"] - ); - assert_eq!( - live_receipt["advancedResult"]["jobId"], - tick_receipt["advancedResult"]["jobId"] - ); - assert_eq!(live_receipt["advancedResult"]["lifecycleOwner"], "Idunn"); - assert_eq!( - live_receipt["advancedResult"]["schemaPreflightPassed"], - true - ); - for field in [ - "lifecycleReceiptId", - "serviceId", - "executableSha256", - "schemaCatalogSha256", - "preflightWitnessId", - ] { - assert!( - live_receipt["advancedResult"][field] - .as_str() - .is_some_and(|value| !value.is_empty()), - "live lifecycle projection omitted {field}" - ); - } - assert_eq!( - live_receipt["advancedResult"]["requiredDocumentTypes"] - .as_array() - .map(Vec::len), - Some(4) - ); - let preserved = temp.keep(); - eprintln!( - "preserved live generation-one fixture at {}", - preserved.display() - ); - } - Ok(()) - } -} - -fn compact_text(text: &str, limit: usize) -> String { - let compact = text.split_whitespace().collect::>().join(" "); - if compact.chars().count() <= limit { - return compact; - } - let mut truncated = compact - .chars() - .take(limit.saturating_sub(3)) - .collect::(); - truncated.push_str("..."); - truncated -} - -fn read_json(path: &Path) -> Result { - let raw = - fs::read_to_string(path).with_context(|| format!("failed to read {}", path.display()))?; - serde_json::from_str(&raw).with_context(|| format!("failed to decode {}", path.display())) -} - -fn file_sha256(path: &Path) -> Result { - let bytes = fs::read(path).with_context(|| format!("failed to hash {}", path.display()))?; - let digest = Sha256::digest(&bytes); - Ok(format!("{digest:x}")) -} - -fn write_json(path: &Path, value: &Value) -> Result<()> { - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; - } - fs::write(path, serde_json::to_vec_pretty(value)?) - .with_context(|| format!("failed to write {}", path.display())) -} - -fn tick_receipt_path(artifact_dir: &Path, item_slug: &str) -> PathBuf { - artifact_dir.join(format!("work-tick-{item_slug}.json")) -} - -fn tick_active_receipt_path(artifact_dir: &Path, item_slug: &str) -> PathBuf { - artifact_dir.join(format!("work-tick-active-{item_slug}.json")) -} - -fn tick_last_completed_receipt_path(artifact_dir: &Path, item_slug: &str) -> PathBuf { - artifact_dir.join(format!("work-tick-last-{item_slug}.json")) -} - -fn scheduler_serve_receipt_path(artifact_dir: &Path, item_slug: &str) -> PathBuf { - artifact_dir.join(format!("work-scheduler-serve-{item_slug}.json")) -} - -fn parse_utc_rfc3339(value: &Value, field: &str) -> Option> { - DateTime::parse_from_rfc3339(value.get(field)?.as_str()?) - .ok() - .map(|timestamp| timestamp.with_timezone(&Utc)) -} - -fn seconds_since(timestamp: DateTime) -> i64 { - Utc::now().signed_duration_since(timestamp).num_seconds() -} - -fn ensure_git_repo(workspace: &Path) -> Result<()> { - let output = Command::new("git") - .arg("-C") - .arg(workspace) - .arg("rev-parse") - .arg("--show-toplevel") - .output() - .with_context(|| format!("failed to run git in {}", workspace.display()))?; - if output.status.success() { - Ok(()) - } else { - Err(anyhow!("{} is not a git repository", workspace.display())) - } -} - -fn take_path(args: &mut impl Iterator, name: &str) -> Result { - Ok(PathBuf::from(take_string(args, name)?)) + Ok(parsed) } -fn take_string(args: &mut impl Iterator, name: &str) -> Result { +fn required_value( + args: &mut std::iter::Peekable>, + flag: &str, +) -> Result { args.next() - .ok_or_else(|| anyhow!("missing value for {name}")) + .filter(|v| !v.starts_with("--")) + .ok_or_else(|| anyhow!("{flag} requires a value")) } -fn take_u64(args: &mut impl Iterator, name: &str) -> Result { - take_string(args, name)? - .parse::() - .with_context(|| format!("invalid integer for {name}")) +fn canonical_frontier_required(operation: &str) -> anyhow::Error { + anyhow!("{operation} is historical-only: {HISTORICAL_REASON}") } -fn sanitize(value: &str) -> String { - let sanitized = value - .chars() - .map(|ch| { - if ch.is_ascii_alphanumeric() { - ch.to_ascii_lowercase() - } else { - '-' - } - }) - .collect::() - .split('-') - .filter(|part| !part.is_empty()) - .collect::>() - .join("-"); - if sanitized.is_empty() { - "work-item".to_string() - } else { - sanitized - } +fn run_overview(args: LegacyArgs) -> Result { + let workspace = args + .workspace + .ok_or_else(|| anyhow!("overview requires --workspace"))?; + Ok(json!({ + "schemaVersion": "epiphany.repo_work_historical_overview.v0", + "status": "historical-only", "reason": HISTORICAL_REASON, + "workspace": workspace, "item": args.item, + "authority": { "durableStateAdmitted": false, "readinessApprovalAuthorized": false, + "publicationAuthorized": false, "serviceLifecycleAuthority": false, "handsActionAuthorized": false }, + "privateStateExposed": false + })) } fn print_usage() { eprintln!( - "usage: epiphany-work ...\n\ - persona-intake --workspace --item --message [--topic ] [--store ] [--runtime-id ]\n\ - accept --workspace --from --item [--summary ] [--topic ] [--store ] [--runtime-id ] [--online-receipt ] [--public-discussion-ref ] [--candidate-action-ref ]\n\ - derive-plan --workspace [--item ] [--accept-receipt ] [--action-family append-worklog|planning-note|checklist-note|section-note|repo-status-section|task-card|repo-tool-request|repo-collaboration-policy|repo-collaboration-topic|repo-consensus-brief|repo-interpreter-brief|repo-objective-draft|repo-adoption-request|repo-scheduling-request|repo-work-order|repo-verification-request|repo-publication-request|repo-sync-request|repo-maintainer-review-request|repo-pr-request|repo-credit-request|repo-artifact-acceptance-request|repo-metrics-request|repo-readiness-review-request|repo-doctrine-update-request|repo-secret-policy-request|repo-dependency-policy-request|repo-deployment-config|repo-deployment-request] [--target-path ] [--model-ref ] [--model-authored] [--action-summary ] [--verification-ask ] [--stop-condition ] [--escalation-reason ] [--assumption ] [--constraint ] [--non-goal ] [--open-question ] [--decision-point ] [--evidence-need ]\n\ - plan --workspace [--item ] --objective --plan-summary --command --changed-path --commit-message [--adoption-evidence-ref ]\n\ - run --workspace [--item ] [--accept-receipt ] [--runtime-store ] [--requested-path ]\n\ - adopt --workspace [--item ] [--run-receipt ] --from-plan --mind-review-id \n\ - execute --workspace [--item ] [--from-plan ] [--command ] [--changed-path ] [--commit-message ]\n\ - close --workspace [--item ] [--execute-receipt ]\n\ - overview --workspace [--item ] [--accept-receipt ] [--no-write]\n\ - readiness --workspace [--item ] [--accept-receipt ] [--public-proof ] [--idunn-lifecycle-receipt ] [--deployment-aftercare-audit-receipt-ref ] [--tool-directory-receipt ] [--no-write]\n\ - deployment-config-audit --workspace [--artifact-dir ] [--no-write]\n\ - deployment-execution-runbook --workspace [--artifact-dir ] [--remote origin] [--no-write]\n\ - deployment-aftercare-audit --workspace [--artifact-dir ] [--local-verse-store ] [--runtime-id ] [--runbook-receipt ] [--idunn-deployment-receipt-ref ] [--aftercare-audit-receipt-ref ] [--no-write]\n\ - export-proof --workspace [--item ] [--accept-receipt ] [--output ] [--local-verse-store ] [--runtime-id repo-swarm-local]\n\ - tick --workspace [--item ] [--local-verse-store ] [--runtime-store ] [--dry-run]\n\ - queue-run --workspace [--local-verse-store ] [--runtime-id repo-swarm-local] [--max-items 1] [--dry-run]" + "usage: epiphany-work [options]\nLegacy mutations are historical-only.\nRead history: epiphany-work overview --workspace [--item ]" ); } + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn mutation_refusal_and_history_are_explicit() -> Result<()> { + assert!( + canonical_frontier_required("plan") + .to_string() + .contains(HISTORICAL_REASON) + ); + let row = run_overview(LegacyArgs { + workspace: Some(PathBuf::from("E:/test")), + item: None, + })?; + assert_eq!(row["status"], "historical-only"); + assert_eq!(row["authority"]["handsActionAuthorized"], false); + Ok(()) + } +} diff --git a/epiphany-core/src/bin/epiphany_work/closure_contracts.rs b/epiphany-core/src/bin/epiphany_work/closure_contracts.rs deleted file mode 100644 index 0d434e22..00000000 --- a/epiphany-core/src/bin/epiphany_work/closure_contracts.rs +++ /dev/null @@ -1,5 +0,0 @@ -include!("closure_contracts/external_governance.rs"); -include!("closure_contracts/collaboration.rs"); -include!("closure_contracts/preparation.rs"); -include!("closure_contracts/workflow.rs"); -include!("closure_contracts/operations.rs"); diff --git a/epiphany-core/src/bin/epiphany_work/closure_contracts/collaboration.rs b/epiphany-core/src/bin/epiphany_work/closure_contracts/collaboration.rs deleted file mode 100644 index 956dc8b8..00000000 --- a/epiphany-core/src/bin/epiphany_work/closure_contracts/collaboration.rs +++ /dev/null @@ -1,196 +0,0 @@ -#[derive(Debug, Deserialize)] -pub(super) struct RepoCollaborationPolicy { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - policy: CollaborationPolicyProposal, - body: CollaborationBody, - verses: std::collections::BTreeMap, - eve: CollaborationEve, - persona: std::collections::BTreeMap, - imagination: CollaborationImagination, - authority: std::collections::BTreeMap, -} -impl RepoCollaborationPolicy { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_collaboration_policy.v0" - && self.safe_action_family == "repo.collaboration_policy" - } - pub(super) fn remains_proposal(&self) -> bool { - self.policy.status == "proposed" - && self.policy.authoring_owner == "Imagination" - && self.policy.required_reviewers == ["Persona", "Mind"] - && !self.policy.policy_admitted - && self.policy.publication_owner == "Bifrost" - } - pub(super) fn preserves_provider_truth(&self) -> bool { - self.body.provider_owns_truth && !self.body.renderer_owns_truth - } - pub(super) fn has_verse_boundaries(&self) -> bool { - self.verses.get("private").and_then(toml::Value::as_str) == Some("epiphany-internal") - && self.verses.get("local").and_then(toml::Value::as_str) == Some("gamecult-local") - && self.verses.get("public").and_then(toml::Value::as_str) == Some("epiphany-global") - && self - .verses - .get("private_state_may_leave_repo") - .and_then(toml::Value::as_bool) - == Some(false) - && self - .verses - .get("odin_discoverable") - .and_then(toml::Value::as_bool) - == Some(true) - } - pub(super) fn has_eve_request(&self) -> bool { - self.eve.surface.starts_with("eve://epiphany/repo/") - && self.eve.compact_tui_required - && self.eve.connection_receipt_required - && self.eve.supported_actions == ["read-queue", "discuss", "submit-feedback"] - } - pub(super) fn has_persona_route(&self) -> bool { - [ - "public_discussion_allowed", - "human_discussion_allowed", - "peer_persona_discussion_allowed", - "speech_audit_required", - "feedback_must_route_to_imagination", - ] - .iter() - .all(|key| self.persona.get(*key) == Some(&true)) - } - pub(super) fn has_imagination_route(&self) -> bool { - self.imagination - .feedback_route - .starts_with("imagination://repo/") - && self.imagination.consensus_required_before_adoption - && self.imagination.candidate_actions_non_authoritative - && self.imagination.mind_adoption_required - && self.imagination.bifrost_publication_required - } - pub(super) fn has_authority_seals(&self) -> bool { - [ - "direct_hands_authority", - "direct_mind_state_commit", - "direct_publication_authority", - "direct_merge_authority", - "service_lifecycle_authority", - "cross_body_mutation_authority", - "private_verse_rummaging", - ] - .iter() - .all(|key| self.authority.get(*key) == Some(&false)) - && self.authority.get("requires_cultmesh_receipts") == Some(&true) - } -} -#[derive(Debug, Deserialize)] -struct CollaborationPolicyProposal { - status: String, - authoring_owner: String, - required_reviewers: Vec, - policy_admitted: bool, - publication_owner: String, -} -#[derive(Debug, Deserialize)] -struct CollaborationBody { - provider_owns_truth: bool, - renderer_owns_truth: bool, -} -#[derive(Debug, Deserialize)] -struct CollaborationEve { - surface: String, - compact_tui_required: bool, - connection_receipt_required: bool, - supported_actions: Vec, -} -#[derive(Debug, Deserialize)] -struct CollaborationImagination { - feedback_route: String, - consensus_required_before_adoption: bool, - candidate_actions_non_authoritative: bool, - mind_adoption_required: bool, - bifrost_publication_required: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoCollaborationTopic { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - topic: CollaborationTopicProposal, - imagination: CollaborationTopicImagination, - authority: std::collections::BTreeMap, -} -impl RepoCollaborationTopic { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_collaboration_topic.v0" - && self.safe_action_family == "repo.collaboration_topic" - } - pub(super) fn remains_unpublished_proposal(&self) -> bool { - let t = &self.topic; - t.status == "proposed" - && t.authoring_owner == "Imagination" - && t.discussion_owner == "Persona" - && t.publication_owner == "Bifrost" - && t.requested_public_room - .starts_with("epiphany-global/persona-collaboration/") - && t.requested_eve_surface.starts_with("eve://epiphany/repo/") - && !t.public_room_published - && !t.eve_surface_published - && t.provider_receipt_required - && t.persona_discussion_allowed - && t.human_discussion_allowed - } - pub(super) fn has_imagination_route(&self) -> bool { - self.imagination - .consensus_route - .starts_with("imagination://repo/") - && self.imagination.consensus_required_before_action - && self.imagination.candidate_actions_are_non_authoritative - && self.imagination.mind_adoption_required - && self.imagination.bifrost_publication_required - } - pub(super) fn has_authority_seals(&self) -> bool { - [ - "adoption_authorized", - "hands_action_authorized", - "publication_authorized", - "cross_body_mutation_authorized", - "private_verse_rummaging", - ] - .iter() - .all(|key| self.authority.get(*key) == Some(&false)) - } -} -#[derive(Debug, Deserialize)] -struct CollaborationTopicProposal { - status: String, - authoring_owner: String, - discussion_owner: String, - publication_owner: String, - requested_public_room: String, - requested_eve_surface: String, - public_room_published: bool, - eve_surface_published: bool, - provider_receipt_required: bool, - persona_discussion_allowed: bool, - human_discussion_allowed: bool, -} -#[derive(Debug, Deserialize)] -struct CollaborationTopicImagination { - consensus_route: String, - consensus_required_before_action: bool, - candidate_actions_are_non_authoritative: bool, - mind_adoption_required: bool, - bifrost_publication_required: bool, -} - -pub(super) fn parse_repo_collaboration_policy(text: &str) -> Result { - toml::from_str(text).context("collaboration policy is not valid typed TOML") -} -pub(super) fn parse_repo_collaboration_topic(text: &str) -> Result { - toml::from_str(text).context("collaboration topic is not valid typed TOML") -} - -include!("collaboration_tests.rs"); diff --git a/epiphany-core/src/bin/epiphany_work/closure_contracts/collaboration_tests.rs b/epiphany-core/src/bin/epiphany_work/closure_contracts/collaboration_tests.rs deleted file mode 100644 index 366bc156..00000000 --- a/epiphany-core/src/bin/epiphany_work/closure_contracts/collaboration_tests.rs +++ /dev/null @@ -1,41 +0,0 @@ -#[cfg(test)] -mod collaboration_tests { - use super::*; - - #[test] - fn topic_comment_cannot_counterfeit_publication_state() { - let text = r#" -schema_version = "epiphany.repo_collaboration_topic.v0" -safe_action_family = "repo.collaboration_topic" -summary = "summary" -private_state_exposed = false -[topic] -status = "proposed" -authoring_owner = "Imagination" -discussion_owner = "Persona" -publication_owner = "Bifrost" -requested_public_room = "epiphany-global/persona-collaboration/item" -requested_eve_surface = "eve://epiphany/repo/item/collaboration" -# public_room_published = false -public_room_published = true -eve_surface_published = false -provider_receipt_required = true -persona_discussion_allowed = true -human_discussion_allowed = true -[imagination] -consensus_route = "imagination://repo/item/consensus-discovery" -consensus_required_before_action = true -candidate_actions_are_non_authoritative = true -mind_adoption_required = true -bifrost_publication_required = true -[authority] -adoption_authorized = false -hands_action_authorized = false -publication_authorized = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -"#; - let topic = parse_repo_collaboration_topic(text).expect("fixture is typed TOML"); - assert!(!topic.remains_unpublished_proposal()); - } -} diff --git a/epiphany-core/src/bin/epiphany_work/closure_contracts/external_governance.rs b/epiphany-core/src/bin/epiphany_work/closure_contracts/external_governance.rs deleted file mode 100644 index b861c62f..00000000 --- a/epiphany-core/src/bin/epiphany_work/closure_contracts/external_governance.rs +++ /dev/null @@ -1,1222 +0,0 @@ -use anyhow::{Context, Result}; -use serde::Deserialize; - -#[derive(Debug, Deserialize)] -pub(super) struct RepoToolRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - pub(super) request: RepoToolRequestBody, - pub(super) cultmesh: RepoToolRequestCultMesh, - pub(super) odin: RepoToolRequestOdin, - pub(super) authority: RepoToolRequestAuthority, -} - -impl RepoToolRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_tool_request.v0" - && self.safe_action_family == "repo.tool_request" - } - - pub(super) fn has_request_contract(&self) -> bool { - !self.request.requester_body.is_empty() - && self.request.routing_owner == "Self" - && self.request.pressure_source == "Persona" - && self.request.target_directory == "gamecult-local/daemon-tool-directory" - && self.request.target_capability == "daemon-tool-capability:selected-by-review" - && self.request.operation == "submitTypedToolIntent" - } - - pub(super) fn has_cultmesh_contract(&self) -> bool { - self.cultmesh.intent_contract == "epiphany.cultmesh.daemon_tool_invocation_intent.v0" - && self.cultmesh.receipt_contract - == "epiphany.cultmesh.daemon_tool_invocation_receipt.v0" - && self.cultmesh.host_daemon_owns_execution - && !self.cultmesh.requester_owns_execution - && self.cultmesh.requires_host_liveness_ready - && self.cultmesh.requires_cultmesh_receipts - } - - pub(super) fn has_odin_contract(&self) -> bool { - self.odin.discoverable - && self.odin.preserves_provider_ownership - && !self.odin.private_verse_passthrough - } - - pub(super) fn has_authority_seals(&self) -> bool { - !self.authority.direct_tool_execution - && !self.authority.arbitrary_shell_authority - && !self.authority.hands_action_authority - && !self.authority.state_commit_authority - && !self.authority.publication_authority - && !self.authority.service_lifecycle_authority - && !self.authority.cross_body_mutation_authority - && !self.authority.private_verse_rummaging - } -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoToolRequestBody { - requester_body: String, - routing_owner: String, - pressure_source: String, - target_directory: String, - target_capability: String, - operation: String, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoToolRequestCultMesh { - intent_contract: String, - receipt_contract: String, - host_daemon_owns_execution: bool, - requester_owns_execution: bool, - requires_host_liveness_ready: bool, - requires_cultmesh_receipts: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoToolRequestOdin { - discoverable: bool, - preserves_provider_ownership: bool, - private_verse_passthrough: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoToolRequestAuthority { - pub(super) direct_tool_execution: bool, - arbitrary_shell_authority: bool, - hands_action_authority: bool, - state_commit_authority: bool, - publication_authority: bool, - service_lifecycle_authority: bool, - cross_body_mutation_authority: bool, - private_verse_rummaging: bool, -} - -pub(super) fn parse_repo_tool_request(text: &str) -> Result { - toml::from_str(text).context("tool request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoMetricsRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - request: RepoMetricsRequestBody, - antecedents: RepoMetricsAntecedents, - required_receipts: RepoMetricsReceipts, - metrics_packet: RepoMetricsPacket, - authority: RepoMetricsAuthority, -} - -impl RepoMetricsRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_metrics_request.v0" - && self.safe_action_family == "repo.metrics_request" - } - - pub(super) fn awaits_owned_review(&self) -> bool { - self.request.status == "awaiting-metrics-review" - && self.request.routing_owner == "Self" - && self.request.accounting_owner == "Bifrost" - && self.request.review_evidence_owner == "Maintainer" - && self.request.spend_receipt_required - && self.request.review_load_receipt_required - && self.request.requested_effect == "record-compute-review-and-artifact-accounting" - && !self.request.publication_request_ref.is_empty() - && !self.request.credit_request_ref.is_empty() - && !self.request.artifact_acceptance_request_ref.is_empty() - } - - pub(super) fn has_antecedent_contract(&self) -> bool { - let a = &self.antecedents; - a.closure_review_required - && a.soul_verdict_required - && a.mind_commit_required - && a.public_proof_required - && a.accepted_artifact_required - && a.credit_request_required - } - - pub(super) fn has_receipt_contract(&self) -> bool { - let r = &self.required_receipts; - r.closure_review == "epiphany.repo_work_closure_review.v0" - && r.soul_verdict == "epiphany.soul.verification_verdict" - && r.mind_commit == "epiphany.mind.state_commit_receipt" - && r.public_proof == "epiphany.repo_work_public_proof_bundle.v0" - && r.accepted_artifact == "gamecult.artifact.acceptance_receipt.v0" - && r.model_spend == "gamecult.metrics.model_spend_receipt.v0" - && r.review_load == "gamecult.metrics.review_load_receipt.v0" - && r.credit_readback == "gamecult.bifrost.credit_readback_receipt.v0" - } - - pub(super) fn has_metrics_packet(&self) -> bool { - let p = &self.metrics_packet; - p.requires_model_call_count - && p.requires_token_summary - && p.requires_cost_availability_status - && p.requires_review_duration - && p.requires_review_event_count - && p.requires_accepted_artifact_ref - && p.requires_public_proof_ref - && p.requires_credit_readback_ref - && p.requires_private_state_redaction_check - } - - pub(super) fn has_authority_seals(&self) -> bool { - let a = &self.authority; - a.branch_local_only - && !a.metrics_ledger_authorized - && !a.spend_authorized - && !a.review_load_authorized - && !a.credit_ledger_authorized - && !a.github_pr_authorized - && !a.merge_authorized - && !a.publication_authorized - && !a.upstream_sync_authorized - && !a.hands_action_authorized - && !a.service_lifecycle_authority - && !a.cross_body_mutation_authorized - && !a.private_verse_rummaging - && a.bifrost_accounting_required - && a.maintainer_review_evidence_required - } -} - -#[derive(Debug, Deserialize)] -struct RepoMetricsRequestBody { - status: String, - routing_owner: String, - accounting_owner: String, - review_evidence_owner: String, - spend_receipt_required: bool, - review_load_receipt_required: bool, - requested_effect: String, - publication_request_ref: String, - credit_request_ref: String, - artifact_acceptance_request_ref: String, -} - -#[derive(Debug, Deserialize)] -struct RepoMetricsAntecedents { - closure_review_required: bool, - soul_verdict_required: bool, - mind_commit_required: bool, - public_proof_required: bool, - accepted_artifact_required: bool, - credit_request_required: bool, -} - -#[derive(Debug, Deserialize)] -struct RepoMetricsReceipts { - closure_review: String, - soul_verdict: String, - mind_commit: String, - public_proof: String, - accepted_artifact: String, - model_spend: String, - review_load: String, - credit_readback: String, -} - -#[derive(Debug, Deserialize)] -struct RepoMetricsPacket { - requires_model_call_count: bool, - requires_token_summary: bool, - requires_cost_availability_status: bool, - requires_review_duration: bool, - requires_review_event_count: bool, - requires_accepted_artifact_ref: bool, - requires_public_proof_ref: bool, - requires_credit_readback_ref: bool, - requires_private_state_redaction_check: bool, -} - -#[derive(Debug, Deserialize)] -struct RepoMetricsAuthority { - branch_local_only: bool, - metrics_ledger_authorized: bool, - spend_authorized: bool, - review_load_authorized: bool, - credit_ledger_authorized: bool, - github_pr_authorized: bool, - merge_authorized: bool, - publication_authorized: bool, - upstream_sync_authorized: bool, - hands_action_authorized: bool, - service_lifecycle_authority: bool, - cross_body_mutation_authorized: bool, - private_verse_rummaging: bool, - bifrost_accounting_required: bool, - maintainer_review_evidence_required: bool, -} - -pub(super) fn parse_repo_metrics_request(text: &str) -> Result { - toml::from_str(text).context("metrics request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoArtifactAcceptanceRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - request: RepoArtifactAcceptanceRequestBody, - antecedents: RepoArtifactAcceptanceAntecedents, - required_receipts: RepoArtifactAcceptanceReceipts, - artifact_packet: RepoArtifactAcceptancePacket, - authority: RepoArtifactAcceptanceAuthority, -} - -impl RepoArtifactAcceptanceRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_artifact_acceptance_request.v0" - && self.safe_action_family == "repo.artifact_acceptance_request" - } - - pub(super) fn awaits_owned_review(&self) -> bool { - let r = &self.request; - r.status == "awaiting-artifact-acceptance-review" - && r.routing_owner == "Self" - && r.acceptance_owner == "Maintainer" - && r.accounting_owner == "Bifrost" - && r.acceptance_receipt_required - && r.requested_effect == "record-accepted-artifact-for-reviewed-branch-work" - && !r.verification_request_ref.is_empty() - && !r.maintainer_review_request_ref.is_empty() - && !r.publication_request_ref.is_empty() - } - - pub(super) fn has_antecedent_contract(&self) -> bool { - let a = &self.antecedents; - a.closure_review_required - && a.soul_verdict_required - && a.mind_commit_required - && a.public_proof_required - && a.maintainer_review_required - && a.hands_commit_required - } - - pub(super) fn has_receipt_contract(&self) -> bool { - let r = &self.required_receipts; - r.closure_review == "epiphany.repo_work_closure_review.v0" - && r.soul_verdict == "epiphany.soul.verification_verdict" - && r.mind_commit == "epiphany.mind.state_commit_receipt" - && r.public_proof == "epiphany.repo_work_public_proof_bundle.v0" - && r.maintainer_review == "gamecult.maintainer.review_receipt.v0" - && r.hands_commit == "epiphany.hands.commit_receipt" - && r.accepted_artifact == "gamecult.artifact.acceptance_receipt.v0" - } - - pub(super) fn has_artifact_packet(&self) -> bool { - let p = &self.artifact_packet; - p.requires_artifact_ref - && p.requires_commit_sha - && p.requires_changed_path_list - && p.requires_review_verdict - && p.requires_public_proof_ref - && p.requires_acceptance_rationale - && p.requires_private_state_redaction_check - } - - pub(super) fn has_authority_seals(&self) -> bool { - let a = &self.authority; - a.branch_local_only - && !a.artifact_acceptance_authorized - && !a.credit_ledger_authorized - && !a.github_pr_authorized - && !a.merge_authorized - && !a.publication_authorized - && !a.upstream_sync_authorized - && !a.hands_action_authorized - && !a.service_lifecycle_authority - && !a.cross_body_mutation_authorized - && !a.private_verse_rummaging - && a.maintainer_acceptance_authority_required - && a.bifrost_accounting_required - } -} - -#[derive(Debug, Deserialize)] -struct RepoArtifactAcceptanceRequestBody { - status: String, - routing_owner: String, - acceptance_owner: String, - accounting_owner: String, - acceptance_receipt_required: bool, - requested_effect: String, - verification_request_ref: String, - maintainer_review_request_ref: String, - publication_request_ref: String, -} - -#[derive(Debug, Deserialize)] -struct RepoArtifactAcceptanceAntecedents { - closure_review_required: bool, - soul_verdict_required: bool, - mind_commit_required: bool, - public_proof_required: bool, - maintainer_review_required: bool, - hands_commit_required: bool, -} - -#[derive(Debug, Deserialize)] -struct RepoArtifactAcceptanceReceipts { - closure_review: String, - soul_verdict: String, - mind_commit: String, - public_proof: String, - maintainer_review: String, - hands_commit: String, - accepted_artifact: String, -} - -#[derive(Debug, Deserialize)] -struct RepoArtifactAcceptancePacket { - requires_artifact_ref: bool, - requires_commit_sha: bool, - requires_changed_path_list: bool, - requires_review_verdict: bool, - requires_public_proof_ref: bool, - requires_acceptance_rationale: bool, - requires_private_state_redaction_check: bool, -} - -#[derive(Debug, Deserialize)] -struct RepoArtifactAcceptanceAuthority { - branch_local_only: bool, - artifact_acceptance_authorized: bool, - credit_ledger_authorized: bool, - github_pr_authorized: bool, - merge_authorized: bool, - publication_authorized: bool, - upstream_sync_authorized: bool, - hands_action_authorized: bool, - service_lifecycle_authority: bool, - cross_body_mutation_authorized: bool, - private_verse_rummaging: bool, - maintainer_acceptance_authority_required: bool, - bifrost_accounting_required: bool, -} - -pub(super) fn parse_repo_artifact_acceptance_request( - text: &str, -) -> Result { - toml::from_str(text).context("artifact acceptance request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoCreditRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - request: RepoCreditRequestBody, - antecedents: RepoCreditAntecedents, - required_receipts: RepoCreditReceipts, - credit_packet: RepoCreditPacket, - authority: RepoCreditAuthority, -} - -impl RepoCreditRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_credit_request.v0" - && self.safe_action_family == "repo.credit_request" - } - pub(super) fn awaits_bifrost_review(&self) -> bool { - let r = &self.request; - r.status == "awaiting-bifrost-credit-review" - && r.requested_owner == "Bifrost" - && r.requested_effect == "record-credit-for-redacted-proof-and-accepted-artifact" - && !r.publication_request_ref.is_empty() - && !r.maintainer_review_request_ref.is_empty() - && !r.pr_request_ref.is_empty() - } - pub(super) fn has_antecedent_contract(&self) -> bool { - let a = &self.antecedents; - a.closure_review_required - && a.soul_verdict_required - && a.mind_commit_required - && a.public_proof_required - && a.maintainer_review_required - && a.accepted_artifact_required - && a.authorship_context_required - } - pub(super) fn has_receipt_contract(&self) -> bool { - let r = &self.required_receipts; - r.closure_review == "epiphany.repo_work_closure_review.v0" - && r.soul_verdict == "epiphany.soul.verification_verdict" - && r.mind_commit == "epiphany.mind.state_commit_receipt" - && r.public_proof == "epiphany.repo_work_public_proof_bundle.v0" - && r.maintainer_review == "gamecult.maintainer.review_receipt.v0" - && r.accepted_artifact == "gamecult.artifact.acceptance_receipt.v0" - && r.credit_ledger == "gamecult.bifrost.credit_receipt.v0" - && r.credit_readback == "gamecult.bifrost.credit_readback_receipt.v0" - } - pub(super) fn has_credit_packet(&self) -> bool { - let p = &self.credit_packet; - p.requires_author_identity - && p.requires_reviewer_identity - && p.requires_accepted_artifact_ref - && p.requires_public_proof_ref - && p.requires_changed_path_list - && p.requires_credit_ledger_target - && p.requires_private_state_redaction_check - } - pub(super) fn has_authority_seals(&self) -> bool { - let a = &self.authority; - a.branch_local_only - && !a.credit_ledger_authorized - && !a.bifrost_publication_authorized - && !a.github_pr_authorized - && !a.merge_authorized - && !a.publication_authorized - && !a.upstream_sync_authorized - && !a.hands_action_authorized - && !a.service_lifecycle_authority - && !a.cross_body_mutation_authorized - && !a.private_verse_rummaging - && a.bifrost_credit_authority_required - } -} - -#[derive(Debug, Deserialize)] -struct RepoCreditRequestBody { - status: String, - requested_owner: String, - requested_effect: String, - publication_request_ref: String, - maintainer_review_request_ref: String, - pr_request_ref: String, -} -#[derive(Debug, Deserialize)] -struct RepoCreditAntecedents { - closure_review_required: bool, - soul_verdict_required: bool, - mind_commit_required: bool, - public_proof_required: bool, - maintainer_review_required: bool, - accepted_artifact_required: bool, - authorship_context_required: bool, -} -#[derive(Debug, Deserialize)] -struct RepoCreditReceipts { - closure_review: String, - soul_verdict: String, - mind_commit: String, - public_proof: String, - maintainer_review: String, - accepted_artifact: String, - credit_ledger: String, - credit_readback: String, -} -#[derive(Debug, Deserialize)] -struct RepoCreditPacket { - requires_author_identity: bool, - requires_reviewer_identity: bool, - requires_accepted_artifact_ref: bool, - requires_public_proof_ref: bool, - requires_changed_path_list: bool, - requires_credit_ledger_target: bool, - requires_private_state_redaction_check: bool, -} -#[derive(Debug, Deserialize)] -struct RepoCreditAuthority { - branch_local_only: bool, - credit_ledger_authorized: bool, - bifrost_publication_authorized: bool, - github_pr_authorized: bool, - merge_authorized: bool, - publication_authorized: bool, - upstream_sync_authorized: bool, - hands_action_authorized: bool, - service_lifecycle_authority: bool, - cross_body_mutation_authorized: bool, - private_verse_rummaging: bool, - bifrost_credit_authority_required: bool, -} - -pub(super) fn parse_repo_credit_request(text: &str) -> Result { - toml::from_str(text).context("credit request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoPublicationRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - request: RepoPublicationRequestBody, - antecedents: RepoPublicationAntecedents, - required_receipts: RepoPublicationReceipts, - public_export: RepoPublicationExport, - authority: RepoPublicationAuthority, -} - -impl RepoPublicationRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_publication_request.v0" - && self.safe_action_family == "repo.publication_request" - } - pub(super) fn awaits_bifrost_review(&self) -> bool { - self.request.status == "awaiting-bifrost-review" - && self.request.requested_owner == "Bifrost" - && self.request.requested_effect == "publish-redacted-proof-and-route-maintainer-review" - && !self.request.verification_request_ref.is_empty() - } - pub(super) fn has_antecedent_contract(&self) -> bool { - let a = &self.antecedents; - a.closure_review_required - && a.soul_verdict_required - && a.mind_commit_required - && a.public_proof_export_required - && a.private_state_redaction_required - } - pub(super) fn has_receipt_contract(&self) -> bool { - let r = &self.required_receipts; - r.closure_review == "epiphany.repo_work_closure_review.v0" - && r.soul_verdict == "epiphany.soul.verification_verdict" - && r.mind_commit == "epiphany.mind.state_commit_receipt" - && r.public_proof == "epiphany.repo_work_public_proof_bundle.v0" - && r.bifrost_publication == "gamecult.bifrost.public_proof_publication_receipt.v0" - && r.github_publication == "gamecult.github.publication_receipt.v0" - && r.credit_ledger == "gamecult.bifrost.credit_receipt.v0" - && r.upstream_sync == "epiphany.repo_work_upstream_main_sync.v0" - } - pub(super) fn has_redaction_contract(&self) -> bool { - let e = &self.public_export; - e.redacted_only - && !e.raw_receipts_allowed - && !e.private_paths_allowed - && !e.worker_thought_allowed - && !e.operator_context_allowed - && e.credit_required - } - pub(super) fn has_authority_seals(&self) -> bool { - let a = &self.authority; - a.branch_local_only - && !a.bifrost_publication_authorized - && !a.github_publication_authorized - && !a.credit_ledger_authorized - && !a.merge_authorized - && !a.upstream_sync_authorized - && !a.hands_action_authorized - && !a.service_lifecycle_authority - && !a.cross_body_mutation_authorized - && !a.private_verse_rummaging - && a.maintainer_review_required - } -} - -#[derive(Debug, Deserialize)] -struct RepoPublicationRequestBody { - status: String, - requested_owner: String, - requested_effect: String, - verification_request_ref: String, -} -#[derive(Debug, Deserialize)] -struct RepoPublicationAntecedents { - closure_review_required: bool, - soul_verdict_required: bool, - mind_commit_required: bool, - public_proof_export_required: bool, - private_state_redaction_required: bool, -} -#[derive(Debug, Deserialize)] -struct RepoPublicationReceipts { - closure_review: String, - soul_verdict: String, - mind_commit: String, - public_proof: String, - bifrost_publication: String, - github_publication: String, - credit_ledger: String, - upstream_sync: String, -} -#[derive(Debug, Deserialize)] -struct RepoPublicationExport { - redacted_only: bool, - raw_receipts_allowed: bool, - private_paths_allowed: bool, - worker_thought_allowed: bool, - operator_context_allowed: bool, - credit_required: bool, -} -#[derive(Debug, Deserialize)] -struct RepoPublicationAuthority { - branch_local_only: bool, - bifrost_publication_authorized: bool, - github_publication_authorized: bool, - credit_ledger_authorized: bool, - merge_authorized: bool, - upstream_sync_authorized: bool, - hands_action_authorized: bool, - service_lifecycle_authority: bool, - cross_body_mutation_authorized: bool, - private_verse_rummaging: bool, - maintainer_review_required: bool, -} - -pub(super) fn parse_repo_publication_request(text: &str) -> Result { - toml::from_str(text).context("publication request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoSyncRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - request: RepoSyncRequestBody, - antecedents: RepoSyncAntecedents, - required_receipts: RepoSyncReceipts, - sync_proof: RepoSyncProof, - authority: RepoSyncAuthority, -} -impl RepoSyncRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_sync_request.v0" - && self.safe_action_family == "repo.sync_request" - } - pub(super) fn awaits_upstream_proof(&self) -> bool { - self.request.status == "awaiting-upstream-main-proof" - && self.request.proof_owner == "Bifrost" - && self.request.requested_effect == "prove-published-commit-contained-by-upstream-main" - && !self.request.publication_request_ref.is_empty() - } - pub(super) fn has_antecedent_contract(&self) -> bool { - let a = &self.antecedents; - a.publication_receipt_required - && a.github_publication_required - && a.maintainer_review_required - && a.credit_ledger_required - && a.public_proof_required - } - pub(super) fn has_receipt_contract(&self) -> bool { - let r = &self.required_receipts; - r.bifrost_publication == "gamecult.bifrost.public_proof_publication_receipt.v0" - && r.github_publication == "gamecult.github.publication_receipt.v0" - && r.maintainer_review == "gamecult.maintainer.review_receipt.v0" - && r.credit_ledger == "gamecult.bifrost.credit_receipt.v0" - && r.upstream_sync == "epiphany.repo_work_upstream_main_sync.v0" - && r.ancestry_proof == "git.merge_base_is_ancestor" - } - pub(super) fn has_proof_contract(&self) -> bool { - let p = &self.sync_proof; - p.target_ref == "origin/main" - && p.requires_fetch_before_check - && p.requires_merge_base_ancestor_check - && p.requires_clean_public_proof_readback - && p.records_upstream_main_sha - } - pub(super) fn has_authority_seals(&self) -> bool { - let a = &self.authority; - a.branch_local_only - && !a.merge_authorized - && !a.push_authorized - && !a.upstream_sync_authorized - && !a.github_publication_authorized - && !a.credit_ledger_authorized - && !a.hands_action_authorized - && !a.service_lifecycle_authority - && !a.cross_body_mutation_authorized - && !a.private_verse_rummaging - && a.bifrost_upstream_proof_required - && a.maintainer_review_receipt_required - } -} -#[derive(Debug, Deserialize)] -struct RepoSyncRequestBody { - status: String, - proof_owner: String, - requested_effect: String, - publication_request_ref: String, -} -#[derive(Debug, Deserialize)] -struct RepoSyncAntecedents { - publication_receipt_required: bool, - github_publication_required: bool, - maintainer_review_required: bool, - credit_ledger_required: bool, - public_proof_required: bool, -} -#[derive(Debug, Deserialize)] -struct RepoSyncReceipts { - bifrost_publication: String, - github_publication: String, - maintainer_review: String, - credit_ledger: String, - upstream_sync: String, - ancestry_proof: String, -} -#[derive(Debug, Deserialize)] -struct RepoSyncProof { - target_ref: String, - requires_fetch_before_check: bool, - requires_merge_base_ancestor_check: bool, - requires_clean_public_proof_readback: bool, - records_upstream_main_sha: bool, -} -#[derive(Debug, Deserialize)] -struct RepoSyncAuthority { - branch_local_only: bool, - merge_authorized: bool, - push_authorized: bool, - upstream_sync_authorized: bool, - github_publication_authorized: bool, - credit_ledger_authorized: bool, - hands_action_authorized: bool, - service_lifecycle_authority: bool, - cross_body_mutation_authorized: bool, - private_verse_rummaging: bool, - bifrost_upstream_proof_required: bool, - maintainer_review_receipt_required: bool, -} -pub(super) fn parse_repo_sync_request(text: &str) -> Result { - toml::from_str(text).context("sync request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoPrRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - request: RepoPrRequestBody, - antecedents: RepoPrAntecedents, - required_receipts: RepoPrReceipts, - pr_packet: RepoPrPacket, - authority: RepoPrAuthority, -} -impl RepoPrRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_pr_request.v0" - && self.safe_action_family == "repo.pr_request" - } - pub(super) fn awaits_owned_review(&self) -> bool { - let r = &self.request; - r.status == "awaiting-pr-publication-review" - && r.routing_owner == "Self" - && r.publication_owner == "Bifrost" - && r.execution_owner == "Hands" - && r.provider == "GitHub" - && r.provider_receipt_required - && r.requested_effect - == "open-or-update-review-pr-from-redacted-proof-and-maintainer-context" - && !r.maintainer_review_request_ref.is_empty() - && !r.publication_request_ref.is_empty() - && !r.sync_request_ref.is_empty() - } - pub(super) fn has_antecedent_contract(&self) -> bool { - let a = &self.antecedents; - a.closure_review_required - && a.soul_verdict_required - && a.mind_commit_required - && a.public_proof_required - && a.maintainer_review_required - && a.bifrost_publication_required - && a.credit_ledger_required - } - pub(super) fn has_receipt_contract(&self) -> bool { - let r = &self.required_receipts; - r.closure_review == "epiphany.repo_work_closure_review.v0" - && r.soul_verdict == "epiphany.soul.verification_verdict" - && r.mind_commit == "epiphany.mind.state_commit_receipt" - && r.public_proof == "epiphany.repo_work_public_proof_bundle.v0" - && r.maintainer_review == "gamecult.maintainer.review_receipt.v0" - && r.bifrost_publication == "gamecult.bifrost.public_proof_publication_receipt.v0" - && r.credit_ledger == "gamecult.bifrost.credit_receipt.v0" - && r.pr_publication == "gamecult.github.pull_request_publication_receipt.v0" - } - pub(super) fn has_packet_contract(&self) -> bool { - let p = &self.pr_packet; - p.base_ref == "origin/main" - && p.requires_branch_name - && p.requires_title - && p.requires_body - && p.requires_changed_path_list - && p.requires_public_proof_ref - && p.requires_maintainer_review_ref - && p.requires_credit_ref - && p.requires_private_state_redaction_check - } - pub(super) fn has_authority_seals(&self) -> bool { - let a = &self.authority; - a.branch_local_only - && !a.github_pr_authorized - && !a.branch_push_authorized - && !a.merge_authorized - && !a.publication_authorized - && !a.upstream_sync_authorized - && !a.hands_action_authorized - && !a.service_lifecycle_authority - && !a.cross_body_mutation_authorized - && !a.private_verse_rummaging - && a.maintainer_review_required - && a.bifrost_publication_gate_required - && a.hands_execution_required - && a.github_provider_receipt_required - } -} -#[derive(Debug, Deserialize)] -struct RepoPrRequestBody { - status: String, - routing_owner: String, - publication_owner: String, - execution_owner: String, - provider: String, - provider_receipt_required: bool, - requested_effect: String, - maintainer_review_request_ref: String, - publication_request_ref: String, - sync_request_ref: String, -} -#[derive(Debug, Deserialize)] -struct RepoPrAntecedents { - closure_review_required: bool, - soul_verdict_required: bool, - mind_commit_required: bool, - public_proof_required: bool, - maintainer_review_required: bool, - bifrost_publication_required: bool, - credit_ledger_required: bool, -} -#[derive(Debug, Deserialize)] -struct RepoPrReceipts { - closure_review: String, - soul_verdict: String, - mind_commit: String, - public_proof: String, - maintainer_review: String, - bifrost_publication: String, - credit_ledger: String, - pr_publication: String, -} -#[derive(Debug, Deserialize)] -struct RepoPrPacket { - base_ref: String, - requires_branch_name: bool, - requires_title: bool, - requires_body: bool, - requires_changed_path_list: bool, - requires_public_proof_ref: bool, - requires_maintainer_review_ref: bool, - requires_credit_ref: bool, - requires_private_state_redaction_check: bool, -} -#[derive(Debug, Deserialize)] -struct RepoPrAuthority { - branch_local_only: bool, - github_pr_authorized: bool, - branch_push_authorized: bool, - merge_authorized: bool, - publication_authorized: bool, - upstream_sync_authorized: bool, - hands_action_authorized: bool, - service_lifecycle_authority: bool, - cross_body_mutation_authorized: bool, - private_verse_rummaging: bool, - maintainer_review_required: bool, - bifrost_publication_gate_required: bool, - hands_execution_required: bool, - github_provider_receipt_required: bool, -} -pub(super) fn parse_repo_pr_request(text: &str) -> Result { - toml::from_str(text).context("PR request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoMaintainerReviewRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - request: RepoMaintainerReviewBody, - antecedents: RepoMaintainerReviewAntecedents, - required_receipts: RepoMaintainerReviewReceipts, - review_packet: RepoMaintainerReviewPacket, - authority: RepoMaintainerReviewAuthority, -} -impl RepoMaintainerReviewRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_maintainer_review_request.v0" - && self.safe_action_family == "repo.maintainer_review_request" - } - pub(super) fn awaits_review(&self) -> bool { - let r = &self.request; - r.status == "awaiting-maintainer-review" - && r.requested_owner == "Maintainer" - && r.requested_effect == "review-redacted-proof-and-branch-diff" - && !r.verification_request_ref.is_empty() - && !r.publication_request_ref.is_empty() - } - pub(super) fn has_antecedent_contract(&self) -> bool { - let a = &self.antecedents; - a.closure_review_required - && a.soul_verdict_required - && a.mind_commit_required - && a.public_proof_required - && a.bifrost_publication_request_required - } - pub(super) fn has_receipt_contract(&self) -> bool { - let r = &self.required_receipts; - r.closure_review == "epiphany.repo_work_closure_review.v0" - && r.soul_verdict == "epiphany.soul.verification_verdict" - && r.mind_commit == "epiphany.mind.state_commit_receipt" - && r.public_proof == "epiphany.repo_work_public_proof_bundle.v0" - && r.maintainer_review == "gamecult.maintainer.review_receipt.v0" - && r.bifrost_publication == "gamecult.bifrost.public_proof_publication_receipt.v0" - } - pub(super) fn has_review_packet(&self) -> bool { - let p = &self.review_packet; - p.requires_reviewer_identity - && p.requires_review_verdict - && p.allowed_verdicts - == [ - "approved", - "changes-requested", - "rejected", - "needs-human-context", - ] - && p.requires_changed_path_list - && p.requires_public_proof_ref - && p.requires_private_state_redaction_check - } - pub(super) fn has_authority_seals(&self) -> bool { - let a = &self.authority; - a.branch_local_only - && !a.maintainer_approval_authorized - && !a.merge_authorized - && !a.push_authorized - && !a.publication_authorized - && !a.upstream_sync_authorized - && !a.hands_action_authorized - && !a.service_lifecycle_authority - && !a.cross_body_mutation_authorized - && !a.private_verse_rummaging - && a.maintainer_response_required - } -} -#[derive(Debug, Deserialize)] -struct RepoMaintainerReviewBody { - status: String, - requested_owner: String, - requested_effect: String, - verification_request_ref: String, - publication_request_ref: String, -} -#[derive(Debug, Deserialize)] -struct RepoMaintainerReviewAntecedents { - closure_review_required: bool, - soul_verdict_required: bool, - mind_commit_required: bool, - public_proof_required: bool, - bifrost_publication_request_required: bool, -} -#[derive(Debug, Deserialize)] -struct RepoMaintainerReviewReceipts { - closure_review: String, - soul_verdict: String, - mind_commit: String, - public_proof: String, - maintainer_review: String, - bifrost_publication: String, -} -#[derive(Debug, Deserialize)] -struct RepoMaintainerReviewPacket { - requires_reviewer_identity: bool, - requires_review_verdict: bool, - allowed_verdicts: Vec, - requires_changed_path_list: bool, - requires_public_proof_ref: bool, - requires_private_state_redaction_check: bool, -} -#[derive(Debug, Deserialize)] -struct RepoMaintainerReviewAuthority { - branch_local_only: bool, - maintainer_approval_authorized: bool, - merge_authorized: bool, - push_authorized: bool, - publication_authorized: bool, - upstream_sync_authorized: bool, - hands_action_authorized: bool, - service_lifecycle_authority: bool, - cross_body_mutation_authorized: bool, - private_verse_rummaging: bool, - maintainer_response_required: bool, -} -pub(super) fn parse_repo_maintainer_review_request( - text: &str, -) -> Result { - toml::from_str(text).context("maintainer review request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoReadinessReviewRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - request: RepoReadinessReviewBody, - antecedents: std::collections::BTreeMap, - required_receipts: std::collections::BTreeMap, - readiness_packet: RepoReadinessPacket, - authority: std::collections::BTreeMap, -} - -impl RepoReadinessReviewRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_readiness_review_request.v0" - && self.safe_action_family == "repo.readiness_review_request" - } - - pub(super) fn has_coherent_routing(&self) -> bool { - let r = &self.request; - r.status == "awaiting-mvp-readiness-review" - && r.routing_owner == "Self" - && r.required_reviewers == ["Maintainer", "Soul", "Mind", "Bifrost"] - && r.readiness_approval_owner == "Maintainer" - && r.requested_effect == "review-redacted-repo-swarm-mvp-proof-bundle" - && r.maintainer_readiness_acceptance_required - && r.bifrost_publication_review_required - } - - pub(super) fn has_antecedent_contract(&self) -> bool { - [ - "repo_init_required", - "swarm_online_required", - "persona_intake_required", - "imagination_plan_required", - "self_queue_run_required", - "hands_commit_required", - "soul_closure_required", - "modeling_map_update_required", - "mind_admission_required", - "public_proof_required", - "bifrost_publication_required", - "upstream_main_sync_required", - "idunn_lifecycle_readiness_required", - "tool_directory_readiness_required", - "private_state_redaction_required", - ] - .iter() - .all(|key| self.antecedents.get(*key) == Some(&true)) - } - - pub(super) fn has_receipt_contract(&self) -> bool { - [ - ("repo_init", "epiphany.repo_swarm_init_receipt.v0"), - ("swarm_online", "epiphany.repo_swarm_online_receipt.v0"), - ("persona_speech_audit", "epiphany.persona_speech_audit.v0"), - ( - "imagination_action_items", - "epiphany.repo_work_imagination_action_items_receipt.v0", - ), - ("queue_run", "epiphany.repo_work_queue_run_receipt.v0"), - ("hands_commit", "epiphany.hands.commit_receipt"), - ("closure_review", "epiphany.repo_work_closure_review.v0"), - ("soul_verdict", "epiphany.soul.verification_verdict"), - ("modeling_map", "epiphany.repo_work_map_entry.v0"), - ("mind_commit", "epiphany.mind.state_commit_receipt"), - ("public_proof", "epiphany.repo_work_public_proof_bundle.v0"), - ( - "bifrost_publication", - "gamecult.bifrost.public_proof_publication_receipt.v0", - ), - ( - "upstream_sync", - "epiphany.repo_work_upstream_sync_receipt.v0", - ), - ("idunn_lifecycle", "epiphany.repo_work_service_audit.v0"), - ( - "tool_directory", - "epiphany.cultmesh.daemon_tool_directory.v0", - ), - ] - .iter() - .all(|(key, value)| self.required_receipts.get(*key).is_some_and(|v| v == value)) - } - - pub(super) fn has_packet_contract(&self) -> bool { - let p = &self.readiness_packet; - p.requires_proof_bundle_ref - && p.requires_changed_path_list - && p.requires_branch_name - && p.requires_upstream_main_ref - && p.requires_public_proof_ref - && p.requires_bifrost_ledger_ref - && p.requires_idunn_lifecycle_ref - && p.requires_tool_directory_ref - && p.requires_redaction_report - && p.requires_reviewer_identity - && p.allowed_verdicts - == [ - "ready", - "ready-with-caveats", - "not-ready", - "needs-human-review", - ] - } - - pub(super) fn has_authority_seals(&self) -> bool { - let denied = [ - "readiness_approval_authorized", - "durable_state_commit_authorized", - "publication_authorized", - "bifrost_publication_authorized", - "github_pr_authorized", - "merge_authorized", - "upstream_sync_authorized", - "deployment_authority", - "service_lifecycle_authority", - "hands_action_authorized", - "cross_body_mutation_authorized", - "private_verse_rummaging", - ]; - denied - .iter() - .all(|key| self.authority.get(*key) == Some(&false)) - && self.authority.get("maintainer_review_required") == Some(&true) - && self.authority.get("soul_verification_required") == Some(&true) - && self.authority.get("mind_admission_required") == Some(&true) - && self.authority.get("bifrost_publication_review_required") == Some(&true) - } -} - -#[derive(Debug, Deserialize)] -struct RepoReadinessReviewBody { - status: String, - routing_owner: String, - required_reviewers: Vec, - readiness_approval_owner: String, - requested_effect: String, - maintainer_readiness_acceptance_required: bool, - bifrost_publication_review_required: bool, -} - -#[derive(Debug, Deserialize)] -struct RepoReadinessPacket { - requires_proof_bundle_ref: bool, - requires_changed_path_list: bool, - requires_branch_name: bool, - requires_upstream_main_ref: bool, - requires_public_proof_ref: bool, - requires_bifrost_ledger_ref: bool, - requires_idunn_lifecycle_ref: bool, - requires_tool_directory_ref: bool, - requires_redaction_report: bool, - requires_reviewer_identity: bool, - allowed_verdicts: Vec, -} - -pub(super) fn parse_repo_readiness_review_request( - text: &str, -) -> Result { - toml::from_str(text).context("readiness review request is not valid typed TOML") -} - -include!("external_governance_tests.rs"); diff --git a/epiphany-core/src/bin/epiphany_work/closure_contracts/external_governance_tests.rs b/epiphany-core/src/bin/epiphany_work/closure_contracts/external_governance_tests.rs deleted file mode 100644 index a5e2773b..00000000 --- a/epiphany-core/src/bin/epiphany_work/closure_contracts/external_governance_tests.rs +++ /dev/null @@ -1,485 +0,0 @@ -#[cfg(test)] -mod external_governance_tests { - use super::*; - - #[test] - fn readiness_comment_cannot_counterfeit_approval_seal() { - let text = r#" -schema_version = "epiphany.repo_readiness_review_request.v0" -safe_action_family = "repo.readiness_review_request" -summary = "summary" -private_state_exposed = false -[request] -status = "awaiting-mvp-readiness-review" -routing_owner = "Self" -required_reviewers = ["Maintainer", "Soul", "Mind", "Bifrost"] -readiness_approval_owner = "Maintainer" -requested_effect = "review-redacted-repo-swarm-mvp-proof-bundle" -maintainer_readiness_acceptance_required = true -bifrost_publication_review_required = true -[antecedents] -[required_receipts] -[readiness_packet] -requires_proof_bundle_ref = false -requires_changed_path_list = false -requires_branch_name = false -requires_upstream_main_ref = false -requires_public_proof_ref = false -requires_bifrost_ledger_ref = false -requires_idunn_lifecycle_ref = false -requires_tool_directory_ref = false -requires_redaction_report = false -requires_reviewer_identity = false -allowed_verdicts = [] -[authority] -# readiness_approval_authorized = false -readiness_approval_authorized = true -"#; - let request = parse_repo_readiness_review_request(text).expect("fixture is typed TOML"); - assert!(!request.has_authority_seals()); - } - - #[test] - fn comment_cannot_counterfeit_direct_execution_seal() { - let text = r#" -schema_version = "epiphany.repo_tool_request.v0" -safe_action_family = "repo.tool_request" -summary = "summary" -private_state_exposed = false -[request] -requester_body = "repo:test" -routing_owner = "Self" -pressure_source = "Persona" -target_directory = "gamecult-local/daemon-tool-directory" -target_capability = "daemon-tool-capability:selected-by-review" -operation = "submitTypedToolIntent" -[cultmesh] -intent_contract = "epiphany.cultmesh.daemon_tool_invocation_intent.v0" -receipt_contract = "epiphany.cultmesh.daemon_tool_invocation_receipt.v0" -host_daemon_owns_execution = true -requester_owns_execution = false -requires_host_liveness_ready = true -requires_cultmesh_receipts = true -[odin] -discoverable = true -preserves_provider_ownership = true -private_verse_passthrough = false -[authority] -# direct_tool_execution = false -direct_tool_execution = true -arbitrary_shell_authority = false -hands_action_authority = false -state_commit_authority = false -publication_authority = false -service_lifecycle_authority = false -cross_body_mutation_authority = false -private_verse_rummaging = false -"#; - let request = parse_repo_tool_request(text).expect("fixture is typed TOML"); - assert!(request.authority.direct_tool_execution); - assert!(!request.has_authority_seals()); - } - - #[test] - fn metrics_comment_cannot_counterfeit_spend_seal() { - let text = r#" -schema_version = "epiphany.repo_metrics_request.v0" -safe_action_family = "repo.metrics_request" -summary = "summary" -private_state_exposed = false -[request] -status = "awaiting-metrics-review" -routing_owner = "Self" -accounting_owner = "Bifrost" -review_evidence_owner = "Maintainer" -spend_receipt_required = true -review_load_receipt_required = true -requested_effect = "record-compute-review-and-artifact-accounting" -publication_request_ref = "publication" -credit_request_ref = "credit" -artifact_acceptance_request_ref = "artifact" -[antecedents] -closure_review_required = true -soul_verdict_required = true -mind_commit_required = true -public_proof_required = true -accepted_artifact_required = true -credit_request_required = true -[required_receipts] -closure_review = "epiphany.repo_work_closure_review.v0" -soul_verdict = "epiphany.soul.verification_verdict" -mind_commit = "epiphany.mind.state_commit_receipt" -public_proof = "epiphany.repo_work_public_proof_bundle.v0" -accepted_artifact = "gamecult.artifact.acceptance_receipt.v0" -model_spend = "gamecult.metrics.model_spend_receipt.v0" -review_load = "gamecult.metrics.review_load_receipt.v0" -credit_readback = "gamecult.bifrost.credit_readback_receipt.v0" -[metrics_packet] -requires_model_call_count = true -requires_token_summary = true -requires_cost_availability_status = true -requires_review_duration = true -requires_review_event_count = true -requires_accepted_artifact_ref = true -requires_public_proof_ref = true -requires_credit_readback_ref = true -requires_private_state_redaction_check = true -[authority] -branch_local_only = true -metrics_ledger_authorized = false -# spend_authorized = false -spend_authorized = true -review_load_authorized = false -credit_ledger_authorized = false -github_pr_authorized = false -merge_authorized = false -publication_authorized = false -upstream_sync_authorized = false -hands_action_authorized = false -service_lifecycle_authority = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -bifrost_accounting_required = true -maintainer_review_evidence_required = true -"#; - let request = parse_repo_metrics_request(text).expect("fixture is typed TOML"); - assert!(!request.has_authority_seals()); - } - - #[test] - fn artifact_comment_cannot_counterfeit_acceptance_seal() { - let text = r#" -schema_version = "epiphany.repo_artifact_acceptance_request.v0" -safe_action_family = "repo.artifact_acceptance_request" -summary = "summary" -private_state_exposed = false -[request] -status = "awaiting-artifact-acceptance-review" -routing_owner = "Self" -acceptance_owner = "Maintainer" -accounting_owner = "Bifrost" -acceptance_receipt_required = true -requested_effect = "record-accepted-artifact-for-reviewed-branch-work" -verification_request_ref = "verification" -maintainer_review_request_ref = "review" -publication_request_ref = "publication" -[antecedents] -closure_review_required = true -soul_verdict_required = true -mind_commit_required = true -public_proof_required = true -maintainer_review_required = true -hands_commit_required = true -[required_receipts] -closure_review = "epiphany.repo_work_closure_review.v0" -soul_verdict = "epiphany.soul.verification_verdict" -mind_commit = "epiphany.mind.state_commit_receipt" -public_proof = "epiphany.repo_work_public_proof_bundle.v0" -maintainer_review = "gamecult.maintainer.review_receipt.v0" -hands_commit = "epiphany.hands.commit_receipt" -accepted_artifact = "gamecult.artifact.acceptance_receipt.v0" -[artifact_packet] -requires_artifact_ref = true -requires_commit_sha = true -requires_changed_path_list = true -requires_review_verdict = true -requires_public_proof_ref = true -requires_acceptance_rationale = true -requires_private_state_redaction_check = true -[authority] -branch_local_only = true -# artifact_acceptance_authorized = false -artifact_acceptance_authorized = true -credit_ledger_authorized = false -github_pr_authorized = false -merge_authorized = false -publication_authorized = false -upstream_sync_authorized = false -hands_action_authorized = false -service_lifecycle_authority = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -maintainer_acceptance_authority_required = true -bifrost_accounting_required = true -"#; - let request = parse_repo_artifact_acceptance_request(text).expect("fixture is typed TOML"); - assert!(!request.has_authority_seals()); - } - - #[test] - fn credit_comment_cannot_counterfeit_ledger_seal() { - let text = r#" -schema_version = "epiphany.repo_credit_request.v0" -safe_action_family = "repo.credit_request" -summary = "summary" -private_state_exposed = false -[request] -status = "awaiting-bifrost-credit-review" -requested_owner = "Bifrost" -requested_effect = "record-credit-for-redacted-proof-and-accepted-artifact" -publication_request_ref = "publication" -maintainer_review_request_ref = "review" -pr_request_ref = "pr" -[antecedents] -closure_review_required = true -soul_verdict_required = true -mind_commit_required = true -public_proof_required = true -maintainer_review_required = true -accepted_artifact_required = true -authorship_context_required = true -[required_receipts] -closure_review = "epiphany.repo_work_closure_review.v0" -soul_verdict = "epiphany.soul.verification_verdict" -mind_commit = "epiphany.mind.state_commit_receipt" -public_proof = "epiphany.repo_work_public_proof_bundle.v0" -maintainer_review = "gamecult.maintainer.review_receipt.v0" -accepted_artifact = "gamecult.artifact.acceptance_receipt.v0" -credit_ledger = "gamecult.bifrost.credit_receipt.v0" -credit_readback = "gamecult.bifrost.credit_readback_receipt.v0" -[credit_packet] -requires_author_identity = true -requires_reviewer_identity = true -requires_accepted_artifact_ref = true -requires_public_proof_ref = true -requires_changed_path_list = true -requires_credit_ledger_target = true -requires_private_state_redaction_check = true -[authority] -branch_local_only = true -# credit_ledger_authorized = false -credit_ledger_authorized = true -bifrost_publication_authorized = false -github_pr_authorized = false -merge_authorized = false -publication_authorized = false -upstream_sync_authorized = false -hands_action_authorized = false -service_lifecycle_authority = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -bifrost_credit_authority_required = true -"#; - let request = parse_repo_credit_request(text).expect("fixture is typed TOML"); - assert!(!request.has_authority_seals()); - } - - #[test] - fn publication_comment_cannot_counterfeit_bifrost_seal() { - let text = r#" -schema_version = "epiphany.repo_publication_request.v0" -safe_action_family = "repo.publication_request" -summary = "summary" -private_state_exposed = false -[request] -status = "awaiting-bifrost-review" -requested_owner = "Bifrost" -requested_effect = "publish-redacted-proof-and-route-maintainer-review" -verification_request_ref = "verification" -[antecedents] -closure_review_required = true -soul_verdict_required = true -mind_commit_required = true -public_proof_export_required = true -private_state_redaction_required = true -[required_receipts] -closure_review = "epiphany.repo_work_closure_review.v0" -soul_verdict = "epiphany.soul.verification_verdict" -mind_commit = "epiphany.mind.state_commit_receipt" -public_proof = "epiphany.repo_work_public_proof_bundle.v0" -bifrost_publication = "gamecult.bifrost.public_proof_publication_receipt.v0" -github_publication = "gamecult.github.publication_receipt.v0" -credit_ledger = "gamecult.bifrost.credit_receipt.v0" -upstream_sync = "epiphany.repo_work_upstream_main_sync.v0" -[public_export] -redacted_only = true -raw_receipts_allowed = false -private_paths_allowed = false -worker_thought_allowed = false -operator_context_allowed = false -credit_required = true -[authority] -branch_local_only = true -# bifrost_publication_authorized = false -bifrost_publication_authorized = true -github_publication_authorized = false -credit_ledger_authorized = false -merge_authorized = false -upstream_sync_authorized = false -hands_action_authorized = false -service_lifecycle_authority = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -maintainer_review_required = true -"#; - let request = parse_repo_publication_request(text).expect("fixture is typed TOML"); - assert!(!request.has_authority_seals()); - } - - #[test] - fn sync_comment_cannot_counterfeit_push_seal() { - let text = r#" -schema_version = "epiphany.repo_sync_request.v0" -safe_action_family = "repo.sync_request" -summary = "summary" -private_state_exposed = false -[request] -status = "awaiting-upstream-main-proof" -proof_owner = "Bifrost" -requested_effect = "prove-published-commit-contained-by-upstream-main" -publication_request_ref = "publication" -[antecedents] -publication_receipt_required = true -github_publication_required = true -maintainer_review_required = true -credit_ledger_required = true -public_proof_required = true -[required_receipts] -bifrost_publication = "gamecult.bifrost.public_proof_publication_receipt.v0" -github_publication = "gamecult.github.publication_receipt.v0" -maintainer_review = "gamecult.maintainer.review_receipt.v0" -credit_ledger = "gamecult.bifrost.credit_receipt.v0" -upstream_sync = "epiphany.repo_work_upstream_main_sync.v0" -ancestry_proof = "git.merge_base_is_ancestor" -[sync_proof] -target_ref = "origin/main" -requires_fetch_before_check = true -requires_merge_base_ancestor_check = true -requires_clean_public_proof_readback = true -records_upstream_main_sha = true -[authority] -branch_local_only = true -merge_authorized = false -# push_authorized = false -push_authorized = true -upstream_sync_authorized = false -github_publication_authorized = false -credit_ledger_authorized = false -hands_action_authorized = false -service_lifecycle_authority = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -bifrost_upstream_proof_required = true -maintainer_review_receipt_required = true -"#; - let request = parse_repo_sync_request(text).expect("fixture is typed TOML"); - assert!(!request.has_authority_seals()); - } - - #[test] - fn pr_comment_cannot_counterfeit_github_seal() { - let text = r#" -schema_version = "epiphany.repo_pr_request.v0" -safe_action_family = "repo.pr_request" -summary = "summary" -private_state_exposed = false -[request] -status = "awaiting-pr-publication-review" -routing_owner = "Self" -publication_owner = "Bifrost" -execution_owner = "Hands" -provider = "GitHub" -provider_receipt_required = true -requested_effect = "open-or-update-review-pr-from-redacted-proof-and-maintainer-context" -maintainer_review_request_ref = "review" -publication_request_ref = "publication" -sync_request_ref = "sync" -[antecedents] -closure_review_required = true -soul_verdict_required = true -mind_commit_required = true -public_proof_required = true -maintainer_review_required = true -bifrost_publication_required = true -credit_ledger_required = true -[required_receipts] -closure_review = "epiphany.repo_work_closure_review.v0" -soul_verdict = "epiphany.soul.verification_verdict" -mind_commit = "epiphany.mind.state_commit_receipt" -public_proof = "epiphany.repo_work_public_proof_bundle.v0" -maintainer_review = "gamecult.maintainer.review_receipt.v0" -bifrost_publication = "gamecult.bifrost.public_proof_publication_receipt.v0" -credit_ledger = "gamecult.bifrost.credit_receipt.v0" -pr_publication = "gamecult.github.pull_request_publication_receipt.v0" -[pr_packet] -base_ref = "origin/main" -requires_branch_name = true -requires_title = true -requires_body = true -requires_changed_path_list = true -requires_public_proof_ref = true -requires_maintainer_review_ref = true -requires_credit_ref = true -requires_private_state_redaction_check = true -[authority] -branch_local_only = true -# github_pr_authorized = false -github_pr_authorized = true -branch_push_authorized = false -merge_authorized = false -publication_authorized = false -upstream_sync_authorized = false -hands_action_authorized = false -service_lifecycle_authority = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -maintainer_review_required = true -bifrost_publication_gate_required = true -hands_execution_required = true -github_provider_receipt_required = true -"#; - let request = parse_repo_pr_request(text).expect("fixture is typed TOML"); - assert!(!request.has_authority_seals()); - } - - #[test] - fn maintainer_comment_cannot_counterfeit_approval_seal() { - let text = r#" -schema_version = "epiphany.repo_maintainer_review_request.v0" -safe_action_family = "repo.maintainer_review_request" -summary = "summary" -private_state_exposed = false -[request] -status = "awaiting-maintainer-review" -requested_owner = "Maintainer" -requested_effect = "review-redacted-proof-and-branch-diff" -verification_request_ref = "verification" -publication_request_ref = "publication" -[antecedents] -closure_review_required = true -soul_verdict_required = true -mind_commit_required = true -public_proof_required = true -bifrost_publication_request_required = true -[required_receipts] -closure_review = "epiphany.repo_work_closure_review.v0" -soul_verdict = "epiphany.soul.verification_verdict" -mind_commit = "epiphany.mind.state_commit_receipt" -public_proof = "epiphany.repo_work_public_proof_bundle.v0" -maintainer_review = "gamecult.maintainer.review_receipt.v0" -bifrost_publication = "gamecult.bifrost.public_proof_publication_receipt.v0" -[review_packet] -requires_reviewer_identity = true -requires_review_verdict = true -allowed_verdicts = ["approved", "changes-requested", "rejected", "needs-human-context"] -requires_changed_path_list = true -requires_public_proof_ref = true -requires_private_state_redaction_check = true -[authority] -branch_local_only = true -# maintainer_approval_authorized = false -maintainer_approval_authorized = true -merge_authorized = false -push_authorized = false -publication_authorized = false -upstream_sync_authorized = false -hands_action_authorized = false -service_lifecycle_authority = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -maintainer_response_required = true -"#; - let request = parse_repo_maintainer_review_request(text).expect("fixture is typed TOML"); - assert!(!request.has_authority_seals()); - } -} diff --git a/epiphany-core/src/bin/epiphany_work/closure_contracts/operations.rs b/epiphany-core/src/bin/epiphany_work/closure_contracts/operations.rs deleted file mode 100644 index 94f84fdf..00000000 --- a/epiphany-core/src/bin/epiphany_work/closure_contracts/operations.rs +++ /dev/null @@ -1,686 +0,0 @@ -#[derive(Debug, Deserialize)] -pub(super) struct RepoDeploymentConfig { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - pub(super) deployment: RepoDeploymentSettings, - pub(super) cultmesh: RepoDeploymentCultMesh, - pub(super) required_receipts: RepoDeploymentRequiredReceipts, - pub(super) authority: RepoDeploymentAuthority, -} - -impl RepoDeploymentConfig { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_deployment_config.v0" - && self.safe_action_family == "repo.deployment_config" - } - - pub(super) fn has_idunn_trigger_contract(&self) -> bool { - let deployment = &self.deployment; - !deployment.enabled - && deployment.owner == "Idunn" - && deployment.trigger == "git-push-observed-by-idunn" - && deployment.watched_ref == "refs/heads/main" - && deployment.deployment_script_ref == "deploy/idunn-deploy.ps1" - && deployment.deployment_script_hash_required - && deployment.deployment_script_review_required - && deployment.host_access_policy_ref_required - && !deployment.secret_values_embedded - && deployment.rollback_plan_ref_required - && deployment.aftercare_checks_required - && deployment.idunn_receipt_required - && deployment.aftercare_audit_required - } - - pub(super) fn has_cultmesh_contract(&self) -> bool { - let cultmesh = &self.cultmesh; - cultmesh.local_verse == "gamecult-local" - && cultmesh.capability_family == "gamecult.idunn.deployment" - && cultmesh.intent_contract == "gamecult.idunn.deployment_intent.v0" - && cultmesh.receipt_contract == "gamecult.idunn.deployment_receipt.v0" - && cultmesh.aftercare_contract == "gamecult.idunn.deployment_aftercare_audit.v0" - && cultmesh.daemon_owns_execution - } - - pub(super) fn has_required_receipt_contract(&self) -> bool { - let receipts = &self.required_receipts; - receipts.mind_adoption == "epiphany.repo_work_plan_adoption_review.v0" - && receipts.soul_review == "epiphany.repo_work_closure_review.v0" - && receipts.maintainer_review == "gamecult.maintainer.review_receipt.v0" - && receipts.secret_policy == "epiphany.repo_secret_policy_request.v0" - && receipts.idunn_deployment == "gamecult.idunn.deployment_receipt.v0" - && receipts.aftercare_audit == "gamecult.idunn.deployment_aftercare_audit.v0" - } - - pub(super) fn has_authority_seals(&self) -> bool { - let authority = &self.authority; - authority.configuration_only - && !authority.direct_deployment_authority - && !authority.direct_ssh_authority - && !authority.direct_git_push_authority - && !authority.direct_service_lifecycle_authority - && !authority.direct_hands_authority - && !authority.publication_authorized - && !authority.merge_authorized - && !authority.cross_body_mutation_authorized - && !authority.private_verse_rummaging - && authority.idunn_deployment_authority_required - } -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDeploymentSettings { - pub(super) enabled: bool, - pub(super) owner: String, - pub(super) trigger: String, - pub(super) watched_ref: String, - pub(super) deployment_script_ref: String, - pub(super) deployment_script_hash_required: bool, - pub(super) deployment_script_review_required: bool, - pub(super) host_access_policy_ref_required: bool, - pub(super) secret_values_embedded: bool, - pub(super) rollback_plan_ref_required: bool, - pub(super) aftercare_checks_required: bool, - pub(super) idunn_receipt_required: bool, - pub(super) aftercare_audit_required: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDeploymentCultMesh { - pub(super) local_verse: String, - pub(super) capability_family: String, - pub(super) intent_contract: String, - pub(super) receipt_contract: String, - pub(super) aftercare_contract: String, - pub(super) daemon_owns_execution: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDeploymentRequiredReceipts { - pub(super) mind_adoption: String, - pub(super) soul_review: String, - pub(super) maintainer_review: String, - pub(super) secret_policy: String, - pub(super) idunn_deployment: String, - pub(super) aftercare_audit: String, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDeploymentAuthority { - pub(super) configuration_only: bool, - pub(super) direct_deployment_authority: bool, - pub(super) direct_ssh_authority: bool, - pub(super) direct_git_push_authority: bool, - pub(super) direct_service_lifecycle_authority: bool, - pub(super) direct_hands_authority: bool, - pub(super) publication_authorized: bool, - pub(super) merge_authorized: bool, - pub(super) cross_body_mutation_authorized: bool, - pub(super) private_verse_rummaging: bool, - pub(super) idunn_deployment_authority_required: bool, -} - -pub(super) fn parse_repo_deployment_config(text: &str) -> Result { - toml::from_str(text).context("deployment config is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoSecretPolicyRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - pub(super) request: RepoSecretPolicyRequestBody, - pub(super) antecedents: RepoSecretPolicyAntecedents, - pub(super) required_receipts: RepoSecretPolicyReceipts, - pub(super) security_packet: RepoSecretPolicyPacket, - pub(super) authority: RepoSecretPolicyAuthority, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoSecretPolicyRequestBody { - pub(super) status: String, - pub(super) routing_owner: String, - pub(super) required_reviewers: Vec, - pub(super) policy_admission_owner: String, - pub(super) requested_effect: String, - pub(super) requires_secret_inventory_without_values: bool, - pub(super) requires_write_permission_scope: bool, - pub(super) requires_public_private_export_boundary: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoSecretPolicyAntecedents { - pub(super) source_grounding_required: bool, - pub(super) soul_review_required: bool, - pub(super) mind_adoption_required: bool, - pub(super) maintainer_review_required: bool, - pub(super) bifrost_publication_review_required: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoSecretPolicyReceipts { - pub(super) source_grounding: String, - pub(super) soul_review: String, - pub(super) mind_adoption: String, - pub(super) maintainer_review: String, - pub(super) bifrost_publication_review: String, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoSecretPolicyPacket { - pub(super) requires_secret_locations_without_values: bool, - pub(super) requires_credential_owner: bool, - pub(super) requires_write_scope_matrix: bool, - pub(super) requires_public_export_redaction_rules: bool, - pub(super) requires_deployment_authority_owner: bool, - pub(super) requires_incident_rollback_plan: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoSecretPolicyAuthority { - pub(super) direct_secret_access_authority: bool, - pub(super) secret_value_materialization: bool, - pub(super) write_permission_authority: bool, - pub(super) deployment_authority: bool, - pub(super) publication_authorized: bool, - pub(super) merge_authorized: bool, - pub(super) service_lifecycle_authority: bool, - pub(super) cross_body_mutation_authorized: bool, - pub(super) private_verse_rummaging: bool, - pub(super) maintainer_security_review_required: bool, - pub(super) soul_security_verification_required: bool, - pub(super) mind_policy_admission_required: bool, - pub(super) bifrost_publication_review_required: bool, -} - -impl RepoSecretPolicyRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_secret_policy_request.v0" - && self.safe_action_family == "repo.secret_policy_request" - } - - pub(super) fn awaits_security_review(&self) -> bool { - let request = &self.request; - request.status == "awaiting-security-review" - && request.routing_owner == "Self" - && request.required_reviewers == ["Maintainer", "Soul", "Mind", "Bifrost"] - && request.policy_admission_owner == "Mind" - && request.requested_effect == "review-repo-secret-and-write-permission-policy" - && request.requires_secret_inventory_without_values - && request.requires_write_permission_scope - && request.requires_public_private_export_boundary - } - - pub(super) fn has_review_antecedents(&self) -> bool { - let antecedents = &self.antecedents; - antecedents.source_grounding_required - && antecedents.soul_review_required - && antecedents.mind_adoption_required - && antecedents.maintainer_review_required - && antecedents.bifrost_publication_review_required - } - - pub(super) fn has_receipt_contract(&self) -> bool { - let receipts = &self.required_receipts; - receipts.source_grounding == "epiphany.eyes.evidence_packet" - && receipts.soul_review == "epiphany.repo_work_closure_review.v0" - && receipts.mind_adoption == "epiphany.repo_work_plan_adoption_review.v0" - && receipts.maintainer_review == "gamecult.maintainer.review_receipt.v0" - && receipts.bifrost_publication_review - == "gamecult.bifrost.publication_review_receipt.v0" - } - - pub(super) fn has_security_packet_contract(&self) -> bool { - let packet = &self.security_packet; - packet.requires_secret_locations_without_values - && packet.requires_credential_owner - && packet.requires_write_scope_matrix - && packet.requires_public_export_redaction_rules - && packet.requires_deployment_authority_owner - && packet.requires_incident_rollback_plan - } - - pub(super) fn has_authority_seals(&self) -> bool { - let authority = &self.authority; - !authority.direct_secret_access_authority - && !authority.secret_value_materialization - && !authority.write_permission_authority - && !authority.deployment_authority - && !authority.publication_authorized - && !authority.merge_authorized - && !authority.service_lifecycle_authority - && !authority.cross_body_mutation_authorized - && !authority.private_verse_rummaging - && authority.maintainer_security_review_required - && authority.soul_security_verification_required - && authority.mind_policy_admission_required - && authority.bifrost_publication_review_required - } -} - -pub(super) fn parse_repo_secret_policy_request(text: &str) -> Result { - toml::from_str(text).context("secret policy request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDependencyPolicyRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - pub(super) request: RepoDependencyPolicyRequestBody, - pub(super) antecedents: RepoDependencyPolicyAntecedents, - pub(super) required_receipts: RepoDependencyPolicyReceipts, - pub(super) dependency_packet: RepoDependencyPolicyPacket, - pub(super) authority: RepoDependencyPolicyAuthority, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDependencyPolicyRequestBody { - pub(super) status: String, - pub(super) routing_owner: String, - pub(super) required_reviewers: Vec, - pub(super) policy_admission_owner: String, - pub(super) requested_effect: String, - pub(super) requires_manifest_inventory: bool, - pub(super) requires_lockfile_policy: bool, - pub(super) requires_package_manager_command_review: bool, - pub(super) requires_network_fetch_policy: bool, - pub(super) requires_vulnerability_review: bool, - pub(super) requires_license_review: bool, - pub(super) requires_rollback_plan: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDependencyPolicyAntecedents { - pub(super) source_grounding_required: bool, - pub(super) eyes_evidence_required: bool, - pub(super) soul_review_required: bool, - pub(super) mind_adoption_required: bool, - pub(super) maintainer_review_required: bool, - pub(super) bifrost_publication_review_required: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDependencyPolicyReceipts { - pub(super) source_grounding: String, - pub(super) soul_review: String, - pub(super) mind_adoption: String, - pub(super) maintainer_review: String, - pub(super) bifrost_publication_review: String, - pub(super) dependency_audit: String, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDependencyPolicyPacket { - pub(super) requires_manifest_paths: bool, - pub(super) requires_lockfile_paths: bool, - pub(super) requires_package_manager_commands: bool, - pub(super) requires_vulnerability_sources: bool, - pub(super) requires_license_constraints: bool, - pub(super) requires_vendored_code_policy: bool, - pub(super) requires_update_cadence: bool, - pub(super) requires_private_state_redaction_check: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDependencyPolicyAuthority { - pub(super) direct_dependency_update_authority: bool, - pub(super) direct_package_install_authority: bool, - pub(super) direct_lockfile_mutation_authority: bool, - pub(super) direct_network_fetch_authority: bool, - pub(super) direct_ci_mutation_authority: bool, - pub(super) direct_hands_authority: bool, - pub(super) publication_authorized: bool, - pub(super) merge_authorized: bool, - pub(super) deployment_authority: bool, - pub(super) service_lifecycle_authority: bool, - pub(super) cross_body_mutation_authorized: bool, - pub(super) private_verse_rummaging: bool, - pub(super) maintainer_dependency_review_required: bool, - pub(super) soul_dependency_verification_required: bool, - pub(super) mind_policy_admission_required: bool, - pub(super) bifrost_publication_review_required: bool, - pub(super) supply_chain_audit_required: bool, -} - -impl RepoDependencyPolicyRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_dependency_policy_request.v0" - && self.safe_action_family == "repo.dependency_policy_request" - } - - pub(super) fn awaits_review(&self) -> bool { - let request = &self.request; - request.status == "awaiting-dependency-policy-review" - && request.routing_owner == "Self" - && request.required_reviewers == ["Maintainer", "Soul", "Mind", "Bifrost"] - && request.policy_admission_owner == "Mind" - && request.requested_effect == "review-repo-dependency-and-supply-chain-policy" - && request.requires_manifest_inventory - && request.requires_lockfile_policy - && request.requires_package_manager_command_review - && request.requires_network_fetch_policy - && request.requires_vulnerability_review - && request.requires_license_review - && request.requires_rollback_plan - } - - pub(super) fn has_antecedents(&self) -> bool { - let value = &self.antecedents; - value.source_grounding_required - && value.eyes_evidence_required - && value.soul_review_required - && value.mind_adoption_required - && value.maintainer_review_required - && value.bifrost_publication_review_required - } - - pub(super) fn has_receipt_contract(&self) -> bool { - let value = &self.required_receipts; - value.source_grounding == "epiphany.eyes.evidence_packet" - && value.soul_review == "epiphany.repo_work_closure_review.v0" - && value.mind_adoption == "epiphany.repo_work_plan_adoption_review.v0" - && value.maintainer_review == "gamecult.maintainer.review_receipt.v0" - && value.bifrost_publication_review == "gamecult.bifrost.publication_review_receipt.v0" - && value.dependency_audit == "gamecult.supply_chain.dependency_audit_receipt.v0" - } - - pub(super) fn has_packet_contract(&self) -> bool { - let value = &self.dependency_packet; - value.requires_manifest_paths - && value.requires_lockfile_paths - && value.requires_package_manager_commands - && value.requires_vulnerability_sources - && value.requires_license_constraints - && value.requires_vendored_code_policy - && value.requires_update_cadence - && value.requires_private_state_redaction_check - } - - pub(super) fn has_authority_seals(&self) -> bool { - let value = &self.authority; - !value.direct_dependency_update_authority - && !value.direct_package_install_authority - && !value.direct_lockfile_mutation_authority - && !value.direct_network_fetch_authority - && !value.direct_ci_mutation_authority - && !value.direct_hands_authority - && !value.publication_authorized - && !value.merge_authorized - && !value.deployment_authority - && !value.service_lifecycle_authority - && !value.cross_body_mutation_authorized - && !value.private_verse_rummaging - && value.maintainer_dependency_review_required - && value.soul_dependency_verification_required - && value.mind_policy_admission_required - && value.bifrost_publication_review_required - && value.supply_chain_audit_required - } -} - -pub(super) fn parse_repo_dependency_policy_request( - text: &str, -) -> Result { - toml::from_str(text).context("dependency policy request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDeploymentRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - pub(super) request: RepoDeploymentRequestBody, - pub(super) antecedents: RepoDeploymentRequestAntecedents, - pub(super) required_receipts: RepoDeploymentRequestReceipts, - pub(super) deployment_packet: RepoDeploymentRequestPacket, - pub(super) authority: RepoDeploymentRequestAuthority, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDeploymentRequestBody { - pub(super) status: String, - pub(super) routing_owner: String, - pub(super) required_reviewers: Vec, - pub(super) execution_owner: String, - pub(super) requested_effect: String, - pub(super) deployment_trigger: String, - pub(super) requires_explicit_deployment_policy: bool, - pub(super) requires_idunn_receipt: bool, - pub(super) requires_aftercare_audit: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDeploymentRequestAntecedents { - pub(super) source_grounding_required: bool, - pub(super) mind_adoption_required: bool, - pub(super) soul_review_required: bool, - pub(super) maintainer_review_required: bool, - pub(super) secret_policy_review_required: bool, - pub(super) bifrost_publication_review_required: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDeploymentRequestReceipts { - pub(super) source_grounding: String, - pub(super) mind_adoption: String, - pub(super) soul_review: String, - pub(super) maintainer_review: String, - pub(super) secret_policy: String, - pub(super) bifrost_publication_review: String, - pub(super) idunn_deployment: String, - pub(super) aftercare_audit: String, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDeploymentRequestPacket { - pub(super) requires_target_environment: bool, - pub(super) requires_watched_ref: bool, - pub(super) requires_source_commit_sha: bool, - pub(super) requires_deployment_script_ref: bool, - pub(super) requires_script_hash: bool, - pub(super) requires_script_review_ref: bool, - pub(super) requires_host_access_policy_ref: bool, - pub(super) requires_secret_policy_ref: bool, - pub(super) requires_rollback_plan: bool, - pub(super) requires_aftercare_checks: bool, -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDeploymentRequestAuthority { - pub(super) direct_deployment_authority: bool, - pub(super) direct_ssh_authority: bool, - pub(super) direct_git_push_authority: bool, - pub(super) direct_service_lifecycle_authority: bool, - pub(super) direct_hands_authority: bool, - pub(super) publication_authorized: bool, - pub(super) merge_authorized: bool, - pub(super) cross_body_mutation_authorized: bool, - pub(super) private_verse_rummaging: bool, - pub(super) idunn_deployment_authority_required: bool, -} - -impl RepoDeploymentRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_deployment_request.v0" - && self.safe_action_family == "repo.deployment_request" - } - - pub(super) fn awaits_idunn_review(&self) -> bool { - let value = &self.request; - value.status == "awaiting-idunn-review" - && value.routing_owner == "Self" - && value.required_reviewers == ["Maintainer", "Soul", "Mind", "Bifrost"] - && value.execution_owner == "Idunn" - && value.requested_effect == "review-repo-deployment-trigger-and-script" - && value.deployment_trigger == "git-push-observed-by-idunn" - && value.requires_explicit_deployment_policy - && value.requires_idunn_receipt - && value.requires_aftercare_audit - } - - pub(super) fn has_antecedents(&self) -> bool { - let value = &self.antecedents; - value.source_grounding_required - && value.mind_adoption_required - && value.soul_review_required - && value.maintainer_review_required - && value.secret_policy_review_required - && value.bifrost_publication_review_required - } - - pub(super) fn has_receipt_contract(&self) -> bool { - let value = &self.required_receipts; - value.source_grounding == "epiphany.eyes.evidence_packet" - && value.mind_adoption == "epiphany.repo_work_plan_adoption_review.v0" - && value.soul_review == "epiphany.repo_work_closure_review.v0" - && value.maintainer_review == "gamecult.maintainer.review_receipt.v0" - && value.secret_policy == "epiphany.repo_secret_policy_request.v0" - && value.bifrost_publication_review == "gamecult.bifrost.publication_review_receipt.v0" - && value.idunn_deployment == "gamecult.idunn.deployment_receipt.v0" - && value.aftercare_audit == "gamecult.idunn.deployment_aftercare_audit.v0" - } - - pub(super) fn has_packet_contract(&self) -> bool { - let value = &self.deployment_packet; - value.requires_target_environment - && value.requires_watched_ref - && value.requires_source_commit_sha - && value.requires_deployment_script_ref - && value.requires_script_hash - && value.requires_script_review_ref - && value.requires_host_access_policy_ref - && value.requires_secret_policy_ref - && value.requires_rollback_plan - && value.requires_aftercare_checks - } - - pub(super) fn has_authority_seals(&self) -> bool { - let value = &self.authority; - !value.direct_deployment_authority - && !value.direct_ssh_authority - && !value.direct_git_push_authority - && !value.direct_service_lifecycle_authority - && !value.direct_hands_authority - && !value.publication_authorized - && !value.merge_authorized - && !value.cross_body_mutation_authorized - && !value.private_verse_rummaging - && value.idunn_deployment_authority_required - } -} - -pub(super) fn parse_repo_deployment_request(text: &str) -> Result { - toml::from_str(text).context("deployment request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoDoctrineUpdateRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - request: RepoDoctrineRequestBody, - antecedents: std::collections::BTreeMap, - required_receipts: std::collections::BTreeMap, - doctrine_packet: std::collections::BTreeMap, - authority: std::collections::BTreeMap, -} -impl RepoDoctrineUpdateRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_doctrine_update_request.v0" - && self.safe_action_family == "repo.doctrine_update_request" - } - pub(super) fn has_coherent_routing(&self) -> bool { - let r = &self.request; - r.status == "awaiting-doctrine-review" - && r.routing_owner == "Self" - && r.required_reviewers == ["Maintainer", "Mind", "Soul"] - && r.doctrine_admission_owner == "Mind" - && r.mutation_owner == "Hands" - && r.requested_effect == "review-repo-agent-doctrine-update" - && r.doctrine_target == "AGENTS.md" - && r.requires_source_grounding - && r.maintainer_review_required - } - pub(super) fn has_antecedent_contract(&self) -> bool { - [ - "persona_or_human_feedback_required", - "imagination_plan_required", - "mind_adoption_required", - "soul_review_required", - "maintainer_review_required", - ] - .iter() - .all(|key| self.antecedents.get(*key) == Some(&true)) - } - pub(super) fn has_receipt_contract(&self) -> bool { - [ - ( - "imagination_plan", - "epiphany.repo_work_imagination_action_items_receipt.v0", - ), - ( - "mind_adoption", - "epiphany.repo_work_plan_adoption_review.v0", - ), - ("soul_review", "epiphany.repo_work_closure_review.v0"), - ("maintainer_review", "gamecult.maintainer.review_receipt.v0"), - ("hands_commit", "epiphany.hands.commit_receipt"), - ] - .iter() - .all(|(key, value)| self.required_receipts.get(*key).is_some_and(|v| v == value)) - } - pub(super) fn has_packet_contract(&self) -> bool { - [ - "requires_current_doctrine_ref", - "requires_proposed_change_summary", - "requires_invariant_impact", - "requires_rehydration_impact", - "requires_rollback_plan", - "requires_private_state_redaction_check", - ] - .iter() - .all(|key| self.doctrine_packet.get(*key) == Some(&true)) - } - pub(super) fn has_authority_seals(&self) -> bool { - [ - "direct_doctrine_mutation_authority", - "direct_hands_authority", - "direct_mind_state_commit", - "publication_authorized", - "merge_authorized", - "service_lifecycle_authority", - "cross_body_mutation_authorized", - "private_verse_rummaging", - ] - .iter() - .all(|key| self.authority.get(*key) == Some(&false)) - && [ - "maintainer_review_required", - "mind_admission_required", - "hands_receipts_required", - ] - .iter() - .all(|key| self.authority.get(*key) == Some(&true)) - } -} -#[derive(Debug, Deserialize)] -struct RepoDoctrineRequestBody { - status: String, - routing_owner: String, - required_reviewers: Vec, - doctrine_admission_owner: String, - mutation_owner: String, - requested_effect: String, - doctrine_target: String, - requires_source_grounding: bool, - maintainer_review_required: bool, -} -pub(super) fn parse_repo_doctrine_update_request(text: &str) -> Result { - toml::from_str(text).context("doctrine update request is not valid typed TOML") -} diff --git a/epiphany-core/src/bin/epiphany_work/closure_contracts/preparation.rs b/epiphany-core/src/bin/epiphany_work/closure_contracts/preparation.rs deleted file mode 100644 index cf78c033..00000000 --- a/epiphany-core/src/bin/epiphany_work/closure_contracts/preparation.rs +++ /dev/null @@ -1,311 +0,0 @@ -#[derive(Debug, Deserialize)] -pub(super) struct RepoConsensusBrief { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - consensus: RepoConsensusState, - imagination: RepoConsensusImagination, - inputs: RepoConsensusInputs, - authority: std::collections::BTreeMap, -} -impl RepoConsensusBrief { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_consensus_brief.v0" - && self.safe_action_family == "repo.consensus_brief" - } - pub(super) fn remains_unconverged_draft(&self) -> bool { - self.consensus.status == "draft" - && !self.consensus.converged - && self.consensus.conflicts_remaining - && self.consensus.requires_additional_public_feedback - } - pub(super) fn has_imagination_route(&self) -> bool { - let i = &self.imagination; - i.role == "consensus-discovery" - && i.candidate_actions_non_authoritative - && i.may_emit_action_items_receipt - && i.must_preserve_public_refs - && i.must_not_read_private_verses - } - pub(super) fn has_input_contract(&self) -> bool { - self.inputs.feedback_source == "Persona public discussion" - && self - .inputs - .public_discussion_refs - .iter() - .all(|v| !v.trim().is_empty()) - && self - .inputs - .candidate_action_refs - .iter() - .all(|v| !v.trim().is_empty()) - } - pub(super) fn has_authority_seals(&self) -> bool { - [ - "objective_adoption_authorized", - "hands_action_authorized", - "publication_authorized", - "cross_body_mutation_authorized", - ] - .iter() - .all(|key| self.authority.get(*key) == Some(&false)) - && self.authority.get("mind_adoption_required") == Some(&true) - && self.authority.get("bifrost_publication_required") == Some(&true) - } -} -#[derive(Debug, Deserialize)] -struct RepoConsensusState { - status: String, - converged: bool, - conflicts_remaining: bool, - requires_additional_public_feedback: bool, -} -#[derive(Debug, Deserialize)] -struct RepoConsensusImagination { - role: String, - candidate_actions_non_authoritative: bool, - may_emit_action_items_receipt: bool, - must_preserve_public_refs: bool, - must_not_read_private_verses: bool, -} -#[derive(Debug, Deserialize)] -struct RepoConsensusInputs { - public_discussion_refs: Vec, - candidate_action_refs: Vec, - feedback_source: String, -} -pub(super) fn parse_repo_consensus_brief(text: &str) -> Result { - toml::from_str(text).context("consensus brief is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoInterpreterBrief { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - interpreter: RepoInterpreterRequest, - semantic_checks: std::collections::BTreeMap, - allowed_outputs: RepoInterpreterOutputs, - required_gates: std::collections::BTreeMap, - authority: std::collections::BTreeMap, -} - -impl RepoInterpreterBrief { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_interpreter_brief.v0" - && self.safe_action_family == "repo.interpreter_brief" - } - pub(super) fn is_imagination_request_for_mind(&self) -> bool { - let i = &self.interpreter; - i.status == "awaiting-mind-interpretation" - && i.authoring_owner == "Imagination" - && i.requested_interpreter == "Mind" - && !i.interpretation_admitted - && i.purpose == "public-pressure-to-action-semantics" - && i.requires_consensus_readback - && i.requires_safe_family_choice - && i.requires_requested_paths - && i.requires_verification_asks - && i.requires_evidence_needs - && i.candidate_actions_non_authoritative - } - pub(super) fn has_semantic_checks(&self) -> bool { - [ - "intent_summary_required", - "scope_boundary_required", - "requested_paths_required", - "verification_required", - "evidence_required", - "rollback_required", - "non_goals_required", - "open_questions_required", - "consensus_alignment_required", - ] - .iter() - .all(|key| self.semantic_checks.get(*key) == Some(&true)) - } - pub(super) fn has_allowed_outputs(&self) -> bool { - let o = &self.allowed_outputs; - o.candidate_safe_families - == [ - "repo.consensus_brief", - "repo.objective_draft", - "repo.adoption_request", - "repo.work_order", - "repo.verification_request", - "repo.publication_request", - ] - && o.may_request_replanning - && o.may_request_more_consensus - && !o.may_adopt_objective - && !o.may_schedule_work - && !o.may_touch_substrate - && !o.may_publish - && !o.may_deploy - } - pub(super) fn has_required_gates(&self) -> bool { - [ - "imagination_consensus_required", - "mind_review_required", - "soul_source_grounding_required", - "bifrost_publication_review_required", - "hands_receipt_required_before_state_change", - "substrate_receipt_required_before_mutation", - "idunn_receipt_required_before_deployment", - ] - .iter() - .all(|key| self.required_gates.get(*key) == Some(&true)) - } - pub(super) fn has_authority_seals(&self) -> bool { - [ - "direct_state_commit_authorized", - "objective_adoption_authorized", - "self_scheduling_authorized", - "substrate_access_authorized", - "hands_action_authorized", - "shell_command_authorized", - "commit_authorized", - "publication_authorized", - "deployment_execution_authority", - "cross_body_mutation_authorized", - "private_worker_transcripts_allowed", - "raw_result_payloads_allowed", - "private_state_exposed", - ] - .iter() - .all(|key| self.authority.get(*key) == Some(&false)) - } -} - -#[derive(Debug, Deserialize)] -struct RepoInterpreterRequest { - status: String, - authoring_owner: String, - requested_interpreter: String, - interpretation_admitted: bool, - purpose: String, - requires_consensus_readback: bool, - requires_safe_family_choice: bool, - requires_requested_paths: bool, - requires_verification_asks: bool, - requires_evidence_needs: bool, - candidate_actions_non_authoritative: bool, -} -#[derive(Debug, Deserialize)] -struct RepoInterpreterOutputs { - candidate_safe_families: Vec, - may_request_replanning: bool, - may_request_more_consensus: bool, - may_adopt_objective: bool, - may_schedule_work: bool, - may_touch_substrate: bool, - may_publish: bool, - may_deploy: bool, -} -pub(super) fn parse_repo_interpreter_brief(text: &str) -> Result { - toml::from_str(text).context("interpreter brief is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoObjectiveDraft { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - draft: RepoObjectiveDraftState, - acceptance: RepoObjectiveDraftAcceptance, - inputs: RepoObjectiveDraftInputs, - authority: RepoObjectiveDraftAuthority, -} - -impl RepoObjectiveDraft { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_objective_draft.v0" - && self.safe_action_family == "repo.objective_draft" - } - - pub(super) fn remains_imagination_draft(&self) -> bool { - let d = &self.draft; - d.status == "review-required" - && d.owner == "Imagination" - && d.adoption_gate == "Mind" - && d.scheduler_gate == "Self" - && d.publication_gate == "Bifrost" - && !d.objective_adopted - } - - pub(super) fn has_acceptance_contract(&self) -> bool { - self.acceptance.criteria - == [ - "Mind explicitly accepts or rejects this Objective Draft before Self schedules it.", - "Self schedules only after Mind adoption and a safe-family action plan exist.", - "Hands acts only through a later receipt-backed plan and declared path scope.", - "Bifrost gates publication, credit, and upstream-main sync.", - ] - } - - pub(super) fn has_input_contract(&self) -> bool { - self.inputs.consensus_brief_required - && self - .inputs - .public_discussion_refs - .iter() - .all(|v| !v.trim().is_empty()) - && self - .inputs - .candidate_action_refs - .iter() - .all(|v| !v.trim().is_empty()) - } - - pub(super) fn has_authority_seals(&self) -> bool { - let a = &self.authority; - a.branch_local_only - && !a.objective_adoption_authorized - && !a.self_scheduling_authorized - && !a.hands_action_authorized - && !a.publication_authorized - && !a.cross_body_mutation_authorized - && a.mind_adoption_required - && a.bifrost_publication_required - } -} - -#[derive(Debug, Deserialize)] -struct RepoObjectiveDraftState { - status: String, - owner: String, - adoption_gate: String, - scheduler_gate: String, - publication_gate: String, - objective_adopted: bool, -} -#[derive(Debug, Deserialize)] -struct RepoObjectiveDraftAcceptance { - criteria: Vec, -} -#[derive(Debug, Deserialize)] -struct RepoObjectiveDraftInputs { - public_discussion_refs: Vec, - candidate_action_refs: Vec, - consensus_brief_required: bool, -} -#[derive(Debug, Deserialize)] -struct RepoObjectiveDraftAuthority { - branch_local_only: bool, - objective_adoption_authorized: bool, - self_scheduling_authorized: bool, - hands_action_authorized: bool, - publication_authorized: bool, - cross_body_mutation_authorized: bool, - mind_adoption_required: bool, - bifrost_publication_required: bool, -} - -pub(super) fn parse_repo_objective_draft(text: &str) -> Result { - toml::from_str(text).context("objective draft is not valid typed TOML") -} - -include!("preparation_tests.rs"); diff --git a/epiphany-core/src/bin/epiphany_work/closure_contracts/preparation_tests.rs b/epiphany-core/src/bin/epiphany_work/closure_contracts/preparation_tests.rs deleted file mode 100644 index ef99ffc5..00000000 --- a/epiphany-core/src/bin/epiphany_work/closure_contracts/preparation_tests.rs +++ /dev/null @@ -1,112 +0,0 @@ -#[cfg(test)] -mod preparation_tests { - use super::*; - - #[test] - fn consensus_comment_cannot_counterfeit_adoption_seal() { - let text = r#" -schema_version = "epiphany.repo_consensus_brief.v0" -safe_action_family = "repo.consensus_brief" -summary = "summary" -private_state_exposed = false -[consensus] -status = "draft" -converged = false -conflicts_remaining = true -requires_additional_public_feedback = true -[imagination] -role = "consensus-discovery" -candidate_actions_non_authoritative = true -may_emit_action_items_receipt = true -must_preserve_public_refs = true -must_not_read_private_verses = true -[inputs] -public_discussion_refs = [] -candidate_action_refs = [] -feedback_source = "Persona public discussion" -[authority] -# objective_adoption_authorized = false -objective_adoption_authorized = true -hands_action_authorized = false -publication_authorized = false -cross_body_mutation_authorized = false -mind_adoption_required = true -bifrost_publication_required = true -"#; - let brief = parse_repo_consensus_brief(text).expect("fixture is typed TOML"); - assert!(!brief.has_authority_seals()); - } - - #[test] - fn interpreter_comment_cannot_counterfeit_state_authority_seal() { - let text = r#" -schema_version = "epiphany.repo_interpreter_brief.v0" -safe_action_family = "repo.interpreter_brief" -summary = "summary" -private_state_exposed = false -[interpreter] -status = "awaiting-mind-interpretation" -authoring_owner = "Imagination" -requested_interpreter = "Mind" -interpretation_admitted = false -purpose = "public-pressure-to-action-semantics" -requires_consensus_readback = true -requires_safe_family_choice = true -requires_requested_paths = true -requires_verification_asks = true -requires_evidence_needs = true -candidate_actions_non_authoritative = true -[semantic_checks] -[allowed_outputs] -candidate_safe_families = [] -may_request_replanning = false -may_request_more_consensus = false -may_adopt_objective = false -may_schedule_work = false -may_touch_substrate = false -may_publish = false -may_deploy = false -[required_gates] -[authority] -# direct_state_commit_authorized = false -direct_state_commit_authorized = true -"#; - let brief = parse_repo_interpreter_brief(text).expect("fixture is typed TOML"); - assert!(!brief.has_authority_seals()); - } - - #[test] - fn objective_draft_comment_cannot_counterfeit_adoption_seal() { - let text = r#" -schema_version = "epiphany.repo_objective_draft.v0" -safe_action_family = "repo.objective_draft" -summary = "summary" -private_state_exposed = false -[draft] -status = "review-required" -owner = "Imagination" -adoption_gate = "Mind" -scheduler_gate = "Self" -publication_gate = "Bifrost" -objective_adopted = false -[acceptance] -criteria = ["Mind explicitly accepts or rejects this Objective Draft before Self schedules it.", "Self schedules only after Mind adoption and a safe-family action plan exist.", "Hands acts only through a later receipt-backed plan and declared path scope.", "Bifrost gates publication, credit, and upstream-main sync."] -[inputs] -public_discussion_refs = [] -candidate_action_refs = [] -consensus_brief_required = true -[authority] -branch_local_only = true -# objective_adoption_authorized = false -objective_adoption_authorized = true -self_scheduling_authorized = false -hands_action_authorized = false -publication_authorized = false -cross_body_mutation_authorized = false -mind_adoption_required = true -bifrost_publication_required = true -"#; - let draft = parse_repo_objective_draft(text).expect("fixture is typed TOML"); - assert!(!draft.has_authority_seals()); - } -} diff --git a/epiphany-core/src/bin/epiphany_work/closure_contracts/workflow.rs b/epiphany-core/src/bin/epiphany_work/closure_contracts/workflow.rs deleted file mode 100644 index 73c69d73..00000000 --- a/epiphany-core/src/bin/epiphany_work/closure_contracts/workflow.rs +++ /dev/null @@ -1,431 +0,0 @@ -#[derive(Debug, Deserialize)] -pub(super) struct RepoWorkOrder { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - work_order: RepoWorkOrderBody, - antecedents: RepoWorkOrderAntecedents, - required_receipts: RepoWorkOrderReceipts, - scope: RepoWorkOrderScope, - authority: RepoWorkOrderAuthority, -} - -impl RepoWorkOrder { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_work_order.v0" - && self.safe_action_family == "repo.work_order" - } - - pub(super) fn awaits_hands_review(&self) -> bool { - self.work_order.status == "awaiting-hands-review" - && self.work_order.requested_owner == "Hands" - && self.work_order.requested_effect == "branch-local-implementation" - } - - pub(super) fn has_antecedent_contract(&self) -> bool { - !self.antecedents.objective_draft_ref.is_empty() - && !self.antecedents.adoption_request_ref.is_empty() - && !self.antecedents.scheduling_request_ref.is_empty() - && self.antecedents.mind_adoption_required - && self.antecedents.self_queue_selection_required - } - - pub(super) fn has_receipt_contract(&self) -> bool { - let r = &self.required_receipts; - r.substrate_gate == "epiphany.substrate_gate.grant" - && r.hands_intent == "epiphany.hands.action_intent" - && r.hands_review == "epiphany.hands.action_review" - && r.hands_patch == "epiphany.hands.patch_receipt" - && r.hands_command == "epiphany.hands.command_receipt" - && r.hands_commit == "epiphany.hands.commit_receipt" - && r.soul_verdict == "epiphany.soul.verification_verdict" - && r.mind_commit == "epiphany.mind.state_commit_receipt" - } - - pub(super) fn has_bounded_scope(&self) -> bool { - self.scope.branch_required - && self.scope.allowed_branch_prefix == "epiphany/" - && self.scope.max_changed_paths == 3 - && self.scope.requires_reviewable_diff - } - - pub(super) fn has_authority_seals(&self) -> bool { - let a = &self.authority; - a.branch_local_only - && !a.substrate_access_authorized - && !a.hands_action_authorized - && !a.shell_command_authorized - && !a.commit_authorized - && !a.publication_authorized - && !a.cross_body_mutation_authorized - && a.bifrost_publication_required - } -} - -#[derive(Debug, Deserialize)] -struct RepoWorkOrderBody { - status: String, - requested_owner: String, - requested_effect: String, -} -#[derive(Debug, Deserialize)] -struct RepoWorkOrderAntecedents { - objective_draft_ref: String, - adoption_request_ref: String, - scheduling_request_ref: String, - mind_adoption_required: bool, - self_queue_selection_required: bool, -} -#[derive(Debug, Deserialize)] -struct RepoWorkOrderReceipts { - substrate_gate: String, - hands_intent: String, - hands_review: String, - hands_patch: String, - hands_command: String, - hands_commit: String, - soul_verdict: String, - mind_commit: String, -} -#[derive(Debug, Deserialize)] -struct RepoWorkOrderScope { - branch_required: bool, - allowed_branch_prefix: String, - max_changed_paths: u64, - requires_reviewable_diff: bool, -} -#[derive(Debug, Deserialize)] -struct RepoWorkOrderAuthority { - branch_local_only: bool, - substrate_access_authorized: bool, - hands_action_authorized: bool, - shell_command_authorized: bool, - commit_authorized: bool, - publication_authorized: bool, - cross_body_mutation_authorized: bool, - bifrost_publication_required: bool, -} - -pub(super) fn parse_repo_work_order(text: &str) -> Result { - toml::from_str(text).context("work order is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoSchedulingRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - request: RepoSchedulingBody, - queue: RepoSchedulingQueue, - required_receipts: RepoSchedulingReceipts, - authority: RepoSchedulingAuthority, -} - -impl RepoSchedulingRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_scheduling_request.v0" - && self.safe_action_family == "repo.scheduling_request" - } - - pub(super) fn awaits_mind_adoption(&self) -> bool { - let r = &self.request; - r.status == "awaiting-mind-adoption" - && r.requested_scheduler == "Self" - && r.mind_adoption_receipt_required - && r.self_may_schedule_after_mind_only - && r.queue_run_allowed_after_adoption - } - - pub(super) fn has_bounded_queue_contract(&self) -> bool { - let q = &self.queue; - q.target_gate == "repo-work-queue" - && q.preferred_next_safe_family == "repo.task_card" - && q.max_items_per_pulse == 1 - && q.requires_epiphany_branch - && q.publish_blocker == "bifrost-publication-missing" - } - - pub(super) fn has_receipt_contract(&self) -> bool { - let r = &self.required_receipts; - r.mind_review == "epiphany.mind.gateway_review" - && r.mind_commit == "epiphany.mind.state_commit_receipt" - && r.expected_self_receipt == "epiphany.repo_work_queue_selection.v0" - } - - pub(super) fn has_authority_seals(&self) -> bool { - let a = &self.authority; - a.branch_local_only - && !a.self_scheduling_authorized - && !a.queue_mutation_authorized - && !a.hands_action_authorized - && !a.publication_authorized - && !a.cross_body_mutation_authorized - && a.mind_adoption_required - && a.bifrost_publication_required - } -} - -#[derive(Debug, Deserialize)] -struct RepoSchedulingBody { - status: String, - requested_scheduler: String, - mind_adoption_receipt_required: bool, - self_may_schedule_after_mind_only: bool, - queue_run_allowed_after_adoption: bool, -} -#[derive(Debug, Deserialize)] -struct RepoSchedulingQueue { - target_gate: String, - preferred_next_safe_family: String, - max_items_per_pulse: u64, - requires_epiphany_branch: bool, - publish_blocker: String, -} -#[derive(Debug, Deserialize)] -struct RepoSchedulingReceipts { - mind_review: String, - mind_commit: String, - expected_self_receipt: String, -} -#[derive(Debug, Deserialize)] -struct RepoSchedulingAuthority { - branch_local_only: bool, - self_scheduling_authorized: bool, - queue_mutation_authorized: bool, - hands_action_authorized: bool, - publication_authorized: bool, - cross_body_mutation_authorized: bool, - mind_adoption_required: bool, - bifrost_publication_required: bool, -} - -pub(super) fn parse_repo_scheduling_request(text: &str) -> Result { - toml::from_str(text).context("scheduling request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoAdoptionRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - request: RepoAdoptionBody, - decision_contract: RepoAdoptionDecisionContract, - inputs: RepoAdoptionInputs, - authority: RepoAdoptionAuthority, -} - -impl RepoAdoptionRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_adoption_request.v0" - && self.safe_action_family == "repo.adoption_request" - } - - pub(super) fn awaits_mind_review(&self) -> bool { - let r = &self.request; - r.status == "awaiting-mind-review" - && r.requested_decision == "adopt-or-refuse-objective-draft" - && r.mind_review_required - && r.mind_state_commit_required - && r.self_scheduling_after_mind_only - } - - pub(super) fn has_decision_contract(&self) -> bool { - let d = &self.decision_contract; - d.allowed_verdicts == ["adopted", "refused", "needs-more-consensus"] - && d.requires_review_finding - && d.requires_receipt == "epiphany.mind.gateway_review" - && d.requires_commit_receipt_if_adopted == "epiphany.mind.state_commit_receipt" - && d.does_not_modify_state - } - - pub(super) fn has_input_contract(&self) -> bool { - self.inputs.objective_draft_required - && self.inputs.consensus_brief_required - && self - .inputs - .public_discussion_refs - .iter() - .all(|value| !value.trim().is_empty()) - && self - .inputs - .candidate_action_refs - .iter() - .all(|value| !value.trim().is_empty()) - } - - pub(super) fn has_authority_seals(&self) -> bool { - let a = &self.authority; - a.branch_local_only - && !a.objective_adoption_authorized - && !a.state_commit_authorized - && !a.self_scheduling_authorized - && !a.hands_action_authorized - && !a.publication_authorized - && !a.cross_body_mutation_authorized - } -} - -#[derive(Debug, Deserialize)] -struct RepoAdoptionBody { - status: String, - requested_decision: String, - mind_review_required: bool, - mind_state_commit_required: bool, - self_scheduling_after_mind_only: bool, -} -#[derive(Debug, Deserialize)] -struct RepoAdoptionDecisionContract { - allowed_verdicts: Vec, - requires_review_finding: bool, - requires_receipt: String, - requires_commit_receipt_if_adopted: String, - does_not_modify_state: bool, -} -#[derive(Debug, Deserialize)] -struct RepoAdoptionInputs { - public_discussion_refs: Vec, - candidate_action_refs: Vec, - objective_draft_required: bool, - consensus_brief_required: bool, -} -#[derive(Debug, Deserialize)] -struct RepoAdoptionAuthority { - branch_local_only: bool, - objective_adoption_authorized: bool, - state_commit_authorized: bool, - self_scheduling_authorized: bool, - hands_action_authorized: bool, - publication_authorized: bool, - cross_body_mutation_authorized: bool, -} - -pub(super) fn parse_repo_adoption_request(text: &str) -> Result { - toml::from_str(text).context("adoption request is not valid typed TOML") -} - -#[derive(Debug, Deserialize)] -pub(super) struct RepoVerificationRequest { - pub(super) schema_version: String, - pub(super) safe_action_family: String, - pub(super) summary: String, - pub(super) private_state_exposed: bool, - request: RepoVerificationBody, - antecedents: RepoVerificationAntecedents, - required_receipts: RepoVerificationReceipts, - checks: RepoVerificationChecks, - authority: RepoVerificationAuthority, -} -impl RepoVerificationRequest { - pub(super) fn has_canonical_identity(&self) -> bool { - self.schema_version == "epiphany.repo_verification_request.v0" - && self.safe_action_family == "repo.verification_request" - } - pub(super) fn awaits_soul_review(&self) -> bool { - let r = &self.request; - r.status == "awaiting-soul-review" - && r.requested_owner == "Soul" - && r.requested_effect == "verify-branch-local-hands-work" - && !r.work_order_ref.is_empty() - } - pub(super) fn has_antecedent_contract(&self) -> bool { - let a = &self.antecedents; - a.substrate_gate_required - && a.hands_intent_required - && a.hands_review_required - && a.hands_patch_required - && a.hands_command_required - && a.hands_commit_required - && a.work_order_required - } - pub(super) fn has_receipt_contract(&self) -> bool { - let r = &self.required_receipts; - r.hands_patch == "epiphany.hands.patch_receipt" - && r.hands_command == "epiphany.hands.command_receipt" - && r.hands_commit == "epiphany.hands.commit_receipt" - && r.soul_verdict == "epiphany.soul.verification_verdict" - && r.closure_review == "epiphany.repo_work_closure_review.v0" - && r.mind_review == "epiphany.mind.gateway_review" - && r.mind_commit == "epiphany.mind.state_commit_receipt" - } - pub(super) fn has_check_contract(&self) -> bool { - self.checks.required - == [ - "declared-paths-match-commit", - "hands-receipts-present", - "visible-diff-supports-summary", - "no-private-state-exposure", - "publication-remains-gated", - ] - && self.checks.model_verdict_allowed - && self.checks.failure_blocks_mind_admission - } - pub(super) fn has_authority_seals(&self) -> bool { - let a = &self.authority; - a.branch_local_only - && !a.soul_verdict_authorized - && !a.state_commit_authorized - && !a.hands_action_authorized - && !a.rerun_authorized - && !a.publication_authorized - && !a.merge_authorized - && !a.service_lifecycle_authority - && !a.cross_body_mutation_authorized - && !a.private_verse_rummaging - && a.bifrost_publication_required - } -} -#[derive(Debug, Deserialize)] -struct RepoVerificationBody { - status: String, - requested_owner: String, - requested_effect: String, - work_order_ref: String, -} -#[derive(Debug, Deserialize)] -struct RepoVerificationAntecedents { - substrate_gate_required: bool, - hands_intent_required: bool, - hands_review_required: bool, - hands_patch_required: bool, - hands_command_required: bool, - hands_commit_required: bool, - work_order_required: bool, -} -#[derive(Debug, Deserialize)] -struct RepoVerificationReceipts { - hands_patch: String, - hands_command: String, - hands_commit: String, - soul_verdict: String, - closure_review: String, - mind_review: String, - mind_commit: String, -} -#[derive(Debug, Deserialize)] -struct RepoVerificationChecks { - required: Vec, - model_verdict_allowed: bool, - failure_blocks_mind_admission: bool, -} -#[derive(Debug, Deserialize)] -struct RepoVerificationAuthority { - branch_local_only: bool, - soul_verdict_authorized: bool, - state_commit_authorized: bool, - hands_action_authorized: bool, - rerun_authorized: bool, - publication_authorized: bool, - merge_authorized: bool, - service_lifecycle_authority: bool, - cross_body_mutation_authorized: bool, - private_verse_rummaging: bool, - bifrost_publication_required: bool, -} -pub(super) fn parse_repo_verification_request(text: &str) -> Result { - toml::from_str(text).context("verification request is not valid typed TOML") -} - -include!("workflow_tests.rs"); diff --git a/epiphany-core/src/bin/epiphany_work/closure_contracts/workflow_tests.rs b/epiphany-core/src/bin/epiphany_work/closure_contracts/workflow_tests.rs deleted file mode 100644 index 65f7bea5..00000000 --- a/epiphany-core/src/bin/epiphany_work/closure_contracts/workflow_tests.rs +++ /dev/null @@ -1,176 +0,0 @@ -#[cfg(test)] -mod workflow_tests { - use super::*; - - #[test] - fn adoption_comment_cannot_counterfeit_state_authority_seal() { - let text = r#" -schema_version = "epiphany.repo_adoption_request.v0" -safe_action_family = "repo.adoption_request" -summary = "summary" -private_state_exposed = false -[request] -status = "awaiting-mind-review" -requested_decision = "adopt-or-refuse-objective-draft" -mind_review_required = true -mind_state_commit_required = true -self_scheduling_after_mind_only = true -[decision_contract] -allowed_verdicts = ["adopted", "refused", "needs-more-consensus"] -requires_review_finding = true -requires_receipt = "epiphany.mind.gateway_review" -requires_commit_receipt_if_adopted = "epiphany.mind.state_commit_receipt" -does_not_modify_state = true -[inputs] -public_discussion_refs = [] -candidate_action_refs = [] -objective_draft_required = true -consensus_brief_required = true -[authority] -branch_local_only = true -objective_adoption_authorized = false -# state_commit_authorized = false -state_commit_authorized = true -self_scheduling_authorized = false -hands_action_authorized = false -publication_authorized = false -cross_body_mutation_authorized = false -"#; - let request = parse_repo_adoption_request(text).expect("fixture is typed TOML"); - assert!(!request.has_authority_seals()); - } - - #[test] - fn scheduling_comment_cannot_counterfeit_queue_authority_seal() { - let text = r#" -schema_version = "epiphany.repo_scheduling_request.v0" -safe_action_family = "repo.scheduling_request" -summary = "summary" -private_state_exposed = false -[request] -status = "awaiting-mind-adoption" -requested_scheduler = "Self" -mind_adoption_receipt_required = true -self_may_schedule_after_mind_only = true -queue_run_allowed_after_adoption = true -[queue] -target_gate = "repo-work-queue" -preferred_next_safe_family = "repo.task_card" -max_items_per_pulse = 1 -requires_epiphany_branch = true -publish_blocker = "bifrost-publication-missing" -[required_receipts] -mind_review = "epiphany.mind.gateway_review" -mind_commit = "epiphany.mind.state_commit_receipt" -expected_self_receipt = "epiphany.repo_work_queue_selection.v0" -[authority] -branch_local_only = true -self_scheduling_authorized = false -# queue_mutation_authorized = false -queue_mutation_authorized = true -hands_action_authorized = false -publication_authorized = false -cross_body_mutation_authorized = false -mind_adoption_required = true -bifrost_publication_required = true -"#; - let request = parse_repo_scheduling_request(text).expect("fixture is typed TOML"); - assert!(!request.has_authority_seals()); - } - - #[test] - fn work_order_comment_cannot_counterfeit_hands_authority_seal() { - let text = r#" -schema_version = "epiphany.repo_work_order.v0" -safe_action_family = "repo.work_order" -summary = "summary" -private_state_exposed = false -[work_order] -status = "awaiting-hands-review" -requested_owner = "Hands" -requested_effect = "branch-local-implementation" -[antecedents] -objective_draft_ref = "objective" -adoption_request_ref = "adoption" -scheduling_request_ref = "schedule" -mind_adoption_required = true -self_queue_selection_required = true -[required_receipts] -substrate_gate = "epiphany.substrate_gate.grant" -hands_intent = "epiphany.hands.action_intent" -hands_review = "epiphany.hands.action_review" -hands_patch = "epiphany.hands.patch_receipt" -hands_command = "epiphany.hands.command_receipt" -hands_commit = "epiphany.hands.commit_receipt" -soul_verdict = "epiphany.soul.verification_verdict" -mind_commit = "epiphany.mind.state_commit_receipt" -[scope] -branch_required = true -allowed_branch_prefix = "epiphany/" -max_changed_paths = 3 -requires_reviewable_diff = true -[authority] -branch_local_only = true -substrate_access_authorized = false -# hands_action_authorized = false -hands_action_authorized = true -shell_command_authorized = false -commit_authorized = false -publication_authorized = false -cross_body_mutation_authorized = false -bifrost_publication_required = true -"#; - let work_order = parse_repo_work_order(text).expect("fixture is typed TOML"); - assert!(!work_order.has_authority_seals()); - } - - #[test] - fn verification_comment_cannot_counterfeit_soul_verdict_seal() { - let text = r#" -schema_version = "epiphany.repo_verification_request.v0" -safe_action_family = "repo.verification_request" -summary = "summary" -private_state_exposed = false -[request] -status = "awaiting-soul-review" -requested_owner = "Soul" -requested_effect = "verify-branch-local-hands-work" -work_order_ref = "work-order" -[antecedents] -substrate_gate_required = true -hands_intent_required = true -hands_review_required = true -hands_patch_required = true -hands_command_required = true -hands_commit_required = true -work_order_required = true -[required_receipts] -hands_patch = "epiphany.hands.patch_receipt" -hands_command = "epiphany.hands.command_receipt" -hands_commit = "epiphany.hands.commit_receipt" -soul_verdict = "epiphany.soul.verification_verdict" -closure_review = "epiphany.repo_work_closure_review.v0" -mind_review = "epiphany.mind.gateway_review" -mind_commit = "epiphany.mind.state_commit_receipt" -[checks] -required = ["declared-paths-match-commit", "hands-receipts-present", "visible-diff-supports-summary", "no-private-state-exposure", "publication-remains-gated"] -model_verdict_allowed = true -failure_blocks_mind_admission = true -[authority] -branch_local_only = true -# soul_verdict_authorized = false -soul_verdict_authorized = true -state_commit_authorized = false -hands_action_authorized = false -rerun_authorized = false -publication_authorized = false -merge_authorized = false -service_lifecycle_authority = false -cross_body_mutation_authorized = false -private_verse_rummaging = false -bifrost_publication_required = true -"#; - let request = parse_repo_verification_request(text).expect("fixture is typed TOML"); - assert!(!request.has_authority_seals()); - } -} diff --git a/epiphany-core/src/cultmesh_integration.rs b/epiphany-core/src/cultmesh_integration.rs index 3d3a717a..15d9b5ec 100644 --- a/epiphany-core/src/cultmesh_integration.rs +++ b/epiphany-core/src/cultmesh_integration.rs @@ -5572,25 +5572,6 @@ fn agent_state_soa_generation_key( ) } -pub fn write_epiphany_cultmesh_repo_work_overview( - store_path: impl AsRef, - overview: EpiphanyCultMeshRepoWorkOverviewEntry, -) -> Result { - validate_repo_work_overview(&overview)?; - let mut node = open_epiphany_cultmesh_node(&store_path, overview.runtime_id.clone())?; - let written = node.put(overview.overview_id.clone(), &overview)?; - let current_latest = node.get::( - EPIPHANY_CULTMESH_REPO_WORK_OVERVIEW_LATEST_KEY, - )?; - if current_latest.as_ref().is_none_or(|current| { - repo_work_overview_generation_key(&written) >= repo_work_overview_generation_key(current) - }) { - node.put(EPIPHANY_CULTMESH_REPO_WORK_OVERVIEW_LATEST_KEY, &written)?; - } - node.flush()?; - Ok(written) -} - pub fn load_latest_epiphany_cultmesh_repo_work_overview( store_path: impl AsRef, runtime_id: impl Into, @@ -5618,25 +5599,6 @@ pub fn load_epiphany_cultmesh_repo_work_overviews( Ok(overviews) } -pub fn write_epiphany_cultmesh_repo_work_readiness( - store_path: impl AsRef, - readiness: EpiphanyCultMeshRepoWorkReadinessEntry, -) -> Result { - validate_repo_work_readiness(&readiness)?; - let mut node = open_epiphany_cultmesh_node(&store_path, readiness.runtime_id.clone())?; - let written = node.put(readiness.readiness_id.clone(), &readiness)?; - let current_latest = node.get::( - EPIPHANY_CULTMESH_REPO_WORK_READINESS_LATEST_KEY, - )?; - if current_latest.as_ref().is_none_or(|current| { - repo_work_readiness_generation_key(&written) >= repo_work_readiness_generation_key(current) - }) { - node.put(EPIPHANY_CULTMESH_REPO_WORK_READINESS_LATEST_KEY, &written)?; - } - node.flush()?; - Ok(written) -} - pub fn load_latest_epiphany_cultmesh_repo_work_readiness( store_path: impl AsRef, runtime_id: impl Into, @@ -5664,25 +5626,6 @@ pub fn load_epiphany_cultmesh_repo_work_readiness_reports( Ok(reports) } -pub fn write_epiphany_cultmesh_repo_work_map_entry( - store_path: impl AsRef, - map_entry: EpiphanyCultMeshRepoWorkMapEntry, -) -> Result { - validate_repo_work_map_entry(&map_entry)?; - let mut node = open_epiphany_cultmesh_node(&store_path, map_entry.runtime_id.clone())?; - let written = node.put(map_entry.map_entry_id.clone(), &map_entry)?; - let current_latest = node.get::( - EPIPHANY_CULTMESH_REPO_WORK_MAP_ENTRY_LATEST_KEY, - )?; - if current_latest.as_ref().is_none_or(|current| { - repo_work_map_admission_key(&written) >= repo_work_map_admission_key(current) - }) { - node.put(EPIPHANY_CULTMESH_REPO_WORK_MAP_ENTRY_LATEST_KEY, &written)?; - } - node.flush()?; - Ok(written) -} - pub fn load_latest_epiphany_cultmesh_repo_work_map_entry( store_path: impl AsRef, runtime_id: impl Into, @@ -5710,29 +5653,6 @@ pub fn load_epiphany_cultmesh_repo_work_map_entries( Ok(entries) } -pub fn write_epiphany_cultmesh_repo_work_public_proof( - store_path: impl AsRef, - proof: EpiphanyCultMeshRepoWorkPublicProofEntry, -) -> Result { - validate_repo_work_public_proof(&proof)?; - let mut node = open_epiphany_cultmesh_node(&store_path, proof.runtime_id.clone())?; - let written = node.put(proof.public_proof_id.clone(), &proof)?; - let current_latest = node.get::( - EPIPHANY_CULTMESH_REPO_WORK_PUBLIC_PROOF_LATEST_KEY, - )?; - if current_latest.as_ref().is_none_or(|current| { - repo_work_public_proof_generation_key(&written) - >= repo_work_public_proof_generation_key(current) - }) { - node.put( - EPIPHANY_CULTMESH_REPO_WORK_PUBLIC_PROOF_LATEST_KEY, - &written, - )?; - } - node.flush()?; - Ok(written) -} - pub fn load_latest_epiphany_cultmesh_repo_work_public_proof( store_path: impl AsRef, runtime_id: impl Into, @@ -5760,228 +5680,6 @@ pub fn load_epiphany_cultmesh_repo_work_public_proofs( Ok(proofs) } -fn validate_repo_work_overview(overview: &EpiphanyCultMeshRepoWorkOverviewEntry) -> Result<()> { - if overview.private_state_exposed { - return Err(anyhow!("repo work overview must not expose private state")); - } - if overview.schema_version != EPIPHANY_CULTMESH_REPO_WORK_OVERVIEW_SCHEMA_VERSION { - return Err(anyhow!( - "repo work overview schema_version must be {:?}", - EPIPHANY_CULTMESH_REPO_WORK_OVERVIEW_SCHEMA_VERSION - )); - } - if overview.verse_id != EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID { - return Err(anyhow!( - "repo work overview belongs in local-area Verse {:?}", - EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID - )); - } - if overview.overview_id.trim().is_empty() || overview.item.trim().is_empty() { - return Err(anyhow!("repo work overview requires overview_id and item")); - } - DateTime::parse_from_rfc3339(&overview.generated_at) - .map_err(|error| anyhow!("repo work overview has invalid generated_at: {error}"))?; - if overview.tui_rows.is_empty() { - return Err(anyhow!("repo work overview requires compact TUI rows")); - } - if overview - .tui_rows - .iter() - .any(|row| row.to_ascii_lowercase().contains("rawresult")) - { - return Err(anyhow!( - "repo work overview rows must not expose raw worker payload names" - )); - } - Ok(()) -} - -fn repo_work_overview_generation_key( - overview: &EpiphanyCultMeshRepoWorkOverviewEntry, -) -> (DateTime, &str) { - ( - DateTime::parse_from_rfc3339(&overview.generated_at) - .expect("validated repo work overview generation timestamp"), - overview.overview_id.as_str(), - ) -} - -fn validate_repo_work_readiness(readiness: &EpiphanyCultMeshRepoWorkReadinessEntry) -> Result<()> { - if readiness.private_state_exposed { - return Err(anyhow!("repo work readiness must not expose private state")); - } - if readiness.schema_version != EPIPHANY_CULTMESH_REPO_WORK_READINESS_SCHEMA_VERSION { - return Err(anyhow!( - "repo work readiness schema_version must be {:?}", - EPIPHANY_CULTMESH_REPO_WORK_READINESS_SCHEMA_VERSION - )); - } - if readiness.verse_id != EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID { - return Err(anyhow!( - "repo work readiness belongs in local-area Verse {:?}", - EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID - )); - } - if readiness.readiness_id.trim().is_empty() || readiness.item.trim().is_empty() { - return Err(anyhow!( - "repo work readiness requires readiness_id and item" - )); - } - DateTime::parse_from_rfc3339(&readiness.generated_at) - .map_err(|error| anyhow!("repo work readiness has invalid generated_at: {error}"))?; - if !readiness.sight_only - || readiness.readiness_approval_authorized - || readiness.publication_authorized - || readiness.service_lifecycle_authority - || readiness.hands_action_authorized - { - return Err(anyhow!( - "repo work readiness is sight only and must not grant approval, publication, service, or Hands authority" - )); - } - if readiness.tui_rows.is_empty() { - return Err(anyhow!("repo work readiness requires compact TUI rows")); - } - if readiness.tui_rows.iter().any(|row| { - let lower = row.to_ascii_lowercase(); - lower.contains("rawresult") || lower.contains("receipt body") || lower.contains("thought") - }) { - return Err(anyhow!( - "repo work readiness rows must not expose raw worker payload names" - )); - } - Ok(()) -} - -fn repo_work_readiness_generation_key( - readiness: &EpiphanyCultMeshRepoWorkReadinessEntry, -) -> (DateTime, &str) { - ( - DateTime::parse_from_rfc3339(&readiness.generated_at) - .expect("validated repo work readiness generation timestamp"), - readiness.readiness_id.as_str(), - ) -} - -fn validate_repo_work_map_entry(entry: &EpiphanyCultMeshRepoWorkMapEntry) -> Result<()> { - if entry.private_state_exposed { - return Err(anyhow!("repo work map entry must not expose private state")); - } - if entry.schema_version != EPIPHANY_CULTMESH_REPO_WORK_MAP_ENTRY_SCHEMA_VERSION { - return Err(anyhow!( - "repo work map entry schema_version must be {:?}", - EPIPHANY_CULTMESH_REPO_WORK_MAP_ENTRY_SCHEMA_VERSION - )); - } - if entry.verse_id != EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID { - return Err(anyhow!( - "repo work map entry belongs in local-area Verse {:?}", - EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID - )); - } - if entry.map_entry_id.trim().is_empty() || entry.item.trim().is_empty() { - return Err(anyhow!( - "repo work map entry requires map_entry_id and item" - )); - } - if entry.modeling_finding_receipt_id.trim().is_empty() { - return Err(anyhow!( - "repo work map entry requires a Modeling finding receipt" - )); - } - if !entry.durable_state_admitted { - return Err(anyhow!( - "repo work map entry projection requires admitted durable state" - )); - } - let admitted_at = DateTime::parse_from_rfc3339(&entry.admitted_at) - .map_err(|error| anyhow!("repo work map entry has invalid admitted_at: {error}"))?; - let mirrored_at = DateTime::parse_from_rfc3339(&entry.mirrored_at) - .map_err(|error| anyhow!("repo work map entry has invalid mirrored_at: {error}"))?; - if mirrored_at < admitted_at { - return Err(anyhow!( - "repo work map entry was mirrored before Mind admission" - )); - } - if entry.tui_rows.is_empty() { - return Err(anyhow!("repo work map entry requires compact TUI rows")); - } - if entry - .tui_rows - .iter() - .any(|row| row.to_ascii_lowercase().contains("rawresult")) - { - return Err(anyhow!( - "repo work map entry rows must not expose raw worker payload names" - )); - } - Ok(()) -} - -fn repo_work_map_admission_key( - entry: &EpiphanyCultMeshRepoWorkMapEntry, -) -> (DateTime, &str) { - ( - DateTime::parse_from_rfc3339(&entry.admitted_at) - .expect("validated repo work map admission timestamp"), - entry.map_entry_id.as_str(), - ) -} - -fn validate_repo_work_public_proof(proof: &EpiphanyCultMeshRepoWorkPublicProofEntry) -> Result<()> { - if proof.private_state_exposed { - return Err(anyhow!( - "repo work public proof must not expose private state" - )); - } - if proof.schema_version != EPIPHANY_CULTMESH_REPO_WORK_PUBLIC_PROOF_SCHEMA_VERSION { - return Err(anyhow!( - "repo work public proof schema_version must be {:?}", - EPIPHANY_CULTMESH_REPO_WORK_PUBLIC_PROOF_SCHEMA_VERSION - )); - } - if proof.verse_id != EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID { - return Err(anyhow!( - "repo work public proof belongs in local-area Verse {:?}", - EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID - )); - } - if proof.public_proof_id.trim().is_empty() || proof.item.trim().is_empty() { - return Err(anyhow!( - "repo work public proof requires public_proof_id and item" - )); - } - DateTime::parse_from_rfc3339(&proof.generated_at) - .map_err(|error| anyhow!("repo work public proof has invalid generated_at: {error}"))?; - if proof.public_proof_ref.trim().is_empty() || proof.public_proof_sha256.trim().is_empty() { - return Err(anyhow!( - "repo work public proof requires artifact ref and sha256" - )); - } - if proof.tui_rows.is_empty() { - return Err(anyhow!("repo work public proof requires compact TUI rows")); - } - if proof.tui_rows.iter().any(|row| { - let lower = row.to_ascii_lowercase(); - lower.contains("rawresult") || lower.contains("receipt body") || lower.contains("thought") - }) { - return Err(anyhow!( - "repo work public proof rows must not expose raw worker payload names" - )); - } - Ok(()) -} - -fn repo_work_public_proof_generation_key( - proof: &EpiphanyCultMeshRepoWorkPublicProofEntry, -) -> (DateTime, &str) { - ( - DateTime::parse_from_rfc3339(&proof.generated_at) - .expect("validated repo work public proof generation timestamp"), - proof.public_proof_id.as_str(), - ) -} - pub fn seed_epiphany_local_verse_context( store_path: impl AsRef, runtime_id: impl Into, @@ -7618,164 +7316,6 @@ mod tests { Ok(()) } - #[test] - fn repo_work_map_latest_follows_mind_admission_not_mirror_arrival() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("repo-work-map-order.ccmp"); - let older = EpiphanyCultMeshRepoWorkMapEntry { - schema_version: EPIPHANY_CULTMESH_REPO_WORK_MAP_ENTRY_SCHEMA_VERSION.to_string(), - runtime_id: "repo-work-test".to_string(), - verse_id: EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID.to_string(), - map_entry_id: "repo-work-map-older".to_string(), - admitted_at: "2026-07-13T01:00:00Z".to_string(), - mirrored_at: "2026-07-13T01:00:01Z".to_string(), - workspace: "E:/Projects/test".to_string(), - item: "test-item".to_string(), - branch: "main".to_string(), - changed_paths: vec!["src/lib.rs".to_string()], - commit_sha: "older".to_string(), - safe_action_family: "planning-note".to_string(), - modeling_summary: "Older admitted map.".to_string(), - soul_verdict_receipt_id: "soul-older".to_string(), - mind_gateway_review_id: "mind-review-older".to_string(), - mind_state_commit_receipt_id: "mind-commit-older".to_string(), - publication_gate: "bifrost".to_string(), - durable_state_admitted: true, - source_store_path: "state/runtime.cc".to_string(), - tui_rows: vec!["MAP test-item older".to_string()], - private_state_exposed: false, - notes: Vec::new(), - modeling_finding_receipt_id: "modeling-finding-older".to_string(), - modeling_route_id: "modeling-route-older".to_string(), - modeling_generation: 1, - }; - let mut newer = older.clone(); - newer.map_entry_id = "repo-work-map-newer".to_string(); - newer.admitted_at = "2026-07-13T02:00:00Z".to_string(); - newer.mirrored_at = "2026-07-13T02:00:01Z".to_string(); - newer.commit_sha = "newer".to_string(); - newer.modeling_generation = 2; - - write_epiphany_cultmesh_repo_work_map_entry(&store, newer.clone())?; - write_epiphany_cultmesh_repo_work_map_entry(&store, older.clone())?; - assert_eq!( - load_latest_epiphany_cultmesh_repo_work_map_entry(&store, "repo-work-test")?, - Some(newer) - ); - - let mut impossible = older; - impossible.map_entry_id = "repo-work-map-impossible".to_string(); - impossible.mirrored_at = "2026-07-13T00:59:59Z".to_string(); - let err = write_epiphany_cultmesh_repo_work_map_entry(&store, impossible) - .expect_err("map projection before Mind admission must be refused"); - assert!(err.to_string().contains("before Mind admission")); - Ok(()) - } - - #[test] - fn repo_work_overview_latest_follows_generation_not_arrival() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("repo-work-overview-order.ccmp"); - let older = EpiphanyCultMeshRepoWorkOverviewEntry { - schema_version: EPIPHANY_CULTMESH_REPO_WORK_OVERVIEW_SCHEMA_VERSION.to_string(), - runtime_id: "repo-work-test".to_string(), - verse_id: EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID.to_string(), - overview_id: "repo-work-overview-older".to_string(), - generated_at: "2026-07-13T01:00:00Z".to_string(), - workspace: "E:/Projects/test".to_string(), - item: "older-item".to_string(), - branch: "main".to_string(), - current_gate: "awaiting-plan".to_string(), - blocker: "plan-missing".to_string(), - next_safe_move: "derive plan".to_string(), - changed_paths: Vec::new(), - commit_sha: String::new(), - soul_verdict: "missing".to_string(), - publication_status: "not-started".to_string(), - sync_status: "not-started".to_string(), - receipt_refs: Vec::new(), - tui_rows: vec!["OVERVIEW older-item awaiting-plan".to_string()], - proof_bundle_ref: "proof://older".to_string(), - private_state_exposed: false, - notes: Vec::new(), - }; - let mut newer = older.clone(); - newer.overview_id = "repo-work-overview-newer".to_string(); - newer.item = "newer-item".to_string(); - newer.generated_at = "2026-07-13T02:00:00Z".to_string(); - newer.current_gate = "ready-to-run".to_string(); - newer.blocker = "none".to_string(); - newer.next_safe_move = "run tick".to_string(); - - write_epiphany_cultmesh_repo_work_overview(&store, newer.clone())?; - write_epiphany_cultmesh_repo_work_overview(&store, older.clone())?; - assert_eq!( - load_latest_epiphany_cultmesh_repo_work_overview(&store, "repo-work-test")?, - Some(newer) - ); - - let mut invalid = older; - invalid.overview_id = "repo-work-overview-invalid".to_string(); - invalid.generated_at = "not-a-time".to_string(); - let err = write_epiphany_cultmesh_repo_work_overview(&store, invalid) - .expect_err("invalid overview generation time must be refused"); - assert!(err.to_string().contains("invalid generated_at")); - Ok(()) - } - - #[test] - fn repo_work_readiness_latest_follows_generation_not_arrival() -> Result<()> { - let temp = tempfile::tempdir()?; - let store = temp.path().join("repo-work-readiness-order.ccmp"); - let older = EpiphanyCultMeshRepoWorkReadinessEntry { - schema_version: EPIPHANY_CULTMESH_REPO_WORK_READINESS_SCHEMA_VERSION.to_string(), - runtime_id: "repo-work-test".to_string(), - verse_id: EPIPHANY_CULTMESH_LOCAL_AREA_VERSE_ID.to_string(), - readiness_id: "repo-work-readiness-older".to_string(), - generated_at: "2026-07-13T01:00:00Z".to_string(), - workspace: "E:/Projects/test".to_string(), - item: "older-item".to_string(), - status: "incomplete".to_string(), - missing_required_count: 1, - satisfied_required_count: 2, - readiness_receipt_ref: "receipt://older".to_string(), - overview_receipt_ref: "overview://older".to_string(), - proof_bundle_id: "proof-older".to_string(), - missing_kinds: vec!["maintainer-review".to_string()], - tui_rows: vec!["READINESS older-item incomplete".to_string()], - sight_only: true, - readiness_approval_authorized: false, - publication_authorized: false, - service_lifecycle_authority: false, - hands_action_authorized: false, - private_state_exposed: false, - notes: Vec::new(), - }; - let mut newer = older.clone(); - newer.readiness_id = "repo-work-readiness-newer".to_string(); - newer.item = "newer-item".to_string(); - newer.generated_at = "2026-07-13T02:00:00Z".to_string(); - newer.status = "ready".to_string(); - newer.missing_required_count = 0; - newer.satisfied_required_count = 3; - newer.missing_kinds.clear(); - - write_epiphany_cultmesh_repo_work_readiness(&store, newer.clone())?; - write_epiphany_cultmesh_repo_work_readiness(&store, older.clone())?; - assert_eq!( - load_latest_epiphany_cultmesh_repo_work_readiness(&store, "repo-work-test")?, - Some(newer) - ); - - let mut invalid = older; - invalid.readiness_id = "repo-work-readiness-invalid".to_string(); - invalid.generated_at = "not-a-time".to_string(); - let err = write_epiphany_cultmesh_repo_work_readiness(&store, invalid) - .expect_err("invalid readiness generation time must be refused"); - assert!(err.to_string().contains("invalid generated_at")); - Ok(()) - } - #[test] fn scheduler_latest_mirror_refuses_delayed_replay() -> Result<()> { let temp = tempfile::tempdir()?; @@ -9783,22 +9323,6 @@ mod tests { private_state_exposed: false, notes: vec!["redacted proof".to_string()], }; - let mut newer_proof = proof.clone(); - newer_proof.public_proof_id = "repo-work-public-proof-newer".to_string(); - newer_proof.generated_at = "2026-06-20T13:00:00Z".to_string(); - newer_proof.commit_sha = "def456".to_string(); - write_epiphany_cultmesh_repo_work_public_proof(&store, newer_proof.clone())?; - write_epiphany_cultmesh_repo_work_public_proof(&store, proof.clone())?; - assert_eq!( - load_latest_epiphany_cultmesh_repo_work_public_proof(&store, "epiphany-test")?, - Some(newer_proof) - ); - let mut invalid_time = proof.clone(); - invalid_time.public_proof_id = "repo-work-public-proof-invalid".to_string(); - invalid_time.generated_at = "not-a-time".to_string(); - let error = write_epiphany_cultmesh_repo_work_public_proof(&store, invalid_time) - .expect_err("invalid public proof generation time must be refused"); - assert!(error.to_string().contains("invalid generated_at")); let receipt = epiphany_cultmesh_bifrost_public_proof_publication_receipt_for_proof( "bifrost-public-proof-publication-test", &proof, diff --git a/epiphany-core/src/lib.rs b/epiphany-core/src/lib.rs index d81a49fd..be6d4bcd 100644 --- a/epiphany-core/src/lib.rs +++ b/epiphany-core/src/lib.rs @@ -17,7 +17,6 @@ mod hands_gateway; mod heartbeat_state; mod memory_graph; mod mind_gateway; -mod modeling_gateway; mod organ_dependencies; mod persona_memory_cache; mod persona_turn; @@ -505,10 +504,6 @@ pub use cultmesh_integration::write_epiphany_cultmesh_operator_run_intent; pub use cultmesh_integration::write_epiphany_cultmesh_operator_run_receipt; pub use cultmesh_integration::write_epiphany_cultmesh_operator_snapshot; pub use cultmesh_integration::write_epiphany_cultmesh_persona_speech_audit; -pub use cultmesh_integration::write_epiphany_cultmesh_repo_work_map_entry; -pub use cultmesh_integration::write_epiphany_cultmesh_repo_work_overview; -pub use cultmesh_integration::write_epiphany_cultmesh_repo_work_public_proof; -pub use cultmesh_integration::write_epiphany_cultmesh_repo_work_readiness; pub use cultmesh_integration::write_epiphany_cultmesh_role_review_event; pub use cultmesh_integration::write_epiphany_cultmesh_soul_contracts; pub use cultmesh_integration::write_epiphany_cultmesh_status; @@ -662,31 +657,12 @@ pub use mind_gateway::MindGatewayDecision; pub use mind_gateway::MindGatewayReview; pub use mind_gateway::MindInterpreterPromptInput; pub use mind_gateway::MindStateCommitReceipt; -pub use mind_gateway::REPO_WORK_HANDS_GRANT_SCHEMA_VERSION; -pub use mind_gateway::REPO_WORK_HANDS_GRANT_TYPE; -pub use mind_gateway::REPO_WORK_PLAN_ADOPTION_REVIEW_SCHEMA_VERSION; -pub use mind_gateway::REPO_WORK_PLAN_ADOPTION_REVIEW_TYPE; -pub use mind_gateway::RepoWorkHandsGrant; -pub use mind_gateway::RepoWorkPlanAdoptionDecision; -pub use mind_gateway::RepoWorkPlanAdoptionReview; pub use mind_gateway::build_mind_interpreter_prompt; pub use mind_gateway::default_mind_cultnet_contracts; pub use mind_gateway::mind_review_allows_state; pub use mind_gateway::mind_review_reorient_acceptance; pub use mind_gateway::mind_review_role_acceptance; pub use mind_gateway::mind_state_commit_receipt; -pub use modeling_gateway::REPO_WORK_MAP_ENTRY_SCHEMA_VERSION; -pub use modeling_gateway::REPO_WORK_MAP_ENTRY_TYPE; -pub use modeling_gateway::REPO_WORK_MODELING_FINDING_SCHEMA_VERSION; -pub use modeling_gateway::REPO_WORK_MODELING_FINDING_TYPE; -pub use modeling_gateway::REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION; -pub use modeling_gateway::REPO_WORK_MODELING_REQUEST_TYPE; -pub use modeling_gateway::REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION; -pub use modeling_gateway::REPO_WORK_MODELING_ROUTE_TYPE; -pub use modeling_gateway::RepoWorkMapEntry; -pub use modeling_gateway::RepoWorkModelingFinding; -pub use modeling_gateway::RepoWorkModelingRequest; -pub use modeling_gateway::RepoWorkModelingRoute; pub use organ_dependencies::EPIPHANY_LAUNCH_ORGAN_CONTRACT_SCHEMA_VERSION; pub use organ_dependencies::EPIPHANY_ORGAN_DEPENDENCY_SCHEMA_VERSION; pub use organ_dependencies::EPIPHANY_STANDING_ORGANS; @@ -799,15 +775,11 @@ pub use runtime_spine::RuntimeSpineInitOptions; pub use runtime_spine::RuntimeSpineJobOptions; pub use runtime_spine::RuntimeSpineJobResultOptions; pub use runtime_spine::RuntimeSpineSessionOptions; -pub use runtime_spine::advance_repo_work_modeling_route; pub use runtime_spine::append_runtime_event; pub use runtime_spine::clear_epiphany_job_binding_backend; -pub use runtime_spine::commit_initial_repo_work_modeling_route; pub use runtime_spine::commit_repo_frontier_modeling_request; pub use runtime_spine::commit_repo_frontier_verification_request_for_chain; pub use runtime_spine::commit_repo_model_admission; -pub use runtime_spine::commit_repo_work_hands_grant; -pub use runtime_spine::commit_repo_work_map_admission; pub use runtime_spine::complete_runtime_job; pub use runtime_spine::create_runtime_job; pub use runtime_spine::create_runtime_session; @@ -831,9 +803,6 @@ pub use runtime_spine::put_mind_gateway_review; pub use runtime_spine::put_mind_state_commit_receipt; pub use runtime_spine::put_repo_frontier_hands_authority; pub use runtime_spine::put_repo_frontier_verification_request; -pub use runtime_spine::put_repo_work_modeling_finding; -pub use runtime_spine::put_repo_work_modeling_request; -pub use runtime_spine::put_repo_work_plan_adoption_review; pub use runtime_spine::put_runtime_reorient_worker_result; pub use runtime_spine::put_runtime_role_worker_result; pub use runtime_spine::put_soul_verdict_receipt; @@ -858,12 +827,6 @@ pub use runtime_spine::runtime_registered_document_types; pub use runtime_spine::runtime_reorient_worker_result; pub use runtime_spine::runtime_repo_frontier_route; pub use runtime_spine::runtime_repo_frontier_verification_request; -pub use runtime_spine::runtime_repo_work_hands_grant; -pub use runtime_spine::runtime_repo_work_map_entry; -pub use runtime_spine::runtime_repo_work_modeling_finding; -pub use runtime_spine::runtime_repo_work_modeling_request; -pub use runtime_spine::runtime_repo_work_modeling_route; -pub use runtime_spine::runtime_repo_work_plan_adoption_review; pub use runtime_spine::runtime_role_worker_result; pub use runtime_spine::runtime_schema_catalog_response; pub use runtime_spine::runtime_soul_verdict_receipt; @@ -972,7 +935,6 @@ pub use surfaces::EpiphanyReorientPressureLevel; pub use surfaces::EpiphanyReorientReason; pub use surfaces::EpiphanyReorientStateStatus; pub use surfaces::EpiphanyReorientWorkerLaunchDocument; -pub use surfaces::EpiphanyRepoWorkModelingLaunchDocument; pub use surfaces::EpiphanyRetrievalFreshness; pub use surfaces::EpiphanyRetrievalFreshnessStatus; pub use surfaces::EpiphanyRoleAcceptanceFinding; @@ -1005,7 +967,6 @@ pub use surfaces::EpiphanyTokenUsageSnapshot; pub use surfaces::EpiphanyViewLens; pub use surfaces::EpiphanyWorkerLaunchDocument; pub use surfaces::REORIENT_WORKER_OUTPUT_CONTRACT_ID; -pub use surfaces::REPO_WORK_MODELING_OUTPUT_CONTRACT_ID; pub use surfaces::ROLE_WORKER_OUTPUT_CONTRACT_ID; pub use surfaces::build_reorient_acceptance_bundle; pub use surfaces::build_reorient_job_launch_request; diff --git a/epiphany-core/src/mind_gateway.rs b/epiphany-core/src/mind_gateway.rs index cf428b13..ecf314e6 100644 --- a/epiphany-core/src/mind_gateway.rs +++ b/epiphany-core/src/mind_gateway.rs @@ -22,119 +22,6 @@ pub const MIND_STATE_REJECTION_RECEIPT_SCHEMA_VERSION: &str = "epiphany.mind.state_rejection_receipt.v0"; pub const MIND_VERSE_ADOPTION_RECEIPT_SCHEMA_VERSION: &str = "epiphany.mind.verse_adoption_receipt.v0"; -pub const REPO_WORK_PLAN_ADOPTION_REVIEW_TYPE: &str = "epiphany.repo_work.plan_adoption_review"; -pub const REPO_WORK_PLAN_ADOPTION_REVIEW_SCHEMA_VERSION: &str = - "epiphany.repo_work_plan_adoption_review.v0"; -pub const REPO_WORK_HANDS_GRANT_TYPE: &str = "epiphany.repo_work.hands_grant"; -pub const REPO_WORK_HANDS_GRANT_SCHEMA_VERSION: &str = "epiphany.repo_work_hands_grant.v0"; - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum RepoWorkPlanAdoptionDecision { - Adopt, - Refuse, - Hold, -} - -/// Mind-authored review of one immutable repo-work plan and its complete authority chain. -#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "epiphany.repo_work.plan_adoption_review", - schema = "RepoWorkPlanAdoptionReview" -)] -pub struct RepoWorkPlanAdoptionReview { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub review_id: String, - #[cultcache(key = 2)] - pub decision: RepoWorkPlanAdoptionDecision, - #[cultcache(key = 3)] - pub workspace_identity: String, - #[cultcache(key = 4)] - pub item: String, - #[cultcache(key = 5)] - pub plan_schema_version: String, - #[cultcache(key = 6)] - pub plan_id: String, - #[cultcache(key = 7)] - pub plan_sha256: String, - #[cultcache(key = 8)] - pub run_receipt_sha256: String, - #[cultcache(key = 9)] - pub plan_receipt_path: String, - #[cultcache(key = 10)] - pub run_receipt_path: String, - #[cultcache(key = 11)] - pub hands_intent_id: String, - #[cultcache(key = 12)] - pub queued_hands_review_id: String, - #[cultcache(key = 13)] - pub substrate_grant_receipt_id: String, - #[cultcache(key = 14)] - pub action_id: String, - #[cultcache(key = 15)] - pub action_command: String, - #[cultcache(key = 16)] - pub action_commit_message: String, - #[cultcache(key = 17)] - pub changed_paths: Vec, - #[cultcache(key = 18)] - pub reviewed_at: String, - #[cultcache(key = 19)] - pub private_state_exposed: bool, -} - -/// The only capability that converts an accepted Mind review into Hands authority. -#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "epiphany.repo_work.hands_grant", schema = "RepoWorkHandsGrant")] -pub struct RepoWorkHandsGrant { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub grant_id: String, - #[cultcache(key = 2)] - pub adoption_review_id: String, - #[cultcache(key = 3)] - pub adoption_review_sha256: String, - #[cultcache(key = 4)] - pub workspace_identity: String, - #[cultcache(key = 5)] - pub item: String, - #[cultcache(key = 6)] - pub plan_id: String, - #[cultcache(key = 7)] - pub plan_sha256: String, - #[cultcache(key = 8)] - pub run_receipt_sha256: String, - #[cultcache(key = 9)] - pub plan_receipt_path: String, - #[cultcache(key = 10)] - pub run_receipt_path: String, - #[cultcache(key = 11)] - pub hands_intent_id: String, - #[cultcache(key = 12)] - pub queued_hands_review_id: String, - #[cultcache(key = 13)] - pub approved_hands_review_id: String, - #[cultcache(key = 14)] - pub substrate_grant_receipt_id: String, - #[cultcache(key = 15)] - pub action_id: String, - #[cultcache(key = 16)] - pub action_command: String, - #[cultcache(key = 17)] - pub action_commit_message: String, - #[cultcache(key = 18)] - pub allowed_operations: Vec, - #[cultcache(key = 19)] - pub changed_paths: Vec, - #[cultcache(key = 20)] - pub granted_at: String, - #[cultcache(key = 21)] - pub private_state_exposed: bool, -} - #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum MindGatewayDecision { diff --git a/epiphany-core/src/modeling_gateway.rs b/epiphany-core/src/modeling_gateway.rs deleted file mode 100644 index 6a9c98b0..00000000 --- a/epiphany-core/src/modeling_gateway.rs +++ /dev/null @@ -1,155 +0,0 @@ -use cultcache_rs::DatabaseEntry; - -pub const REPO_WORK_MODELING_FINDING_TYPE: &str = "epiphany.modeling.repo_work_finding"; -pub const REPO_WORK_MODELING_FINDING_SCHEMA_VERSION: &str = - "epiphany.modeling.repo_work_finding.v0"; -pub const REPO_WORK_MODELING_REQUEST_TYPE: &str = "epiphany.modeling.repo_work_request"; -pub const REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION: &str = - "epiphany.modeling.repo_work_request.v0"; -pub const REPO_WORK_MODELING_ROUTE_TYPE: &str = "epiphany.modeling.repo_work_route"; -pub const REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION: &str = "epiphany.modeling.repo_work_route.v0"; -pub const REPO_WORK_MAP_ENTRY_TYPE: &str = "epiphany.repo_work.map_entry"; -pub const REPO_WORK_MAP_ENTRY_SCHEMA_VERSION: &str = "epiphany.repo_work.map_entry.v0"; - -#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "epiphany.modeling.repo_work_finding", - schema = "RepoWorkModelingFinding" -)] -pub struct RepoWorkModelingFinding { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub receipt_id: String, - #[cultcache(key = 2)] - pub item: String, - #[cultcache(key = 3)] - pub model_ref: String, - #[cultcache(key = 4)] - pub soul_verdict_receipt_id: String, - #[cultcache(key = 5)] - pub verdict: String, - #[cultcache(key = 6)] - pub finding: String, - #[cultcache(key = 7)] - pub summary: String, - #[cultcache(key = 8)] - pub changed_paths: Vec, - #[cultcache(key = 9)] - pub commit_sha: String, - #[cultcache(key = 10)] - pub emitted_at: String, - #[cultcache(key = 11)] - pub private_state_exposed: bool, - #[cultcache(key = 12)] - pub contract: String, - #[cultcache(key = 13)] - pub request_id: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "epiphany.modeling.repo_work_request", - schema = "RepoWorkModelingRequest" -)] -pub struct RepoWorkModelingRequest { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub request_id: String, - #[cultcache(key = 2)] - pub item: String, - #[cultcache(key = 3)] - pub requester: String, - #[cultcache(key = 4)] - pub soul_verdict_receipt_id: String, - #[cultcache(key = 5)] - pub commit_sha: String, - #[cultcache(key = 6)] - pub changed_paths: Vec, - #[cultcache(key = 7)] - pub instruction: String, - #[cultcache(key = 8)] - pub requested_at: String, - #[cultcache(key = 9)] - pub private_state_exposed: bool, - #[cultcache(key = 10)] - pub contract: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)] -#[cultcache( - type = "epiphany.modeling.repo_work_route", - schema = "RepoWorkModelingRoute" -)] -pub struct RepoWorkModelingRoute { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub route_id: String, - #[cultcache(key = 2)] - pub item: String, - #[cultcache(key = 3)] - pub generation: u64, - #[cultcache(key = 4)] - pub request_id: String, - #[cultcache(key = 5)] - pub previous_finding_receipt_id: String, - #[cultcache(key = 6)] - pub authority_owner: String, - #[cultcache(key = 7)] - pub authority_witness_id: String, - #[cultcache(key = 8)] - pub updated_at: String, - #[cultcache(key = 9)] - pub private_state_exposed: bool, - #[cultcache(key = 10)] - pub contract: String, -} - -#[derive(Debug, Clone, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "epiphany.repo_work.map_entry", schema = "RepoWorkMapEntry")] -pub struct RepoWorkMapEntry { - #[cultcache(key = 0)] - pub schema_version: String, - #[cultcache(key = 1)] - pub map_entry_id: String, - #[cultcache(key = 2)] - pub admitted_at: String, - #[cultcache(key = 3)] - pub item: String, - #[cultcache(key = 4)] - pub branch: String, - #[cultcache(key = 5)] - pub changed_paths: Vec, - #[cultcache(key = 6)] - pub commit_sha: String, - #[cultcache(key = 7)] - pub safe_action_family: String, - #[cultcache(key = 8)] - pub modeling_summary: String, - #[cultcache(key = 9)] - pub modeling_finding_receipt_id: String, - #[cultcache(key = 10)] - pub soul_verdict_receipt_id: String, - #[cultcache(key = 11)] - pub mind_gateway_review_id: String, - #[cultcache(key = 12)] - pub mind_state_commit_receipt_id: String, - #[cultcache(key = 13)] - pub execute_receipt_path: String, - #[cultcache(key = 14)] - pub closure_review_path: String, - #[cultcache(key = 15)] - pub closure_receipt_path: String, - #[cultcache(key = 16)] - pub publication_gate: String, - #[cultcache(key = 17)] - pub durable_state_admitted: bool, - #[cultcache(key = 18)] - pub private_state_exposed: bool, - #[cultcache(key = 19)] - pub modeling_route_id: String, - #[cultcache(key = 20)] - pub modeling_generation: u64, -} diff --git a/epiphany-core/src/runtime_spine.rs b/epiphany-core/src/runtime_spine.rs index be7792da..497f31c0 100644 --- a/epiphany-core/src/runtime_spine.rs +++ b/epiphany-core/src/runtime_spine.rs @@ -39,21 +39,6 @@ use crate::mind_gateway::MIND_VERSE_ADOPTION_RECEIPT_TYPE; use crate::mind_gateway::MindGatewayDecision; use crate::mind_gateway::MindGatewayReview; use crate::mind_gateway::MindStateCommitReceipt; -use crate::mind_gateway::RepoWorkHandsGrant; -use crate::mind_gateway::RepoWorkPlanAdoptionDecision; -use crate::mind_gateway::RepoWorkPlanAdoptionReview; -use crate::modeling_gateway::REPO_WORK_MAP_ENTRY_SCHEMA_VERSION; -use crate::modeling_gateway::REPO_WORK_MAP_ENTRY_TYPE; -use crate::modeling_gateway::REPO_WORK_MODELING_FINDING_SCHEMA_VERSION; -use crate::modeling_gateway::REPO_WORK_MODELING_FINDING_TYPE; -use crate::modeling_gateway::REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION; -use crate::modeling_gateway::REPO_WORK_MODELING_REQUEST_TYPE; -use crate::modeling_gateway::REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION; -use crate::modeling_gateway::REPO_WORK_MODELING_ROUTE_TYPE; -use crate::modeling_gateway::RepoWorkMapEntry; -use crate::modeling_gateway::RepoWorkModelingFinding; -use crate::modeling_gateway::RepoWorkModelingRequest; -use crate::modeling_gateway::RepoWorkModelingRoute; use crate::organ_dependencies::EpiphanyLaunchOrganContract; use crate::repo_model_gateway::{ REPO_FRONTIER_HANDS_AUTHORITY_CONTRACT, REPO_FRONTIER_HANDS_AUTHORITY_SCHEMA_VERSION, @@ -775,12 +760,6 @@ pub fn runtime_spine_cache(store_path: impl AsRef) -> Result { cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; - cache.register_entry_type::()?; - cache.register_entry_type::()?; - cache.register_entry_type::()?; - cache.register_entry_type::()?; - cache.register_entry_type::()?; - cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; cache.register_entry_type::()?; @@ -2087,7 +2066,9 @@ pub fn put_substrate_gate_repo_access_grant_receipt( require_identity(&cache)?; let (envelope, _) = cache.prepare_entry(&receipt.receipt_id, receipt)?; let backing = SingleFileMessagePackBackingStore::new(store_path); - if backing.compare_and_swap_batch(&[], vec![envelope])? { return Ok(()); } + if backing.compare_and_swap_batch(&[], vec![envelope])? { + return Ok(()); + } let mut reloaded = runtime_spine_cache(store_path)?; reloaded.pull_all_backing_stores()?; match reloaded.get::(&receipt.receipt_id)? { @@ -2161,7 +2142,9 @@ pub fn put_hands_action_intent( } let (envelope, _) = cache.prepare_entry(&intent.intent_id, intent)?; let backing = SingleFileMessagePackBackingStore::new(store_path); - if backing.compare_and_swap_batch(&[], vec![envelope])? { return Ok(()); } + if backing.compare_and_swap_batch(&[], vec![envelope])? { + return Ok(()); + } let mut reloaded = runtime_spine_cache(store_path)?; reloaded.pull_all_backing_stores()?; match reloaded.get::(&intent.intent_id)? { @@ -2203,7 +2186,9 @@ pub fn put_hands_action_review( require_identity(&cache)?; let (envelope, _) = cache.prepare_entry(&review.review_id, review)?; let backing = SingleFileMessagePackBackingStore::new(store_path); - if backing.compare_and_swap_batch(&[], vec![envelope])? { return Ok(()); } + if backing.compare_and_swap_batch(&[], vec![envelope])? { + return Ok(()); + } let mut reloaded = runtime_spine_cache(store_path)?; reloaded.pull_all_backing_stores()?; match reloaded.get::(&review.review_id)? { @@ -2226,49 +2211,81 @@ fn validate_repo_frontier_hands_authority_chain( cache: &CultCache, authority: &RepoFrontierHandsAuthority, ) -> Result<()> { - let route = cache.get::(&authority.route_id)? + let route = cache + .get::(&authority.route_id)? .ok_or_else(|| anyhow!("Hands authority requires its persisted route"))?; - let current_entry = cache.get::(crate::MEMORY_GRAPH_KEY)? + let current_entry = cache + .get::(crate::MEMORY_GRAPH_KEY)? .ok_or_else(|| anyhow!("Hands authority requires the current model"))?; crate::validate_memory_graph_entry(¤t_entry)?; let current = current_entry.snapshot()?; - let intent = cache.get::(&authority.hands_intent_id)? + let intent = cache + .get::(&authority.hands_intent_id)? .ok_or_else(|| anyhow!("Hands authority requires its persisted intent"))?; - let review = cache.get::(&authority.hands_review_id)? + let review = cache + .get::(&authority.hands_review_id)? .ok_or_else(|| anyhow!("Hands authority requires its persisted review"))?; - let grant = cache.get::(&authority.substrate_grant_receipt_id)? + let grant = cache + .get::(&authority.substrate_grant_receipt_id)? .ok_or_else(|| anyhow!("Hands authority requires its persisted Substrate grant"))?; - let within_scope = authority.requested_paths.iter().all(|path| route.source_scope.iter().any(|scope| { - path == scope || path.starts_with(&format!("{}/", scope.trim_end_matches(['/', '\\']))) - })); + let within_scope = authority.requested_paths.iter().all(|path| { + route.source_scope.iter().any(|scope| { + path == scope || path.starts_with(&format!("{}/", scope.trim_end_matches(['/', '\\']))) + }) + }); let requested_operations: &[&str] = match intent.requested_action.as_str() { "patch" => &["patch"], "continueImplementation" => &["patch", "command", "commit"], - _ => return Err(anyhow!("Hands authority names an unsupported requested action")), + _ => { + return Err(anyhow!( + "Hands authority names an unsupported requested action" + )); + } }; if route.schema_version != REPO_FRONTIER_ROUTE_SCHEMA_VERSION || route.contract != REPO_FRONTIER_ROUTE_CONTRACT || intent.schema_version != HANDS_ACTION_INTENT_SCHEMA_VERSION || review.schema_version != HANDS_ACTION_REVIEW_SCHEMA_VERSION || grant.schema_version != SUBSTRATE_GATE_REPO_ACCESS_GRANT_RECEIPT_SCHEMA_VERSION - || intent.contract.trim().is_empty() || review.contract.trim().is_empty() || grant.contract.trim().is_empty() + || intent.contract.trim().is_empty() + || review.contract.trim().is_empty() + || grant.contract.trim().is_empty() || chrono::DateTime::parse_from_rfc3339(&intent.requested_at).is_err() || chrono::DateTime::parse_from_rfc3339(&review.reviewed_at).is_err() || chrono::DateTime::parse_from_rfc3339(&grant.granted_at).is_err() || route.next_organ != RepoFrontierNextOrgan::Hands - || authority.model_revision != route.model_revision || authority.model_hash != route.model_hash - || authority.frontier_item_id != route.frontier_item_id || authority.frontier_item_hash != route.frontier_item_hash - || current.model_revision != route.model_revision || crate::memory_graph_model_hash(¤t)? != route.model_hash - || review.intent_id != intent.intent_id || review.decision != "approved" - || !requested_operations.iter().all(|required| review.allowed_operations.iter().any(|operation| operation == required)) + || authority.model_revision != route.model_revision + || authority.model_hash != route.model_hash + || authority.frontier_item_id != route.frontier_item_id + || authority.frontier_item_hash != route.frontier_item_hash + || current.model_revision != route.model_revision + || crate::memory_graph_model_hash(¤t)? != route.model_hash + || review.intent_id != intent.intent_id + || review.decision != "approved" + || !requested_operations.iter().all(|required| { + review + .allowed_operations + .iter() + .any(|operation| operation == required) + }) || intent.substrate_gate_grant_receipt_id != grant.receipt_id - || grant.runtime_job_id != intent.runtime_job_id || grant.binding_id != intent.binding_id - || grant.role != intent.role || grant.authority_scope != intent.authority_scope - || !requested_operations.iter().all(|required| grant.granted_operations.iter().any(|operation| operation == required)) - || authority.requested_paths != intent.requested_paths || authority.requested_paths != grant.granted_paths + || grant.runtime_job_id != intent.runtime_job_id + || grant.binding_id != intent.binding_id + || grant.role != intent.role + || grant.authority_scope != intent.authority_scope + || !requested_operations.iter().all(|required| { + grant + .granted_operations + .iter() + .any(|operation| operation == required) + }) + || authority.requested_paths != intent.requested_paths + || authority.requested_paths != grant.granted_paths || !within_scope { - return Err(anyhow!("repo frontier Hands authority chain violates its full authority contract")); + return Err(anyhow!( + "repo frontier Hands authority chain violates its full authority contract" + )); } Ok(()) } @@ -2717,193 +2734,6 @@ pub fn commit_repo_frontier_verification_request_for_chain( Ok(request) } -pub fn put_repo_work_plan_adoption_review( - store_path: impl AsRef, - review: &RepoWorkPlanAdoptionReview, -) -> Result<()> { - validate_repo_work_plan_adoption_review(review)?; - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - require_identity(&cache)?; - if let Some(existing) = cache.get::(&review.review_id)? { - if existing == *review { - return Ok(()); - } - return Err(anyhow!( - "repo-work plan adoption review ids are immutable; {} already names different bytes", - review.review_id - )); - } - cache.put(&review.review_id, review)?; - Ok(()) -} - -pub fn runtime_repo_work_plan_adoption_review( - store_path: impl AsRef, - review_id: &str, -) -> Result> { - validate_non_empty(review_id, "repo-work plan adoption review id")?; - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - cache.get::(review_id) -} - -pub fn runtime_repo_work_hands_grant( - store_path: impl AsRef, - grant_id: &str, -) -> Result> { - validate_non_empty(grant_id, "repo-work Hands grant id")?; - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - cache.get::(grant_id) -} - -/// Atomically publishes the capability and its approved generic Hands review. -/// Neither document is observable unless both pass validation and the backing-store swap succeeds. -pub fn commit_repo_work_hands_grant( - store_path: impl AsRef, - grant: &RepoWorkHandsGrant, - approved_review: &HandsActionReview, -) -> Result<()> { - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - require_identity(&cache)?; - let adoption = cache - .get::(&grant.adoption_review_id)? - .ok_or_else(|| { - anyhow!("repo-work Hands grant requires its persisted Mind adoption review") - })?; - validate_repo_work_plan_adoption_review(&adoption)?; - let persisted_adoption_sha256 = format!("{:x}", Sha256::digest(serde_json::to_vec(&adoption)?)); - if adoption.decision != RepoWorkPlanAdoptionDecision::Adopt - || grant.schema_version != crate::mind_gateway::REPO_WORK_HANDS_GRANT_SCHEMA_VERSION - || grant.private_state_exposed - || !valid_lower_sha256(&grant.adoption_review_sha256) - || grant.adoption_review_sha256 != persisted_adoption_sha256 - || !valid_lower_sha256(&grant.plan_sha256) - || !valid_lower_sha256(&grant.run_receipt_sha256) - || chrono::DateTime::parse_from_rfc3339(&grant.granted_at).is_err() - || !safe_sorted_unique_paths(&grant.changed_paths) - || grant.adoption_review_id != adoption.review_id - || grant.workspace_identity != adoption.workspace_identity - || grant.item != adoption.item - || grant.plan_id != adoption.plan_id - || grant.plan_sha256 != adoption.plan_sha256 - || grant.run_receipt_sha256 != adoption.run_receipt_sha256 - || grant.plan_receipt_path != adoption.plan_receipt_path - || grant.run_receipt_path != adoption.run_receipt_path - || grant.hands_intent_id != adoption.hands_intent_id - || grant.queued_hands_review_id != adoption.queued_hands_review_id - || grant.substrate_grant_receipt_id != adoption.substrate_grant_receipt_id - || grant.action_id != adoption.action_id - || grant.action_command != adoption.action_command - || grant.action_commit_message != adoption.action_commit_message - || grant.changed_paths != adoption.changed_paths - || approved_review.review_id != grant.approved_hands_review_id - || approved_review.intent_id != grant.hands_intent_id - || approved_review.decision != "approved" - || approved_review.allowed_operations != grant.allowed_operations - { - return Err(anyhow!( - "repo-work Hands grant does not exactly bind its accepted Mind review and approved Hands review" - )); - } - let intent = cache - .get::(&grant.hands_intent_id)? - .ok_or_else(|| anyhow!("repo-work Hands grant requires its persisted Hands intent"))?; - let queued = cache - .get::(&grant.queued_hands_review_id)? - .ok_or_else(|| anyhow!("repo-work Hands grant requires its queued Hands review"))?; - if intent.intent_id != queued.intent_id - || queued.decision != "queued-for-adoption" - || intent.substrate_gate_grant_receipt_id != grant.substrate_grant_receipt_id - || intent.requested_paths != grant.changed_paths - { - return Err(anyhow!( - "repo-work Hands grant authority chain is inconsistent" - )); - } - let existing_grant = cache.get::(&grant.grant_id)?; - let existing_review = cache.get::(&approved_review.review_id)?; - match (existing_grant, existing_review) { - (None, None) => {} - (Some(existing_grant), Some(existing_review)) - if existing_grant == *grant && existing_review == *approved_review => - { - return Ok(()); - } - _ => { - return Err(anyhow!( - "repo-work Hands grant and approved review ids are an immutable pair" - )); - } - } - let (grant_entry, _) = cache.prepare_entry(&grant.grant_id, grant)?; - let (review_entry, _) = cache.prepare_entry(&approved_review.review_id, approved_review)?; - cache.put_prepared_batch(vec![grant_entry, review_entry]) -} - -fn validate_repo_work_plan_adoption_review(review: &RepoWorkPlanAdoptionReview) -> Result<()> { - validate_non_empty(&review.review_id, "repo-work plan adoption review id")?; - validate_non_empty(&review.workspace_identity, "repo-work workspace identity")?; - validate_non_empty(&review.item, "repo-work item")?; - validate_non_empty(&review.plan_id, "repo-work plan id")?; - validate_non_empty(&review.plan_sha256, "repo-work plan SHA-256")?; - validate_non_empty(&review.run_receipt_sha256, "repo-work run receipt SHA-256")?; - validate_non_empty(&review.plan_receipt_path, "repo-work plan receipt path")?; - validate_non_empty(&review.run_receipt_path, "repo-work run receipt path")?; - validate_non_empty(&review.hands_intent_id, "repo-work Hands intent")?; - validate_non_empty( - &review.queued_hands_review_id, - "repo-work queued Hands review", - )?; - validate_non_empty( - &review.substrate_grant_receipt_id, - "repo-work Substrate grant", - )?; - validate_non_empty(&review.action_id, "repo-work action id")?; - validate_non_empty(&review.action_command, "repo-work action command")?; - validate_non_empty( - &review.action_commit_message, - "repo-work action commit message", - )?; - validate_non_empty(&review.reviewed_at, "repo-work adoption review timestamp")?; - let valid_sha256 = - |value: &str| value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit()); - let normalized_paths = review - .changed_paths - .iter() - .map(|path| path.replace('\\', "/")) - .collect::>(); - let mut sorted_paths = normalized_paths.clone(); - sorted_paths.sort(); - sorted_paths.dedup(); - if review.schema_version != crate::mind_gateway::REPO_WORK_PLAN_ADOPTION_REVIEW_SCHEMA_VERSION - || review.plan_schema_version != "epiphany.repo_work_action_plan_receipt.v0" - || !valid_sha256(&review.plan_sha256) - || !valid_sha256(&review.run_receipt_sha256) - || review.private_state_exposed - || review.changed_paths.is_empty() - || !valid_lower_sha256(&review.plan_sha256) - || !valid_lower_sha256(&review.run_receipt_sha256) - || !Path::new(&review.plan_receipt_path).is_absolute() - || !Path::new(&review.run_receipt_path).is_absolute() - || chrono::DateTime::parse_from_rfc3339(&review.reviewed_at).is_err() - || !safe_sorted_unique_paths(&review.changed_paths) - || review.changed_paths != sorted_paths - { - return Err(anyhow!("invalid repo-work plan adoption review contract")); - } - Ok(()) -} - -fn valid_lower_sha256(value: &str) -> bool { - value.len() == 64 - && value - .bytes() - .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) -} - fn safe_sorted_unique_paths(paths: &[String]) -> bool { paths.windows(2).all(|pair| pair[0] < pair[1]) && paths.iter().all(|path| { @@ -3363,394 +3193,6 @@ pub fn runtime_soul_verdict_receipt( cache.get::(receipt_id) } -pub fn put_repo_work_modeling_finding( - store_path: impl AsRef, - finding: &RepoWorkModelingFinding, -) -> Result<()> { - validate_non_empty(&finding.receipt_id, "Modeling finding receipt id")?; - validate_non_empty(&finding.item, "Modeling finding item")?; - validate_non_empty(&finding.model_ref, "Modeling finding model ref")?; - validate_non_empty( - &finding.soul_verdict_receipt_id, - "Modeling finding Soul verdict receipt id", - )?; - validate_non_empty(&finding.verdict, "Modeling finding verdict")?; - validate_non_empty(&finding.finding, "Modeling finding text")?; - validate_non_empty(&finding.commit_sha, "Modeling finding commit sha")?; - validate_non_empty(&finding.emitted_at, "Modeling finding timestamp")?; - if finding.schema_version != REPO_WORK_MODELING_FINDING_SCHEMA_VERSION { - return Err(anyhow!("unsupported Modeling finding schema")); - } - if finding.private_state_exposed { - return Err(anyhow!("Modeling finding cannot expose private state")); - } - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - require_identity(&cache)?; - let request = cache - .get::(&finding.request_id)? - .ok_or_else(|| anyhow!("Modeling finding requires its typed request"))?; - let soul = cache - .get::(&finding.soul_verdict_receipt_id)? - .ok_or_else(|| anyhow!("Modeling finding requires its Soul verdict receipt"))?; - if soul.verdict.trim().to_ascii_lowercase() != "passed" { - return Err(anyhow!( - "Modeling finding requires a passing Soul verdict receipt" - )); - } - if request.item != finding.item - || request.soul_verdict_receipt_id != finding.soul_verdict_receipt_id - || request.commit_sha != finding.commit_sha - || request.changed_paths != finding.changed_paths - { - return Err(anyhow!( - "Modeling finding does not answer its typed request" - )); - } - if let Some(existing) = cache.get::(&finding.receipt_id)? { - if existing == *finding { - return Ok(()); - } - return Err(anyhow!( - "Modeling finding receipt id already belongs to different immutable evidence" - )); - } - cache.put(&finding.receipt_id, finding)?; - Ok(()) -} - -pub fn put_repo_work_modeling_request( - store_path: impl AsRef, - request: &RepoWorkModelingRequest, -) -> Result<()> { - if request.schema_version != REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION { - return Err(anyhow!("unsupported Modeling request schema")); - } - validate_non_empty(&request.request_id, "Modeling request id")?; - validate_non_empty(&request.item, "Modeling request item")?; - validate_non_empty(&request.requester, "Modeling request requester")?; - validate_non_empty( - &request.soul_verdict_receipt_id, - "Modeling request Soul verdict receipt id", - )?; - validate_non_empty(&request.commit_sha, "Modeling request commit sha")?; - validate_non_empty(&request.instruction, "Modeling request instruction")?; - validate_non_empty(&request.requested_at, "Modeling request timestamp")?; - if request.requester != "self" || request.private_state_exposed { - return Err(anyhow!( - "repo-work Modeling requests must be Self-routed and private-state sealed" - )); - } - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - require_identity(&cache)?; - let soul = cache - .get::(&request.soul_verdict_receipt_id)? - .ok_or_else(|| anyhow!("Modeling request requires its Soul verdict receipt"))?; - if soul.verdict.trim().to_ascii_lowercase() != "passed" { - return Err(anyhow!("Modeling request requires a passing Soul verdict")); - } - if let Some(existing) = cache.get::(&request.request_id)? { - if existing == *request { - return Ok(()); - } - return Err(anyhow!( - "Modeling request id already belongs to different immutable work" - )); - } - cache.put(&request.request_id, request)?; - Ok(()) -} - -pub fn runtime_repo_work_modeling_request( - store_path: impl AsRef, - request_id: &str, -) -> Result> { - validate_non_empty(request_id, "Modeling request id")?; - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - cache.get::(request_id) -} - -pub fn commit_initial_repo_work_modeling_route( - store_path: impl AsRef, - request: &RepoWorkModelingRequest, - route: &RepoWorkModelingRoute, -) -> Result { - if request.schema_version != REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION { - return Err(anyhow!("unsupported Modeling request schema")); - } - validate_non_empty(&request.request_id, "Modeling request id")?; - validate_non_empty(&request.item, "Modeling request item")?; - validate_non_empty( - &request.soul_verdict_receipt_id, - "Modeling request Soul verdict receipt id", - )?; - validate_non_empty(&request.commit_sha, "Modeling request commit sha")?; - validate_non_empty(&request.instruction, "Modeling request instruction")?; - validate_non_empty(&request.requested_at, "Modeling request timestamp")?; - if request.requester != "self" || request.private_state_exposed { - return Err(anyhow!( - "initial Modeling request must be Self-routed and private-state sealed" - )); - } - if route.schema_version != REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION { - return Err(anyhow!("unsupported Modeling route schema")); - } - validate_non_empty(&route.route_id, "Modeling route id")?; - validate_non_empty(&route.item, "Modeling route item")?; - validate_non_empty(&route.request_id, "Modeling route request id")?; - validate_non_empty(&route.authority_owner, "Modeling route authority owner")?; - validate_non_empty( - &route.authority_witness_id, - "Modeling route authority witness", - )?; - validate_non_empty(&route.updated_at, "Modeling route timestamp")?; - if route.generation != 0 - || !route.previous_finding_receipt_id.is_empty() - || route.authority_owner != "soul" - || route.authority_witness_id != request.soul_verdict_receipt_id - || route.item != request.item - || route.request_id != request.request_id - || route.private_state_exposed - { - return Err(anyhow!( - "initial Modeling route must be generation zero, Soul-backed, request-matched, and private-state sealed" - )); - } - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - require_identity(&cache)?; - let soul = cache - .get::(&request.soul_verdict_receipt_id)? - .ok_or_else(|| anyhow!("initial Modeling route requires its Soul verdict"))?; - if soul.verdict.trim().to_ascii_lowercase() != "passed" { - return Err(anyhow!( - "initial Modeling route requires passing Soul truth" - )); - } - if let Some(existing) = cache.get::(&route.route_id)? { - let stored_request = cache - .get::(&existing.request_id)? - .ok_or_else(|| anyhow!("existing Modeling route lost its request"))?; - if existing == *route && stored_request == *request { - return Ok(existing); - } - return Err(anyhow!( - "initial Modeling route already belongs to different routing truth" - )); - } - if cache - .get::(&request.request_id)? - .is_some() - { - return Err(anyhow!( - "Modeling request exists without its atomic initial route" - )); - } - let (request_envelope, _) = cache.prepare_entry(&request.request_id, request)?; - let (route_envelope, _) = cache.prepare_entry(&route.route_id, route)?; - cache.put_prepared_batch(vec![request_envelope, route_envelope])?; - Ok(route.clone()) -} - -pub fn runtime_repo_work_modeling_route( - store_path: impl AsRef, - route_id: &str, -) -> Result> { - validate_non_empty(route_id, "Modeling route id")?; - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - cache.get::(route_id) -} - -pub fn advance_repo_work_modeling_route( - store_path: impl AsRef, - request: &RepoWorkModelingRequest, - route: &RepoWorkModelingRoute, - mind_review: &MindGatewayReview, -) -> Result { - if request.schema_version != REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION - || route.schema_version != REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION - { - return Err(anyhow!("unsupported Modeling route generation schema")); - } - validate_non_empty(&request.request_id, "next Modeling request id")?; - validate_non_empty(&request.item, "next Modeling request item")?; - validate_non_empty( - &request.soul_verdict_receipt_id, - "next Modeling request Soul verdict", - )?; - validate_non_empty(&request.commit_sha, "next Modeling request commit")?; - validate_non_empty(&request.instruction, "next Modeling request instruction")?; - validate_non_empty(&request.requested_at, "next Modeling request timestamp")?; - validate_non_empty(&route.route_id, "Modeling route id")?; - validate_non_empty( - &route.previous_finding_receipt_id, - "previous Modeling finding receipt id", - )?; - validate_non_empty(&route.updated_at, "next Modeling route timestamp")?; - if request.requester != "mind" - || request.private_state_exposed - || route.private_state_exposed - || route.authority_owner != "mind" - || route.authority_witness_id != mind_review.gateway_id - || route.request_id != request.request_id - || route.item != request.item - || mind_review.decision != MindGatewayDecision::Accept - || mind_review.source_kind != "repo_work_modeling_revision" - || !mind_review - .allowed_effects - .iter() - .any(|effect| effect == "repoWork.modelingRoute") - { - return Err(anyhow!( - "next Modeling generation requires a private-state-sealed Mind acceptance that owns only the route transition" - )); - } - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - require_identity(&cache)?; - let current = cache - .get::(&route.route_id)? - .ok_or_else(|| anyhow!("cannot advance a missing Modeling route"))?; - let current_request = cache - .get::(¤t.request_id)? - .ok_or_else(|| anyhow!("current Modeling route lost its request"))?; - let previous_finding = cache - .get::(&route.previous_finding_receipt_id)? - .ok_or_else(|| anyhow!("next Modeling generation requires the previous finding"))?; - if route.generation != current.generation.saturating_add(1) - || previous_finding.request_id != current.request_id - || previous_finding.item != current.item - || previous_finding - .verdict - .trim() - .eq_ignore_ascii_case("passed") - || request.item != current_request.item - || request.soul_verdict_receipt_id != current_request.soul_verdict_receipt_id - || request.commit_sha != current_request.commit_sha - || request.changed_paths != current_request.changed_paths - { - return Err(anyhow!( - "next Modeling generation must follow one non-passing current finding and preserve the Soul-verified consequence" - )); - } - if cache - .get::(&request.request_id)? - .is_some() - { - return Err(anyhow!("next Modeling request id already exists")); - } - let (request_envelope, _) = cache.prepare_entry(&request.request_id, request)?; - let (review_envelope, _) = cache.prepare_entry(&mind_review.gateway_id, mind_review)?; - let (route_envelope, _) = cache.prepare_entry(&route.route_id, route)?; - cache.put_prepared_batch(vec![request_envelope, review_envelope, route_envelope])?; - Ok(route.clone()) -} - -pub fn runtime_repo_work_modeling_finding( - store_path: impl AsRef, - receipt_id: &str, -) -> Result> { - validate_non_empty(receipt_id, "Modeling finding receipt id")?; - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - cache.get::(receipt_id) -} - -pub fn commit_repo_work_map_admission( - store_path: impl AsRef, - entry: &RepoWorkMapEntry, - mind_review: &MindGatewayReview, - mind_commit: &MindStateCommitReceipt, -) -> Result { - if entry.schema_version != REPO_WORK_MAP_ENTRY_SCHEMA_VERSION { - return Err(anyhow!("unsupported repo-work map entry schema")); - } - validate_non_empty(&entry.map_entry_id, "repo-work map entry id")?; - validate_non_empty(&entry.item, "repo-work map item")?; - validate_non_empty( - &entry.modeling_finding_receipt_id, - "repo-work map Modeling finding receipt id", - )?; - validate_non_empty(&entry.modeling_route_id, "repo-work map Modeling route id")?; - if !entry.durable_state_admitted || entry.private_state_exposed { - return Err(anyhow!( - "repo-work map admission requires admitted, private-state-sealed state" - )); - } - if entry.mind_gateway_review_id != mind_review.gateway_id - || entry.mind_state_commit_receipt_id != mind_commit.receipt_id - || mind_commit.gateway_id != mind_review.gateway_id - { - return Err(anyhow!( - "repo-work map entry and Mind witnesses do not share one identity" - )); - } - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - require_identity(&cache)?; - let modeling = cache - .get::(&entry.modeling_finding_receipt_id)? - .ok_or_else(|| anyhow!("repo-work map admission requires typed Modeling finding"))?; - let route = cache - .get::(&entry.modeling_route_id)? - .ok_or_else(|| anyhow!("repo-work map admission requires current Modeling route"))?; - if modeling.item != entry.item - || modeling.soul_verdict_receipt_id != entry.soul_verdict_receipt_id - || modeling.commit_sha != entry.commit_sha - || modeling.changed_paths != entry.changed_paths - || modeling.summary != entry.modeling_summary - || modeling.verdict.trim().to_ascii_lowercase() != "passed" - || route.item != entry.item - || route.generation != entry.modeling_generation - || route.request_id != modeling.request_id - { - return Err(anyhow!( - "repo-work map entry does not match its passing current-generation Modeling finding" - )); - } - if let Some(existing) = cache.get::(&entry.map_entry_id)? { - let mut candidate = entry.clone(); - candidate.admitted_at = existing.admitted_at.clone(); - if existing != candidate { - return Err(anyhow!( - "repo-work map entry id already belongs to different admitted state" - )); - } - let stored_review = cache - .get::(&existing.mind_gateway_review_id)? - .ok_or_else(|| anyhow!("admitted repo-work map is missing its Mind review"))?; - let stored_commit = cache - .get::(&existing.mind_state_commit_receipt_id)? - .ok_or_else(|| anyhow!("admitted repo-work map is missing its Mind commit"))?; - if stored_review.gateway_id != existing.mind_gateway_review_id - || stored_commit.gateway_id != stored_review.gateway_id - { - return Err(anyhow!( - "admitted repo-work map has incoherent Mind witnesses" - )); - } - return Ok(existing); - } - let (review_envelope, _) = cache.prepare_entry(&mind_review.gateway_id, mind_review)?; - let (commit_envelope, _) = cache.prepare_entry(&mind_commit.receipt_id, mind_commit)?; - let (map_envelope, _) = cache.prepare_entry(&entry.map_entry_id, entry)?; - cache.put_prepared_batch(vec![review_envelope, commit_envelope, map_envelope])?; - Ok(entry.clone()) -} - -pub fn runtime_repo_work_map_entry( - store_path: impl AsRef, - map_entry_id: &str, -) -> Result> { - validate_non_empty(map_entry_id, "repo-work map entry id")?; - let mut cache = runtime_spine_cache(store_path)?; - cache.pull_all_backing_stores()?; - cache.get::(map_entry_id) -} - pub fn put_continuity_recovery_receipt( store_path: impl AsRef, receipt: &ContinuityRecoveryReceipt, @@ -4337,69 +3779,6 @@ fn epiphany_mutation_contracts() -> Vec { "Job results are evidence records; review and acceptance are separate typed flows.", ], ), - mutation_contract( - REPO_WORK_MODELING_REQUEST_TYPE, - REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION, - vec![ - CultNetDocumentOperation::Snapshot, - CultNetDocumentOperation::IntentSubmit, - CultNetDocumentOperation::ReceiptWatch, - ], - CultNetMutationAuthority::Coordinator, - vec![REPO_WORK_MODELING_REQUEST_TYPE], - vec![REPO_WORK_MODELING_FINDING_TYPE], - vec![ - "Self routes Soul-verified repo consequence to Modeling through this request.", - "The request grants no authority to author the Modeling result.", - ], - ), - mutation_contract( - REPO_WORK_MODELING_FINDING_TYPE, - REPO_WORK_MODELING_FINDING_SCHEMA_VERSION, - vec![ - CultNetDocumentOperation::Snapshot, - CultNetDocumentOperation::ReceiptWatch, - ], - CultNetMutationAuthority::ReadOnly, - vec![], - vec![], - vec![ - "Modeling findings interpret a Soul-verified repo consequence before Mind admits a map update.", - "Schedulers and raw CLI fields cannot substitute for this persisted receipt.", - ], - ), - mutation_contract( - REPO_WORK_MODELING_ROUTE_TYPE, - REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION, - vec![ - CultNetDocumentOperation::Snapshot, - CultNetDocumentOperation::IntentSubmit, - CultNetDocumentOperation::ReceiptWatch, - ], - CultNetMutationAuthority::Coordinator, - vec![REPO_WORK_MODELING_REQUEST_TYPE, MIND_GATEWAY_REVIEW_TYPE], - vec![REPO_WORK_MODELING_ROUTE_TYPE], - vec![ - "The route is the sole current-generation owner for repo-work Modeling requests.", - "Generation zero is Soul-backed; later generations require a Mind review and preserve the previous finding.", - "Filesystem closure artifacts and Self are projections/routers, not route writers.", - ], - ), - mutation_contract( - REPO_WORK_MAP_ENTRY_TYPE, - REPO_WORK_MAP_ENTRY_SCHEMA_VERSION, - vec![ - CultNetDocumentOperation::Snapshot, - CultNetDocumentOperation::ReceiptWatch, - ], - CultNetMutationAuthority::ReadOnly, - vec![], - vec![], - vec![ - "Repo-work map entries are Mind-admitted durable state committed atomically with their Mind witnesses.", - "CultMesh rows are projections of this entry, not a second map owner.", - ], - ), mutation_contract( MIND_THOUGHT_TYPE, MIND_THOUGHT_SCHEMA_VERSION, @@ -6546,46 +5925,116 @@ mod tests { fn hands_authority_documents_choose_one_immutable_identity_under_race() -> Result<()> { let temp = tempdir()?; let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine(&store, RuntimeSpineInitOptions { - runtime_id: "authority-race".to_string(), display_name: "Authority Race".to_string(), - created_at: "2026-07-13T05:30:00Z".to_string(), - })?; + initialize_runtime_spine( + &store, + RuntimeSpineInitOptions { + runtime_id: "authority-race".to_string(), + display_name: "Authority Race".to_string(), + created_at: "2026-07-13T05:30:00Z".to_string(), + }, + )?; let base_grant = crate::substrate_gate_coordinator_implementation_grant( - "race-grant".to_string(), "race-job".to_string(), vec!["epiphany-core/src".to_string()], - "2026-07-13T05:30:00Z".to_string()); - let mut other_grant = base_grant.clone(); other_grant.granted_paths = vec!["epiphany-core/tests".to_string()]; + "race-grant".to_string(), + "race-job".to_string(), + vec!["epiphany-core/src".to_string()], + "2026-07-13T05:30:00Z".to_string(), + ); + let mut other_grant = base_grant.clone(); + other_grant.granted_paths = vec!["epiphany-core/tests".to_string()]; let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); - let outcomes = [base_grant.clone(), other_grant.clone()].into_iter().map(|grant| { - let path = store.clone(); let barrier = barrier.clone(); - std::thread::spawn(move || { barrier.wait(); put_substrate_gate_repo_access_grant_receipt(path, &grant) }) - }).collect::>(); - assert_eq!(outcomes.into_iter().map(|outcome| outcome.join().unwrap()).filter(Result::is_ok).count(), 1); - let winner = runtime_substrate_gate_repo_access_grant_receipt(&store, "race-grant")?.unwrap(); + let outcomes = [base_grant.clone(), other_grant.clone()] + .into_iter() + .map(|grant| { + let path = store.clone(); + let barrier = barrier.clone(); + std::thread::spawn(move || { + barrier.wait(); + put_substrate_gate_repo_access_grant_receipt(path, &grant) + }) + }) + .collect::>(); + assert_eq!( + outcomes + .into_iter() + .map(|outcome| outcome.join().unwrap()) + .filter(Result::is_ok) + .count(), + 1 + ); + let winner = + runtime_substrate_gate_repo_access_grant_receipt(&store, "race-grant")?.unwrap(); - let base_intent = HandsActionIntent { schema_version: HANDS_ACTION_INTENT_SCHEMA_VERSION.to_string(), - intent_id: "race-intent".to_string(), runtime_job_id: winner.runtime_job_id.clone(), binding_id: winner.binding_id.clone(), - role: winner.role.clone(), authority_scope: winner.authority_scope.clone(), requested_action: "patch".to_string(), - requested_paths: winner.granted_paths.clone(), substrate_gate_grant_receipt_id: winner.receipt_id.clone(), - requested_at: "2026-07-13T05:30:01Z".to_string(), contract: "race intent".to_string() }; - let mut other_intent = base_intent.clone(); other_intent.requested_action = "continueImplementation".to_string(); + let base_intent = HandsActionIntent { + schema_version: HANDS_ACTION_INTENT_SCHEMA_VERSION.to_string(), + intent_id: "race-intent".to_string(), + runtime_job_id: winner.runtime_job_id.clone(), + binding_id: winner.binding_id.clone(), + role: winner.role.clone(), + authority_scope: winner.authority_scope.clone(), + requested_action: "patch".to_string(), + requested_paths: winner.granted_paths.clone(), + substrate_gate_grant_receipt_id: winner.receipt_id.clone(), + requested_at: "2026-07-13T05:30:01Z".to_string(), + contract: "race intent".to_string(), + }; + let mut other_intent = base_intent.clone(); + other_intent.requested_action = "continueImplementation".to_string(); let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); - let outcomes = [base_intent.clone(), other_intent].into_iter().map(|intent| { - let path = store.clone(); let barrier = barrier.clone(); - std::thread::spawn(move || { barrier.wait(); put_hands_action_intent(path, &intent) }) - }).collect::>(); - assert_eq!(outcomes.into_iter().map(|outcome| outcome.join().unwrap()).filter(Result::is_ok).count(), 1); + let outcomes = [base_intent.clone(), other_intent] + .into_iter() + .map(|intent| { + let path = store.clone(); + let barrier = barrier.clone(); + std::thread::spawn(move || { + barrier.wait(); + put_hands_action_intent(path, &intent) + }) + }) + .collect::>(); + assert_eq!( + outcomes + .into_iter() + .map(|outcome| outcome.join().unwrap()) + .filter(Result::is_ok) + .count(), + 1 + ); let winner_intent = runtime_hands_action_intent(&store, "race-intent")?.unwrap(); - let base_review = hands_action_review_for_intent("race-review".to_string(), &winner_intent, "approved".to_string(), - vec!["patch".to_string(), "command".to_string(), "commit".to_string()], vec!["race".to_string()], - "2026-07-13T05:30:02Z".to_string()); - let mut other_review = base_review.clone(); other_review.allowed_operations = vec!["patch".to_string()]; + let base_review = hands_action_review_for_intent( + "race-review".to_string(), + &winner_intent, + "approved".to_string(), + vec![ + "patch".to_string(), + "command".to_string(), + "commit".to_string(), + ], + vec!["race".to_string()], + "2026-07-13T05:30:02Z".to_string(), + ); + let mut other_review = base_review.clone(); + other_review.allowed_operations = vec!["patch".to_string()]; let barrier = std::sync::Arc::new(std::sync::Barrier::new(2)); - let outcomes = [base_review, other_review].into_iter().map(|review| { - let path = store.clone(); let barrier = barrier.clone(); - std::thread::spawn(move || { barrier.wait(); put_hands_action_review(path, &review) }) - }).collect::>(); - assert_eq!(outcomes.into_iter().map(|outcome| outcome.join().unwrap()).filter(Result::is_ok).count(), 1); + let outcomes = [base_review, other_review] + .into_iter() + .map(|review| { + let path = store.clone(); + let barrier = barrier.clone(); + std::thread::spawn(move || { + barrier.wait(); + put_hands_action_review(path, &review) + }) + }) + .collect::>(); + assert_eq!( + outcomes + .into_iter() + .map(|outcome| outcome.join().unwrap()) + .filter(Result::is_ok) + .count(), + 1 + ); Ok(()) } @@ -6656,244 +6105,6 @@ mod tests { } Ok(()) } - - struct RepoWorkAdoptionFixture { - store: PathBuf, - review: RepoWorkPlanAdoptionReview, - grant: RepoWorkHandsGrant, - approved: HandsActionReview, - } - - fn repo_work_adoption_fixture() -> Result<(tempfile::TempDir, RepoWorkAdoptionFixture)> { - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "epiphany-adoption-test".to_string(), - display_name: "Epiphany Adoption Test".to_string(), - created_at: "2026-07-13T00:00:00Z".to_string(), - }, - )?; - let paths = vec!["src/lib.rs".to_string()]; - let substrate = crate::substrate_gate_coordinator_implementation_grant( - "substrate-adoption-1".to_string(), - "hands-job-adoption-1".to_string(), - paths.clone(), - "2026-07-13T00:00:01Z".to_string(), - ); - put_substrate_gate_repo_access_grant_receipt(&store, &substrate)?; - let intent = HandsActionIntent { - schema_version: crate::HANDS_ACTION_INTENT_SCHEMA_VERSION.to_string(), - intent_id: "hands-intent-adoption-1".to_string(), - runtime_job_id: "hands-job-adoption-1".to_string(), - binding_id: "implementation-worker".to_string(), - role: "epiphany-hands".to_string(), - authority_scope: "epiphany.role.implementation".to_string(), - requested_action: "runAcceptedWorkItem".to_string(), - requested_paths: paths.clone(), - substrate_gate_grant_receipt_id: substrate.receipt_id.clone(), - requested_at: "2026-07-13T00:00:02Z".to_string(), - contract: "Mind adoption test intent.".to_string(), - }; - put_hands_action_intent(&store, &intent)?; - let queued = crate::hands_action_review_for_intent( - "hands-review-queued-adoption-1".to_string(), - &intent, - "queued-for-adoption".to_string(), - vec![ - "patch".to_string(), - "command".to_string(), - "commit".to_string(), - ], - vec!["Mind decision required.".to_string()], - "2026-07-13T00:00:03Z".to_string(), - ); - put_hands_action_review(&store, &queued)?; - let review = RepoWorkPlanAdoptionReview { - schema_version: crate::mind_gateway::REPO_WORK_PLAN_ADOPTION_REVIEW_SCHEMA_VERSION - .to_string(), - review_id: "mind-adoption-1".to_string(), - decision: crate::mind_gateway::RepoWorkPlanAdoptionDecision::Adopt, - workspace_identity: "workspace-1".to_string(), - item: "item-1".to_string(), - plan_schema_version: "epiphany.repo_work_action_plan_receipt.v0".to_string(), - plan_id: "plan-1".to_string(), - plan_sha256: "a".repeat(64), - run_receipt_sha256: "b".repeat(64), - plan_receipt_path: temp.path().join("plan.json").display().to_string(), - run_receipt_path: temp.path().join("run.json").display().to_string(), - hands_intent_id: intent.intent_id.clone(), - queued_hands_review_id: queued.review_id.clone(), - substrate_grant_receipt_id: substrate.receipt_id.clone(), - action_id: "action-1".to_string(), - action_command: "cargo test --lib".to_string(), - action_commit_message: "Test immutable adoption".to_string(), - changed_paths: paths.clone(), - reviewed_at: "2026-07-13T00:00:04Z".to_string(), - private_state_exposed: false, - }; - put_repo_work_plan_adoption_review(&store, &review)?; - let approved = crate::hands_action_review_for_intent( - "hands-review-approved-adoption-1".to_string(), - &intent, - "approved".to_string(), - vec![ - "patch".to_string(), - "command".to_string(), - "commit".to_string(), - ], - vec!["Bound to immutable Mind review.".to_string()], - "2026-07-13T00:00:05Z".to_string(), - ); - let grant = RepoWorkHandsGrant { - schema_version: crate::mind_gateway::REPO_WORK_HANDS_GRANT_SCHEMA_VERSION.to_string(), - grant_id: "hands-grant-adoption-1".to_string(), - adoption_review_id: review.review_id.clone(), - adoption_review_sha256: format!("{:x}", Sha256::digest(serde_json::to_vec(&review)?)), - workspace_identity: review.workspace_identity.clone(), - item: review.item.clone(), - plan_id: review.plan_id.clone(), - plan_sha256: review.plan_sha256.clone(), - run_receipt_sha256: review.run_receipt_sha256.clone(), - plan_receipt_path: review.plan_receipt_path.clone(), - run_receipt_path: review.run_receipt_path.clone(), - hands_intent_id: review.hands_intent_id.clone(), - queued_hands_review_id: review.queued_hands_review_id.clone(), - approved_hands_review_id: approved.review_id.clone(), - substrate_grant_receipt_id: review.substrate_grant_receipt_id.clone(), - action_id: review.action_id.clone(), - action_command: review.action_command.clone(), - action_commit_message: review.action_commit_message.clone(), - allowed_operations: approved.allowed_operations.clone(), - changed_paths: review.changed_paths.clone(), - granted_at: "2026-07-13T00:00:05Z".to_string(), - private_state_exposed: false, - }; - Ok(( - temp, - RepoWorkAdoptionFixture { - store, - review, - grant, - approved, - }, - )) - } - - #[test] - fn repo_work_mind_review_is_create_once_and_idempotent() -> Result<()> { - let (_temp, fixture) = repo_work_adoption_fixture()?; - put_repo_work_plan_adoption_review(&fixture.store, &fixture.review)?; - let mut counterfeit = fixture.review.clone(); - counterfeit.action_command = "cargo test --all".to_string(); - assert!(put_repo_work_plan_adoption_review(&fixture.store, &counterfeit).is_err()); - assert_eq!( - runtime_repo_work_plan_adoption_review(&fixture.store, &fixture.review.review_id)?, - Some(fixture.review) - ); - Ok(()) - } - - #[test] - fn repo_work_refuse_and_hold_cannot_mint_hands_authority() -> Result<()> { - for decision in [ - crate::mind_gateway::RepoWorkPlanAdoptionDecision::Refuse, - crate::mind_gateway::RepoWorkPlanAdoptionDecision::Hold, - ] { - let (_temp, mut fixture) = repo_work_adoption_fixture()?; - fixture.review.review_id = format!("mind-{decision:?}").to_lowercase(); - fixture.review.decision = decision; - fixture.grant.adoption_review_id = fixture.review.review_id.clone(); - put_repo_work_plan_adoption_review(&fixture.store, &fixture.review)?; - assert!( - commit_repo_work_hands_grant(&fixture.store, &fixture.grant, &fixture.approved) - .is_err() - ); - assert!( - runtime_repo_work_hands_grant(&fixture.store, &fixture.grant.grant_id)?.is_none() - ); - assert!( - runtime_hands_action_review(&fixture.store, &fixture.approved.review_id)?.is_none() - ); - } - Ok(()) - } - - #[test] - fn repo_work_swapped_binding_fails_atomically() -> Result<()> { - let (_temp, mut fixture) = repo_work_adoption_fixture()?; - fixture.grant.plan_receipt_path = fixture.review.run_receipt_path.clone(); - assert!( - commit_repo_work_hands_grant(&fixture.store, &fixture.grant, &fixture.approved) - .is_err() - ); - assert!(runtime_repo_work_hands_grant(&fixture.store, &fixture.grant.grant_id)?.is_none()); - assert!( - runtime_hands_action_review(&fixture.store, &fixture.approved.review_id)?.is_none() - ); - Ok(()) - } - - #[test] - fn repo_work_counterfeit_review_digest_fails_atomically() -> Result<()> { - let (_temp, mut fixture) = repo_work_adoption_fixture()?; - fixture.grant.adoption_review_sha256 = "c".repeat(64); - assert!( - commit_repo_work_hands_grant(&fixture.store, &fixture.grant, &fixture.approved) - .is_err() - ); - assert!(runtime_repo_work_hands_grant(&fixture.store, &fixture.grant.grant_id)?.is_none()); - assert!( - runtime_hands_action_review(&fixture.store, &fixture.approved.review_id)?.is_none() - ); - Ok(()) - } - - #[test] - fn repo_work_exact_adoption_chain_commits_grant_and_review_together() -> Result<()> { - let (_temp, fixture) = repo_work_adoption_fixture()?; - commit_repo_work_hands_grant(&fixture.store, &fixture.grant, &fixture.approved)?; - assert_eq!( - runtime_repo_work_hands_grant(&fixture.store, &fixture.grant.grant_id)?, - Some(fixture.grant) - ); - assert_eq!( - runtime_hands_action_review(&fixture.store, &fixture.approved.review_id)?, - Some(fixture.approved) - ); - Ok(()) - } - - #[test] - fn repo_work_grant_and_approved_review_are_create_once_as_a_pair() -> Result<()> { - let (_temp, fixture) = repo_work_adoption_fixture()?; - commit_repo_work_hands_grant(&fixture.store, &fixture.grant, &fixture.approved)?; - commit_repo_work_hands_grant(&fixture.store, &fixture.grant, &fixture.approved)?; - - let mut counterfeit_grant = fixture.grant.clone(); - counterfeit_grant.action_command = "cargo test --all".to_string(); - assert!( - commit_repo_work_hands_grant(&fixture.store, &counterfeit_grant, &fixture.approved) - .is_err() - ); - let mut counterfeit_review = fixture.approved.clone(); - counterfeit_review.reasons = vec!["replacement opinion".to_string()]; - assert!( - commit_repo_work_hands_grant(&fixture.store, &fixture.grant, &counterfeit_review) - .is_err() - ); - assert_eq!( - runtime_repo_work_hands_grant(&fixture.store, &fixture.grant.grant_id)?, - Some(fixture.grant) - ); - assert_eq!( - runtime_hands_action_review(&fixture.store, &fixture.approved.review_id)?, - Some(fixture.approved) - ); - Ok(()) - } - #[test] fn runtime_spine_initializes_sessions_events_and_status() -> Result<()> { let temp = tempdir()?; diff --git a/epiphany-core/src/surfaces/mod.rs b/epiphany-core/src/surfaces/mod.rs index 24f56eab..2c2c1097 100644 --- a/epiphany-core/src/surfaces/mod.rs +++ b/epiphany-core/src/surfaces/mod.rs @@ -141,10 +141,8 @@ pub use view::epiphany_view_needs_reorientation_inputs; pub use view::epiphany_view_needs_runtime_store; pub use worker_launch::EpiphanyReorientLaunchRequestInput; pub use worker_launch::EpiphanyReorientWorkerLaunchDocument; -pub use worker_launch::EpiphanyRepoWorkModelingLaunchDocument; pub use worker_launch::EpiphanyRoleWorkerLaunchDocument; pub use worker_launch::EpiphanyWorkerLaunchDocument; pub use worker_launch::REORIENT_WORKER_OUTPUT_CONTRACT_ID; -pub use worker_launch::REPO_WORK_MODELING_OUTPUT_CONTRACT_ID; pub use worker_launch::ROLE_WORKER_OUTPUT_CONTRACT_ID; pub use worker_launch::build_reorient_job_launch_request; diff --git a/epiphany-core/src/surfaces/worker_launch.rs b/epiphany-core/src/surfaces/worker_launch.rs index 3c032d54..82ffd2a2 100644 --- a/epiphany-core/src/surfaces/worker_launch.rs +++ b/epiphany-core/src/surfaces/worker_launch.rs @@ -26,15 +26,12 @@ use crate::EpiphanyReorientReason; pub const ROLE_WORKER_OUTPUT_CONTRACT_ID: &str = "epiphany.worker.role_result.v0"; pub const REORIENT_WORKER_OUTPUT_CONTRACT_ID: &str = "epiphany.worker.reorient_result.v0"; -pub const REPO_WORK_MODELING_OUTPUT_CONTRACT_ID: &str = - "epiphany.worker.repo_work_modeling_result.v0"; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", tag = "documentKind")] pub enum EpiphanyWorkerLaunchDocument { Role(EpiphanyRoleWorkerLaunchDocument), Reorient(EpiphanyReorientWorkerLaunchDocument), - RepoWorkModeling(EpiphanyRepoWorkModelingLaunchDocument), } impl EpiphanyWorkerLaunchDocument { @@ -42,7 +39,6 @@ impl EpiphanyWorkerLaunchDocument { match self { Self::Role(_) => ROLE_WORKER_OUTPUT_CONTRACT_ID, Self::Reorient(_) => REORIENT_WORKER_OUTPUT_CONTRACT_ID, - Self::RepoWorkModeling(_) => REPO_WORK_MODELING_OUTPUT_CONTRACT_ID, } } @@ -50,7 +46,6 @@ impl EpiphanyWorkerLaunchDocument { match self { Self::Role(_) => "role", Self::Reorient(_) => "reorient", - Self::RepoWorkModeling(_) => "repo-work-modeling", } } @@ -58,7 +53,6 @@ impl EpiphanyWorkerLaunchDocument { match self { Self::Role(document) => &document.thread_id, Self::Reorient(document) => &document.thread_id, - Self::RepoWorkModeling(document) => &document.thread_id, } } @@ -66,28 +60,12 @@ impl EpiphanyWorkerLaunchDocument { match self { Self::Role(document) => document.dynamic_prompt_context.as_deref(), Self::Reorient(document) => document.dynamic_prompt_context.as_deref(), - Self::RepoWorkModeling(document) => document.dynamic_prompt_context.as_deref(), } .map(str::trim) .filter(|context| !context.is_empty()) } } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct EpiphanyRepoWorkModelingLaunchDocument { - pub thread_id: String, - pub request_id: String, - pub item: String, - pub soul_verdict_receipt_id: String, - pub commit_sha: String, - #[serde(default)] - pub changed_paths: Vec, - pub instruction: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub dynamic_prompt_context: Option, -} - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct EpiphanyRoleWorkerLaunchDocument { diff --git a/epiphany-openai-runtime/src/lib.rs b/epiphany-openai-runtime/src/lib.rs index 3783d191..b1c9cc12 100644 --- a/epiphany-openai-runtime/src/lib.rs +++ b/epiphany-openai-runtime/src/lib.rs @@ -659,34 +659,6 @@ pub fn complete_worker_job_from_assistant_text( ); put_runtime_reorient_worker_result(store_path.as_ref(), &typed_result)?; } - ( - EpiphanyWorkerLaunchDocument::RepoWorkModeling(document), - WorkerResultIngress::RepoWorkModeling(parsed), - ) => { - let typed_result = epiphany_core::RepoWorkModelingFinding { - schema_version: epiphany_core::REPO_WORK_MODELING_FINDING_SCHEMA_VERSION - .to_string(), - receipt_id: format!("{}-finding", document.request_id), - item: document.item.clone(), - model_ref: openai_request_id.to_string(), - soul_verdict_receipt_id: document.soul_verdict_receipt_id.clone(), - verdict: clean_optional_string(parsed.verdict.as_deref()) - .unwrap_or_else(|| "failed".to_string()), - finding: clean_optional_string(parsed.finding.as_deref()).unwrap_or_else(|| { - "Modeling returned no bounded repo-work finding.".to_string() - }), - summary: clean_optional_string(parsed.summary.as_deref()).unwrap_or_else(|| { - "Modeling returned no repo-work summary.".to_string() - }), - changed_paths: document.changed_paths.clone(), - commit_sha: document.commit_sha.clone(), - emitted_at: now(), - private_state_exposed: false, - contract: "Model-authored interpretation of one typed Self request over a Soul-verified repo consequence.".to_string(), - request_id: document.request_id.clone(), - }; - epiphany_core::put_repo_work_modeling_finding(store_path.as_ref(), &typed_result)?; - } _ => { return Err(anyhow!( "worker launch document and parsed result kind diverged" @@ -1331,19 +1303,6 @@ fn worker_output_schema_json(document: &EpiphanyWorkerLaunchDocument) -> Result< EpiphanyWorkerLaunchDocument::Reorient(_) => { epiphany_core::epiphany_reorient_launch_output_schema() } - EpiphanyWorkerLaunchDocument::RepoWorkModeling(_) => serde_json::json!({ - "type": "object", - "additionalProperties": false, - "required": ["verdict", "finding", "summary", "nextSafeMove", "evidenceIds"], - "properties": { - "verdict": { "type": "string", "enum": ["passed", "failed", "needs-work", "blocked"] }, - "finding": { "type": "string", "minLength": 1 }, - "summary": { "type": "string", "minLength": 1 }, - "nextSafeMove": { "type": "string", "minLength": 1 }, - "evidenceIds": { "type": "array", "items": { "type": "string" } }, - "artifactRefs": { "type": "array", "items": { "type": "string" } } - } - }), }; serde_json::to_string_pretty(&schema).context("failed to render worker output schema") } @@ -1370,9 +1329,6 @@ fn worker_output_contract_text(document: &EpiphanyWorkerLaunchDocument) -> &'sta EpiphanyWorkerLaunchDocument::Reorient(_) => { "Required reorient-result fields: mode, summary, nextSafeMove. Include checkpointStillValid, filesInspected, frontierNodeIds, evidenceIds, openQuestions, and continuityRisks when present." } - EpiphanyWorkerLaunchDocument::RepoWorkModeling(_) => { - "Required repo-work Modeling fields: verdict, finding, summary, nextSafeMove, evidenceIds. Interpret only the Soul-verified consequence named by the request. Do not claim Mind admission, publication, merge, or further Hands authority." - } } } @@ -1415,22 +1371,10 @@ struct ReorientWorkerResultIngress { continuity_risks: Vec, } -#[derive(Debug, Clone, Default, serde::Deserialize)] -#[serde(rename_all = "camelCase", default)] -struct RepoWorkModelingResultIngress { - verdict: Option, - finding: Option, - summary: Option, - next_safe_move: Option, - evidence_ids: Vec, - artifact_refs: Vec, -} - #[derive(Debug, Clone)] enum WorkerResultIngress { Role(RoleWorkerResultIngress), Reorient(ReorientWorkerResultIngress), - RepoWorkModeling(RepoWorkModelingResultIngress), } impl WorkerResultIngress { @@ -1438,9 +1382,6 @@ impl WorkerResultIngress { match self { WorkerResultIngress::Role(result) => clean_optional_string(result.verdict.as_deref()), WorkerResultIngress::Reorient(result) => clean_optional_string(result.mode.as_deref()), - WorkerResultIngress::RepoWorkModeling(result) => { - clean_optional_string(result.verdict.as_deref()) - } } } @@ -1450,9 +1391,6 @@ impl WorkerResultIngress { WorkerResultIngress::Reorient(result) => { clean_optional_string(result.summary.as_deref()) } - WorkerResultIngress::RepoWorkModeling(result) => { - clean_optional_string(result.summary.as_deref()) - } } } @@ -1464,9 +1402,6 @@ impl WorkerResultIngress { WorkerResultIngress::Reorient(result) => { clean_optional_string(result.next_safe_move.as_deref()) } - WorkerResultIngress::RepoWorkModeling(result) => { - clean_optional_string(result.next_safe_move.as_deref()) - } } } @@ -1474,7 +1409,6 @@ impl WorkerResultIngress { match self { WorkerResultIngress::Role(result) => clean_string_vec(&result.evidence_ids), WorkerResultIngress::Reorient(result) => clean_string_vec(&result.evidence_ids), - WorkerResultIngress::RepoWorkModeling(result) => clean_string_vec(&result.evidence_ids), } } @@ -1482,9 +1416,6 @@ impl WorkerResultIngress { match self { WorkerResultIngress::Role(result) => clean_string_vec(&result.artifact_refs), WorkerResultIngress::Reorient(result) => clean_string_vec(&result.artifact_refs), - WorkerResultIngress::RepoWorkModeling(result) => { - clean_string_vec(&result.artifact_refs) - } } } } @@ -1502,10 +1433,6 @@ fn parse_worker_result_ingress( parse_assistant_json::(assistant_text) .map(WorkerResultIngress::Reorient) } - EpiphanyWorkerLaunchDocument::RepoWorkModeling(_) => { - parse_assistant_json::(assistant_text) - .map(WorkerResultIngress::RepoWorkModeling) - } } } @@ -2054,282 +1981,6 @@ mod tests { Ok(()) } - #[test] - fn repo_work_modeling_generation_retry_admits_only_current_runtime_finding() -> Result<()> { - let temp = tempdir()?; - let store = temp.path().join("runtime.msgpack"); - initialize_runtime_spine( - &store, - RuntimeSpineInitOptions { - runtime_id: "repo-work-test".to_string(), - display_name: "Repo Work Test".to_string(), - created_at: now(), - }, - )?; - epiphany_core::put_soul_verdict_receipt( - &store, - &epiphany_core::SoulVerdictReceipt { - schema_version: epiphany_core::SOUL_VERDICT_RECEIPT_SCHEMA_VERSION.to_string(), - receipt_id: "soul-repo-1".to_string(), - source_result_id: "hands-result-1".to_string(), - source_job_id: "hands-job-1".to_string(), - verdict: "passed".to_string(), - summary: "Soul passed.".to_string(), - evidence_ids: vec!["commit-abc".to_string()], - risks: Vec::new(), - emitted_at: now(), - contract: "test".to_string(), - verification_request_id: String::new(), - frontier_route_id: String::new(), - }, - )?; - let request = epiphany_core::RepoWorkModelingRequest { - schema_version: epiphany_core::REPO_WORK_MODELING_REQUEST_SCHEMA_VERSION.to_string(), - request_id: "repo-request-1".to_string(), - item: "map-repo".to_string(), - requester: "self".to_string(), - soul_verdict_receipt_id: "soul-repo-1".to_string(), - commit_sha: "abc123".to_string(), - changed_paths: vec!["README.md".to_string()], - instruction: "Model the verified consequence.".to_string(), - requested_at: now(), - private_state_exposed: false, - contract: "test".to_string(), - }; - let route0 = epiphany_core::RepoWorkModelingRoute { - schema_version: epiphany_core::REPO_WORK_MODELING_ROUTE_SCHEMA_VERSION.to_string(), - route_id: "repo-route-1".to_string(), - item: request.item.clone(), - generation: 0, - request_id: request.request_id.clone(), - previous_finding_receipt_id: String::new(), - authority_owner: "soul".to_string(), - authority_witness_id: request.soul_verdict_receipt_id.clone(), - updated_at: now(), - private_state_exposed: false, - contract: "test initial route".to_string(), - }; - epiphany_core::commit_initial_repo_work_modeling_route(&store, &request, &route0)?; - open_runtime_spine_heartbeat_job( - &store, - RuntimeSpineHeartbeatJobOptions { - runtime_id: "repo-work-test".to_string(), - display_name: "Repo Work Test".to_string(), - session_id: "repo-session-1".to_string(), - objective: "Map repo work.".to_string(), - coordinator_note: "Self routes; Modeling authors.".to_string(), - job_id: "repo-modeling-job-1".to_string(), - role: "modeling".to_string(), - binding_id: "repo-work-modeling-worker".to_string(), - authority_scope: "epiphany.role.modeling.repo-work".to_string(), - instruction: "Return the required repo-work Modeling result.".to_string(), - launch_document: EpiphanyWorkerLaunchDocument::RepoWorkModeling( - epiphany_core::EpiphanyRepoWorkModelingLaunchDocument { - thread_id: "repo-thread-1".to_string(), - request_id: request.request_id.clone(), - item: request.item.clone(), - soul_verdict_receipt_id: request.soul_verdict_receipt_id.clone(), - commit_sha: request.commit_sha.clone(), - changed_paths: request.changed_paths.clone(), - instruction: request.instruction.clone(), - dynamic_prompt_context: None, - }, - ), - output_contract_id: epiphany_core::REPO_WORK_MODELING_OUTPUT_CONTRACT_ID - .to_string(), - organ_launch_contract: epiphany_core::default_launch_organ_contract( - "epiphany.role.modeling.repo-work", - "repo-work-modeling", - epiphany_core::REPO_WORK_MODELING_OUTPUT_CONTRACT_ID, - ), - created_at: now(), - }, - )?; - let launch = load_worker_launch_request(&store, "repo-modeling-job-1")?; - let model_request = build_worker_model_request(&launch, DEFAULT_MODEL_PROVIDER, "gpt-5.4")?; - assert_eq!( - model_request.output_contract_id.as_deref(), - Some(epiphany_core::REPO_WORK_MODELING_OUTPUT_CONTRACT_ID) - ); - assert!( - model_request - .output_schema_json - .as_deref() - .is_some_and(|schema| schema.contains("\"finding\"")) - ); - let openai_summary = EpiphanyOpenAiRuntimeRunSummary { - store: store.display().to_string(), - session_id: "openai-repo-session".to_string(), - job_id: "openai-repo-job".to_string(), - request_id: model_request.request_id.clone(), - event_count: 1, - verdict: "pass".to_string(), - summary: "completed".to_string(), - result_id: "openai-repo-result".to_string(), - receipt_id: Some(model_request.request_id.clone()), - tool_intent_ids: Vec::new(), - }; - complete_worker_job_from_assistant_text( - &store, - &launch, - &model_request.request_id, - &openai_summary, - r#"{"verdict":"needs-work","finding":"The verified README consequence needs reviewed context.","summary":"Context incomplete.","nextSafeMove":"Ask Mind to review a retry.","evidenceIds":["soul-repo-1"],"artifactRefs":[]}"#, - )?; - let finding0 = - epiphany_core::runtime_repo_work_modeling_finding(&store, "repo-request-1-finding")? - .expect("typed repo-work Modeling finding"); - assert_eq!(finding0.request_id, request.request_id); - assert_eq!(finding0.verdict, "needs-work"); - assert_eq!(finding0.commit_sha, "abc123"); - assert!(!finding0.private_state_exposed); - - let review = epiphany_core::MindGatewayReview { - schema_version: epiphany_core::MIND_GATEWAY_REVIEW_SCHEMA_VERSION.to_string(), - gateway_id: "repo-route-1-g1-review".to_string(), - source_kind: "repo_work_modeling_revision".to_string(), - source_role_id: "mind".to_string(), - decision: epiphany_core::MindGatewayDecision::Accept, - allowed_effects: vec!["repoWork.modelingRoute".to_string()], - refused_effects: vec!["repoWork.map".to_string()], - reasons: vec!["Reviewed the missing context.".to_string()], - contract: "test route review".to_string(), - }; - let request1 = epiphany_core::RepoWorkModelingRequest { - request_id: "repo-request-2".to_string(), - requester: "mind".to_string(), - instruction: "Re-model with reviewed context.".to_string(), - requested_at: now(), - ..request.clone() - }; - let route1 = epiphany_core::RepoWorkModelingRoute { - generation: 1, - request_id: request1.request_id.clone(), - previous_finding_receipt_id: finding0.receipt_id.clone(), - authority_owner: "mind".to_string(), - authority_witness_id: review.gateway_id.clone(), - updated_at: now(), - ..route0.clone() - }; - epiphany_core::advance_repo_work_modeling_route(&store, &request1, &route1, &review)?; - open_runtime_spine_heartbeat_job( - &store, - RuntimeSpineHeartbeatJobOptions { - runtime_id: "repo-work-test".to_string(), - display_name: "Repo Work Test".to_string(), - session_id: "repo-session-1".to_string(), - objective: "Map reviewed repo work.".to_string(), - coordinator_note: "Mind selected generation one; Modeling authors.".to_string(), - job_id: "repo-modeling-job-2".to_string(), - role: "modeling".to_string(), - binding_id: "repo-work-modeling-worker".to_string(), - authority_scope: "epiphany.role.modeling.repo-work".to_string(), - instruction: "Return the reviewed repo-work Modeling result.".to_string(), - launch_document: EpiphanyWorkerLaunchDocument::RepoWorkModeling( - epiphany_core::EpiphanyRepoWorkModelingLaunchDocument { - thread_id: "repo-thread-1".to_string(), - request_id: request1.request_id.clone(), - item: request1.item.clone(), - soul_verdict_receipt_id: request1.soul_verdict_receipt_id.clone(), - commit_sha: request1.commit_sha.clone(), - changed_paths: request1.changed_paths.clone(), - instruction: request1.instruction.clone(), - dynamic_prompt_context: Some("Mind-reviewed generation one.".to_string()), - }, - ), - output_contract_id: epiphany_core::REPO_WORK_MODELING_OUTPUT_CONTRACT_ID - .to_string(), - organ_launch_contract: epiphany_core::default_launch_organ_contract( - "epiphany.role.modeling.repo-work", - "repo-work-modeling", - epiphany_core::REPO_WORK_MODELING_OUTPUT_CONTRACT_ID, - ), - created_at: now(), - }, - )?; - let launch1 = load_worker_launch_request(&store, "repo-modeling-job-2")?; - let model_request1 = - build_worker_model_request(&launch1, DEFAULT_MODEL_PROVIDER, "gpt-5.4")?; - let openai_summary1 = EpiphanyOpenAiRuntimeRunSummary { - request_id: model_request1.request_id.clone(), - job_id: "openai-repo-job-2".to_string(), - result_id: "openai-repo-result-2".to_string(), - ..openai_summary - }; - complete_worker_job_from_assistant_text( - &store, - &launch1, - &model_request1.request_id, - &openai_summary1, - r#"{"verdict":"passed","finding":"The reviewed README consequence updates the repo map.","summary":"README consequence mapped.","nextSafeMove":"Let Mind admit generation one.","evidenceIds":["soul-repo-1"],"artifactRefs":[]}"#, - )?; - let finding1 = - epiphany_core::runtime_repo_work_modeling_finding(&store, "repo-request-2-finding")? - .expect("generation-one typed finding"); - assert_eq!(finding1.verdict, "passed"); - - let map_review = epiphany_core::MindGatewayReview { - gateway_id: "repo-map-review".to_string(), - source_kind: "repo_work_closure".to_string(), - allowed_effects: vec!["repoWork.map".to_string()], - refused_effects: Vec::new(), - reasons: vec!["Admit current passing finding.".to_string()], - contract: "test map review".to_string(), - ..review.clone() - }; - let map_commit = epiphany_core::mind_state_commit_receipt( - "repo-map-commit".to_string(), - &map_review, - 1, - vec!["repoWork.map".to_string()], - now(), - ); - let map = epiphany_core::RepoWorkMapEntry { - schema_version: epiphany_core::REPO_WORK_MAP_ENTRY_SCHEMA_VERSION.to_string(), - map_entry_id: "repo-map-entry".to_string(), - admitted_at: now(), - item: request1.item.clone(), - branch: "test".to_string(), - changed_paths: request1.changed_paths.clone(), - commit_sha: request1.commit_sha.clone(), - safe_action_family: "repo.status_section".to_string(), - modeling_summary: finding1.summary.clone(), - modeling_finding_receipt_id: finding1.receipt_id.clone(), - soul_verdict_receipt_id: request1.soul_verdict_receipt_id.clone(), - mind_gateway_review_id: map_review.gateway_id.clone(), - mind_state_commit_receipt_id: map_commit.receipt_id.clone(), - execute_receipt_path: "execute.json".to_string(), - closure_review_path: "review.json".to_string(), - closure_receipt_path: "close.json".to_string(), - publication_gate: "Bifrost".to_string(), - durable_state_admitted: true, - private_state_exposed: false, - modeling_route_id: route1.route_id.clone(), - modeling_generation: 1, - }; - epiphany_core::commit_repo_work_map_admission(&store, &map, &map_review, &map_commit)?; - let mut stale = map.clone(); - stale.map_entry_id = "stale-generation-zero-map".to_string(); - stale.modeling_finding_receipt_id = finding0.receipt_id.clone(); - stale.modeling_summary = finding0.summary.clone(); - stale.modeling_generation = 0; - assert!( - epiphany_core::commit_repo_work_map_admission( - &store, - &stale, - &map_review, - &map_commit, - ) - .is_err() - ); - let current_route = - epiphany_core::runtime_repo_work_modeling_route(&store, &route1.route_id)? - .expect("current route"); - assert_eq!(current_route.generation, 1); - assert_eq!(current_route.request_id, request1.request_id); - Ok(()) - } - #[test] fn mcp_model_tool_call_becomes_typed_invocation_intent() -> Result<()> { let event = EpiphanyModelStreamEvent { diff --git a/notes/fresh-workspace-handoff.md b/notes/fresh-workspace-handoff.md index 576fe4cd..f2b1c88b 100644 --- a/notes/fresh-workspace-handoff.md +++ b/notes/fresh-workspace-handoff.md @@ -91,6 +91,29 @@ that workflow on canonical RepoFrontier route/Hands/Soul/Modeling authority and demote `RepoWorkMapEntry` to derived closure history. Do not let item-slug routes or the legacy special Modeling worker close work independently of RepoModel. +Stage 1 of that convergence is now landed in the worktree and Soul-approved. +The parallel authority was cut before its replacement was enabled. Legacy +RepoWork Modeling request/route/finding/map types, worker launch, OpenAI ingress, +runtime writers, manual generation retry, Mind plan-adoption type, independent +Hands grant, CultMesh overview/readiness/public-proof writers, and closure +contract corpse are deleted. `epiphany-work` is an 82-line quarantine mouth: +every mutation/scheduling/publication command refuses before substrate access; +overview emits only an explicit `historical-only` non-authoritative projection. +Verse query cannot turn historical map rows into current gates, actions, +closure, acceptance, pending Bifrost requests, or accounting. Legitimate +Bifrost artifact-acceptance and metrics receipts still produce accounting rows +without consulting RepoWork history. The authoritative serial proof is core +294 passed/1 ignored, epiphany-work 1 passed, Verse query 13 passed, OpenAI +runtime 8 passed; independent Soul verdict is PASS. + +The temporary outage is intentional. Do not resurrect old plan/run/adopt/ +execute/close code to restore motion. The next build begins from the authority +map in `notes/repo-work-canonical-convergence.md`: inert proposal -> ordinary +Modeling frontier admission -> typed Self planning request -> Imagination plan +candidate -> Mind plan adoption -> distinct Self execution route -> canonical +Hands/Soul/verdict-incorporation chain. Plan readiness does not belong in +`RepoFrontierStatus`, and a generic phase router has not earned existence. + The next artifact-contract audit then cut `epiphany.persona_chat.v0`: its live writer and catalog had disagreed on field vocabulary, evidence fields, and lifecycle closure. The writer is now typed Rust with closed diff --git a/notes/repo-work-canonical-convergence.md b/notes/repo-work-canonical-convergence.md new file mode 100644 index 00000000..ebaece51 --- /dev/null +++ b/notes/repo-work-canonical-convergence.md @@ -0,0 +1,74 @@ +# Repo-Work Canonical Convergence + +## Objective + +Preserve the branch-local repo-work user story without preserving its second +Modeling, Self, Hands, Soul, or Mind authority. Repo-work is a workflow over one +canonical `RepoFrontierItem`; it is not another repository model. + +## Authority Map + +- Owner: runtime-spine `RepoModel` owns repository anatomy and frontier + lifecycle. +- Inputs: an immutable work proposal; an admitted frontier identity; a typed + plan candidate and Mind adoption; the current model and route; immutable + Substrate/Hands consequences; Soul verification; Modeling verdict + incorporation; provider publication receipts. +- Outputs: one admitted frontier transition plus derived workflow/closure/public + proof projections. +- Derived state: filesystem plan/run/execute/close artifacts, operator rows, + closure history, and public proof bundles. They may explain or export the + canonical chain; they may not schedule, repair, or close it. +- Forbidden writers: item-slug route synthesis, `RepoWorkModelingRequest`, + `RepoWorkModelingRoute`, `RepoWorkModelingFinding`, `RepoWorkMapEntry`, + `revise-modeling`, plan-derived independent Hands grants, JSON-existence phase + selection, and local Verse map rows that claim current anatomy. +- Shared path: `proposal -> Modeling Evolution -> Mind frontier admission -> Self + planning request -> Imagination plan candidate -> Mind plan adoption -> Self + execution route -> Hands authority/consequence -> Soul verification -> Modeling + verdict incorporation -> Mind final admission -> derived closure/public proof`. +- Deletion line: legacy Modeling/map writers and scheduler routes are cut before + new execution is enabled. Historical documents may remain readable only as + inert history. + +## Organ Ownership + +- Modeling authors repository claims and frontier proposals; it does not author + commands or adopt its own output. +- Self emits a typed planning request bound to one current frontier id/hash and + assigns Imagination. This is not an execution route. +- Imagination authors a candidate response bound to that planning request. +- Mind admits the exact plan candidate. +- Self then emits a distinct execution route that freezes the current model, + frontier item, and adopted plan for Hands. Do not generalize both phases into + a generic router until a shared invariant actually earns that abstraction. +- Hands acts only from that route and the Substrate grant. +- Soul judges the exact consequence chain. +- Modeling incorporates Soul's verdict into the same frontier item; Mind admits + the transition. +- Bifrost/provider receipts own publication and merge truth. + +## Bootstrap + +Persona/intake emits an immutable proposal, not a work item. Ordinary Modeling +may cite that proposal in an Evolution patch that creates the frontier item. +Mind admission makes the wound real. Plan/adopt requires that admitted frontier +identity; no CLI slug, filesystem path, or old close receipt may synthesize it. + +## Rebuild Order + +1. **Landed:** refuse and delete new legacy repo-work Modeling/map mutations, + retry routes, worker ingress, independent plan-adoption/Hands grant, + scheduler/publication authority, and current-looking CultMesh writers. + Historical readers are sight-only and cannot feed gates, actions, closure, + pending Bifrost requests, or accounting. Temporary workflow outage is honest. +2. Add typed proposal-to-frontier bootstrap through ordinary Modeling/Mind. +3. Add typed Self planning request, frontier plan candidate/adoption, and bind + plan identity into the later Self execution route plus Hands authority. + Re-enable execution only through that chain. +4. Rewire verification/closure through canonical Soul and verdict incorporation. +5. Rebuild closure/public proof as read-only joins, then delete stale map schemas + and projection keys. + +Do not encode plan readiness in `RepoFrontierStatus`. The model owns the wound; +the plan owns a proposed response; Self owns their binding. diff --git a/state/ledgers.msgpack b/state/ledgers.msgpack index b42b9ea3..f281209a 100644 Binary files a/state/ledgers.msgpack and b/state/ledgers.msgpack differ diff --git a/state/map.yaml b/state/map.yaml index e79d1c36..d97c09e4 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -661,4 +661,4 @@ current_status: - Service lifecycle receipt history is now event-only: `load_epiphany_cultmesh_daemon_service_lifecycle_receipts` filters out the `epiphany-local/daemon-service-lifecycle-receipt/latest` mirror, while `load_latest_epiphany_cultmesh_daemon_service_lifecycle_receipt` remains the latest-state reader. Focused unit test `service_lifecycle_receipt_history_excludes_latest_mirror` proves two per-receipt writes return exactly two history records and latest points at the second. Fresh smoke `verse-query-lifecycle-history-filter-smoke` and live overview/triage `local-20260618-145632-497-efac6f0d` / `local-20260618-145632-321-867947af` prove compact swarm sights still expose service lifecycle attention plus the present elevated runbook artifact without daemon pokes or service mutation. Do not use a broad unscoped cargo test filter for this check on Windows; it fans out across bin harnesses and hit a broken pipe during this pass. - `epiphany-verse-query seed-compact` is the compact seed receipt for wrappers and read-only rites. The older `seed` command still prints the full local Verse context for explicit debugging, but compact wrapper modes now avoid full `seed`/final `query` readback after the combined overview proof exposed Windows debug stack overflow from full-context serialization pressure. last_completed_repo_swarm_cut: Huginn live-fire has crossed the first real repo Body from Persona pressure to branch-local Hands commit and Soul/Mind closure, and now has repeatable closure and redacted-public-proof mouths. On `E:\Projects\Huginn` branch `epiphany/huginn/first-awakening`, `tools/epiphany_local_run.ps1 -Mode repo-persona-intake` accepted item `huginn-inspection-readback-livefire`, Weksa/Persona intake remained sealed, and `epiphany-work derive-plan` lowered it to model-authored safe family `repo.status_section` for `README.md` only. `tools/epiphany_local_run.ps1 -Mode repo-swarm-run` advanced four bounded pulses: run-from-plan, adopt-from-plan, execute-from-plan, and close-from-execute. Huginn commit `e9b07c38fceabbdc89ea35c2156326c80c0393a2` updated only `README.md`; closure receipt `.epiphany\work\work-close-huginn-inspection-readback-livefire.json` records status `closed`, Soul verdict `passed`, Mind state commit `repo-work-close-huginn-inspection-readback-livefire-mind-commit`, safe family `repo.status_section`, path scope `README.md`, Bifrost publication gate, and `privateStateExposed=false`. Verification also ran Huginn's TypeScript compiler through concrete Node path: `C:\Program Files\nodejs\node.exe E:\Projects\Huginn\node_modules\typescript\bin\tsc -p tsconfig.json` passed. Native verifier `epiphany-repo-livefire-closure-smoke --workspace E:\Projects\Huginn --item huginn-inspection-readback-livefire --expected-path README.md --expected-family repo.status_section --expected-gate awaiting-publication --expected-blocker bifrost-publication-missing` checks closure receipt, Mind map entry, overview gate/blocker, authority seals, and `git show` changed paths, returning `status=ok`, `soulVerdict=passed`, `publicationGate=Bifrost`, and `privateStateExposed=false`. Wrapper `tools/epiphany_local_run.ps1 -Mode repo-livefire-closure -Workspace E:\Projects\Huginn -RepoWorkItem huginn-inspection-readback-livefire -SkipBuild` exposes the same read-only proof through the local operator mouth; artifact `local-20260621-190156-803-2f85ba15` printed commit, path, gate, blocker, Soul verdict, Mind commit receipt, and `privateStateExposed=False` without push, merge, publication, or target mutation. New wrapper `tools/epiphany_local_run.ps1 -Mode repo-work-public-proof -Workspace E:\Projects\Huginn -RepoWorkItem huginn-inspection-readback-livefire -SkipBuild` exports the redacted proof bundle and repo-local Verse index without publishing; artifact `local-20260621-190645-345-4555b1dc` wrote `.epiphany\public\proof-bundles\repo-work-public-proof-huginn-inspection-readback-livefire.json`, proof id `repo-work-public-proof-huginn-inspection-readback-livefire`, SHA-256 `857545b199f3e37eb06c2e757e5cfc201958e46667bb1f8403fd333a22620f63`, nine artifact rows, zero publication rows, and `privateStateExposed=False`. swarm overview readback `local-20260621-190701-140-b9519ec6` sees the `REPO-WORK-PUBLIC-PROOF` row and action row from Huginn's repo-local Verse with the same SHA-256 while Bifrost publication remains missing. Launcher compact modes are now named compact operator-context modes instead of read-only modes, and `bifrost-public-proof` summaries print item, target public Verse, room, proof SHA-256, review receipts, and credit receipts so publication receipts are auditable without claiming upstream sync. - next_action: Converge the legacy RepoWork closure workflow on the accepted canonical RepoModel organ loop. The first causal slice is now proven: typed Modeling patch and Mind admission; Self route bound to current model/frontier identity; immutable Substrate/Hands consequence chain; exact Soul verification request and verdict; typed Modeling verdict-incorporation request; pass-to-Resolved and nonpass-to-Blocked; no unrouted Hands default; full-chain replay at final CAS; atomic absent-only companions; recoverable split coordinator retry; hostile substitution/race/nonselection proof; Soul PASS. Do not add index polish or another adapter. Keep repo-work plan/adopt/execute only where it serves the branch-local workflow, require it to consume canonical RepoFrontierRoute and RepoFrontierHandsAuthority, delete the special RepoWorkModeling Request/Route/Finding worker protocol and item-slug retry route, and demote or rename RepoWorkMapEntry as derived closure history with no anatomy/routing authority. Then add typed Eyes challenges and Imagination campaign revisions so Blocked persistence becomes real Aetheria-style corrective circulation rather than a terminal note. The intentionally absent Other-world action still requires a typed intent and real owner. Keep closure's zero-substring invariant. + next_action: Build canonical repo-work planning on the purified RepoModel loop; do not restore the deleted legacy workflow. Stage 1 is Soul-approved and intentionally fail-closed: RepoWork Modeling/map worker authority, plan-adoption/independent Hands grant, closure contracts, scheduler/publication writers, and live history-derived Bifrost/accounting decisions are deleted; epiphany-work is a warning-clean quarantine mouth and historical Verse rows are sight-only. Start with an immutable inert work proposal. Ordinary Modeling cites it in an Evolution patch that creates one frontier item; Mind admission makes the wound real. Self then emits a typed planning request bound to the current frontier id/hash and assigns Imagination; Imagination emits a typed plan candidate; Mind adopts the exact candidate; a distinct Self execution route freezes model, frontier, and adopted plan for canonical Hands authority. Only then re-enable execution, Soul verification, verdict incorporation, derived closure, and public proof. Do not put plan readiness in RepoFrontierStatus, invent a generic phase router, infer identity from an item slug, or add a compatibility adapter. Then add typed Eyes challenges so Blocked pressure can circulate. The intentionally absent Other-world action still requires a typed intent and real owner. Keep closure's zero-substring invariant.