1673 lines
81 KiB
Python
1673 lines
81 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, quote, urlencode, urlsplit, urlunsplit
|
|
|
|
|
|
PIPELINE_VERSION = "1.4.0"
|
|
PUBLIC_SCHEMA_VERSION = "1.2"
|
|
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"
|
|
READINESS_PATCH_SCHEMA_PATH = BASE_DIR / "schemas" / "readiness-patch.schema.json"
|
|
CONNECTIONS_SCHEMA_PATH = BASE_DIR / "schemas" / "connections.schema.json"
|
|
DERIVATIVE_SCHEMA_PATH = BASE_DIR / "schemas" / "future-map-derivative.schema.json"
|
|
DERIVATIVE_PATCH_SCHEMA_PATH = BASE_DIR / "schemas" / "derivative-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)
|
|
CAPTURE_TYPES = {
|
|
"legacy", "signal", "observation", "idea", "question", "draft",
|
|
"correspondence", "other", "unknown",
|
|
}
|
|
|
|
|
|
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 sha256_json(value: Any) -> str:
|
|
payload = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
|
return sha256_bytes(payload)
|
|
|
|
|
|
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 dedupe_preserving_order(value: Any) -> Any:
|
|
"""Remove repeated list items without coercing invalid values."""
|
|
if not isinstance(value, list):
|
|
return value
|
|
result: list[Any] = []
|
|
for item in value:
|
|
if item not in result:
|
|
result.append(item)
|
|
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:
|
|
# The master template uses "public" as an affirmative publishing state.
|
|
# Blank values are legacy publishable records; all other values fail closed.
|
|
return any(item.casefold() != "public" for item in normalize_list(value))
|
|
|
|
|
|
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 empty_source_assessment(source: dict[str, Any], links: list[dict[str, Any]], media: list[dict[str, Any]]) -> dict[str, Any]:
|
|
basis: list[str] = []
|
|
if source.get("Summary"):
|
|
basis.append("summary")
|
|
if source.get("Notes"):
|
|
basis.append("notes")
|
|
if source.get("CaptureContext"):
|
|
basis.append("capture-context")
|
|
if source.get("SourceURL") or any(item.get("kind") == "source" for item in links):
|
|
basis.append("source-url")
|
|
if media:
|
|
basis.append("connected-media")
|
|
return {
|
|
"status": "unassessed",
|
|
"basis": basis,
|
|
"missing_elements": [],
|
|
"assessment": None,
|
|
"review_required": True,
|
|
"assessed_at": None,
|
|
"assessed_by": None,
|
|
}
|
|
|
|
|
|
def empty_media_inspection(copy_status: str) -> dict[str, Any]:
|
|
return {
|
|
"requirement": "unassessed",
|
|
"status": "missing" if copy_status == "missing" else "unassessed",
|
|
"method": None,
|
|
"inspected_at": None,
|
|
"inspected_by": None,
|
|
}
|
|
|
|
|
|
def preserve_media_assessment(media: list[dict[str, Any]], previous: dict[str, Any] | None) -> None:
|
|
previous_media = {item.get("id"): item for item in (previous or {}).get("media", [])}
|
|
for item in media:
|
|
prior = previous_media.get(item.get("id"))
|
|
unchanged = prior and all(
|
|
prior.get(key) == item.get(key)
|
|
for key in ("source_reference", "source_url", "content_hash", "copy_status")
|
|
)
|
|
if unchanged:
|
|
item["inspection"] = prior.get("inspection", empty_media_inspection(item["copy_status"]))
|
|
item["description"] = prior.get("description")
|
|
item["extracted_text"] = prior.get("extracted_text")
|
|
else:
|
|
item["inspection"] = empty_media_inspection(item["copy_status"])
|
|
|
|
|
|
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"))
|
|
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]] = []
|
|
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 any(item["kind"] == "source" for item in links) else "related",
|
|
"source_field": 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"))
|
|
preserve_media_assessment(media, previous)
|
|
if (
|
|
previous
|
|
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()
|
|
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 previous and reasoning.get("status") == "excluded" and source_changed:
|
|
reasoning = empty_reasoning()
|
|
elif reasoning.get("status") not in {"complete", "stale", "excluded"}:
|
|
reasoning = empty_reasoning()
|
|
|
|
if previous and not source_changed and previous.get("source_assessment"):
|
|
source_assessment = previous["source_assessment"]
|
|
else:
|
|
source_assessment = empty_source_assessment(source, links, media)
|
|
|
|
canonical_url = explicit_source_url or next((item["url"] for item in links if item["kind"] == "source"), None)
|
|
result = {
|
|
"schema_version": PUBLIC_SCHEMA_VERSION,
|
|
"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,
|
|
"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),
|
|
},
|
|
"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,
|
|
"source_assessment": source_assessment,
|
|
"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", "source_assessment", "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"] != 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")
|
|
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}")
|
|
inspection = item.get("inspection", {})
|
|
if inspection.get("status") == "inspected" and (not inspection.get("method") or not inspection.get("inspected_by")):
|
|
errors.append(f"inspected media requires method and inspected_by: {item.get('id')}")
|
|
if inspection.get("requirement") == "not-required" and inspection.get("status") != "not-required":
|
|
errors.append(f"not-required media must have not-required status: {item.get('id')}")
|
|
assessment = record.get("source_assessment", {})
|
|
if assessment.get("status") == "sufficient":
|
|
incomplete = [
|
|
item.get("id") for item in record.get("media", [])
|
|
if item.get("inspection", {}).get("requirement") == "required"
|
|
and item.get("inspection", {}).get("status") != "inspected"
|
|
]
|
|
if incomplete:
|
|
errors.append("sufficient source assessment has uninspected required media: " + ", ".join(incomplete))
|
|
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 publication_settings(base: Path) -> dict[str, Any]:
|
|
return load_json(base / "config" / "publication.json") or {}
|
|
|
|
|
|
def public_repository_url(settings: dict[str, Any], repository_path: str, locator: str | None = None) -> str | None:
|
|
base_url = str(settings.get("repository_browser_base_url") or "").rstrip("/")
|
|
if not base_url:
|
|
return None
|
|
encoded_path = quote(repository_path.replace("\\", "/"), safe="/-_.~()")
|
|
return f"{base_url}/{encoded_path}{locator or ''}"
|
|
|
|
|
|
def connection_identifier(source_id: str, target_type: str, target_id: str, relationship: str) -> str:
|
|
payload = f"{source_id}|{target_type}|{target_id}|{relationship}".encode("utf-8")
|
|
return "fm-connection-" + hashlib.sha256(payload).hexdigest()[:20]
|
|
|
|
|
|
def resolve_connections(records: list[dict[str, Any]], base: Path) -> tuple[dict[str, Any], dict[str, list[dict[str, Any]]], dict[str, list[dict[str, Any]]], list[dict[str, Any]]]:
|
|
settings = publication_settings(base)
|
|
section_index = load_json(base / "indexes" / "core-document-sections.json") or {}
|
|
section_targets: dict[tuple[str, str], dict[str, Any]] = {}
|
|
for document in section_index.get("documents", []):
|
|
for section in document.get("sections", []):
|
|
section_targets[(document.get("document_id"), section.get("section_id"))] = {
|
|
"document_title": document.get("title") or document.get("document_id"),
|
|
"repository_path": document.get("path"),
|
|
"format": document.get("format"),
|
|
"section_title": section.get("heading") or section.get("section_id"),
|
|
"locator": section.get("locator"),
|
|
}
|
|
|
|
record_by_id = {record["id"]: record for record in records}
|
|
titles = {
|
|
record["id"]: record["source_record"].get("title") or f"Future Map Signal {record['source_record']['source_file_id']}"
|
|
for record in records
|
|
}
|
|
outgoing: dict[str, list[dict[str, Any]]] = {record["id"]: [] for record in records}
|
|
incoming_signals: dict[str, list[dict[str, Any]]] = {record["id"]: [] for record in records}
|
|
core_backlinks: dict[str, list[dict[str, Any]]] = {}
|
|
connections: list[dict[str, Any]] = []
|
|
issues: list[dict[str, Any]] = []
|
|
|
|
for record in records:
|
|
source_id = record["id"]
|
|
source_page = f"signals/{source_id}.md"
|
|
reasoning = record.get("reasoning", {})
|
|
for relationship in reasoning.get("related_documents", []):
|
|
document_id = str(relationship.get("document_id") or "")
|
|
section_id = str(relationship.get("section_id") or "")
|
|
target = section_targets.get((document_id, section_id))
|
|
if not target or not target.get("repository_path"):
|
|
issues.append({
|
|
"source_signal_id": source_id,
|
|
"target_type": "core-section",
|
|
"document_id": document_id,
|
|
"section_id": section_id,
|
|
"issue": "unresolved-core-section-target",
|
|
})
|
|
continue
|
|
target_id = f"{document_id}#{section_id}"
|
|
locator = target.get("locator") or ""
|
|
repository_path = str(target["repository_path"])
|
|
edge = {
|
|
"connection_id": connection_identifier(source_id, "core-section", target_id, relationship.get("relationship", "illustrates")),
|
|
"source_signal_id": source_id,
|
|
"source_label": titles[source_id],
|
|
"source_page_path": source_page,
|
|
"source_public_url": public_repository_url(settings, f"data/insights-hub/{source_page}"),
|
|
"target_type": "core-section",
|
|
"target_id": target_id,
|
|
"document_id": document_id,
|
|
"section_id": section_id,
|
|
"label": f"{target['document_title']} — {target['section_title']}",
|
|
"relationship": relationship.get("relationship", "illustrates"),
|
|
"relevance": relationship.get("relevance"),
|
|
"review_status": relationship.get("review_status", "machine-proposed"),
|
|
"repository_path": repository_path,
|
|
"locator": locator or None,
|
|
"relative_url": f"../../{repository_path}{locator}",
|
|
"page_relative_url": f"../../../{repository_path}{locator}",
|
|
"public_url": public_repository_url(settings, repository_path, locator),
|
|
}
|
|
connections.append(edge)
|
|
outgoing[source_id].append(edge)
|
|
core_backlinks.setdefault(target_id, []).append(edge)
|
|
|
|
for relationship in reasoning.get("related_signals", []):
|
|
target_signal_id = str(relationship.get("signal_id") or "")
|
|
if target_signal_id == source_id or target_signal_id not in record_by_id:
|
|
issues.append({
|
|
"source_signal_id": source_id,
|
|
"target_type": "signal",
|
|
"target_signal_id": target_signal_id,
|
|
"issue": "self-link" if target_signal_id == source_id else "unresolved-signal-target",
|
|
})
|
|
continue
|
|
target_path = f"signals/{target_signal_id}.md"
|
|
edge = {
|
|
"connection_id": connection_identifier(source_id, "signal", target_signal_id, relationship.get("relationship", "illustrates")),
|
|
"source_signal_id": source_id,
|
|
"source_label": titles[source_id],
|
|
"source_page_path": source_page,
|
|
"source_public_url": public_repository_url(settings, f"data/insights-hub/{source_page}"),
|
|
"target_type": "signal",
|
|
"target_id": target_signal_id,
|
|
"label": titles[target_signal_id],
|
|
"relationship": relationship.get("relationship", "illustrates"),
|
|
"relevance": relationship.get("relevance"),
|
|
"review_status": relationship.get("review_status", "machine-proposed"),
|
|
"repository_path": f"data/insights-hub/{target_path}",
|
|
"locator": None,
|
|
"relative_url": target_path,
|
|
"page_relative_url": f"{target_signal_id}.md",
|
|
"public_url": public_repository_url(settings, f"data/insights-hub/{target_path}"),
|
|
}
|
|
connections.append(edge)
|
|
outgoing[source_id].append(edge)
|
|
incoming_signals[target_signal_id].append(edge)
|
|
|
|
connections.sort(key=lambda item: (item["source_signal_id"], item["target_type"], item["target_id"], item["relationship"]))
|
|
for values in outgoing.values():
|
|
values.sort(key=lambda item: (item["target_type"], item["label"], item["relationship"]))
|
|
for values in incoming_signals.values():
|
|
values.sort(key=lambda item: (-(item.get("relevance") or 0), item["source_label"], item["relationship"]))
|
|
|
|
signal_backlinks = [
|
|
{
|
|
"signal_id": signal_id,
|
|
"label": titles[signal_id],
|
|
"page_path": f"signals/{signal_id}.md",
|
|
"incoming": [
|
|
{
|
|
"connection_id": edge["connection_id"],
|
|
"source_signal_id": edge["source_signal_id"],
|
|
"source_label": edge["source_label"],
|
|
"relationship": edge["relationship"],
|
|
"relevance": edge["relevance"],
|
|
"source_page_path": edge["source_page_path"],
|
|
"source_public_url": edge["source_public_url"],
|
|
}
|
|
for edge in incoming_signals[signal_id]
|
|
],
|
|
}
|
|
for signal_id in sorted(incoming_signals)
|
|
if incoming_signals[signal_id]
|
|
]
|
|
core_section_backlinks = [
|
|
{
|
|
"target_id": target_id,
|
|
"document_id": edges[0]["document_id"],
|
|
"section_id": edges[0]["section_id"],
|
|
"label": edges[0]["label"],
|
|
"repository_path": edges[0]["repository_path"],
|
|
"locator": edges[0]["locator"],
|
|
"public_url": edges[0]["public_url"],
|
|
"incoming": [
|
|
{
|
|
"connection_id": edge["connection_id"],
|
|
"source_signal_id": edge["source_signal_id"],
|
|
"source_label": edge["source_label"],
|
|
"relationship": edge["relationship"],
|
|
"relevance": edge["relevance"],
|
|
"source_page_path": edge["source_page_path"],
|
|
"source_public_url": edge["source_public_url"],
|
|
}
|
|
for edge in sorted(edges, key=lambda item: (item["source_label"], item["relationship"]))
|
|
],
|
|
}
|
|
for target_id, edges in sorted(core_backlinks.items())
|
|
]
|
|
payload = {
|
|
"schema_version": "1.0",
|
|
"generated_at": utc_now(),
|
|
"connection_count": len(connections),
|
|
"core_section_connection_count": sum(1 for item in connections if item["target_type"] == "core-section"),
|
|
"signal_connection_count": sum(1 for item in connections if item["target_type"] == "signal"),
|
|
"connections": connections,
|
|
"signal_backlinks": signal_backlinks,
|
|
"core_section_backlinks": core_section_backlinks,
|
|
}
|
|
return payload, outgoing, incoming_signals, issues
|
|
|
|
|
|
def derivative_json_paths(base: Path) -> list[Path]:
|
|
root = base / "derivatives"
|
|
if not root.exists():
|
|
return []
|
|
return sorted(path for path in root.glob("*/*.json") if path.is_file())
|
|
|
|
|
|
def derivative_lineage_status(
|
|
derivative: dict[str, Any],
|
|
records_by_id: dict[str, dict[str, Any]],
|
|
connections_by_id: dict[str, dict[str, Any]],
|
|
) -> str:
|
|
record = records_by_id.get(str(derivative.get("source_signal_id") or ""))
|
|
if not record or record.get("reasoning", {}).get("status") != "complete":
|
|
return "source-unavailable"
|
|
lineage = derivative.get("lineage", {})
|
|
if lineage.get("source_record_hash") != record.get("provenance", {}).get("source_hash"):
|
|
return "stale"
|
|
if lineage.get("source_reasoning_hash") != sha256_json(record.get("reasoning", {})):
|
|
return "stale"
|
|
connection_ids = [item.get("connection_id") for item in derivative.get("references", [])]
|
|
if any(connection_id not in connections_by_id for connection_id in connection_ids):
|
|
return "broken-reference"
|
|
selected = [connections_by_id[connection_id] for connection_id in connection_ids]
|
|
if lineage.get("selected_connections_hash") != sha256_json(selected):
|
|
return "broken-reference"
|
|
return "current"
|
|
|
|
|
|
def render_derivative_page(derivative: dict[str, Any], lineage_status: str) -> str:
|
|
title = derivative.get("title") or derivative["id"]
|
|
lines = [
|
|
f"# {markdown_clean(title)}", "",
|
|
f"**Derivative ID:** `{derivative['id']}`", "",
|
|
f"**Source signal:** [{derivative['source_signal_id']}](../../signals/{derivative['source_signal_id']}.md)", "",
|
|
f"**Artifact:** {derivative['artifact_type']} · {derivative['channel']}", "",
|
|
f"**Review:** {derivative['review']['status']}", "",
|
|
f"**Lineage:** {lineage_status}", "",
|
|
"## Draft", "", markdown_clean(derivative["content"]), "",
|
|
]
|
|
if derivative.get("call_to_action"):
|
|
lines.extend(["## Call to action", "", markdown_clean(derivative["call_to_action"]), ""])
|
|
if derivative.get("references"):
|
|
lines.extend(["## Connected Future Map context", ""])
|
|
for reference in derivative["references"]:
|
|
url = reference["url"]
|
|
if not url.startswith(("http://", "https://")):
|
|
url = f"../../{url}"
|
|
lines.append(f"- [{markdown_clean(reference['label'])} ({reference['relationship']})]({url})")
|
|
lines.append("")
|
|
if derivative.get("claims_used"):
|
|
lines.extend(["## Claims used", ""])
|
|
for claim in derivative["claims_used"]:
|
|
lines.append(f"- {markdown_clean(claim['text'])} _({claim['type']}; {claim['confidence']} confidence)_")
|
|
lines.append("")
|
|
lines.extend([f"[Structured derivative]({derivative['id']}.json)", ""])
|
|
return "\n".join(lines)
|
|
|
|
|
|
def render_derivatives(
|
|
base: Path,
|
|
records: list[dict[str, Any]],
|
|
connections: list[dict[str, Any]],
|
|
) -> tuple[dict[str, list[dict[str, Any]]], dict[str, int], dict[str, int]]:
|
|
records_by_id = {record["id"]: record for record in records}
|
|
connections_by_id = {edge["connection_id"]: edge for edge in connections}
|
|
by_source: dict[str, list[dict[str, Any]]] = {record["id"]: [] for record in records}
|
|
review_counts: dict[str, int] = {}
|
|
lineage_counts: dict[str, int] = {}
|
|
index_lines: list[str] = []
|
|
review_lines: list[str] = []
|
|
collection = [
|
|
"# Future Map Authored Derivatives", "",
|
|
"Versioned drafts derived from enriched Future Map signals. Each artifact preserves its selected claims, references, and lineage.", "",
|
|
"- [Machine-readable derivative index](../derivative-index.jsonl)",
|
|
"- [Derivative review queue](../review/derivatives.jsonl)", "",
|
|
"## All derivatives", "",
|
|
]
|
|
for path in derivative_json_paths(base):
|
|
derivative = load_json(path)
|
|
if not derivative:
|
|
continue
|
|
status = derivative_lineage_status(derivative, records_by_id, connections_by_id)
|
|
review_status = derivative.get("review", {}).get("status", "draft")
|
|
lineage_counts[status] = lineage_counts.get(status, 0) + 1
|
|
review_counts[review_status] = review_counts.get(review_status, 0) + 1
|
|
source_id = str(derivative.get("source_signal_id") or "")
|
|
source_file_id = source_id.removeprefix("fm-signal-")
|
|
markdown_path = path.with_suffix(".md")
|
|
write_text_if_changed(markdown_path, render_derivative_page(derivative, status))
|
|
relative_json = path.relative_to(base).as_posix()
|
|
relative_markdown = markdown_path.relative_to(base).as_posix()
|
|
entry = {
|
|
"id": derivative.get("id"), "source_signal_id": source_id,
|
|
"artifact_type": derivative.get("artifact_type"), "channel": derivative.get("channel"),
|
|
"audiences": derivative.get("audiences", []), "objective": derivative.get("objective"),
|
|
"title": derivative.get("title"), "content": derivative.get("content"),
|
|
"review_status": review_status, "publication_status": derivative.get("publication", {}).get("status"),
|
|
"lineage_status": status, "json_path": relative_json, "page_path": relative_markdown,
|
|
}
|
|
index_lines.append(json.dumps(entry, ensure_ascii=False))
|
|
if source_id in by_source:
|
|
by_source[source_id].append(entry)
|
|
if review_status in {"draft", "human-reviewed"} or status != "current":
|
|
review_lines.append(json.dumps(entry, ensure_ascii=False))
|
|
collection.append(f"- [{markdown_clean(derivative.get('title') or derivative['id'])}]({source_file_id}/{derivative['id']}.md) — {derivative['artifact_type']} · {review_status} · {status}")
|
|
collection.append("")
|
|
write_text_if_changed(base / "derivative-index.jsonl", "\n".join(index_lines) + ("\n" if index_lines else ""))
|
|
write_text_if_changed(base / "review" / "derivatives.jsonl", "\n".join(review_lines) + ("\n" if review_lines else ""))
|
|
write_text_if_changed(base / "derivatives" / "README.md", "\n".join(collection))
|
|
return by_source, review_counts, lineage_counts
|
|
|
|
|
|
def render_signal_page(
|
|
record: dict[str, Any],
|
|
outgoing: list[dict[str, Any]],
|
|
incoming: list[dict[str, Any]],
|
|
derivatives: list[dict[str, Any]],
|
|
) -> str:
|
|
source = record["source_record"]
|
|
reasoning = record["reasoning"]
|
|
title = source.get("title") or f"Future Map Signal {source['source_file_id']}"
|
|
lines = [
|
|
f"# {markdown_clean(title)}", "",
|
|
f"**Signal ID:** `{record['id']}`", "",
|
|
f"**Date:** {source.get('date') or source.get('date_original') or 'Unknown'}", "",
|
|
f"**Reasoning:** {reasoning.get('status', 'pending')}", "",
|
|
"[Future Map Insights Hub](../future-map-insights.md)", "",
|
|
]
|
|
if source.get("summary"):
|
|
lines.extend(["## Source observation", "", markdown_clean(source["summary"]), ""])
|
|
capture_context = source.get("capture_context", {}).get("text")
|
|
if capture_context:
|
|
lines.extend(["## Capture context", "", markdown_clean(capture_context), ""])
|
|
if reasoning.get("analysis"):
|
|
lines.extend(["## Future Map analysis", "", markdown_clean(reasoning["analysis"]), ""])
|
|
if reasoning.get("implications"):
|
|
lines.extend(["## Implications", ""] + [f"- {markdown_clean(item)}" for item in reasoning["implications"]] + [""])
|
|
classification = reasoning.get("classification", {})
|
|
if reasoning.get("status") == "complete":
|
|
lines.extend(["## 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:
|
|
lines.append(f"- **{label}:** {', '.join(markdown_clean(value) for value in values)}")
|
|
lines.extend([f"- **Direction:** {classification.get('direction', 'uncertain')}", f"- **Maturity:** {classification.get('maturity', 'uncertain')}", f"- **Confidence:** {reasoning.get('confidence', 'unrated')}", ""])
|
|
if outgoing:
|
|
lines.extend(["## Connected Future Map context", ""])
|
|
for edge in outgoing:
|
|
prefix = "Core section" if edge["target_type"] == "core-section" else "Related signal"
|
|
lines.append(f"- [{prefix}: {markdown_clean(edge['label'])} ({edge['relationship']})]({edge['page_relative_url']})")
|
|
lines.append("")
|
|
if incoming:
|
|
lines.extend(["## Signals that reference this signal", ""])
|
|
for edge in incoming[:20]:
|
|
lines.append(f"- [{markdown_clean(edge['source_label'])} ({edge['relationship']})]({edge['source_signal_id']}.md)")
|
|
if len(incoming) > 20:
|
|
lines.append(f"- {len(incoming) - 20} additional backlinks are available in the [connection index](../indexes/connections.json).")
|
|
lines.append("")
|
|
if derivatives:
|
|
lines.extend(["## Authored derivatives", ""])
|
|
for derivative in derivatives:
|
|
label = derivative.get("title") or derivative["id"]
|
|
page = f"../{derivative['page_path']}"
|
|
lines.append(f"- [{markdown_clean(label)}]({page}) — {derivative['artifact_type']} · {derivative['review_status']} · {derivative['lineage_status']}")
|
|
lines.append("")
|
|
for item in record.get("media", []):
|
|
public_path = item.get("public_path")
|
|
if item.get("copy_status") != "copied" or not public_path:
|
|
continue
|
|
page_path = f"../{public_path}"
|
|
if item.get("media_type") == "image":
|
|
lines.extend([f"", ""])
|
|
else:
|
|
lines.extend([f"[Connected {item.get('media_type', 'file')}]({page_path})", ""])
|
|
if record.get("links"):
|
|
lines.extend(["## Source links", ""] + [f"- [{markdown_clean(link.get('title') or link['url'])}]({link['url']})" for link in record["links"]] + [""])
|
|
lines.extend([f"[Authoritative structured record](../hrecords/{source['source_file_id']}.json)", ""])
|
|
return "\n".join(lines)
|
|
|
|
|
|
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)
|
|
settings = publication_settings(base)
|
|
connection_data, outgoing, incoming, connection_issues = resolve_connections(records, base)
|
|
previous_connections = load_json(base / "indexes" / "connections.json")
|
|
if previous_connections:
|
|
comparable_old = dict(previous_connections)
|
|
comparable_new = dict(connection_data)
|
|
comparable_old.pop("generated_at", None)
|
|
comparable_new.pop("generated_at", None)
|
|
if comparable_old == comparable_new:
|
|
connection_data["generated_at"] = previous_connections.get("generated_at")
|
|
write_json_if_changed(base / "indexes" / "connections.json", connection_data)
|
|
write_text_if_changed(base / "review" / "connection-issues.jsonl", "\n".join(json.dumps(item, ensure_ascii=False) for item in connection_issues) + ("\n" if connection_issues else ""))
|
|
derivatives_by_source, derivative_review_counts, derivative_lineage_counts = render_derivatives(
|
|
base, records, connection_data["connections"]
|
|
)
|
|
|
|
signal_directory = base / "signals"
|
|
signal_directory.mkdir(parents=True, exist_ok=True)
|
|
expected_pages: set[str] = set()
|
|
for record in records:
|
|
page_name = f"{record['id']}.md"
|
|
expected_pages.add(page_name)
|
|
write_text_if_changed(
|
|
signal_directory / page_name,
|
|
render_signal_page(record, outgoing[record["id"]], incoming[record["id"]], derivatives_by_source[record["id"]]),
|
|
)
|
|
for page in signal_directory.glob("fm-signal-*.md"):
|
|
if page.name not in expected_pages:
|
|
page.unlink()
|
|
collection_page = [
|
|
"# Future Map Signal Pages", "",
|
|
f"Browse {len(records)} generated public signal pages.", "",
|
|
"- [Reverse-chronological Insights Hub](../future-map-insights.md)",
|
|
"- [Machine-readable signal index](../signal-index.jsonl)",
|
|
"- [Resolved connection and backlink index](../indexes/connections.json)",
|
|
"- [Authored derivative collection](../derivatives/README.md)",
|
|
"", "## All signals", "",
|
|
]
|
|
for record in records:
|
|
source = record["source_record"]
|
|
title = source.get("title") or f"Future Map Signal {source['source_file_id']}"
|
|
date_label = source.get("date") or source.get("date_original") or "Unknown date"
|
|
collection_page.append(f"- [{markdown_clean(title)}]({record['id']}.md) — {date_label}")
|
|
collection_page.append("")
|
|
write_text_if_changed(signal_directory / "README.md", "\n".join(collection_page))
|
|
|
|
counts = {state: 0 for state in ("pending", "complete", "stale", "failed", "excluded")}
|
|
readiness_counts = {state: 0 for state in ("unassessed", "sufficient", "partial", "insufficient", "unavailable", "needs-human-context")}
|
|
inspection_counts: dict[str, int] = {}
|
|
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
|
|
assessment = record.get("source_assessment", {})
|
|
readiness_state = assessment.get("status", "unassessed")
|
|
readiness_counts[readiness_state] = readiness_counts.get(readiness_state, 0) + 1
|
|
required_media_pending = 0
|
|
for media_item in record.get("media", []):
|
|
inspection_state = media_item.get("inspection", {}).get("status", "unassessed")
|
|
inspection_counts[inspection_state] = inspection_counts.get(inspection_state, 0) + 1
|
|
if media_item.get("inspection", {}).get("requirement") == "required" and inspection_state != "inspected":
|
|
required_media_pending += 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", [])
|
|
signal_page = f"signals/{record['id']}.md"
|
|
md.extend([
|
|
f"## [{markdown_clean(title)}]({signal_page})", "",
|
|
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}", "",
|
|
f"**Source readiness:** {readiness_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"):
|
|
md.extend(["### Implications", ""] + [f"- {markdown_clean(item)}" for item in reasoning["implications"]] + [""])
|
|
classification = reasoning.get("classification", {})
|
|
if state == "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:** {classification.get('direction', 'uncertain')}", f"- **Maturity:** {classification.get('maturity', 'uncertain')}", f"- **Confidence:** {reasoning.get('confidence', 'unrated')}", ""])
|
|
if outgoing[record["id"]]:
|
|
md.extend(["### Connected Future Map context", ""])
|
|
for edge in outgoing[record["id"]]:
|
|
prefix = "Core section" if edge["target_type"] == "core-section" else "Related signal"
|
|
md.append(f"- [{prefix}: {markdown_clean(edge['label'])} ({edge['relationship']})]({edge['relative_url']})")
|
|
md.append("")
|
|
if incoming[record["id"]]:
|
|
md.extend(["### Referenced by", ""])
|
|
for edge in incoming[record["id"]][:5]:
|
|
md.append(f"- [{markdown_clean(edge['source_label'])} ({edge['relationship']})]({edge['source_page_path']})")
|
|
if len(incoming[record["id"]]) > 5:
|
|
md.append(f"- {len(incoming[record['id']]) - 5} additional backlinks are listed on the [signal page]({signal_page}).")
|
|
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"", ""])
|
|
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"- [{markdown_clean(link.get('title') or link['url'])}]({link['url']})" for link in record["links"]] + [""])
|
|
md.extend([f"[Readable signal page]({signal_page}) · [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, "capture_type": source.get("capture_type", "legacy"),
|
|
"capture_context": capture_context, "intended_use": intended_use, "reasoning_status": state,
|
|
"source_readiness_status": readiness_state, "required_media_pending": required_media_pending,
|
|
"signal_types": classification.get("signal_types", []), "topics": 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", [])],
|
|
"connection_ids": [edge["connection_id"] for edge in outgoing[record["id"]]],
|
|
"backlink_connection_ids": [edge["connection_id"] for edge in incoming[record["id"]]],
|
|
"derivative_ids": [item["id"] for item in derivatives_by_source[record["id"]]],
|
|
"record_path": f"hrecords/{source['source_file_id']}.json", "page_path": signal_page,
|
|
"page_url": public_repository_url(settings, f"data/insights-hub/{signal_page}"),
|
|
"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 assessment.get("review_required") or required_media_pending 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, "source_readiness_status": readiness_state,
|
|
"source_readiness_review_required": bool(assessment.get("review_required")), "required_media_pending": required_media_pending,
|
|
"warnings": record.get("review", {}).get("warnings", []), "record_path": f"hrecords/{source['source_file_id']}.json",
|
|
}, ensure_ascii=False))
|
|
|
|
manifest = {
|
|
"schema_version": "1.2", "pipeline_version": PIPELINE_VERSION,
|
|
"required_tag": "Future Map", "record_count": len(records), "signal_page_count": len(expected_pages),
|
|
"connection_count": connection_data["connection_count"],
|
|
"core_section_connection_count": connection_data["core_section_connection_count"],
|
|
"signal_connection_count": connection_data["signal_connection_count"],
|
|
"derivative_count": sum(derivative_review_counts.values()),
|
|
"derivative_review_counts": derivative_review_counts,
|
|
"derivative_lineage_counts": derivative_lineage_counts,
|
|
"media_file_count": len(media_names), "reasoning_counts": counts,
|
|
"source_assessment_counts": readiness_counts, "media_inspection_counts": inspection_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
|
|
record_paths = list(iter_json_files(base / "hrecords"))
|
|
signal_ids: set[str] = set()
|
|
for path in record_paths:
|
|
record = load_json(path)
|
|
if not record:
|
|
errors.append(f"{path.name}: unreadable record")
|
|
continue
|
|
signal_ids.add(record.get("id", ""))
|
|
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", []))
|
|
|
|
connections_path = base / "indexes" / "connections.json"
|
|
connections = load_json(connections_path)
|
|
if not connections:
|
|
errors.append("missing or unreadable indexes/connections.json")
|
|
else:
|
|
if CONNECTIONS_SCHEMA_PATH.exists():
|
|
errors.extend(f"connections.json: {issue}" for issue in schema_validate(connections, CONNECTIONS_SCHEMA_PATH))
|
|
if connections.get("connection_count") != len(connections.get("connections", [])):
|
|
errors.append("connections.json connection_count does not match connections array")
|
|
for edge in connections.get("connections", []):
|
|
if edge.get("source_signal_id") not in signal_ids:
|
|
errors.append(f"connection has missing source signal: {edge.get('connection_id')}")
|
|
if edge.get("target_type") == "signal":
|
|
if edge.get("target_id") not in signal_ids:
|
|
errors.append(f"connection has missing target signal: {edge.get('connection_id')}")
|
|
target_page = base / str(edge.get("relative_url") or "")
|
|
if not target_page.exists():
|
|
errors.append(f"connection has missing signal page: {edge.get('connection_id')}")
|
|
elif edge.get("target_type") == "core-section":
|
|
repository_root = base.parents[1] if len(base.parents) > 1 else base
|
|
if not (repository_root / str(edge.get("repository_path") or "")).exists():
|
|
errors.append(f"connection has missing core document: {edge.get('connection_id')}")
|
|
|
|
records_by_id = {
|
|
record["id"]: record
|
|
for path in record_paths
|
|
if (record := load_json(path)) and record.get("id")
|
|
}
|
|
connections_by_id = {
|
|
edge["connection_id"]: edge
|
|
for edge in (connections or {}).get("connections", [])
|
|
if edge.get("connection_id")
|
|
}
|
|
derivative_paths = derivative_json_paths(base)
|
|
for path in derivative_paths:
|
|
derivative = load_json(path)
|
|
if not derivative:
|
|
errors.append(f"{path}: unreadable derivative")
|
|
continue
|
|
errors.extend(f"{path.name}: {issue}" for issue in schema_validate(derivative, DERIVATIVE_SCHEMA_PATH))
|
|
source_id = derivative.get("source_signal_id")
|
|
source_file_id = str(source_id or "").removeprefix("fm-signal-")
|
|
if path.parent.name != source_file_id:
|
|
errors.append(f"{path.name}: derivative folder does not match source signal")
|
|
if path.stem != derivative.get("id"):
|
|
errors.append(f"{path.name}: derivative filename does not match ID")
|
|
status = derivative_lineage_status(derivative, records_by_id, connections_by_id)
|
|
if status == "broken-reference":
|
|
errors.append(f"{path.name}: derivative has a broken connection reference")
|
|
elif status != "current":
|
|
warnings += 1
|
|
for reference in derivative.get("references", []):
|
|
edge = connections_by_id.get(reference.get("connection_id"))
|
|
if edge and edge.get("source_signal_id") != source_id:
|
|
errors.append(f"{path.name}: connection does not originate from source signal")
|
|
if not path.with_suffix(".md").exists():
|
|
errors.append(f"{path.name}: missing generated Markdown derivative")
|
|
|
|
derivative_index_path = base / "derivative-index.jsonl"
|
|
derivative_index_lines = [
|
|
line for line in derivative_index_path.read_text(encoding="utf-8").splitlines() if line.strip()
|
|
] if derivative_index_path.exists() else []
|
|
if len(derivative_index_lines) != len(derivative_paths):
|
|
errors.append(
|
|
f"derivative index count {len(derivative_index_lines)} does not match derivative count {len(derivative_paths)}"
|
|
)
|
|
|
|
issue_path = base / "review" / "connection-issues.jsonl"
|
|
connection_issues = [line for line in issue_path.read_text(encoding="utf-8").splitlines() if line.strip()] if issue_path.exists() else []
|
|
for issue in connection_issues:
|
|
errors.append(f"unresolved connection: {issue}")
|
|
|
|
page_paths = list((base / "signals").glob("fm-signal-*.md")) if (base / "signals").exists() else []
|
|
if len(page_paths) != len(record_paths):
|
|
errors.append(f"signal page count {len(page_paths)} does not match record count {len(record_paths)}")
|
|
for signal_id in signal_ids:
|
|
if not (base / "signals" / f"{signal_id}.md").exists():
|
|
errors.append(f"missing signal page for {signal_id}")
|
|
for error in errors:
|
|
print("ERROR", error)
|
|
print(f"Validated records: {len(record_paths)}")
|
|
print(f"Validated signal pages: {len(page_paths)}")
|
|
print(f"Validated connections: {len((connections or {}).get('connections', []))}")
|
|
print(f"Validated derivatives: {len(derivative_paths)}")
|
|
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()
|
|
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
|
|
target = output_hrecords / source_path.name
|
|
source = load_json(source_path)
|
|
if not source:
|
|
skipped += 1
|
|
if target.exists():
|
|
expected_records.add(target.name)
|
|
previous = load_json(target) or {}
|
|
for media in previous.get("media", []):
|
|
public_path = media.get("public_path")
|
|
if public_path:
|
|
expected_files.add(Path(public_path).name)
|
|
continue
|
|
if required_tag not in normalize_list(source.get("HubTags")):
|
|
continue
|
|
matched += 1
|
|
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)
|
|
expected_files.update(record_files)
|
|
if write_json_if_changed(target, record):
|
|
changed += 1
|
|
|
|
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
|
|
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}")
|
|
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 validate_readiness_patch(patch: dict[str, Any], record: dict[str, Any]) -> list[str]:
|
|
errors = schema_validate(patch, READINESS_PATCH_SCHEMA_PATH)
|
|
required = {"record_id", "source_assessment", "media_inspections"}
|
|
missing = required - set(patch)
|
|
if missing:
|
|
errors.append("missing fields: " + ", ".join(sorted(missing)))
|
|
return errors
|
|
known_media = {item.get("id") for item in record.get("media", [])}
|
|
media_ids = [item.get("media_id") for item in patch.get("media_inspections", [])]
|
|
if len(media_ids) != len(set(media_ids)):
|
|
errors.append("media_inspections contains duplicate media_id values")
|
|
unknown = sorted(str(item) for item in set(media_ids) - known_media)
|
|
if unknown:
|
|
errors.append("unknown media_id values: " + ", ".join(unknown))
|
|
for item in patch.get("media_inspections", []):
|
|
if item.get("status") == "inspected" and (not item.get("method") or not item.get("inspected_by")):
|
|
errors.append(f"inspected media requires method and inspected_by: {item.get('media_id')}")
|
|
if item.get("requirement") == "not-required" and item.get("status") != "not-required":
|
|
errors.append(f"not-required media must have not-required status: {item.get('media_id')}")
|
|
assessment_status = patch.get("source_assessment", {}).get("status")
|
|
patched = {item.get("media_id"): item for item in patch.get("media_inspections", [])}
|
|
incomplete_required: list[str] = []
|
|
for item in record.get("media", []):
|
|
inspection = patched.get(item.get("id"), item.get("inspection", {}))
|
|
if inspection.get("requirement") == "required" and inspection.get("status") != "inspected":
|
|
incomplete_required.append(str(item.get("id")))
|
|
if assessment_status == "sufficient" and incomplete_required:
|
|
errors.append("sufficient assessment requires inspection of required media: " + ", ".join(incomplete_required))
|
|
return errors
|
|
|
|
|
|
def validate_derivative_patch(patch: dict[str, Any]) -> list[str]:
|
|
errors = schema_validate(patch, DERIVATIVE_PATCH_SCHEMA_PATH)
|
|
required = {
|
|
"schema_version", "derivative_id", "source_signal_id", "artifact_type", "channel",
|
|
"audiences", "objective", "title", "content", "content_format", "call_to_action",
|
|
"claim_indexes", "connection_ids", "authoring_notes", "generated_by",
|
|
"supersedes_derivative_id",
|
|
}
|
|
missing = required - set(patch)
|
|
if missing:
|
|
errors.append("missing fields: " + ", ".join(sorted(missing)))
|
|
if len(str(patch.get("objective") or "")) < 10:
|
|
errors.append("objective must contain at least 10 characters")
|
|
if len(str(patch.get("content") or "")) < 20:
|
|
errors.append("content must contain at least 20 characters")
|
|
if not patch.get("audiences"):
|
|
errors.append("at least one audience is required")
|
|
return errors
|
|
|
|
|
|
def command_apply_derivative(args: argparse.Namespace) -> int:
|
|
base = Path(args.output_root).resolve() if args.output_root else BASE_DIR
|
|
patch = json.loads(Path(args.patch).read_text(encoding="utf-8"))
|
|
if patch.get("source_signal_id") != args.record_id:
|
|
raise RuntimeError("Patch source_signal_id does not match --record-id")
|
|
issues = validate_derivative_patch(patch)
|
|
if issues:
|
|
for issue in issues:
|
|
print("ERROR", issue)
|
|
return 1
|
|
source_file_id = args.record_id.removeprefix("fm-signal-")
|
|
if not patch["derivative_id"].startswith(f"fm-derivative-{source_file_id}-"):
|
|
raise RuntimeError("Derivative ID must include the source file ID")
|
|
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"Signal record not found: {record_path}")
|
|
reasoning = record.get("reasoning", {})
|
|
if reasoning.get("status") != "complete":
|
|
raise RuntimeError("Derivative authoring requires complete reasoning")
|
|
|
|
claims = reasoning.get("claims", [])
|
|
claim_indexes = patch.get("claim_indexes", [])
|
|
invalid_claim_indexes = [index for index in claim_indexes if not isinstance(index, int) or index < 0 or index >= len(claims)]
|
|
if invalid_claim_indexes:
|
|
raise RuntimeError("Invalid claim indexes: " + ", ".join(str(index) for index in invalid_claim_indexes))
|
|
claims_used = [
|
|
{
|
|
"claim_index": index,
|
|
"text": claims[index]["text"],
|
|
"type": claims[index]["type"],
|
|
"confidence": claims[index]["confidence"],
|
|
}
|
|
for index in claim_indexes
|
|
]
|
|
|
|
connection_data = load_json(base / "indexes" / "connections.json") or {}
|
|
connections_by_id = {item["connection_id"]: item for item in connection_data.get("connections", [])}
|
|
selected_connections: list[dict[str, Any]] = []
|
|
for connection_id in patch.get("connection_ids", []):
|
|
edge = connections_by_id.get(connection_id)
|
|
if not edge:
|
|
raise RuntimeError(f"Unknown connection ID: {connection_id}")
|
|
if edge.get("source_signal_id") != args.record_id:
|
|
raise RuntimeError(f"Connection does not originate from {args.record_id}: {connection_id}")
|
|
selected_connections.append(edge)
|
|
references = [
|
|
{
|
|
"connection_id": edge["connection_id"],
|
|
"target_type": edge["target_type"],
|
|
"target_id": edge["target_id"],
|
|
"relationship": edge["relationship"],
|
|
"label": edge["label"],
|
|
"repository_path": edge["repository_path"],
|
|
"url": edge.get("public_url") or edge["relative_url"],
|
|
}
|
|
for edge in selected_connections
|
|
]
|
|
|
|
derivative_id = patch["derivative_id"]
|
|
output_path = base / "derivatives" / source_file_id / f"{derivative_id}.json"
|
|
patch_hash = sha256_json(patch)
|
|
existing = load_json(output_path) if output_path.exists() else None
|
|
if existing:
|
|
if existing.get("lineage", {}).get("authoring_patch_hash") == patch_hash:
|
|
print(f"Derivative unchanged: {derivative_id}")
|
|
render_outputs(base)
|
|
errors, _ = validate_output(base)
|
|
return 1 if errors else 0
|
|
if not args.replace:
|
|
raise RuntimeError("Derivative ID already exists with different content; use --replace intentionally")
|
|
if existing.get("review", {}).get("status") not in {"draft", "rejected"}:
|
|
raise RuntimeError("Only draft or rejected derivatives can be replaced")
|
|
|
|
supersedes = patch.get("supersedes_derivative_id")
|
|
if supersedes:
|
|
superseded_path = base / "derivatives" / source_file_id / f"{supersedes}.json"
|
|
if not superseded_path.exists():
|
|
raise RuntimeError(f"Superseded derivative does not exist for this source: {supersedes}")
|
|
derivative = {
|
|
"schema_version": "1.0",
|
|
"id": derivative_id,
|
|
"source_signal_id": args.record_id,
|
|
"artifact_type": patch["artifact_type"],
|
|
"channel": patch["channel"],
|
|
"audiences": patch["audiences"],
|
|
"objective": patch["objective"],
|
|
"title": patch.get("title"),
|
|
"content": patch["content"],
|
|
"content_format": patch["content_format"],
|
|
"call_to_action": patch.get("call_to_action"),
|
|
"claims_used": claims_used,
|
|
"references": references,
|
|
"authoring": {
|
|
"skill": "eddie-voice-writing",
|
|
"source_repository": "ES-authoring-skills",
|
|
"source_path": "skills/ES-writing-skill.md",
|
|
"voice_profile": "eddie-soehnel",
|
|
"authoring_notes": patch.get("authoring_notes", []),
|
|
"generated_by": patch["generated_by"],
|
|
"generated_at": utc_now(),
|
|
},
|
|
"review": {"status": "draft", "reviewer": None, "reviewed_at": None, "feedback": None},
|
|
"publication": {"status": "not-published", "url": None, "published_at": None, "channel": None},
|
|
"lineage": {
|
|
"source_record_hash": record.get("provenance", {}).get("source_hash"),
|
|
"source_reasoning_hash": sha256_json(reasoning),
|
|
"selected_connections_hash": sha256_json(selected_connections),
|
|
"authoring_patch_hash": patch_hash,
|
|
"supersedes_derivative_id": supersedes,
|
|
},
|
|
}
|
|
derivative_issues = schema_validate(derivative, DERIVATIVE_SCHEMA_PATH)
|
|
if derivative_issues:
|
|
for issue in derivative_issues:
|
|
print("ERROR", issue)
|
|
return 1
|
|
write_json_if_changed(output_path, derivative)
|
|
render_outputs(base)
|
|
errors, _ = validate_output(base)
|
|
return 1 if errors else 0
|
|
|
|
|
|
def command_apply_readiness(args: argparse.Namespace) -> int:
|
|
base = Path(args.output_root).resolve() if args.output_root else BASE_DIR
|
|
patch = json.loads(Path(args.patch).read_text(encoding="utf-8"))
|
|
if patch.get("record_id") != args.record_id:
|
|
raise RuntimeError("Patch record_id does not match --record-id")
|
|
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}")
|
|
issues = validate_readiness_patch(patch, record)
|
|
if issues:
|
|
for issue in issues:
|
|
print("ERROR", issue)
|
|
return 1
|
|
assessment = dict(patch["source_assessment"])
|
|
assessment["assessed_at"] = utc_now()
|
|
assessment["review_required"] = assessment["status"] != "sufficient"
|
|
record["source_assessment"] = assessment
|
|
media_patches = {item["media_id"]: item for item in patch["media_inspections"]}
|
|
for media_item in record.get("media", []):
|
|
media_patch = media_patches.get(media_item.get("id"))
|
|
if not media_patch:
|
|
continue
|
|
media_item["inspection"] = {
|
|
"requirement": media_patch["requirement"],
|
|
"status": media_patch["status"],
|
|
"method": media_patch.get("method"),
|
|
"inspected_at": utc_now() if media_patch["status"] == "inspected" else None,
|
|
"inspected_by": media_patch.get("inspected_by"),
|
|
}
|
|
media_item["description"] = media_patch.get("description")
|
|
media_item["extracted_text"] = media_patch.get("extracted_text")
|
|
write_json_if_changed(record_path, record)
|
|
render_outputs(base)
|
|
errors, _ = validate_output(base)
|
|
return 1 if errors else 0
|
|
|
|
|
|
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")
|
|
consulted_documents = patch.get("corpus_documents_consulted")
|
|
normalized_documents = dedupe_preserving_order(consulted_documents)
|
|
if isinstance(consulted_documents, list) and len(normalized_documents) != len(consulted_documents):
|
|
patch = dict(patch)
|
|
patch["corpus_documents_consulted"] = normalized_documents
|
|
removed = len(consulted_documents) - len(normalized_documents)
|
|
print(f"Normalized corpus_documents_consulted: removed {removed} duplicate entr{'y' if removed == 1 else 'ies'}.")
|
|
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}")
|
|
assessment = record.get("source_assessment", {})
|
|
if assessment.get("status") not in {"sufficient", "partial"}:
|
|
raise RuntimeError("Reasoning requires a source assessment of sufficient or partial")
|
|
incomplete_media = [
|
|
item.get("id") for item in record.get("media", [])
|
|
if item.get("inspection", {}).get("requirement") == "required"
|
|
and item.get("inspection", {}).get("status") != "inspected"
|
|
]
|
|
if incomplete_media:
|
|
raise RuntimeError("Reasoning requires inspection of required media: " + ", ".join(incomplete_media))
|
|
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")
|
|
apply_readiness = subparsers.add_parser("apply-readiness", help="Apply one validated source/media readiness patch.")
|
|
apply_readiness.add_argument("--record-id", required=True)
|
|
apply_readiness.add_argument("--patch", required=True)
|
|
apply_readiness.add_argument("--output-root")
|
|
apply_derivative = subparsers.add_parser("apply-derivative", help="Apply one validated authored-derivative patch.")
|
|
apply_derivative.add_argument("--record-id", required=True)
|
|
apply_derivative.add_argument("--patch", required=True)
|
|
apply_derivative.add_argument("--output-root")
|
|
apply_derivative.add_argument("--replace", action="store_true")
|
|
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)
|
|
if args.command == "apply-readiness":
|
|
return command_apply_readiness(args)
|
|
if args.command == "apply-derivative":
|
|
return command_apply_derivative(args)
|
|
return 2
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
sys.exit(main())
|
|
except Exception as exc:
|
|
print(f"ERROR: {exc}", file=sys.stderr)
|
|
sys.exit(1)
|