This commit is contained in:
eddiesoehnel committed 2026-08-19 17:39:51 -06:00
1 parent b177acda37
commit c04ca92c13
1021 files changed
+33110 -4026

No files matched your search

+106 -12
View File
@@ -18,7 +18,8 @@ from typing import Any, Iterable
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
PIPELINE_VERSION = "1.0.0"
PIPELINE_VERSION = "1.1.0"
PUBLIC_SCHEMA_VERSION = "1.1"
BASE_DIR = Path(__file__).resolve().parent.parent
REPOSITORY_ROOT = BASE_DIR.parents[1]
DEFAULT_CONFIG = BASE_DIR / "config" / "local.json"
@@ -31,6 +32,10 @@ TRACKING_KEYS = {
EMAIL_RE = re.compile(r"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}", re.I)
WINDOWS_USER_PATH_RE = re.compile(r"[A-Za-z]:\\Users\\[^\s\"'<>]+", re.I)
URL_RE = re.compile(r"https?://[^\s<>\"']+", re.I)
CAPTURE_TYPES = {
"legacy", "signal", "observation", "idea", "question", "draft",
"correspondence", "other", "unknown",
}
class TextExtractor(HTMLParser):
@@ -88,6 +93,23 @@ def normalize_list(value: Any) -> list[str]:
return result
def normalize_capture_type(source: dict[str, Any], warnings: list[str]) -> str:
if "CaptureType" not in source:
return "legacy"
raw = str(source.get("CaptureType") or "").strip().lower()
if not raw:
return "unknown"
normalized = re.sub(r"[^a-z0-9]+", "-", raw).strip("-")
if normalized not in CAPTURE_TYPES:
warnings.append(f"Unsupported CaptureType normalized to other: {raw}")
return "other"
return normalized
def has_publication_restrictions(value: Any) -> bool:
return bool(normalize_list(value))
def parse_record_date(value: Any) -> str | None:
if value is None or not str(value).strip():
return None
@@ -226,22 +248,42 @@ def build_record(
title, title_links, _ = extract_text_and_links(source.get("Title"))
summary, summary_links, _ = extract_text_and_links(source.get("Summary"))
notes_text, notes_links, notes_type = extract_text_and_links(source.get("Notes"))
context_text, context_links, context_type = extract_text_and_links(source.get("CaptureContext"))
warnings: list[str] = []
capture_schema_version = str(source.get("TemplateVersion") or "legacy").strip()
capture_type = normalize_capture_type(source, warnings)
intended_use = normalize_list(source.get("IntendedUse"))
date_original = str(source.get("Date")).strip() if source.get("Date") else None
normalized_date = parse_record_date(source.get("Date"))
if date_original and not normalized_date:
warnings.append("Unrecognized source date format")
links: list[dict[str, Any]] = []
for field, values in (("Summary", summary_links), ("Notes", notes_links), ("Title", title_links)):
raw_source_url = str(source.get("SourceURL") or "").strip()
explicit_source_url = sanitize_url(raw_source_url) if raw_source_url else None
if raw_source_url and not explicit_source_url:
warnings.append("Invalid SourceURL")
if explicit_source_url:
links.append({
"url": explicit_source_url,
"title": None,
"kind": "source",
"source_field": "SourceURL",
})
for field, values in (
("Summary", summary_links),
("Notes", notes_links),
("Title", title_links),
("CaptureContext", context_links),
):
for url in values:
if any(item["url"] == url for item in links):
continue
links.append({
"url": url,
"title": None,
"kind": "source" if field in {"Summary", "Title"} and not links else "related",
"source_field": "Summary" if field == "Title" else field,
"kind": "source" if field in {"Summary", "Title"} and not any(item["kind"] == "source" for item in links) else "related",
"source_field": field,
})
media: list[dict[str, Any]] = []
@@ -290,23 +332,24 @@ def build_record(
fingerprint = sha256_bytes("\n".join(fingerprint_parts).encode("utf-8"))
if (
previous
and previous.get("schema_version") == "1.0"
and previous.get("schema_version") == PUBLIC_SCHEMA_VERSION
and previous.get("provenance", {}).get("input_fingerprint") == fingerprint
and previous.get("provenance", {}).get("pipeline_version") == PIPELINE_VERSION
):
return previous, expected_files
reasoning = previous.get("reasoning", empty_reasoning()) if previous else empty_reasoning()
if previous and reasoning.get("status") == "complete":
source_changed = bool(previous) and previous.get("provenance", {}).get("input_fingerprint") != fingerprint
if previous and reasoning.get("status") == "complete" and source_changed:
reasoning = dict(reasoning)
reasoning["status"] = "stale"
warnings.append("Source or connected media changed after enrichment")
elif reasoning.get("status") not in {"complete", "stale"}:
reasoning = empty_reasoning()
canonical_url = next((item["url"] for item in links if item["kind"] == "source"), None)
canonical_url = explicit_source_url or next((item["url"] for item in links if item["kind"] == "source"), None)
result = {
"schema_version": "1.0",
"schema_version": PUBLIC_SCHEMA_VERSION,
"id": signal_id,
"source_record": {
"source_file_id": source_file_id,
@@ -315,6 +358,14 @@ def build_record(
"date_original": date_original,
"title": title,
"summary": summary,
"capture_schema_version": capture_schema_version,
"capture_type": capture_type,
"capture_context": {
"present": bool(context_text), "content_type": context_type,
"text": context_text, "used_for_reasoning": bool(context_text),
},
"intended_use": intended_use,
"publication_restriction_present": False,
"notes": {
"present": bool(notes_text), "content_type": notes_type,
"text": notes_text, "used_for_reasoning": bool(notes_text),
@@ -358,13 +409,15 @@ def basic_validate(record: dict[str, Any], base: Path) -> list[str]:
if missing:
errors.append("missing top-level fields: " + ", ".join(sorted(missing)))
return errors
if record["schema_version"] != "1.0" or not re.fullmatch(r"fm-signal-[a-z0-9-]+", str(record["id"])):
if record["schema_version"] != PUBLIC_SCHEMA_VERSION or not re.fullmatch(r"fm-signal-[a-z0-9-]+", str(record["id"])):
errors.append("invalid schema version or signal ID")
source_record = record.get("source_record", {})
if not source_record.get("source_file_id") or "Future Map" not in source_record.get("hub_tags", []):
errors.append("missing source file ID or exact Future Map tag")
if source_record.get("contact_reference_count", 0) < 0:
errors.append("invalid contact reference count")
if source_record.get("publication_restriction_present") is not False:
errors.append("restricted source must not appear in public output")
public_text = json.dumps(record, ensure_ascii=False)
if EMAIL_RE.search(public_text):
errors.append("email address remains in public record")
@@ -450,14 +503,21 @@ def render_outputs(base: Path) -> dict[str, int]:
counts[state] = counts.get(state, 0) + 1
title = source.get("title") or f"Future Map Signal {source['source_file_id']}"
summary = source.get("summary")
capture_context = source.get("capture_context", {}).get("text")
intended_use = source.get("intended_use", [])
md.extend([
f"## {title}", "",
f"**Signal ID:** `{record['id']}`", "",
f"**Date:** {source.get('date') or source.get('date_original') or 'Unknown'}", "",
f"**Capture type:** {source.get('capture_type', 'legacy')}", "",
f"**Reasoning:** {state}", "",
])
if summary:
md.extend([markdown_clean(summary), ""])
if capture_context:
md.extend(["### Capture context", "", markdown_clean(capture_context), ""])
if intended_use:
md.extend([f"**Intended use:** {', '.join(markdown_clean(item) for item in intended_use)}", ""])
if reasoning.get("analysis"):
md.extend(["### Future Map analysis", "", markdown_clean(reasoning["analysis"]), ""])
if reasoning.get("implications"):
@@ -510,7 +570,8 @@ def render_outputs(base: Path) -> dict[str, int]:
index_lines.append(json.dumps({
"id": record["id"], "source_file_id": source["source_file_id"], "hub_id": source.get("hub_id"), "date": source.get("date"),
"title": title, "summary": summary, "reasoning_status": state,
"title": title, "summary": summary, "capture_type": source.get("capture_type", "legacy"),
"capture_context": capture_context, "intended_use": intended_use, "reasoning_status": state,
"signal_types": reasoning.get("classification", {}).get("signal_types", []),
"topics": reasoning.get("classification", {}).get("topics", []),
"related_documents": [item.get("document_id") for item in reasoning.get("related_documents", [])],
@@ -594,8 +655,14 @@ def command_sync(args: argparse.Namespace) -> int:
expected_records: set[str] = set()
expected_files: set[str] = set()
matched = changed = skipped = 0
quarantined_media_candidates: set[str] = set()
quarantine_lines: list[str] = []
matched = changed = skipped = quarantined = ignored_templates = 0
removed_records = removed_files = 0
for source_path in iter_json_files(source_hrecords):
if source_path.stem.lower().startswith("hub_template"):
ignored_templates += 1
continue
source = load_json(source_path)
if not source:
skipped += 1
@@ -604,6 +671,22 @@ def command_sync(args: argparse.Namespace) -> int:
continue
matched += 1
target = output_hrecords / source_path.name
if has_publication_restrictions(source.get("PublicationRestrictions")):
quarantined += 1
previous = load_json(target) if target.exists() else None
for media in (previous or {}).get("media", []):
public_path = media.get("public_path")
if public_path:
quarantined_media_candidates.add(Path(public_path).name)
if target.exists():
target.unlink()
removed_records += 1
quarantine_lines.append(json.dumps({
"source_file_id": source_path.stem,
"hub_id": str(source.get("HubID") or "").strip() or None,
"reason": "publication-restriction-present",
}, ensure_ascii=False))
continue
expected_records.add(target.name)
previous = load_json(target) if target.exists() else None
record, record_files = build_record(source_path, source, source_files, output_files, previous)
@@ -611,7 +694,6 @@ def command_sync(args: argparse.Namespace) -> int:
if write_json_if_changed(target, record):
changed += 1
removed_records = removed_files = 0
if not args.no_prune:
for path in output_hrecords.glob("*.json"):
if path.name not in expected_records:
@@ -621,12 +703,24 @@ def command_sync(args: argparse.Namespace) -> int:
if path.is_file() and path.name not in expected_files:
path.unlink()
removed_files += 1
for name in quarantined_media_candidates - expected_files:
path = output_files / name
if path.exists() and path.is_file():
path.unlink()
removed_files += 1
write_text_if_changed(
base / "runtime" / "quarantine.jsonl",
"\n".join(quarantine_lines) + ("\n" if quarantine_lines else ""),
)
counts = render_outputs(base)
errors, warnings = validate_output(base)
print("DONE")
print(f"Required tag: {required_tag}")
print(f"Matched records: {matched}")
print(f"Ignored template/reference files: {ignored_templates}")
print(f"Quarantined by publication restriction: {quarantined}")
print(f"Changed derivative records: {changed}")
print(f"Skipped unreadable records: {skipped}")
print(f"Removed stale records: {removed_records}")