Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions src/github_repo_auditor/portfolio_truth_reconcile.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
discover_workspace_projects,
load_legacy_registry_rows,
load_safe_notion_project_context,
normalize_report_clock,
)
from github_repo_auditor.portfolio_truth_types import (
DERIVATION_POLICY_VERSION,
Expand Down Expand Up @@ -896,12 +897,6 @@ def _projects_at_clock(
return result


def normalize_report_clock(now: datetime) -> datetime:
if now.utcoffset() is None:
raise ValueError("The report clock must be timezone-aware.")
return now.astimezone(timezone.utc)


def build_materialization_context(
*,
workspace_root: Path,
Expand All @@ -918,7 +913,7 @@ def build_materialization_context(
now = normalize_report_clock(now or datetime.now(timezone.utc))
catalog_data = load_portfolio_catalog(catalog_path)
legacy_rows = load_legacy_registry_rows(legacy_registry_path)
notion_context = load_safe_notion_project_context() if include_notion else {}
notion_context = load_safe_notion_project_context(now=now) if include_notion else {}
notion_source_mode = str(getattr(notion_context, "source_mode", "live") or "live")
notion_observed_at = getattr(notion_context, "observed_at", None)
notion_context_carried_forward = False
Expand Down
33 changes: 28 additions & 5 deletions src/github_repo_auditor/portfolio_truth_sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import hashlib
import json
import logging
import os
import re
import subprocess
Expand All @@ -19,6 +20,8 @@
)
from github_repo_auditor.registry_parser import _normalize

logger = logging.getLogger(__name__)

MAX_CONTEXT_DEPTH = 2
MAX_CONTEXT_BYTES = 32_000
SKIP_DIRS = frozenset(
Expand Down Expand Up @@ -820,6 +823,8 @@ def load_legacy_registry_rows(path: Path | None) -> dict[str, dict[str, str]]:
def load_safe_notion_project_context(
config_dir: Path = Path("config"),
snapshot_path: Path | None = None,
*,
now: datetime | None = None,
) -> dict[str, dict[str, str]]:
raw_context = load_notion_project_context(config_dir)
source_mode = "live"
Expand All @@ -828,7 +833,7 @@ def load_safe_notion_project_context(
configured_snapshot = snapshot_path or _notion_snapshot_path_from_environment()
if configured_snapshot:
raw_context, observed_at = _load_verified_notion_snapshot_context(
configured_snapshot
configured_snapshot, now=now
)
source_mode = "verified-snapshot"
else:
Expand Down Expand Up @@ -857,8 +862,16 @@ def _notion_snapshot_path_from_environment() -> Path | None:
return Path(configured).expanduser()


def normalize_report_clock(now: datetime) -> datetime:
if now.utcoffset() is None:
raise ValueError("The report clock must be timezone-aware.")
return now.astimezone(timezone.utc)


def verified_notion_snapshot(
snapshot_path: Path,
*,
now: datetime | None = None,
) -> tuple[list[Any], datetime] | None:
"""Return a Notion snapshot's projects only if the whole receipt verifies.

Expand All @@ -872,6 +885,9 @@ def verified_notion_snapshot(
Callers that only enrich descriptive text may read the file directly; anything
deriving a write target (a Notion page id) must come through here.
"""
clock = (
normalize_report_clock(now) if now is not None else datetime.now(timezone.utc)
)
try:
payload = json.loads(snapshot_path.read_text())
except (OSError, json.JSONDecodeError):
Expand Down Expand Up @@ -906,9 +922,14 @@ def verified_notion_snapshot(
)
except ValueError:
return None
age_hours = (
datetime.now(timezone.utc) - generated_at.astimezone(timezone.utc)
).total_seconds() / 3600
if generated_at.utcoffset() is None:
# astimezone() would read an offsetless time in the host time zone.
return None
age_hours = (clock - generated_at.astimezone(timezone.utc)).total_seconds() / 3600
# Only the wall-clock verifier allows skew. A report has a fixed evidence cutoff.
if now is not None and age_hours < 0:
logger.warning("Skipping Notion snapshot dated after the report clock.")
return None
if age_hours < -(5 / 60) or age_hours > MAX_NOTION_SNAPSHOT_AGE_HOURS:
return None
content_bytes = json.dumps(
Expand All @@ -921,8 +942,10 @@ def verified_notion_snapshot(

def _load_verified_notion_snapshot_context(
snapshot_path: Path,
*,
now: datetime | None = None,
) -> tuple[dict[str, dict[str, str]], str | None]:
verified = verified_notion_snapshot(snapshot_path)
verified = verified_notion_snapshot(snapshot_path, now=now)
if verified is None:
return {}, None
projects, generated_at = verified
Expand Down
26 changes: 16 additions & 10 deletions src/github_repo_auditor/project_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,8 @@ def _read_bridge_names(bridge_db_path: Path | None) -> list[str]:

def _read_notion_projects(
notion_snapshot_path: Path | None,
*,
now: datetime | None = None,
) -> list[tuple[str, str | None]]:
"""Read ``(title, page_id)`` for every row of the live Notion snapshot.

Expand All @@ -312,23 +314,27 @@ def _read_notion_projects(
"""
if notion_snapshot_path is None or not notion_snapshot_path.exists():
return []
try:
data = json.loads(notion_snapshot_path.read_text())
except (json.JSONDecodeError, OSError):
return []
# Local import: portfolio_truth_sources reaches the catalog and context
# machinery, which sits on the other side of this module in the import graph.
from github_repo_auditor.portfolio_truth_sources import verified_notion_snapshot

ids_are_trustworthy = verified_notion_snapshot(notion_snapshot_path) is not None
verified = verified_notion_snapshot(notion_snapshot_path, now=now)
if verified is not None:
projects, _ = verified
else:
try:
data = json.loads(notion_snapshot_path.read_text())
except (ValueError, OSError):
return []
if not isinstance(data, dict) or not isinstance(data.get("projects"), list):
return []
projects = data["projects"]
rows: list[tuple[str, str | None]] = []
for project in data.get("projects", []):
for project in projects:
if not isinstance(project, dict):
continue
title = project.get("title")
if not title:
continue
page_id = project.get("page_id") if ids_are_trustworthy else None
page_id = project.get("page_id") if verified is not None else None
page_id = (
page_id.strip() if isinstance(page_id, str) and page_id.strip() else None
)
Expand Down Expand Up @@ -560,7 +566,7 @@ def resolve_entry(raw: str, *, refuse_ambiguous: bool = False) -> _Entry | None:
# The verified live snapshot is the only source of a row's page id. The
# hand-maintained static map that used to fill the gaps now serves only
# notion_export's repo-name keyspace and is not read here.
for title, page_id in _read_notion_projects(notion_snapshot_path):
for title, page_id in _read_notion_projects(notion_snapshot_path, now=generated_at):
entry = resolve_entry(title, refuse_ambiguous=True)
if entry is not None:
entry.notion_local_title = title
Expand Down
2 changes: 1 addition & 1 deletion tests/test_portfolio_truth.py
Original file line number Diff line number Diff line change
Expand Up @@ -1819,7 +1819,7 @@ def test_discovered_bare_coordinator_sibling_preserves_identity_and_mutation_pat
)
monkeypatch.setattr(
"github_repo_auditor.portfolio_truth_reconcile.load_safe_notion_project_context",
lambda: {
lambda *, now: {
"repo": {
"portfolio_call": "Maintain",
"momentum": "Stable",
Expand Down
151 changes: 151 additions & 0 deletions tests/test_portfolio_truth_notion_clock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import hashlib
import json
import os
import time
from collections.abc import Iterator
from datetime import datetime, timedelta, timezone
from pathlib import Path

import pytest

from github_repo_auditor import portfolio_truth_sources
from github_repo_auditor.portfolio_truth_publish import publish_portfolio_truth


@pytest.fixture(autouse=True)
def _restore_host_timezone() -> Iterator[None]:
saved = os.environ.get("TZ")
yield
if saved is None:
os.environ.pop("TZ", None)
else:
os.environ["TZ"] = saved
time.tzset()


def _set_host_timezone(name: str) -> None:
os.environ["TZ"] = name
time.tzset()


@pytest.mark.parametrize(
("minutes_ahead", "host_tz", "offsetless"),
[
(0, "UTC", False),
(1, "UTC", False),
(0, "UTC", True),
(0, "America/Los_Angeles", True),
],
ids=["current", "future", "offsetless-utc-host", "offsetless-pacific-host"],
)
def test_pinned_publication_clock_controls_cached_notion_freshness(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
minutes_ahead: int,
host_tz: str,
offsetless: bool,
) -> None:
_set_host_timezone(host_tz)
clock = datetime(2025, 2, 1, tzinfo=timezone.utc)
receipt_time = clock + timedelta(minutes=minutes_ahead)
if offsetless:
receipt_time = receipt_time.replace(tzinfo=None)
workspace = tmp_path / "workspace"
project = workspace / "sample"
project.mkdir(parents=True)
(project / "README.md").write_text("# Sample\n")
snapshot = tmp_path / "advisory.json"
projects = [
{"title": "sample", "portfolio_call": "Maintain", "page_id": "fixture-page"}
]
snapshot.write_text(
json.dumps(
{
"schema_version": "2.0.0",
"generated_at": receipt_time.isoformat(),
"project_count": 1,
"projects": projects,
"content_sha256": hashlib.sha256(
json.dumps(projects, separators=(",", ":")).encode()
).hexdigest(),
"live_read_receipt": {"state": "verified", "page_count": 1},
"attention_authority_receipt": {"state": "verified"},
}
)
)
monkeypatch.setenv("GHRA_NOTION_SNAPSHOT_PATH", str(snapshot))
monkeypatch.setattr(
portfolio_truth_sources, "load_notion_project_context", lambda _: {}
)
monkeypatch.setattr(
"github_repo_auditor.portfolio_truth_publish.load_source_paths",
lambda _: dict(bridge_db=None, notion_snapshot=snapshot, memory_dir=None),
)

class WallClock(datetime):
@classmethod
def now(cls, tz=None):
return wall_time.astimezone(tz)

monkeypatch.setattr(portfolio_truth_sources, "datetime", WallClock)
publications = []
for elapsed_days in (0, 30):
wall_time = clock + timedelta(days=elapsed_days)
generation = publish_portfolio_truth(
workspace_root=workspace,
output_dir=tmp_path / f"published-{elapsed_days}",
registry_output=workspace / "registry.md",
portfolio_report_output=workspace / "report.md",
catalog_path=tmp_path / "missing.yaml",
include_notion=True,
now=clock,
)
assert generation.project_registry_path is not None
registry = json.loads(generation.project_registry_path.read_text())
sample = next(
row for row in registry["entries"] if row["display_name"] == "sample"
)
assert sample["notion_local_page_id"] == (
None if offsetless or minutes_ahead else "fixture-page"
)
publications.append(
(
generation.latest_path.read_bytes(),
generation.portfolio_report_output.read_bytes(),
)
)

assert publications[0] == publications[1]
published = json.loads(publications[0][0])
if offsetless:
assert published["inputs"]["notion"]["mode"] == "unavailable"
assert published["source_summary"]["notion_context_rows"] == 0
elif minutes_ahead:
assert published["inputs"]["notion"]["mode"] == "unavailable"
assert published["source_summary"]["notion_context_rows"] == 0
assert "after the report clock" in caplog.text
else:
assert published["inputs"]["notion"]["mode"] == "verified-snapshot"
assert published["source_summary"]["notion_context_rows"] == 1


def test_registry_uses_the_page_id_from_the_verified_rows(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from github_repo_auditor.project_registry import _read_notion_projects

cache = tmp_path / "receipt.json"
cache.write_text(
json.dumps({"projects": [{"title": "sample", "page_id": "old-copy"}]})
)
observed = datetime(2025, 2, 1, tzinfo=timezone.utc)
monkeypatch.setattr(
portfolio_truth_sources,
"verified_notion_snapshot",
lambda path, **kwargs: (
[{"title": "sample", "page_id": "verified-copy"}],
observed,
),
)
assert _read_notion_projects(cache) == [("sample", "verified-copy")]
Loading