From 42f4d66349759be817d077f33dbe85b59dd092d7 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 14 Oct 2026 19:23:36 +0200 Subject: [PATCH] feat(serve): require native receipt before ignored labels --- CHANGELOG.md | 6 ++ README.md | 16 ++++-- VERSION | 2 +- contextmd/serve/card.py | 46 ++++++++++++--- contextmd/serve/report.py | 104 +++++++++++++++++++++++++++++++--- docs/map.md | 6 +- prompts/serve/label.md | 10 ++++ tests/test_card.py | 75 ++++++++++++++++++++++++- tests/test_report.py | 115 ++++++++++++++++++++++++++++++++++++++ 9 files changed, 352 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cab4a95..c05ca83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [1.1.0] - 2026-10-14 + +### Added + +- Require native context receipt before ignored labels + ## [1.0.0] - 2026-10-14 ### Changed diff --git a/README.md b/README.md index d24253b..036d353 100644 --- a/README.md +++ b/README.md @@ -218,10 +218,10 @@ model. It covers every serve the hook settled (`injected`, `truncated`, check did not find in the call's recorded output (`hidden`). Per serve it records: -- `shown`: `yes` when Chromeria found the deny text in the call's recorded - output, `no` when its check did not find it there, `unproven` otherwise - (context serves, denies on Codex and OpenCode, and denies whose check never - arrived); +- `shown`: `yes` when a Claude request record or Codex rollout proves context + receipt followed by a response, or Chromeria found the deny text in the + call's recorded output; `no` for a recorded negative; `unproven` without + usable evidence. Grok and OpenCode context serves remain unproven; - `lift`: how a deny's rule lifted (`read`, `delivered_inline`, `not_read_capped`), `open` when the session went on without that, or `pending` when nothing came after it yet; @@ -317,8 +317,12 @@ The first lines say what happened and why it matters, then give the facts. The judge labels the card with [`prompts/serve/label.md`](prompts/serve/label.md), using only the card's `allowed_labels`. `ignored` is allowed only on a serve proven shown -(`shown = yes`), and a breach on any other serve stays unlabeled. A window cut -at 60 events still allows every label its events can prove, except +(`shown = yes`), and a breach on any other serve stays unlabeled. For context, +the governed action must be marked `after_consumption`: strictly after the +first output of the consuming response, or the exact consuming call itself. +The card shows the native source, request reference and why receipt is +unproven. A window cut at 60 events still allows every label its events can +prove, except `no_governed_action`, since the governed action may come after the cut. A card the judge must not label names its gap under `no_evidence`: diff --git a/VERSION b/VERSION index 3eefcb9..9084fa2 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.0.0 +1.1.0 diff --git a/contextmd/serve/card.py b/contextmd/serve/card.py index 3c5374d..1818a38 100644 --- a/contextmd/serve/card.py +++ b/contextmd/serve/card.py @@ -44,8 +44,10 @@ def allowed_labels(card: dict) -> list[str]: if card.get("no_evidence"): return [] cut = (card.get("window") or {}).get("end") == "cap" + after = any(e.get("after_consumption") for e in card["events"] if e["role"] == "after") + ignorable = card.get("shown") == "yes" and (card["seam"] == "deny" or (card.get("consumed") and after)) return [label for label in LABELS - if (label != "ignored" or card.get("shown") == "yes") + if (label != "ignored" or ignorable) and (label != "no_governed_action" or not cut)] @@ -57,6 +59,11 @@ def check_label(card: dict, verdict: dict) -> None: if label is not None and label not in allowed_labels(card): raise LabelError(f"label {label!r} is not allowed on card {card['candidate']}" f" (shown {card.get('shown')}, no_evidence {card.get('no_evidence')})") + if label == "ignored" and card["seam"] != "deny": + action = verdict.get("governed_action") + eligible = [e["id"] for e in card["events"] if e.get("after_consumption")] + if not any(type(action) is type(eid) and action == eid for eid in eligible): + raise LabelError("ignored must cite a governed action after the model received the serve") def _event_details(command: str, ledger: Path, ids: list[int]) -> dict: @@ -195,24 +202,35 @@ def window(observer: report.Observer, command: str, row: dict) -> tuple[list[dic after, end, message = after[:WINDOW_CAP - 1], "cap", None details = _event_details(command, observer.ledger, [e["id"] for e in [trigger, *after] if e["family"] == "tool_call"]) - out = [_event(trigger, details, "trigger")] + [_event(e, details, "after") for e in after] + consumed = row.get("consumed") # report.rows validated this value before serializing it + out = [_event(trigger, details, "trigger", consumed)] + [_event(e, details, "after", consumed) for e in after] if message: out.append({"id": message["native_id"], "role": "message", "kind": message["kind"], "text": _short(message["text_excerpt"] or "")}) return out, end -def _event(e: dict, details: dict, role: str) -> dict: +def after_consumption(event: dict, consumed: dict) -> bool: + at = report._seconds(event.get("ts")) + ids = {consumed["id"]} | ({consumed["call"]} if consumed.get("call") else set()) + return (at is not None and at > consumed["at"]) or event.get("native_id") in ids + + +def _event(e: dict, details: dict, role: str, consumed: dict | None = None) -> dict: d = details.get(e["id"], {}) if e["family"] == "tool_call": tool = d.get("tool") or e.get("name") given = d.get("input") or {} call = given.get("command") if isinstance(given, dict) and "command" in given else given - return {"id": e["id"], "role": role, "kind": "tool", "tool": tool, "input": _short(call), - "status": d.get("status"), "result": _short(d.get("result") or "")} - if e["family"] == "assistant_message": - return {"id": e["id"], "role": role, "kind": "says", "text": _short((e.get("detail") or {}).get("excerpt", ""))} - return {"id": e["id"], "role": role, "kind": e["family"], "text": _short(e.get("name") or e.get("target") or "")} + result = {"id": e["id"], "role": role, "kind": "tool", "tool": tool, "input": _short(call), + "status": d.get("status"), "result": _short(d.get("result") or "")} + elif e["family"] == "assistant_message": + result = {"id": e["id"], "role": role, "kind": "says", "text": _short((e.get("detail") or {}).get("excerpt", ""))} + else: + result = {"id": e["id"], "role": role, "kind": e["family"], "text": _short(e.get("name") or e.get("target") or "")} + if consumed: + result["after_consumption"] = after_consumption(e, consumed) + return result def build(db_path: Path, observer: report.Observer, candidate: int, command: str = "agent-observer") -> dict: @@ -234,6 +252,7 @@ def build(db_path: Path, observer: report.Observer, candidate: int, command: str "harness": row["harness"], "seam": row["seam"], "moment": row["moment"], "shown": row["shown"], "lift": row["lift"], "late": row["late"], "evidence": row["evidence"], "rule": rule, "window": {"end": end, "events": len(events)}, "events": events, "no_evidence": no_evidence} + built.update({key: row[key] for key in ("consumed", "shown_source", "shown_request", "shown_reason")}) built["allowed_labels"] = allowed_labels(built) return built @@ -262,6 +281,13 @@ def _session_went_on(db_path: Path, row: dict, observer: report.Observer) -> boo def render(card: dict) -> str: trigger = next((e for e in card["events"] if e["role"] == "trigger"), None) call = f"a {trigger['tool']} call" if trigger else "a call" + proof = "" + if card.get("consumed"): + proof = (f" Native proof: {card['shown_source']}" + + (f", request {card['shown_request']}" if card.get("shown_request") else "") + + f"; first response output after the model received the serve at {card['consumed']['at']}.") + elif card.get("shown_reason"): + proof = f" Receipt: {card['shown_reason']}." lines = [ f"# Serve card {card['candidate']}", f"What happened: `{card['entry']}` was served as {SEAMS.get(card['seam'], card['seam'])} {call} on " @@ -270,7 +296,7 @@ def render(card: dict) -> str: "or show it was wrong or did not apply.", f"Facts: key `{card['key']}`; lift {card['lift'] or 'none'}; late {'yes' if card['late'] else 'no'}; " + (f"No evidence: {card['no_evidence']}." if card["no_evidence"] - else f"{card['window']['events']} events, {ENDS[card['window']['end']]}."), + else f"{card['window']['events']} events, {ENDS[card['window']['end']]}.") + proof, "", f"## Rule ({card['rule']['source']}, version {card['version']})" + (f"; the reply carried {card['rule']['rules_in_reply']} rules, this is one of them" @@ -283,6 +309,8 @@ def render(card: dict) -> str: lines += ["", "## Events"] for e in card["events"]: mark = "trigger " if e["role"] == "trigger" else "" + if "after_consumption" in e: + mark += "after consumption " if e["after_consumption"] else "before consumption " if e["kind"] == "tool": lines.append(f"[{e['id']}] {mark}{e['tool']}: {e['input']} -> {e['status']}: {e['result']}") elif e["role"] == "message": diff --git a/contextmd/serve/report.py b/contextmd/serve/report.py index 64a4bbb..8385c49 100644 --- a/contextmd/serve/report.py +++ b/contextmd/serve/report.py @@ -3,9 +3,9 @@ One row per served candidate: every outcome of a settled delivery (``SERVED``), including a deny whose text Chromeria's check did not find in the call's recorded output (``hidden``): -- ``shown``: ``yes`` when Chromeria found the deny text in the call's recorded output, ``no`` when its - check did not find it there, ``unproven`` otherwise (every context serve today, and denies on hosts - without that check or whose check never arrived); +- ``shown``: ``yes`` when native evidence proves the context reached the model, or Chromeria found + the deny text in the call's recorded output; ``no`` for a recorded negative, ``unproven`` otherwise. + Claude request records and Codex rollout input can prove context receipt; hook success cannot; - ``lift``: for a deny, how its rule lifted (``read``, ``delivered_inline``, ``not_read_capped``), ``open`` when the session went on without that, or ``pending`` when nothing came after it yet; - ``late``: a must-know-before entry served after a call its own key matched: as context on that @@ -20,21 +20,92 @@ from __future__ import annotations import json +import math import os import sqlite3 from collections import Counter +from dataclasses import asdict, dataclass from datetime import datetime, timezone from pathlib import Path SERVED = ("injected", "truncated", "unverified", "awaiting_evidence", "hidden") CANARY_PREFIX = "live-canary-" # the per-host canary entries (#21); test serves, not use DEFAULT_LEDGER = "~/.local/state/agent-observer/observer.db" # Agent Observer's default +SOURCES = {"claude": "claude_request_replay", "codex": "codex_rollout"} +SHOWN_REASONS = frozenset({ + "not_checked", "no_evidence_source", "final_input_unrecorded", "absent_from_request", "no_transcript", + "transcript_unreadable", "transcript_too_large", "unrecognized_format", "not_found", "ambiguous", + "no_model_response", "compacted", "rolled_back", "request_unverifiable", +}) class LogError(Exception): """The serving log is not one this report can read.""" +def _seconds(value): + if type(value) not in (int, float): + return None + try: + number = float(value) + except OverflowError: + return None + return number if math.isfinite(number) else None + + +def _ident(value): + return type(value) is str and 0 < len(value) <= 512 + + +@dataclass(frozen=True) +class Consumption: + """A native context-receipt proof, validated before it can grant a label.""" + source: str + record_id: str + record_at: float + turn: str | None + id: str + call: str | None + at: float + request: str | None + + +def consumption(harness, fact, raw) -> Consumption | None: + source = SOURCES.get(harness) if type(harness) is str else None + if source is None or fact != "shown" or type(raw) is not str: + return None + try: + ev = json.loads(raw) + except (ValueError, RecursionError): + return None + if type(ev) is not dict or type(ev.get("v")) is not int or ev["v"] != 1 or ev.get("source") != source: + return None + rec, con, checked = ev.get("record"), ev.get("consumed"), _seconds(ev.get("checked_at")) + if type(rec) is not dict or type(con) is not dict or checked is None: + return None + rec_at, con_at = _seconds(rec.get("at")), _seconds(con.get("at")) + slot, turn, call, request = rec.get("slot"), rec.get("turn"), con.get("call"), con.get("request") + if not (_ident(rec.get("id")) and type(slot) is int and slot >= 0 and rec_at is not None + and _ident(con.get("id")) and (call is None or _ident(call)) and con_at is not None): + return None + if source == "codex_rollout" and not (_ident(turn) and request is None): + return None + if source == "claude_request_replay" and not (turn is None and _ident(request)): + return None + if not rec_at <= con_at <= checked: + return None + return Consumption(source, rec["id"], rec_at, turn, con["id"], call, con_at, request) + + +def _reason(raw): + try: + ev = json.loads(raw) if type(raw) is str else None + except (ValueError, RecursionError): + return "unreadable" + value = ev.get("reason") if type(ev) is dict else None + return value if type(value) is str and value in SHOWN_REASONS else "unreadable" + + class Observer: """Agent Observer's ledger, opened read-only, one query per session, cached. @@ -110,6 +181,9 @@ def rows(db_path: Path, observer: Observer, since: float | None = None, candidat db = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) db.row_factory = sqlite3.Row try: + has_fact = {"shown", "shown_json"} <= {c[1] for c in db.execute("PRAGMA table_info(deliveries)")} + extra = ", dl.shown AS context_shown, dl.shown_json" if has_fact else ", NULL AS context_shown, NULL AS shown_json" + join = "LEFT JOIN deliveries dl ON dl.delivery = m.delivery" if has_fact else "" served = db.execute( f"""SELECT c.id AS candidate_id, c.entry, c.version, c.key, c.seam, c.outcome, m.owners_json, m.id AS moment_id, m.received_at, m.harness, m.kind, m.session, m.epoch, m.tool_use_id, @@ -122,10 +196,11 @@ def rows(db_path: Path, observer: Observer, since: float | None = None, candidat (SELECT om.kind FROM claims pc JOIN carries ca ON ca.delivery = pc.delivery AND ca.entry = c.entry AND ca.version = c.version JOIN candidates oc ON oc.id = ca.candidate_id JOIN moments om ON om.id = oc.moment_id - WHERE pc.candidate_id = c.id LIMIT 1) AS carried_at + WHERE pc.candidate_id = c.id LIMIT 1) AS carried_at {extra} FROM candidates c JOIN moments m ON m.id = c.moment_id LEFT JOIN deny_state d ON c.seam = 'deny' AND d.harness = m.harness AND d.session = m.session AND d.epoch = m.epoch AND d.entry = c.entry AND d.version = c.version + {join} WHERE c.outcome IN ({",".join("?" * len(SERVED))}) AND m.received_at >= ? AND (? IS NULL OR c.id = ?) ORDER BY m.received_at, c.id""", (*SERVED, since or 0, candidate, candidate)).fetchall() @@ -141,14 +216,24 @@ def rows(db_path: Path, observer: Observer, since: float | None = None, candidat after_call = (r["seam"] == "context" and r["kind"] in ("tool_result", "tool_failure")) or ( r["seam"] == "carry_print" and r["carried_at"] in ("tool_result", "tool_failure")) ev, event_id = evidence(observer, r["harness"], r["session"], r["tool_use_id"], r["received_at"]) + consumed = None + shown_reason = None + if r["seam"] in ("context", "carry_print"): + consumed = consumption(r["harness"], r["context_shown"], r["shown_json"]) + shown = "yes" if consumed else "no" if r["context_shown"] == "not_shown" else "unproven" + shown_reason = None if consumed else _reason(r["shown_json"]) + else: + shown = ("no" if r["checked"] == "hidden" or r["outcome"] == "hidden" + else "yes" if r["checked"] == "shown" else "unproven") out.append({ "moment_id": r["moment_id"], "candidate_id": r["candidate_id"], "at": r["received_at"], "harness": r["harness"], "session": r["session"], "epoch": r["epoch"], "tool_use_id": r["tool_use_id"], "entry": r["entry"], "version": r["version"], "key": r["key"], "seam": r["seam"], "moment": r["kind"], "owners": json.loads(r["owners_json"] or "{}"), "outcome": r["outcome"], - "shown": "no" if r["checked"] == "hidden" or r["outcome"] == "hidden" - else "yes" if r["checked"] == "shown" else "unproven", + "shown": shown, "shown_source": consumed.source if consumed else None, + "shown_request": consumed.request if consumed else None, "shown_reason": shown_reason, + "consumed": asdict(consumed) if consumed else None, "lift": None if r["seam"] != "deny" else r["lift_outcome"] if r["lifted"] else "open" if r["went_on"] else "pending", "late": bool(after_call and r["must_know"]), @@ -174,7 +259,7 @@ def _top(counter: Counter, n: int = 4) -> str: ("Late", lambda r: r["late"], "serves", "A before-action rule was served after its own command had already run.", "It came too late for that action and used the turn's serve budget (toolboxmd/chromeria#231)."), - ("Hidden", lambda r: r["shown"] == "no", "serves", + ("Hidden", lambda r: r["seam"] == "deny" and r["shown"] == "no", "serves", "Chromeria's check did not find this rule's text in the output recorded for the denied call.", "The rule may not have reached the agent and stays armed; on Grok the check misfires (toolboxmd/chromeria#228)."), ("Passed without reading", lambda r: r["lift"] == "not_read_capped", "rules", @@ -221,6 +306,11 @@ def render(served: list[dict], canaries: int) -> str: facts += f" Proven shown: {sum(rule(r) in proven for r in hit)} of {len(hit)}." if title == "No Observer record": facts += f" Reasons: {_top(Counter(r['evidence'] for r in hit))}." + elif title == "Not proven shown": + reasons = Counter(r["shown_reason"] for r in hit if r.get("shown_reason")) + facts += f" Hosts: {_top(Counter(r['harness'] for r in hit))}." + if reasons: + facts += f" Reasons: {_top(reasons)}." else: facts += f" Hosts: {_top(Counter(r['harness'] for r in hit))}." parts.append(f"## {title}: {len(hit)}\nWhat happened: {happened}\nWhy it matters: {why}\nFacts: {facts}") diff --git a/docs/map.md b/docs/map.md index 88b0e78..7a15b0a 100644 --- a/docs/map.md +++ b/docs/map.md @@ -59,9 +59,9 @@ flowchart TD GL["Great Library pointer and registration on every machine"] %% GL: #34 SR["6 Serve evidence report"] - %% SR: PR #38 #15 + %% SR: PR #38 PR #75 #15 SC["6 Serve card and label prompt"] - %% SC: PR #45 #15 + %% SC: PR #45 PR #75 #15 LJ["6 Labeler judge runs"] %% LJ: #15 RP["7 Twice-weekly report"] @@ -71,7 +71,7 @@ flowchart TD WF["Cue input window format"] %% WF: #20 SP["Per-row proof that a serve was shown"] - %% SP: toolboxmd/chromeria#245 + %% SP: toolboxmd/chromeria#245 PR #75 CK["Command keys fire on runs, not mentions"] %% CK: toolboxmd/chromeria#232 toolboxmd/chromeria#284 RD["Readers called by path; OpenCode reservations"] diff --git a/prompts/serve/label.md b/prompts/serve/label.md index 2eddaac..8752c0a 100644 --- a/prompts/serve/label.md +++ b/prompts/serve/label.md @@ -5,6 +5,8 @@ You are the serve-outcome judge. You get one serve card, from - the rule as it was served (`rule.text`, and `rule.target` for a pointer rule); - how it was served (`seam`, `shown`, `lift`, `late`); +- the native receipt, when proved (`consumed`, `shown_source`, `shown_request`), + or why receipt is unproven (`shown_reason`); - the events from the served call to the next message into the session, in order. The first event has `role: "trigger"`. A final `role: "message"` event is the next user or parent message. @@ -23,6 +25,12 @@ you: proven to have reached the model. When the governed action breaks a rule on any other card, return `"label": null` and say in the reason that the breach is on a serve not proven shown. Do not use another label in its place. +- On a context card with `consumed`, only an event marked + `after_consumption: true` can be an ignored governed action. The boundary is + the first response output after the model received the serve, not the + request start. A breach before it stays `"label": null`; say the action + came before the model had the rule. `ignored` must cite an eligible event + as `governed_action`. - When `window.end` is `"cap"`, the window was cut at its event limit and the governed action may come after the cut, so `no_governed_action` is not allowed. Give any other allowed label the events prove. If the events show @@ -34,6 +42,8 @@ Find the governed action first. That is the first event in the window that the rule's key and text are about: the call the rule must come before, the next call of that kind, or a decision the agent states. A rule that reached its cap or lifted does not prove the action happened; read the events. +When `consumed` is present, find the first governed action marked +`after_consumption: true`. Check the labels in this order and return the first that fits. Every label cites at least one event id. diff --git a/tests/test_card.py b/tests/test_card.py index 54882b3..b35f03c 100644 --- a/tests/test_card.py +++ b/tests/test_card.py @@ -1,3 +1,4 @@ +import copy import json import re import subprocess @@ -124,6 +125,11 @@ def window_case(self): self.event(504, "tool_call", 1004.0, tool="Bash", input={"command": "echo after"}, result="after") return n + def prove(self, candidate, **consumed): + ev = copy.deepcopy(fixture.CLAUDE_SHOWN) + ev["consumed"].update(consumed) + self.log.native_fact(candidate, json.dumps(ev)) + def test_the_card_holds_the_rule_as_served_and_the_window_up_to_the_next_message(self): text = self.card(self.window_case()).stdout head, _, rest = text.partition("\n\n") @@ -164,7 +170,7 @@ def test_a_window_cut_at_the_cap_withholds_only_no_governed_action(self): self.assertEqual(len(cut["events"]), 60) self.assertIsNone(cut["no_evidence"]) # the events it shows are evidence self.assertEqual(cut["allowed_labels"], ["irrelevant", "wrong", "followed"]) # unproven: no ignored - self.assertIn("ignored", card.allowed_labels({**cut, "shown": "yes"})) + self.assertNotIn("ignored", card.allowed_labels({**cut, "shown": "yes"})) # the flag alone is not receipt verdict = {"candidate": n, "governed_action": None, "events": [600], "reason": "x"} with self.assertRaises(card.LabelError): # the action may sit past the cut card.check_label(cut, {**verdict, "label": "no_governed_action"}) @@ -249,9 +255,74 @@ def test_ignored_is_allowed_only_on_a_serve_proven_shown(self): with self.assertRaises(card.LabelError): card.check_label(unproven, breach) card.check_label(unproven, {**breach, "label": None}) # a breach nobody proved was seen: unlabeled - self.assertIn("ignored", card.allowed_labels({**unproven, "shown": "yes"})) + self.assertNotIn("ignored", card.allowed_labels({**unproven, "shown": "yes"})) self.assertNotIn("ignored", card.allowed_labels({**unproven, "shown": "no"})) + def test_native_consumption_marks_actions_before_and_after_the_model_received_context(self): + from contextmd.serve import card + n = self.window_case() + self.prove(n) + shown = json.loads(self.card(n, "--json").stdout) + self.assertEqual(shown["shown"], "yes") + with self.assertRaises(card.LabelError): + card.check_label(shown, {"candidate": n, "label": "ignored", "governed_action": 500}) + self.assertEqual(shown["shown_source"], "claude_request_replay") + self.assertEqual(shown["shown_request"], "request-1") + self.assertEqual(shown["consumed"]["at"], 1001.0) + self.assertEqual([(e["id"], e.get("after_consumption")) for e in shown["events"] if e["role"] != "message"], + [(500, False), (502, False), (503, True)]) + self.assertIn("ignored", shown["allowed_labels"]) + for action in (500, 502, None, "u2", [], {}): + with self.subTest(action=action), self.assertRaises(card.LabelError): + card.check_label(shown, {"candidate": n, "label": "ignored", "governed_action": action, + "events": [action], "reason": "breach"}) + card.check_label(shown, {"candidate": n, "label": "ignored", "governed_action": 503, + "events": [503], "reason": "breach"}) + text = self.card(n).stdout + self.assertIn("first response output after the model received the serve", text) + self.assertIn("[503] after consumption", text) + self.assertIn("claude_request_replay", text) + self.assertIn("request-1", text) + + def test_only_the_exact_consuming_native_call_can_count_at_a_time_tie(self): + from contextmd.serve import card + n, tool = self.served() + self.event(500, "tool_call", 999.0, native_id=tool) + self.event(1, "tool_call", 1001.0, native_id="toolu_received") + self.event(502, "tool_call", 1001.0, native_id="toolu_other") + self.message("end", 1002.0, "done") + self.prove(n) + shown = json.loads(self.card(n, "--json").stdout) + self.assertEqual({e["id"]: e.get("after_consumption") for e in shown["events"] if e["role"] == "after"}, + {1: True, 502: False}) + card.check_label(shown, {"candidate": n, "label": "ignored", "governed_action": 1}) + for action in (502, True, "1"): + with self.subTest(action=action), self.assertRaises(card.LabelError): + card.check_label(shown, {"candidate": n, "label": "ignored", "governed_action": action}) + + def test_a_window_ending_before_consumption_withholds_ignored(self): + n = self.window_case() + self.prove(n, at=1002.75, call=None) + shown = json.loads(self.card(n, "--json").stdout) + self.assertEqual(shown["shown"], "yes") + self.assertNotIn("ignored", shown["allowed_labels"]) + + def test_malformed_or_unsupported_receipt_never_unlocks_the_card(self): + from contextmd.serve import card + n = self.window_case() + for ev in ([], {**fixture.CLAUDE_SHOWN, "source": None}, + {**fixture.CLAUDE_SHOWN, "source": "codex_rollout"}, + {**fixture.CLAUDE_SHOWN, "consumed": {"id": "msg-1", "at": 1001}}): + self.log.native_fact(n, json.dumps(ev)) + unproven = json.loads(self.card(n, "--json").stdout) + self.assertEqual(unproven["shown"], "unproven") + self.assertIsNone(unproven["consumed"]) + self.assertNotIn("ignored", unproven["allowed_labels"]) + with self.assertRaises(card.LabelError): + card.check_label(unproven, {"candidate": n, "label": "ignored", "governed_action": 503}) + self.log.native_fact(n, '{"v":1,"source":null,"reason":"request_unverifiable"}', fact="unknown") + self.assertIn("request_unverifiable", self.card(n).stdout) + def test_a_shown_deny_allows_ignored(self): from contextmd.serve import card n, tool = self.served(seam="deny", kind="pre_tool", checked="shown", lift="read") diff --git a/tests/test_report.py b/tests/test_report.py index c1dbb72..7da2132 100644 --- a/tests/test_report.py +++ b/tests/test_report.py @@ -1,3 +1,4 @@ +import copy import json import sqlite3 import subprocess @@ -44,6 +45,12 @@ text_excerpt TEXT NOT NULL, is_genuine INTEGER NOT NULL); """ +CLAUDE_SHOWN = { + "v": 1, "source": "claude_request_replay", "checked_at": 1003.0, + "record": {"id": "attachment-1", "slot": 0, "at": 1000.0, "turn": None}, + "consumed": {"id": "msg-1", "call": "toolu_received", "at": 1001.0, "request": "request-1"}, +} + def ledger(path, version="3"): """An Observer ledger fixture; returns an open connection for adding events.""" @@ -103,6 +110,25 @@ def carry(self, *, entry="agentsmd-version-control", kind="tool_result", harness self.db.commit() return n + def native_fact(self, candidate, raw, fact="shown"): + """A producer fact, joined by the moment's own delivery rather than a candidate claim.""" + self.db.execute("""CREATE TABLE IF NOT EXISTS deliveries (delivery TEXT PRIMARY KEY, harness TEXT NOT NULL, + moment_id INTEGER, stage TEXT NOT NULL, status INTEGER NOT NULL, body TEXT, + created_at REAL NOT NULL, expires_at REAL NOT NULL)""") + columns = {r[1] for r in self.db.execute("PRAGMA table_info(deliveries)")} + for name in ("shown", "shown_json"): + if name not in columns: + self.db.execute(f"ALTER TABLE deliveries ADD COLUMN {name} TEXT") + delivery, harness, moment = self.db.execute( + "SELECT cl.delivery, m.harness, m.id FROM claims cl JOIN candidates c ON c.id = cl.candidate_id" + " JOIN moments m ON m.id = c.moment_id WHERE c.id = ?", (candidate,)).fetchone() + self.db.execute("UPDATE moments SET delivery = ? WHERE id = ?", (delivery, moment)) + self.db.execute("""INSERT INTO deliveries (delivery, harness, moment_id, stage, status, created_at, + expires_at, shown, shown_json) VALUES (?, ?, ?, 'settled', 200, 1000, 1005, ?, ?) + ON CONFLICT(delivery) DO UPDATE SET shown = excluded.shown, shown_json = excluded.shown_json""", + (delivery, harness, moment, fact, raw)) + self.db.commit() + class ReportTest(unittest.TestCase): def setUp(self): @@ -142,6 +168,95 @@ def test_shown_is_proven_per_row(self): self.log.serve(seam="context", kind="tool_result", entry="other-fact", session="e") self.assertEqual([r["shown"] for r in self.rows()], ["yes", "unproven", "no", "unproven", "unproven"]) + def test_native_context_proof_reaches_the_json_report(self): + self.log.serve(seam="context", checked="hidden") # a claim is not the context's proof + self.log.native_fact(1, json.dumps(CLAUDE_SHOWN)) + row = self.rows()[0] + self.assertEqual(row["shown"], "yes") + self.assertEqual(row["shown_source"], "claude_request_replay") + self.assertEqual(row["shown_request"], "request-1") + self.assertEqual(row["consumed"]["at"], 1001.0) + self.assertEqual(row["consumed"]["call"], "toolu_received") + self.assertIsNone(row["shown_reason"]) + + def test_legacy_context_claims_never_grant_shown(self): + self.log.serve(seam="context", checked="shown") + row = self.rows()[0] + self.assertEqual(row["shown"], "unproven") + + def test_native_fact_uses_only_the_moment_delivery_key(self): + self.log.serve(seam="context") + self.log.native_fact(1, json.dumps(CLAUDE_SHOWN)) + self.log.db.execute("UPDATE moments SET delivery = 'another-delivery' WHERE id = 1") + self.log.db.commit() + self.assertEqual(self.rows()[0]["shown"], "unproven") + + def test_candidates_in_one_delivery_share_one_fact_without_duplicate_rows(self): + for entry in ("rule-a", "rule-b"): + self.log.serve(seam="context", entry=entry, delivery="batch") + self.log.native_fact(self.log.next, json.dumps(CLAUDE_SHOWN)) + rows = self.rows() + self.assertEqual([(r["entry"], r["shown"]) for r in rows], [("rule-a", "yes"), ("rule-b", "yes")]) + + def test_validated_native_consumption_accepts_both_sources_and_small_times(self): + from contextmd.serve import report + claude = copy.deepcopy(CLAUDE_SHOWN) + claude["record"]["at"], claude["consumed"]["at"], claude["checked_at"] = 1, 2, 3 + codex = copy.deepcopy(claude) + codex["source"] = "codex_rollout" + codex["record"]["turn"] = "native-turn-1" + codex["consumed"].pop("request") + for harness, ev in (("claude", claude), ("codex", codex)): + with self.subTest(harness=harness): + value = report.consumption(harness, "shown", json.dumps(ev)) + self.assertIsNotNone(value) + self.assertEqual(value.at, 2.0) + self.assertEqual(value.id, "msg-1") + + def test_incomplete_or_malformed_native_proof_never_grants_consumption(self): + from contextmd.serve import report + invalid = [None, "{", "null", "[]", '"text"'] + changes = [("v", True), ("v", 1.0), ("v", "1"), ("v", 2), ("source", None), + ("source", "codex_rollout"), ("consumed", None), ("consumed", [])] + for key, value in changes: + ev = copy.deepcopy(CLAUDE_SHOWN); ev[key] = value + invalid.append(json.dumps(ev)) + for part, key, value in [("record", "id", None), ("record", "id", ""), ("record", "slot", True), + ("record", "slot", -1), ("record", "slot", 0.5), ("record", "turn", "other-turn"), + ("consumed", "id", None), ("consumed", "call", []), + ("consumed", "request", None), ("record", "at", 1002), + ("consumed", "at", 1004)]: + ev = copy.deepcopy(CLAUDE_SHOWN); ev[part][key] = value + invalid.append(json.dumps(ev)) + for value in (True, "1000", float("nan"), float("inf"), 10 ** 1000): + for part in ("record", "consumed", None): + ev = copy.deepcopy(CLAUDE_SHOWN) + if part: + ev[part]["at"] = value + else: + ev["checked_at"] = value + invalid.append(json.dumps(ev)) + invalid.append('{"v":1,"checked_at":' + "1" * 5000 + '}') + for raw in invalid: + with self.subTest(raw=str(raw)[:80]): + self.assertIsNone(report.consumption("claude", "shown", raw)) + for harness in ("grok", "opencode", "cursor", "antigravity", None, []): + self.assertIsNone(report.consumption(harness, "shown", json.dumps(CLAUDE_SHOWN))) + codex = copy.deepcopy(CLAUDE_SHOWN); codex["source"] = "codex_rollout" + self.assertIsNone(report.consumption("codex", "shown", json.dumps(codex))) + codex["record"]["turn"] = "native-turn-1" # a request field still belongs only to Claude + self.assertIsNone(report.consumption("codex", "shown", json.dumps(codex))) + + def test_unknown_native_reason_is_reported_without_treating_it_as_hidden(self): + self.log.serve(seam="context") + self.log.native_fact(1, '{"v":1,"source":null,"reason":"request_unverifiable"}', fact="unknown") + row = self.rows()[0] + self.assertEqual(row["shown"], "unproven") + self.assertEqual(row["shown_reason"], "request_unverifiable") + self.assertIn("Reasons: request_unverifiable 1.", self.run_report()) + self.log.native_fact(1, "[]", fact="shown") + self.assertEqual(self.rows()[0]["shown"], "unproven") + def test_lift_outcome_of_each_deny(self): self.log.serve(checked="shown", lift="read", session="a") self.log.serve(checked="shown", lift="not_read_capped", session="b")