release: bump to 2.1.2 (EK production chain + View V0–V3 bar)
Ship evidence/closure invalidation, verify/adjudicate, reuse_execute and agent bind/publish gates, document.extract, KnowledgePresentation + SSE page_token, and upload max_bytes with the 45-test offline gate. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
0b80ff8e50
commit
dc853fb580
38 files changed
+3045
-298
No files matched your search
+133
-25
@@ -572,9 +572,17 @@ fn artifact_for_function(
|
||||
content_digest: Some(implementation.clone()),
|
||||
relation: "defines".into(),
|
||||
}];
|
||||
let resolved = super::provenance::resolve_provenance(path, module_prov);
|
||||
provenance.extend(resolved.refs);
|
||||
let evidence = digest(contract_summary(&contract));
|
||||
let fn_sources = super::provenance::sources_for_function(module_prov, &function.name);
|
||||
let mut fn_prov = module_prov.clone();
|
||||
fn_prov.sources = fn_sources;
|
||||
let resolved = super::provenance::resolve_provenance_sources(path, &fn_prov, &fn_prov.sources);
|
||||
provenance.extend(resolved.refs.clone());
|
||||
// M02: evidence digest includes contract + canonical provenance (URI/locator/content/applicability).
|
||||
let evidence = digest(format!(
|
||||
"{}|{}",
|
||||
contract_summary(&contract),
|
||||
resolved.evidence_record
|
||||
));
|
||||
let kind = match symbol.kind {
|
||||
SymbolKind::Type => "type",
|
||||
SymbolKind::Function => "function",
|
||||
@@ -1012,39 +1020,139 @@ fn direct_effects(calls: &[(usize, CallExpr, u32)]) -> EffectSet {
|
||||
|
||||
/// Propagate callee effects along local `dependencies` edges until fixpoint.
|
||||
/// Empty effect sets become `pure` only after closure (no unknown remains).
|
||||
/// Fixpoint closure digest: own artifact hash + sorted dependency closure hashes (G08).
|
||||
///
|
||||
/// Deterministic SCC closure digests (M02/G08):
|
||||
/// - Member seed = sorted `(artifact_id, interface, implementation)` within the SCC
|
||||
/// - External = sorted closures of dependencies outside the SCC
|
||||
/// - All members of an SCC share one closure digest
|
||||
fn close_closure_digests(artifacts: &mut [SemanticArtifact]) {
|
||||
let n = artifacts.len();
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let index: BTreeMap<String, usize> = artifacts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, a)| (a.artifact_id.0.clone(), i))
|
||||
.collect();
|
||||
for _ in 0..n.saturating_add(1) {
|
||||
let mut changed = false;
|
||||
let snap: Vec<String> = artifacts
|
||||
.iter()
|
||||
.map(|a| a.hashes.closure.0.clone())
|
||||
.collect();
|
||||
for artifact in artifacts.iter_mut() {
|
||||
let mut parts = vec![artifact.hashes.artifact.0.clone()];
|
||||
for dep in &artifact.dependencies {
|
||||
if let Some(&i) = index.get(&dep.0) {
|
||||
parts.push(snap[i].clone());
|
||||
} else {
|
||||
parts.push(dep.0.clone());
|
||||
|
||||
// Tarjan SCC
|
||||
let mut stack: Vec<usize> = Vec::new();
|
||||
let mut on_stack = vec![false; n];
|
||||
let mut indices = vec![-1i32; n];
|
||||
let mut lowlink = vec![0i32; n];
|
||||
let mut index_counter = 0i32;
|
||||
let mut sccs: Vec<Vec<usize>> = Vec::new();
|
||||
|
||||
fn strongconnect(
|
||||
v: usize,
|
||||
artifacts: &[SemanticArtifact],
|
||||
index_map: &BTreeMap<String, usize>,
|
||||
stack: &mut Vec<usize>,
|
||||
on_stack: &mut [bool],
|
||||
indices: &mut [i32],
|
||||
lowlink: &mut [i32],
|
||||
index_counter: &mut i32,
|
||||
sccs: &mut Vec<Vec<usize>>,
|
||||
) {
|
||||
indices[v] = *index_counter;
|
||||
lowlink[v] = *index_counter;
|
||||
*index_counter += 1;
|
||||
stack.push(v);
|
||||
on_stack[v] = true;
|
||||
for dep in &artifacts[v].dependencies {
|
||||
if let Some(&w) = index_map.get(&dep.0) {
|
||||
if indices[w] < 0 {
|
||||
strongconnect(
|
||||
w,
|
||||
artifacts,
|
||||
index_map,
|
||||
stack,
|
||||
on_stack,
|
||||
indices,
|
||||
lowlink,
|
||||
index_counter,
|
||||
sccs,
|
||||
);
|
||||
lowlink[v] = lowlink[v].min(lowlink[w]);
|
||||
} else if on_stack[w] {
|
||||
lowlink[v] = lowlink[v].min(indices[w]);
|
||||
}
|
||||
}
|
||||
parts.sort();
|
||||
parts.dedup();
|
||||
let next = digest(parts.join("|"));
|
||||
if next.0 != artifact.hashes.closure.0 {
|
||||
artifact.hashes.closure = next;
|
||||
changed = true;
|
||||
}
|
||||
if lowlink[v] == indices[v] {
|
||||
let mut scc = Vec::new();
|
||||
loop {
|
||||
let w = stack.pop().expect("tarjan stack");
|
||||
on_stack[w] = false;
|
||||
scc.push(w);
|
||||
if w == v {
|
||||
break;
|
||||
}
|
||||
}
|
||||
scc.sort_unstable();
|
||||
sccs.push(scc);
|
||||
}
|
||||
}
|
||||
|
||||
for v in 0..n {
|
||||
if indices[v] < 0 {
|
||||
strongconnect(
|
||||
v,
|
||||
artifacts,
|
||||
&index,
|
||||
&mut stack,
|
||||
&mut on_stack,
|
||||
&mut indices,
|
||||
&mut lowlink,
|
||||
&mut index_counter,
|
||||
&mut sccs,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// sccs are in reverse topological order (callees before callers for DAGs).
|
||||
let mut scc_of = vec![0usize; n];
|
||||
for (si, scc) in sccs.iter().enumerate() {
|
||||
for &v in scc {
|
||||
scc_of[v] = si;
|
||||
}
|
||||
}
|
||||
let mut closure_done = vec![false; n];
|
||||
for scc in &sccs {
|
||||
let mut member_parts = Vec::new();
|
||||
for &v in scc {
|
||||
let a = &artifacts[v];
|
||||
member_parts.push(format!(
|
||||
"{}|{}|{}",
|
||||
a.artifact_id.0, a.hashes.interface.0, a.hashes.implementation.0
|
||||
));
|
||||
}
|
||||
member_parts.sort();
|
||||
member_parts.dedup();
|
||||
let mut external = Vec::new();
|
||||
for &v in scc {
|
||||
for dep in &artifacts[v].dependencies {
|
||||
if let Some(&w) = index.get(&dep.0) {
|
||||
if scc_of[w] != scc_of[v] && closure_done[w] {
|
||||
external.push(artifacts[w].hashes.closure.0.clone());
|
||||
} else if scc_of[w] != scc_of[v] {
|
||||
// External not yet closed — use artifact hash as stable seed.
|
||||
external.push(artifacts[w].hashes.artifact.0.clone());
|
||||
}
|
||||
} else {
|
||||
external.push(dep.0.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break;
|
||||
external.sort();
|
||||
external.dedup();
|
||||
let mut parts = member_parts;
|
||||
parts.extend(external);
|
||||
let scc_digest = digest(parts.join("|"));
|
||||
for &v in scc {
|
||||
artifacts[v].hashes.closure = scc_digest.clone();
|
||||
closure_done[v] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+69
-10
@@ -111,7 +111,8 @@ pub fn check_links_lock(out_dir: &Path, project: &SemanticProject) -> Result<Loc
|
||||
}
|
||||
|
||||
/// Static reverse dependency closure. Queries can be an artifact/symbol URI,
|
||||
/// a declaration suffix, or a project-relative source filename.
|
||||
/// a declaration suffix, a project-relative source filename, or a corpus
|
||||
/// provenance URI (`supports` relation — M02).
|
||||
pub fn impact(project: &SemanticProject, query: &str) -> Value {
|
||||
let mut seeds = BTreeSet::new();
|
||||
for artifact in &project.artifacts {
|
||||
@@ -125,6 +126,15 @@ pub fn impact(project: &SemanticProject, query: &str) -> Value {
|
||||
.and_then(|s| s.to_str())
|
||||
.is_some_and(|stem| stem == query || query.ends_with(stem))
|
||||
|| artifact.artifact_id.0.ends_with(query)
|
||||
|| artifact.provenance.iter().any(|p| {
|
||||
p.relation == "supports"
|
||||
&& (p.uri == query
|
||||
|| p.uri.ends_with(query)
|
||||
|| query.ends_with(&p.uri)
|
||||
|| p.locator
|
||||
.as_ref()
|
||||
.is_some_and(|loc| format!("{}#{}", p.uri, loc) == query))
|
||||
})
|
||||
{
|
||||
seeds.insert(artifact.artifact_id.0.clone());
|
||||
}
|
||||
@@ -137,6 +147,22 @@ pub fn impact(project: &SemanticProject, query: &str) -> Value {
|
||||
.or_default()
|
||||
.push(artifact.artifact_id.0.clone());
|
||||
}
|
||||
// Corpus URI → citing artifact (provenance supports edges).
|
||||
for prov in &artifact.provenance {
|
||||
if prov.relation != "supports" {
|
||||
continue;
|
||||
}
|
||||
reverse
|
||||
.entry(prov.uri.clone())
|
||||
.or_default()
|
||||
.push(artifact.artifact_id.0.clone());
|
||||
if let Some(loc) = &prov.locator {
|
||||
reverse
|
||||
.entry(format!("{}#{}", prov.uri, loc))
|
||||
.or_default()
|
||||
.push(artifact.artifact_id.0.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
// NarrativeRef edges: step → symbol; impact includes the step's owning artifact.
|
||||
for step in &project.steps {
|
||||
@@ -157,21 +183,54 @@ pub fn impact(project: &SemanticProject, query: &str) -> Value {
|
||||
.push(owner.clone());
|
||||
}
|
||||
}
|
||||
// Also seed reverse walk from corpus URI keys when query matches them.
|
||||
if reverse.contains_key(query) {
|
||||
seeds.insert(query.to_string());
|
||||
}
|
||||
let mut queue: VecDeque<String> = seeds.iter().cloned().collect();
|
||||
let mut affected = BTreeSet::new();
|
||||
while let Some(current) = queue.pop_front() {
|
||||
if !affected.insert(current.clone()) { continue; }
|
||||
if !affected.insert(current.clone()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(users) = reverse.get(¤t) {
|
||||
for user in users { queue.push_back(user.clone()); }
|
||||
for user in users {
|
||||
queue.push_back(user.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let entries = affected.iter().filter_map(|id| project.artifacts.iter().find(|a| &a.artifact_id.0 == id)).map(|artifact| json!({
|
||||
"artifact_id": artifact.artifact_id.0,
|
||||
"symbol_id": artifact.symbol_id.as_ref().map(|id| id.as_str()),
|
||||
"display_name": artifact.display_name,
|
||||
"kind": artifact.kind,
|
||||
"source": {"file": artifact.source.file, "line": artifact.source.line},
|
||||
})).collect::<Vec<_>>();
|
||||
// Drop pure corpus URI keys that are not artifacts from the affected set display.
|
||||
let entries = affected
|
||||
.iter()
|
||||
.filter_map(|id| project.artifacts.iter().find(|a| &a.artifact_id.0 == id))
|
||||
.map(|artifact| {
|
||||
let classes = {
|
||||
let mut c = Vec::new();
|
||||
if !artifact.hashes.interface.0.is_empty() {
|
||||
c.push("interface");
|
||||
}
|
||||
if !artifact.hashes.implementation.0.is_empty() {
|
||||
c.push("implementation");
|
||||
}
|
||||
if !artifact.hashes.evidence.0.is_empty() {
|
||||
c.push("evidence");
|
||||
}
|
||||
if !artifact.dependencies.is_empty() {
|
||||
c.push("dependency");
|
||||
}
|
||||
c
|
||||
};
|
||||
json!({
|
||||
"artifact_id": artifact.artifact_id.0,
|
||||
"symbol_id": artifact.symbol_id.as_ref().map(|id| id.as_str()),
|
||||
"display_name": artifact.display_name,
|
||||
"kind": artifact.kind,
|
||||
"source": {"file": artifact.source.file, "line": artifact.source.line},
|
||||
"hash_classes": classes,
|
||||
"evidence": artifact.verification.evidence,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
json!({"schema_version":SCHEMA_VERSION,"query":query,"resolved":!seeds.is_empty(),"seeds":seeds,"affected":entries})
|
||||
}
|
||||
|
||||
|
||||
+277
-16
@@ -1,4 +1,4 @@
|
||||
//! Optional source / applicability facts from module frontmatter (G05).
|
||||
//! Optional source / applicability facts from module frontmatter (G05 / M02).
|
||||
//!
|
||||
//! Authors declare `sources:` and optional `applicability:` / `valid_until` in
|
||||
//! frontmatter. Absence means a pure tool may still run but must stay
|
||||
@@ -11,12 +11,19 @@ use sha2::{Digest as _, Sha256};
|
||||
|
||||
use super::ir::{Digest, SourceRef};
|
||||
|
||||
/// Provenance extractor / verifier identity hashed into evidence digests.
|
||||
pub const PROVENANCE_EXTRACTOR_VERSION: &str = "marqdo-provenance/1";
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ModuleProvenance {
|
||||
/// Relative corpus paths, optional `#anchor`.
|
||||
pub sources: Vec<String>,
|
||||
pub valid_until: Option<String>,
|
||||
pub region: Option<String>,
|
||||
/// True when author wrote `sources: [...]` inline (ignored by parser — M07).
|
||||
pub inline_sources_ignored: bool,
|
||||
/// Optional per-function source overrides (M07): `function_sources: { name: [uri…] }`.
|
||||
pub function_sources: std::collections::BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
/// Scan YAML-ish frontmatter for sources / applicability (no full YAML parser).
|
||||
@@ -28,6 +35,8 @@ pub fn parse_module_provenance(source: &str) -> ModuleProvenance {
|
||||
let mut out = ModuleProvenance::default();
|
||||
let mut in_sources = false;
|
||||
let mut in_applicability = false;
|
||||
let mut in_function_sources = false;
|
||||
let mut current_fn: Option<String> = None;
|
||||
for line in lines {
|
||||
let t = line.trim_end();
|
||||
if t.trim() == "---" {
|
||||
@@ -40,21 +49,59 @@ pub fn parse_module_provenance(source: &str) -> ModuleProvenance {
|
||||
if !line.starts_with(' ') && !line.starts_with('\t') {
|
||||
in_sources = false;
|
||||
in_applicability = false;
|
||||
in_function_sources = false;
|
||||
current_fn = None;
|
||||
}
|
||||
if trimmed == "sources:" || trimmed.starts_with("sources:") {
|
||||
in_sources = true;
|
||||
in_applicability = false;
|
||||
in_function_sources = false;
|
||||
if let Some(rest) = trimmed.strip_prefix("sources:") {
|
||||
let rest = rest.trim();
|
||||
if !rest.is_empty() && rest != "|" {
|
||||
// inline list not used; ignore
|
||||
// inline list is not parsed — flag for diagnosis (M07).
|
||||
out.inline_sources_ignored = true;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if trimmed == "function_sources:" || trimmed.starts_with("function_sources:") {
|
||||
in_function_sources = true;
|
||||
in_sources = false;
|
||||
in_applicability = false;
|
||||
current_fn = None;
|
||||
continue;
|
||||
}
|
||||
if trimmed == "applicability:" || trimmed.starts_with("applicability:") {
|
||||
in_applicability = true;
|
||||
in_sources = false;
|
||||
in_function_sources = false;
|
||||
continue;
|
||||
}
|
||||
if in_function_sources {
|
||||
// Indent levels: ` name:` then ` - uri`
|
||||
let indent = line.len() - line.trim_start().len();
|
||||
if trimmed.ends_with(':') && !trimmed.starts_with('-') {
|
||||
let name = trimmed.trim_end_matches(':').trim().to_string();
|
||||
if !name.is_empty() {
|
||||
current_fn = Some(name.clone());
|
||||
out.function_sources.entry(name).or_default();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(item) = trimmed.strip_prefix("- ") {
|
||||
let path = item.trim().trim_matches('"').to_string();
|
||||
if let Some(name) = ¤t_fn {
|
||||
if !path.is_empty() {
|
||||
out.function_sources
|
||||
.entry(name.clone())
|
||||
.or_default()
|
||||
.push(path);
|
||||
}
|
||||
} else if indent >= 2 && !path.is_empty() {
|
||||
// ignore orphan list items
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if in_sources {
|
||||
@@ -77,26 +124,56 @@ pub fn parse_module_provenance(source: &str) -> ModuleProvenance {
|
||||
out
|
||||
}
|
||||
|
||||
/// Sources applicable to a named function: function_sources override, else module sources.
|
||||
pub fn sources_for_function(prov: &ModuleProvenance, function_name: &str) -> Vec<String> {
|
||||
if let Some(list) = prov.function_sources.get(function_name) {
|
||||
if !list.is_empty() {
|
||||
return list.clone();
|
||||
}
|
||||
}
|
||||
prov.sources.clone()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ProvenanceDiag {
|
||||
Missing { path: String },
|
||||
AnchorMissing { path: String, locator: String },
|
||||
ReadError { path: String, message: String },
|
||||
Expired { valid_until: String },
|
||||
InvalidDate { valid_until: String },
|
||||
InlineSourcesIgnored,
|
||||
}
|
||||
|
||||
impl ProvenanceDiag {
|
||||
pub fn code(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Missing { .. } => "source.missing",
|
||||
Self::AnchorMissing { .. } => "source.anchor_missing",
|
||||
Self::ReadError { .. } => "source.read_error",
|
||||
Self::Expired { .. } => "source.expired",
|
||||
Self::InvalidDate { .. } => "source.invalid_date",
|
||||
Self::InlineSourcesIgnored => "source.inline_ignored",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn message(&self) -> String {
|
||||
match self {
|
||||
Self::Missing { path } => format!("来源文件缺失:`{path}`"),
|
||||
Self::AnchorMissing { path, locator } => {
|
||||
format!("来源锚点不存在:`{path}` 中找不到 `#{}`", locator)
|
||||
}
|
||||
Self::ReadError { path, message } => {
|
||||
format!("来源文件无法读取:`{path}`({message})")
|
||||
}
|
||||
Self::Expired { valid_until } => {
|
||||
format!("来源适用期已过(valid_until={valid_until})")
|
||||
}
|
||||
Self::InvalidDate { valid_until } => {
|
||||
format!("适用期日期格式无效(期望 YYYY-MM-DD):`{valid_until}`")
|
||||
}
|
||||
Self::InlineSourcesIgnored => {
|
||||
"sources 行内列表被忽略;请改用 YAML block list(`- path#anchor`)".into()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,21 +183,35 @@ pub struct ProvenanceResolution {
|
||||
pub applicability: String,
|
||||
pub evidence_status: String,
|
||||
pub diagnostics: Vec<ProvenanceDiag>,
|
||||
/// Canonical record hashed into `hashes.evidence` (M02).
|
||||
pub evidence_record: String,
|
||||
}
|
||||
|
||||
/// Resolve corpus paths relative to the module file; never mark verified here.
|
||||
pub fn resolve_provenance(
|
||||
module_path: &Path,
|
||||
prov: &ModuleProvenance,
|
||||
) -> ProvenanceResolution {
|
||||
resolve_provenance_sources(module_path, prov, &prov.sources)
|
||||
}
|
||||
|
||||
/// Resolve an explicit source list (module or per-function).
|
||||
pub fn resolve_provenance_sources(
|
||||
module_path: &Path,
|
||||
prov: &ModuleProvenance,
|
||||
sources: &[String],
|
||||
) -> ProvenanceResolution {
|
||||
let mut refs = Vec::new();
|
||||
let mut diagnostics = Vec::new();
|
||||
if prov.inline_sources_ignored {
|
||||
diagnostics.push(ProvenanceDiag::InlineSourcesIgnored);
|
||||
}
|
||||
let base = module_path
|
||||
.parent()
|
||||
.map(|p| p.to_path_buf())
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
|
||||
for raw in &prov.sources {
|
||||
for raw in sources {
|
||||
let (path_part, locator) = match raw.split_once('#') {
|
||||
Some((p, a)) => (p.trim(), Some(a.trim().to_string())),
|
||||
None => (raw.as_str(), None),
|
||||
@@ -138,22 +229,56 @@ pub fn resolve_provenance(
|
||||
});
|
||||
continue;
|
||||
}
|
||||
let content = fs::read(&resolved).unwrap_or_default();
|
||||
let content = match fs::read(&resolved) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) => {
|
||||
diagnostics.push(ProvenanceDiag::ReadError {
|
||||
path: path_part.to_string(),
|
||||
message: e.to_string(),
|
||||
});
|
||||
refs.push(SourceRef {
|
||||
uri: path_part.to_string(),
|
||||
locator,
|
||||
content_digest: None,
|
||||
relation: "supports".into(),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut hash = Sha256::new();
|
||||
hash.update(&content);
|
||||
let content_digest = Digest(format!("sha256:{:x}", hash.finalize()));
|
||||
if let Some(loc) = locator.as_ref() {
|
||||
let text = String::from_utf8_lossy(&content);
|
||||
if !anchor_exists(&text, loc) {
|
||||
diagnostics.push(ProvenanceDiag::AnchorMissing {
|
||||
path: path_part.to_string(),
|
||||
locator: loc.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
refs.push(SourceRef {
|
||||
uri: path_part.to_string(),
|
||||
locator,
|
||||
content_digest: Some(Digest(format!("sha256:{:x}", hash.finalize()))),
|
||||
content_digest: Some(content_digest),
|
||||
relation: "supports".into(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(until) = &prov.valid_until {
|
||||
if is_expired(until) {
|
||||
diagnostics.push(ProvenanceDiag::Expired {
|
||||
valid_until: until.clone(),
|
||||
});
|
||||
match validate_date(until) {
|
||||
DateCheck::Ok => {
|
||||
if is_expired(until) {
|
||||
diagnostics.push(ProvenanceDiag::Expired {
|
||||
valid_until: until.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
DateCheck::Invalid => {
|
||||
diagnostics.push(ProvenanceDiag::InvalidDate {
|
||||
valid_until: until.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,45 +302,168 @@ pub fn resolve_provenance(
|
||||
}
|
||||
};
|
||||
|
||||
let evidence_status = if diagnostics.iter().any(|d| matches!(d, ProvenanceDiag::Missing { .. }))
|
||||
let evidence_status = if diagnostics
|
||||
.iter()
|
||||
.any(|d| matches!(d, ProvenanceDiag::Missing { .. } | ProvenanceDiag::ReadError { .. }))
|
||||
{
|
||||
"missing_source".into()
|
||||
} else if diagnostics
|
||||
.iter()
|
||||
.any(|d| matches!(d, ProvenanceDiag::AnchorMissing { .. }))
|
||||
{
|
||||
"anchor_missing".into()
|
||||
} else if diagnostics
|
||||
.iter()
|
||||
.any(|d| matches!(d, ProvenanceDiag::Expired { .. }))
|
||||
{
|
||||
"expired".into()
|
||||
} else if prov.sources.is_empty() {
|
||||
} else if diagnostics
|
||||
.iter()
|
||||
.any(|d| matches!(d, ProvenanceDiag::InvalidDate { .. }))
|
||||
{
|
||||
"invalid_date".into()
|
||||
} else if sources.is_empty() {
|
||||
"unverified".into()
|
||||
} else {
|
||||
// Corpus present and in date — still not domain-verified by compile alone.
|
||||
"sourced".into()
|
||||
};
|
||||
|
||||
let prov_for_record = ModuleProvenance {
|
||||
sources: sources.to_vec(),
|
||||
valid_until: prov.valid_until.clone(),
|
||||
region: prov.region.clone(),
|
||||
inline_sources_ignored: prov.inline_sources_ignored,
|
||||
function_sources: Default::default(),
|
||||
};
|
||||
let evidence_record = evidence_canonical_record(&prov_for_record, &refs);
|
||||
|
||||
ProvenanceResolution {
|
||||
refs,
|
||||
applicability,
|
||||
evidence_status,
|
||||
diagnostics,
|
||||
evidence_record,
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical evidence inputs: extractor version, applicability, sorted source facts.
|
||||
pub fn evidence_canonical_record(prov: &ModuleProvenance, refs: &[SourceRef]) -> String {
|
||||
let mut parts = vec![
|
||||
format!("extractor={PROVENANCE_EXTRACTOR_VERSION}"),
|
||||
format!("region={}", prov.region.as_deref().unwrap_or("")),
|
||||
format!("valid_until={}", prov.valid_until.as_deref().unwrap_or("")),
|
||||
];
|
||||
let mut source_parts: Vec<String> = refs
|
||||
.iter()
|
||||
.filter(|r| r.relation == "supports")
|
||||
.map(|r| {
|
||||
format!(
|
||||
"{}#{}@{}",
|
||||
r.uri,
|
||||
r.locator.as_deref().unwrap_or(""),
|
||||
r.content_digest
|
||||
.as_ref()
|
||||
.map(|d| d.0.as_str())
|
||||
.unwrap_or("none")
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
source_parts.sort();
|
||||
parts.extend(source_parts);
|
||||
parts.join("|")
|
||||
}
|
||||
|
||||
/// Whether a Markdown heading / id matches the `#locator` fragment.
|
||||
pub fn anchor_exists(content: &str, locator: &str) -> bool {
|
||||
let loc = locator.trim().trim_start_matches('#').trim();
|
||||
if loc.is_empty() {
|
||||
return true;
|
||||
}
|
||||
for line in content.lines() {
|
||||
let t = line.trim();
|
||||
if let Some(rest) = t.strip_prefix('#') {
|
||||
let heading = rest.trim_start_matches('#').trim();
|
||||
let heading = heading
|
||||
.split('{')
|
||||
.next()
|
||||
.unwrap_or(heading)
|
||||
.trim();
|
||||
if heading == loc || slugify_heading(heading) == loc {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if t.contains(&format!("id=\"{loc}\""))
|
||||
|| t.contains(&format!("id='{loc}'"))
|
||||
|| t.contains(&format!("{{#{loc}}}"))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn slugify_heading(heading: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for ch in heading.chars() {
|
||||
if ch.is_ascii_alphanumeric() {
|
||||
out.push(ch.to_ascii_lowercase());
|
||||
} else if ch == ' ' || ch == '-' || ch == '_' {
|
||||
if !out.ends_with('-') {
|
||||
out.push('-');
|
||||
}
|
||||
} else if !ch.is_ascii() {
|
||||
// Keep non-ASCII letters (common in ZH docs) without lowercasing rules.
|
||||
out.push(ch);
|
||||
}
|
||||
}
|
||||
out.trim_matches('-').to_string()
|
||||
}
|
||||
|
||||
enum DateCheck {
|
||||
Ok,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
fn validate_date(valid_until: &str) -> DateCheck {
|
||||
let parts: Vec<&str> = valid_until.split('-').collect();
|
||||
if parts.len() != 3 {
|
||||
return DateCheck::Invalid;
|
||||
}
|
||||
let Ok(y) = parts[0].parse::<i32>() else {
|
||||
return DateCheck::Invalid;
|
||||
};
|
||||
let Ok(m) = parts[1].parse::<u32>() else {
|
||||
return DateCheck::Invalid;
|
||||
};
|
||||
let Ok(d) = parts[2].parse::<u32>() else {
|
||||
return DateCheck::Invalid;
|
||||
};
|
||||
if !(1..=12).contains(&m) || !(1..=31).contains(&d) || y < 1970 {
|
||||
return DateCheck::Invalid;
|
||||
}
|
||||
if parts[0].len() != 4 || parts[1].len() != 2 || parts[2].len() != 2 {
|
||||
return DateCheck::Invalid;
|
||||
}
|
||||
DateCheck::Ok
|
||||
}
|
||||
|
||||
fn is_expired(valid_until: &str) -> bool {
|
||||
// Expect YYYY-MM-DD; compare lexicographically to today's UTC date.
|
||||
let today = chrono_today();
|
||||
!valid_until.is_empty() && valid_until < today.as_str()
|
||||
}
|
||||
|
||||
/// Public recheck for handle.execute (M02).
|
||||
pub fn valid_until_expired(valid_until: &str) -> bool {
|
||||
matches!(validate_date(valid_until), DateCheck::Ok) && is_expired(valid_until)
|
||||
}
|
||||
|
||||
fn chrono_today() -> String {
|
||||
// Avoid new dependency: use system local date via `date` is bad; use
|
||||
// SystemTime → rough days since epoch is fragile. Prefer `time` crate if
|
||||
// present, else format via `js_sys` — check Cargo.toml.
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
let secs = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as i64;
|
||||
// UTC civil date from days since epoch (proleptic Gregorian).
|
||||
let days = secs.div_euclid(86_400);
|
||||
let (y, m, d) = civil_from_days(days);
|
||||
format!("{y:04}-{m:02}-{d:02}")
|
||||
@@ -248,4 +496,17 @@ mod tests {
|
||||
assert_eq!(p.region.as_deref(), Some("CN"));
|
||||
assert_eq!(p.valid_until.as_deref(), Some("2099-12-31"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchor_matches_heading() {
|
||||
assert!(anchor_exists("# rate\n\nrate = 0.13\n", "rate"));
|
||||
assert!(!anchor_exists("# rate\n\nrate = 0.13\n", "missing-anchor"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_date_rejected() {
|
||||
assert!(matches!(validate_date("2099-12-31"), DateCheck::Ok));
|
||||
assert!(matches!(validate_date("not-a-date"), DateCheck::Invalid));
|
||||
assert!(matches!(validate_date("2099-13-01"), DateCheck::Invalid));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user