feat: land S1–S6 executable-knowledge slices (NarrativeRef through CI)

Add comment-line NarrativeRef steps, generation CURRENT snapshots, frontmatter
sources/applicability, digest-guarded artifact.patch, lock change classes, and
an offline CI gate so the documented S0–S6 path has reviewable evidence.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-10-23 23:24:18 +08:00
1 parent 0e1bfb3359
commit dcd3d329d4
18 files changed
+1314 -77

No files matched your search

+262 -51
View File
@@ -284,9 +284,21 @@ pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
artifacts.push(module_artifact(&index, module_id, path, text));
let mut by_path = BTreeMap::new();
collect_functions(&module.functions, &mut Vec::new(), &mut by_path);
let narrative_links = crate::parse::scan_narrative_links(text);
let module_prov = super::provenance::parse_module_provenance(text);
let module_symbols: Vec<&SymbolDecl> = index
.symbols()
.iter()
.filter(|s| &s.module == module_id)
.collect();
for symbol in index.symbols().iter().filter(|s| &s.module == module_id) {
let function = by_path.get(&symbol.declaration_path).expect("symbol collected from module");
let (artifact, mut artifact_refs, mut artifact_steps, mut bounds, mut dynamics) =
let owned_links: Vec<_> = narrative_links
.iter()
.filter(|link| enclosing_symbol(&module_symbols, link.line).is_some_and(|s| s.id == symbol.id))
.cloned()
.collect();
let (artifact, mut artifact_refs, mut artifact_steps, mut bounds, mut dynamics, prov_diags) =
artifact_for_function(
&index,
module_id,
@@ -295,7 +307,16 @@ pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
function,
symbol,
&local_by_name,
&owned_links,
&module_prov,
);
for diag in prov_diags {
diagnostics.push(
Diagnostic::new(Some(path), Span::new(1, 1), diag.message())
.with_code(diag.code())
.with_severity(Severity::Warning),
);
}
refs.append(&mut artifact_refs);
steps.append(&mut artifact_steps);
bound_calls.append(&mut bounds);
@@ -391,6 +412,37 @@ fn attach_project_imports(files: &mut BTreeMap<ModuleId, (PathBuf, String, Modul
}
}
fn enclosing_symbol<'a>(symbols: &[&'a SymbolDecl], line: u32) -> Option<&'a SymbolDecl> {
symbols
.iter()
.copied()
.filter(|s| s.line <= line)
.max_by_key(|s| s.line)
}
fn resolve_narrative_target(
index: &ProjectIndex,
module_id: &ModuleId,
local_by_name: &BTreeMap<(ModuleId, String), SymbolId>,
target: &str,
) -> Option<SymbolId> {
let t = target.trim().trim_start_matches('#');
if t.is_empty() {
return None;
}
if let Some(id) = local_by_name.get(&(module_id.clone(), t.to_string())) {
return Some(id.clone());
}
// Path-like `bind.member` via display name suffix match within project.
index.symbols().iter().find_map(|s| {
if s.declaration_path.join(".") == t || s.name == t {
Some(s.id.clone())
} else {
None
}
})
}
fn artifact_for_function(
index: &ProjectIndex,
module_id: &ModuleId,
@@ -399,12 +451,15 @@ fn artifact_for_function(
function: &Function,
symbol: &SymbolDecl,
local_by_name: &BTreeMap<(ModuleId, String), SymbolId>,
narrative_links: &[crate::parse::NarrativeLink],
module_prov: &super::provenance::ModuleProvenance,
) -> (
SemanticArtifact,
Vec<KnowledgeRef>,
Vec<KnowledgeStep>,
Vec<BoundCall>,
Vec<DynamicCall>,
Vec<super::provenance::ProvenanceDiag>,
) {
let calls = collect_call_sites(function);
let mut effects = direct_effects(&calls);
@@ -436,14 +491,16 @@ fn artifact_for_function(
let named = collect_named_steps(function);
let mut refs = Vec::new();
let mut steps = Vec::new();
for (n, named) in named.iter().enumerate() {
let mut step_n = 0u32;
for named in named.iter() {
step_n += 1;
let target = named.call.as_ref().and_then(|call| {
match classify_call(index, module_id, ast_module, function, call, local_by_name) {
CallClass::Bound { target, .. } => Some(target),
_ => None,
}
});
let ref_id = format!("{}#ref-{}", symbol.id.as_str(), n + 1);
let ref_id = format!("{}#ref-{}", symbol.id.as_str(), step_n);
refs.push(KnowledgeRef {
id: ref_id.clone(),
label: named.label.clone(),
@@ -461,7 +518,7 @@ fn artifact_for_function(
.map(effects_for_call)
.unwrap_or_else(EffectSet::pure);
steps.push(KnowledgeStep {
id: ArtifactId(format!("{}#step-{}", symbol.id.as_str(), n + 1)),
id: ArtifactId(format!("{}#step-{}", symbol.id.as_str(), step_n)),
reference: ref_id,
kind: named.kind.clone(),
calls: target.into_iter().collect(),
@@ -469,24 +526,57 @@ fn artifact_for_function(
source: source_location(index.root().path(), path, named.line, named.line),
});
}
// G03 NarrativeRef: comment-line []() — never BoundCall, never effects.
for link in narrative_links {
step_n += 1;
let target = match link.kind {
crate::parse::NarrativeLinkKind::Narrate => {
resolve_narrative_target(index, module_id, local_by_name, &link.target)
}
crate::parse::NarrativeLinkKind::Navigation => None,
};
let ref_id = format!("{}#ref-{}", symbol.id.as_str(), step_n);
refs.push(KnowledgeRef {
id: ref_id.clone(),
label: link.label.clone(),
context: "narrative".into(),
source: source_location(index.root().path(), path, link.line, link.line),
resolution: match link.kind {
crate::parse::NarrativeLinkKind::Navigation => "navigation".into(),
crate::parse::NarrativeLinkKind::Narrate if target.is_some() => "symbol".into(),
crate::parse::NarrativeLinkKind::Narrate => "unresolved".into(),
},
target: target.clone(),
});
steps.push(KnowledgeStep {
id: ArtifactId(format!("{}#step-{}", symbol.id.as_str(), step_n)),
reference: ref_id,
kind: link.kind.as_str().into(),
calls: target.into_iter().collect(),
effects: EffectSet::pure(),
source: source_location(index.root().path(), path, link.line, link.line),
});
}
if effects.0.is_empty() {
effects = EffectSet::pure();
}
let (signature, contract) = signature(function, symbol.callable, &effects);
let interface = digest(signature_json(signature.as_ref()));
let implementation = digest(format!("{:?}", function.body));
let provenance = vec![SourceRef {
let mut provenance = vec![SourceRef {
uri: rel_uri(index.root().path(), path),
locator: Some(format!("L{}", function.span.line)),
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 kind = match symbol.kind {
SymbolKind::Type => "type",
SymbolKind::Function => "function",
}.to_string();
let artifact = semantic_artifact(
let mut artifact = semantic_artifact(
ArtifactId(symbol.id.as_str().to_string()),
Some(symbol.id.clone()),
symbol.declaration_path.join("."),
@@ -498,12 +588,20 @@ fn artifact_for_function(
effects,
dependencies,
provenance,
"no explicit applicability constraints".into(),
resolved.applicability,
interface,
implementation,
evidence,
);
(artifact, refs, steps, bound_calls, dynamic_calls)
artifact.verification.evidence = resolved.evidence_status;
(
artifact,
refs,
steps,
bound_calls,
dynamic_calls,
resolved.diagnostics,
)
}
enum CallClass {
@@ -1009,57 +1107,166 @@ fn dynamic_call_json(call: &DynamicCall) -> Value {
})
}
/// Atomically write the semantic portion of `.marqdo/`. A reader therefore
/// sees either the previous graph or the complete next graph, never a mix.
const SEMANTIC_NAMES: &[&str] = &[
"project.json",
"symbols.json",
"refs.json",
"steps.json",
"bound_calls.json",
"dynamic_calls.json",
"artifacts",
"graph",
"verification",
];
/// Resolve the active semantic generation directory (G04).
/// Prefers `CURRENT` → `generations/<id>/`; falls back to `out_dir` itself.
pub fn semantic_generation_dir(out_dir: &Path) -> PathBuf {
let current = out_dir.join("CURRENT");
if let Ok(id) = fs::read_to_string(&current) {
let id = id.trim();
if !id.is_empty() {
let gen = out_dir.join("generations").join(id);
if gen.join("project.json").is_file() {
return gen;
}
}
}
out_dir.to_path_buf()
}
/// Atomically write the semantic portion of `.marqdo/` as a whole generation
/// (G04). Readers that open via [`semantic_generation_dir`] never see a mix.
pub fn write_semantic_projections(out_dir: &Path, compilation: &Compilation) -> Result<()> {
let stage = out_dir.with_extension("tmp-sema");
if stage.exists() { fs::remove_dir_all(&stage).with_context(|| format!("clear {}", stage.display()))?; }
fs::create_dir_all(stage.join("artifacts"))?;
fs::create_dir_all(stage.join("graph"))?;
fs::create_dir_all(stage.join("verification"))?;
fs::create_dir_all(out_dir).with_context(|| format!("create {}", out_dir.display()))?;
let build_id = {
let mut hasher = Sha256::new();
hasher.update(compilation.semantics.project_id.as_bytes());
for a in &compilation.semantics.artifacts {
hasher.update(a.hashes.artifact.0.as_bytes());
}
hasher.update(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos()
.to_le_bytes(),
);
format!("{:x}", hasher.finalize())[..16].to_string()
};
let gens = out_dir.join("generations");
fs::create_dir_all(&gens)?;
let gen_dir = gens.join(&build_id);
if gen_dir.exists() {
fs::remove_dir_all(&gen_dir)?;
}
fs::create_dir_all(gen_dir.join("artifacts"))?;
fs::create_dir_all(gen_dir.join("graph"))?;
fs::create_dir_all(gen_dir.join("verification"))?;
write_generation_tree(&gen_dir, compilation)?;
// Atomic generation pointer: only publish CURRENT after the tree is complete.
let current_tmp = out_dir.join("CURRENT.tmp");
fs::write(&current_tmp, format!("{build_id}\n"))
.with_context(|| format!("write {}", current_tmp.display()))?;
fs::rename(&current_tmp, out_dir.join("CURRENT"))
.with_context(|| format!("publish CURRENT under {}", out_dir.display()))?;
// Compatibility root: stage a full mirror, then swap names (best-effort for
// legacy readers that do not follow CURRENT).
let stage = out_dir.join(".tmp-sema-publish");
if stage.exists() {
fs::remove_dir_all(&stage)?;
}
copy_dir_recursive(&gen_dir, &stage)?;
for name in SEMANTIC_NAMES {
let target = out_dir.join(name);
if target.exists() {
if target.is_dir() {
fs::remove_dir_all(&target)?;
} else {
fs::remove_file(&target)?;
}
}
fs::rename(stage.join(name), &target)?;
}
let _ = fs::remove_dir_all(&stage);
Ok(())
}
fn write_generation_tree(stage: &Path, compilation: &Compilation) -> Result<()> {
let project = compilation.semantics.to_json();
write_json(&stage.join("project.json"), &json!({"schema_version":SCHEMA_VERSION,"project":project["project"],"artifact_count":compilation.semantics.artifacts.len()}))?;
write_json(
&stage.join("project.json"),
&json!({
"schema_version": SCHEMA_VERSION,
"project": project["project"],
"artifact_count": compilation.semantics.artifacts.len(),
"generation": stage.file_name().and_then(|s| s.to_str()),
}),
)?;
write_json(&stage.join("symbols.json"), &json!({"schema_version":SCHEMA_VERSION,"symbols":compilation.index.symbols().iter().map(|s|json!({"id":s.id.as_str(),"module":s.module.as_str(),"kind":s.kind.as_str(),"callable":s.callable.map(|c|c.as_str()),"name":s.name,"declaration_path":s.declaration_path,"source":{"file":rel_uri(compilation.index.root().path(),&s.source),"line":s.line}})).collect::<Vec<_>>() }))?;
write_json(&stage.join("refs.json"), &json!({"schema_version":SCHEMA_VERSION,"refs":project["refs"]}))?;
write_json(&stage.join("steps.json"), &json!({"schema_version":SCHEMA_VERSION,"steps":project["steps"]}))?;
write_json(&stage.join("bound_calls.json"), &json!({"schema_version":SCHEMA_VERSION,"bound_calls":project["bound_calls"]}))?;
write_json(&stage.join("dynamic_calls.json"), &json!({"schema_version":SCHEMA_VERSION,"dynamic_calls":project["dynamic_calls"]}))?;
write_json(&stage.join("graph/nodes.json"), &json!({"schema_version":SCHEMA_VERSION,"nodes":project["artifacts"]}))?;
write_json(&stage.join("graph/edges.json"), &json!({"schema_version":SCHEMA_VERSION,"authority":"SemanticProject","edges":compilation.semantics.artifacts.iter().flat_map(|a|a.dependencies.iter().map(move |d|json!({"from":a.artifact_id.0,"to":d.0,"kind":"calls"}))).collect::<Vec<_>>() }))?;
for artifact in &compilation.semantics.artifacts {
let name = hex_name(&artifact.artifact_id.0);
write_json(&stage.join("artifacts").join(format!("{name}.json")), &artifact_json(artifact))?;
write_json(&stage.join("verification").join(format!("{name}.json")), &artifact_json(artifact)["verification"])?;
}
const SEMANTIC_NAMES: &[&str] = &[
"project.json",
"symbols.json",
"refs.json",
"steps.json",
"bound_calls.json",
"dynamic_calls.json",
"artifacts",
"graph",
"verification",
];
if out_dir.exists() {
for name in SEMANTIC_NAMES {
let target = out_dir.join(name);
if target.exists() {
if target.is_dir() {
fs::remove_dir_all(&target)?;
} else {
fs::remove_file(&target)?;
}
let mut edges: Vec<Value> = compilation
.semantics
.artifacts
.iter()
.flat_map(|a| {
a.dependencies.iter().map(move |d| {
json!({"from": a.artifact_id.0, "to": d.0, "kind": "calls"})
})
})
.collect();
for step in &compilation.semantics.steps {
if step.kind == "narrate" {
for target in &step.calls {
edges.push(json!({
"from": step.id.0,
"to": target.as_str(),
"kind": "narrates",
}));
}
}
} else {
fs::create_dir_all(out_dir)?;
}
for name in SEMANTIC_NAMES {
fs::rename(stage.join(name), out_dir.join(name))?;
write_json(
&stage.join("graph/edges.json"),
&json!({
"schema_version": SCHEMA_VERSION,
"authority": "SemanticProject",
"edges": edges,
}),
)?;
for artifact in &compilation.semantics.artifacts {
let name = hex_name(&artifact.artifact_id.0);
write_json(
&stage.join("artifacts").join(format!("{name}.json")),
&artifact_json(artifact),
)?;
write_json(
&stage.join("verification").join(format!("{name}.json")),
&artifact_json(artifact)["verification"],
)?;
}
Ok(())
}
fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
fs::create_dir_all(dst)?;
for ent in fs::read_dir(src).with_context(|| format!("read {}", src.display()))? {
let ent = ent?;
let from = ent.path();
let to = dst.join(ent.file_name());
if from.is_dir() {
copy_dir_recursive(&from, &to)?;
} else {
fs::copy(&from, &to)
.with_context(|| format!("copy {} → {}", from.display(), to.display()))?;
}
}
fs::remove_dir_all(stage)?;
Ok(())
}
@@ -1103,25 +1310,29 @@ mod tests {
let root = root();
fs::write(
root.join("main.mq.md"),
r#"# main
r#"---
markup: occlusion
---
## save
> fs.write_text path=out.txt text=ok
*1*
## wrap
> save
*None*
## mystery
> weird_plugin_thing x=1
*None*
# main
> wrap
> print text=ok
"#,
)
.unwrap();
+75 -10
View File
@@ -15,6 +15,8 @@ pub struct LockReport {
pub missing: Vec<String>,
pub changed: Vec<String>,
pub removed: Vec<String>,
/// Per-artifact which digest class drifted (G08).
pub classes: Vec<Value>,
}
impl LockReport {
@@ -29,6 +31,7 @@ impl LockReport {
"missing": self.missing,
"changed": self.changed,
"removed": self.removed,
"classes": self.classes,
})
}
}
@@ -63,21 +66,47 @@ pub fn check_links_lock(out_dir: &Path, project: &SemanticProject) -> Result<Loc
..LockReport::default()
});
}
let expected = artifact_lock_map(project);
let expected = artifact_lock_entries(project);
let actual = raw.get("artifacts").and_then(Value::as_object).cloned().unwrap_or_default();
let mut report = LockReport::default();
for (id, digest) in &expected {
for (id, entry) in &expected {
match actual.get(id).and_then(Value::as_object) {
None => report.missing.push(id.clone()),
Some(found) if found.get("artifact").and_then(Value::as_str) != Some(digest.as_str()) => report.changed.push(id.clone()),
_ => {}
Some(found) => {
let mut drifted = Vec::new();
for key in ["interface", "implementation", "evidence", "artifact"] {
let want = entry.get(key).and_then(Value::as_str);
let got = found.get(key).and_then(Value::as_str);
if want != got {
drifted.push(key.to_string());
}
}
if !drifted.is_empty() {
report.changed.push(id.clone());
report.classes.push(json!({
"artifact_id": id,
"changed": drifted,
}));
}
}
}
}
for id in actual.keys() {
if !expected.contains_key(id) { report.removed.push(id.clone()); }
if !expected.contains_key(id) {
report.removed.push(id.clone());
}
}
report.missing.sort(); report.changed.sort(); report.removed.sort();
report.status = if report.missing.is_empty() && report.changed.is_empty() && report.removed.is_empty() { "clean".into() } else { "outdated".into() };
report.missing.sort();
report.changed.sort();
report.removed.sort();
report.status = if report.missing.is_empty()
&& report.changed.is_empty()
&& report.removed.is_empty()
{
"clean".into()
} else {
"outdated".into()
};
Ok(report)
}
@@ -98,7 +127,29 @@ pub fn impact(project: &SemanticProject, query: &str) -> Value {
let mut reverse: BTreeMap<String, Vec<String>> = BTreeMap::new();
for artifact in &project.artifacts {
for dependency in &artifact.dependencies {
reverse.entry(dependency.0.clone()).or_default().push(artifact.artifact_id.0.clone());
reverse
.entry(dependency.0.clone())
.or_default()
.push(artifact.artifact_id.0.clone());
}
}
// NarrativeRef edges: step → symbol; impact includes the step's owning artifact.
for step in &project.steps {
if step.kind != "narrate" {
continue;
}
let owner = step
.id
.0
.split("#step-")
.next()
.unwrap_or(step.id.0.as_str())
.to_string();
for target in &step.calls {
reverse
.entry(target.as_str().to_string())
.or_default()
.push(owner.clone());
}
}
let mut queue: VecDeque<String> = seeds.iter().cloned().collect();
@@ -119,8 +170,22 @@ pub fn impact(project: &SemanticProject, query: &str) -> Value {
json!({"schema_version":SCHEMA_VERSION,"query":query,"resolved":!seeds.is_empty(),"seeds":seeds,"affected":entries})
}
fn artifact_lock_map(project: &SemanticProject) -> BTreeMap<String, String> {
project.artifacts.iter().map(|artifact| (artifact.artifact_id.0.clone(), artifact.hashes.artifact.0.clone())).collect()
fn artifact_lock_entries(project: &SemanticProject) -> BTreeMap<String, Value> {
project
.artifacts
.iter()
.map(|artifact| {
(
artifact.artifact_id.0.clone(),
json!({
"interface": artifact.hashes.interface.0,
"implementation": artifact.hashes.implementation.0,
"evidence": artifact.hashes.evidence.0,
"artifact": artifact.hashes.artifact.0,
}),
)
})
.collect()
}
fn lock_json(project: &SemanticProject) -> Value {
+4 -2
View File
@@ -7,14 +7,16 @@
pub mod bind;
pub mod ir;
pub mod lock;
pub mod provenance;
pub mod symbols;
pub use bind::{
call_display, is_static_bound, lookup_local, resolve_for_exec, DynamicReason, ExecTarget,
};
pub use ir::{
artifact_json, compile_project, write_semantic_projections, ArtifactId, BoundCall, CompileOptions,
Compilation, Digest, DynamicCall, EffectSet, LockMode, SemanticArtifact, SemanticProject,
artifact_json, compile_project, semantic_generation_dir, write_semantic_projections, ArtifactId,
BoundCall, CompileOptions, Compilation, Digest, DynamicCall, EffectSet, LockMode,
SemanticArtifact, SemanticProject,
};
pub use lock::{check_links_lock, impact as semantic_impact, update_links_lock, LockReport};
pub use symbols::{CallableKind, ModuleId, ProjectIndex, SymbolDecl, SymbolId, SymbolKind};
+251
View File
@@ -0,0 +1,251 @@
//! Optional source / applicability facts from module frontmatter (G05).
//!
//! Authors declare `sources:` and optional `applicability:` / `valid_until` in
//! frontmatter. Absence means a pure tool may still run but must stay
//! `evidence=unverified` — never invent a business SourceRef.
use std::fs;
use std::path::{Path, PathBuf};
use sha2::{Digest as _, Sha256};
use super::ir::{Digest, SourceRef};
#[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>,
}
/// Scan YAML-ish frontmatter for sources / applicability (no full YAML parser).
pub fn parse_module_provenance(source: &str) -> ModuleProvenance {
let mut lines = source.lines();
if lines.next().map(|l| l.trim_end()) != Some("---") {
return ModuleProvenance::default();
}
let mut out = ModuleProvenance::default();
let mut in_sources = false;
let mut in_applicability = false;
for line in lines {
let t = line.trim_end();
if t.trim() == "---" {
break;
}
let trimmed = t.trim();
if trimmed.is_empty() {
continue;
}
if !line.starts_with(' ') && !line.starts_with('\t') {
in_sources = false;
in_applicability = false;
}
if trimmed == "sources:" || trimmed.starts_with("sources:") {
in_sources = true;
in_applicability = false;
if let Some(rest) = trimmed.strip_prefix("sources:") {
let rest = rest.trim();
if !rest.is_empty() && rest != "|" {
// inline list not used; ignore
}
}
continue;
}
if trimmed == "applicability:" || trimmed.starts_with("applicability:") {
in_applicability = true;
in_sources = false;
continue;
}
if in_sources {
if let Some(item) = trimmed.strip_prefix("- ") {
let path = item.trim().trim_matches('"').to_string();
if !path.is_empty() {
out.sources.push(path);
}
}
continue;
}
if in_applicability {
if let Some(rest) = trimmed.strip_prefix("valid_until:") {
out.valid_until = Some(rest.trim().trim_matches('"').to_string());
} else if let Some(rest) = trimmed.strip_prefix("region:") {
out.region = Some(rest.trim().trim_matches('"').to_string());
}
}
}
out
}
#[derive(Debug, Clone)]
pub enum ProvenanceDiag {
Missing { path: String },
Expired { valid_until: String },
}
impl ProvenanceDiag {
pub fn code(&self) -> &'static str {
match self {
Self::Missing { .. } => "source.missing",
Self::Expired { .. } => "source.expired",
}
}
pub fn message(&self) -> String {
match self {
Self::Missing { path } => format!("来源文件缺失:`{path}`"),
Self::Expired { valid_until } => {
format!("来源适用期已过(valid_until={valid_until})")
}
}
}
}
pub struct ProvenanceResolution {
pub refs: Vec<SourceRef>,
pub applicability: String,
pub evidence_status: String,
pub diagnostics: Vec<ProvenanceDiag>,
}
/// Resolve corpus paths relative to the module file; never mark verified here.
pub fn resolve_provenance(
module_path: &Path,
prov: &ModuleProvenance,
) -> ProvenanceResolution {
let mut refs = Vec::new();
let mut diagnostics = Vec::new();
let base = module_path
.parent()
.map(|p| p.to_path_buf())
.unwrap_or_else(|| PathBuf::from("."));
for raw in &prov.sources {
let (path_part, locator) = match raw.split_once('#') {
Some((p, a)) => (p.trim(), Some(a.trim().to_string())),
None => (raw.as_str(), None),
};
let resolved = base.join(path_part);
if !resolved.is_file() {
diagnostics.push(ProvenanceDiag::Missing {
path: raw.clone(),
});
refs.push(SourceRef {
uri: path_part.to_string(),
locator,
content_digest: None,
relation: "supports".into(),
});
continue;
}
let content = fs::read(&resolved).unwrap_or_default();
let mut hash = Sha256::new();
hash.update(&content);
refs.push(SourceRef {
uri: path_part.to_string(),
locator,
content_digest: Some(Digest(format!("sha256:{:x}", hash.finalize()))),
relation: "supports".into(),
});
}
if let Some(until) = &prov.valid_until {
if is_expired(until) {
diagnostics.push(ProvenanceDiag::Expired {
valid_until: until.clone(),
});
}
}
let applicability = match (&prov.region, &prov.valid_until) {
(None, None) if prov.sources.is_empty() => {
"no explicit applicability constraints".into()
}
(region, until) => {
let mut parts = Vec::new();
if let Some(r) = region {
parts.push(format!("region={r}"));
}
if let Some(u) = until {
parts.push(format!("valid_until={u}"));
}
if parts.is_empty() {
"sources declared".into()
} else {
parts.join("; ")
}
}
};
let evidence_status = if diagnostics.iter().any(|d| matches!(d, ProvenanceDiag::Missing { .. }))
{
"missing_source".into()
} else if diagnostics
.iter()
.any(|d| matches!(d, ProvenanceDiag::Expired { .. }))
{
"expired".into()
} else if prov.sources.is_empty() {
"unverified".into()
} else {
// Corpus present and in date — still not domain-verified by compile alone.
"sourced".into()
};
ProvenanceResolution {
refs,
applicability,
evidence_status,
diagnostics,
}
}
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()
}
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}")
}
/// Algorithm from Howard Hinnant (public domain).
fn civil_from_days(z: i64) -> (i32, u32, u32) {
let z = z + 719_468;
let era = if z >= 0 { z } else { z - 146_096 }.div_euclid(146_097);
let doe = (z - era * 146_097) as u64;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
let y = (yoe as i64 + era * 400) as i32;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = if m <= 2 { y + 1 } else { y };
(y, m as u32, d as u32)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_sources_and_valid_until() {
let src = "---\nsources:\n - ../corpus/tax.md#rate\napplicability:\n region: CN\n valid_until: 2099-12-31\n---\n\n# main\n";
let p = parse_module_provenance(src);
assert_eq!(p.sources, vec!["../corpus/tax.md#rate"]);
assert_eq!(p.region.as_deref(), Some("CN"));
assert_eq!(p.valid_until.as_deref(), Some("2099-12-31"));
}
}