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
12 changes: 11 additions & 1 deletion fixos/diagnostics/project_scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
118 changes: 118 additions & 0 deletions fixos/diagnostics/urtlog_emit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
"""Fail-open uritime.urtlog.record/v2 telemetry emitter for fixOS diagnostics.

Writes structured JSONL records into ``<state_dir>/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,
)
1 change: 1 addition & 0 deletions project/TICKETS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) | - | - | - | - | - |
<!-- AUTO:TICKET_INDEX:END -->
20 changes: 20 additions & 0 deletions project/ticket-185/README.md
Original file line number Diff line number Diff line change
@@ -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`.
78 changes: 78 additions & 0 deletions project/ticket-185/intent.json
Original file line number Diff line number Diff line change
@@ -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."
}
]
}
}
80 changes: 80 additions & 0 deletions tests/unit/test_urtlog_emit.py
Original file line number Diff line number Diff line change
@@ -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"]
Loading