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
85 changes: 85 additions & 0 deletions infra/systemd/check-continuation-snapshot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""Emit one Reflex check.fact about an existing Monag continuation snapshot."""
import argparse
from datetime import datetime, timezone
import fcntl
import hashlib
import json
import os
from pathlib import Path
import tempfile
import uuid


def inspect_snapshot(path, root, now, max_age):
try:
raw = path.read_bytes()
except OSError as exc:
return {"state": "missing" if isinstance(exc, FileNotFoundError) else "unreadable"}
proof = {"bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest()}
try:
report = json.loads(raw)
if not isinstance(report, dict) or report.get("schema") != "monag.resume/v1":
return dict(proof, state="wrong-schema")
if report.get("root") != str(root) or not isinstance(report.get("projects"), list):
return dict(proof, state="wrong-workspace-or-projects")
timestamp = report["observed_at"]
observed = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
if observed.utcoffset() is None:
raise ValueError("timezone required")
except (ValueError, KeyError, AttributeError, TypeError, OverflowError, RecursionError):
return dict(proof, state="invalid-document")
age = (now - observed).total_seconds()
if age < 0:
return dict(proof, state="future-timestamp")
return dict(proof, state="stale" if age > max_age else "fresh", observed_at=timestamp,
projects=len(report["projects"]))


def remember(fact, path):
"""Atomically retain the original event identity while the same evidence persists."""
with path.with_suffix(path.suffix + ".lock").open("a") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
try:
previous = json.loads(path.read_bytes())
except FileNotFoundError:
previous = None
identity = ("event_type", "repository", "operation", "task_id", "failure_code", "status", "evidence")
if isinstance(previous, dict) and all(previous.get(key) == fact[key] for key in identity):
return previous
with tempfile.NamedTemporaryFile(dir=path.parent, mode="w", delete=False) as tmp:
name = Path(tmp.name)
try:
json.dump(fact, tmp)
tmp.flush()
os.fsync(tmp.fileno())
name.replace(path)
finally:
name.unlink(missing_ok=True)
return fact


def main():
cli = argparse.ArgumentParser(description=__doc__)
cli.add_argument("--snapshot", type=Path, required=True)
cli.add_argument("--root", type=Path, required=True)
cli.add_argument("--target", required=True, help="Stable check target in this workspace")
cli.add_argument("--max-age-seconds", type=int, required=True)
cli.add_argument("--last-observation", type=Path, help="Private state file for replay of unchanged evidence")
args = cli.parse_args()
if args.max_age_seconds <= 0:
cli.error("--max-age-seconds must be positive")
now = datetime.now(timezone.utc)
proof = inspect_snapshot(args.snapshot, args.root.resolve(), now, args.max_age_seconds)
invocation = os.environ.get("INVOCATION_ID") or uuid.uuid4().hex
fact = {"event_type": "check.fact", "operation": "ops.monag-continuation-snapshot",
"repository": "semcod/monag", "task_id": args.target, "failure_code": "unusable-snapshot",
"failure_category": proof["state"], "occurred_at": now.isoformat(),
"source_event_id": f"monag-snapshot-{invocation}-{now.isoformat()}",
"status": "success" if proof["state"] == "fresh" else "failure",
"summary": "Scheduled Monag snapshot: " + proof["state"], "evidence": proof}
print(json.dumps(remember(fact, args.last_observation) if args.last_observation else fact))


if __name__ == "__main__":
main()
49 changes: 49 additions & 0 deletions infra/systemd/test_continuation_snapshot_check.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from datetime import datetime, timezone
import json
from pathlib import Path
import runpy
import subprocess
import sys

import pytest

SCRIPT = Path(__file__).with_name("check-continuation-snapshot.py")
inspect_snapshot = runpy.run_path(str(SCRIPT))["inspect_snapshot"]
NOW = datetime(2026, 11, 24, 21, 0, tzinfo=timezone.utc)


@pytest.mark.parametrize(("change", "expected"), [
({}, "fresh"),
({"observed_at": "2026-11-24T20:58:59Z"}, "stale"),
({"observed_at": "2026-11-24T20:59:00Z"}, "fresh"),
({"observed_at": "2026-11-24T21:01:00Z"}, "future-timestamp"),
({"observed_at": "2026-11-24T21:00:00"}, "invalid-document"),
({"observed_at": 5}, "invalid-document"),
({"schema": "other"}, "wrong-schema"),
({"root": "/wrong"}, "wrong-workspace-or-projects"),
({"projects": None}, "wrong-workspace-or-projects"),
])
def test_validity_and_freshness(tmp_path, change, expected):
report = {"schema": "monag.resume/v1", "root": str(tmp_path), "projects": [], "observed_at": NOW.isoformat()}
f = tmp_path / "report.json"
f.write_text(json.dumps(dict(report, **change)))
result = inspect_snapshot(f, tmp_path, NOW, 60)
assert result["state"] == expected and result["bytes"] == f.stat().st_size


def test_failed_and_recovered_observations_share_target_and_cause(tmp_path):
path = tmp_path / "snapshot.json"
cmd = [sys.executable, str(SCRIPT), "--root", str(tmp_path), "--target", "continuation",
"--snapshot", str(path), "--max-age-seconds", "60", "--last-observation", str(tmp_path / "last.json")]
missing = json.loads(subprocess.check_output(cmd))
assert json.loads(subprocess.check_output(cmd)) == missing
path.touch()
invalid = json.loads(subprocess.check_output(cmd))
path.write_text(json.dumps({"schema": "monag.resume/v1", "root": str(tmp_path), "projects": [],
"observed_at": datetime.now(timezone.utc).isoformat()}))
recovered = json.loads(subprocess.check_output(cmd))
assert json.loads(subprocess.check_output(cmd)) == recovered
assert len({row["source_event_id"] for row in (missing, invalid, recovered)}) == 3
assert [row["status"] for row in [missing, invalid, recovered]] == ["failure", "failure", "success"]
assert [row["evidence"]["state"] for row in [missing, invalid, recovered]] == ["missing", "invalid-document", "fresh"]
assert len({(row["operation"], row["task_id"], row["failure_code"]) for row in [missing, invalid, recovered]}) == 1
1 change: 1 addition & 0 deletions project/TICKETS.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,5 @@
| **ticket-164** | [`README.md`](./ticket-164/README.md) | - | - | - | - | - |
| **ticket-165** | [`README.md`](./ticket-165/README.md) | - | - | - | - | - |
| **ticket-166** | [`README.md`](./ticket-166/README.md) | - | - | - | - | - |
| **ticket-167** | [`README.md`](./ticket-167/README.md) | - | - | - | - | - |
<!-- AUTO:TICKET_INDEX:END -->
36 changes: 36 additions & 0 deletions project/ticket-167/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Ticket 167: PLF-29793 Observe the scheduled continuation snapshot from an independent timer

- **ID**: ticket-167
- **Owner**: unresolved:human
- **Status**: IN_PROGRESS
- **Workflow state**: EDIT
- **Created**: 2026-11-24

## Goal and scope

Check the on-disk snapshot from a timer independent of the scan. Emit a Reflex fact carrying the observed cause and a content digest without publishing the project list.

## Acceptance criteria

- [x] Report missing, stale, malformed or misdirected snapshots and verified recovery under the same check identity.

## Tracking boundary

This directory contains the minimal reviewed intent. Optional participant prose
and raw command logs are not required delivery output.

<!-- ticket-radar:start -->
## Ticket Radar

Initial planned-scope estimate; advisory only, not execution or merge approval.

| Measure | Initial assessment |
| --- | --- |
| Impact score | 48/100 |
| Complexity | M |
| Estimated effort | 47 min |
| Planning budget | 30 min |
| Split recommended | yes |

Diagnostics: RADAR-ACCEPTANCE-MISSING, RADAR-BUDGET-EXCEEDED.
<!-- ticket-radar:end -->
25 changes: 25 additions & 0 deletions project/ticket-167/intent.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"schema": "new-project.intent/v3",
"ticket": "ticket-167",
"summary": "PLF-29793 Observe the scheduled continuation snapshot from an independent timer",
"workstream": "infrastructure",
"classification": {
"kind": "BUG",
"priority": "P1",
"origin": "requested"
},
"allowedPaths": [
"project/ticket-167/**",
"TODO.md",
"project/TICKETS.md",
"infra/systemd/check-continuation-snapshot.py",
"infra/systemd/test_continuation_snapshot_check.py"
],
"forbiddenPaths": [
"project/ticket-*/user-*.md"
],
"stacks": [],
"dependsOn": [],
"conflictsWith": [],
"integrationTicket": null
}