added
This commit is contained in:
1 parent
aca6452f20
commit
6524457c7c
65 files changed
+2381
-192
No files matched your search
@@ -1,6 +1,8 @@
|
||||
# Deterministic Scripts
|
||||
|
||||
`future_map_pipeline.py` owns exact-tag selection, source normalization, link cleaning, media copying, hashing, stable signal generation, readiness and reasoning merging, relationship resolution, derivative application and lineage, validation, indexes, review queues, manifest, and Markdown rendering.
|
||||
`copy_future_map_tagged_files.py` owns the narrow unattended intake boundary. It mirrors exact-tag, unrestricted source JSON and referenced local media byte-for-byte into ignored `runtime/intake/` folders. It does not transform public records, render outputs, validate the historical corpus, call AI, or use Git.
|
||||
|
||||
`future_map_pipeline.py` owns downstream source normalization, link cleaning, media publishing, hashing, stable signal generation, readiness and reasoning merging, relationship resolution, derivative application and lineage, validation, indexes, review queues, manifest, and Markdown rendering.
|
||||
|
||||
Commands:
|
||||
|
||||
@@ -13,6 +15,6 @@ python future_map_pipeline.py apply-reasoning --record-id fm-signal-ID --patch P
|
||||
python future_map_pipeline.py apply-derivative --record-id fm-signal-ID --patch PATH
|
||||
```
|
||||
|
||||
`run_daily.ps1` runs deterministic sync and writes ignored local logs. `install_daily_task.ps1` installs or updates the Windows task. `publish_future_map_insights.py` preserves the former publisher command as a compatibility entry point.
|
||||
`run_daily.ps1` runs only the exact-tag intake copy and writes ignored local logs. `install_daily_task.ps1` installs or updates the Windows task. The separate 6:30 AM processing automation runs `future_map_pipeline.py sync` against `runtime/intake/` before processing new or stale records. `publish_future_map_insights.py` preserves the former publisher command as a compatibility entry point.
|
||||
|
||||
Do not hand-edit generated signal pages, collection pages, indexes, review queues, the manifest, or the digest. The daily task does not call AI, author derivatives, commit, push, or publish externally.
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Mirror exact-tag Future Map source JSON and connected files into local intake."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import filecmp
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
|
||||
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||
INSIGHTS_HUB_ROOT = SCRIPT_DIR.parent
|
||||
DEFAULT_CONFIG = INSIGHTS_HUB_ROOT / "config" / "local.json"
|
||||
DEFAULT_INTAKE_ROOT = INSIGHTS_HUB_ROOT / "runtime" / "intake"
|
||||
MEDIA_FIELDS = ("File", "Image")
|
||||
|
||||
|
||||
@dataclass
|
||||
class CopyStats:
|
||||
matched_records: int = 0
|
||||
copied_records: int = 0
|
||||
unchanged_records: int = 0
|
||||
restricted_records: int = 0
|
||||
malformed_records: list[str] = field(default_factory=list)
|
||||
preserved_unreadable_records: int = 0
|
||||
copied_files: int = 0
|
||||
unchanged_files: int = 0
|
||||
missing_files: list[str] = field(default_factory=list)
|
||||
removed_records: int = 0
|
||||
removed_files: int = 0
|
||||
|
||||
|
||||
def normalize_list(value: Any) -> list[str]:
|
||||
if value is None:
|
||||
return []
|
||||
values = value if isinstance(value, list) else [value]
|
||||
return [str(item).strip() for item in values if str(item).strip()]
|
||||
|
||||
|
||||
def has_publication_restriction(value: Any) -> bool:
|
||||
"""Return whether a source value blocks publication.
|
||||
|
||||
The master hrecord template uses ``public`` as an affirmative publishing
|
||||
state, not as a restriction. Blank values are legacy publishable records;
|
||||
every other non-empty value remains fail-closed.
|
||||
"""
|
||||
values = normalize_list(value)
|
||||
return any(item.casefold() != "public" for item in values)
|
||||
|
||||
|
||||
def local_media_names(record: dict[str, Any]) -> set[str]:
|
||||
names: set[str] = set()
|
||||
for field_name in MEDIA_FIELDS:
|
||||
for reference in normalize_list(record.get(field_name)):
|
||||
parsed = urlsplit(reference)
|
||||
if parsed.scheme or parsed.netloc:
|
||||
continue
|
||||
name = Path(reference).name
|
||||
if name:
|
||||
names.add(name)
|
||||
return names
|
||||
|
||||
|
||||
def copy_if_changed(source: Path, destination: Path) -> bool:
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
if destination.exists() and filecmp.cmp(source, destination, shallow=False):
|
||||
return False
|
||||
shutil.copy2(source, destination)
|
||||
return True
|
||||
|
||||
|
||||
def prune_files(directory: Path, expected_names: set[str], pattern: str) -> int:
|
||||
removed = 0
|
||||
if not directory.exists():
|
||||
return removed
|
||||
for path in directory.glob(pattern):
|
||||
if path.is_file() and path.name not in expected_names:
|
||||
path.unlink()
|
||||
removed += 1
|
||||
return removed
|
||||
|
||||
|
||||
def copy_tagged_files(
|
||||
source_hrecords: Path,
|
||||
source_files: Path,
|
||||
intake_root: Path,
|
||||
required_tag: str,
|
||||
preserve_unreadable_names: set[str] | None = None,
|
||||
) -> CopyStats:
|
||||
if not source_hrecords.is_dir():
|
||||
raise FileNotFoundError(f"Source hrecords folder not found: {source_hrecords}")
|
||||
if not source_files.is_dir():
|
||||
raise FileNotFoundError(f"Source files folder not found: {source_files}")
|
||||
|
||||
intake_hrecords = intake_root / "hrecords"
|
||||
intake_files = intake_root / "files"
|
||||
intake_hrecords.mkdir(parents=True, exist_ok=True)
|
||||
intake_files.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
stats = CopyStats()
|
||||
expected_records: set[str] = set()
|
||||
expected_files: set[str] = set()
|
||||
preserve_unreadable_names = preserve_unreadable_names or set()
|
||||
|
||||
for source_path in sorted(source_hrecords.glob("*.json"), key=lambda path: path.name.lower()):
|
||||
if source_path.stem.lower().startswith("hub_template"):
|
||||
continue
|
||||
try:
|
||||
record = json.loads(source_path.read_text(encoding="utf-8-sig"))
|
||||
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
||||
stats.malformed_records.append(f"{source_path.name}: {exc}")
|
||||
if source_path.name in preserve_unreadable_names:
|
||||
expected_records.add(source_path.name)
|
||||
if copy_if_changed(source_path, intake_hrecords / source_path.name):
|
||||
stats.copied_records += 1
|
||||
else:
|
||||
stats.unchanged_records += 1
|
||||
stats.preserved_unreadable_records += 1
|
||||
continue
|
||||
if required_tag not in normalize_list(record.get("HubTags")):
|
||||
continue
|
||||
|
||||
stats.matched_records += 1
|
||||
if has_publication_restriction(record.get("PublicationRestrictions")):
|
||||
stats.restricted_records += 1
|
||||
continue
|
||||
|
||||
expected_records.add(source_path.name)
|
||||
if copy_if_changed(source_path, intake_hrecords / source_path.name):
|
||||
stats.copied_records += 1
|
||||
else:
|
||||
stats.unchanged_records += 1
|
||||
|
||||
for media_name in local_media_names(record):
|
||||
expected_files.add(media_name)
|
||||
media_source = source_files / media_name
|
||||
if not media_source.is_file():
|
||||
stats.missing_files.append(f"{source_path.name}: {media_name}")
|
||||
continue
|
||||
if copy_if_changed(media_source, intake_files / media_name):
|
||||
stats.copied_files += 1
|
||||
else:
|
||||
stats.unchanged_files += 1
|
||||
|
||||
stats.removed_records = prune_files(intake_hrecords, expected_records, "*.json")
|
||||
stats.removed_files = prune_files(intake_files, expected_files, "*")
|
||||
return stats
|
||||
|
||||
|
||||
def load_settings(config_path: Path) -> tuple[Path, Path, str]:
|
||||
config = json.loads(config_path.read_text(encoding="utf-8")) if config_path.exists() else {}
|
||||
source_hrecords = os.environ.get("FUTURE_MAP_SOURCE_HRECORDS") or config.get("source_hrecords")
|
||||
source_files = os.environ.get("FUTURE_MAP_SOURCE_FILES") or config.get("source_files")
|
||||
required_tag = str(config.get("required_tag") or "Future Map")
|
||||
if not source_hrecords or not source_files:
|
||||
raise RuntimeError(
|
||||
"Set source_hrecords and source_files in config/local.json or the FUTURE_MAP_SOURCE_* environment variables."
|
||||
)
|
||||
return Path(os.path.expandvars(source_hrecords)), Path(os.path.expandvars(source_files)), required_tag
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
|
||||
parser.add_argument("--intake-root", type=Path, default=DEFAULT_INTAKE_ROOT)
|
||||
return parser
|
||||
|
||||
|
||||
def main() -> int:
|
||||
args = build_parser().parse_args()
|
||||
source_hrecords, source_files, required_tag = load_settings(args.config)
|
||||
existing_public_names = {
|
||||
path.name for path in (INSIGHTS_HUB_ROOT / "hrecords").glob("*.json") if path.is_file()
|
||||
}
|
||||
stats = copy_tagged_files(
|
||||
source_hrecords,
|
||||
source_files,
|
||||
args.intake_root,
|
||||
required_tag,
|
||||
preserve_unreadable_names=existing_public_names,
|
||||
)
|
||||
|
||||
print(f"Required tag: {required_tag}")
|
||||
print(f"Matched records: {stats.matched_records}")
|
||||
print(f"Copied records: {stats.copied_records}")
|
||||
print(f"Unchanged records: {stats.unchanged_records}")
|
||||
print(f"Skipped publication-restricted records: {stats.restricted_records}")
|
||||
print(f"Copied connected files: {stats.copied_files}")
|
||||
print(f"Unchanged connected files: {stats.unchanged_files}")
|
||||
print(f"Removed stale intake records: {stats.removed_records}")
|
||||
print(f"Removed stale intake files: {stats.removed_files}")
|
||||
print(f"Malformed source files skipped: {len(stats.malformed_records)}")
|
||||
print(f"Unreadable sources preserved as last-known-good records: {stats.preserved_unreadable_records}")
|
||||
for warning in stats.malformed_records:
|
||||
print(f"WARN malformed JSON: {warning}")
|
||||
print(f"Missing connected files: {len(stats.missing_files)}")
|
||||
for warning in stats.missing_files:
|
||||
print(f"WARN missing connected file: {warning}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except Exception as exc:
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -102,6 +102,17 @@ def normalize_list(value: Any) -> list[str]:
|
||||
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"
|
||||
@@ -116,7 +127,9 @@ def normalize_capture_type(source: dict[str, Any], warnings: list[str]) -> str:
|
||||
|
||||
|
||||
def has_publication_restrictions(value: Any) -> bool:
|
||||
return bool(normalize_list(value))
|
||||
# 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:
|
||||
@@ -1244,14 +1257,21 @@ def command_sync(args: argparse.Namespace) -> int:
|
||||
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
|
||||
target = output_hrecords / source_path.name
|
||||
if has_publication_restrictions(source.get("PublicationRestrictions")):
|
||||
quarantined += 1
|
||||
previous = load_json(target) if target.exists() else None
|
||||
@@ -1546,6 +1566,13 @@ def command_apply_reasoning(args: argparse.Namespace) -> int:
|
||||
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:
|
||||
|
||||
@@ -5,7 +5,7 @@ param(
|
||||
$ErrorActionPreference = "Stop"
|
||||
$scriptDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$insightsHubRoot = (Resolve-Path (Join-Path $scriptDirectory "..")).Path
|
||||
$pipeline = Join-Path $scriptDirectory "future_map_pipeline.py"
|
||||
$copyScript = Join-Path $scriptDirectory "copy_future_map_tagged_files.py"
|
||||
$runtimeDirectory = Join-Path $insightsHubRoot "runtime"
|
||||
$logDirectory = Join-Path $runtimeDirectory "logs"
|
||||
$logFile = Join-Path $logDirectory ("future-map-insights-hub-" + (Get-Date -Format "yyyy-MM-dd") + ".log")
|
||||
@@ -18,16 +18,15 @@ if (-not $PythonExecutable) {
|
||||
New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
|
||||
|
||||
$started = Get-Date -Format "yyyy-MM-dd HH:mm:ss zzz"
|
||||
"[$started] Starting deterministic Future Map Insights Hub preparation." | Set-Content -LiteralPath $logFile -Encoding utf8
|
||||
"[$started] Starting exact-tag Future Map intake copy." | Set-Content -LiteralPath $logFile -Encoding utf8
|
||||
|
||||
$pipelineOutput = & $PythonExecutable $pipeline sync 2>&1
|
||||
$pipelineOutput = & $PythonExecutable $copyScript 2>&1
|
||||
$exitCode = $LASTEXITCODE
|
||||
$pipelineOutput | Add-Content -LiteralPath $logFile -Encoding utf8
|
||||
|
||||
$finished = Get-Date -Format "yyyy-MM-dd HH:mm:ss zzz"
|
||||
"[$finished] Finished with exit code $exitCode. AI reasoning remains a separate skill-driven step." | Add-Content -LiteralPath $logFile -Encoding utf8
|
||||
"[$finished] Finished exact-tag intake copy with exit code $exitCode. Public transformation and AI reasoning remain separate steps." | Add-Content -LiteralPath $logFile -Encoding utf8
|
||||
|
||||
if ($exitCode -ne 0) {
|
||||
throw "Future Map Insights Hub preparation failed with exit code $exitCode. See $logFile"
|
||||
throw "Future Map exact-tag intake copy failed with exit code $exitCode. See $logFile"
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user