Files
future-map-OPEN/data/insights-hub/scripts/future_map_pipeline.py
T
2026-08-12 16:41:20 -06:00

735 lines
32 KiB
Python

#!/usr/bin/env python3
"""Contained deterministic pipeline for Future Map Insights Hub records."""
from __future__ import annotations
import argparse
import hashlib
import html
from html.parser import HTMLParser
import json
import os
from pathlib import Path
import re
import shutil
import sys
from datetime import date, datetime, timezone
from typing import Any, Iterable
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
PIPELINE_VERSION = "1.0.0"
BASE_DIR = Path(__file__).resolve().parent.parent
REPOSITORY_ROOT = BASE_DIR.parents[1]
DEFAULT_CONFIG = BASE_DIR / "config" / "local.json"
SCHEMA_PATH = BASE_DIR / "schemas" / "future-map-signal.schema.json"
PATCH_SCHEMA_PATH = BASE_DIR / "schemas" / "reasoning-patch.schema.json"
TRACKING_KEYS = {
"token", "auth", "signature", "sig", "key", "j", "r", "redirect",
"fbclid", "gclid", "mc_cid", "mc_eid", "isfreemail",
}
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)
class TextExtractor(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: list[str] = []
self.hrefs: list[str] = []
self._skip_depth = 0
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
if tag in {"script", "style"}:
self._skip_depth += 1
if tag in {"p", "div", "br", "li", "tr", "h1", "h2", "h3", "h4"}:
self.parts.append("\n")
for key, value in attrs:
if key.lower() == "href" and value:
self.hrefs.append(value)
def handle_endtag(self, tag: str) -> None:
if tag in {"script", "style"} and self._skip_depth:
self._skip_depth -= 1
if tag in {"p", "div", "li", "tr", "h1", "h2", "h3", "h4"}:
self.parts.append("\n")
def handle_data(self, data: str) -> None:
if not self._skip_depth:
self.parts.append(data)
def utc_now() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
def sha256_bytes(data: bytes) -> str:
return "sha256:" + hashlib.sha256(data).hexdigest()
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return "sha256:" + digest.hexdigest()
def normalize_list(value: Any) -> list[str]:
if value is None:
return []
values = value if isinstance(value, list) else [value]
result: list[str] = []
for item in values:
text = str(item).strip()
if text and text not in result:
result.append(text)
return result
def parse_record_date(value: Any) -> str | None:
if value is None or not str(value).strip():
return None
text = str(value).strip()
for fmt in ("%m/%d/%Y", "%Y-%m-%d", "%Y/%m/%d", "%m-%d-%Y", "%B %d, %Y", "%b %d, %Y"):
try:
return datetime.strptime(text, fmt).date().isoformat()
except ValueError:
continue
return None
def sanitize_url(value: str) -> str | None:
candidate = html.unescape(value).strip().rstrip(".,);]")
try:
parts = urlsplit(candidate)
except ValueError:
return None
if parts.scheme not in {"http", "https"} or not parts.netloc:
return None
host = parts.netloc.lower()
if host.endswith("substack.com") and (parts.path.startswith("/redirect/") or parts.path.startswith("/app-link/")):
return None
kept: list[tuple[str, str]] = []
for key, val in parse_qsl(parts.query, keep_blank_values=False):
lowered = key.lower()
if lowered.startswith("utm_") or lowered in TRACKING_KEYS:
continue
kept.append((key, val))
return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(kept, doseq=True), ""))
def extract_text_and_links(value: Any) -> tuple[str | None, list[str], str]:
if value is None or not str(value).strip():
return None, [], "none"
raw = str(value)
looks_html = bool(re.search(r"</?[A-Za-z][^>]*>", raw))
parser = TextExtractor()
if looks_html:
try:
parser.feed(raw)
text = "".join(parser.parts)
except Exception:
text = re.sub(r"<[^>]+>", " ", raw)
else:
text = raw
urls = parser.hrefs + URL_RE.findall(raw)
cleaned_urls: list[str] = []
for url in urls:
cleaned = sanitize_url(url)
if cleaned and cleaned not in cleaned_urls:
cleaned_urls.append(cleaned)
def replace_url(match: re.Match[str]) -> str:
return sanitize_url(match.group(0)) or "[personalized link removed]"
text = URL_RE.sub(replace_url, html.unescape(text))
text = EMAIL_RE.sub("[email removed]", text)
text = WINDOWS_USER_PATH_RE.sub("[local path removed]", text)
text = text.replace("\r", "")
text = re.sub(r"[ \t]+", " ", text)
text = re.sub(r"\n[ \t]+", "\n", text)
text = re.sub(r"\n{3,}", "\n\n", text).strip()
email_markers = bool(re.search(r"forwarded this email|you received this (message|email)|unsubscribe", raw, re.I))
content_type = "email-html" if looks_html and email_markers else "html" if looks_html else "plain-text"
return text or None, cleaned_urls, content_type
def load_json(path: Path) -> dict[str, Any] | None:
try:
with path.open("r", encoding="utf-8-sig") as handle:
value = json.load(handle, strict=False)
return value if isinstance(value, dict) else None
except Exception as exc:
print(f"SKIP unreadable JSON: {path.name} | {exc}")
return None
def iter_json_files(folder: Path) -> Iterable[Path]:
yield from sorted(folder.glob("*.json"), key=lambda item: item.name.lower())
def media_type(path_or_url: str) -> str:
suffix = Path(urlsplit(path_or_url).path).suffix.lower()
if suffix in {".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg", ".avif"}:
return "image"
if suffix in {".pdf", ".doc", ".docx", ".ppt", ".pptx", ".odp", ".xls", ".xlsx"}:
return "document"
if suffix in {".mp3", ".wav", ".m4a", ".ogg"}:
return "audio"
if suffix in {".mp4", ".mov", ".webm", ".mkv"}:
return "video"
return "other"
def copy_if_changed(source: Path, target: Path, source_hash: str) -> None:
target.parent.mkdir(parents=True, exist_ok=True)
if target.exists() and sha256_file(target) == source_hash:
return
shutil.copy2(source, target)
def empty_reasoning() -> dict[str, Any]:
return {
"status": "pending",
"analysis": None,
"implications": [],
"claims": [],
"classification": {
"signal_types": [], "topics": [], "future_map_concepts": [],
"time_horizons": [], "geographies": [], "industries": [],
"audiences": [], "direction": "uncertain", "maturity": "uncertain",
},
"related_documents": [],
"related_signals": [],
"confidence": "unrated",
"novelty": "unrated",
"corpus_documents_consulted": [],
"generated_at": None,
"generated_by": None,
}
def build_record(
source_path: Path,
source: dict[str, Any],
source_files_dir: Path,
output_files_dir: Path,
previous: dict[str, Any] | None,
) -> tuple[dict[str, Any], set[str]]:
source_file_id = source_path.stem
hub_id = str(source.get("HubID")).strip() if source.get("HubID") else None
signal_id = "fm-signal-" + re.sub(r"[^a-z0-9-]+", "-", source_file_id.lower()).strip("-")
raw_bytes = source_path.read_bytes()
source_hash = sha256_bytes(raw_bytes)
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"))
warnings: list[str] = []
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)):
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,
})
media: list[dict[str, Any]] = []
expected_files: set[str] = set()
fingerprint_parts = [source_hash]
media_index = 0
for field in ("File", "Image"):
for reference in normalize_list(source.get(field)):
media_index += 1
item_id = f"fm-media-{source_file_id}-{media_index}"
if reference.startswith(("http://", "https://")):
cleaned = sanitize_url(reference)
if cleaned:
links.append({"url": cleaned, "title": None, "kind": "media", "source_field": field})
media.append({
"id": item_id, "media_type": media_type(reference), "source_field": field,
"source_reference": Path(urlsplit(reference).path).name or reference,
"public_path": None, "source_url": cleaned, "content_hash": None,
"copy_status": "remote", "rights_status": "unknown",
"publication_decision": "publish", "description": None, "extracted_text": None,
})
fingerprint_parts.append(cleaned or reference)
continue
source_asset = source_files_dir / reference
public_name = Path(reference).name
expected_files.add(public_name)
if source_asset.exists() and source_asset.is_file():
content_hash = sha256_file(source_asset)
copy_if_changed(source_asset, output_files_dir / public_name, content_hash)
status = "copied"
fingerprint_parts.append(content_hash)
else:
content_hash = None
status = "missing"
fingerprint_parts.append("missing:" + reference)
warnings.append(f"Missing connected {field}: {reference}")
media.append({
"id": item_id, "media_type": media_type(reference), "source_field": field,
"source_reference": public_name, "public_path": f"files/{public_name}",
"source_url": None, "content_hash": content_hash, "copy_status": status,
"rights_status": "unknown", "publication_decision": "publish",
"description": None, "extracted_text": None,
})
fingerprint = sha256_bytes("\n".join(fingerprint_parts).encode("utf-8"))
if (
previous
and previous.get("schema_version") == "1.0"
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":
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)
result = {
"schema_version": "1.0",
"id": signal_id,
"source_record": {
"source_file_id": source_file_id,
"hub_id": hub_id,
"date": normalized_date,
"date_original": date_original,
"title": title,
"summary": summary,
"notes": {
"present": bool(notes_text), "content_type": notes_type,
"text": notes_text, "used_for_reasoning": bool(notes_text),
},
"hub_tags": normalize_list(source.get("HubTags")),
"companies": normalize_list(source.get("Companies")),
"contact_reference_count": len(normalize_list(source.get("Contacts"))),
},
"source": {
"title": None, "publisher": None, "author": None,
"publication_date": normalized_date, "canonical_url": canonical_url,
"access": "unknown",
},
"links": links,
"media": media,
"rights": {
"ownership": "unknown", "rights_status": "unknown", "source_access": "unknown",
"publication_policy": "publish-with-attribution", "publication_decision": "publish",
"approved_by": "repository-owner", "attribution": None,
},
"reasoning": reasoning,
"review": {
"publication_status": "review-required" if reasoning["status"] != "complete" else "approved",
"content_review": "pending" if reasoning["status"] != "complete" else "automated",
"privacy_review": "automated-passed",
"rights_review": "owner-risk-accepted",
"warnings": warnings,
},
"provenance": {
"source_hash": source_hash, "input_fingerprint": fingerprint,
"pipeline_version": PIPELINE_VERSION, "prepared_at": utc_now(),
},
}
return result, expected_files
def basic_validate(record: dict[str, Any], base: Path) -> list[str]:
errors: list[str] = []
required = {"schema_version", "id", "source_record", "source", "links", "media", "rights", "reasoning", "review", "provenance"}
missing = required - set(record)
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"])):
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")
public_text = json.dumps(record, ensure_ascii=False)
if EMAIL_RE.search(public_text):
errors.append("email address remains in public record")
if WINDOWS_USER_PATH_RE.search(public_text):
errors.append("private Windows user path remains in public record")
for item in record.get("media", []):
if item.get("copy_status") == "copied":
public_path = item.get("public_path")
if not public_path or not (base / public_path).exists():
errors.append(f"missing copied media path: {public_path}")
reasoning = record.get("reasoning", {})
if reasoning.get("status") == "complete":
if not reasoning.get("analysis") or len(reasoning.get("analysis", "")) < 20:
errors.append("complete reasoning requires analysis")
if not reasoning.get("classification", {}).get("signal_types"):
errors.append("complete reasoning requires at least one signal type")
if not reasoning.get("classification", {}).get("topics"):
errors.append("complete reasoning requires at least one topic")
if not reasoning.get("corpus_documents_consulted"):
errors.append("complete reasoning requires consulted corpus documents")
return errors
def schema_validate(instance: dict[str, Any], schema_path: Path) -> list[str]:
try:
import jsonschema # type: ignore
except ImportError:
return []
schema = json.loads(schema_path.read_text(encoding="utf-8"))
validator = jsonschema.Draft202012Validator(schema)
return [f"{'/'.join(str(part) for part in error.path)}: {error.message}" for error in validator.iter_errors(instance)]
def write_json_if_changed(path: Path, value: Any) -> bool:
text = json.dumps(value, ensure_ascii=False, indent=2) + "\n"
if path.exists() and path.read_text(encoding="utf-8") == text:
return False
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return True
def write_text_if_changed(path: Path, text: str) -> bool:
if path.exists() and path.read_text(encoding="utf-8") == text:
return False
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return True
def markdown_clean(value: Any) -> str:
"""Remove line-end whitespace before placing source text in generated Markdown."""
return "\n".join(line.rstrip() for line in str(value).splitlines()).strip()
def records_from_output(base: Path) -> list[dict[str, Any]]:
result: list[dict[str, Any]] = []
for path in iter_json_files(base / "hrecords"):
value = load_json(path)
if value:
result.append(value)
return result
def render_outputs(base: Path) -> dict[str, int]:
records = records_from_output(base)
records.sort(key=lambda item: (item.get("source_record", {}).get("date") or "", item.get("id", "")), reverse=True)
content_index = load_json(base.parents[1] / "content-index.json") if len(base.parents) > 1 else None
document_paths = {
item.get("content_id"): item.get("path")
for item in (content_index or {}).get("items", [])
if item.get("content_id") and item.get("path")
}
counts = {state: 0 for state in ("pending", "complete", "stale", "failed", "excluded")}
media_names: set[str] = set()
pending_lines: list[str] = []
index_lines: list[str] = []
md: list[str] = ["# Future Map Insights Hub", "", f"Generated from {len(records)} public derivative records.", "", "---", ""]
for record in records:
source = record["source_record"]
reasoning = record["reasoning"]
state = reasoning.get("status", "pending")
counts[state] = counts.get(state, 0) + 1
title = source.get("title") or f"Future Map Signal {source['source_file_id']}"
summary = source.get("summary")
md.extend([
f"## {title}", "",
f"**Signal ID:** `{record['id']}`", "",
f"**Date:** {source.get('date') or source.get('date_original') or 'Unknown'}", "",
f"**Reasoning:** {state}", "",
])
if summary:
md.extend([markdown_clean(summary), ""])
if reasoning.get("analysis"):
md.extend(["### Future Map analysis", "", markdown_clean(reasoning["analysis"]), ""])
if reasoning.get("implications"):
md.extend(["### Implications", ""] + [f"- {markdown_clean(item)}" for item in reasoning["implications"]] + [""])
classification = reasoning.get("classification", {})
if reasoning.get("status") == "complete":
md.extend(["### Future Map classification", ""])
for label, key in (
("Signal types", "signal_types"),
("Topics", "topics"),
("Future Map concepts", "future_map_concepts"),
("Time horizons", "time_horizons"),
):
values = classification.get(key, [])
if values:
md.append(f"- **{label}:** {', '.join(markdown_clean(value) for value in values)}")
md.extend([
f"- **Direction:** {markdown_clean(classification.get('direction', 'uncertain'))}",
f"- **Maturity:** {markdown_clean(classification.get('maturity', 'uncertain'))}",
f"- **Confidence:** {markdown_clean(reasoning.get('confidence', 'unrated'))}",
"",
])
related_documents = reasoning.get("related_documents", [])
related_signals = reasoning.get("related_signals", [])
if related_documents or related_signals:
md.extend(["### Connected Future Map context", ""])
for item in related_documents:
document_id = item.get("document_id")
relationship = item.get("relationship", "related")
path = document_paths.get(document_id)
label = f"Core document: {document_id} ({relationship})"
md.append(f"- [{label}](../../{path})" if path else f"- {label}")
for item in related_signals:
signal_id = item.get("signal_id", "")
relationship = item.get("relationship", "related")
source_file_id = signal_id.removeprefix("fm-signal-")
md.append(f"- [Related signal: {signal_id} ({relationship})](hrecords/{source_file_id}.json)")
md.append("")
for item in record.get("media", []):
public_path = item.get("public_path")
if public_path:
media_names.add(Path(public_path).name)
if item.get("media_type") == "image" and item.get("copy_status") == "copied" and public_path:
md.extend([f"![{title}]({public_path})", ""])
elif item.get("copy_status") == "copied" and public_path:
md.extend([f"[Connected {item.get('media_type', 'file')}]({public_path})", ""])
if record.get("links"):
md.extend(["### Links", ""] + [f"- [{link.get('title') or link['url']}]({link['url']})" for link in record["links"]] + [""])
md.extend([f"[Structured record](hrecords/{source['source_file_id']}.json)", "", "---", ""])
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,
"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", [])],
"related_signals": [item.get("signal_id") for item in reasoning.get("related_signals", [])],
"record_path": f"hrecords/{source['source_file_id']}.json",
"media_paths": [item.get("public_path") for item in record.get("media", []) if item.get("public_path")],
}, ensure_ascii=False))
if state in {"pending", "stale", "failed"} or record.get("review", {}).get("warnings"):
pending_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, "reasoning_status": state,
"warnings": record.get("review", {}).get("warnings", []),
"record_path": f"hrecords/{source['source_file_id']}.json",
}, ensure_ascii=False))
manifest = {
"schema_version": "1.0", "pipeline_version": PIPELINE_VERSION,
"required_tag": "Future Map", "record_count": len(records),
"media_file_count": len(media_names), "reasoning_counts": counts,
"latest_source_date": max((item["source_record"].get("date") or "" for item in records), default="") or None,
"generated_at": utc_now(),
}
previous_manifest = load_json(base / "manifest.json") if (base / "manifest.json").exists() else None
if previous_manifest:
comparable_old = dict(previous_manifest)
comparable_new = dict(manifest)
comparable_old.pop("generated_at", None)
comparable_new.pop("generated_at", None)
if comparable_old == comparable_new:
manifest["generated_at"] = previous_manifest.get("generated_at")
write_json_if_changed(base / "manifest.json", manifest)
write_text_if_changed(base / "signal-index.jsonl", "\n".join(index_lines) + ("\n" if index_lines else ""))
write_text_if_changed(base / "review" / "pending.jsonl", "\n".join(pending_lines) + ("\n" if pending_lines else ""))
write_text_if_changed(base / "future-map-insights.md", "\n".join(md))
return counts
def validate_output(base: Path) -> tuple[int, int]:
errors: list[str] = []
warnings = 0
for path in iter_json_files(base / "hrecords"):
record = load_json(path)
if not record:
errors.append(f"{path.name}: unreadable record")
continue
for issue in basic_validate(record, base) + schema_validate(record, SCHEMA_PATH):
errors.append(f"{path.name}: {issue}")
warnings += len(record.get("review", {}).get("warnings", []))
for error in errors:
print("ERROR", error)
print(f"Validated records: {len(list((base / 'hrecords').glob('*.json')))}")
print(f"Validation errors: {len(errors)}")
print(f"Review warnings: {warnings}")
return len(errors), warnings
def resolve_sources(args: argparse.Namespace) -> tuple[Path, Path, str]:
config: dict[str, Any] = {}
config_path = Path(args.config) if args.config else DEFAULT_CONFIG
if config_path.exists():
config = json.loads(config_path.read_text(encoding="utf-8"))
hrecords = args.source_hrecords or os.environ.get("FUTURE_MAP_SOURCE_HRECORDS") or config.get("source_hrecords")
files = args.source_files or os.environ.get("FUTURE_MAP_SOURCE_FILES") or config.get("source_files")
tag = config.get("required_tag", "Future Map")
if not hrecords or not files:
raise RuntimeError("Set source folders in ignored config/local.json, environment variables, or command arguments.")
return Path(os.path.expandvars(hrecords)), Path(os.path.expandvars(files)), tag
def command_sync(args: argparse.Namespace) -> int:
source_hrecords, source_files, required_tag = resolve_sources(args)
base = Path(args.output_root).resolve() if args.output_root else BASE_DIR
output_hrecords = base / "hrecords"
output_files = base / "files"
output_hrecords.mkdir(parents=True, exist_ok=True)
output_files.mkdir(parents=True, exist_ok=True)
if not source_hrecords.exists():
raise FileNotFoundError(f"Source hrecords folder not found: {source_hrecords}")
if not source_files.exists():
raise FileNotFoundError(f"Source files folder not found: {source_files}")
expected_records: set[str] = set()
expected_files: set[str] = set()
matched = changed = skipped = 0
for source_path in iter_json_files(source_hrecords):
source = load_json(source_path)
if not source:
skipped += 1
continue
if required_tag not in normalize_list(source.get("HubTags")):
continue
matched += 1
target = output_hrecords / source_path.name
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)
expected_files.update(record_files)
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:
path.unlink()
removed_records += 1
for path in output_files.iterdir():
if path.is_file() and path.name not in expected_files:
path.unlink()
removed_files += 1
counts = render_outputs(base)
errors, warnings = validate_output(base)
print("DONE")
print(f"Required tag: {required_tag}")
print(f"Matched records: {matched}")
print(f"Changed derivative records: {changed}")
print(f"Skipped unreadable records: {skipped}")
print(f"Removed stale records: {removed_records}")
print(f"Removed stale files: {removed_files}")
print(f"Reasoning counts: {json.dumps(counts, sort_keys=True)}")
print(f"Review warnings: {warnings}")
return 1 if errors else 0
def validate_reasoning_patch(patch: dict[str, Any]) -> list[str]:
errors = schema_validate(patch, PATCH_SCHEMA_PATH)
required = {"record_id", "analysis", "implications", "claims", "classification", "related_documents", "related_signals", "confidence", "novelty", "corpus_documents_consulted", "generated_by"}
missing = required - set(patch)
if missing:
errors.append("missing fields: " + ", ".join(sorted(missing)))
if len(str(patch.get("analysis", ""))) < 20:
errors.append("analysis must contain at least 20 characters")
classification = patch.get("classification", {})
if not classification.get("signal_types") or not classification.get("topics"):
errors.append("classification requires signal_types and topics")
if not patch.get("corpus_documents_consulted"):
errors.append("at least one corpus document must be consulted")
return errors
def command_apply_reasoning(args: argparse.Namespace) -> int:
base = Path(args.output_root).resolve() if args.output_root else BASE_DIR
patch_path = Path(args.patch)
patch = json.loads(patch_path.read_text(encoding="utf-8"))
if patch.get("record_id") != args.record_id:
raise RuntimeError("Patch record_id does not match --record-id")
issues = validate_reasoning_patch(patch)
if issues:
for issue in issues:
print("ERROR", issue)
return 1
source_file_id = args.record_id.removeprefix("fm-signal-")
record_path = base / "hrecords" / f"{source_file_id}.json"
record = load_json(record_path)
if not record or record.get("id") != args.record_id:
raise FileNotFoundError(f"Derivative record not found: {record_path}")
record["reasoning"] = {
"status": "complete",
"analysis": patch["analysis"],
"implications": patch["implications"],
"claims": patch["claims"],
"classification": patch["classification"],
"related_documents": patch["related_documents"],
"related_signals": patch["related_signals"],
"confidence": patch["confidence"],
"novelty": patch["novelty"],
"corpus_documents_consulted": patch["corpus_documents_consulted"],
"generated_at": utc_now(),
"generated_by": patch["generated_by"],
}
record["review"]["publication_status"] = "approved"
record["review"]["content_review"] = "automated"
write_json_if_changed(record_path, record)
render_outputs(base)
errors, _ = validate_output(base)
return 1 if errors else 0
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(dest="command", required=True)
sync = subparsers.add_parser("sync", help="Prepare public derivatives and copy connected media.")
sync.add_argument("--config")
sync.add_argument("--source-hrecords")
sync.add_argument("--source-files")
sync.add_argument("--output-root")
sync.add_argument("--no-prune", action="store_true")
validate = subparsers.add_parser("validate", help="Validate all derivative records and media paths.")
validate.add_argument("--output-root")
render = subparsers.add_parser("render", help="Regenerate manifest, queues, index, and Markdown.")
render.add_argument("--output-root")
apply_reasoning = subparsers.add_parser("apply-reasoning", help="Apply one validated AI reasoning patch.")
apply_reasoning.add_argument("--record-id", required=True)
apply_reasoning.add_argument("--patch", required=True)
apply_reasoning.add_argument("--output-root")
return parser
def main() -> int:
args = build_parser().parse_args()
if args.command == "sync":
return command_sync(args)
base = Path(args.output_root).resolve() if getattr(args, "output_root", None) else BASE_DIR
if args.command == "validate":
errors, _ = validate_output(base)
return 1 if errors else 0
if args.command == "render":
print(json.dumps(render_outputs(base), sort_keys=True))
return 0
if args.command == "apply-reasoning":
return command_apply_reasoning(args)
return 2
if __name__ == "__main__":
try:
sys.exit(main())
except Exception as exc:
print(f"ERROR: {exc}", file=sys.stderr)
sys.exit(1)