This commit is contained in:
eddiesoehnel committed 2026-10-14 12:05:54 -06:00
commit ffbf83ebc5
41 files changed
+2782

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
# Scripts
`workflow.py` calculates review windows, validates research artifacts and finalizes complete runs. `validate_repository.py` adapts the repository template validator to this pack's declared file set. `audit_repository.py` is the template's read-only profile audit. Copied template code retains [its MIT notice](../LICENSE-repo-template-MIT.txt).
Run from the repo root:
```text
python -B scripts/audit_repository.py . --profile skill-workflow --json
python -B scripts/validate_repository.py .
python -B scripts/workflow.py validate .
python -B -m unittest discover -s tests -v
```
JSON Schema validation additionally requires jsonschema. Profile, link and research checks use the standard library. The catalog uses content_id/path records; successful operational checkpoints continue to use id/report_path/evidence_path/window.
+370
View File
@@ -0,0 +1,370 @@
#!/usr/bin/env python3
"""Read-only structural audit for an AI-ready repository."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import re
import sys
PROFILES = {
"documentation-guide": {
"README.md",
"AUTHOR.md",
"repository-variables.json",
"repository.json",
"LICENSE",
"CHANGELOG.md",
"UPDATES.md",
"VERSION",
"CITATION.cff",
"docs",
},
"skill-workflow": {
"README.md",
"AUTHOR.md",
"repository-variables.json",
"repository.json",
"LICENSE",
"CHANGELOG.md",
"UPDATES.md",
"VERSION",
"AGENTS.md",
"skills.md",
"skills",
"templates",
"examples",
},
"software-automation": {
"README.md",
"AUTHOR.md",
"repository-variables.json",
"repository.json",
"LICENSE",
"CHANGELOG.md",
"UPDATES.md",
"VERSION",
"CONTRIBUTING.md",
"SECURITY.md",
"AGENTS.md",
"docs",
"scripts",
"tests",
},
"dataset": {
"README.md",
"AUTHOR.md",
"repository-variables.json",
"repository.json",
"LICENSE",
"CHANGELOG.md",
"UPDATES.md",
"VERSION",
"CITATION.cff",
"data",
"schemas",
"docs",
},
}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("repository", type=Path, help="Repository root to inspect")
parser.add_argument(
"--profile",
choices=sorted(PROFILES),
required=True,
help="Approved repository profile",
)
parser.add_argument("--json", action="store_true", help="Emit JSON")
return parser.parse_args()
def read_version_from_citation(path: Path) -> str | None:
if not path.is_file():
return None
match = re.search(
r"(?m)^version:\s*[\"']?([^\"'\s#]+)",
path.read_text(encoding="utf-8-sig"),
)
return match.group(1) if match else None
def audit_content_index(root: Path, findings: list[dict[str, str]]) -> None:
path = root / "content-index.json"
if not path.is_file():
return
try:
index = json.loads(path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
findings.append({"level": "error", "message": f"content-index.json is invalid: {exc}"})
return
items = index.get("items")
if not isinstance(items, list):
findings.append(
{"level": "error", "message": "content-index.json items must be an array"}
)
return
content_ids: set[str] = set()
paths: set[str] = set()
for position, item in enumerate(items):
if not isinstance(item, dict):
findings.append(
{
"level": "error",
"message": f"content-index.json item {position + 1} must be an object",
}
)
continue
content_id = item.get("content_id")
declared = item.get("path")
if not content_id:
findings.append(
{
"level": "error",
"message": f"content-index.json item {position + 1} lacks content_id",
}
)
elif content_id in content_ids:
findings.append(
{
"level": "error",
"message": f"Duplicate content_id in content-index.json: {content_id}",
}
)
else:
content_ids.add(content_id)
if not declared:
findings.append(
{
"level": "error",
"message": f"content-index.json item {position + 1} lacks path",
}
)
elif declared in paths:
findings.append(
{
"level": "error",
"message": f"Duplicate path in content-index.json: {declared}",
}
)
else:
paths.add(declared)
declared_path = Path(declared)
if (
declared_path.is_absolute()
or ".." in declared_path.parts
or not (root / declared_path).is_file()
):
findings.append(
{
"level": "error",
"message": f"Indexed content path does not exist or is unsafe: {declared}",
}
)
def audit(root: Path, profile: str) -> dict:
findings: list[dict[str, str]] = []
if not root.is_dir():
return {
"repository": str(root),
"profile": profile,
"passed": False,
"findings": [{"level": "error", "message": "Repository path is not a directory"}],
}
for relative in sorted(PROFILES[profile]):
if not (root / relative).exists():
findings.append({"level": "error", "message": f"Missing required path: {relative}"})
manifest_path = root / "repository.json"
manifest = None
if manifest_path.is_file():
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
findings.append({"level": "error", "message": f"repository.json is invalid: {exc}"})
else:
for key in ("schema_version", "repository_id", "title", "description", "version", "entrypoints"):
if key not in manifest:
findings.append({"level": "error", "message": f"repository.json lacks key: {key}"})
entrypoints = manifest.get("entrypoints", {})
if isinstance(entrypoints, dict):
for audience in ("human", "ai"):
declared = entrypoints.get(audience)
if not declared:
findings.append(
{"level": "error", "message": f"Missing {audience} entrypoint declaration"}
)
elif not (root / declared).exists():
findings.append(
{
"level": "error",
"message": f"Declared {audience} entrypoint does not exist: {declared}",
}
)
else:
findings.append({"level": "error", "message": "entrypoints must be an object"})
variables_path = root / "repository-variables.json"
variables = None
if variables_path.is_file():
try:
variables = json.loads(variables_path.read_text(encoding="utf-8-sig"))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
findings.append(
{"level": "error", "message": f"repository-variables.json is invalid: {exc}"}
)
else:
for key in (
"schema_version",
"repository_profile",
"identity",
"repository",
"rights",
"skill_defaults",
"verified_by",
"verified_at",
):
if key not in variables:
findings.append(
{
"level": "error",
"message": f"repository-variables.json lacks key: {key}",
}
)
if manifest and variables:
identity = variables.get("identity", {})
variable_authors = [
item.get("name")
for item in identity.get("authors", [])
if isinstance(item, dict)
]
manifest_authors = [
item.get("name")
for item in manifest.get("authors", [])
if isinstance(item, dict)
]
comparisons = (
("authors", variable_authors, manifest_authors),
(
"publisher",
identity.get("publisher", {}).get("name"),
manifest.get("publisher", {}).get("name"),
),
(
"maintainer",
identity.get("maintainer", {}).get("name"),
manifest.get("maintenance", {}).get("maintainer"),
),
(
"repository",
variables.get("repository"),
{
key: manifest.get(key)
for key in (
"repository_id",
"name",
"title",
"canonical_url",
"organization",
)
},
),
(
"rights",
variables.get("rights"),
{
key: manifest.get("rights", {}).get(key)
for key in ("license", "license_file")
},
),
)
for label, variable_value, manifest_value in comparisons:
if variable_value != manifest_value:
findings.append(
{
"level": "error",
"message": (
f"{label} differs between repository-variables.json "
"and repository.json"
),
}
)
if variables and variables.get("repository_profile") != profile:
findings.append(
{
"level": "error",
"message": (
"repository_profile differs between repository-variables.json "
f"({variables.get('repository_profile')}) and requested audit ({profile})"
),
}
)
audit_content_index(root, findings)
version_path = root / "VERSION"
version = version_path.read_text(encoding="utf-8-sig").strip() if version_path.is_file() else None
if version and manifest and manifest.get("version") != version:
findings.append(
{
"level": "error",
"message": f"VERSION ({version}) differs from repository.json ({manifest.get('version')})",
}
)
citation_version = read_version_from_citation(root / "CITATION.cff")
if version and citation_version and citation_version != version:
findings.append(
{
"level": "error",
"message": f"VERSION ({version}) differs from CITATION.cff ({citation_version})",
}
)
readme = root / "README.md"
if readme.is_file() and not readme.read_text(encoding="utf-8-sig").strip():
findings.append({"level": "error", "message": "README.md is empty"})
return {
"repository": str(root.resolve()),
"profile": profile,
"passed": not any(item["level"] == "error" for item in findings),
"findings": findings,
}
def emit_markdown(result: dict) -> None:
print(f"# Repository Audit\n\n- Repository: `{result['repository']}`")
print(f"- Profile: `{result['profile']}`")
print(f"- Result: `{'PASS' if result['passed'] else 'FAIL'}`")
print("\n## Findings")
if not result["findings"]:
print("\n- No structural errors found.")
else:
for finding in result["findings"]:
print(f"\n- {finding['level'].upper()}: {finding['message']}")
def main() -> int:
args = parse_args()
result = audit(args.repository, args.profile)
if args.json:
print(json.dumps(result, indent=2))
else:
emit_markdown(result)
return 0 if result["passed"] else 1
if __name__ == "__main__":
sys.exit(main())
+398
View File
@@ -0,0 +1,398 @@
#!/usr/bin/env python3
"""Validate the implemented AI-ready repository template without dependencies."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import re
import sys
from urllib.parse import unquote
REQUIRED_PATHS = ('README.md', 'AUTHOR.md', 'repository-variables.json', 'repository.json', 'content-index.json', 'LICENSE', 'CHANGELOG.md', 'UPDATES.md', 'VERSION', 'AGENTS.md', 'skills.md', 'CITATION.cff', 'CONTRIBUTING.md', 'SECURITY.md', 'examples/README.md', 'examples/synthetic-evidence.json', 'schemas/README.md', 'schemas/repository.schema.json', 'schemas/repository-variables.schema.json', 'schemas/content-index.schema.json', 'scripts/README.md', 'templates/README.md', 'tests/README.md', 'skills/outdoor-industry-intelligence/SKILL.md')
MANIFEST_REQUIRED_KEYS = (
"schema_version",
"repository_id",
"name",
"title",
"description",
"authors",
"publisher",
"repository_status",
"visibility",
"maturity",
"version",
"resource_types",
"entrypoints",
"rights",
"maintenance",
"ai_retrieval",
)
CONTENT_INDEX_REQUIRED_KEYS = (
"schema_version",
"collection_id",
"title",
"description",
"updated_at",
"items",
)
CONTENT_ITEM_REQUIRED_KEYS = (
"content_id",
"title",
"description",
"content_type",
"path",
"status",
)
MARKDOWN_LINK = re.compile(r"(?<!!)\[[^\]]+\]\(([^)]+)\)")
CITATION_VERSION = re.compile(r"(?m)^version:\s*[\"']?([^\"'\s#]+)")
CITATION_LICENSE = re.compile(r"(?m)^license:\s*[\"']?([^\"'\s#]+)")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("repository", nargs="?", default=".", type=Path)
parser.add_argument("--json", action="store_true", help="Emit JSON")
return parser.parse_args()
def read_text(path: Path) -> str:
return path.read_text(encoding="utf-8-sig")
def add(findings: list[dict[str, str]], level: str, message: str) -> None:
findings.append({"level": level, "message": message})
def validate_manifest(root: Path, findings: list[dict[str, str]]) -> dict | None:
path = root / "repository.json"
try:
manifest = json.loads(read_text(path))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
add(findings, "error", f"repository.json is invalid: {exc}")
return None
for key in MANIFEST_REQUIRED_KEYS:
if key not in manifest:
add(findings, "error", f"repository.json lacks required key: {key}")
entrypoints = manifest.get("entrypoints")
if not isinstance(entrypoints, dict):
add(findings, "error", "repository.json entrypoints must be an object")
else:
for name in ("human", "ai"):
value = entrypoints.get(name)
if not isinstance(value, str) or not value:
add(findings, "error", f"Missing {name} entrypoint")
elif not (root / value).exists():
add(findings, "error", f"Declared {name} entrypoint does not exist: {value}")
for name, value in entrypoints.items():
if name in ("human", "ai") or value is None:
continue
if not isinstance(value, str) or not (root / value).exists():
add(findings, "error", f"Declared entrypoint does not exist: {name}={value}")
contents = manifest.get("contents", [])
if not isinstance(contents, list):
add(findings, "error", "repository.json contents must be an array")
else:
for item in contents:
declared = item.get("path") if isinstance(item, dict) else None
if not declared or not (root / declared).exists():
add(findings, "error", f"Declared contents path does not exist: {declared}")
declared_paths = {
item.get("path") for item in contents if isinstance(item, dict)
}
if (root / "content-index.json").is_file() and "content-index.json" not in declared_paths:
add(findings, "error", "repository.json contents must declare content-index.json")
retrieval = manifest.get("ai_retrieval", {})
if isinstance(retrieval, dict):
for field in ("read_first", "retrieve_as_needed"):
for declared in retrieval.get(field, []):
normalized = declared.rstrip("/")
if normalized and not (root / normalized).exists():
add(findings, "error", f"AI retrieval path does not exist: {declared}")
author_text = read_text(root / "AUTHOR.md") if (root / "AUTHOR.md").is_file() else ""
citation_text = read_text(root / "CITATION.cff") if (root / "CITATION.cff").is_file() else ""
license_text = read_text(root / "LICENSE") if (root / "LICENSE").is_file() else ""
authors = manifest.get("authors", [])
if not isinstance(authors, list) or not authors:
add(findings, "error", "repository.json authors must be a non-empty array")
else:
for author in authors:
name = author.get("name") if isinstance(author, dict) else None
if not name:
add(findings, "error", "Every repository.json author must have a name")
continue
if name not in author_text:
add(findings, "error", f"Author is absent from AUTHOR.md: {name}")
parts = name.split()
if not all(part in citation_text for part in parts):
add(findings, "error", f"Author is not aligned with CITATION.cff: {name}")
if name not in license_text:
add(findings, "error", f"Author is absent from LICENSE copyright: {name}")
publisher = manifest.get("publisher")
publisher_name = publisher.get("name") if isinstance(publisher, dict) else None
if not publisher_name:
add(findings, "error", "repository.json publisher must have a name")
elif publisher_name not in author_text:
add(findings, "error", f"Publisher is absent from AUTHOR.md: {publisher_name}")
maintainer = manifest.get("maintenance", {}).get("maintainer")
if maintainer and maintainer not in author_text:
add(findings, "error", f"Maintainer is absent from AUTHOR.md: {maintainer}")
return manifest
def validate_content_index(root: Path, findings: list[dict[str, str]]) -> dict | None:
path = root / "content-index.json"
try:
index = json.loads(read_text(path))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
add(findings, "error", f"content-index.json is invalid: {exc}")
return None
for key in CONTENT_INDEX_REQUIRED_KEYS:
if key not in index:
add(findings, "error", f"content-index.json lacks required key: {key}")
items = index.get("items")
if not isinstance(items, list):
add(findings, "error", "content-index.json items must be an array")
return index
content_ids: set[str] = set()
paths: set[str] = set()
related_references: list[tuple[str, str]] = []
for position, item in enumerate(items):
label = f"content-index.json item {position + 1}"
if not isinstance(item, dict):
add(findings, "error", f"{label} must be an object")
continue
for key in CONTENT_ITEM_REQUIRED_KEYS:
if key not in item:
add(findings, "error", f"{label} lacks required key: {key}")
content_id = item.get("content_id")
if not isinstance(content_id, str) or not content_id:
add(findings, "error", f"{label} has an invalid content_id")
elif content_id in content_ids:
add(findings, "error", f"Duplicate content_id in content-index.json: {content_id}")
else:
content_ids.add(content_id)
declared = item.get("path")
if not isinstance(declared, str) or not declared:
add(findings, "error", f"{label} has an invalid path")
else:
declared_path = Path(declared)
if declared_path.is_absolute() or ".." in declared_path.parts:
add(findings, "error", f"Unsafe content-index.json path: {declared}")
elif declared in paths:
add(findings, "error", f"Duplicate path in content-index.json: {declared}")
else:
paths.add(declared)
if not (root / declared_path).is_file():
add(findings, "error", f"Indexed content path does not exist: {declared}")
related = item.get("related_content_ids", [])
if not isinstance(related, list):
add(findings, "error", f"{label} related_content_ids must be an array")
elif isinstance(content_id, str):
related_references.extend((content_id, value) for value in related)
for source_id, related_id in related_references:
if related_id not in content_ids:
add(
findings,
"error",
f"Unknown related_content_id in content-index.json: {source_id} -> {related_id}",
)
return index
def validate_variables(
root: Path, manifest: dict | None, findings: list[dict[str, str]]
) -> dict | None:
path = root / "repository-variables.json"
try:
variables = json.loads(read_text(path))
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
add(findings, "error", f"repository-variables.json is invalid: {exc}")
return None
required = (
"schema_version",
"purpose",
"repository_profile",
"identity",
"repository",
"rights",
"skill_defaults",
"verified_by",
"verified_at",
)
for key in required:
if key not in variables:
add(findings, "error", f"repository-variables.json lacks required key: {key}")
if not manifest:
return variables
identity = variables.get("identity", {})
variable_authors = [
item.get("name") for item in identity.get("authors", []) if isinstance(item, dict)
]
manifest_authors = [
item.get("name")
for item in manifest.get("authors", [])
if isinstance(item, dict)
]
if variable_authors != manifest_authors:
add(findings, "error", "Authors differ between repository-variables.json and repository.json")
variable_publisher = identity.get("publisher", {}).get("name")
manifest_publisher = manifest.get("publisher", {}).get("name")
if variable_publisher != manifest_publisher:
add(findings, "error", "Publisher differs between repository-variables.json and repository.json")
variable_maintainer = identity.get("maintainer", {}).get("name")
manifest_maintainer = manifest.get("maintenance", {}).get("maintainer")
if variable_maintainer != manifest_maintainer:
add(findings, "error", "Maintainer differs between repository-variables.json and repository.json")
repository = variables.get("repository", {})
for key in ("repository_id", "name", "title", "canonical_url", "organization"):
if repository.get(key) != manifest.get(key):
add(
findings,
"error",
f"{key} differs between repository-variables.json and repository.json",
)
variable_rights = variables.get("rights", {})
manifest_rights = manifest.get("rights", {})
for key in ("license", "license_file"):
if variable_rights.get(key) != manifest_rights.get(key):
add(
findings,
"error",
f"{key} differs between repository-variables.json and repository.json",
)
return variables
def validate_versions(root: Path, manifest: dict | None, findings: list[dict[str, str]]) -> None:
version = read_text(root / "VERSION").strip()
if not re.fullmatch(r"\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?", version):
add(findings, "error", f"VERSION is not semantic: {version!r}")
if manifest and manifest.get("version") != version:
add(findings, "error", "VERSION differs from repository.json")
citation = read_text(root / "CITATION.cff")
match = CITATION_VERSION.search(citation)
if not match or match.group(1) != version:
add(findings, "error", "VERSION differs from or is absent in CITATION.cff")
changelog = read_text(root / "CHANGELOG.md")
if f"## [{version}]" not in changelog:
add(findings, "error", f"CHANGELOG.md lacks release heading for {version}")
if manifest:
manifest_license = manifest.get("rights", {}).get("license")
citation_match = CITATION_LICENSE.search(citation)
if citation_match and manifest_license != citation_match.group(1):
add(findings, "error", "License differs between repository.json and CITATION.cff")
def validate_markdown_links(root: Path, findings: list[dict[str, str]]) -> None:
for path in root.rglob("*.md"):
if ".git" in path.parts:
continue
text = read_text(path)
for raw_target in MARKDOWN_LINK.findall(text):
target = raw_target.strip().split(maxsplit=1)[0].strip("<>")
if (
not target
or target.startswith(("#", "http://", "https://", "mailto:"))
or "{{" in target
):
continue
local = unquote(target.split("#", 1)[0])
if local and not (path.parent / local).resolve().exists():
add(
findings,
"error",
f"Broken relative Markdown link in {path.relative_to(root)}: {target}",
)
def validate(root: Path) -> dict:
findings: list[dict[str, str]] = []
root = root.resolve()
if not root.is_dir():
add(findings, "error", "Repository path is not a directory")
return {"repository": str(root), "passed": False, "findings": findings}
for relative in REQUIRED_PATHS:
if not (root / relative).exists():
add(findings, "error", f"Missing required path: {relative}")
if findings:
missing_core = any(
item["message"].endswith(("repository.json", "VERSION", "CITATION.cff", "CHANGELOG.md"))
for item in findings
)
else:
missing_core = False
manifest = None if not (root / "repository.json").is_file() else validate_manifest(root, findings)
if (root / "content-index.json").is_file():
validate_content_index(root, findings)
if (root / "repository-variables.json").is_file():
validate_variables(root, manifest, findings)
if not missing_core:
validate_versions(root, manifest, findings)
validate_markdown_links(root, findings)
return {
"repository": str(root),
"passed": not any(item["level"] == "error" for item in findings),
"findings": findings,
}
def emit_markdown(result: dict) -> None:
print("# Repository Validation")
print(f"\n- Repository: `{result['repository']}`")
print(f"- Result: `{'PASS' if result['passed'] else 'FAIL'}`")
print("\n## Findings")
if not result["findings"]:
print("\n- No validation errors found.")
else:
for finding in result["findings"]:
print(f"\n- {finding['level'].upper()}: {finding['message']}")
def main() -> int:
args = parse_args()
result = validate(args.repository)
if args.json:
print(json.dumps(result, indent=2))
else:
emit_markdown(result)
return 0 if result["passed"] else 1
if __name__ == "__main__":
sys.exit(main())
+183
View File
@@ -0,0 +1,183 @@
"""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")