184 lines
10 KiB
Python
184 lines
10 KiB
Python
"""Date boundaries, artifact validation and success-only local finalization."""
|
|
import argparse
|
|
import datetime as dt
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
from pathlib import Path
|
|
|
|
POOLS = {"standard_web", "exa", "rock_fight", "sec_edgar"}
|
|
METHODS = {"standard_web", "exa", "direct"}
|
|
HEADINGS = ["Executive Summary", "Major Themes This Week", "Notable Brand and Industry Signals",
|
|
"Playbook Concept Matches", "Public Company and SEC Intelligence", "Rock Fight Intelligence",
|
|
"International Relevance to North America", "Other Interesting Activity",
|
|
"Weak Signals to Monitor", "Watchlist Updates", "Search Methods and Coverage", "Exclusions and Noise"]
|
|
|
|
|
|
def window(day):
|
|
day = dt.date.fromisoformat(day)
|
|
end = day - dt.timedelta(days=day.weekday())
|
|
return {"start": str(end-dt.timedelta(days=7)), "end_exclusive": str(end), "timezone": "America/Denver"}
|
|
|
|
|
|
def read(path):
|
|
return json.loads(Path(path).read_text(encoding="utf-8-sig"))
|
|
|
|
|
|
def inside(root, relative):
|
|
p = (root / relative).resolve()
|
|
if not p.is_relative_to(root.resolve()):
|
|
raise ValueError("Artifact path outside repository")
|
|
return p
|
|
|
|
|
|
def require(condition, message):
|
|
if not condition:
|
|
raise ValueError(message)
|
|
|
|
|
|
def validate_run(root, path, success=False):
|
|
root = Path(root).resolve()
|
|
e = read(path)
|
|
require(e["window"] == window(e["run_date"]), "Window must be previous completed Denver week")
|
|
require(e["status"] in {"complete", "incomplete"}, "Unknown run status")
|
|
report = inside(root, e["report_path"])
|
|
receipt = read(inside(root, e["receipt_path"]))
|
|
body = report.read_text(encoding="utf-8")
|
|
require(all("## " + h in body for h in HEADINGS), "Missing report sections")
|
|
require(receipt["run_id"] == e["run_id"], "Receipt run mismatch")
|
|
require(receipt["status"] == e["status"], "Receipt status mismatch")
|
|
require(set(e["coverage"]) == POOLS, "Missing coverage pools")
|
|
require(all(v in {"complete", "partial", "unavailable"} for v in e["coverage"].values()), "Invalid coverage")
|
|
require(receipt["capture_completeness"] in {"complete", "partial", "unavailable"}, "Capture status missing")
|
|
dt.datetime.fromisoformat(receipt["started_at"])
|
|
dt.datetime.fromisoformat(receipt["ended_at"])
|
|
require("usage" in receipt and isinstance(receipt["gaps"], list), "Receipt lacks gaps/usage")
|
|
searches = e["searches"]
|
|
for s in searches:
|
|
require(s["method"] in METHODS and s["status"] in {"ok", "error"}, "Invalid search provenance")
|
|
require(bool(s["query"]), "Missing query")
|
|
require((s["status"] == "error" and s["returned_count"] is None) or
|
|
(s["status"] == "ok" and type(s["returned_count"]) is int and s["returned_count"] >= 0),
|
|
"Invalid observed result count")
|
|
ids = set()
|
|
urls = set()
|
|
for s in e["sources"]:
|
|
require(s["id"] not in ids and s["url"] not in urls, "Duplicate evidence ID or URL")
|
|
ids.add(s["id"])
|
|
urls.add(s["url"])
|
|
require(s["url"].startswith("https://"), "Missing public source URL")
|
|
require(bool(s["discovery_methods"]) and set(s["discovery_methods"]) <= METHODS, "Missing discovery method")
|
|
for key in ("title", "retrieval_method", "format", "claim", "north_america_relevance"):
|
|
require(bool(s[key]), "Missing source field: " + key)
|
|
require(s["evidence_level"] in {"explicit", "inferred", "speculative"}, "Invalid evidence level")
|
|
require(s["confidence"] in {"high", "medium", "low"}, "Invalid confidence")
|
|
date = dt.date.fromisoformat(s["published_date"])
|
|
require(dt.date.fromisoformat(e["window"]["start"]) <= date < dt.date.fromisoformat(e["window"]["end_exclusive"]), "Source out of window")
|
|
require(s["id"] in body and s["url"] in body, "Report lacks evidence ID/link")
|
|
require(s["kind"] in {"news", "podcast", "sec"}, "Invalid source kind")
|
|
if s["kind"] == "sec":
|
|
for k in ("issuer", "cik", "form", "accession", "period_of_report", "section_or_exhibit"):
|
|
require(bool(s[k]), "SEC field missing: " + k)
|
|
require("sec.gov/" in s["url"].split("https://", 1)[1] and
|
|
s["url"].split("/")[2] in {"www.sec.gov", "sec.gov", "data.sec.gov"}, "SEC evidence must be official")
|
|
if s["kind"] == "podcast":
|
|
require(s["format"] in {"publisher_transcript", "show_notes", "outline", "audio_transcribed"}, "Podcast format overclaim")
|
|
for k in ("episode_title", "speaker", "timestamps"):
|
|
require(bool(s[k]), "Podcast field missing: " + k)
|
|
if success or e["status"] == "complete":
|
|
require(e["status"] == "complete" and all(v == "complete" for v in e["coverage"].values()), "Incomplete research cannot finalize")
|
|
require(receipt["validation_passed"] is True and not receipt["gaps"], "Receipt has failed validation or gaps")
|
|
config = read(root / "config/research.json")
|
|
for method in ("standard_web", "exa"):
|
|
require(sum(s["method"] == method and s["status"] == "ok" for s in searches) >= config["baseline_searches_per_method"], "Independent discovery pass incomplete: " + method)
|
|
checks = e.get("pool_checks", {})
|
|
for pool in ("sec_edgar", "rock_fight"):
|
|
require(bool(checks.get(pool)), "Missing direct pool enumeration: " + pool)
|
|
require(all(c.get("status") == "ok" and c.get("url", "").startswith("https://") for c in checks[pool]), "Incomplete direct pool enumeration")
|
|
pb = e["playbook"]
|
|
require(bool(pb["sections"]), "Playbook mapping unavailable")
|
|
playbook = Path(pb["path"])
|
|
require(playbook.is_file(), "Playbook unavailable")
|
|
require(hashlib.sha256(playbook.read_bytes()).hexdigest() == pb["sha256"], "Playbook hash mismatch")
|
|
return e
|
|
|
|
|
|
def validate_repo(root):
|
|
root = Path(root).resolve()
|
|
repo = read(root / "repository.json")
|
|
require(repo["version"] == (root / "VERSION").read_text().strip(), "Version mismatch")
|
|
require(isinstance(repo["entrypoints"], dict), "Entrypoints must be an object")
|
|
for p in repo["entrypoints"].values():
|
|
if p is not None:
|
|
require(inside(root, p).is_file(), "Missing entrypoint: " + p)
|
|
index = read(root / "content-index.json")
|
|
ids = set()
|
|
paths = set()
|
|
evidence_runs = []
|
|
for p in (root / "evidence").glob("*.json"):
|
|
evidence_runs.append(validate_run(root, p))
|
|
for item in index["items"]:
|
|
require(item["content_id"] not in ids, "Duplicate index ID")
|
|
require(item["path"] not in paths, "Duplicate index path")
|
|
ids.add(item["content_id"])
|
|
paths.add(item["path"])
|
|
require(inside(root, item["path"]).is_file(), "Missing indexed report")
|
|
require(item["status"] == "draft", "Local research catalog does not authorize publication")
|
|
matches = [e for e in evidence_runs if e["report_path"] == item["path"] and content_id(e["run_id"]) == item["content_id"]]
|
|
require(len(matches) == 1 and matches[0]["status"] == "complete", "Catalog item lacks unique completed evidence")
|
|
return {"status": "passed", "indexed_reports": len(index["items"])}
|
|
|
|
|
|
def atomic_json(path, data):
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
temp = path.with_suffix(path.suffix + ".tmp")
|
|
temp.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
|
os.replace(temp, path)
|
|
|
|
|
|
def content_id(run_id):
|
|
require(bool(re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", run_id)), "Run ID must be stable lowercase kebab-case for catalog indexing")
|
|
return "outdoor-industry-" + run_id
|
|
|
|
|
|
def finalize(root, evidence):
|
|
root = Path(root).resolve()
|
|
evidence = inside(root, evidence)
|
|
e = validate_run(root, evidence, success=True)
|
|
validate_repo(root)
|
|
index = read(root / "content-index.json")
|
|
catalog_id = content_id(e["run_id"])
|
|
existing = next((i for i in index["items"] if i["content_id"] == catalog_id), None)
|
|
item = {"id": e["run_id"], "report_path": e["report_path"], "evidence_path": str(evidence.relative_to(root)).replace("\\", "/"), "window": e["window"]}
|
|
catalog = {"content_id": catalog_id, "title": "Outdoor Industry Intelligence — " + e["run_date"], "description": "Weekly strategic brief for " + e["window"]["start"] + " to " + e["window"]["end_exclusive"] + " (exclusive), America/Denver.", "content_type": "research-report", "path": e["report_path"], "status": "draft", "published_at": None, "updated_at": e["run_date"], "author": "Eddie Soehnel", "topics": ["outdoor-industry", "active-lifestyle"], "related_content_ids": []}
|
|
require(existing is None or existing == catalog, "Existing run ID points to different catalog metadata")
|
|
require(not any(i["path"] == e["report_path"] and i["content_id"] != catalog_id for i in index["items"]), "Report path already indexed by another ID")
|
|
checkpoint = root / "state/last-successful-run.json"
|
|
if checkpoint.exists():
|
|
previous = read(checkpoint)
|
|
require(previous["id"] != e["run_id"] or previous == item, "Run ID conflicts with successful checkpoint")
|
|
if existing is None:
|
|
index["items"].append(catalog)
|
|
index["updated_at"] = max(index["updated_at"], e["run_date"])
|
|
atomic_json(root / "content-index.json", index)
|
|
if not checkpoint.exists() or read(checkpoint)["window"]["end_exclusive"] <= e["window"]["end_exclusive"]:
|
|
atomic_json(checkpoint, item)
|
|
return {"status": "complete", "run_id": e["run_id"]}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
parser = argparse.ArgumentParser()
|
|
sub = parser.add_subparsers(dest="command", required=True)
|
|
sub.add_parser("window").add_argument("--date", required=True)
|
|
sub.add_parser("validate").add_argument("root")
|
|
final = sub.add_parser("finalize")
|
|
final.add_argument("root")
|
|
final.add_argument("--evidence", required=True)
|
|
a = parser.parse_args()
|
|
try:
|
|
result = window(a.date) if a.command == "window" else validate_repo(a.root) if a.command == "validate" else finalize(a.root, a.evidence)
|
|
print(json.dumps(result))
|
|
except (ValueError, KeyError, OSError, TypeError) as error:
|
|
parser.exit(1, str(error) + "\n")
|