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:
1 parent
0e1bfb3359
commit
dcd3d329d4
18 files changed
+1314
-77
No files matched your search
+154
-1
@@ -64,13 +64,14 @@ fn dispatch(req: &Value) -> Result<Value, Value> {
|
||||
Some("artifact.impact") => artifact_impact(¶ms),
|
||||
Some("artifact.bind") => artifact_bind(¶ms),
|
||||
Some("artifact.execute") => artifact_execute(¶ms),
|
||||
Some("artifact.patch") => artifact_patch(¶ms),
|
||||
// `<TAB>` M9: occlusion label search (two-tier vocabulary).
|
||||
Some("labels.search") => labels_search(¶ms),
|
||||
// `<TAB>` M6: one-shot session summary (T1 staleness seen/fixed).
|
||||
Some("session.summary") => session_summary(),
|
||||
other => Err(err(
|
||||
"mlsp.unknown_method",
|
||||
format!("未知方法 {other:?};可用:locate / syntax / validate / repair_targets / repair_apply / schema / artifact.find / artifact.inspect / link.resolve / artifact.verify / artifact.impact / artifact.bind / artifact.execute"),
|
||||
format!("未知方法 {other:?};可用:locate / syntax / validate / repair_targets / repair_apply / schema / artifact.find / artifact.inspect / link.resolve / artifact.verify / artifact.impact / artifact.bind / artifact.execute / artifact.patch"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
@@ -186,6 +187,19 @@ fn artifact_bind(params: &Value) -> Result<Value, Value> {
|
||||
"effects": effects,
|
||||
}));
|
||||
}
|
||||
if policy == "business"
|
||||
&& !matches!(
|
||||
artifact.verification.evidence.as_str(),
|
||||
"sourced" | "verified"
|
||||
)
|
||||
{
|
||||
return Err(json!({
|
||||
"code": "artifact.evidence_denied",
|
||||
"message": "business 策略要求来源已关联;当前证据状态不足",
|
||||
"policy": policy,
|
||||
"evidence": artifact.verification.evidence,
|
||||
}));
|
||||
}
|
||||
let symbol_id = artifact
|
||||
.symbol_id
|
||||
.as_ref()
|
||||
@@ -198,10 +212,149 @@ fn artifact_bind(params: &Value) -> Result<Value, Value> {
|
||||
"project": compilation.semantics.root,
|
||||
"policy": policy,
|
||||
"effects": effects,
|
||||
"evidence": artifact.verification.evidence,
|
||||
"source": {"file": artifact.source.file, "line": artifact.source.line},
|
||||
}}))
|
||||
}
|
||||
|
||||
/// Digest-guarded local patch (S3/G09). `intent: wording` refuses signature/effect drift.
|
||||
fn artifact_patch(params: &Value) -> Result<Value, Value> {
|
||||
let compilation = semantic_project(params)?;
|
||||
let query = params
|
||||
.get("artifact_id")
|
||||
.or_else(|| params.get("symbol_id"))
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| err("mlsp.bad_request", "artifact.patch 需要 artifact_id 或 symbol_id"))?;
|
||||
let candidates = artifact_query(&compilation.semantics, query);
|
||||
if candidates.len() != 1 {
|
||||
return Err(err(
|
||||
if candidates.is_empty() {
|
||||
"artifact.unresolved"
|
||||
} else {
|
||||
"artifact.ambiguous"
|
||||
},
|
||||
format!("无法唯一修补 `{query}`"),
|
||||
));
|
||||
}
|
||||
let before = candidates[0];
|
||||
let expected = params
|
||||
.get("expected_digest")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| {
|
||||
err(
|
||||
"mlsp.bad_request",
|
||||
"artifact.patch 需要 expected_digest(hashes.implementation)",
|
||||
)
|
||||
})?;
|
||||
if expected != before.hashes.implementation.0 {
|
||||
return Err(json!({
|
||||
"code": "artifact.digest_mismatch",
|
||||
"message": "源码实现摘要已变化,拒绝覆盖",
|
||||
"expected": expected,
|
||||
"actual": before.hashes.implementation.0,
|
||||
}));
|
||||
}
|
||||
let path = compilation.semantics.root.join(&before.source.file);
|
||||
let original = std::fs::read_to_string(&path)
|
||||
.map_err(|e| err("artifact.load", format!("读源失败: {e}")))?;
|
||||
let edits_v = params
|
||||
.get("edits")
|
||||
.and_then(Value::as_array)
|
||||
.ok_or_else(|| err("mlsp.bad_request", "artifact.patch 需要 edits"))?;
|
||||
let mut edits = Vec::new();
|
||||
for e in edits_v {
|
||||
let line = e
|
||||
.get("line")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or_else(|| err("mlsp.bad_request", "edit.line 必填"))? as u32;
|
||||
let kind = e.get("op").and_then(Value::as_str).unwrap_or("replace");
|
||||
match kind {
|
||||
"replace" => {
|
||||
let text = e
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.ok_or_else(|| err("mlsp.bad_request", "replace 需要 text"))?
|
||||
.to_string();
|
||||
edits.push(crate::repair::Edit::Replace { line, text });
|
||||
}
|
||||
"delete" => edits.push(crate::repair::Edit::Delete { line }),
|
||||
"insert_before" => {
|
||||
let text = e
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
edits.push(crate::repair::Edit::InsertBefore { line, text });
|
||||
}
|
||||
other => {
|
||||
return Err(err(
|
||||
"mlsp.bad_request",
|
||||
format!("未知 edit.op `{other}`"),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
let start = before.source.line;
|
||||
let end = before.source.end_line.max(start);
|
||||
let ranges = [(start, end.max(start + 40))];
|
||||
let patched = crate::repair::apply_edits(&original, &ranges, &edits).map_err(|o| {
|
||||
json!({
|
||||
"code": "mlsp.repair_out_of_scope",
|
||||
"message": "补丁超出制品源码范围",
|
||||
"lines": o.lines,
|
||||
"ranges": o.ranges,
|
||||
})
|
||||
})?;
|
||||
std::fs::write(&path, &patched)
|
||||
.map_err(|e| err("artifact.write", format!("写源失败: {e}")))?;
|
||||
let after_comp = semantic_project(params)?;
|
||||
let after_cands = artifact_query(&after_comp.semantics, query);
|
||||
if after_cands.len() != 1 {
|
||||
// roll back
|
||||
let _ = std::fs::write(&path, &original);
|
||||
return Err(err(
|
||||
"artifact.patch_ambiguous",
|
||||
"补丁后制品无法唯一解析;已回滚",
|
||||
));
|
||||
}
|
||||
let after = after_cands[0];
|
||||
let signature_changed = before.hashes.interface.0 != after.hashes.interface.0;
|
||||
let effects_changed = before.effects.values() != after.effects.values();
|
||||
let implementation_changed =
|
||||
before.hashes.implementation.0 != after.hashes.implementation.0;
|
||||
let intent = params.get("intent").and_then(Value::as_str).unwrap_or("edit");
|
||||
if intent == "wording" && (signature_changed || effects_changed) {
|
||||
let _ = std::fs::write(&path, &original);
|
||||
return Err(json!({
|
||||
"code": "artifact.wording_broke_contract",
|
||||
"message": "intent=wording 但签名或效应已变;已回滚",
|
||||
"signature_changed": signature_changed,
|
||||
"effects_changed": effects_changed,
|
||||
}));
|
||||
}
|
||||
Ok(json!({
|
||||
"schema_version": 1,
|
||||
"artifact_id": after.artifact_id.0,
|
||||
"symbol_id": after.symbol_id.as_ref().map(|id| id.as_str()),
|
||||
"applied": true,
|
||||
"diff": {
|
||||
"signature_changed": signature_changed,
|
||||
"effects_changed": effects_changed,
|
||||
"implementation_changed": implementation_changed,
|
||||
"before": {
|
||||
"interface": before.hashes.interface.0,
|
||||
"implementation": before.hashes.implementation.0,
|
||||
"effects": before.effects.values(),
|
||||
},
|
||||
"after": {
|
||||
"interface": after.hashes.interface.0,
|
||||
"implementation": after.hashes.implementation.0,
|
||||
"effects": after.effects.values(),
|
||||
},
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
fn artifact_execute(params: &Value) -> Result<Value, Value> {
|
||||
let handle = params.get("handle").ok_or_else(|| err("mlsp.bad_request", "artifact.execute 需要 artifact.bind 返回的 handle"))?;
|
||||
let artifact_id = handle.get("artifact_id").and_then(Value::as_str).ok_or_else(|| err("mlsp.bad_handle", "handle 缺少 artifact_id"))?;
|
||||
|
||||
+4
-1
@@ -7,7 +7,10 @@ pub use expr::{
|
||||
parse_call_after_gt, parse_call_arg_value, parse_expr, parse_expr_prefer_var,
|
||||
parse_value_or_interp,
|
||||
};
|
||||
pub use prose::{scan_prose_line, ProseBit};
|
||||
pub use prose::{
|
||||
classify_narrative_target, scan_md_links_in_line, scan_narrative_links, scan_prose_line,
|
||||
NarrativeLink, NarrativeLinkKind, ProseBit,
|
||||
};
|
||||
|
||||
use anyhow::{bail, Result};
|
||||
|
||||
|
||||
+186
-1
@@ -2,8 +2,11 @@
|
||||
//!
|
||||
//! Soft Markdown emphasis that does not look like code/return is skipped (G2 —
|
||||
//! [code-as-docs-gaps.md](../../../doc/design/code-as-docs-gaps.md)).
|
||||
//!
|
||||
//! Comment-line Markdown links `[label](target)` are NarrativeRef / navigation
|
||||
//! sites (G03); they are never executed.
|
||||
|
||||
use crate::lex::{matching_bold_close_inline, matching_italic_close_inline};
|
||||
use crate::lex::{matching_bold_close_inline, matching_italic_close_inline, LineKind};
|
||||
|
||||
pub use crate::lex::looks_like_bold_code;
|
||||
|
||||
@@ -22,6 +25,162 @@ pub enum ProseBit {
|
||||
ItalicReturn { inner: String, at: usize },
|
||||
}
|
||||
|
||||
/// Why a comment-line `[]()` is not an executable BoundCall (G03).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum NarrativeLinkKind {
|
||||
/// In-project symbol / binding / `#anchor` — inert explanation.
|
||||
Narrate,
|
||||
/// URL or file path — navigation only; never fetched by compile/run.
|
||||
Navigation,
|
||||
}
|
||||
|
||||
impl NarrativeLinkKind {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Narrate => "narrate",
|
||||
Self::Navigation => "navigation",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One Markdown link found on a comment (narrative) line.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct NarrativeLink {
|
||||
pub label: String,
|
||||
pub target: String,
|
||||
pub kind: NarrativeLinkKind,
|
||||
/// 1-based source line.
|
||||
pub line: u32,
|
||||
pub at: usize,
|
||||
}
|
||||
|
||||
/// Classify a link target without parsing it as an expression.
|
||||
pub fn classify_narrative_target(target: &str) -> NarrativeLinkKind {
|
||||
let t = target.trim();
|
||||
if t.starts_with("http://")
|
||||
|| t.starts_with("https://")
|
||||
|| t.starts_with("mailto:")
|
||||
|| t.starts_with("//")
|
||||
{
|
||||
return NarrativeLinkKind::Navigation;
|
||||
}
|
||||
if t.contains('/') || t.ends_with(".md") || t.ends_with(".mq.md") || t.ends_with(".html")
|
||||
{
|
||||
return NarrativeLinkKind::Navigation;
|
||||
}
|
||||
NarrativeLinkKind::Narrate
|
||||
}
|
||||
|
||||
/// Scan whole-source comment lines for Markdown links; skip fences and code lines.
|
||||
pub fn scan_narrative_links(source: &str) -> Vec<NarrativeLink> {
|
||||
let classified = crate::lex::classify_source(source);
|
||||
let mut out = Vec::new();
|
||||
let mut in_fence = false;
|
||||
for (i, cl) in classified.iter().enumerate() {
|
||||
let line_no = (i + 1) as u32;
|
||||
let trimmed = cl.text.trim();
|
||||
if trimmed.starts_with("```") {
|
||||
in_fence = !in_fence;
|
||||
continue;
|
||||
}
|
||||
if in_fence {
|
||||
continue;
|
||||
}
|
||||
if cl.kind != LineKind::Comment {
|
||||
continue;
|
||||
}
|
||||
out.extend(scan_md_links_in_line(&cl.text, line_no));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Scan one line for `[label](target)`, skipping `` `inline` `` spans.
|
||||
pub fn scan_md_links_in_line(line: &str, line_no: u32) -> Vec<NarrativeLink> {
|
||||
let bytes = line.as_bytes();
|
||||
let mut i = 0usize;
|
||||
let mut out = Vec::new();
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'`' {
|
||||
if let Some(rel) = line[i + 1..].find('`') {
|
||||
i = i + 1 + rel + 1;
|
||||
continue;
|
||||
}
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if bytes[i] != b'[' {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let Some((label, target, next)) = parse_md_link(line, i) else {
|
||||
i += 1;
|
||||
continue;
|
||||
};
|
||||
let kind = classify_narrative_target(&target);
|
||||
out.push(NarrativeLink {
|
||||
label,
|
||||
target,
|
||||
kind,
|
||||
line: line_no,
|
||||
at: i,
|
||||
});
|
||||
i = next;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn parse_md_link(line: &str, start: usize) -> Option<(String, String, usize)> {
|
||||
if !line[start..].starts_with('[') {
|
||||
return None;
|
||||
}
|
||||
let mut depth = 0i32;
|
||||
let mut label_end = None;
|
||||
for (rel, ch) in line[start..].char_indices() {
|
||||
match ch {
|
||||
'[' => depth += 1,
|
||||
']' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
label_end = Some(start + rel);
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let label_end = label_end?;
|
||||
let after = line.get(label_end + 1..)?;
|
||||
if !after.starts_with('(') {
|
||||
return None;
|
||||
}
|
||||
let mut depth = 0i32;
|
||||
let mut target_end = None;
|
||||
for (rel, ch) in after.char_indices() {
|
||||
match ch {
|
||||
'(' => depth += 1,
|
||||
')' => {
|
||||
depth -= 1;
|
||||
if depth == 0 {
|
||||
target_end = Some(rel);
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let target_end = target_end?;
|
||||
let label = line[start + 1..label_end].to_string();
|
||||
let target = after[1..target_end].trim().to_string();
|
||||
if label.is_empty() || target.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// Executable occlusion payloads look like calls (`foo(…)` / `a.b(…)`); those
|
||||
// live on Code lines already. If a comment link target is expression-shaped
|
||||
// with `(`, still treat as narrate/navigation by target class — do not eval.
|
||||
let next = label_end + 1 + target_end + 1;
|
||||
Some((label, target, next))
|
||||
}
|
||||
|
||||
/// Scan a narrative (or mixed) line for v0.3 inline bits, left to right.
|
||||
pub fn scan_prose_line(line: &str) -> Vec<ProseBit> {
|
||||
let bytes = line.as_bytes();
|
||||
@@ -255,4 +414,30 @@ mod tests {
|
||||
"glob-like ticks must not yield italic: {bits:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrative_links_skip_fence_and_classify() {
|
||||
let src = "---\nmarkup: occlusion\n---\n\n# main\n\n见[文档](https://example.com/a)与[总额](总额)。\n\n```\n[ignored](https://x.test)\n```\n\n行内跳过 `[not](x)` 标记。\n";
|
||||
let links = scan_narrative_links(src);
|
||||
assert!(
|
||||
links.iter().any(|l| {
|
||||
l.kind == NarrativeLinkKind::Navigation && l.target.contains("example.com")
|
||||
}),
|
||||
"{links:?}"
|
||||
);
|
||||
assert!(
|
||||
links
|
||||
.iter()
|
||||
.any(|l| l.kind == NarrativeLinkKind::Narrate && l.target == "总额"),
|
||||
"{links:?}"
|
||||
);
|
||||
assert!(
|
||||
!links.iter().any(|l| l.target.contains("x.test")),
|
||||
"fenced link must not become a step: {links:?}"
|
||||
);
|
||||
assert!(
|
||||
!links.iter().any(|l| l.target == "x"),
|
||||
"inline-code link must not become a step: {links:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
+262
-51
@@ -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(¤t) {
|
||||
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(¤t_tmp, format!("{build_id}\n"))
|
||||
.with_context(|| format!("write {}", current_tmp.display()))?;
|
||||
fs::rename(¤t_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
@@ -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
@@ -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};
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user