diff --git a/AGENTS.md b/AGENTS.md index a501c4e..d667f74 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -439,11 +439,26 @@ WARN 100–200K, DUMB>200K), so limits are a total-context budget values (presence 1.5 etc.) override them at request time and the writes converged — no long loop. -- [ ] **7. SKILL.md auditability** (`codegen.py`, `scheduler.py`, `static/app.js`) +- [x] **7. SKILL.md auditability** (`codegen.py`, `scheduler.py`, `static/app.js`) - `read_skill_contract` also yields sha256 of SKILL.md; record `contract_sha256` on the `skill_writing` trace event (+ dashboard display). - Test: the actually-sent HTTP payload's system message contains a SKILL.md phrase (harness already records request bodies). + - **Reshaped on the dev machine (2026-09-24): commit-ref provenance, not a + content hash.** A bare sha256 flags stale bodies but can't revive the old + contract; the ref is the revivable pointer. `skill_contract_ref()` + (`codegen.py`) returns `{"ref", "dirty"}`: `ref` is the short git commit + sha the contract was read under — revive with + `git show :SKILL.md` — and `dirty` records whether the working-tree + contract differed from that commit. Both degrade to `None` (never a + non-revivable hash) outside a git checkout; only a missing contract + raises, mirroring `read_skill_contract`. Recorded as `contract_ref` / + `contract_dirty` on the `skill_writing` trace event + (`scheduler._create_skill`); the dashboard shows `SKILL.md @ ` with a + `*` when dirty. Unit-tested: ref matches the real `git rev-parse --short + HEAD` in the repo, degrades off-repo, the sent HTTP payload's system + message contains the real SKILL.md text, and the ref fields round-trip + through `/api/trace`. - [x] **8. Config + AGENTS.md docs** - Update `config.example.json` codegen block and the AGENTS.md codegen diff --git a/semif_agent/codegen.py b/semif_agent/codegen.py index d3f906f..c7165fd 100644 --- a/semif_agent/codegen.py +++ b/semif_agent/codegen.py @@ -13,6 +13,7 @@ from __future__ import annotations import ast import json import select +import subprocess import sys import time import urllib.error @@ -63,6 +64,45 @@ def read_skill_contract(path: str | None = None) -> str: return contract.read_text() +def skill_contract_ref(path: str | None = None) -> dict: + """Provenance pointer for the SKILL.md revision at authoring time. + + Returns {"ref": str | None, "dirty": bool | None}. `ref` is the short git + commit sha the contract was read under — revivable with + `git show :SKILL.md` — and `dirty` records whether the working-tree + contract differed from that commit. Both are None when the contract is not + inside a git checkout (the pointer degrades to nothing rather than a + non-revivable hash). Any subprocess failure degrades the same way; only a + missing contract file raises, mirroring `read_skill_contract`. + """ + contract = Path(path) if path else DEFAULT_CONTRACT + if not contract.is_file(): + raise CodegenError(f"skill contract not found: {contract}") + directory = str(contract.parent) + try: + rev = subprocess.run( + ["git", "rev-parse", "--short", "HEAD"], + cwd=directory, + capture_output=True, + text=True, + timeout=10.0, + ) + if rev.returncode != 0: + return {"ref": None, "dirty": None} + status = subprocess.run( + ["git", "status", "--porcelain", "--", contract.name], + cwd=directory, + capture_output=True, + text=True, + timeout=10.0, + ) + except (OSError, subprocess.SubprocessError): + return {"ref": None, "dirty": None} + ref = rev.stdout.strip() or None + dirty = bool(status.stdout.strip()) if status.returncode == 0 else None + return {"ref": ref, "dirty": dirty} + + class CodegenClient: """Minimal OpenAI-compatible chat client for writing skill bodies. diff --git a/semif_agent/scheduler.py b/semif_agent/scheduler.py index 879dc4f..c063b7d 100644 --- a/semif_agent/scheduler.py +++ b/semif_agent/scheduler.py @@ -10,7 +10,12 @@ from __future__ import annotations from dataclasses import dataclass, field from typing import Callable -from .codegen import CodegenClient, CodegenError, generate_skill_body +from .codegen import ( + CodegenClient, + CodegenError, + generate_skill_body, + skill_contract_ref, +) from .decisions import DecisionRequest, Option, Request from .engine import SemIfEngine from .llm import LLMClient @@ -420,6 +425,7 @@ class Scheduler: self.tree.setdefault(category, []).append( Skill(name=draft.name, category=category, description=draft.description) ) + contract = skill_contract_ref() self.trace.append( "skill_writing", request.id, @@ -427,6 +433,8 @@ class Scheduler: skill=draft.name, description=draft.description, model=self.codegen.model if self.codegen else None, + contract_ref=contract["ref"], + contract_dirty=contract["dirty"], ) if self.codegen is None: diff --git a/semif_agent/static/app.js b/semif_agent/static/app.js index 5c1eea2..77013e3 100644 --- a/semif_agent/static/app.js +++ b/semif_agent/static/app.js @@ -123,6 +123,9 @@ function eventRow(evt) { div.textContent = `preempted ${evt.preempted}`; } else if (evt.kind === "skill_writing") { div.textContent = `writing skill ${evt.skill} — ${evt.description} (${evt.model || "codegen"})`; + if (evt.contract_ref) { + div.title = `SKILL.md @ ${evt.contract_ref}${evt.contract_dirty ? "*" : ""}`; + } } else if (evt.kind === "skill_created") { div.textContent = `created ${evt.skill}${evt.written ? " (body written)" : " (stub)"}`; div.title = evt.body || evt.description || ""; @@ -349,6 +352,12 @@ function eventNode(evt) { desc.className = "muted"; desc.textContent = evt.description || ""; body.appendChild(desc); + if (evt.contract_ref) { + const ref = document.createElement("div"); + ref.className = "muted"; + ref.textContent = `SKILL.md @ ${evt.contract_ref}${evt.contract_dirty ? "*" : ""}`; + body.appendChild(ref); + } const badge = document.createElement("span"); badge.className = "writing-badge"; badge.textContent = "writing skill body…"; diff --git a/tests/test_codegen.py b/tests/test_codegen.py index db2b318..0ccfca0 100644 --- a/tests/test_codegen.py +++ b/tests/test_codegen.py @@ -7,9 +7,11 @@ the CodegenClient itself is real, not mocked. """ import json +import subprocess import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path import pytest @@ -22,6 +24,7 @@ from semif_agent.codegen import ( generate_skill_body, parse_skill_body, read_skill_contract, + skill_contract_ref, ) from semif_agent.decisions import Request from semif_agent.skills import ( @@ -53,6 +56,34 @@ def test_read_skill_contract_loads_contract(): assert "data/skills" in text +def test_skill_contract_ref_returns_git_commit_in_repo(): + """In a git checkout the ref is the real short HEAD sha (revivable with + `git show :SKILL.md`), and dirty is a bool. Real subprocess, no + mocking.""" + repo = Path(__file__).resolve().parent.parent + git = subprocess.run( + ["git", "rev-parse", "--short", "HEAD"], cwd=repo, capture_output=True, text=True + ) + info = skill_contract_ref() + if git.returncode != 0: + assert info["ref"] is None + assert info["dirty"] is None + else: + assert info["ref"] == git.stdout.strip() + assert info["dirty"] in (True, False) + + +def test_skill_contract_ref_degrades_off_repo(tmp_path): + """Outside a git checkout the pointer degrades to None rather than a + non-revivable hash; a missing contract still raises like read_skill_contract.""" + contract = tmp_path / "SKILL.md" + contract.write_text("contract\n") + info = skill_contract_ref(str(contract)) + assert info == {"ref": None, "dirty": None} + with pytest.raises(CodegenError): + skill_contract_ref(str(tmp_path / "missing.md")) + + def test_contract_directs_reusable_self_mocked_skills(): """SKILL.md must tell the model that a body is a reusable module owning its own source of truth, not a one-shot that leans on the human for data.""" @@ -263,6 +294,25 @@ def test_generate_skill_body_end_to_end(tmp_path): httpd.server_close() +def test_sent_payload_system_message_contains_contract_phrase(): + """The real SKILL.md contract must actually reach the model: the recorded + HTTP payload's system message carries a SKILL.md phrase (no mocking — the + fake server records the real request body).""" + httpd, base = _fake_server(GOOD_BODY) + try: + client = CodegenClient(base_url=base, model="test", timeout=10) + tree = build_tree(build_skills({"skills": {}})) + draft = SkillDraft(name="probe", description="Probe the service.") + generate_skill_body(client, Request("is the service up?"), "tracking", draft, tree) + sent = httpd.RequestHandlerClass.received[0] + system = sent["messages"][0]["content"] + assert "data/skills" in system + assert read_skill_contract() in system + finally: + httpd.shutdown() + httpd.server_close() + + def test_generate_skill_body_retries_then_fails(tmp_path): httpd, base = _fake_server("this is not python at all") try: diff --git a/tests/test_dashboard_api.py b/tests/test_dashboard_api.py index 395c98a..7382f42 100644 --- a/tests/test_dashboard_api.py +++ b/tests/test_dashboard_api.py @@ -159,6 +159,8 @@ def test_skill_writing_and_created_events_in_payload(tmp_path): skill="track_live", description="Follow a package in real time.", model="qwen38-iq3s", + contract_ref="a1b2c3d", + contract_dirty=True, ) scheduler.trace.append( "skill_created", @@ -180,6 +182,8 @@ def test_skill_writing_and_created_events_in_payload(tmp_path): assert writing["skill"] == "track_live" assert "real time" in writing["description"] assert writing["model"] == "qwen38-iq3s" + assert writing["contract_ref"] == "a1b2c3d" + assert writing["contract_dirty"] is True created = next(e for e in run["events"] if e["kind"] == "skill_created") assert created["written"] is True assert created["body"] == "data/skills/tracking/track_live.py"