2026-11-09 13:34:58 -07:00
"""Date boundaries, evidence validation and coverage-aware local finalization."""
2026-10-14 12:05:54 -06:00
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" }
2026-10-20 16:14:03 -06:00
METHODS = { "standard_web" , "exa" , "direct" , "gmail" }
2026-10-14 12:05:54 -06:00
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" )
2026-11-09 13:34:58 -07:00
require ( e [ "status" ] in { "complete" , "completed-with-gaps" , "incomplete" }, "Unknown run status" )
2026-10-14 12:05:54 -06:00
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" )
2026-10-20 16:14:03 -06:00
config = read ( root / "config/research.json" )
gmail_config = config . get ( "gmail_candidate_source" , {})
gmail_active = bool ( gmail_config ) and e [ "run_date" ] >= gmail_config [ "enabled_from_run_date" ]
expected_pools = POOLS | ({ "gmail_brandemails" } if gmail_active else set ())
require ( set ( e [ "coverage" ]) == expected_pools , "Missing coverage pools" )
if gmail_active :
collection = e . get ( "gmail_collection" , {})
require ( collection . get ( "status" ) == e [ "coverage" ][ "gmail_brandemails" ], "Gmail coverage mismatch" )
for key in ( "pages_read" , "messages_enumerated" , "messages_screened" ):
require ( type ( collection . get ( key )) is int and collection [ key ] >= 0 , "Invalid Gmail collection count: " + key )
require ( collection [ "messages_screened" ] <= collection [ "messages_enumerated" ], "Gmail screening exceeds enumeration" )
for key in ( "enumeration_complete" , "screening_complete" ):
require ( type ( collection . get ( key )) is bool , "Missing Gmail completeness: " + key )
require ( isinstance ( collection . get ( "limitations" ), list ), "Missing Gmail limitations" )
if collection [ "status" ] == "complete" :
require ( collection [ "enumeration_complete" ] and collection [ "screening_complete" ] and
collection [ "messages_screened" ] == collection [ "messages_enumerated" ] and
collection [ "pages_read" ] > 0 and not collection [ "limitations" ], "Incomplete Gmail scan" )
else :
require ( bool ( collection [ "limitations" ]), "Missing Gmail coverage limitation" )
2026-10-14 12:05:54 -06:00
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" :
2026-10-20 16:14:03 -06:00
require ( s [ "format" ] in { "publisher_transcript" , "show_notes" , "outline" , "audio_transcribed" , "provided_speech_to_text" }, "Podcast format overclaim" )
2026-10-14 12:05:54 -06:00
for k in ( "episode_title" , "speaker" , "timestamps" ):
require ( bool ( s [ k ]), "Podcast field missing: " + k )
2026-10-20 16:14:03 -06:00
if s . get ( "podcast_series" ) in { "sia_inside_line" , "sia_other" }:
require ( s [ "kind" ] == "podcast" and s [ "format" ] in { "publisher_transcript" , "provided_speech_to_text" }, "SIA podcast requires provided transcript text" )
require ( s . get ( "transcript_url" , "" ) . startswith ( "https://" ) and bool ( s . get ( "transcript_provider" )), "SIA transcript provenance missing" )
require ( s . get ( "transcript_completeness" ) in { "full" , "partial" } and isinstance ( s . get ( "transcript_limitations" ), list ), "SIA transcript completeness missing" )
require ( s [ "transcript_completeness" ] != "partial" or bool ( s [ "transcript_limitations" ]), "Partial SIA transcript needs limitations" )
2026-10-31 14:55:34 -06:00
if s . get ( "podcast_series" ) in { "outdoor_unfiltered" , "eoin_comerford_other" }:
require ( s [ "kind" ] == "podcast" and s [ "format" ] in { "publisher_transcript" , "provided_speech_to_text" }, "Outdoor Unfiltered/Eoin requires provided transcript text" )
require ( bool ( s . get ( "transcript_provider" )) and ( s . get ( "transcript_url" , "" ) . startswith ( "https://" ) or bool ( s . get ( "transcript_file" ))), "Outdoor Unfiltered/Eoin transcript provenance missing" )
if s . get ( "transcript_file" ):
require ( bool ( s . get ( "transcript_original_filename" )) and re . fullmatch ( r "[0-9a-fA-F] {64} " , s . get ( "transcript_sha256" , "" )), "Transcript file provenance missing" )
require ( s . get ( "transcript_completeness" ) in { "full" , "partial" } and isinstance ( s . get ( "transcript_limitations" ), list ), "Transcript completeness missing" )
require ( s [ "transcript_completeness" ] != "partial" or bool ( s [ "transcript_limitations" ]), "Partial transcript needs limitations" )
2026-11-09 13:34:58 -07:00
completed = e [ "status" ] in { "complete" , "completed-with-gaps" }
if success :
require ( completed , "Incomplete research cannot finalize" )
if completed :
require ( receipt [ "validation_passed" ] is True , "Receipt validation failed" )
partial = e [ "status" ] == "completed-with-gaps"
if partial :
require ( receipt [ "capture_completeness" ] == "partial" and bool ( receipt [ "gaps" ]), "Partial completion needs explicit gaps" )
require ( all ( isinstance ( g , str ) and g . strip () and g in body for g in receipt [ "gaps" ]), "Every gap must be disclosed in report" )
require ( e . get ( "verified_subset_reviewed" ) is True , "Verified subset review missing" )
require ( bool ( e [ "sources" ]), "Partial completion needs verified material" )
else :
require ( all ( v == "complete" for v in e [ "coverage" ] . values ()), "Incomplete coverage cannot claim complete" )
require ( not receipt [ "gaps" ], "Complete receipt has gaps" )
2026-10-14 12:05:54 -06:00
config = read ( root / "config/research.json" )
for method in ( "standard_web" , "exa" ):
2026-11-09 13:34:58 -07:00
if e [ "coverage" ][ method ] != "complete" :
continue
2026-10-14 12:05:54 -06:00
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" ):
2026-11-09 13:34:58 -07:00
if e [ "coverage" ][ pool ] != "complete" :
continue
2026-10-14 12:05:54 -06:00
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" ]
2026-11-09 13:34:58 -07:00
if partial and pb . get ( "status" ) == "unavailable" :
require ( not pb . get ( "sections" ) and bool ( pb . get ( "limitation" )) and pb [ "limitation" ] in receipt [ "gaps" ], "Unavailable playbook must omit mappings and disclose limitation" )
return e
2026-10-14 12:05:54 -06:00
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" ]]
2026-11-09 13:34:58 -07:00
require ( len ( matches ) == 1 and matches [ 0 ][ "status" ] in { "complete" , "completed-with-gaps" }, "Catalog item lacks unique completed evidence" )
2026-10-14 12:05:54 -06:00
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 ( 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" )
2026-11-09 13:34:58 -07:00
if e [ "status" ] == "completed-with-gaps" :
catalog [ "description" ] += " Completed with explicitly disclosed coverage gaps."
require ( existing is None or existing == catalog , "Existing run ID points to different catalog metadata" )
checkpoint = root / ( "state/last-completed-with-gaps-run.json" if e [ "status" ] == "completed-with-gaps" else "state/last-successful-run.json" )
2026-10-14 12:05:54 -06:00
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 )
2026-11-09 13:34:58 -07:00
return { "status" : e [ "status" ], "run_id" : e [ "run_id" ]}
2026-10-14 12:05:54 -06:00
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 " )