From e2dbdbf9e3a5120c49ab83640090b3c757aebc3b Mon Sep 17 00:00:00 2001 From: Tom Softreck Date: Mon, 23 Nov 2026 16:18:24 +0100 Subject: [PATCH] feat(diagnostics): emit uritime.urtlog.record/v2 events for cleanup vetos and summaries (ticket-185) --- fixos/diagnostics/project_scanner.py | 12 ++- fixos/diagnostics/urtlog_emit.py | 118 +++++++++++++++++++++++++++ project/TICKETS.md | 1 + project/ticket-185/README.md | 20 +++++ project/ticket-185/intent.json | 78 ++++++++++++++++++ tests/unit/test_urtlog_emit.py | 80 ++++++++++++++++++ 6 files changed, 308 insertions(+), 1 deletion(-) create mode 100644 fixos/diagnostics/urtlog_emit.py create mode 100644 project/ticket-185/README.md create mode 100644 project/ticket-185/intent.json create mode 100644 tests/unit/test_urtlog_emit.py diff --git a/fixos/diagnostics/project_scanner.py b/fixos/diagnostics/project_scanner.py index 9cc05f1..948ad90 100644 --- a/fixos/diagnostics/project_scanner.py +++ b/fixos/diagnostics/project_scanner.py @@ -589,12 +589,22 @@ def evaluate_cleanup_vetos( reasons.append(reason) verdict = VERDICT_HOLD_PROTECTED if codes else VERDICT_ALLOW - return CleanupVetoReport( + report = CleanupVetoReport( target=str(target), verdict=verdict, veto_codes=tuple(codes), reasons=tuple(reasons), ) + if report.protected: + from fixos.diagnostics.urtlog_emit import emit_cleanup_veto + + emit_cleanup_veto( + target=report.target, + verdict=report.verdict, + veto_codes=report.veto_codes, + reasons=report.reasons, + ) + return report def scan_project_artifacts( diff --git a/fixos/diagnostics/urtlog_emit.py b/fixos/diagnostics/urtlog_emit.py new file mode 100644 index 0000000..b89e470 --- /dev/null +++ b/fixos/diagnostics/urtlog_emit.py @@ -0,0 +1,118 @@ +"""Fail-open uritime.urtlog.record/v2 telemetry emitter for fixOS diagnostics. + +Writes structured JSONL records into ``/events.jsonl`` only when +``FIXOS_URTLOG_STATE_DIR`` or ``URTLOG_STATE_DIR`` (or an explicit ``state_dir``) +is configured. Never raises and adds zero external runtime dependencies. +""" + +from __future__ import annotations + +import json +import os +import socket +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +URTLOG_RECORD_SCHEMA = "uritime.urtlog.record/v2" +FIXOS_ACTOR = "semcod:fixos" + + +def resolve_urtlog_state_dir(state_dir: str | Path | None = None) -> Path | None: + """Return configured URTLog state directory, or ``None`` if disabled.""" + if state_dir is not None: + raw = str(state_dir).strip() + return Path(raw).expanduser() if raw else None + raw_env = ( + os.environ.get("FIXOS_URTLOG_STATE_DIR") + or os.environ.get("URTLOG_STATE_DIR") + or "" + ).strip() + return Path(raw_env).expanduser() if raw_env else None + + +def emit_urtlog_record( + *, + action: str, + uri: str, + status: str = "succeeded", + kind: str = "log", + stage: str = "completed", + details: dict[str, Any] | None = None, + state_dir: str | Path | None = None, +) -> bool: + """Append one ``uritime.urtlog.record/v2`` record to ``events.jsonl``.""" + target_dir = resolve_urtlog_state_dir(state_dir) + if target_dir is None: + return False + + record: dict[str, Any] = { + "schema": URTLOG_RECORD_SCHEMA, + "kind": kind, + "stage": stage, + "status": status, + "actor": FIXOS_ACTOR, + "action": action, + "uri": uri, + "timestamp": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"), + "host": socket.gethostname(), + } + if details: + record["details"] = details + + try: + target_dir.mkdir(parents=True, exist_ok=True) + events_path = target_dir / "events.jsonl" + with events_path.open("a", encoding="utf-8") as fh: + fh.write(json.dumps(record, ensure_ascii=False) + "\n") + return True + except OSError: + return False + + +def emit_cleanup_veto( + *, + target: str, + verdict: str, + veto_codes: tuple[str, ...] | list[str], + reasons: tuple[str, ...] | list[str], + state_dir: str | Path | None = None, +) -> bool: + """Emit a structured URTLog event when a hard cleanup veto protects a workspace.""" + return emit_urtlog_record( + action="fixos.cleanup_veto", + uri="proc://semcod/fixos/project-scanner/veto/v1", + status="blocked", + details={ + "target": target, + "verdict": verdict, + "veto_codes": list(veto_codes), + "reasons": list(reasons), + }, + state_dir=state_dir, + ) + + +def emit_cleanup_summary( + *, + mode: str, + reclaimed_bytes: int, + steps: list[str], + dry_run: bool = False, + errors: list[str] | None = None, + state_dir: str | Path | None = None, +) -> bool: + """Emit a structured URTLog event summarizing a fixOS cleanup run.""" + return emit_urtlog_record( + action="fixos.cleanup_summary", + uri="proc://semcod/fixos/cleanup/v1", + status="failed" if errors else "succeeded", + details={ + "mode": mode, + "reclaimed_bytes": int(reclaimed_bytes), + "steps": list(steps), + "dry_run": bool(dry_run), + "errors": list(errors or []), + }, + state_dir=state_dir, + ) diff --git a/project/TICKETS.md b/project/TICKETS.md index daaf70d..bff0dc4 100644 --- a/project/TICKETS.md +++ b/project/TICKETS.md @@ -180,4 +180,5 @@ This file indexes governance tickets without taking ownership of | **ticket-182** | [`README.md`](./ticket-182/README.md) | - | - | - | - | - | | **ticket-183** | [`README.md`](./ticket-183/README.md) | - | - | - | - | - | | **ticket-184** | [`README.md`](./ticket-184/README.md) | - | - | - | - | - | +| **ticket-185** | [`README.md`](./ticket-185/README.md) | - | - | - | - | - | diff --git a/project/ticket-185/README.md b/project/ticket-185/README.md new file mode 100644 index 0000000..138da4c --- /dev/null +++ b/project/ticket-185/README.md @@ -0,0 +1,20 @@ +# Ticket 185: Emit uritime urtlog records for fixos diagnostics and cleanup vetos + +- **ID**: ticket-185 +- **Owner**: agent:antigravity (SESSION_EXECUTION_AUTHORIZATION from user request) +- **Status**: IN_PROGRESS +- **Workflow state**: EDIT +- **Created**: 2026-11-23 + +## Goal and scope + +Add a fail-open, zero-dependency `uritime.urtlog.record/v2` telemetry emitter in +`fixos/diagnostics/urtlog_emit.py` and wire `evaluate_cleanup_vetos` in +`fixos/diagnostics/project_scanner.py` to record `HOLD_PROTECTED` cleanup vetos +when `FIXOS_URTLOG_STATE_DIR` or `URTLOG_STATE_DIR` is configured. + +## Acceptance criteria + +- [x] AC-01: `fixos/diagnostics/urtlog_emit.py` emits valid `uritime.urtlog.record/v2` JSONL records when configured, stays no-op when unconfigured, and fails open on `OSError`. +- [x] AC-02: `evaluate_cleanup_vetos` emits a `fixos.cleanup_veto` record whenever a hard veto forces `HOLD_PROTECTED`. +- [x] AC-03: Unit tests in `tests/unit/test_urtlog_emit.py` and `tests/unit/test_project_scanner.py` pass alongside `./project/governance-check.sh`. diff --git a/project/ticket-185/intent.json b/project/ticket-185/intent.json new file mode 100644 index 0000000..d82a769 --- /dev/null +++ b/project/ticket-185/intent.json @@ -0,0 +1,78 @@ +{ + "schema": "new-project.intent/v3", + "ticket": "ticket-185", + "summary": "Emit uritime urtlog records for fixos diagnostics and cleanup vetos", + "workstream": "application", + "classification": { + "kind": "SERVICE", + "priority": "P1", + "origin": "requested" + }, + "allowedPaths": [ + "project/ticket-185/**", + "TODO.md", + "project/TICKETS.md", + "fixos/diagnostics/urtlog_emit.py", + "fixos/diagnostics/project_scanner.py", + "tests/unit/test_urtlog_emit.py" + ], + "forbiddenPaths": [ + "project/ticket-*/user-*.md" + ], + "stacks": [], + "dependsOn": [], + "conflictsWith": [], + "integrationTicket": null, + "delivery": { + "targetBranch": "main", + "acceptedBaseSha": "2b15b92a35a3c56f6b8cb72c147d1ec129b0498f", + "outcome": "Add fail-open uritime.urtlog.record/v2 emitter in fixos/diagnostics/urtlog_emit.py and emit veto telemetry from evaluate_cleanup_vetos.", + "complexity": "S", + "estimatedMinutes": 20, + "budgets": { + "maxImplementationFiles": 3, + "maxAffectedComponents": 1, + "maxPublicInterfaceChanges": 1, + "maxRuntimeDependencies": 0 + }, + "runtimeDependencies": [], + "nonGoals": [ + "Touching fixos/cli/fix_cmd.py or any file reserved by foreign leases." + ], + "architecture": { + "status": "accepted", + "decision": "Introduce fixos/diagnostics/urtlog_emit.py with fail-open JSONL emission controlled by FIXOS_URTLOG_STATE_DIR / URTLOG_STATE_DIR and invoke emit_cleanup_veto when evaluate_cleanup_vetos returns HOLD_PROTECTED.", + "components": [ + { + "name": "fixos urtlog telemetry emitter", + "paths": [ + "fixos/diagnostics/urtlog_emit.py", + "fixos/diagnostics/project_scanner.py", + "tests/unit/test_urtlog_emit.py" + ] + } + ], + "responsibilityChanges": false, + "interfaceChanges": [ + "Add fixos.diagnostics.urtlog_emit (emit_urtlog_record, emit_cleanup_veto, emit_cleanup_summary)" + ], + "dataChanges": [], + "ui": { + "impact": "none", + "states": [], + "evidence": [] + }, + "rollback": "Revert the commit adding fixos/diagnostics/urtlog_emit.py and its call in fixos/diagnostics/project_scanner.py." + }, + "validation": [ + { + "criterion": "AC-01", + "commands": [ + "python -m pytest -q tests/unit/test_urtlog_emit.py tests/unit/test_project_scanner.py", + "./project/governance-check.sh" + ], + "evidence": "Unit tests verify uritime.urtlog.record/v2 emission, no-op when unconfigured, fail-open on OSError, and veto event emission from evaluate_cleanup_vetos." + } + ] + } +} diff --git a/tests/unit/test_urtlog_emit.py b/tests/unit/test_urtlog_emit.py new file mode 100644 index 0000000..d47558b --- /dev/null +++ b/tests/unit/test_urtlog_emit.py @@ -0,0 +1,80 @@ +"""Unit tests for fail-open uritime.urtlog.record/v2 emission in fixOS.""" + +from __future__ import annotations + +import json + +from fixos.diagnostics import project_scanner as ps +from fixos.diagnostics.urtlog_emit import ( + FIXOS_ACTOR, + URTLOG_RECORD_SCHEMA, + emit_cleanup_summary, + emit_cleanup_veto, + emit_urtlog_record, +) + + +def test_emit_urtlog_record_noop_when_unconfigured(monkeypatch): + monkeypatch.delenv("FIXOS_URTLOG_STATE_DIR", raising=False) + monkeypatch.delenv("URTLOG_STATE_DIR", raising=False) + assert emit_urtlog_record(action="fixos.test", uri="proc://semcod/fixos/test/v1") is False + + +def test_emit_cleanup_summary_writes_valid_v2_record(tmp_path, monkeypatch): + monkeypatch.setenv("URTLOG_STATE_DIR", str(tmp_path)) + ok = emit_cleanup_summary( + mode="auto", + reclaimed_bytes=1024 * 1024, + steps=["user-cache", "docker-build-cache"], + dry_run=False, + ) + assert ok is True + events_file = tmp_path / "events.jsonl" + assert events_file.is_file() + records = [json.loads(line) for line in events_file.read_text(encoding="utf-8").splitlines()] + assert len(records) == 1 + rec = records[0] + assert rec["schema"] == URTLOG_RECORD_SCHEMA + assert rec["actor"] == FIXOS_ACTOR + assert rec["action"] == "fixos.cleanup_summary" + assert rec["status"] == "succeeded" + assert rec["details"]["reclaimed_bytes"] == 1024 * 1024 + assert rec["details"]["steps"] == ["user-cache", "docker-build-cache"] + + +def test_emit_cleanup_veto_fail_open_on_unwritable_path(tmp_path): + blocker = tmp_path / "not-a-dir" + blocker.write_text("file", encoding="utf-8") + ok = emit_cleanup_veto( + target="/tmp/demo", + verdict="HOLD_PROTECTED", + veto_codes=("VETO_ACTIVE_LEASE",), + reasons=("Active lease",), + state_dir=blocker, + ) + assert ok is False + + +def test_project_scanner_emits_urtlog_on_hard_veto(tmp_path, monkeypatch): + urtlog_dir = tmp_path / "urtlog" + monkeypatch.setenv("FIXOS_URTLOG_STATE_DIR", str(urtlog_dir)) + + proj = tmp_path / "leased_repo" + (proj / ".git").mkdir(parents=True) + lease_dir = proj / ".subactor" / "leases" + lease_dir.mkdir(parents=True) + (lease_dir / "ticket-001--demo.json").write_text( + json.dumps({"ticketId": "ticket-001", "phase": "claimed", "ownerActor": "agent:codex"}), + encoding="utf-8", + ) + + report = ps.evaluate_cleanup_vetos(proj) + assert report.verdict == ps.VERDICT_HOLD_PROTECTED + events_file = urtlog_dir / "events.jsonl" + assert events_file.is_file() + records = [json.loads(line) for line in events_file.read_text(encoding="utf-8").splitlines()] + assert len(records) == 1 + assert records[0]["schema"] == URTLOG_RECORD_SCHEMA + assert records[0]["action"] == "fixos.cleanup_veto" + assert records[0]["status"] == "blocked" + assert ps.VETO_ACTIVE_LEASE in records[0]["details"]["veto_codes"]