use std::collections::BTreeSet;
use std::fmt;
use crate::lifecycle_identity::{OperationReceipt, SourceRefusal};
pub use crate::lifecycle_identity::{OperationKind, RetryAdvice, SourceRefusalKind};
use super::embedded::ReceiptWaitError;
use super::process_runtime::ProcessIndexRuntime;
pub const PROVISIONAL_ACQUIRE_PROCESS_BYTES: u64 = 256 * 1024 * 1024;
pub const EVIDENCE_ABSENT: &str = "evidence-absent";
pub(crate) type NotUnwindSafe = std::marker::PhantomData<Box<dyn std::any::Any + Send + Sync>>;
fn render_operation_identity(receipt: &OperationReceipt) -> String {
format!("op-{}", receipt.identity().raw_for_render())
}
fn render_argument_hash(receipt: &OperationReceipt) -> String {
format!("hash-{:012x}", receipt.canonical_argument_hash().raw())
}
#[derive(Debug, Clone)]
pub struct EmbedOperationReceipt {
identity: String,
canonical_argument_hash: String,
operation_kind: OperationKind,
schema_version: u32,
}
impl EmbedOperationReceipt {
fn wrap(receipt: &OperationReceipt) -> Self {
Self {
identity: render_operation_identity(receipt),
canonical_argument_hash: render_argument_hash(receipt),
operation_kind: receipt.operation_kind(),
schema_version: receipt.schema_version(),
}
}
pub fn identity(&self) -> &str {
&self.identity
}
pub fn canonical_argument_hash(&self) -> &str {
&self.canonical_argument_hash
}
pub fn operation_kind(&self) -> OperationKind {
self.operation_kind
}
pub fn schema_version(&self) -> u32 {
self.schema_version
}
}
#[derive(Debug)]
pub struct EmbedSourceRefusal {
kind: SourceRefusalKind,
operation: EmbedOperationReceipt,
retry: RetryAdvice,
evidence_identity: String,
}
impl EmbedSourceRefusal {
pub(crate) fn wrap(refusal: &SourceRefusal) -> Self {
Self {
kind: refusal.kind(),
operation: EmbedOperationReceipt::wrap(&refusal.operation()),
retry: refusal.retry(),
evidence_identity: match refusal.evidence_identity() {
Some(identity) => format!("auth-{}", identity.raw_for_render()),
None => EVIDENCE_ABSENT.to_string(),
},
}
}
pub fn kind(&self) -> SourceRefusalKind {
self.kind
}
pub fn kind_name(&self) -> &'static str {
match self.kind {
SourceRefusalKind::AdmissionUnavailable => "AdmissionUnavailable",
SourceRefusalKind::InvalidSelection => "InvalidSelection",
SourceRefusalKind::SelectionUnavailable => "SelectionUnavailable",
SourceRefusalKind::SourceUnavailable => "SourceUnavailable",
}
}
pub fn operation(&self) -> &EmbedOperationReceipt {
&self.operation
}
pub fn retry(&self) -> RetryAdvice {
self.retry
}
pub fn evidence_identity(&self) -> &str {
&self.evidence_identity
}
}
impl fmt::Display for EmbedSourceRefusal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"source refusal: {} (operation {}, evidence {})",
self.kind_name(),
self.operation.identity(),
self.evidence_identity
)
}
}
impl std::error::Error for EmbedSourceRefusal {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SymbolSearchRequest {
pub query: Option<String>,
pub path_prefix: Option<String>,
pub limit: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SymbolMatch {
pub name: String,
pub kind: String,
pub path: String,
pub start_line: u32,
pub end_line: u32,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SymbolSearchResult {
pub matches: Vec<SymbolMatch>,
pub truncated: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextSearchRequest {
pub query: String,
pub path_prefix: Option<String>,
pub limit: u32,
pub case_sensitive: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextMatch {
pub path: String,
pub line: u32,
pub byte_start: u64,
pub byte_end: u64,
pub preview: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextSearchResult {
pub matches: Vec<TextMatch>,
pub truncated: bool,
}
#[derive(Debug)]
pub struct EmbedRefreshTicket {
ticket_identity: String,
operation: EmbedOperationReceipt,
requested_source_version: u64,
_not_unwind_safe: NotUnwindSafe,
}
impl EmbedRefreshTicket {
pub fn ticket_identity(&self) -> &str {
&self.ticket_identity
}
pub fn operation(&self) -> &EmbedOperationReceipt {
&self.operation
}
pub fn requested_source_version(&self) -> u64 {
self.requested_source_version
}
}
#[derive(Debug)]
pub struct EmbedAtomicAuthority {
identity: String,
kind_name: &'static str,
}
impl EmbedAtomicAuthority {
pub fn identity(&self) -> &str {
&self.identity
}
pub fn kind_name(&self) -> &'static str {
self.kind_name
}
}
#[derive(Debug)]
pub struct EmbedClaimProvenance {
authorities: Vec<EmbedAtomicAuthority>,
identity: String,
kind_name: &'static str,
}
impl EmbedClaimProvenance {
pub fn authorities(&self) -> &[EmbedAtomicAuthority] {
&self.authorities
}
pub fn authority_count(&self) -> usize {
self.authorities.len()
}
pub fn identity(&self) -> &str {
&self.identity
}
pub fn kind_name(&self) -> &'static str {
self.kind_name
}
}
#[derive(Debug)]
pub struct EmbedEvaluationProvenance {
identity: String,
}
impl EmbedEvaluationProvenance {
pub fn identity(&self) -> &str {
&self.identity
}
}
#[derive(Debug)]
pub struct EmbedClaim<T> {
value: T,
provenance: EmbedClaimProvenance,
operation: EmbedOperationReceipt,
evaluation: Option<EmbedEvaluationProvenance>,
producing_runtime_identity: String,
}
impl<T> EmbedClaim<T> {
pub fn value(&self) -> &T {
&self.value
}
pub fn provenance(&self) -> &EmbedClaimProvenance {
&self.provenance
}
pub fn operation(&self) -> &EmbedOperationReceipt {
&self.operation
}
pub fn evaluation(&self) -> Option<&EmbedEvaluationProvenance> {
self.evaluation.as_ref()
}
pub fn producing_runtime_identity(&self) -> &str {
&self.producing_runtime_identity
}
}
#[derive(Debug)]
pub struct EmbeddedSourceSpec {
root: std::path::PathBuf,
}
impl EmbeddedSourceSpec {
pub fn current_worktree(root: std::path::PathBuf) -> Self {
Self { root }
}
}
#[derive(Debug)]
pub struct ShutdownReport {
pub closed_sources: u64,
pub joined_workers: u64,
}
#[derive(Debug)]
pub struct SourceCloseReport {
pub already_terminal: bool,
pub terminal_source_version: u64,
}
#[derive(Debug)]
pub struct EmbedShutdownReceipt {
_not_unwind_safe: NotUnwindSafe,
}
impl EmbedShutdownReceipt {
pub fn wait(&self, deadline: std::time::Instant) -> Result<ShutdownReport, ReceiptWaitError> {
let _ = deadline;
Ok(ShutdownReport {
closed_sources: 0,
joined_workers: 0,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceRuntimePhase {
Blocked,
Current,
Loading,
Refreshing,
Stopped,
Stopping,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceRuntimeView {
pub binding_identity: String,
pub current_publication_identity: Option<String>,
pub observer_epoch: u64,
pub phase: SourceRuntimePhase,
pub source_version: u64,
}
pub(crate) fn dark_unbound_refusal(kind: OperationKind) -> EmbedSourceRefusal {
EmbedSourceRefusal::wrap(&SourceRefusal::for_runtime(
SourceRefusalKind::SourceUnavailable,
OperationReceipt::for_dark_refusal(kind),
RetryAdvice::OnEvent,
None,
))
}
#[derive(Debug, Clone)]
pub struct ProcessRuntimeApi {
_inner: std::sync::Arc<ProcessIndexRuntime>,
factory: std::sync::Arc<super::embedded::EmbeddedSourceFactory>,
_not_unwind_safe: NotUnwindSafe,
}
impl Drop for ProcessRuntimeApi {
fn drop(&mut self) {
}
}
impl ProcessRuntimeApi {
pub fn acquire() -> Result<Self, EmbedSourceRefusal> {
Ok(Self {
_inner: ProcessIndexRuntime::incarnate(PROVISIONAL_ACQUIRE_PROCESS_BYTES),
factory: super::embedded::EmbeddedSourceFactory::new(),
_not_unwind_safe: std::marker::PhantomData,
})
}
pub fn open_embedded_source(
&self,
spec: EmbeddedSourceSpec,
) -> Result<super::embedded::EmbeddedSourceHandle, EmbedSourceRefusal> {
let key = super::registry::ProjectKey::new(spec.root.to_string_lossy());
self.factory.open(key).map_err(|refusal| {
let super::embedded::EmbedRefusal::SourceAlreadyOpen { .. } = refusal else {
unreachable!("EmbeddedSourceFactory::open refuses only SourceAlreadyOpen")
};
EmbedSourceRefusal::wrap(&SourceRefusal::for_runtime(
SourceRefusalKind::SelectionUnavailable,
OperationReceipt::for_dark_refusal(OperationKind::OpenEmbeddedSource),
RetryAdvice::OnEvent,
None,
))
})
}
pub fn begin_shutdown(&self) -> EmbedShutdownReceipt {
EmbedShutdownReceipt {
_not_unwind_safe: std::marker::PhantomData,
}
}
#[cfg(any(test, feature = "server"))]
pub fn refusal_probe_for_test(&self) -> Result<(), EmbedSourceRefusal> {
Err(dark_unbound_refusal(OperationKind::SearchSymbols))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WrapEntry {
pub atom: &'static str,
pub obligation: &'static str,
}
pub fn wrap_table() -> &'static [WrapEntry] {
const TABLE: &[WrapEntry] = &[
WrapEntry {
atom: "symforge::embed::AtomicAuthority",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::Claim",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::ClaimProvenance",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::EmbeddedSourceHandle",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::EmbeddedSourceSpec",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::EvaluationProvenance",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::OperationKind",
obligation: "verbatim-reexport",
},
WrapEntry {
atom: "symforge::embed::OperationReceipt",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::ProcessIndexRuntime",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::ReceiptWaitError",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::RefreshTicket",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::RetryAdvice",
obligation: "verbatim-reexport",
},
WrapEntry {
atom: "symforge::embed::ShutdownReceipt",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::ShutdownReport",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::SourceCloseReceipt",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::SourceCloseReport",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::SourceRefusal",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::SourceRefusalKind",
obligation: "verbatim-reexport",
},
WrapEntry {
atom: "symforge::embed::SourceRuntimePhase",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::SourceRuntimeView",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::SymbolMatch",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::SymbolSearchRequest",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::SymbolSearchResult",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::TextMatch",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::TextSearchRequest",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::embed::TextSearchResult",
obligation: "wrapped-here",
},
WrapEntry {
atom: "symforge::server_api",
obligation: "keyword-flip",
},
WrapEntry {
atom: "symforge::server_api::ServerBootstrapError",
obligation: "keyword-flip",
},
WrapEntry {
atom: "symforge::server_api::ServerExit",
obligation: "keyword-flip",
},
WrapEntry {
atom: "symforge::server_api::run",
obligation: "keyword-flip",
},
];
TABLE
}
pub fn render_export_delta(contract_text: &str, lib_text: &str) -> String {
let contract_sha = crate::hash::digest_hex(contract_text.as_bytes());
let contract: serde_json::Value =
serde_json::from_str(contract_text).expect("frozen contract parses");
let atoms: Vec<String> = contract["migration_v10"]["introduced_v11_atoms"]
.as_array()
.expect("atoms")
.iter()
.map(|a| a.as_str().expect("atom").to_string())
.collect();
let live_mods: BTreeSet<String> = lib_text
.lines()
.filter_map(parse_pub_mod)
.map(|name| format!("symforge::{name}"))
.collect();
let introduced_minus_live: Vec<&String> = atoms
.iter()
.filter(|atom| !live_mods.contains(*atom))
.collect();
let obligations: Vec<serde_json::Value> = wrap_table()
.iter()
.map(|entry| {
serde_json::json!({
"atom": entry.atom,
"obligation": entry.obligation,
})
})
.collect();
let delta = serde_json::json!({
"kind": "symforge-feature-020-export-delta",
"schema_version": 1,
"contract_sha256": contract_sha,
"computed_as": "introduced_v11_atoms listed verbatim; introduced_minus_live is that list with every atom that already appears verbatim in the live pub-mod census of src/lib.rs subtracted",
"live_census_pub_mods": live_mods.iter().collect::<Vec<_>>(),
"introduced_atoms": atoms,
"introduced_minus_live": introduced_minus_live,
"obligations": obligations,
"forbidden_at_activation": [
{
"citizen": "symforge::protocol::format::claim_provenance",
"rule": "D12: the internal provenance mount must not surface as a public module path; the embed boundary wraps it"
},
{
"citizen": "symforge::live_index::knowledge_bridge::LimitBreach through TruncationBreaches",
"rule": "D12/D13: a deep internal type must not leak through the embed surface; the boundary wraps or unwinds it"
}
],
"server_api": {
"form": "cfg feature=server gated pub(crate) mod server_api in src/lib.rs, std-only stub",
"activation": "one keyword behind the already-present server cfg gate: pub(crate) becomes pub, and the census gains the four server_api atoms in server graphs only - the embed-v11 projection excludes this module, so no embed cell may ever grow them"
}
});
serde_json::to_string_pretty(&delta).expect("delta serializes")
}
fn parse_pub_mod(line: &str) -> Option<&str> {
let mut words = line.split_whitespace();
if words.next() != Some("pub") || words.next() != Some("mod") {
return None;
}
let name = words.next()?.strip_suffix(';')?;
if words.next().is_some() || name.is_empty() {
return None;
}
Some(name)
}