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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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`:

Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.0.0
1.1.0
46 changes: 37 additions & 9 deletions contextmd/serve/card.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)]


Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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

Expand Down Expand Up @@ -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 "
Expand All @@ -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"
Expand All @@ -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":
Expand Down
104 changes: 97 additions & 7 deletions contextmd/serve/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand Down Expand Up @@ -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,
Expand All @@ -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()
Expand All @@ -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"]),
Expand All @@ -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",
Expand Down Expand Up @@ -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}")
Expand Down
6 changes: 3 additions & 3 deletions docs/map.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand All @@ -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"]
Expand Down
Loading