From 110b4deac86bc49a9762e0aa0defe731c87c0c6d Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 18:50:10 +0100 Subject: [PATCH 01/44] wip: record response checkout evidence during legacy placement sync --- agent_observer/placement.py | 423 ++++++++++++++---------------------- tests/test_codex_fork.py | 21 +- tests/test_placement.py | 199 ++++++++++------- 3 files changed, 298 insertions(+), 345 deletions(-) diff --git a/agent_observer/placement.py b/agent_observer/placement.py index ecf395f..1b15683 100644 --- a/agent_observer/placement.py +++ b/agent_observer/placement.py @@ -1,30 +1,22 @@ -"""Place each response of a session shared by several PRs on one PR (#43). +"""Legacy checkout placement for sessions shared by T3 PR links. -A T3 thread linked to several PRs binds its sessions whole to every one of -them. Within such a session, a response belongs to a PR when the paths its -tool calls name lie in a checkout of that PR's repository on that PR's head -branch. A response matching no PR, or more than one, stays unplaced and is -reported apart from every PR's headline. - -Checkouts are recorded in the ledger when first seen, so placement still -works after a task's worktree is removed. +Sync records what checkout each tool path was observed in, with its event +and response. Reports match those observations against the current PR links. +A checkout path can be reused without changing an earlier observation. """ from __future__ import annotations import bisect +import hashlib import os import re -import sqlite3 import subprocess -import time from .db import _has_table -# Harnesses whose tool calls can be tied to the response that made them. -# Claude writes the tool_use in the response's own record, so a call -# belongs to the latest response at or before it. Codex reports usage -# after the response's items, so a call belongs to the next response. +# Claude writes tool_use in the response record. Codex reports usage after +# the response's items. CALL_FOLLOWS_RESPONSE = {"claude": True, "codex": False} PATH_RE = re.compile(r"(?(){}\[\],=]*") @@ -40,268 +32,189 @@ def _git(root: str, *args: str) -> str | None: return out.stdout.strip() if out.returncode == 0 else None -def _known_checkouts(con) -> list: - return con.execute( - "SELECT root, repository, branch FROM checkouts ORDER BY length(root) DESC" - ).fetchall() - - -def checkout_of(con, path: str, known: list | None = None, - roots: dict | None = None): - """(repository, branch) of the checkout holding path, or None. - - A checkout that still exists is read live through git and its record - refreshed, so a reused path never keeps a stale repository or branch. - Only a removed checkout falls back to its recorded mapping. Detached - checkouts record no branch and so match no PR. - """ - path = os.path.normpath(os.path.expanduser(path)) - probe = path - while probe and probe != os.path.dirname(probe): - if os.path.exists(os.path.join(probe, ".git")): - return _live(con, probe, known, roots) - probe = os.path.dirname(probe) - for row in known if known is not None else _known_checkouts(con): - if path == row["root"] or path.startswith(row["root"] + "/"): - if not os.path.exists(row["root"]): - return row["repository"], row["branch"] - return None - - -def _write(con, sql: str, args: tuple) -> None: - """Record a checkout; `task` and `publish` read a read-only ledger, - where the live answer still applies and only the record is skipped.""" - try: - con.execute(sql, args) - except sqlite3.OperationalError: - pass - - -def _end_write(con) -> None: - """Commit an open write so the next git call is outside it. - - A read-only report holds BEGIN for one snapshot. COMMIT succeeds on - that connection and would end the snapshot. `PRAGMA query_only` is - off for a normal `mode=ro` open, and SAVEPOINT itself does not write, - so the probe writes a row inside the savepoint and removes it before - release. A connection that cannot write leaves its transaction open. - """ - if not con.in_transaction: - return - try: - con.execute("SAVEPOINT ao_write_probe") - con.execute( - "INSERT OR REPLACE INTO schema_meta(key, value)" - " VALUES('ao_write_probe', '1')") - con.execute("DELETE FROM schema_meta WHERE key='ao_write_probe'") - con.execute("RELEASE ao_write_probe") - except sqlite3.OperationalError: - try: - con.execute("ROLLBACK TO ao_write_probe") - con.execute("RELEASE ao_write_probe") - except sqlite3.OperationalError: - pass - return - try: - con.commit() - except sqlite3.OperationalError: - pass - - -def _live(con, root: str, known: list | None, roots: dict | None): - if roots is not None and root in roots: - return roots[root] - _end_write(con) - remote = _git(root, "remote", "get-url", "origin") or "" - match = REMOTE_RE.search(remote) - found = None - if match is not None: - branch = _git(root, "rev-parse", "--abbrev-ref", "HEAD") - branch = branch if branch and branch != "HEAD" else None - found = (match.group(1), branch) - _write(con, "INSERT OR REPLACE INTO checkouts(root, repository, branch, seen_at)" - " VALUES(?,?,?,?)", (root, found[0], branch, time.time())) - _end_write(con) - if known is not None: - known[:] = [r for r in known if r["root"] != root] - known.append({"root": root, "repository": found[0], "branch": branch}) - known.sort(key=lambda r: -len(r["root"])) - else: - # No recognizable origin now: drop the old mapping so it cannot - # answer for this path after the checkout is removed. - _write(con, "DELETE FROM checkouts WHERE root=?", (root,)) - _end_write(con) - if known is not None: - known[:] = [r for r in known if r["root"] != root] - if roots is not None: - roots[root] = found - return found +def _checkout(path: str, roots: dict) -> tuple: + root = os.path.normpath(os.path.expanduser(path)) + while root != os.path.dirname(root): + if os.path.exists(os.path.join(root, ".git")): + if root not in roots: + remote = _git(root, "remote", "get-url", "origin") or "" + match = REMOTE_RE.search(remote) + branch = _git(root, "rev-parse", "--abbrev-ref", "HEAD") if match else None + roots[root] = (match.group(1) if match else None, + branch if branch != "HEAD" else None) + return roots[root] + root = os.path.dirname(root) + return None, None + + +def _legacy_session(con, session_key): + rows = con.execute( + "SELECT s.harness, a.evidence, a.task_id FROM sessions s" + " JOIN session_assignments a USING(session_key) WHERE s.session_key=?", + (session_key,)).fetchall() + if (len(rows) < 2 or rows[0]["harness"] not in CALL_FOLLOWS_RESPONSE + or any(r["evidence"] != "t3" and not r["evidence"].startswith("t3:") + for r in rows)): + return None + return rows[0]["harness"], [r["task_id"] for r in rows] -def task_heads(con, task_ids) -> dict: - """task_id -> (repository, head branch) for linked PRs with a known head.""" - heads = {} - for t in task_ids: - repo, _, number = t.rpartition("#") - row = con.execute( - "SELECT head_branch FROM t3_links WHERE kind='pr' AND repository=?" - " AND number=? AND head_branch IS NOT NULL LIMIT 1", - (repo, int(number) if number.isdigit() else -1)).fetchone() - if row is not None: - heads[t] = (repo, row["head_branch"]) - return heads +def _task_heads(con, task_ids): + by_head = {} + if "head_branch" not in {r["name"] for r in con.execute("PRAGMA table_info(t3_links)")}: + return by_head + for task in task_ids: + repo, _, number = task.rpartition("#") + for row in con.execute( + "SELECT DISTINCT head_branch FROM t3_links WHERE kind='pr'" + " AND repository=? AND number=? AND head_branch IS NOT NULL", + (repo, number)): + by_head.setdefault((repo, row["head_branch"]), set()).add(task) + return by_head -def session_tasks(con, session_key: str) -> list: - return [r["task_id"] for r in con.execute( - "SELECT task_id FROM session_assignments WHERE session_key=?", - (session_key,))] +def _has_occurrences(con, session_key: str) -> bool: + return _has_table(con, "codex_occurrences") and con.execute( + "SELECT 1 FROM codex_occurrences WHERE session_key=? LIMIT 1", + (session_key,)).fetchone() is not None -def place_session(con, session_key: str, known: list | None = None, - roots: dict | None = None) -> dict | None: - """response_id -> task_id (or None when unplaced) for one shared session. +def _occurrence_owners(con, session_key, live_ids): + """A call's owner is the next live response in each witnessing source. - None when the harness cannot tie tool calls to responses, so the - session keeps whole-session sharing. `known` and `roots` are optional - and cover one sync; omitted, this call resolves checkouts itself. + A source with no following response supplies no witness. Disagreeing + witnesses leave the call unplaced, regardless of import order. """ - session = con.execute("SELECT harness, project_dir FROM sessions WHERE session_key=?", - (session_key,)).fetchone() - if session is None or session["harness"] not in CALL_FOLLOWS_RESPONSE: - return None - follows = CALL_FOLLOWS_RESPONSE[session["harness"]] - heads = task_heads(con, session_tasks(con, session_key)) - if not heads: - return None - by_head = {head: task for task, head in heads.items()} - if session["harness"] == "codex" and _has_occurrences(con, session_key): - return _place_occurrences(con, session_key, by_head, known, roots) + witnesses = {} + sources = con.execute( + "SELECT DISTINCT source_id FROM codex_occurrences WHERE session_key=?", + (session_key,)) + for source in sources: + following = None + for row in con.execute( + "SELECT row_kind, row_key FROM codex_occurrences" + " WHERE session_key=? AND source_id=? AND row_kind IN ('response','event')" + " ORDER BY record_position DESC, row_kind DESC", + (session_key, source["source_id"])): + if row["row_kind"] == "response": + if row["row_key"] in live_ids: + following = row["row_key"] + elif following is not None: + witnesses.setdefault(row["row_key"], set()).add(following) + return {event: next(iter(owners)) for event, owners in witnesses.items() + if len(owners) == 1} + + +def _session_paths(con, session_key, harness): + """Current response ids and tool paths with their native call owners.""" responses = con.execute( "SELECT response_id, ordinal_num FROM responses WHERE session_key=?" - " AND is_overlap=0 AND ordinal_num IS NOT NULL ORDER BY ordinal_num", - (session_key,)).fetchall() - calls = con.execute( - "SELECT ordinal_num, target FROM events WHERE session_key=? AND" - " family IN ('tool_call', 'read', 'skill_read', 'file_change')" - " AND ordinal_num IS NOT NULL ORDER BY ordinal_num", (session_key,)).fetchall() - if known is None: - known = [dict(r) for r in _known_checkouts(con)] - if roots is None: - roots = {} - seen: dict = {} - touched: dict = {r["response_id"]: set() for r in responses} - ordinals = [r["ordinal_num"] for r in responses] - for call in calls: - owner = _owner(ordinals, call["ordinal_num"], follows) - if owner is None: - continue - rid = responses[owner]["response_id"] + " AND is_overlap=0 ORDER BY ordinal_num", (session_key,)).fetchall() + ids = [r["response_id"] for r in responses] + timed = [r for r in responses if r["ordinal_num"] is not None] + ordinals = [r["ordinal_num"] for r in timed] + owners = None + if harness == "codex" and _has_occurrences(con, session_key): + owners = _occurrence_owners(con, session_key, set(ids)) + paths = {} + for call in con.execute( + "SELECT id, ordinal_num, target FROM events WHERE session_key=?" + " AND family IN ('tool_call','read','skill_read','file_change')", + (session_key,)): + rid = None + if owners is not None: + rid = owners.get(str(call["id"])) + elif call["ordinal_num"] is not None: + if CALL_FOLLOWS_RESPONSE[harness]: + index = bisect.bisect_right(ordinals, call["ordinal_num"]) - 1 + else: + index = bisect.bisect_left(ordinals, call["ordinal_num"]) + if 0 <= index < len(timed): + rid = timed[index]["response_id"] for path in PATH_RE.findall(call["target"] or ""): - if path not in seen: - seen[path] = checkout_of(con, path, known, roots) - found = seen[path] - if found in by_head: - touched[rid].add(by_head[found]) - return {rid: next(iter(tasks)) if len(tasks) == 1 else None - for rid, tasks in touched.items()} + # Bind the observation to this path without retaining tool inputs. + digest = hashlib.sha256(path.encode()).digest() + paths[call["id"], digest] = (rid, path) + return ids, paths -def _has_occurrences(con, session_key: str) -> bool: - if not _has_table(con, "codex_occurrences"): - return False - row = con.execute( - "SELECT 1 FROM codex_occurrences WHERE session_key=? LIMIT 1", - (session_key,)).fetchone() - return row is not None +def _observations(con, session_key): + return {(r["event_id"], r["path_digest"]): + (r["response_id"], r["repository"], r["branch"]) + for r in con.execute( + "SELECT o.* FROM events e JOIN response_checkouts o ON e.id=o.event_id" + " WHERE e.session_key=?", (session_key,))} -def _place_occurrences(con, session_key: str, by_head: dict, - known: list | None, roots: dict | None) -> dict: - """Place Codex calls from agreeing per-source response witnesses. +def read_placements(con, session_key: str) -> dict | None: + """Read response_id -> sole matching PR, or None for an unplaced response. - Each source keeps the first position of a call and of a live response. - The witness is the first live response at or after the call in that - source. A source that repeats a call with no response after it adds - no witness. Witnesses that name different responses leave the call - unplaced. A session with no stored occurrences uses the ordinal bisect. + None leaves whole-session sharing to the caller. An empty map leaves + every response unplaced on a ledger without observations. Only current + call/response pairings count, even between syncs. """ - live = [r["response_id"] for r in con.execute( - "SELECT response_id FROM responses WHERE session_key=? AND is_overlap=0", - (session_key,))] - live_ids = set(live) - touched = {rid: set() for rid in live} - if known is None: - known = [dict(r) for r in _known_checkouts(con)] - if roots is None: - roots = {} - witnesses: dict = {} - targets: dict = {} - sources = con.execute( - "SELECT DISTINCT source_id FROM codex_occurrences WHERE session_key=?", - (session_key,)).fetchall() - for source in sources: - sid = source["source_id"] - response_seq = [ - (row["record_position"], row["row_key"]) - for row in con.execute( - "SELECT record_position, row_key FROM codex_occurrences" - " WHERE source_id=? AND session_key=? AND row_kind='response'" - " ORDER BY record_position", - (sid, session_key)) - if row["row_key"] in live_ids] - calls = con.execute( - "SELECT o.record_position AS record_position, e.family, e.native_id," - " e.target FROM codex_occurrences o" - " JOIN events e ON e.id = o.row_key" - " WHERE o.source_id=? AND o.session_key=? AND o.row_kind='event'" - " AND e.family IN ('tool_call', 'read', 'skill_read', 'file_change')" - " ORDER BY o.record_position", - (sid, session_key)).fetchall() - for call in calls: - following = [rid for position, rid in response_seq - if position >= call["record_position"]] - if not following: - continue - identity = (call["family"], call["native_id"]) - witnesses.setdefault(identity, set()).add(following[0]) - targets.setdefault(identity, call["target"]) - seen: dict = {} - for identity, rids in witnesses.items(): - if len(rids) != 1: + legacy = _legacy_session(con, session_key) + if legacy is None: + return None + harness, tasks = legacy + if not _has_table(con, "response_checkouts"): + return {} + heads = _task_heads(con, tasks) + if not heads: + return None + ids, paths = _session_paths(con, session_key, harness) + observations = _observations(con, session_key) + matches = {rid: set() for rid in ids} + pending = set() + for key, (rid, _) in paths.items(): + if rid is None: continue - rid = next(iter(rids)) - for path in PATH_RE.findall(targets.get(identity) or ""): - if path not in seen: - seen[path] = checkout_of(con, path, known, roots) - found = seen[path] - if found in by_head: - touched[rid].add(by_head[found]) - return {rid: next(iter(tasks)) if len(tasks) == 1 else None - for rid, tasks in touched.items()} + observed = observations.get(key) + if observed is None or observed[0] != rid: + pending.add(rid) + else: + matches[rid].update(heads.get(observed[1:], ())) + return {rid: next(iter(owners)) if rid not in pending and len(owners) == 1 else None + for rid, owners in matches.items()} -def _owner(ordinals: list, ordinal: int, follows: bool) -> int | None: - """Index of the response that issued the call at ordinal.""" - if follows: - i = bisect.bisect_right(ordinals, ordinal) - 1 - return i if i >= 0 else None - i = bisect.bisect_left(ordinals, ordinal) - return i if i < len(ordinals) else None +# Compatibility for callers using the original report helper. +place_session = read_placements def record_shared_checkouts(con) -> int: - """Record the checkouts of every session bound to several PRs. - - Sync calls this once, while task worktrees still exist. One `known` - list and one `roots` map serve every session in that call. - """ - shared = [r["session_key"] for r in con.execute( - "SELECT session_key FROM session_assignments GROUP BY session_key" - " HAVING COUNT(DISTINCT task_id) > 1")] - known = [dict(r) for r in _known_checkouts(con)] - roots: dict = {} - for key in shared: - place_session(con, key, known, roots) + """Observe each event/path once. Reimports can revise its response witness.""" + con.execute( + "CREATE TABLE IF NOT EXISTS response_checkouts(" + " event_id INTEGER NOT NULL REFERENCES events(id) ON DELETE CASCADE," + " path_digest BLOB NOT NULL, response_id TEXT, repository TEXT, branch TEXT," + " PRIMARY KEY(event_id, path_digest))") + shared = [r[0] for r in con.execute( + "SELECT session_key FROM session_assignments GROUP BY session_key HAVING COUNT(*) > 1")] con.commit() + roots = {} + for session_key in shared: + legacy = _legacy_session(con, session_key) + if legacy is None: + continue + harness, _ = legacy + _, paths = _session_paths(con, session_key, harness) + observations = _observations(con, session_key) + changed = [] + for key, (rid, path) in paths.items(): + observed = observations.get(key) + if observed is None: + repo, branch = _checkout(path, roots) + elif observed[0] != rid: + repo, branch = observed[1:] + else: + continue + changed.append((*key, rid, repo, branch)) + # No git subprocess runs under the ledger write lock. On a racing + # sync the first checkout observation wins, including a missing one. + with con: + con.executemany( + "INSERT INTO response_checkouts(event_id,path_digest,response_id,repository,branch)" + " VALUES(?,?,?,?,?) ON CONFLICT(event_id,path_digest) DO UPDATE" + " SET response_id=excluded.response_id", changed) return len(shared) diff --git a/tests/test_codex_fork.py b/tests/test_codex_fork.py index fe52cbc..0db31cc 100644 --- a/tests/test_codex_fork.py +++ b/tests/test_codex_fork.py @@ -551,8 +551,8 @@ def _rows(self, history_start, user_id): "content_item_kinds": ["user.text"]}} if user_id: user["id"] = user_id - alpha = os.path.join(self.tmp.name, "removed-alpha", "x.py") - beta = os.path.join(self.tmp.name, "removed-beta", "x.py") + alpha = os.path.join(self.tmp.name, "alpha-checkout", "x.py") + beta = os.path.join(self.tmp.name, "beta-checkout", "x.py") rows = [ {"type": "session_meta", "payload": child}, {"type": "session_meta", "payload": { @@ -596,24 +596,26 @@ def _bind(self, con): t3._ensure_tables(con) for i, repo in enumerate(("alpha", "beta"), 1): task = f"o/{repo}#{i}" - root = os.path.join(self.tmp.name, f"removed-{repo}") + root = os.path.join(self.tmp.name, f"{repo}-checkout") con.execute( "INSERT OR IGNORE INTO tasks(task_id, title, created_at)" " VALUES(?,?,0)", (task, task)) con.execute( "INSERT OR IGNORE INTO session_assignments" "(session_key, task_id, evidence, created_at)" - " VALUES('codex:parent', ?, 'review', 0)", (task,)) + " VALUES('codex:parent', ?, 't3', 0)", (task,)) con.execute( "INSERT OR IGNORE INTO t3_links(thread_id, kind, host," " repository, number, url, head_branch)" " VALUES('t','pr','github.com',?,?,?,?)", (f"o/{repo}", i, f"https://github.com/o/{repo}/pull/{i}", "fix/" + repo)) - con.execute( - "INSERT OR IGNORE INTO checkouts(root, repository, branch," - " seen_at) VALUES(?,?,?,0)", - (root, f"o/{repo}", "fix/" + repo)) + if not os.path.isdir(root): + for args in (["init", "-q", "-b", "fix/" + repo, root], + ["-C", root, "remote", "add", "origin", f"git@github.com:o/{repo}.git"], + ["-C", root, "-c", "user.email=t@t", "-c", "user.name=t", + "commit", "-q", "--allow-empty", "-m", "start"]): + subprocess.run(["git", *args], check=True, capture_output=True) def test_upgrade_keeps_parent_input_and_read_attribution(self): for user_id in (None, "parent-input"): @@ -640,7 +642,8 @@ def test_upgrade_keeps_parent_input_and_read_attribution(self): con, [sub], turns_before=0, turns_after=0)[0] self.assertEqual(shown["status"], "ok", shown) self.assertIn("retained parent input", shown["text"]) - placed = placement.place_session(con, "codex:parent") + placement.record_shared_checkouts(con) + placed = placement.read_placements(con, "codex:parent") self.assertEqual(placed["codex:parent-r1"], "o/alpha#1") self.assertEqual(placed["codex:parent-r2"], "o/beta#2") for i, repo in enumerate(("alpha", "beta"), 1): diff --git a/tests/test_placement.py b/tests/test_placement.py index 485c4aa..3390172 100644 --- a/tests/test_placement.py +++ b/tests/test_placement.py @@ -6,6 +6,7 @@ import shutil import subprocess from contextlib import redirect_stdout +from unittest.mock import patch from agent_observer import cli, db, placement, report from agent_observer.adapters import t3 as t3_adapter @@ -76,6 +77,7 @@ def claude_session(self): def test_each_pr_counts_only_its_own_responses_and_totals_reconcile(self): self.claude_session() + placement.record_shared_checkouts(self.con) alpha = report.task_report(self.con, "o/alpha#1", schedule=SCHEDULE) beta = report.task_report(self.con, "o/beta#2", schedule=SCHEDULE) self.assertEqual(alpha["measured"]["attributed_responses"], ["r0"]) @@ -91,7 +93,8 @@ def test_each_pr_counts_only_its_own_responses_and_totals_reconcile(self): def test_codex_calls_belong_to_the_next_response(self): a, b = self.checkouts["alpha"], self.checkouts["beta"] self.session("codex", [(2, 1, f"ls {a}"), (4, 3, f"ls {b}")]) - placed = placement.place_session(self.con, "codex:s") + placement.record_shared_checkouts(self.con) + placed = placement.read_placements(self.con, "codex:s") self.assertEqual(placed, {"r0": "o/alpha#1", "r1": "o/beta#2"}) def test_removed_worktree_still_places_from_recorded_checkouts(self): @@ -99,45 +102,90 @@ def test_removed_worktree_still_places_from_recorded_checkouts(self): self.assertEqual(placement.record_shared_checkouts(self.con), 1) for root in self.checkouts.values(): shutil.rmtree(root) - placed = placement.place_session(self.con, "claude:s") + placed = placement.read_placements(self.con, "claude:s") self.assertEqual((placed["r0"], placed["r1"]), ("o/alpha#1", "o/beta#2")) def test_without_head_branches_the_session_stays_shared_whole(self): self.claude_session() self.con.execute("UPDATE t3_links SET head_branch=NULL") + placement.record_shared_checkouts(self.con) alpha = report.task_report(self.con, "o/alpha#1", schedule=SCHEDULE) self.assertEqual(alpha["shared_joint"]["responses"], 5) self.assertEqual(alpha["attributed"]["responses"], 0) + def test_heads_linked_after_checkout_retirement_use_the_original_observation(self): + key = self.claude_session() + self.con.execute("UPDATE t3_links SET head_branch=NULL") + placement.record_shared_checkouts(self.con) + shutil.rmtree(self.checkouts["alpha"]) + self.con.execute("UPDATE t3_links SET head_branch='fix/a' WHERE number=1") + self.assertEqual(placement.read_placements(self.con, key)["r0"], "o/alpha#1") + def test_unsupported_harness_stays_shared_whole(self): self.session("opencode", [(1, 2, f"ls {self.checkouts['alpha']}")]) - self.assertIsNone(placement.place_session(self.con, "opencode:s")) + self.assertIsNone(placement.read_placements(self.con, "opencode:s")) def test_detached_checkout_matches_no_pr(self): + _git("-C", self.checkouts["alpha"], "checkout", "-q", "--detach") + key = self.claude_session() + placement.record_shared_checkouts(self.con) + self.assertIsNone(placement.read_placements(self.con, key)["r0"]) + + def test_reused_checkout_path_preserves_old_and_new_response_witnesses(self): + key = self.claude_session() + placement.record_shared_checkouts(self.con) root = self.checkouts["alpha"] - _git("-C", root, "checkout", "-q", "--detach") - self.assertEqual(placement.checkout_of(self.con, root), ("o/alpha", None)) + _git("-C", root, "checkout", "-q", "-b", "fix/b") + _git("-C", root, "remote", "set-url", "origin", "git@github.com:o/beta.git") + self.con.execute("INSERT INTO responses(response_id,source_id,session_key," + " ordinal_num) VALUES('new',?,?,10)", (self.source, key)) + self.con.execute("INSERT INTO events(session_key,ordinal_num,family,native_id,target)" + " VALUES(?,11,'read','new-call',?)", (key, root)) + self.assertIsNone(placement.read_placements(self.con, key)["new"]) + placement.record_shared_checkouts(self.con) + shutil.rmtree(root) + placement.record_shared_checkouts(self.con) + placed = placement.read_placements(self.con, key) + self.assertEqual((placed["r0"], placed["new"]), ("o/alpha#1", "o/beta#2")) - def test_reused_checkout_path_is_read_live_not_from_its_record(self): - # Review of 8e20c4b: a recorded root later holding another branch. - self.claude_session() + def test_removed_checkout_without_response_evidence_does_not_place(self): + key = self.claude_session() + root = self.checkouts["alpha"] + self.con.execute("INSERT INTO checkouts(root,repository,branch,seen_at)" + " VALUES(?,'o/alpha','fix/a',0)", (root,)) + shutil.rmtree(root) + self.assertEqual(placement.read_placements(self.con, key), {}) placement.record_shared_checkouts(self.con) - _git("-C", self.checkouts["alpha"], "checkout", "-q", "-b", "fix/b") - _git("-C", self.checkouts["alpha"], "remote", "set-url", "origin", - "git@github.com:o/beta.git") - placed = placement.place_session(self.con, "claude:s") - self.assertEqual(placed["r0"], "o/beta#2") - self.assertEqual(placement.checkout_of(self.con, self.checkouts["alpha"]), - ("o/beta", "fix/b")) - - def test_checkout_without_origin_forgets_its_old_record(self): - # Second review of 382552e: no origin now, removed later. + self.assertIsNone(placement.read_placements(self.con, key)["r0"]) + + def test_checkout_without_origin_cannot_gain_a_retroactive_match(self): + key = self.claude_session() root = self.checkouts["alpha"] - self.assertEqual(placement.checkout_of(self.con, root), ("o/alpha", "fix/a")) _git("-C", root, "remote", "remove", "origin") - self.assertIsNone(placement.checkout_of(self.con, root)) - shutil.rmtree(root) - self.assertIsNone(placement.checkout_of(self.con, root)) + placement.record_shared_checkouts(self.con) + _git("-C", root, "remote", "add", "origin", "git@github.com:o/alpha.git") + placement.record_shared_checkouts(self.con) + self.assertIsNone(placement.read_placements(self.con, key)["r0"]) + + def test_identical_heads_are_ambiguous_even_if_linked_after_sync(self): + key = self.claude_session() + placement.record_shared_checkouts(self.con) + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES('o/alpha#3',0)") + self.con.execute("INSERT INTO session_assignments VALUES(?,'o/alpha#3','t3',0)", (key,)) + self.con.execute("INSERT INTO t3_links(thread_id,kind,host,repository,number,url," + " head_branch) VALUES('t','pr','github.com','o/alpha',3,'url','fix/a')") + placed = placement.read_placements(self.con, key) + self.assertIsNone(placed["r0"]) + self.assertEqual(placed["r1"], "o/beta#2") + + def test_explicit_session_owner_preserves_whole_sharing(self): + key = self.claude_session() + placement.record_shared_checkouts(self.con) + self.con.execute("UPDATE session_assignments SET evidence='router:job'" + " WHERE task_id='o/alpha#1'") + self.assertIsNone(placement.read_placements(self.con, key)) + alpha = report.task_report(self.con, "o/alpha#1", schedule=SCHEDULE) + self.assertEqual(alpha["shared_joint"]["responses"], 5) def test_read_only_ledger_still_splits(self): # publish and task open the ledger read-only (cli.py). @@ -151,33 +199,21 @@ def test_read_only_ledger_still_splits(self): ro.close() self.assertEqual(alpha["measured"]["attributed_responses"], ["r0"]) - def test_read_only_report_keeps_its_snapshot_across_git(self): - # A concurrent sync commits during live git. The reader opened - # with BEGIN must not COMMIT, or scope totals see the new row - # while attributed rows stay on the old snapshot. + def test_report_uses_only_ledger_reads_and_keeps_its_snapshot(self): self.claude_session() - self.con.commit() + placement.record_shared_checkouts(self.con) ro = db.connect_read_only(self.db_path) - real = placement._git - bumped = [] - - def wrapped(checkout, *args): - if not bumped: - bumped.append(checkout) - self.con.execute( - "UPDATE responses SET input_tokens=1100, total_tokens=1110" - " WHERE response_id='r0'") - self.con.commit() - return real(checkout, *args) - - placement._git = wrapped - try: + self.addCleanup(ro.close) + statements = [] + ro.set_trace_callback(statements.append) + self.con.execute("UPDATE responses SET input_tokens=1100, total_tokens=1110" + " WHERE response_id='r0'") + self.con.commit() + with patch.object(placement, "_git", side_effect=AssertionError("report ran git")): alpha = report.task_report(ro, "o/alpha#1", schedule=SCHEDULE) - self.assertTrue(ro.in_transaction) - finally: - placement._git = real - ro.close() - self.assertTrue(bumped) + self.assertTrue(ro.in_transaction) + self.assertEqual({s.split()[0].upper() for s in statements} - + {"SELECT", "WITH", "PRAGMA"}, set()) self.assertTrue(alpha["reconciles"]) self.assertEqual(alpha["attributed"]["total_tokens"], 110) self.assertEqual(alpha["scope"]["total_tokens"], 550) @@ -227,7 +263,8 @@ def usage(name, total): stored = dict(self.con.execute( "SELECT response_id, ordinal_num FROM responses")) self.assertEqual(stored, {"codex:r1": 3, "codex:r2": 6}) - self.assertEqual(placement.place_session(self.con, key), { + placement.record_shared_checkouts(self.con) + self.assertEqual(placement.read_placements(self.con, key), { "codex:r1": "o/alpha#1", "codex:r2": "o/beta#2"}) alpha_report = report.task_report(self.con, "o/alpha#1", schedule=SCHEDULE) beta_report = report.task_report(self.con, "o/beta#2", schedule=SCHEDULE) @@ -244,7 +281,8 @@ def usage(name, total): self.assertEqual(self.con.execute( "SELECT ordinal_num FROM responses WHERE response_id='codex:r1'" ).fetchone()[0], 3) - self.assertEqual(placement.place_session(self.con, key), { + placement.record_shared_checkouts(self.con) + self.assertEqual(placement.read_placements(self.con, key), { "codex:r1": "o/alpha#1", "codex:r2": "o/beta#2"}) def test_repeated_fallback_snapshot_keeps_its_first_position(self): @@ -320,7 +358,8 @@ def usage(name, total): stored = dict(self.con.execute( "SELECT native_id, ordinal_num FROM events")) self.assertEqual(stored, {"call-a": 2, "call-b": 5}) - self.assertEqual(placement.place_session(self.con, key), { + placement.record_shared_checkouts(self.con) + self.assertEqual(placement.read_placements(self.con, key), { "codex:r1": "o/alpha#1", "codex:r2": "o/beta#2"}) alpha_report = report.task_report(self.con, "o/alpha#1", schedule=SCHEDULE) beta_report = report.task_report(self.con, "o/beta#2", schedule=SCHEDULE) @@ -344,7 +383,8 @@ def usage(name, total): self.assertEqual(self.con.execute( "SELECT intervention_id FROM verdicts").fetchone()[0], f"ev:{key}/tool_call/call-a") - self.assertEqual(placement.place_session(self.con, key)["codex:r1"], + placement.record_shared_checkouts(self.con) + self.assertEqual(placement.read_placements(self.con, key)["codex:r1"], "o/alpha#1") def test_continuation_keeps_the_original_call_and_response(self): @@ -412,7 +452,8 @@ def owned(table, key_column, native): (3, "calls.jsonl")) self.assertEqual(owned("responses", "response_id", "codex:r2"), (6, "calls.jsonl")) - self.assertEqual(placement.place_session(self.con, key), { + placement.record_shared_checkouts(self.con) + self.assertEqual(placement.read_placements(self.con, key), { "codex:r1": "o/alpha#1", "codex:r2": "o/beta#2"}) alpha_report = report.task_report( self.con, "o/alpha#1", schedule=SCHEDULE) @@ -480,7 +521,8 @@ def _assert_public_placement(self, con): "SELECT COUNT(*) FROM events WHERE native_id='call-a'").fetchone()[0], 1) self.assertEqual(con.execute( "SELECT COUNT(*) FROM responses WHERE is_overlap=0").fetchone()[0], 2) - self.assertEqual(placement.place_session(con, key), { + placement.record_shared_checkouts(con) + self.assertEqual(placement.read_placements(con, key), { "codex:r1": "o/alpha#1", "codex:r2": "o/beta#2"}) alpha_report = report.task_report(con, "o/alpha#1", schedule=SCHEDULE) beta_report = report.task_report(con, "o/beta#2", schedule=SCHEDULE) @@ -575,11 +617,19 @@ def write(name, response, total): (f"o/{repo}", n, f"https://github.com/o/{repo}/pull/{n}", branch)) self._bind_placement_tasks(other) for con, order in ((self.con, (first, second)), (other, (second, first))): + import_codex_file(con, order[0]) + placement.record_shared_checkouts(con) + self.assertEqual(list(placement.read_placements(con, key).values()), ["o/alpha#1"]) + import_codex_file(con, order[1]) + # A Codex-only import can invalidate a sync's witness before + # the placement recorder next runs. + ambiguous = {"codex:r1": None, "codex:r2": None} + self.assertEqual(placement.read_placements(con, key), ambiguous) for full in (False, True, False): for path in order: import_codex_file(con, path, full=full) - self.assertEqual(placement.place_session(con, key), { - "codex:r1": None, "codex:r2": None}) + placement.record_shared_checkouts(con) + self.assertEqual(placement.read_placements(con, key), ambiguous) def test_shared_checkout_is_resolved_once_per_sync(self): # Two shared sessions in one record_shared_checkouts share a root. @@ -622,38 +672,25 @@ def wrapped(checkout, *args): self.assertEqual( [c for c in calls if c == (root, ("rev-parse", "--abbrev-ref", "HEAD"))], [(root, ("rev-parse", "--abbrev-ref", "HEAD"))]) - row = self.con.execute( - "SELECT repository, branch FROM checkouts WHERE root=?", - (root,)).fetchone() - self.assertEqual((row["repository"], row["branch"]), ("o/alpha", "fix/a")) + for n in (1, 2): + self.assertEqual(placement.read_placements(self.con, f"claude:s{n}"), + {f"once{n}": "o/alpha#1"}) def test_live_git_runs_outside_an_open_write(self): - self.con.execute( - "INSERT INTO checkouts(root, repository, branch, seen_at)" - " VALUES(?,?,?,0)", ("/tmp/seed-open-write", "o/seed", "main")) + key = self.claude_session() self.assertTrue(self.con.in_transaction) - flags = [] real = placement._git - def wrapped(checkout, *args): - flags.append(self.con.in_transaction) - return real(checkout, *args) + def check_transaction(root, *args): + self.assertFalse(self.con.in_transaction) + return real(root, *args) - placement._git = wrapped - try: - found = placement.checkout_of(self.con, self.checkouts["alpha"]) - finally: - placement._git = real - self.assertEqual(found, ("o/alpha", "fix/a")) - self.assertEqual(flags, [False, False]) - other = db.connect(self.db_path) - try: - row = other.execute( - "SELECT repository, branch FROM checkouts WHERE root=?", - (self.checkouts["alpha"],)).fetchone() - finally: - other.close() - self.assertEqual((row["repository"], row["branch"]), ("o/alpha", "fix/a")) + with patch.object(placement, "_git", side_effect=check_transaction) as git: + placement.record_shared_checkouts(self.con) + self.assertTrue(git.called) + other = db.connect_read_only(self.db_path) + self.addCleanup(other.close) + self.assertEqual(placement.read_placements(other, key)["r0"], "o/alpha#1") def test_sync_records_shared_sessions_once_after_refresh(self): calls = [] @@ -681,7 +718,7 @@ def sync(self, con, root=None, full=False, source=None): ns = type("NS", (), {})() ns.harness = ["t3", "codex"] ns.source = None - ns.root = None + ns.root = self.tmp.name ns.full = False ns.agentsmd_repo = os.path.join(self.tmp.name, "no-such-repo") ns.as_json = True From 2841b9b9b0b89afc1a27a1a61eddba3e24649ead Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 18:54:27 +0100 Subject: [PATCH 02/44] wip: retain literal native response input evidence for #105 --- agent_observer/adapters/claude.py | 105 ++++++++++++++++++- agent_observer/adapters/codex.py | 39 +++++-- agent_observer/adapters/grok.py | 83 +++++++++++++++ agent_observer/adapters/opencode.py | 18 ++-- agent_observer/native_response.py | 62 +++++++++++ tests/test_native_response.py | 157 ++++++++++++++++++++++++++++ 6 files changed, 449 insertions(+), 15 deletions(-) create mode 100644 agent_observer/native_response.py create mode 100644 tests/test_native_response.py diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index d7dec46..b8a0610 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -17,8 +17,9 @@ import json import os import sqlite3 +from collections import defaultdict, deque -from .. import db, privacy, intervention_evidence +from .. import db, native_response, privacy, intervention_evidence from ..identity import SessionIdentity, skill_from_path from ..ingest import (JsonlSource, MissingNativeId, fingerprint, insert_event, iso_ts, text_hash) @@ -105,7 +106,7 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 5 # Replay T3 completion-report parsing once (#142). +_IMPORT_VERSION = 6 # Replay UUID ancestry from existing sources. def _ensure_native_kinds(con) -> None: @@ -382,6 +383,7 @@ def import_claude_file(con: sqlite3.Connection, path: str, _ensure_finality_table(con) _ensure_native_kinds(con) _seed_queue_identity(r) + _prepare_ancestry(r) # Durable per-response finality is authoritative for accepted final # rows. It covers copied sources, full reimports and incremental # appends. The file prefix is never authority on its own, so a malformed @@ -409,6 +411,7 @@ def import_claude_file(con: sqlite3.Connection, path: str, line) continue try: + _record_ancestry(r, obj) _ingest(r, obj, ordinal) if obj.get("type") == "queue-operation": con.execute("DELETE FROM import_errors WHERE harness=? AND source_path=?" @@ -1060,3 +1063,101 @@ def _system(r: _Reader, obj: dict, ordinal: int, ts) -> None: elif subtype in ("api_error", "stop_hook_summary", "informational"): r.event("lifecycle", native, ordinal, ts, name=subtype, status=obj.get("level")) + + +def _prepare_ancestry(r): + r.con.execute(""" + CREATE TABLE IF NOT EXISTS claude_response_ancestry ( + session_key TEXT NOT NULL, uuid TEXT NOT NULL, parent TEXT NOT NULL, + input_id TEXT NOT NULL, response_id TEXT NOT NULL, + source_id INTEGER NOT NULL REFERENCES sources(id), + PRIMARY KEY(session_key, uuid, parent, input_id, response_id, source_id) + ) WITHOUT ROWID""") + r.con.execute("CREATE INDEX IF NOT EXISTS claude_ancestry_source" + " ON claude_response_ancestry(source_id)") + if not r.src.incremental: + r.con.execute("DELETE FROM claude_response_ancestry WHERE source_id=?", + (r.src.source_id,)) + + +def _record_ancestry(r, obj): + uuid = native_response.identifier(obj.get("uuid")) + if (not uuid or not r.native_session or obj.get("sessionId") != r.native_session + or (obj.get("agentId") and obj["agentId"] != r.agent_id)): + return + parent = native_response.identifier(obj.get("parentUuid")) + kind = obj.get("type") + message = obj.get("message") + if kind in ("user", "assistant") and ( + not isinstance(message, dict) or message.get("role", kind) != kind): + return + input_id = response_id = "" + if kind == "user": + content = message.get("content") + if ((isinstance(content, str) and content) or + (isinstance(content, list) and any( + isinstance(block, dict) and block.get("type") in ("text", "image", "document") + for block in content))): + input_id = uuid + elif not (isinstance(content, list) and content and all( + isinstance(block, dict) and block.get("type") == "tool_result" + for block in content)): + return + elif kind == "assistant": + mid = native_response.identifier(message.get("id")) + if mid and message.get("model") != "": + response_id = f"{HARNESS}:{mid}" + elif kind == "attachment" and isinstance(obj.get("attachment"), dict): + if obj["attachment"].get("type") == "queued_command": + # A consumed queued input has its own identity. A missing identity + # must not send its descendants back to the previous prompt. + input_id = native_response.identifier(obj["attachment"].get("source_uuid")) + if input_id is None: + return + elif kind not in ("system", "progress"): + return + r.con.execute("INSERT OR IGNORE INTO claude_response_ancestry" + "(session_key,uuid,parent,input_id,response_id,source_id)" + " VALUES(?,?,?,?,?,?)", + (r.session_key, uuid, "" if input_id else parent or "", + input_id, response_id, r.src.source_id)) + + +def response_inputs(con, session_key): + """Resolve every UUID once, stopping each chain at its nearest native input. + + A missing parent or cycle leaves that chain unresolved. Multiple observed + parents must all resolve, and competing inputs survive for the consumer. + """ + if not db._has_table(con, "claude_response_ancestry"): + return {} + parents, children, anchors, blocks = (defaultdict(set) for _ in range(4)) + for uuid, parent, input_id, response_id in con.execute( + "SELECT DISTINCT uuid,parent,input_id,response_id FROM claude_response_ancestry" + " WHERE session_key=?", (session_key,) + ): + if input_id: + anchors[uuid].add(input_id) + elif parent: + parents[uuid].add(parent) + children[parent].add(uuid) + if response_id: + blocks[response_id].add(uuid) + # Process an interior node only after all its parents have resolved. + ready = deque(uuid for uuid in anchors if uuid not in parents) + resolved = set() + while ready: + uuid = ready.popleft() + resolved.add(uuid) + for child in children.get(uuid, ()): + parents[child].remove(uuid) + anchors[child].update(anchors[uuid]) + if not parents[child]: + ready.append(child) + results = {} + for response_id, in con.execute("SELECT response_id FROM responses" + " WHERE session_key=? AND is_overlap=0", (session_key,)): + nodes = blocks.get(response_id) + if nodes and nodes <= resolved: + results[response_id] = set.union(*(anchors[node] for node in nodes)) + return results diff --git a/agent_observer/adapters/codex.py b/agent_observer/adapters/codex.py index 2c291c8..e8fbf05 100644 --- a/agent_observer/adapters/codex.py +++ b/agent_observer/adapters/codex.py @@ -18,7 +18,7 @@ import os import sqlite3 -from .. import db, privacy +from .. import db, native_response, privacy from ..identity import SessionIdentity, skill_from_path from ..ingest import (JsonlSource, MissingNativeId, fingerprint, insert_event, iso_ts, stored_path, text_hash) @@ -61,6 +61,7 @@ def _occurrences_ready(row) -> bool: HARNESS = "codex" +_CONTEXT_VERSION = 7 # Record literal turn witnesses from every atomic occurrence. SEMANTICS = "codex:input_includes_cached,output_includes_reasoning" # Older rollouts carry usage only in token_count events: last_token_usage per # response and a cumulative total that repeats when nothing new happened. @@ -760,10 +761,9 @@ def import_codex_file(con: sqlite3.Connection, path: str, "events_duplicate": 0, "compactions": 0, "malformed": 0, } src = JsonlSource(con, HARNESS, path, full=full) - if (src.row["codex_context_version"] != 6 + if (src.row["codex_context_version"] != _CONTEXT_VERSION or src.row["codex_context_offset"] != src.row["read_offset"]): - # Replay older indexes once, including search extensions previously - # discarded from otherwise unchanged sources (#94). + # Replay older indexes once to recover literal turn witnesses from copies. src.start_offset = 0 src.end_offset = 0 src.unchanged = False @@ -811,6 +811,7 @@ def import_codex_file(con: sqlite3.Connection, path: str, }) return stats reader = _Reader(con, src, stats) + native_response.prepare(con, src.source_id, replace=not src.incremental) _ensure_cumulative_table(con) own = _first_meta(path) boundary = _history_file_boundary(path, own) if own is not None else None @@ -960,9 +961,9 @@ def import_codex_file(con: sqlite3.Connection, path: str, thread_source=reader.thread_source)) backfill = 1 if _backfill_complete( con, src.source_id, getattr(src, "last_ordinal", None)) else 0 - con.execute("UPDATE sources SET codex_context_version=6,codex_context_offset=?," + con.execute("UPDATE sources SET codex_context_version=?,codex_context_offset=?," "codex_model=?,codex_effort=?,occurrence_backfill=? WHERE id=?", - (src.end_offset, reader.model, reader.effort, backfill, + (_CONTEXT_VERSION, src.end_offset, reader.model, reader.effort, backfill, src.source_id)) for key, (native, lost_rows) in settle.items(): _settle(con, key, native, lost_rows) @@ -1599,6 +1600,11 @@ def _ingest_usage(r: _Reader, obj: dict) -> None: th = th_raw if isinstance(th_raw, dict) else {} rid = f"{HARNESS}:{p['response_id']}" turn_id = f"{HARNESS}:{p['turn_id']}" if p.get("turn_id") else None + native_turn = native_response.identifier(p.get("turn_id")) + if (native_turn and (r.thread_id or r.session_id) + and native_response.identifier(p.get("response_id")) + and p.get("thread_id") in (None, r.thread_id)): + native_response.record(r.con, r.src.source_id, r.session_key, rid, native_turn) cur = r.con.execute( "INSERT OR IGNORE INTO responses(response_id, source_id, harness," " session_key, thread_id, turn_id, root_turn_id, session_id," @@ -2191,3 +2197,24 @@ def _function_read(r, obj, call_id, path, state, turn_id): r.event(obj, family, call_id, turn_id=turn_id, name=os.path.basename(path), target=skill if family == "skill_read" else path, status=state, detail={"skill": skill, "skill_path": path} if family == "skill_read" else None) + + +def legacy_response_inputs(con, session_key): + """Atomic records imported before per-occurrence evidence still have + their literal turn_id. Retouch touches Claude exclusively. Fallback + token_count records have a separate semantics and no native response id. + """ + columns = {row[1] for row in con.execute("PRAGMA table_info(sources)")} + old = (" AND COALESCE(s.codex_context_version,0)<7" + if "codex_context_version" in columns else "") + for rid, turn in con.execute( + "SELECT r.response_id,r.turn_id FROM responses r JOIN sources s ON s.id=r.source_id" + " WHERE r.harness='codex' AND r.session_key=? AND r.semantics=? AND r.is_overlap=0" + " AND (r.thread_id IS NULL OR 'codex:'||r.thread_id=r.session_key)" + old, + (session_key, SEMANTICS) + ): + if (isinstance(turn, str) and turn.startswith("codex:") + and native_response.identifier(turn[6:]) + and isinstance(rid, str) and rid.startswith("codex:") + and native_response.identifier(rid[6:])): + yield rid, turn[6:] diff --git a/agent_observer/adapters/grok.py b/agent_observer/adapters/grok.py index 5b1af9a..be08075 100644 --- a/agent_observer/adapters/grok.py +++ b/agent_observer/adapters/grok.py @@ -1524,6 +1524,15 @@ def import_grok_session(con: sqlite3.Connection, session_dir: str, if updates_path and os.path.isfile(updates_path) else None) events_src = (JsonlSource(con, HARNESS, events_path, full=full) if events_path and os.path.isfile(events_path) else None) + if updates_src is not None: + # grok_session_meta is shared by copies. Each old updates source must + # independently replay once, even when a different copy was upgraded. + con.execute("CREATE TABLE IF NOT EXISTS grok_bridge_sources" + "(source_id INTEGER PRIMARY KEY REFERENCES sources(id))") + if not con.execute("SELECT 1 FROM grok_bridge_sources WHERE source_id=?", + (updates_src.source_id,)).fetchone(): + updates_src.start_offset = updates_src.end_offset = 0 + updates_src.unchanged = False r.updates_src = updates_src r.events_src = events_src known_row = con.execute("SELECT 1 FROM sessions WHERE session_key=?", @@ -1709,6 +1718,10 @@ def _get_chat() -> dict: # yields no turn model and keeps updates unparsed. updates_records = _load_jsonl_records(updates_path) \ if updates_path and os.path.isfile(updates_path) else [] + if updates_records is not None and updates_src is not None: + _record_prompt_bridges(r, updates_src, updates_records) + con.execute("INSERT OR IGNORE INTO grok_bridge_sources VALUES(?)", + (updates_src.source_id,)) if updates_records is not None: try: _spawns = _extract_spawns_from_records(updates_records) @@ -2908,3 +2921,73 @@ def _read_state(status): if status in ("failed", "error", "cancelled"): return "failed" return "pending" if status in ("in_progress", "pending", "running") else "attempted" + + +def _record_prompt_bridges(r, src, records): + """Chromeria's native input ref is prompt:. The completion + has a different prompt_id; only an input frame carrying both can join it. + """ + r.con.execute(""" + CREATE TABLE IF NOT EXISTS grok_prompt_bridges ( + session_key TEXT NOT NULL, prompt_id TEXT NOT NULL, input_ref TEXT NOT NULL, + source_id INTEGER NOT NULL REFERENCES sources(id), + PRIMARY KEY(session_key, prompt_id, input_ref, source_id) + ) WITHOUT ROWID""") + r.con.execute("CREATE INDEX IF NOT EXISTS grok_bridge_source ON grok_prompt_bridges(source_id)") + r.con.execute("DELETE FROM grok_prompt_bridges WHERE source_id=?", (src.source_id,)) + witnesses = set() + for _, obj, _ in records: + if not isinstance(obj, dict) or obj.get("method") not in METHODS: + continue + params = obj.get("params") + if not isinstance(params, dict) or params.get("sessionId") != r.native_sid: + continue + update = params.get("update") + if not isinstance(update, dict): + continue + kind = update.get("sessionUpdate") + if kind == "turn_completed": + ids = {_valid_native_id(update[k]) for k in ("prompt_id", "promptId") if k in update} + if len(ids) == 1 and None not in ids: + pid, = ids + witnesses.add((pid, "")) # A scoped completion, independent of input order. + elif kind == "user_message_chunk": + meta = update.get("_meta") + if not isinstance(meta, dict): + continue + index = meta.get("promptIndex") + if (type(index) is not int or not 0 <= index <= 2**53 - 1 + or meta.get("syntheticPrompt") is True or meta.get("hideFromScrollback") is True): + continue + for fields in (update, meta, params.get("_meta"), obj.get("_meta")): + if isinstance(fields, dict): + for key in ("promptId", "prompt_id"): + pid = _valid_native_id(fields.get(key)) + if pid: + witnesses.add((pid, f"prompt:{index}")) + r.con.executemany("INSERT INTO grok_prompt_bridges VALUES(?,?,?,?)", + ((r.session_key, pid, ref, src.source_id) for pid, ref in witnesses)) + + +def response_inputs(con, session_key): + if not db._has_table(con, "grok_prompt_bridges"): + return {} + completed = set() + indexes = {} + for pid, ref in con.execute("SELECT DISTINCT prompt_id,input_ref FROM grok_prompt_bridges" + " WHERE session_key=?", (session_key,)): + if ref: + indexes.setdefault(ref, set()).add(pid) + else: + completed.add(pid) + # One native index claiming two different prompt ids is contradictory, + # including when the two claims came from different copies. + disputed = {pid for pids in indexes.values() if len(pids) > 1 for pid in pids} + eligible = completed - disputed + refs = {} + for ref, pids in indexes.items(): + for pid in pids & eligible: + refs.setdefault(f"{session_key}:{pid}", set()).add(ref) + return {rid: refs[rid] for rid, in con.execute( + "SELECT response_id FROM responses WHERE session_key=? AND is_overlap=0", (session_key,) + ) if rid in refs} diff --git a/agent_observer/adapters/opencode.py b/agent_observer/adapters/opencode.py index 42a3159..4fccc8b 100644 --- a/agent_observer/adapters/opencode.py +++ b/agent_observer/adapters/opencode.py @@ -19,7 +19,7 @@ import sqlite3 import time -from .. import db, privacy +from .. import db, native_response, privacy from ..identity import SessionIdentity, skill_from_path from ..ingest import fingerprint, insert_event, iso_ts, text_hash @@ -410,7 +410,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, session_key = f"{HARNESS}:{sess_id}" msg_n, msg_m = _count_max(native, "message", sess_id) part_n, part_m = _count_max(native, "part", sess_id) - fp = fingerprint(sess.get("time_updated"), msg_m, part_m, msg_n, part_n) + fp = fingerprint("native-parent-v1", sess.get("time_updated"), msg_m, part_m, msg_n, part_n) row = con.execute( "SELECT * FROM sources WHERE harness=? AND path=?", (HARNESS, src_path)).fetchone() @@ -501,13 +501,14 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, continue parsed_messages.append((index, msg, data)) roles[msg_id] = data.get("role") + native_response.prepare(con, source_id, replace=True) ordinal = 0 for index, msg, data in parsed_messages: ordinal += 1 _ingest_message(con, native, stats, identity, src_path, source_id, session_key, sess, msg, data, index, ordinal, by_message.get(msg.get("id"), []), - privacy_stale=privacy_stale) + roles=roles, privacy_stale=privacy_stale) for part in parts: ordinal += 1 _ingest_part(con, stats, identity, src_path, source_id, @@ -539,7 +540,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, con.execute( "UPDATE sources SET sha256=?, size_bytes=?, imported_at=?," " import_ms=?, session_id=?, privacy_version=? WHERE id=?", - (fp, size_bytes, db.now(), + (fp if complete else "", size_bytes, db.now(), int((time.monotonic() - started) * 1000), sess_id, new_version, source_id)) con.commit() @@ -549,7 +550,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, def _ingest_message(con, native, stats, identity, src_path, source_id, session_key, sess, msg, data, index, ordinal, - msg_parts, privacy_stale: bool = False) -> None: + msg_parts, *, roles, privacy_stale: bool = False) -> None: msg_id = msg.get("id") timing = data.get("time") if isinstance(data.get("time"), dict) else {} completed = timing.get("completed") @@ -575,7 +576,7 @@ def _ingest_message(con, native, stats, identity, src_path, source_id, role = data.get("role") if role == "assistant": _ingest_response(con, stats, src_path, source_id, session_key, - sess, msg, data, index, ts, ordinal) + sess, msg, data, index, ts, ordinal, roles) elif role == "user": _ingest_submission(con, stats, identity, src_path, source_id, session_key, sess, msg, data, index, ts, @@ -586,7 +587,7 @@ def _ingest_message(con, native, stats, identity, src_path, source_id, def _ingest_response(con, stats, src_path, source_id, session_key, sess, - msg, data, index, ts, ordinal) -> None: + msg, data, index, ts, ordinal, roles) -> None: timing = data.get("time") if isinstance(data.get("time"), dict) else {} if timing.get("completed") is None: return @@ -639,6 +640,9 @@ def _ingest_response(con, stats, src_path, source_id, session_key, sess, cost = data.get("cost") cost_usd = cost if isinstance(cost, (int, float)) \ and not isinstance(cost, bool) else None + parent = native_response.identifier(data.get("parentID")) + if parent and roles.get(parent) == "user" and native_response.identifier(msg["id"]): + native_response.record(con, source_id, session_key, f"{HARNESS}:{msg['id']}", parent) _upsert_response( con, stats, src_path, response_id=f"{HARNESS}:{msg.get('id')}", source_id=source_id, session_key=session_key, diff --git a/agent_observer/native_response.py b/agent_observer/native_response.py new file mode 100644 index 0000000..12e0880 --- /dev/null +++ b/agent_observer/native_response.py @@ -0,0 +1,62 @@ +"""Literal, source-scoped input identities for native usage rows.""" + +from __future__ import annotations + +import re +import sqlite3 +from collections import defaultdict + +from . import db + + +def identifier(value: object) -> str | None: + if isinstance(value, str) and re.fullmatch(r"[a-zA-Z0-9_.:-]{1,200}", value): + return value + return None + + +def prepare(con, source_id, *, replace): + """An adapter rebuilds only its own source, in its import transaction.""" + con.execute(""" + CREATE TABLE IF NOT EXISTS native_response_inputs ( + session_key TEXT NOT NULL, response_id TEXT NOT NULL, + input_id TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), + PRIMARY KEY(session_key, response_id, input_id, source_id) + ) WITHOUT ROWID""") + con.execute("CREATE INDEX IF NOT EXISTS native_response_source" + " ON native_response_inputs(source_id)") + if replace: + con.execute("DELETE FROM native_response_inputs WHERE source_id=?", (source_id,)) + + +def record(con, source_id, session_key, response_id, input_id): + con.execute("INSERT OR IGNORE INTO native_response_inputs" + "(session_key,response_id,input_id,source_id) VALUES(?,?,?,?)", + (session_key, response_id, input_id, source_id)) + + +def inputs(con: sqlite3.Connection, session_key: str) -> dict[str, set[str]]: + """Keys are ledger response ids. Values are the adapter's unprefixed ids. + + An absent key has no proved input. Multiple candidates must be reconciled + by the consumer. Reading an old ledger never creates adapter tables. + """ + if session_key.startswith("claude:"): + from .adapters import claude + return claude.response_inputs(con, session_key) + if session_key.startswith("grok:"): + from .adapters import grok + return grok.response_inputs(con, session_key) + found = defaultdict(set) + if db._has_table(con, "native_response_inputs"): + for response_id, input_id in con.execute( + "SELECT DISTINCT i.response_id,i.input_id FROM native_response_inputs i" + " JOIN responses r USING(session_key,response_id)" + " WHERE i.session_key=? AND r.is_overlap=0", (session_key,) + ): + found[response_id].add(input_id) + if session_key.startswith("codex:"): + from .adapters import codex + for response_id, turn_id in codex.legacy_response_inputs(con, session_key): + found[response_id].add(turn_id) + return dict(found) diff --git a/tests/test_native_response.py b/tests/test_native_response.py new file mode 100644 index 0000000..a831062 --- /dev/null +++ b/tests/test_native_response.py @@ -0,0 +1,157 @@ +"""Public adapter import and read-only literal membership queries.""" + +from contextlib import closing +import json +import sqlite3 +from pathlib import Path + +from agent_observer import native_response +from agent_observer.adapters import claude, codex, grok, opencode +from tests.helpers import LedgerCase, fixture +from tests.test_opencode import build_native + + +def write_records(path, rows, mode="w"): + with path.open(mode) as out: + for row in rows: + out.write(json.dumps(row) + "\n") + + +def claude_user(uuid, parent=None, content="identical prompt"): + return {"sessionId": "s", "type": "user", "uuid": uuid, "parentUuid": parent, + "message": {"role": "user", "content": content}} + + +def claude_response(uuid, parent, response_id): + return {"sessionId": "s", "type": "assistant", "uuid": uuid, "parentUuid": parent, + "message": {"id": response_id, "role": "assistant", "model": "model", + "stop_reason": "end_turn", "usage": {"output_tokens": 1}}} + + +class NativeResponseTest(LedgerCase): + def test_claude_out_of_order_tool_chain_cycle_and_competing_streams(self): + path = Path(self.tmp.name, "s.jsonl") + write_records(path, [ + claude_user("b"), + claude_response("r1", "a", "msg-1"), + claude_response("r2", "tool", "msg-2"), + claude_user("tool", "r1", [{"type": "tool_result", "tool_use_id": "call"}]), + claude_response("other", "b", "msg-2"), + claude_response("cycle-1", "cycle-2", "msg-3"), + claude_response("cycle-2", "cycle-1", "msg-3"), + ]) + claude.import_claude_file(self.con, str(path)) + self.assertEqual(native_response.inputs(self.con, "claude:s"), {}) + write_records(path, [claude_user("a")], "a") + claude.import_claude_file(self.con, str(path)) + self.con.execute("UPDATE responses SET turn_id='claude:display-turn'") + expected = {"claude:msg-1": {"a"}, "claude:msg-2": {"a", "b"}} + self.assertEqual(native_response.inputs(self.con, "claude:s"), expected) + # Simulate the durable state of a pre-ancestry import. + self.con.execute("DROP TABLE claude_response_ancestry") + self.con.execute("UPDATE sources SET claude_usage_version=5") + claude.import_claude_file(self.con, str(path)) + self.assertEqual(native_response.inputs(self.con, "claude:s"), expected) + write_records(path, [claude_response("r1", "gone", "msg-1")]) + claude.import_claude_file(self.con, str(path)) + self.assertEqual(native_response.inputs(self.con, "claude:s"), {}) + + def test_codex_atomic_conflict_and_legacy_snapshot(self): + path = Path(self.tmp.name, "rollout.jsonl") + rows = [json.loads(line) for line in Path(fixture("codex-mini.jsonl")).read_text().splitlines()] + atomic = next(row for row in rows if row["type"] == "token_usage_record") + write_records(path, rows) + stats = codex.import_codex_file(self.con, str(path)) + key = stats["session_key"] + rid = "codex:" + atomic["payload"]["response_id"] + turn = atomic["payload"]["turn_id"] + self.assertEqual(native_response.inputs(self.con, key)[rid], {turn}) + self.con.execute("DELETE FROM native_response_inputs") + self.con.execute("UPDATE sources SET codex_context_version=6") + self.assertEqual(native_response.inputs(self.con, key)[rid], {turn}) + atomic["payload"]["turn_id"] = "another-turn" + write_records(path, [atomic], "a") + codex.import_codex_file(self.con, str(path)) + self.assertEqual(native_response.inputs(self.con, key)[rid], {turn, "another-turn"}) + legacy = self.sync("codex-legacy-a.jsonl") + self.con.execute("UPDATE responses SET turn_id='codex:guessed' WHERE session_key=?", + (legacy["session_key"],)) + self.assertEqual(native_response.inputs(self.con, legacy["session_key"]), {}) + + def test_opencode_requires_same_session_user_parent_and_replaces_snapshot(self): + path = Path(self.tmp.name, "opencode.db") + build_native(str(path)) + with closing(sqlite3.connect(path)) as source, source: + source.execute("UPDATE message SET data=json_set(data,'$.parentID','msg_u1')" + " WHERE id='msg_a1'") + opencode.sync(self.con, source=str(path)) + self.assertEqual(native_response.inputs(self.con, "opencode:ses_parent"), + {"opencode:msg_a1": {"msg_u1"}}) + with closing(sqlite3.connect(path)) as source, source: + source.execute("UPDATE message SET data=json_set(data,'$.parentID','msg_a1')" + " WHERE id='msg_a1'") + opencode.sync(self.con, source=str(path), full=True) + self.assertEqual(native_response.inputs(self.con, "opencode:ses_parent"), {}) + + def test_grok_only_explicit_input_index_to_completion_id(self): + root = next(Path(fixture("grok")).glob("*/*0001")) + path = Path(self.tmp.name, root.name) + path.mkdir() + rows = [] + for line in (root / "updates.jsonl").read_text().splitlines(): + try: + row = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(row, dict) and isinstance(row.get("params"), dict): + rows.append(row) + write_records(path / "updates.jsonl", reversed(rows)) + key = "grok:" + root.name + grok.import_grok_session(self.con, str(path)) + self.assertEqual(native_response.inputs(self.con, key)[key + ":p-aaa"], {"prompt:0"}) + # The completion still exists and still names p-aaa after the literal bridge is removed. + for row in rows: + row["params"].get("_meta", {}).pop("promptId", None) + write_records(path / "updates.jsonl", rows) + grok.import_grok_session(self.con, str(path), full=True) + self.assertNotIn(key + ":p-aaa", native_response.inputs(self.con, key)) + + def test_grok_completion_and_input_in_separate_copies_and_competing_index(self): + sid = "sid" + key = "grok:sid" + source_dirs = [Path(self.tmp.name, name, sid) for name in ("completed", "input", "copy")] + for path in source_dirs: + path.mkdir(parents=True) + def frame(data, **meta): + return {"method": "session/update", + "params": {"sessionId": sid, "update": data, "_meta": meta}} + completed = frame({"sessionUpdate": "turn_completed", "prompt_id": "p"}) + chunk = {"sessionUpdate": "user_message_chunk", "_meta": {"promptIndex": 3}, + "content": {"type": "text", "text": "question"}} + write_records(source_dirs[0] / "updates.jsonl", [completed]) + write_records(source_dirs[1] / "updates.jsonl", [frame(chunk, promptId="p")]) + for path in source_dirs[:2]: + grok.import_grok_session(self.con, str(path)) + self.assertEqual(native_response.inputs(self.con, key), {"grok:sid:p": {"prompt:3"}}) + write_records(source_dirs[2] / "updates.jsonl", [frame(chunk, promptId="different")]) + grok.import_grok_session(self.con, str(source_dirs[2])) + self.assertEqual(native_response.inputs(self.con, key), {}) + + def test_opencode_different_copies_preserve_competing_native_parents(self): + for copy, parent in enumerate(("msg_u1", "msg_u2")): + path = Path(self.tmp.name, f"copy-{copy}.db") + build_native(str(path)) + with closing(sqlite3.connect(path)) as source, source: + source.execute("INSERT INTO message SELECT 'msg_u2',session_id,time_created," + "time_updated,data FROM message WHERE id='msg_u1'") + source.execute("UPDATE message SET data=json_set(data,'$.parentID',?)" + " WHERE id='msg_a1'", (parent,)) + opencode.sync(self.con, source=str(path)) + self.con.execute("PRAGMA query_only=ON") + self.assertEqual(native_response.inputs(self.con, "opencode:ses_parent"), + {"opencode:msg_a1": {"msg_u1", "msg_u2"}}) + + def test_query_only_legacy_ledger(self): + self.con.execute("PRAGMA query_only=ON") + for session in ("claude:s", "codex:s", "opencode:s", "grok:s"): + self.assertEqual(native_response.inputs(self.con, session), {}) From 855a9575d1745881abcc53616db61516338e3c56 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 18:58:42 +0100 Subject: [PATCH 03/44] wip: mirror Chromeria run purposes and native execution evidence --- agent_observer/adapters/t3.py | 94 ++-- agent_observer/adapters/t3_purpose.py | 650 ++++++++++++++++++++++++++ tests/test_t3_purpose.py | 282 +++++++++++ 3 files changed, 992 insertions(+), 34 deletions(-) create mode 100644 agent_observer/adapters/t3_purpose.py create mode 100644 tests/test_t3_purpose.py diff --git a/agent_observer/adapters/t3.py b/agent_observer/adapters/t3.py index 2ed9efc..00edc4c 100644 --- a/agent_observer/adapters/t3.py +++ b/agent_observer/adapters/t3.py @@ -23,13 +23,15 @@ (``resume`` for Claude, ``threadId`` for Codex, ``sessionId`` for OpenCode). Claude sessions rotated under one thread are also found through their turn-start uuids in ``submissions``. -- thread trees: child ids of the form ``sub..`` +- legacy thread trees: child ids of the form ``sub..`` (nesting allowed) group under their root. Every PR or Issue linked anywhere in a tree becomes one task (``#``); every native session in the tree is wholly bound to every tree task through ``session_assignments``. A one-link tree attributes exclusively; a multi-link tree lands in the shared joint bucket under the existing - semantics and is never divided. + semantics and is never divided. Purpose-aware trees instead use the run, + attempt, provider input and segment mirrors in t3_purpose. Their session + evidence records participation independently of response ownership. - acceptance: the PR snapshot ``state``; ``merged`` completes the task outcome, every other state stays explicit, and nothing is inferred from exit codes (which are never read). @@ -66,6 +68,7 @@ import sqlite3 from .. import db, privacy +from . import t3_purpose # A PR head branch as T3 snapshots it; anything else is not stored. BRANCH_RE = re.compile(r"^[A-Za-z0-9._/-]{1,200}$") @@ -75,7 +78,7 @@ CAPABILITIES = [ ("turn_origin", True, "T3 turn-start actor_kind maps Claude sdk prompts to genuine (client) or synthetic (server)"), ("thread_sessions", True, "provider resume cursors map T3 threads to native Claude, Codex and OpenCode sessions"), - ("workload_binding", True, "thread-tree PR/Issue links become repo#N tasks with whole-session ownership; multi-link trees stay shared whole"), + ("workload_binding", True, "v1 run purposes and native input identities; legacy-only trees retain linked sessions"), ("acceptance", True, "merged PR snapshots complete task outcomes; other states stay explicit"), ("tool_calls", False, "no tool evidence is imported from T3 state"), ("human_input", False, "no user messages are synthesized; existing user messages are only reclassified"), @@ -147,24 +150,26 @@ def _ensure_tables(con: sqlite3.Connection) -> None: " provider TEXT," " adapter_key TEXT," " native_session TEXT NOT NULL)") - con.execute( + links_schema = ( "CREATE TABLE IF NOT EXISTS t3_links(" - " thread_id TEXT NOT NULL," - " kind TEXT NOT NULL," - " host TEXT NOT NULL," - " repository TEXT NOT NULL," - " number INTEGER NOT NULL," - " url TEXT NOT NULL," - " source TEXT," - " state TEXT," - " linked_at TEXT," - " PRIMARY KEY (thread_id, kind, repository, number))") + " thread_id TEXT NOT NULL, kind TEXT NOT NULL, host TEXT NOT NULL," + " repository TEXT NOT NULL, number INTEGER NOT NULL, url TEXT NOT NULL," + " source TEXT, state TEXT, linked_at TEXT, head_branch TEXT," + " PRIMARY KEY (thread_id, kind, host, repository, number))") + con.execute(links_schema) + link_columns = {r["name"]: r["pk"] for r in con.execute("PRAGMA table_info(t3_links)")} + if not link_columns["host"]: + # Old navigation mirrors keyed only on repository and number. + head = "head_branch" if "head_branch" in link_columns else "NULL" + con.execute("ALTER TABLE t3_links RENAME TO t3_links_old_key") + con.execute(links_schema) + con.execute("INSERT INTO t3_links SELECT thread_id,kind,host,repository,number," + f"url,source,state,linked_at,{head} FROM t3_links_old_key") + con.execute("DROP TABLE t3_links_old_key") if "opened_by" not in {r["name"] for r in con.execute("PRAGMA table_info(t3_threads)")}: # Who created the thread: client (a person), server (an agent or # the system), or NULL without evidence (V1 threads). con.execute("ALTER TABLE t3_threads ADD COLUMN opened_by TEXT") - if "head_branch" not in {r["name"] for r in con.execute("PRAGMA table_info(t3_links)")}: - con.execute("ALTER TABLE t3_links ADD COLUMN head_branch TEXT") con.execute( "CREATE TABLE IF NOT EXISTS t3_spawns(" " thread_id TEXT PRIMARY KEY," @@ -344,13 +349,22 @@ def sync(con: sqlite3.Connection, root: str | None = None, if not os.path.exists(path): totals["skipped"] = f"no T3 state at {path}" return totals - _ensure_tables(con) try: native = _open_read_only(path) except (sqlite3.Error, OSError, ValueError) as exc: totals["failed"].append({"path": path, "error": str(exc)}) return totals + # Keep the source at one WAL snapshot and the ledger under its caller's + # transaction. A failed refresh must preserve the previous complete mirror. + if not con.in_transaction: + con.execute("BEGIN") + con.execute("SAVEPOINT t3_refresh") try: + native.execute("BEGIN") + _ensure_tables(con) + tables = {r[0] for r in native.execute("SELECT name FROM sqlite_master WHERE type='table'")} + task_count_before = con.execute("SELECT count(*) FROM tasks").fetchone()[0] + aware_threads = t3_purpose.refresh(con, native, tables) lineage = _v2_lineage(native) totals["v2_threads"] = len(lineage) _import_turn_origins(con, native, path, totals) @@ -363,8 +377,8 @@ def sync(con: sqlite3.Connection, root: str | None = None, from .. import intervention_evidence intervention_evidence.backfill_root_reasons(con) totals["responses_retouched"] = _retouch_response_turns(con) - bound = _bind_trees(con, threads, links, lineage) - totals["tasks"] = bound["tasks"] + bound = _bind_trees(con, threads, links, lineage, aware_threads) + totals["tasks"] = con.execute("SELECT count(*) FROM tasks").fetchone()[0] - task_count_before totals["sessions_bound"] = bound["sessions_bound"] totals["outcomes"] = _write_outcomes(con, links) con.execute( @@ -374,8 +388,13 @@ def sync(con: sqlite3.Connection, root: str | None = None, (HARNESS, path, _state_marker(path), db.now())) totals["sources"] = 1 except sqlite3.DatabaseError as exc: + con.execute("ROLLBACK TO t3_refresh") totals["failed"].append({"path": path, "error": str(exc)}) + except BaseException: + con.execute("ROLLBACK TO t3_refresh") + raise finally: + con.execute("RELEASE t3_refresh") try: native.close() except sqlite3.Error: @@ -879,14 +898,14 @@ def _import_links(con: sqlite3.Connection, native: sqlite3.Connection, if isinstance(row["linked_at"], str) else None}) unique: dict[tuple, dict] = {} for link in links: - unique[(link["thread_id"], link["kind"], link["repository"], + unique[(link["thread_id"], link["kind"], link["host"], link["repository"], link["number"])] = link links = list(unique.values()) for link in links: con.execute( "INSERT INTO t3_links(thread_id, kind, host, repository, number," " url, source, state, linked_at, head_branch) VALUES(?,?,?,?,?,?,?,?,?,?)" - " ON CONFLICT(thread_id, kind, repository, number) DO UPDATE SET" + " ON CONFLICT(thread_id, kind, host, repository, number) DO UPDATE SET" " host=excluded.host, url=excluded.url, source=excluded.source," " state=excluded.state, linked_at=excluded.linked_at," " head_branch=COALESCE(excluded.head_branch, t3_links.head_branch)", @@ -1174,13 +1193,9 @@ def _tree_sessions(con: sqlite3.Connection, threads: dict, return out -def _task_id(repository: str, number: int) -> str: - return f"{repository}#{number}" - - def _bind_trees(con: sqlite3.Connection, threads: dict, - links: list, lineage: dict | None = None) -> dict: - """Create repo#N tasks and bind every tree session to every tree link.""" + links: list, lineage: dict | None = None, aware_threads=()) -> dict: + """Retain legacy bindings only where the whole-tree inference still applies.""" lineage = lineage or {} roots: dict[str, list[str]] = {} for row in con.execute( @@ -1198,15 +1213,26 @@ def _bind_trees(con: sqlite3.Connection, threads: dict, tree_links.setdefault(_lineage_root(link["thread_id"], lineage), []).append(link) sessions = _tree_sessions(con, threads, roots) + aware_roots = {_lineage_root(t, lineage) for t in aware_threads} + protected = {row[0] for row in con.execute("SELECT session_key FROM t3_purpose_sessions")} + # Historical/rotated sessions can outlive their cursor and their tree. + # This read proves previous whole-session placement unsafe for these keys. + con.execute("DELETE FROM session_assignments WHERE evidence GLOB 't3:*:https://*'" + " AND session_key IN (SELECT session_key FROM t3_purpose_sessions)") + for root, members in roots.items(): + if aware_threads and any(t in aware_threads for t in members): + aware_roots.add(root) + for root in aware_roots: + protected.update(sessions.get(root, ())) tasks = 0 bound = 0 wanted: set = set() for root, root_links in tree_links.items(): seen: dict[tuple, dict] = {} for link in root_links: - seen.setdefault((link["repository"], link["number"]), link) - for (repository, number), link in sorted(seen.items()): - task_id = _task_id(repository, number) + seen.setdefault((link["host"], link["repository"], link["number"]), link) + for (host, repository, number), link in sorted(seen.items()): + task_id = t3_purpose.task_id(con, host, repository, number) cur = con.execute( "INSERT OR IGNORE INTO tasks(task_id, project, title," " issue_url, origin, created_at)" @@ -1214,7 +1240,7 @@ def _bind_trees(con: sqlite3.Connection, threads: dict, (task_id, repository, task_id, link["url"], HARNESS, db.now())) tasks += cur.rowcount - for session_key in sorted(sessions.get(root, set())): + for session_key in sorted(sessions.get(root, set()) - protected): wanted.add((session_key, task_id)) cur = con.execute( "INSERT OR IGNORE INTO session_assignments(session_key," @@ -1227,11 +1253,11 @@ def _bind_trees(con: sqlite3.Connection, threads: dict, # changed PR). Trees absent from this read keep their history, and # bindings made outside this adapter are never touched. present = {_lineage_root(t, lineage) for t in threads} | set(tree_links) - for root in sorted(present): + for root in sorted(present | aware_roots): for row in con.execute( "SELECT session_key, task_id FROM session_assignments" " WHERE substr(evidence, 1, ?)=?", - (len(f"t3:{root}:"), f"t3:{root}:")).fetchall(): + (len(f"t3:{root}:https://"), f"t3:{root}:https://")).fetchall(): if (row["session_key"], row["task_id"]) not in wanted: con.execute( "DELETE FROM session_assignments" @@ -1300,7 +1326,7 @@ def _write_outcomes(con: sqlite3.Connection, links: list) -> int: per_task: dict[str, list] = {} for link in links: per_task.setdefault( - _task_id(link["repository"], link["number"]), []).append(link) + t3_purpose.task_id(con, link["host"], link["repository"], link["number"]), []).append(link) written = 0 for task_id in sorted(per_task): task = con.execute("SELECT origin FROM tasks WHERE task_id=?", diff --git a/agent_observer/adapters/t3_purpose.py b/agent_observer/adapters/t3_purpose.py new file mode 100644 index 0000000..83d6f8d --- /dev/null +++ b/agent_observer/adapters/t3_purpose.py @@ -0,0 +1,650 @@ +"""Local mirror of Chromeria's v1 executionPurpose and nativeExecution contracts. + +Inputs are literal provider identities, before harness-specific ledger namespacing. +Sessions describe participation only. Segment and inventory rows describe native +evidence even when no input boundary or reconciled final usage exists. +""" +from __future__ import annotations + +from datetime import datetime +import json +import re +from typing import NamedTuple + +from .. import db + + +# Separate tables keep an expected attempt with a missing turn, an unresolved +# segment, and an independently counted main-agent turn distinguishable. +TABLES = { + "runs": """run_id TEXT PRIMARY KEY, thread_id TEXT NOT NULL, task_id TEXT, + scope TEXT NOT NULL, reason TEXT, host TEXT, repository TEXT, kind TEXT, number INTEGER, + provenance_json TEXT, status TEXT, version INTEGER, active_attempt_id TEXT""", + "sessions": """run_id TEXT NOT NULL, session_key TEXT NOT NULL, + PRIMARY KEY(run_id,session_key)""", + "inputs": """run_id TEXT NOT NULL, session_key TEXT NOT NULL, native_id TEXT NOT NULL, + kind TEXT NOT NULL, validation TEXT NOT NULL, attempt_id TEXT, provider_turn_id TEXT, + segment_id TEXT""", + "deliveries": """task_id TEXT NOT NULL, thread_id TEXT NOT NULL, host TEXT NOT NULL, + repository TEXT NOT NULL, number INTEGER NOT NULL, url TEXT NOT NULL, declared_at TEXT NOT NULL, + PRIMARY KEY(task_id,thread_id,url,declared_at)""", + "attempts": """attempt_id TEXT PRIMARY KEY, run_id TEXT NOT NULL, provider_thread_id TEXT, + provider_turn_id TEXT, status TEXT, session_key TEXT, provider_session_id TEXT""", + "turns": """provider_turn_id TEXT PRIMARY KEY, attempt_id TEXT NOT NULL, run_id TEXT NOT NULL, + session_key TEXT, status TEXT, usage_json TEXT, context_usage_json TEXT""", + "capabilities": """provider_session_id TEXT PRIMARY KEY, driver TEXT, native_inputs TEXT, + child_segments TEXT, background_inventory TEXT, native_usage_finality TEXT""", + "segments": """owner_id TEXT NOT NULL, thread_id TEXT NOT NULL, segment_id TEXT NOT NULL, + subagent_id TEXT, run_id TEXT, task_id TEXT, kind TEXT, driver TEXT, native_session_id TEXT, + native_operation_id TEXT, native_child_id TEXT, source_json TEXT, boundary_json TEXT, + status TEXT, usage_finality TEXT, notice_ids_json TEXT, wake_dispositions_json TEXT, + provenance_json TEXT, observed_at TEXT, PRIMARY KEY(thread_id,owner_id,segment_id)""", + "child_turns": """run_id TEXT NOT NULL, segment_id TEXT NOT NULL, provider_turn_id TEXT NOT NULL, + session_key TEXT NOT NULL, status TEXT, usage_json TEXT, context_usage_json TEXT, + PRIMARY KEY(run_id,segment_id,provider_turn_id)""", + "workflow_members": """thread_id TEXT NOT NULL, subagent_id TEXT NOT NULL, member_index INTEGER NOT NULL, + attempt INTEGER, agent_id TEXT, child_thread_id TEXT, state TEXT, total_tokens INTEGER""", + "participants": """run_id TEXT, thread_id TEXT NOT NULL, kind TEXT NOT NULL, participant_id TEXT, + child_thread_id TEXT, child_run_id TEXT, environment_id TEXT, status TEXT, group_id TEXT, availability TEXT, declaration_json TEXT""", +} +PROJECTION = "orchestration_v2_projection_" +ID = re.compile(r"[a-zA-Z0-9._:%/@+~=,-]{1,8192}", re.ASCII) +HOST = re.compile(r"[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?(?::[0-9]+)?", re.I | re.ASCII) +REPO = re.compile(r"[a-z0-9_.-]+/[a-z0-9_.-]+", re.I | re.ASCII) +MAX_INT = 2 ** 53 - 1 +DRIVERS = {"codex": "codex", "claudeAgent": "claude", "opencode": "opencode", + "opencode2": "opencode", "grok": "grok", "muse": "muse"} +INPUT_TYPES = {"codex": ("turn", "codex_turn_started"), + "claudeAgent": ("message", "claude_prompt_echo"), + "opencode": ("message", "opencode_admitted_message")} +STATES = ("pending", "preparing", "queued", "starting", "running", "waiting", "completed", + "failed", "cancelled", "superseded", "interrupted", "rolled_back") +INVALID = ("invalid", "invalid_purpose", None, None) + + +def _id(value): + return value if isinstance(value, str) and ID.fullmatch(value) else None + + +def _number(value): + return type(value) is int and 0 <= value <= MAX_INT + + +def _v1(value): + return type(value.get("version")) is int and value["version"] == 1 + + +def _list(value): + return value if isinstance(value, list) else [] + + +def _obj(value): + return value if isinstance(value, dict) else {} + + +def _enum(value, choices): + return value if isinstance(value, str) and value in choices else None + + +def _date(value): + if isinstance(value, str) and len(value) <= 40 and "T" in value: + try: + if datetime.fromisoformat(value.replace("Z", "+00:00")).tzinfo is not None: + return value + except ValueError: + pass + return None + + +def _json(value): + return json.dumps(value, sort_keys=True, separators=(",", ":")) if value is not None else None + + +def _reference(value): + ref = _obj(value) + host, repo = ref.get("host"), ref.get("repository") + n, kind = ref.get("number"), ref.get("kind") + if (isinstance(host, str) and HOST.fullmatch(host) and len(host) <= 253 + and isinstance(repo, str) and REPO.fullmatch(repo) and len(repo) <= 200 + and kind in ("issue", "pr") and _number(n) and n > 0): + return dict(host=host.lower(), repository=repo.lower(), kind=kind, number=n) + + +def task_id(con, host, repository, number): + prefix = "" if host.lower() == "github.com" else host.lower() + "/" + canonical = f"{prefix}{repository.lower()}#{number}" + if con.execute("SELECT 1 FROM tasks WHERE task_id=?", (canonical,)).fetchone(): + return canonical + # Existing GitHub links used the repository's original capitalization. + # Keep the original ledger key (including its assignments and outcomes). + prior = con.execute("SELECT task_id FROM tasks WHERE task_id=? COLLATE NOCASE LIMIT 2", + (canonical,)).fetchall() + return prior[0][0] if len(prior) == 1 else canonical + + +def _url(ref): + path = "issues" if ref["kind"] == "issue" else "pull" + return f"https://{ref['host']}/{ref['repository']}/{path}/{ref['number']}" + + +def _task(con, ref): + key = task_id(con, ref["host"], ref["repository"], ref["number"]) + con.execute("INSERT OR IGNORE INTO tasks(task_id,project,title,issue_url,origin,created_at)" + " VALUES(?,?,?,?, 't3',?)", (key, ref["repository"], key, _url(ref), db.now())) + return key + + +def _provenance(value): + value = _obj(value) + kind = value.get("type") + if kind in ("declared", "legacy"): + return {"type": kind} + if kind == "selection" and _number(value.get("revision")): + return {"type": kind, "revision": value["revision"]} + if kind in ("native_operation", "delegated_completion"): + ids = value.get("operationIds") + if isinstance(ids, list) and all(_id(i) for i in ids): + return {"type": kind, "operationIds": ids} + if kind == "pull_request_watch": + ref = _reference(value.get("reference")) + date = _date(value.get("startedAt")) + if ref and date: + return {"type": kind, "reference": ref, "startedAt": date} + fields = {"parent_run": ("threadId", "runId"), "source_run": ("threadId", "runId"), + "target_run": ("threadId", "runId"), "delegated_launch": ("threadId", "runId", "taskId"), + "remote_launch": ("threadId", "runId", "environmentId", "launchId"), + "schedule": ("scheduledTaskId",)} + if isinstance(kind, str) and kind in fields and all(_id(value.get(k)) for k in fields[kind]): + return {"type": kind, **{k: value[k] for k in fields[kind]}} + + +def _purpose(value): + p = _obj(value) + provenance = _provenance(p.get("provenance")) + if not _v1(p) or provenance is None: + return INVALID + scope = _obj(p.get("scope")) + if scope.get("type") == "single": + ref = _reference(scope.get("reference")) + if ref: + return "single", None, ref, provenance + if scope.get("type") == "unscoped" and scope.get("reason") in ( + "deliberate", "legacy_no_intent", "mixed", "unknown_cause"): + return "unscoped", scope["reason"], None, provenance + return INVALID + + +def _rows(native, tables, name, where=""): + if PROJECTION + name not in tables: + return + for row in native.execute("SELECT * FROM " + PROJECTION + name + where): + row = dict(row) + try: + payload = json.loads(row.pop("payload_json", None)) + except (ValueError, TypeError, RecursionError): + payload = None + yield row, _obj(payload) + + +def _insert(con, table, *values): + con.execute("INSERT OR IGNORE INTO t3_purpose_" + table + " VALUES(" + + ",".join("?" for _ in values) + ")", values) + + +def _participant(con, run, thread, kind, participant, *, child=None, child_run=None, remote=None, + status=None, group=None, declaration=None): + remote = _obj(remote) + scope, reason, ref, provenance = _purpose(declaration) + declared = None + if declaration is not None: + declared = dict(scope=scope, reason=reason, reference=ref, provenance=provenance) + if ref: + _task(con, ref) + _insert(con, "participants", run, thread, kind, _id(participant), _id(remote.get("threadId") or child), + _id(child_run or remote.get("runId")), _id(remote.get("environmentId")), _enum(status, STATES), + _id(group), _enum(remote.get("availability"), ("current", "stale", "unsupported", "lost")), + _json(declared)) + + +class Provider(NamedTuple): + thread: str + driver: str + instance: str | None + session: str | None + native_session: str | None + + +class Segment(NamedTuple): + subagent: str | None + driver: str + native_session: str + operation: str + kind: str + payload: dict + source: dict + purpose: tuple + boundary: dict + + +def _matches(row, payload, *pairs): + return all(column in row and key in payload and row[column] == payload[key] + for column, key in pairs) + + +def _strong(value, driver): + ref = _obj(value) + if ref.get("strength") == "strong" and ref.get("driver") == driver: + return _id(ref.get("nativeId")) + + +def _deliveries(con, native, tables): + aware = set() + for row, p in _rows(native, tables, "threads"): + thread = _id(row.get("thread_id")) + if not thread or p.get("id") != thread: + continue + if "purposeSelection" in p or p.get("purposeDeliveries"): + aware.add(thread) + for d in map(_obj, _list(p.get("purposeDeliveries"))): + purpose, pr = _reference(d.get("purpose")), _reference(d.get("pullRequest")) + at = _date(d.get("declaredAt")) + if _v1(d) and purpose and pr and pr["kind"] == "pr" and at: + _insert(con, "deliveries", _task(con, purpose), thread, pr["host"], + pr["repository"], pr["number"], _url(pr), at) + return aware + + +def _runs(con, native, tables): + runs = {} + for row, p in _rows(native, tables, "runs"): + run, thread = _id(row.get("run_id")), _id(row.get("thread_id")) + if not run or not thread or (p and "purpose" not in p): + continue # A readable pre-v1 run keeps its existing legacy treatment. + purpose = _purpose(p.get("purpose")) if _matches( + row, p, ("run_id", "id"), ("thread_id", "threadId")) else INVALID + scope, reason, ref, provenance = purpose + key = _task(con, ref) if ref else None + coords = ref or {} + status = _enum(row.get("status"), STATES) + version = _obj(p.get("purpose")).get("version") + _insert(con, "runs", run, thread, key, scope, reason, coords.get("host"), + coords.get("repository"), coords.get("kind"), coords.get("number"), + _json(provenance), status, version if _number(version) else None, + _id(p.get("activeAttemptId"))) + runs[run] = (thread, purpose) + delivery = _obj(_obj(p.get("delegatedCompletion")).get("delivery")) + for task in _list(delivery.get("taskIds")): + if _id(task): + _participant(con, run, thread, "completion_member", task) + for cause in map(_obj, _list(delivery.get("purposeCauses"))): + if _id(cause.get("taskId")) and _id(cause.get("runId")): + _participant(con, run, thread, "completion_cause", cause["taskId"], + child_run=cause["runId"], declaration=cause.get("purpose")) + for work in map(_obj, _list(p.get("restartCancelledBackgroundWork"))): + category = _enum(work.get("kind"), ("subagent", "shell", "monitor", "task")) + if category: + _participant(con, run, thread, "cancelled_" + category, work.get("id"), status="cancelled") + return runs + + +def _usage(value, context=False): + p = _obj(value) + if context: + if not _number(p.get("usedTokens")): + return None + result = {"usedTokens": p["usedTokens"]} + fields = ("inputTokens", "cachedInputTokens", "outputTokens", "reasoningOutputTokens", "maxTokens") + else: + status = _enum(p.get("usageStatus"), ("complete", "partial", "unavailable")) + if (not status or p.get("usageScope") != "main_agent" or type(p.get("hasSubagents")) is not bool + or (status == "complete" and not all(_number(p.get(k)) for k in ("inputTokens", "outputTokens")))): + return None + result = dict(usageScope="main_agent", usageStatus=status, hasSubagents=p["hasSubagents"]) + if "localCommand" in p: + if type(p["localCommand"]) is not bool: + return None + result["localCommand"] = p["localCommand"] + if "otherUsage" in p: + other = _obj(p["otherUsage"]) + if not all(_number(other.get(k)) for k in ("inputTokens", "outputTokens")): + return None + result["otherUsage"] = {k: other[k] for k in ("inputTokens", "outputTokens")} + if "models" in p: + if not isinstance(p["models"], list) or not all(_id(m) for m in p["models"]): + return None + result["models"] = p["models"] + fields = ("inputTokens", "outputTokens", "cachedInputTokens", "cacheCreationTokens", "reasoningTokens") + for k in fields: + if k in p and not (context and k == "maxTokens" and p[k] is None): + if not _number(p[k]): + return None + result[k] = p[k] + return _json(result) + + +def _capabilities(con, native, tables): + for row, p in _rows(native, tables, "provider_sessions"): + session = _id(row.get("provider_session_id")) + cap = _obj(_obj(p.get("capabilities")).get("purposeEvidence")) + if session and session == p.get("id") and _v1(cap): + _insert(con, "capabilities", session, _enum(p.get("driver"), DRIVERS), + _enum(cap.get("nativeInputs"), ("native_turn", "input_echo", "admitted_message", "unsupported")), + _enum(cap.get("childSegments"), ("initial_turn_only", "initial_input_only", "causes_only", "unsupported")), + _enum(cap.get("backgroundInventory"), ("observed_causes", "unsupported")), + _enum(cap.get("nativeUsageFinality"), ("main_agent_only", "unavailable"))) + + +def _providers(con, native, tables, runs, segments): + providers = {} + for row, p in _rows(native, tables, "provider_threads"): + pt = _id(row.get("provider_thread_id")) + thread, driver = _id(row.get("thread_id")), _enum(p.get("driver"), DRIVERS) + if (not pt or not thread or not driver or not _matches(row, p, ("provider_thread_id", "id"), + ("thread_id", "appThreadId")) or row.get("driver", driver) != driver + or row.get("provider_instance_id", p.get("providerInstanceId")) != p.get("providerInstanceId")): + continue + providers[pt] = Provider(thread, driver, _id(p.get("providerInstanceId")), _id(p.get("providerSessionId")), + _strong(p.get("nativeThreadRef"), driver)) + for segment in map(_obj, _list(p.get("nativeOperations"))): + segments.append((thread, pt, None, driver, segment)) + for task in map(_obj, _list(p.get("pendingBackgroundTasks"))): + run = _id(task.get("runId")) + if run in runs and runs[run][0] == thread and _id(task.get("taskId")): + _participant(con, run, thread, "pending_background", task["taskId"], + child=task.get("childThreadId"), remote={"environmentId": task.get("childEnvironmentId")}) + return providers + + +def _subagents(con, native, tables, runs, segments): + children = {} + for row, p in _rows(native, tables, "subagents"): + child = _id(row.get("subagent_id")) + thread, origin = _id(row.get("thread_id")), _enum(p.get("origin"), ("app_owned", "provider_native")) + driver = _enum(p.get("driver"), DRIVERS) + if (not child or not thread or not origin or not _matches(row, p, ("subagent_id", "id"), + ("thread_id", "threadId"), ("origin", "origin"), ("run_id", "runId")) + or row.get("driver", driver) != driver + or row.get("child_thread_id") != p.get("childThreadId")): + continue + run = _id(row["run_id"]) + if run in runs and runs[run][0] == thread: + remote = _obj(p.get("remoteChild")) + _participant(con, run, thread, origin, child, child=p.get("childThreadId"), remote=remote, + status=p.get("status"), group=p.get("runGroupId"), declaration=p.get("purpose")) + completion = _obj(p.get("completionSource")) + if _id(completion.get("runId")): + _participant(con, run, thread, "child_completion", child, child=p.get("childThreadId"), + remote=remote, child_run=completion["runId"], declaration=completion.get("purpose")) + for member in map(_obj, _list(_obj(p.get("workflow")).get("agents"))): + if _number(member.get("index")): + _insert(con, "workflow_members", thread, child, member["index"], + member["attempt"] if _number(member.get("attempt")) else None, + _id(member.get("agentId")), _id(member.get("childThreadId")), + _enum(member.get("state"), ("queued", "running", "completed", "failed")), + member["totalTokens"] if _number(member.get("totalTokens")) else None) + if driver and origin == "provider_native": + children[(thread, child)] = (_id(p.get("childThreadId")), _id(p.get("providerThreadId"))) + for segment in map(_obj, _list(p.get("nativeSegments"))): + segments.append((thread, child, child, driver, segment)) + + return children + + +def _expected_children(con, native, tables, runs): + # A subagent turn item names the expected child even if its own projection + # or the remote ledger is missing. Avoid reading unrelated text/tool items. + for row, p in _rows(native, tables, "turn_items", " WHERE type='subagent'"): + run = _id(row.get("run_id")) + if (run not in runs or runs[run][0] != row.get("thread_id") + or not _matches(row, p, ("run_id", "runId"), ("thread_id", "threadId"), + ("turn_item_id", "id"), ("type", "type")) + or not _id(p.get("subagentId"))): + continue + remote = _obj(p.get("remoteChild")) + _participant(con, run, row["thread_id"], "subagent_item", p["subagentId"], + child=p.get("childThreadId"), remote=remote, status=p.get("status")) + + +def _attempts(con, native, tables, runs, providers): + attempts = {} + for row, p in _rows(native, tables, "run_attempts"): + aid, run = _id(row.get("attempt_id")), _id(row.get("run_id")) + if not aid or run not in runs or row.get("thread_id") != runs[run][0]: + continue + pt = _id(row.get("provider_thread_id")) + turn, root = _id(row.get("provider_turn_id")), _id(row.get("root_node_id")) + provider = providers.get(pt) + valid = (provider and root and provider.thread == runs[run][0] and provider.instance is not None + and p.get("providerInstanceId") == provider.instance + and row.get("provider_instance_id", provider.instance) == provider.instance + and _matches(row, p, ("attempt_id", "id"), ("run_id", "runId"), + ("provider_thread_id", "providerThreadId"), ("provider_turn_id", "providerTurnId"), + ("root_node_id", "rootNodeId"))) + key = None + if valid: + driver = provider.driver + sid = _id(p.get("nativeThreadId")) + if sid: + key = f"{DRIVERS[driver]}:{sid}" + _insert(con, "sessions", run, key) + attempts[aid] = (run, provider.thread, pt, root, turn, driver, sid, "nativeThreadId" in p) + _insert(con, "attempts", aid, run, pt, turn, _enum(p.get("status"), STATES), + key, provider.session if valid else None) + return attempts + + +def _turns(con, native, tables, attempts): + for row, p in _rows(native, tables, "provider_turns", " WHERE run_attempt_id IS NOT NULL"): + aid = _id(row.get("run_attempt_id")) + if aid not in attempts: + continue + run, thread, pt, root, expected, driver, sid, has_destination = attempts[aid] + turn = _id(row.get("provider_turn_id")) + if (not turn or (expected and turn != expected) or row.get("node_id") != root + or row.get("thread_id") != thread or row.get("provider_thread_id") != pt + or not _matches(row, p, ("node_id", "nodeId"), ("provider_turn_id", "id"), + ("run_attempt_id", "runAttemptId"), ("provider_thread_id", "providerThreadId"))): + continue + # A reusable provider thread's latest cursor cannot locate a historical input. + turn_sid = _strong(p.get("nativeThreadRef"), driver) + if "nativeThreadRef" in p and (not turn_sid or (has_destination and turn_sid != sid)): + sid = None + else: + sid = turn_sid or sid + key = f"{DRIVERS[driver]}:{sid}" if sid else None + _insert(con, "turns", turn, aid, run, key, _enum(p.get("status"), STATES), + _usage(p.get("turnTokenUsage")), _usage(p.get("tokenUsage"), context=True)) + if not key: + continue + _insert(con, "sessions", run, key) + witnesses = set() + for i in map(_obj, _list(p.get("nativeInputs"))): + identity = _id(i.get("nativeId")) + pair = (i.get("kind"), i.get("validation")) + if identity and _v1(i) and INPUT_TYPES.get(driver) == pair: + witnesses.add((identity, *pair)) + if driver == "grok": + identity = _strong(p.get("nativeTurnRef"), driver) + if identity and re.fullmatch(r"prompt:(0|[1-9][0-9]{0,15})", identity) and int(identity[7:]) <= MAX_INT: + witnesses.add((identity, "message", "grok_prompt_index")) + if p.get("promptDropped") is not True: + for identity, kind, validation in sorted(witnesses): + _insert(con, "inputs", run, key, identity, kind, validation, aid, turn, None) + + +# Native unresolved reasons are open strings. Only known codes can leave the source. +REASONS = frozenset(""" + workflow_member_native_input_boundary_missing owning_child_segment_unresolved + owning_child_call_missing native_start_call_missing native_start_call_not_observed + child_native_input_boundary_missing claude_resume_response_boundary_missing + background_start_call_not_observed background_native_usage_boundary_unavailable + background_start_not_observed codex_owning_child_turn_unresolved awaiting_initial_native_child_turn + codex_resume_response_boundary_missing opencode_child_resume_boundary_missing + awaiting_initial_native_child_input +""".split()) + + +def _source(value): + s = _obj(value) + kind = s.get("type") + if kind in ("app_run", "native_segment"): + keys = ("threadId", "runId") if kind == "app_run" else ("threadId", "subagentId", "segmentId") + if all(_id(s.get(k)) for k in keys): + return {"type": kind, **{k: s[k] for k in keys}} + return {"type": "unresolved", "reason": _enum(s.get("reason"), REASONS) or "unknown"} + + +def _boundary(value): + b = _obj(value) + if b.get("state") == "native_turns": + turns = _list(b.get("nativeTurnIds")) + if turns and all(_id(t) for t in turns): + return dict(state="native_turns", nativeTurnIds=turns) + if b.get("state") == "native_input" and _id(b.get("nativeInputId")): + return dict(state="native_input", nativeInputId=b["nativeInputId"]) + return {"state": "unresolved", "reason": _enum(b.get("reason"), REASONS) or "unknown"} + + +def _segments(con, rows, runs, children): + child_boundaries = {} + # An enclosing subagent's runId names its original launch. Each segment + # carries its own initiating run or earlier segment, including on resume. + segments = {} + for thread, owner, subagent, driver, p in rows: + sid, operation, segment = (_id(p.get(k)) for k in ("nativeSessionId", "nativeOperationId", "id")) + kind = _enum(p.get("kind"), ("start", "resume", "workflow_member", "background")) + if not (_v1(p) and sid and operation and segment and kind and p.get("usageFinality") == "unreconciled" + and p.get("status") in ("running", "ended", "roster_absent", "interrupted", "unknown")): + continue + key = thread, owner, segment + data = Segment(subagent, driver, sid, operation, kind, p, _source(p.get("source")), + _purpose(p.get("purpose")), _boundary(p.get("boundary"))) + # Conflicting copies of one initiating operation cannot prove inputs. + if key in segments and segments[key] != data: + segments[key] = None + else: + segments[key] = data + + destinations = {(r[0], r[1]) for r in con.execute( + "SELECT run_id,session_key FROM t3_purpose_sessions")} + resolved = {} + # Resolve exact predecessor edges independent of projection table order. + # Unresolved edges, cycles, crossed scopes and crossed sessions stay gaps. + pending = {k for k, v in segments.items() if v} + while pending: + done = set() + for key in pending: + subagent, driver, sid, op, kind, p, source, purpose, boundary = segments[key] + if purpose == INVALID: + continue + if source["type"] == "app_run": + run = source["runId"] + if (runs.get(run) != (source["threadId"], purpose) + or (run, f"{DRIVERS[driver]}:{sid}") not in destinations): + continue + elif source["type"] == "native_segment": + parent = source["threadId"], source["subagentId"], source["segmentId"] + run = resolved.get(parent) + if run is None: + continue + parent_data = segments[parent] + if (not parent_data.subagent or parent_data.driver != driver + or parent_data.payload.get("nativeChildId") != sid + or parent_data.purpose != purpose or parent_data.boundary["state"] == "unresolved"): + continue + else: + continue + resolved[key] = run + done.add(key) + if not done: + break + pending -= done + + for key, data in segments.items(): + if data is None: + continue + thread, owner, segment = key + subagent, driver, sid, operation, kind, p, source, purpose, boundary = data + child = _id(p.get("nativeChildId")) + run = resolved.get(key) + ref = purpose[2] + _insert(con, "segments", owner, thread, segment, subagent, run, + _task(con, ref) if ref else None, + kind, driver, sid, operation, child, _json(source), _json(boundary), + _enum(p.get("status"), ("running", "ended", "roster_absent", "interrupted", "unknown")), + _enum(p.get("usageFinality"), ("unreconciled",)), + _json([i for i in _list(p.get("noticeIds")) if _id(i)]), + _json([i for i in _list(p.get("wakeDispositions")) if i in ( + "offered", "consumed_in_active", "dropped_disabled", "dropped_restart", "duplicate")]), + _json(purpose[3]), _date(p.get("observedAt"))) + if not (run and subagent and child and kind != "background"): + continue + if driver not in ("codex", "opencode"): + continue + child_key = f"{DRIVERS[driver]}:{child}" + _insert(con, "sessions", run, child_key) + # Current native contracts certify only Codex child turn boundaries + # and OpenCode child input boundaries. Claude task ids are reusable. + if driver == "codex" and boundary["state"] == "native_turns": + ids = boundary["nativeTurnIds"] + input_kind = "turn" + elif driver == "opencode" and boundary["state"] == "native_input": + ids = [boundary["nativeInputId"]] + input_kind = "message" + else: + continue + child_thread, child_pt = children[(thread, subagent)] + for identity in sorted(set(ids)): + _insert(con, "inputs", run, child_key, identity, input_kind, + "segment_" + boundary["state"], None, None, segment) + if child_thread and child_pt: + lookup = (child_thread, child_pt, driver, child, identity) + child_boundaries.setdefault(lookup, set()).add((run, segment)) + return child_boundaries + + +def _child_turns(con, native, tables, boundaries, providers): + if not boundaries: + return + for row, p in _rows(native, tables, "provider_turns", " WHERE run_attempt_id IS NULL"): + pt, turn = _id(row.get("provider_thread_id")), _id(row.get("provider_turn_id")) + provider = providers.get(pt) + if (not turn or not provider or provider.thread != row.get("thread_id") + or not _matches(row, p, ("provider_turn_id", "id"), ("node_id", "nodeId"), + ("provider_thread_id", "providerThreadId"), ("run_attempt_id", "runAttemptId"))): + continue + thread, driver, _, _, provider_sid = provider + sid = _strong(p["nativeThreadRef"], driver) if "nativeThreadRef" in p else provider_sid + for i in map(_obj, _list(p.get("nativeInputs"))): + native_id = _id(i.get("nativeId")) + if not native_id or not _v1(i) or (i.get("kind"), i.get("validation")) != INPUT_TYPES.get(driver): + continue + for run, segment in boundaries.get((thread, pt, driver, sid, native_id), ()): + _insert(con, "child_turns", run, segment, turn, f"{DRIVERS[driver]}:{sid}", + _enum(p.get("status"), STATES), _usage(p.get("turnTokenUsage")), + _usage(p.get("tokenUsage"), context=True)) + + + +def refresh(con, native, tables): + """Replace the evidence under the caller's snapshot and ledger savepoint.""" + for table, columns in TABLES.items(): + con.execute(f"CREATE TABLE IF NOT EXISTS t3_purpose_{table} ({columns})") + con.execute(f"DELETE FROM t3_purpose_{table}") + con.execute("CREATE INDEX IF NOT EXISTS t3_purpose_runs_task ON t3_purpose_runs(task_id)") + con.execute("CREATE INDEX IF NOT EXISTS t3_purpose_inputs_native" + " ON t3_purpose_inputs(session_key,native_id)") + con.execute("CREATE INDEX IF NOT EXISTS t3_purpose_inputs_run ON t3_purpose_inputs(run_id)") + aware = _deliveries(con, native, tables) + runs = _runs(con, native, tables) + if runs: + _capabilities(con, native, tables) + segments = [] + providers = _providers(con, native, tables, runs, segments) + attempts = _attempts(con, native, tables, runs, providers) + _turns(con, native, tables, attempts) + children = _subagents(con, native, tables, runs, segments) + _expected_children(con, native, tables, runs) + boundaries = _segments(con, segments, runs, children) + _child_turns(con, native, tables, boundaries, providers) + return aware | {thread for thread, _ in runs.values()} diff --git a/tests/test_t3_purpose.py b/tests/test_t3_purpose.py new file mode 100644 index 0000000..b7e7664 --- /dev/null +++ b/tests/test_t3_purpose.py @@ -0,0 +1,282 @@ +"""Projection fixtures use Chromeria #377's v1 JSON and relational identities.""" +import json +import os +import sqlite3 + +from agent_observer.adapters import t3 +from tests.helpers import LedgerCase + +PREFIX = "orchestration_v2_projection_" +TIME = "2026-11-25T01:00:00.000Z" +REF = dict(host="github.com", repository="Example/Project", kind="issue", number=7) +PURPOSE = dict(version=1, scope=dict(type="single", reference=REF), + provenance=dict(type="selection", revision=2)) + + +def strong(driver, native_id): + return dict(driver=driver, strength="strong", nativeId=native_id) + + +class NativePurposeTest(LedgerCase): + def setUp(self): + super().setUp() + self.path = os.path.join(self.tmp.name, "chromeria-v2.sqlite") + self.native = sqlite3.connect(self.path) + self.addCleanup(self.native.close) + tables = { + "threads": "thread_id,created_at", + "runs": "run_id,thread_id,status", + "run_attempts": "attempt_id,run_id,thread_id,provider_thread_id,provider_turn_id,root_node_id", + "provider_turns": "provider_turn_id,thread_id,provider_thread_id,run_attempt_id,node_id", + "provider_threads": "provider_thread_id,thread_id,driver,provider,updated_at", + "subagents": "subagent_id,thread_id,run_id,origin,driver,child_thread_id", + } + for name, columns in tables.items(): + self.native.execute(f"CREATE TABLE {PREFIX}{name} ({columns},payload_json)") + self.row("threads", ["t", TIME], { + "id": "t", "purposeDeliveries": [ + {"version": 1, "purpose": REF, "pullRequest": dict(REF, kind="pr", number=99), + "declaredAt": TIME}]}) + self.provider("codex") + self.run_turn("a", "codex", PURPOSE, [{"version": 1, "kind": "turn", + "nativeId": "cx-A", "validation": "codex_turn_started"}]) + self.run_turn("b", "codex", dict(PURPOSE, scope=dict(type="unscoped", reason="mixed")), []) + self.provider("grok") + self.run_turn("g", "grok", dict(PURPOSE, scope=dict(type="single", reference=dict( + REF, host="git.example.org"))), [], strong("grok", "prompt:3")) + + def provider(self, driver): + pt = "pt-" + driver + self.row("provider_threads", [pt, "t", driver, driver + "-custom", TIME], { + "id": pt, "appThreadId": "t", "driver": driver, "providerInstanceId": driver + "-custom", + "nativeThreadRef": strong(driver, "current-" + driver)}) + + def run_turn(self, run, driver, purpose, inputs, turn_ref=None): + pt, att, turn, root = "pt-" + driver, "attempt-" + run, "turn-" + run, "node-" + run + instance = driver + "-custom" + self.row("runs", [run, "t", "completed"], dict( + id=run, threadId="t", providerThreadId=pt, providerInstanceId=instance, + purpose=purpose, status="completed", output={"text": "private sentence"})) + self.row("run_attempts", [att, run, "t", pt, turn, root], dict( + id=att, runId=run, providerThreadId=pt, rootNodeId=root, providerInstanceId=instance, + nativeThreadId="historic-" + driver, providerTurnId=turn, status="completed")) + self.row("provider_turns", [turn, "t", pt, att, root], dict( + id=turn, nodeId=root, providerThreadId=pt, runAttemptId=att, nativeInputs=inputs, + nativeTurnRef=turn_ref or strong(driver, "display-only"), + status="completed", turnTokenUsage=dict(usageScope="main_agent", usageStatus="complete", + hasSubagents=False, inputTokens=22, outputTokens=4))) + + def row(self, table, columns, payload): + values = [*columns, json.dumps(payload)] + self.native.execute(f"INSERT INTO {PREFIX}{table} VALUES({','.join('?' for _ in values)})", + values) + + def refresh(self): + self.native.commit() + return t3.sync(self.con, source=self.path) + + def values(self, sql): + return [tuple(r) for r in self.query(sql)] + + def test_literal_inputs_and_deliveries_survive_without_local_sessions(self): + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT run_id,session_key,native_id FROM t3_purpose_inputs" + " ORDER BY run_id"), [ + ("a", "codex:historic-codex", "cx-A"), + ("g", "grok:historic-grok", "prompt:3")]) + self.assertEqual(self.values("SELECT task_id,scope,reason FROM t3_purpose_runs WHERE run_id='b'"), + [(None, "unscoped", "mixed")]) + self.assertEqual(self.values("SELECT session_key FROM t3_purpose_sessions WHERE run_id='b'"), + [("codex:historic-codex",)]) + self.assertEqual(self.values("SELECT task_id FROM tasks ORDER BY task_id"), [ + ("example/project#7",), ("git.example.org/example/project#7",)]) + self.assertEqual(self.values("SELECT task_id,url FROM t3_purpose_deliveries"), [ + ("example/project#7", "https://github.com/example/project/pull/99")]) + self.assertNotIn("private sentence", "\n".join(self.con.iterdump())) + + def test_corrupt_joins_and_unvalidated_grok_stay_gaps(self): + self.native.execute(f"UPDATE {PREFIX}provider_turns SET thread_id='other' WHERE run_attempt_id='attempt-a'") + self.native.execute(f"""UPDATE {PREFIX}provider_turns SET payload_json=json_set( + payload_json,'$.nativeTurnRef.strength','weak') WHERE run_attempt_id='attempt-g'""") + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT * FROM t3_purpose_inputs"), []) + + def test_invalid_scope_and_cross_driver_evidence(self): + self.provider("claudeAgent") + self.run_turn("c", "claudeAgent", dict(PURPOSE, version=True), [ + dict(version=1, kind="message", nativeId="echo-c", validation="claude_prompt_echo"), + dict(version=True, kind="message", nativeId="bad", validation="claude_prompt_echo"), + dict(version=1, kind="turn", nativeId="bad", validation="codex_turn_started")]) + self.provider("opencode") + self.run_turn("o", "opencode", PURPOSE, [ + dict(version=1, kind="message", nativeId="msg-native", validation="opencode_admitted_message")]) + self.provider("opencode2") + self.run_turn("oo", "opencode2", dict(PURPOSE, provenance=dict(type="parent_run")), [ + dict(version=1, kind="message", nativeId="forged", validation="opencode_admitted_message")]) + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT run_id,task_id,scope FROM t3_purpose_runs WHERE scope='invalid'" + " ORDER BY run_id"), [("c", None, "invalid"), ("oo", None, "invalid")]) + self.assertEqual(self.values("SELECT run_id,native_id FROM t3_purpose_inputs" + " WHERE run_id IN ('c','o','oo') ORDER BY run_id"), + [("c", "echo-c"), ("o", "msg-native")]) + self.assertEqual(self.values("SELECT session_key FROM t3_purpose_sessions WHERE run_id='oo'"), + [("opencode:historic-opencode2",)]) + + def test_segment_resume_and_background_never_expand_a_child_session(self): + source_a = dict(type="app_run", threadId="t", runId="a") + source_b = dict(type="app_run", threadId="t", runId="b") + unscoped = dict(PURPOSE, scope=dict(type="unscoped", reason="mixed")) + segment = dict(version=1, id="historic-codex:child:call", nativeSessionId="historic-codex", + nativeChildId="child", nativeOperationId="call", kind="start", purpose=PURPOSE, + source=source_a, boundary=dict(state="native_turns", nativeTurnIds=["first-turn"]), + status="ended", usageFinality="unreconciled", noticeIds=[], wakeDispositions=[], + observedAt=TIME) + resume = dict(segment, id="segment-b", nativeOperationId="call-b", kind="resume", + source=source_b, purpose=unscoped, boundary=dict(state="unresolved", + reason="codex_resume_response_boundary_missing")) + conflict = dict(segment, id="wrong", source=source_b, + boundary=dict(state="native_turns", nativeTurnIds=["stolen"])) + self.row("subagents", ["agent-1", "t", "a", "provider_native", "codex", "child-thread"], { + "id": "agent-1", "threadId": "t", "runId": "a", "driver": "codex", + "origin": "provider_native", "childThreadId": "child-thread", + "providerThreadId": "child-pt", "nativeSegments": [resume, segment, conflict], + "prompt": "keep privately", "result": "do not store"}) + self.row("provider_threads", ["child-pt", "child-thread", "codex", "codex-custom", TIME], + dict(id="child-pt", appThreadId="child-thread", driver="codex", providerInstanceId="codex-custom", + nativeThreadRef=strong("codex", "child"))) + for turn in ("first-turn", "later-turn"): + self.row("provider_turns", [turn, "child-thread", "child-pt", None, "child-node"], { + "id": turn, "nodeId": "child-node", "providerThreadId": "child-pt", "runAttemptId": None, + "nativeInputs": [dict(version=1, kind="turn", nativeId=turn, validation="codex_turn_started")], + "turnTokenUsage": dict(usageScope="main_agent", usageStatus="partial", + hasSubagents=False, inputTokens=6)}) + background = dict(segment, id="bg", kind="background", nativeChildId="shell", + boundary=dict(state="native_turns", nativeTurnIds=["parent-turn"])) + self.native.execute(f"""UPDATE {PREFIX}provider_threads SET payload_json=json_set( + payload_json,'$.nativeOperations',json(?)) WHERE provider_thread_id='pt-codex'""", + (json.dumps([background]),)) + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT run_id,segment_id,usage_finality FROM t3_purpose_segments" + " ORDER BY segment_id"), + [("a", "bg", "unreconciled"), ("a", segment["id"], "unreconciled"), + ("b", "segment-b", "unreconciled"), (None, "wrong", "unreconciled")]) + self.assertEqual(self.values("SELECT run_id,session_key,native_id FROM t3_purpose_inputs" + " WHERE segment_id IS NOT NULL"), [("a", "codex:child", "first-turn")]) + self.assertEqual(self.values("SELECT run_id,provider_turn_id FROM t3_purpose_child_turns"), + [("a", "first-turn")]) + self.assertEqual(self.values("SELECT run_id FROM t3_purpose_sessions WHERE session_key='codex:child'" + " ORDER BY run_id"), [("a",), ("b",)]) + self.assertNotIn("keep privately", "\n".join(self.con.iterdump())) + + def test_expected_child_and_turn_counter_have_independent_sources(self): + self.native.execute(f"CREATE TABLE {PREFIX}turn_items (turn_item_id,thread_id,run_id,type,payload_json)") + self.row("turn_items", ["item", "t", "a", "subagent"], dict(id="item", threadId="t", runId="a", + type="subagent", subagentId="job", origin="app_owned", childThreadId=None, + remoteChild=dict(environmentId="other", threadId="remote-thread", runId="remote-run", + label="private sentence", availability="stale"))) + self.native.execute(f"CREATE TABLE {PREFIX}provider_sessions (provider_session_id,payload_json)") + self.row("provider_sessions", ["ps"], dict(id="ps", driver="codex", capabilities=dict( + purposeEvidence=dict(version=1, nativeInputs="native_turn", childSegments="initial_turn_only", + backgroundInventory="observed_causes", nativeUsageFinality="main_agent_only")))) + self.native.execute(f"""UPDATE {PREFIX}runs SET payload_json=json_set( + payload_json,'$.delegatedCompletion',json(?)) WHERE run_id='a'""", + (json.dumps(dict(disposition="open", nextGeneration=2, delivery=dict( + generation=1, messageId="m", taskIds=["job", "missing"], purposeCauses=[]))),)) + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT kind,participant_id,environment_id,child_run_id" + " FROM t3_purpose_participants ORDER BY kind,participant_id"), + [("completion_member", "job", None, None), ("completion_member", "missing", None, None), + ("subagent_item", "job", "other", "remote-run")]) + self.assertEqual(self.values("SELECT background_inventory,native_usage_finality" + " FROM t3_purpose_capabilities"), [("observed_causes", "main_agent_only")]) + usage = self.values("SELECT usage_json FROM t3_purpose_turns WHERE run_id='a'")[0][0] + self.assertEqual(json.loads(usage), dict(usageScope="main_agent", usageStatus="complete", + inputTokens=22, outputTokens=4, hasSubagents=False)) + self.native.execute(f"DELETE FROM {PREFIX}provider_turns WHERE run_attempt_id='attempt-a'") + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT usage_json FROM t3_purpose_turns WHERE run_id='a'"), []) + self.assertEqual(self.values("SELECT provider_turn_id FROM t3_purpose_attempts WHERE run_id='a'"), + [("turn-a",)]) + + def test_failed_refresh_preserves_previous_projection_and_outer_transaction(self): + self.assertEqual(self.refresh()["failed"], []) + self.con.execute("CREATE TRIGGER abort_input BEFORE INSERT ON t3_purpose_inputs" + " BEGIN SELECT RAISE(ABORT, 'fixture interrupted'); END") + self.native.execute(f"DELETE FROM {PREFIX}runs WHERE run_id='g'") + self.assertTrue(self.refresh()["failed"]) + self.assertEqual(self.values("SELECT native_id FROM t3_purpose_inputs ORDER BY native_id"), + [("cx-A",), ("prompt:3",)]) + self.con.execute("DROP TRIGGER abort_input") + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT native_id FROM t3_purpose_inputs"), [("cx-A",)]) + self.assertTrue(self.con.in_transaction) + + def test_explicitly_unscoped_run_retires_legacy_tree_but_keeps_other_bindings(self): + from agent_observer import db + from tests.test_t3_v2 import CHILD, CX9, write_v2 + self.path = write_v2(os.path.join(self.tmp.name, "formerly-legacy.sqlite")) + self.native.close() + self.native = sqlite3.connect(self.path) + self.addCleanup(self.native.close) + self.con.execute("INSERT INTO sources(harness,path,sha256,imported_at) VALUES('codex','fixture','x',1)") + source = self.con.execute("SELECT last_insert_rowid()").fetchone()[0] + session = "codex:" + CX9 + db.upsert_session(self.con, session, "codex", CX9, source) + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT task_id FROM session_assignments" + " WHERE task_id='example/beta#5'"), + [("example/beta#5",)]) + self.con.execute("INSERT INTO tasks(task_id,origin,created_at) VALUES('separate','capture',1)") + self.con.execute("INSERT INTO session_assignments VALUES(?, 'separate', 'manual', 1)", (session,)) + self.native.execute(f"""UPDATE {PREFIX}runs SET payload_json=json_set(payload_json, + '$.threadId',?,'$.purpose',json(?)) WHERE thread_id=?""", + (CHILD, json.dumps(dict(version=1, scope=dict(type="unscoped", reason="deliberate"), + provenance=dict(type="declared"))), CHILD)) + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT task_id FROM session_assignments"), [("separate",)]) + self.assertEqual(self.values("SELECT DISTINCT task_id,reason FROM t3_purpose_runs"), + [(None, "deliberate")]) + + def test_navigation_migration_and_same_issue_numbers_on_two_hosts(self): + self.con.execute("CREATE TABLE t3_links(thread_id,kind,host,repository,number,url,source," + "state,linked_at,head_branch,PRIMARY KEY(thread_id,kind,repository,number))") + self.con.execute("INSERT INTO t3_links VALUES('retired','pr','github.com','fixture/repo',2," + "'https://github.com/fixture/repo/pull/2','agent','merged',NULL,'original-head')") + self.native.execute("CREATE TABLE fork_thread_issue_links(thread_id,host,repository,number," + "url,source,linked_at)") + for host in ("github.com", "git.example.org"): + self.native.execute("INSERT INTO fork_thread_issue_links VALUES('t',?,'example/project',7," + "?,'agent',?)", (host, f"https://{host}/example/project/issues/7", TIME)) + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT host FROM t3_links WHERE thread_id='t' ORDER BY host"), + [("git.example.org",), ("github.com",)]) + self.assertEqual(self.values("SELECT head_branch FROM t3_links WHERE thread_id='retired'"), + [("original-head",)]) + + def test_existing_task_key_keeps_original_repository_capitalization(self): + self.con.execute("INSERT INTO tasks(task_id,origin,created_at) VALUES('Example/Project#7','capture',1)") + result = self.refresh() + self.assertEqual(result["failed"], []) + self.assertEqual(result["tasks"], 1) + self.assertEqual(self.values("SELECT task_id FROM t3_purpose_runs WHERE run_id='a'"), + [("Example/Project#7",)]) + self.assertEqual(self.values("SELECT origin FROM tasks WHERE task_id='Example/Project#7'"), [("capture",)]) + + def test_provenance_keeps_exact_typed_cause_without_copying_free_text(self): + variants = [ + dict(type="parent_run", threadId="t", runId="p"), + dict(type="target_run", threadId="t", runId="p"), + dict(type="source_run", threadId="t", runId="p"), + dict(type="delegated_launch", threadId="t", runId="p", taskId="original-launch"), + dict(type="remote_launch", environmentId="env", threadId="source", runId="p", launchId="launch"), + dict(type="native_operation", operationIds=["op-1", "op-2"]), + dict(type="delegated_completion", operationIds=["done"]), dict(type="schedule", scheduledTaskId="job"), + dict(type="pull_request_watch", reference=dict(REF, repository="example/project"), startedAt=TIME)] + for i, variant in enumerate(variants): + key = f"p-{i}" + self.row("runs", [key, "t", "interrupted"], dict(id=key, threadId="t", + purpose=dict(PURPOSE, provenance=dict(variant, note="do not copy me")))) + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual([json.loads(r[0]) for r in self.values("SELECT provenance_json FROM t3_purpose_runs" + " WHERE run_id LIKE 'p-%' ORDER BY run_id")], variants) + self.assertNotIn("do not copy me", "\n".join(self.con.iterdump())) From 54924c12bdcd1fa589595a2fedd8039deb514501 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:02:19 +0100 Subject: [PATCH 04/44] Report local outcomes from native run and response evidence --- .claude-plugin/plugin.json | 2 +- .codex-plugin/plugin.json | 2 +- .grok-plugin/plugin.json | 2 +- CHANGELOG.md | 6 + README.md | 15 ++ VERSION | 2 +- agent_observer/cli.py | 10 ++ agent_observer/outcome.py | 219 +++++++++++++++++++++++++++++ agent_observer/publish.py | 12 ++ agent_observer/report.py | 158 ++++++++++++++++----- docs/contracts.md | 10 +- tests/test_claude_queue_binding.py | 7 +- tests/test_outcome.py | 95 +++++++++++++ tests/test_source_availability.py | 9 ++ tests/test_t3.py | 16 ++- 15 files changed, 510 insertions(+), 55 deletions(-) create mode 100644 agent_observer/outcome.py create mode 100644 tests/test_outcome.py diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index eb810a6..fd7bc16 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-observer", - "version": "1.5.3", + "version": "1.6.0", "description": "Measure agent work across Codex, Claude Code, OpenCode and Grok Build from native records, and compare behavior by model and AgentsMD version.", "author": { "name": "toolboxmd", diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json index 171e1b5..3740327 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-observer", - "version": "1.5.3", + "version": "1.6.0", "description": "Measure agent work across Codex, Claude Code, OpenCode and Grok Build from native records, and compare behavior by model and AgentsMD version.", "author": { "name": "toolboxmd", diff --git a/.grok-plugin/plugin.json b/.grok-plugin/plugin.json index 11649d2..83cf6cc 100644 --- a/.grok-plugin/plugin.json +++ b/.grok-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-observer", - "version": "1.5.3", + "version": "1.6.0", "description": "Measure agent work across Codex, Claude Code, OpenCode and Grok Build from native records, and compare behavior by model and AgentsMD version.", "author": { "name": "toolboxmd", diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f99f62..f6ed7ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [1.6.0] - 2026-11-25 + +### Added + +- Report native Issue and PR response ownership and show incomplete outcome costs. + ## [1.5.3] - 2026-11-23 ### Changed diff --git a/README.md b/README.md index e0f8608..95884b4 100644 --- a/README.md +++ b/README.md @@ -514,6 +514,21 @@ Intervention text, problem lines and session attributes stay on this machine: ## Ownership and tasks +For a Chromeria run with a declared Issue or PR purpose, use its reference +as the task ID. For example, `agent-observer task show --task owner/repo#12 --json` +lists the native responses joined to that purpose, even before a delivery PR +exists. The `native_purpose` section identifies each run, the input that joins +a response to it, delivery PRs, provider counter checks, and gaps in coverage. +A planner serving two Issues can have responses for each in the same session. + +A provider turn can reconcile while the full outcome cost remains unknown. +Chromeria v1 records observed background causes for some drivers and has no +background inventory for others. A missing child boundary or unavailable +price leaves any priced work as a subtotal. The same scope appears in +`publish --task`. For legacy shared PR sessions, sync captures checkout +evidence per response while the checkout exists. Retiring the checkout +preserves those observations. + Put `observer_task_id` in related Router jobs' prepared task JSON to connect them to one Observer task. `sync` binds their dedicated worker and dispatcher sessions using Router records, preserving captured task metadata and outcomes. diff --git a/VERSION b/VERSION index 8af85be..dc1e644 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.5.3 +1.6.0 diff --git a/agent_observer/cli.py b/agent_observer/cli.py index e8edf46..1aa6ab4 100644 --- a/agent_observer/cli.py +++ b/agent_observer/cli.py @@ -173,6 +173,14 @@ def _text(payload) -> str: f"session span {r.get('time', {}).get('session_span_s')} " f"({r.get('time', {}).get('session_span_label')})", ] + if r.get("native_purpose", {}).get("runs"): + native = r["native_purpose"] + lines.append(f" native purpose: {len(native['runs'])} runs; " + f"{len(native['membership'])} joined responses") + if native.get("coverage_gaps"): + lines.append(" native coverage: " + ", ".join(native["coverage_gaps"])) + for pr in native["deliveries"]: + lines.append(f" delivery PR: {pr['url']}") est = r.get("estimated_cost") or {} if est.get("schedule_source"): lines.append( @@ -209,6 +217,8 @@ def _text(payload) -> str: f"joined call_ids: {len(payload['join']['joined_call_ids'])}", f"unmatched results: {len(payload['join']['unmatched_results'])}", f"unanswered calls: {len(payload['join']['unanswered_calls'])}"] + if "native_response_count" in payload: + lines.append(f"native responses joined to this outcome: {payload['native_response_count']}") if payload.get("truncated"): lines[0] = (f"events: {payload['returned']} of {payload['total']} " f"(truncated). {payload['truncation_hint']}") diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py new file mode 100644 index 0000000..30860cc --- /dev/null +++ b/agent_observer/outcome.py @@ -0,0 +1,219 @@ +"""Read immutable purpose and native response witnesses in one ledger snapshot.""" + +from collections import defaultdict +import json + +from .db import _has_table + + +def sessions(con, task_id): + if not _has_table(con, "t3_purpose_runs"): + return set() + return {row[0] for row in con.execute( + "SELECT DISTINCT s.session_key FROM t3_purpose_sessions s " + "JOIN t3_purpose_runs r USING(run_id) WHERE r.task_id=?", (task_id,))} + + +def active(con, task_id): + return _has_table(con, "t3_purpose_runs") and con.execute( + "SELECT 1 FROM t3_purpose_runs WHERE task_id=? LIMIT 1", (task_id,) + ).fetchone() is not None + + +def evidence(con, task_id, scope): + """A response belongs to one execution only if both native joins agree.""" + from . import native_response + + runs = [dict(r) for r in con.execute( + "SELECT * FROM t3_purpose_runs WHERE task_id=? ORDER BY run_id", (task_id,))] + deliveries = [dict(r) for r in con.execute( + "SELECT * FROM t3_purpose_deliveries WHERE task_id=? ORDER BY declared_at, url, thread_id", (task_id,))] + reference_conflict = len({r["kind"] for r in runs}) > 1 + session_runs = {} + members = {} + ownership = {} + turn_keys = set() + conflicts = set() + for key in sorted(scope): + by_run = dict(con.execute( + "SELECT r.run_id, r.task_id FROM t3_purpose_sessions s " + "JOIN t3_purpose_runs r USING(run_id) WHERE s.session_key=?", (key,))) + if not by_run: + continue + session_runs[key] = sorted(by_run) + by_input = defaultdict(set) + for run, native_id, turn, segment, validation in con.execute( + "SELECT run_id,native_id,provider_turn_id,segment_id,validation FROM t3_purpose_inputs " + "WHERE session_key=?", (key,)): + by_input[native_id].add((run, turn, segment, validation)) + whole = {r["task_id"] for r in con.execute( + "SELECT task_id, evidence FROM session_assignments WHERE session_key=?", (key,)) + if not (r["evidence"] or "").startswith("t3:")} + claimed_inputs = defaultdict(set) + for msg, alias, turn, owner in con.execute( + "SELECT s.native_id,s.alias_id,s.turn_id,a.task_id FROM assignments a " + "JOIN user_messages s ON a.user_message_id=s.native_id WHERE s.session_key=?", (key,)): + for identity in (msg, alias, turn): + if identity: + claimed_inputs[identity].add(owner) + harness = key.partition(":")[0] + for rid, input_ids in native_response.inputs(con, key).items(): + candidates = {run for identity in input_ids for run in by_input.get(identity, ())} + if not candidates: + continue + if len(input_ids) != 1 or len(candidates) != 1: + conflicts.add(rid) + continue + run, turn, segment, validation = next(iter(candidates)) + owner = by_run.get(run) + native_id = next(iter(input_ids)) + claims = whole | claimed_inputs.get(f"{harness}:{native_id}", set()) + if (reference_conflict and owner == task_id) or (claims and claims != {owner}): + conflicts.add(rid) + continue + ownership[rid] = owner + if owner == task_id: + members[rid] = {"run_id": run, "session_key": key, "native_input_id": native_id, + "provider_turn_id": turn, "segment_id": segment, "validation": validation} + if harness == "codex": + turn_keys.add((key, "codex:" + native_id)) + elif harness == "grok": + turn_keys.add((key, rid)) + + return ({"version": 1, "task_id": task_id, "runs": runs, "deliveries": deliveries, + "membership": members, "sessions": session_runs, "conflicting_responses": sorted(conflicts), + "conflicting_reference_kinds": reference_conflict}, + ownership, turn_keys) + + +def _normalized_counters(row): + """Render the native response in Chromeria's inclusive comparison units.""" + from .adapters import claude, codex, grok, opencode + + sem = row["semantics"] + if sem not in {codex.SEMANTICS, claude.SEMANTICS, opencode.SEMANTICS, grok.SEMANTICS}: + return {} + inp = [row["input_tokens"]] + out = [row["output_tokens"]] + if sem in {claude.SEMANTICS, opencode.SEMANTICS}: + inp.extend([row["cached_input_tokens"], row["cache_write_input_tokens"]]) + if sem == opencode.SEMANTICS: + out.append(row["reasoning_output_tokens"]) + + def count(values): + return sum(values) if all(type(n) is int and n >= 0 for n in values) else None + + return {"inputTokens": count(inp), "outputTokens": count(out), + "cachedInputTokens": row["cached_input_tokens"], + "cacheCreationTokens": row["cache_write_input_tokens"], + "reasoningTokens": row["reasoning_output_tokens"]} + + +def _turn_check(turn, responses, finalized): + usage = json.loads(turn["usage_json"]) if turn["usage_json"] else {} + if turn["status"] != "completed" or usage.get("usageStatus") != "complete": + return "native_final_usage_missing" + if not responses: + return "no_joined_responses" + if any(r["harness"] == "claude" and r["response_id"] not in finalized for r in responses): + return "response_not_final" + normalized = [_normalized_counters(r) for r in responses] + for name in ("inputTokens", "outputTokens", "cachedInputTokens", "cacheCreationTokens", "reasoningTokens"): + if name not in usage: + continue + counters = [c.get(name) for c in normalized] + if any(type(n) is not int or n < 0 for n in counters): + return "counter_unavailable" + if sum(counters) != usage[name]: + return "counter_mismatch" + return "reconciled" + + +def check_inventory(con, native, rows): + """Compare independent provider final counters and the expected attempt/turn edges. + + The v1 capability records observed background causes, or no inventory. + Neither can certify that the entire outcome has been collected. + """ + by_turn = defaultdict(list) + by_segment = defaultdict(list) + for row in rows: + member = native["membership"].get(row["response_id"]) + if member: + member["counters"] = {k: row[k] for k in ( + "harness", "model", "semantics", "input_tokens", "cached_input_tokens", + "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", + "total_tokens", "cost_usd", "cache_write_5m_tokens", "cache_write_1h_tokens")} + if member["segment_id"]: + by_segment[(member["run_id"], member["segment_id"], member["session_key"])].append(row) + if member["provider_turn_id"]: + by_turn[member["provider_turn_id"]].append(row) + finalized = set() + if _has_table(con, "claude_response_finality"): + for key in native["sessions"]: + if key.startswith("claude:"): + finalized.update(r[0] for r in con.execute( + "SELECT f.response_id FROM responses r JOIN claude_response_finality f " + "USING(response_id) WHERE r.session_key=?", (key,))) + gaps = set() + main_gaps = set() + checks = [] + for run in native["runs"]: + run_id = run["run_id"] + if run["status"] != "completed": + main_gaps.add("run_not_completed") + attempts = [dict(r) for r in con.execute( + "SELECT a.*,c.native_inputs,c.child_segments,c.background_inventory,c.native_usage_finality " + "FROM t3_purpose_attempts a LEFT JOIN t3_purpose_capabilities c USING(provider_session_id) " + "WHERE a.run_id=? ORDER BY a.attempt_id", (run_id,))] + if run["active_attempt_id"] not in {a["attempt_id"] for a in attempts}: + main_gaps.add("expected_attempt_missing") + for a in attempts: + turns = [dict(r) for r in con.execute( + "SELECT * FROM t3_purpose_turns WHERE attempt_id=? ORDER BY provider_turn_id", (a["attempt_id"],))] + if a["provider_turn_id"] not in {t["provider_turn_id"] for t in turns}: + main_gaps.add("expected_provider_turn_missing") + for turn in turns: + state = _turn_check(turn, by_turn[turn["provider_turn_id"]], finalized) + checks.append({"run_id": run_id, "attempt_id": a["attempt_id"], + "provider_turn_id": turn["provider_turn_id"], "status": state, + "provider_usage": json.loads(turn["usage_json"] or "null")}) + if state != "reconciled": + main_gaps.add(state) + # Even a valid final main-agent counter omits independent background work. + gaps.add("observed_background_causes_only" if a["background_inventory"] == "observed_causes" + else "background_inventory_unavailable") + run["attempts"] = attempts + run["participants"] = [dict(r) for r in con.execute( + "SELECT * FROM t3_purpose_participants WHERE run_id=? ORDER BY kind,participant_id", (run_id,))] + expected = {r["participant_id"] for r in run["participants"] if r["kind"] == "subagent_item"} + observed = {r["participant_id"] for r in run["participants"] + if r["kind"] not in {"subagent_item", "pending_background", "completion_member", "completion_cause"}} + run["missing_children"] = sorted(expected - observed) + if run["missing_children"]: + gaps.add("expected_child_missing") + if any(p["environment_id"] for p in run["participants"]): + gaps.add("remote_participation") + if run["participants"]: + gaps.add("child_inventory_requires_reconciliation") + native["segments"] = [dict(r) for r in con.execute( + "SELECT * FROM t3_purpose_segments WHERE task_id=? ORDER BY thread_id,owner_id,segment_id", + (native["task_id"],))] + for segment in native["segments"]: + segment["provider_turns"] = [dict(r) for r in con.execute( + "SELECT * FROM t3_purpose_child_turns WHERE run_id=? AND segment_id=? ORDER BY provider_turn_id", + (segment["run_id"], segment["segment_id"]))] + turns = segment["provider_turns"] + for turn in turns: + group = by_segment[(turn["run_id"], turn["segment_id"], turn["session_key"])] + turn["counter_check"] = (_turn_check(turn, group, finalized) if len(turns) == 1 + else "segment_turn_boundary_unresolved") + gaps.add("segment_final_usage_unreconciled") + if native["conflicting_reference_kinds"]: + gaps.add("conflicting_reference_kinds") + if native["conflicting_responses"]: + gaps.add("conflicting_response_ownership") + native["turn_checks"] = checks + native["main_agent_counters_reconciled"] = bool(checks) and not main_gaps + native["coverage_gaps"] = sorted(gaps | main_gaps) + return bool(native["coverage_gaps"]) diff --git a/agent_observer/publish.py b/agent_observer/publish.py index 1e8ef3f..c11b3e1 100644 --- a/agent_observer/publish.py +++ b/agent_observer/publish.py @@ -227,6 +227,8 @@ def summarize(con, session_keys: set, label: str, task_id: str | None = None, "total_cost": rep["total_cost"], "subscription_note": rep["subscription_note"], }) + if "native_purpose" in rep: + out["native_purpose"] = rep["native_purpose"] else: out.update({ "scope_kind": "session", @@ -430,6 +432,16 @@ def render(summary: dict, target: str | None = None) -> str: parts += [_counted(responses, "response", "responses"), _counted(sessions, "session", "sessions"), wall] lines = [MARKER, f"### {title}", "", " · ".join(parts), ""] + native = summary.get("native_purpose") or {} + if native.get("runs"): + lines.append(f"Outcome: {_safe_field(summary['task_id'])}. " + "Only responses with proved ownership enter the native subtotal.") + if native.get("coverage_gaps"): + lines.append("Full outcome cost unknown. Native coverage: " + + ", ".join(_safe_field(g.replace("_", " ")) for g in native["coverage_gaps"]) + ".") + for pr in native["deliveries"]: + lines.append(f"Delivery PR: {_safe_field(pr['url'])}") + lines.append("") if not task: lines += [f"_{_safe_field(summary.get('session_note') or 'Session scope only.')} " f"Finished processes never imply an accepted task outcome._", ""] diff --git a/agent_observer/report.py b/agent_observer/report.py index af0f1b6..678dec1 100644 --- a/agent_observer/report.py +++ b/agent_observer/report.py @@ -6,7 +6,7 @@ import json import sqlite3 -from . import codex_order +from . import codex_order, outcome from .db import _has_table BUCKETS = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", @@ -215,9 +215,12 @@ def task_sessions(con: sqlite3.Connection, task_id: str) -> set: "SELECT DISTINCT s.session_key FROM assignments a JOIN user_messages s" " ON s.native_id=a.user_message_id WHERE a.task_id=?" " AND s.session_key IS NOT NULL", (task_id,))} - keys |= {r["session_key"] for r in con.execute( - "SELECT session_key FROM session_assignments WHERE task_id=?", - (task_id,))} + canonical = outcome.active(con, task_id) + keys.update(outcome.sessions(con, task_id)) + for r in con.execute( + "SELECT session_key, evidence FROM session_assignments WHERE task_id=?", (task_id,)): + if not (r["evidence"] or "").startswith("t3:") or not canonical: + keys.add(r["session_key"]) keys |= {r["session_key"] for r in con.execute( "SELECT session_key FROM task_turns WHERE task_id=? AND session_key IS NOT NULL", (task_id,))} @@ -404,7 +407,7 @@ def _is_mcp_result(event) -> bool: def _phase_report(con, task_id, rows, whole, attempts, schedule, - unmeasured=frozenset()): + unmeasured=frozenset(), native_sessions=(), native_turns=()): from . import pricing, analysis by_turn, by_session = {}, {} @@ -429,6 +432,8 @@ def phase(value): by_session.setdefault(a["session_key"], set()).add(phase(a.get("stage"))) def selected(row): + if row["session_key"] in native_sessions and (row["session_key"], row["turn_id"]) not in native_turns: + return "unclassified" labels = by_turn.get(row["turn_id"]) or by_session.get(row["session_key"]) or {"unclassified"} return next(iter(labels)) if len(labels) == 1 else "mixed" @@ -442,8 +447,11 @@ def selected(row): for key in sorted({r["session_key"] for r in rows} | set(whole)): harness = _session_harness(con, key) for event in con.execute("SELECT * FROM events WHERE session_key=?", (key,)): - label = ("session context" if key not in whole and event["turn_id"] not in turns - else selected(event)) + if key in native_sessions: + owned = (key, event["turn_id"]) in native_turns + else: + owned = key in whole or event["turn_id"] in turns + label = selected(event) if owned else "session context" # Capability comes from the event's own native session, never # from the importer that attributed it (Router). contributors.setdefault(label, {})[key] = harness @@ -519,6 +527,17 @@ def task_report(con: sqlite3.Connection, task_id: str, whole = {r["session_key"]: r["evidence"] for r in con.execute( "SELECT session_key, evidence FROM session_assignments WHERE task_id=?", (task_id,))} + native = None + purpose_owners = {} + native_turns = set() + canonical = outcome.active(con, task_id) + if canonical or (_has_table(con, "t3_purpose_sessions") and any( + con.execute("SELECT 1 FROM t3_purpose_sessions WHERE session_key=? LIMIT 1", + (key,)).fetchone() for key in scope_keys)): + native, purpose_owners, native_turns = outcome.evidence(con, task_id, scope_keys) + whole = {k: v for k, v in whole.items() + if not (v or "").startswith("t3:") or (not canonical and k not in native["sessions"])} + legacy_links = {key for key, ev in whole.items() if ev == "t3" or (ev or "").startswith("t3:")} whole_shared = {r["session_key"] for r in con.execute( "SELECT session_key FROM session_assignments GROUP BY session_key" " HAVING COUNT(DISTINCT task_id) > 1")} @@ -532,15 +551,29 @@ def task_report(con: sqlite3.Connection, task_id: str, # A session shared by several PRs is split per response by the checkout # its tool calls worked in (#43); None keeps whole-session sharing. placements = {key: _place(con, key) for key in whole_shared & set(whole) - if key not in whole_conflicts} + if key not in whole_conflicts and not canonical + and not (native and key in native["sessions"])} unplaced, elsewhere = [], [] missing_submissions = [] assigned_anywhere = {r["user_message_id"] for r in con.execute("SELECT user_message_id " "FROM assignments").fetchall()} + conflicts = set(native["conflicting_responses"]) if native else set() for r in responses: if r["is_overlap"]: continue + key, rid = r["session_key"], r["response_id"] + if native and key in native["sessions"]: + owner = purpose_owners.get(rid) + if rid in conflicts: + unplaced.append(dict(r)) + continue + if owner == task_id: + attributed.append(dict(r)) + continue + if rid in purpose_owners or canonical or (key not in whole and not bound_subs): + (elsewhere if owner else unplaced).append(dict(r)) + continue if r["session_key"] in whole: placed = placements.get(r["session_key"]) if placed is not None: @@ -548,7 +581,12 @@ def task_report(con: sqlite3.Connection, task_id: str, (attributed if owner == task_id else unplaced if owner is None else elsewhere).append(dict(r)) continue - (shared if r["session_key"] in whole_shared else attributed).append(dict(r)) + if key in whole_shared: + shared.append(dict(r)) + elif key in legacy_links: + unplaced.append(dict(r)) + else: + attributed.append(dict(r)) continue sub = turn_sub.get(r["turn_id"]) if sub is None: @@ -567,15 +605,8 @@ def task_report(con: sqlite3.Connection, task_id: str, # responses while attributed and shared stay empty (for example every # prompt read synthetic, so per-prompt assignment refused them). This # is a visible coverage gap, never a silent "missing assignments: none". - live_scope = [dict(r) for r in responses if not r["is_overlap"]] - unbound_usage: list = [] - if live_scope and not attributed and not shared: - responders: dict[str, int] = {} - for r in live_scope: - if r.get("session_key"): - responders[r["session_key"]] = \ - responders.get(r["session_key"], 0) + 1 - unbound_usage = sorted(responders) + unbound_usage = sorted({r["session_key"] for r in unassigned + unplaced} + - {r["session_key"] for r in attributed + shared + elsewhere}) def total(rows): return _usage_totals(rows) @@ -605,7 +636,7 @@ def _sem_known_sums(rows): "SELECT * FROM delegations WHERE owning_user_message IN " "(SELECT user_message_id FROM assignments WHERE task_id=?)", (task_id,))] - owned_sessions = set(whole) | {r["session_key"] for r in con.execute( + owned_sessions = outcome.sessions(con, task_id) | set(whole) | {r["session_key"] for r in con.execute( "SELECT s.session_key FROM user_messages s JOIN assignments a" " ON a.user_message_id=s.native_id WHERE a.task_id=?", (task_id,))} @@ -652,14 +683,18 @@ def child_session(identity): unmeasured_attributed.add(key) elif subs: unmeasured_shared.add(key) - unavailable_usage = bool(not scope_keys or missing_sessions or empty_sessions + inventory_gaps = outcome.check_inventory(con, native, attributed) if canonical else False + unavailable_usage = bool(unbound_usage or conflicts or inventory_gaps or legacy_links + or not scope_keys or missing_sessions or empty_sessions or unbound_children or unbound_delegations or whole_conflicts) cutoff = _source_cutoff(con, scope_keys) - task_turns = _task_turn_ids(con, task_id, turn_sub, whole) - diagnostics = _task_diagnostics(con, scope_keys, whole, task_turns) + explicit_whole = {k: ev for k, ev in whole.items() if k not in legacy_links} + task_turns = _task_turn_ids(con, task_id, turn_sub, explicit_whole) + task_turns.update(turn for _, turn in native_turns) + diagnostics = _task_diagnostics(con, scope_keys, explicit_whole, task_turns) phases, activity_context, activity_context_coverage = _phase_report( - con, task_id, attributed, set(whole)-whole_shared, task_turn_rows, schedule, - unmeasured_attributed) + con, task_id, attributed, set(explicit_whole)-whole_shared, task_turn_rows, schedule, + unmeasured_attributed, native["sessions"] if native else (), native_turns) def _resp_tuple(r) -> list: return [r.get("response_id"), r.get("harness"), r.get("model"), @@ -712,16 +747,20 @@ def _resp_tuple(r) -> list: [d.get("owning_user_message"), d.get("child_thread")] for d in delegation_rows), "source_cutoff": cutoff, } + if native: + snapshot_payload["native_purpose"] = native snapshot = _snapshot_id(snapshot_payload) estimated = _pricing.price_scope(attributed, schedule) shared_estimated = _pricing.price_scope(shared, schedule) - total_estimated = _pricing.price_scope(attributed + shared, schedule) + billed_shared = [] if canonical else [r for r in shared if r["session_key"] not in legacy_links] + total_estimated = _pricing.price_scope(attributed + billed_shared, schedule) unplaced_estimated = _pricing.price_scope(unplaced, schedule) for estimate in (estimated, shared_estimated, total_estimated, unplaced_estimated): estimate["status"] = ("complete" if estimate["complete"] else "partial" if estimate["priced_responses"] else "unknown") if unavailable_usage: - estimate.update(complete=False, estimated_cost_usd_total=None, status="partial", + estimate.update(complete=False, estimated_cost_usd_total=None, + status="partial" if estimate["priced_responses"] else "unknown", coverage_note="Native session usage or worker ownership is unavailable") native_cost = _native_cost(attributed) if unavailable_usage: @@ -843,6 +882,10 @@ def _resp_tuple(r) -> list: parts.get(sem, 0) == wholes.get(sem, 0) for sem in parts) report["reconciles"] = responses_reconcile and totals_reconcile + if legacy_links: + report["coverage"]["legacy_thread_links"] = sorted(legacy_links) + if native: + report["native_purpose"] = native report["unbound_usage"] = unbound_usage report["source_availability"] = { "status": source_availability["status"], @@ -862,7 +905,10 @@ def _resp_tuple(r) -> list: report["coverage"]["unavailable_sessions"] = unavailable_sessions report["coverage"]["unavailable_sources"] = unavailable_sources report["total_cost"] = _total_cost( - con, task_id, total_estimated, attributed, shared, joint, whole) + con, task_id, total_estimated, attributed, billed_shared, joint, whole) + if canonical and inventory_gaps and total_estimated.get("priced_responses"): + subtotal = total_estimated["estimated_cost_usd_partial"] + report["total_cost"]["text"] = f"unknown (observed priced subtotal ${subtotal:,.2f})" report["total_cost"]["unplaced"] = { "text": _money(unplaced_estimated) if unplaced else None, "responses": len(unplaced), @@ -873,11 +919,7 @@ def _resp_tuple(r) -> list: def _place(con, session_key: str): from . import placement - try: - return placement.place_session(con, session_key) - except sqlite3.OperationalError: - # A ledger without T3 head branches or checkouts keeps whole sharing. - return None + return placement.read_placements(con, session_key) def _money(estimate: dict) -> str: @@ -925,7 +967,7 @@ def _total_cost(con, task_id, estimate, attributed, shared, joint, # partial: an empty subtotal must never read as a numeric zero. status = estimate["status"] if estimate.get("priced_responses") else "unknown" return { - "text": _money(estimate), + "text": _money(estimate) if status != "unknown" else "unknown", "usd": estimate.get("estimated_cost_usd_total") if status == "complete" else estimate.get("estimated_cost_usd_partial") if status == "partial" else None, @@ -956,17 +998,50 @@ def timeline(con: sqlite3.Connection, task_id: str | None = None, if turn_id: q += " AND turn_id=?" args.append(turn_id) - elif task_turns is not None: - whole = sorted(r["session_key"] for r in con.execute( - "SELECT session_key FROM session_assignments WHERE task_id=?", + trace_scope = {} + if task_turns is not None: + canonical = outcome.active(con, task_id) + native_turns = set() + claude_event_ids = [] + if canonical: + native, _, native_turns = outcome.evidence(con, task_id, outcome.sessions(con, task_id)) + matches = {rid: member for rid, member in native["membership"].items() + if (not session_key or member["session_key"] == session_key) + and (not turn_id or turn_id == member["session_key"].partition(":")[0] + ":" + member["native_input_id"])} + for key in sorted({m["session_key"] for m in matches.values() if m["session_key"].startswith("claude:")}): + # Claude gives each text event the transcript UUID and block + # index. Its parent chain proves the response independently of + # the display turn that may have been retouched. + for event_id, rid in con.execute( + "SELECT DISTINCT e.id,a.response_id FROM events e JOIN claude_response_ancestry a " + "ON e.source_id=a.source_id AND e.session_key=a.session_key " + "AND a.uuid=substr(e.native_id,1,instr(e.native_id,':')-1) " + "WHERE e.session_key=? AND e.family='assistant_message'", (key,)): + if rid in matches: + claude_event_ids.append(event_id) + trace_scope = {"native_response_count": len(matches), + "native_responses": {rid: matches[rid] for rid in sorted(matches)[:limit]}} + # Display turns can be retouched after import. Use only native + # session/turn pairs in an exact outcome timeline. + task_turns.clear() + whole = [] if canonical else sorted(r["session_key"] for r in con.execute( + "SELECT session_key FROM session_assignments WHERE task_id=? AND evidence<>'t3' AND evidence NOT LIKE 't3:%'", (task_id,))) - if not task_turns and not whole: - return {"events": [], "returned": 0, "total": 0, + if not task_turns and not whole and not native_turns and not claude_event_ids: + return {**trace_scope, "events": [], "returned": 0, "total": 0, "truncated": False, "note": "no bound turns; timeline empty", "join": {"calls": 0, "results": 0, "joined_call_ids": [], "unmatched_results": [], "unanswered_calls": []}} clauses = [] + if claude_event_ids: + clauses.append("id IN (SELECT value FROM json_each(?))") + args.append(json.dumps(claude_event_ids)) + if native_turns: + pairs = sorted(native_turns) + clauses.append("(session_key, turn_id) IN (VALUES " + ",".join(["(?,?)"] * len(pairs)) + ")") + for pair in pairs: + args.extend(pair) if task_turns: clauses.append(f"turn_id IN ({','.join('?' * len(task_turns))})") args.extend(sorted(task_turns)) @@ -985,6 +1060,11 @@ def timeline(con: sqlite3.Connection, task_id: str | None = None, out = [] for r in rows: d = dict(r) + if trace_scope: + d.pop("detail_json", None) + d.pop("target", None) + out.append(d) + continue try: d["detail"] = json.loads(d["detail_json"]) if d["detail_json"] else None except ValueError: @@ -1023,7 +1103,7 @@ def timeline(con: sqlite3.Connection, task_id: str | None = None, calls = {e["native_id"] for e in out if e["family"] == "tool_call"} results = {e["native_id"] for e in out if e["family"] == "tool_result"} result = { - "events": out, + **trace_scope, "events": out, "returned": len(out), "total": total, "truncated": len(out) < total, diff --git a/docs/contracts.md b/docs/contracts.md index 1a05962..c982d1a 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -536,17 +536,17 @@ re-read every sync; workload bindings are durable ledger rows. (backfilled rows gain their turn but no excerpt). Scaffolding, command and interrupt verdicts fail closed; unlisted records (typed prompts, Router `sdk-cli` workers) never move; unknown stays unknown. -- Thread trees: `sub..` ids (nesting allowed) group under +- Legacy thread trees: `sub..` ids (nesting allowed) group under their root. Each linked PR or Issue becomes one `repo#N` task (`origin='t3'`); every ledger session in the tree (cursor sessions plus Claude subagent children plus rotated sessions found by turn uuid) binds - whole to every tree task. One-link trees attribute exclusively. + whole to every tree task as historical session context. A thread link alone cannot place a response. In a multi-link tree, a Claude or Codex response belongs to one PR when the paths its tool calls name lie in a checkout of that PR's repository - on its head branch (T3 snapshot `headBranch`; checkouts recorded in - `checkouts` at sync so removed worktrees still match). A response + on its head branch (T3 snapshot `headBranch`). Sync records that observation + against the individual event, path digest and response. Reports read the ledger. A response matching no PR or several stays unplaced and outside every headline. - Other harnesses, and links without a head branch, keep whole sharing. + Whole-session sharing from links stays visible outside the outcome cost. Ghostty bodies and unknown cursor shapes are skipped. - Outcomes come from the PR snapshot (`merged` completes); exit codes are never read. diff --git a/tests/test_claude_queue_binding.py b/tests/test_claude_queue_binding.py index c820415..e8187e5 100644 --- a/tests/test_claude_queue_binding.py +++ b/tests/test_claude_queue_binding.py @@ -115,9 +115,10 @@ def assert_task_cost(self, current): with self.subTest(consumer='report.task_report'): actual = report.task_report(self.con, TASK, schedule=SCHEDULE) self.assertEqual(set(actual['scope_sessions']), keys) - self.assertEqual(actual['attributed']['responses'], 3 if current else 2) - self.assertEqual(actual['attributed']['total_tokens'], tokens) - self.assertAlmostEqual(actual['estimated_cost']['estimated_cost_usd_total'], tokens / 1e6) + self.assertEqual(actual['unplaced_shared']['responses'], 3 if current else 2) + self.assertEqual(actual['unplaced_shared']['total_tokens'], tokens) + self.assertEqual(actual['attributed']['responses'], 0) + self.assertIsNone(actual['estimated_cost']['estimated_cost_usd_total']) with self.subTest(consumer='dispatch.compare'): actual = dispatch.compare(self.con, self.state, schedule=SCHEDULE, approval=lambda _: {'approved_at': None, 'error': None}) diff --git a/tests/test_outcome.py b/tests/test_outcome.py new file mode 100644 index 0000000..2bbae7a --- /dev/null +++ b/tests/test_outcome.py @@ -0,0 +1,95 @@ +"""Exercise shared-planner reports with native usage and independent purpose rows.""" + +from contextlib import closing +import json +import sqlite3 + +from agent_observer import publish, report +from agent_observer.adapters import t3_purpose +from tests.helpers import LedgerCase + + +class NativeOutcomeTest(LedgerCase): + session = "codex:sess-fixture-mini-01" + task = "example/repo#11" + + def setUp(self): + super().setUp() + self.sync("codex-mini.jsonl") + with closing(sqlite3.connect(":memory:")) as native: + t3_purpose.refresh(self.con, native, set()) + self.con.execute("INSERT INTO tasks(task_id,project,title,created_at)" + " VALUES(?,?,?,0)", (self.task, "example/repo", self.task)) + self.con.execute("INSERT INTO t3_purpose_runs(run_id,thread_id,task_id,scope,kind," + "status,active_attempt_id) VALUES('a','planner',?,'single','issue','completed','aa')", + (self.task,)) + self.con.execute("INSERT INTO t3_purpose_sessions VALUES('a',?)", (self.session,)) + self.con.execute("INSERT INTO t3_purpose_inputs(run_id,session_key,native_id,kind,validation," + "attempt_id,provider_turn_id) VALUES('a',?,'turn-mini-aaa','turn'," + "'codex_turn_started','aa','ta')", (self.session,)) + self.con.execute("INSERT INTO t3_purpose_attempts(attempt_id,run_id,provider_turn_id)" + " VALUES('aa','a','ta')") + self.con.execute("INSERT INTO t3_purpose_turns(provider_turn_id,attempt_id,run_id," + "status,usage_json) VALUES('ta','aa','a','completed',?)", + (json.dumps(dict(usageStatus="complete", usageScope="main_agent", + inputTokens=3000, outputTokens=350, hasSubagents=False)),)) + self.con.commit() + + def test_final_counter_reconciliation_changes_when_a_response_disappears(self): + rep = report.task_report(self.con, self.task) + self.assertEqual(rep["measured"]["attributed_responses"], ["codex:resp-mini-001", "codex:resp-mini-002"]) + self.assertEqual(rep["native_purpose"]["turn_checks"][0]["status"], "reconciled") + self.assertFalse(rep["complete"]) + self.assertIn("background_inventory_unavailable", rep["native_purpose"]["coverage_gaps"]) + self.con.execute("DELETE FROM responses WHERE response_id='codex:resp-mini-002'") + late = report.task_report(self.con, self.task) + self.assertEqual(late["native_purpose"]["turn_checks"][0]["status"], "counter_mismatch") + self.assertNotEqual(late["snapshot_id"], rep["snapshot_id"]) + + def test_two_issues_share_a_planner_but_each_gets_its_own_responses(self): + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES('example/repo#12',0)") + self.con.execute("INSERT INTO t3_purpose_runs(run_id,thread_id,task_id,scope)" + " VALUES('b','planner','example/repo#12','single')") + self.con.execute("INSERT INTO t3_purpose_sessions VALUES('b',?)", (self.session,)) + self.con.execute("INSERT INTO t3_purpose_inputs(run_id,session_key,native_id,kind,validation)" + " VALUES('b',?,'turn-mini-bbb','turn','codex_turn_started')", (self.session,)) + a = report.task_report(self.con, self.task) + b = report.task_report(self.con, "example/repo#12") + self.assertEqual(b["measured"]["attributed_responses"], ["codex:resp-mini-003"]) + self.assertEqual(b["measured"]["other_task_responses"], a["measured"]["attributed_responses"]) + self.assertEqual(a["measured"]["other_task_responses"], b["measured"]["attributed_responses"]) + self.assertTrue(a["reconciles"] and b["reconciles"]) + + def test_expected_child_without_its_projection_remains_missing(self): + self.con.execute("INSERT INTO t3_purpose_participants(run_id,thread_id,kind,participant_id)" + " VALUES('a','planner','subagent_item','child-1')") + rep = report.task_report(self.con, self.task) + self.assertEqual(rep["native_purpose"]["runs"][0]["missing_children"], ["child-1"]) + self.assertIn("expected_child_missing", rep["native_purpose"]["coverage_gaps"]) + self.assertTrue(rep["native_purpose"]["main_agent_counters_reconciled"]) + self.assertFalse(rep["coverage"]["complete"]) + + def test_second_claim_on_the_same_input_fails_closed_and_trace_filters_intersect(self): + self.con.execute("INSERT INTO t3_purpose_runs(run_id,thread_id,task_id,scope)" + " VALUES('b','planner','example/repo#12','single')") + self.con.execute("INSERT INTO t3_purpose_sessions VALUES('b',?)", (self.session,)) + self.con.execute("INSERT INTO t3_purpose_inputs(run_id,session_key,native_id,kind,validation)" + " VALUES('b',?,'turn-mini-aaa','turn','codex_turn_started')", (self.session,)) + rep = report.task_report(self.con, self.task) + self.assertEqual(rep["attributed"]["responses"], 0) + self.assertEqual(len(rep["native_purpose"]["conflicting_responses"]), 2) + self.assertEqual(rep["total_cost"]["text"], "unknown") + self.assertFalse(report.timeline(self.con, self.task, turn_id="codex:turn-mini-aaa")["events"]) + + def test_delivery_does_not_move_responses_and_report_needs_no_write(self): + before = report.task_report(self.con, self.task) + self.con.execute("INSERT INTO t3_purpose_deliveries(task_id,thread_id,host,repository,number," + "url,declared_at) VALUES(?,'planner','github.com','example/repo',42," + "'https://github.com/example/repo/pull/42','2026-11-25T00:00:00Z')", (self.task,)) + self.con.execute("PRAGMA query_only=ON") + after = report.task_report(self.con, self.task) + self.assertEqual(after["measured"], before["measured"]) + self.assertNotEqual(after["snapshot_id"], before["snapshot_id"]) + summary = publish.summarize(self.con, set(), self.task, task_id=self.task) + self.assertIn("Delivery PR: https://github.com/example/repo/pull/42", publish.render(summary)) + self.assertTrue(report.timeline(self.con, self.task)["events"]) diff --git a/tests/test_source_availability.py b/tests/test_source_availability.py index e9ec2ab..d3c23e7 100644 --- a/tests/test_source_availability.py +++ b/tests/test_source_availability.py @@ -131,12 +131,19 @@ def test_cli_reports_the_machine_gap(self): self.assertIn("ledger-only", text.stdout) self.assertNotIn(self.live, text.stdout) + def _own_session(self, session, task): + # Isolate source availability from the independent input-ownership gate. + self.con.execute("INSERT INTO session_assignments(session_key,task_id,evidence,created_at)" + " VALUES(?,?,'explicit fixture ownership',0)", (session, task)) + def _bind_all(self, task): _setup_tasks(self, task) rows = self.con.execute("SELECT native_id FROM user_messages").fetchall() self.assertGreater(len(rows), 0) for row in rows: _assign(self, row["native_id"], task) + for row in self.con.execute("SELECT DISTINCT session_key FROM user_messages"): + self._own_session(row[0], task) def test_deleted_opencode_session_is_not_available(self): native_path = os.path.join(self.tmp.name, "opencode.db") @@ -227,6 +234,7 @@ def test_eventless_opencode_session_is_not_available(self): (child,))] self.assertGreater(len(child_messages), 0) _setup_tasks(self, "T-CHILD") + self._own_session(child, "T-CHILD") for native_id in child_messages: _assign(self, native_id, "T-CHILD") source = self.con.execute( @@ -301,6 +309,7 @@ def test_relocated_eventless_source_stays_available(self): "SELECT native_id FROM user_messages WHERE session_key=?", (session_key,)).fetchone()["native_id"] _setup_tasks(self, "T-QUIET") + self._own_session(session_key, "T-QUIET") _assign(self, native_id, "T-QUIET") source = self.con.execute( "SELECT * FROM sources WHERE path=?", (live,)).fetchone() diff --git a/tests/test_t3.py b/tests/test_t3.py index fab75dc..468bd61 100644 --- a/tests/test_t3.py +++ b/tests/test_t3.py @@ -368,18 +368,21 @@ def test_tree_tasks_and_shared_ownership(self): "unit": "USD per million tokens", "models": {}}) self.assertEqual(shared["attributed"]["responses"], 0) - self.assertEqual(shared["shared_joint"]["responses"], 4) + self.assertEqual(shared["unplaced_shared"]["responses"], 4) self.assertEqual(shared["unassigned_in_scope"]["responses"], 0) self.assertTrue(shared["reconciles"]) # Never divided: the same whole responses sit under both tasks. other = report.task_report(self.con, "example/alpha#3", schedule=shared["price_schedule"]) self.assertEqual( - sorted(shared["measured"]["shared_responses"]), - sorted(other["measured"]["shared_responses"])) + sorted(shared["measured"]["unplaced_responses"]), + sorted(other["measured"]["unplaced_responses"])) solo = report.task_report(self.con, "example/alpha#9", schedule=shared["price_schedule"]) - self.assertEqual(solo["attributed"]["responses"], 1) + self.assertEqual(solo["attributed"]["responses"], 0) + self.assertEqual(solo["unplaced_shared"]["responses"], 1) + self.assertEqual(solo["total_cost"]["text"], "unknown") + self.assertEqual(shared["total_cost"]["responses"], 0) self.assertEqual(solo["shared_joint"]["responses"], 0) def test_changed_link_drops_stale_t3_bindings_only(self): @@ -704,6 +707,11 @@ def test_known_sessions_without_bound_usage_are_visible(self): self.assertEqual(rep["coverage"]["unbound_usage"], ["codex:unbound-sess"]) + self.assertFalse(rep["coverage"]["complete"]) + self.assertIsNone(rep["estimated_cost"]["estimated_cost_usd_total"]) + self.assertIsNone(rep["native_cost"]["total_usd"]) + self.assertEqual(rep["total_cost"]["text"], "unknown") + def test_unbound_usage_is_a_visible_cli_failure(self): self.con.execute( "INSERT INTO sources(harness, path, sha256, imported_at)" From a1fa2ed597e2d750c7cee5c474c1fd597a27ab24 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:12:58 +0100 Subject: [PATCH 05/44] wip: reconcile literal Grok tool calls and inverse turn records --- agent_observer/adapters/grok.py | 47 ++++++++++++++++++++++----- agent_observer/adapters/t3_purpose.py | 24 ++++++++++++-- agent_observer/outcome.py | 27 ++++++++++++--- agent_observer/report.py | 13 +++++--- tests/test_outcome.py | 18 ++++++++++ tests/test_t3_purpose.py | 43 +++++++++++++++++++++++- 6 files changed, 151 insertions(+), 21 deletions(-) diff --git a/agent_observer/adapters/grok.py b/agent_observer/adapters/grok.py index be08075..32ad90d 100644 --- a/agent_observer/adapters/grok.py +++ b/agent_observer/adapters/grok.py @@ -2924,9 +2924,7 @@ def _read_state(status): def _record_prompt_bridges(r, src, records): - """Chromeria's native input ref is prompt:. The completion - has a different prompt_id; only an input frame carrying both can join it. - """ + """Keep literal Grok input, tool call and completion witnesses per source.""" r.con.execute(""" CREATE TABLE IF NOT EXISTS grok_prompt_bridges ( session_key TEXT NOT NULL, prompt_id TEXT NOT NULL, input_ref TEXT NOT NULL, @@ -2951,6 +2949,12 @@ def _record_prompt_bridges(r, src, records): if len(ids) == 1 and None not in ids: pid, = ids witnesses.add((pid, "")) # A scoped completion, independent of input order. + elif kind == "tool_call": + meta = params.get("_meta") + pid = _valid_native_id(meta.get("promptId")) if isinstance(meta, dict) else None + call = _valid_native_id(update.get("toolCallId")) + if pid and call: + witnesses.add((pid, "call:" + call)) elif kind == "user_message_chunk": meta = update.get("_meta") if not isinstance(meta, dict): @@ -2969,25 +2973,52 @@ def _record_prompt_bridges(r, src, records): ((r.session_key, pid, ref, src.source_id) for pid, ref in witnesses)) -def response_inputs(con, session_key): +def response_witnesses(con, session_key): if not db._has_table(con, "grok_prompt_bridges"): - return {} + return {}, set() completed = set() indexes = {} + calls = {} for pid, ref in con.execute("SELECT DISTINCT prompt_id,input_ref FROM grok_prompt_bridges" " WHERE session_key=?", (session_key,)): - if ref: + if ref.startswith("call:"): + calls.setdefault(ref[5:], set()).add(pid) + elif ref: indexes.setdefault(ref, set()).add(pid) else: completed.add(pid) + disputed = set() + tool_witnesses = set() + if calls and db._has_table(con, "t3_purpose_grok_calls"): + projected = {} + for call, turn, index in con.execute( + "SELECT c.call_id,c.provider_turn_id,i.native_id FROM t3_purpose_grok_calls c " + "LEFT JOIN t3_purpose_inputs i ON i.session_key=c.session_key " + "AND i.provider_turn_id=c.provider_turn_id AND i.validation='grok_prompt_index' " + "WHERE c.session_key=?", (session_key,)): + projected.setdefault(call, set()).add((turn, index)) + for call in calls.keys() & projected.keys(): + pids, owners = calls[call], projected[call] + if len(pids) != 1 or len(owners) != 1: + disputed.update(pids) + continue + _, index = next(iter(owners)) + if index is not None: + indexes.setdefault(index, set()).update(pids) + tool_witnesses.update(f"{session_key}:{pid}" for pid in pids) # One native index claiming two different prompt ids is contradictory, # including when the two claims came from different copies. - disputed = {pid for pids in indexes.values() if len(pids) > 1 for pid in pids} + disputed.update(pid for pids in indexes.values() if len(pids) > 1 for pid in pids) eligible = completed - disputed refs = {} for ref, pids in indexes.items(): for pid in pids & eligible: refs.setdefault(f"{session_key}:{pid}", set()).add(ref) - return {rid: refs[rid] for rid, in con.execute( + result = {rid: refs[rid] for rid, in con.execute( "SELECT response_id FROM responses WHERE session_key=? AND is_overlap=0", (session_key,) ) if rid in refs} + return result, tool_witnesses.intersection(result) + + +def response_inputs(con, session_key): + return response_witnesses(con, session_key)[0] diff --git a/agent_observer/adapters/t3_purpose.py b/agent_observer/adapters/t3_purpose.py index 83d6f8d..4d5b043 100644 --- a/agent_observer/adapters/t3_purpose.py +++ b/agent_observer/adapters/t3_purpose.py @@ -25,6 +25,8 @@ "inputs": """run_id TEXT NOT NULL, session_key TEXT NOT NULL, native_id TEXT NOT NULL, kind TEXT NOT NULL, validation TEXT NOT NULL, attempt_id TEXT, provider_turn_id TEXT, segment_id TEXT""", + "grok_calls": """session_key TEXT NOT NULL, call_id TEXT NOT NULL, provider_turn_id TEXT NOT NULL, + PRIMARY KEY(session_key,call_id,provider_turn_id)""", "deliveries": """task_id TEXT NOT NULL, thread_id TEXT NOT NULL, host TEXT NOT NULL, repository TEXT NOT NULL, number INTEGER NOT NULL, url TEXT NOT NULL, declared_at TEXT NOT NULL, PRIMARY KEY(task_id,thread_id,url,declared_at)""", @@ -174,10 +176,10 @@ def _purpose(value): return INVALID -def _rows(native, tables, name, where=""): +def _rows(native, tables, name, where="", args=()): if PROJECTION + name not in tables: return - for row in native.execute("SELECT * FROM " + PROJECTION + name + where): + for row in native.execute("SELECT * FROM " + PROJECTION + name + where, args): row = dict(row) try: payload = json.loads(row.pop("payload_json", None)) @@ -433,7 +435,24 @@ def _attempts(con, native, tables, runs, providers): return attempts +def _grok_call_refs(con, native, tables, owner, columns): + if "provider_turn_id" not in columns: + return + key, run, thread, pt, turn = owner + for row, item in _rows(native, tables, "turn_items", " WHERE provider_turn_id=?", (turn,)): + if (row.get("type") not in {"dynamic_tool", "file_search", "web_search", "command_execution", "file_change"} + or (row.get("run_id"), row.get("thread_id"), row.get("provider_thread_id")) != (run, thread, pt) + or not _matches(row, item, ("run_id", "runId"), ("thread_id", "threadId"), + ("provider_thread_id", "providerThreadId"), ("provider_turn_id", "providerTurnId"), + ("turn_item_id", "id"), ("type", "type"))): + continue + call = _strong(item.get("nativeItemRef"), "grok") + if call: + _insert(con, "grok_calls", key, call, turn) + + def _turns(con, native, tables, attempts): + item_columns = {r[1] for r in native.execute("PRAGMA table_info(orchestration_v2_projection_turn_items)")} for row, p in _rows(native, tables, "provider_turns", " WHERE run_attempt_id IS NOT NULL"): aid = _id(row.get("run_attempt_id")) if aid not in attempts: @@ -464,6 +483,7 @@ def _turns(con, native, tables, attempts): if identity and _v1(i) and INPUT_TYPES.get(driver) == pair: witnesses.add((identity, *pair)) if driver == "grok": + _grok_call_refs(con, native, tables, (key, run, thread, pt, turn), item_columns) identity = _strong(p.get("nativeTurnRef"), driver) if identity and re.fullmatch(r"prompt:(0|[1-9][0-9]{0,15})", identity) and int(identity[7:]) <= MAX_INT: witnesses.add((identity, "message", "grok_prompt_index")) diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index 30860cc..aa79a7e 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -16,10 +16,15 @@ def sessions(con, task_id): def active(con, task_id): return _has_table(con, "t3_purpose_runs") and con.execute( - "SELECT 1 FROM t3_purpose_runs WHERE task_id=? LIMIT 1", (task_id,) + "SELECT 1 FROM t3_purpose_runs WHERE task_id=? " + "UNION ALL SELECT 1 FROM t3_purpose_deliveries WHERE task_id=? LIMIT 1", (task_id, task_id) ).fetchone() is not None +def legacy_link(evidence): + return evidence == "t3" or (evidence or "").startswith("t3:") + + def evidence(con, task_id, scope): """A response belongs to one execution only if both native joins agree.""" from . import native_response @@ -48,7 +53,7 @@ def evidence(con, task_id, scope): by_input[native_id].add((run, turn, segment, validation)) whole = {r["task_id"] for r in con.execute( "SELECT task_id, evidence FROM session_assignments WHERE session_key=?", (key,)) - if not (r["evidence"] or "").startswith("t3:")} + if not legacy_link(r["evidence"])} claimed_inputs = defaultdict(set) for msg, alias, turn, owner in con.execute( "SELECT s.native_id,s.alias_id,s.turn_id,a.task_id FROM assignments a " @@ -57,7 +62,13 @@ def evidence(con, task_id, scope): if identity: claimed_inputs[identity].add(owner) harness = key.partition(":")[0] - for rid, input_ids in native_response.inputs(con, key).items(): + call_witnesses = set() + if harness == "grok": + from .adapters import grok + responses, call_witnesses = grok.response_witnesses(con, key) + else: + responses = native_response.inputs(con, key) + for rid, input_ids in responses.items(): candidates = {run for identity in input_ids for run in by_input.get(identity, ())} if not candidates: continue @@ -67,12 +78,15 @@ def evidence(con, task_id, scope): run, turn, segment, validation = next(iter(candidates)) owner = by_run.get(run) native_id = next(iter(input_ids)) - claims = whole | claimed_inputs.get(f"{harness}:{native_id}", set()) + assignment_id = f"{key}:{native_id}" if harness == "grok" else f"{harness}:{native_id}" + claims = whole | claimed_inputs.get(assignment_id, set()) if (reference_conflict and owner == task_id) or (claims and claims != {owner}): conflicts.add(rid) continue ownership[rid] = owner if owner == task_id: + if rid in call_witnesses: + validation = "grok_tool_call" members[rid] = {"run_id": run, "session_key": key, "native_input_id": native_id, "provider_turn_id": turn, "segment_id": segment, "validation": validation} if harness == "codex": @@ -157,6 +171,8 @@ def check_inventory(con, native, rows): "USING(response_id) WHERE r.session_key=?", (key,))) gaps = set() main_gaps = set() + if not native["runs"]: + main_gaps.add("purpose_run_unavailable") checks = [] for run in native["runs"]: run_id = run["run_id"] @@ -171,7 +187,8 @@ def check_inventory(con, native, rows): for a in attempts: turns = [dict(r) for r in con.execute( "SELECT * FROM t3_purpose_turns WHERE attempt_id=? ORDER BY provider_turn_id", (a["attempt_id"],))] - if a["provider_turn_id"] not in {t["provider_turn_id"] for t in turns}: + if not turns or (a["provider_turn_id"] is not None and + a["provider_turn_id"] not in {t["provider_turn_id"] for t in turns}): main_gaps.add("expected_provider_turn_missing") for turn in turns: state = _turn_check(turn, by_turn[turn["provider_turn_id"]], finalized) diff --git a/agent_observer/report.py b/agent_observer/report.py index 678dec1..d517c7b 100644 --- a/agent_observer/report.py +++ b/agent_observer/report.py @@ -219,7 +219,7 @@ def task_sessions(con: sqlite3.Connection, task_id: str) -> set: keys.update(outcome.sessions(con, task_id)) for r in con.execute( "SELECT session_key, evidence FROM session_assignments WHERE task_id=?", (task_id,)): - if not (r["evidence"] or "").startswith("t3:") or not canonical: + if not outcome.legacy_link(r["evidence"]) or not canonical: keys.add(r["session_key"]) keys |= {r["session_key"] for r in con.execute( "SELECT session_key FROM task_turns WHERE task_id=? AND session_key IS NOT NULL", @@ -536,8 +536,8 @@ def task_report(con: sqlite3.Connection, task_id: str, (key,)).fetchone() for key in scope_keys)): native, purpose_owners, native_turns = outcome.evidence(con, task_id, scope_keys) whole = {k: v for k, v in whole.items() - if not (v or "").startswith("t3:") or (not canonical and k not in native["sessions"])} - legacy_links = {key for key, ev in whole.items() if ev == "t3" or (ev or "").startswith("t3:")} + if not outcome.legacy_link(v) or (not canonical and k not in native["sessions"])} + legacy_links = {key for key, ev in whole.items() if outcome.legacy_link(ev)} whole_shared = {r["session_key"] for r in con.execute( "SELECT session_key FROM session_assignments GROUP BY session_key" " HAVING COUNT(DISTINCT task_id) > 1")} @@ -908,7 +908,9 @@ def _resp_tuple(r) -> list: con, task_id, total_estimated, attributed, billed_shared, joint, whole) if canonical and inventory_gaps and total_estimated.get("priced_responses"): subtotal = total_estimated["estimated_cost_usd_partial"] - report["total_cost"]["text"] = f"unknown (observed priced subtotal ${subtotal:,.2f})" + amount = "under $0.01" if 0 < subtotal < 0.005 else f"${subtotal:,.2f}" + report["total_cost"].update(usd=None, observed_subtotal_usd=subtotal, + text=f"unknown (observed priced subtotal {amount})") report["total_cost"]["unplaced"] = { "text": _money(unplaced_estimated) if unplaced else None, "responses": len(unplaced), @@ -1007,7 +1009,8 @@ def timeline(con: sqlite3.Connection, task_id: str | None = None, native, _, native_turns = outcome.evidence(con, task_id, outcome.sessions(con, task_id)) matches = {rid: member for rid, member in native["membership"].items() if (not session_key or member["session_key"] == session_key) - and (not turn_id or turn_id == member["session_key"].partition(":")[0] + ":" + member["native_input_id"])} + and (not turn_id or turn_id == (rid if member["session_key"].startswith("grok:") + else member["session_key"].partition(":")[0] + ":" + member["native_input_id"]))} for key in sorted({m["session_key"] for m in matches.values() if m["session_key"].startswith("claude:")}): # Claude gives each text event the transcript UUID and block # index. Its parent chain proves the response independently of diff --git a/tests/test_outcome.py b/tests/test_outcome.py index 2bbae7a..ed08526 100644 --- a/tests/test_outcome.py +++ b/tests/test_outcome.py @@ -40,12 +40,20 @@ def test_final_counter_reconciliation_changes_when_a_response_disappears(self): self.assertEqual(rep["measured"]["attributed_responses"], ["codex:resp-mini-001", "codex:resp-mini-002"]) self.assertEqual(rep["native_purpose"]["turn_checks"][0]["status"], "reconciled") self.assertFalse(rep["complete"]) + self.assertIsNone(rep["total_cost"]["usd"]) self.assertIn("background_inventory_unavailable", rep["native_purpose"]["coverage_gaps"]) self.con.execute("DELETE FROM responses WHERE response_id='codex:resp-mini-002'") late = report.task_report(self.con, self.task) self.assertEqual(late["native_purpose"]["turn_checks"][0]["status"], "counter_mismatch") self.assertNotEqual(late["snapshot_id"], rep["snapshot_id"]) + def test_validated_inverse_turn_witness_when_attempt_has_no_turn_pointer(self): + self.con.execute("UPDATE t3_purpose_attempts SET provider_turn_id=NULL") + self.assertTrue(report.task_report(self.con, self.task)["native_purpose"]["main_agent_counters_reconciled"]) + self.con.execute("DELETE FROM t3_purpose_turns") + gaps = report.task_report(self.con, self.task)["native_purpose"]["coverage_gaps"] + self.assertIn("expected_provider_turn_missing", gaps) + def test_two_issues_share_a_planner_but_each_gets_its_own_responses(self): self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES('example/repo#12',0)") self.con.execute("INSERT INTO t3_purpose_runs(run_id,thread_id,task_id,scope)" @@ -93,3 +101,13 @@ def test_delivery_does_not_move_responses_and_report_needs_no_write(self): summary = publish.summarize(self.con, set(), self.task, task_id=self.task) self.assertIn("Delivery PR: https://github.com/example/repo/pull/42", publish.render(summary)) self.assertTrue(report.timeline(self.con, self.task)["events"]) + + def test_delivery_survives_missing_run_with_unknown_cost(self): + self.con.execute("INSERT INTO t3_purpose_deliveries VALUES(?, 'planner', 'github.com'," + "'example/repo',42,'https://github.com/example/repo/pull/42','2026-11-25T00:00:00Z')", + (self.task,)) + self.con.execute("DELETE FROM t3_purpose_runs") + rep = report.task_report(self.con, self.task) + self.assertEqual(rep["native_purpose"]["deliveries"][0]["number"], 42) + self.assertIn("purpose_run_unavailable", rep["native_purpose"]["coverage_gaps"]) + self.assertIsNone(rep["total_cost"]["usd"]) diff --git a/tests/test_t3_purpose.py b/tests/test_t3_purpose.py index b7e7664..a40d562 100644 --- a/tests/test_t3_purpose.py +++ b/tests/test_t3_purpose.py @@ -2,8 +2,10 @@ import json import os import sqlite3 +from pathlib import Path -from agent_observer.adapters import t3 +from agent_observer import report +from agent_observer.adapters import grok, t3 from tests.helpers import LedgerCase PREFIX = "orchestration_v2_projection_" @@ -101,6 +103,45 @@ def test_corrupt_joins_and_unvalidated_grok_stay_gaps(self): self.assertEqual(self.refresh()["failed"], []) self.assertEqual(self.values("SELECT * FROM t3_purpose_inputs"), []) + def test_grok_call_identifies_the_completion_and_reused_calls_fail_closed(self): + self.native.execute(f"CREATE TABLE {PREFIX}turn_items (turn_item_id,thread_id,run_id," + "provider_thread_id,provider_turn_id,type,payload_json)") + cols = ["item", "t", "g", "pt-grok", "turn-g", "command_execution"] + item = dict(id="item", threadId="t", runId="g", providerThreadId="pt-grok", + providerTurnId="turn-g", type="command_execution", nativeItemRef=strong("grok", "call")) + self.row("turn_items", cols, item) + sid = "historic-grok" + root = Path(self.tmp.name, sid) + root.mkdir() + records = [] + def frame(update, **meta): + records.append(json.dumps(dict(method="session/update", + params=dict(sessionId=sid, update=update, _meta=meta)))) + def ingest(): + (root / "updates.jsonl").write_text("\n".join(records) + "\n") + grok.import_grok_session(self.con, str(root), full=True) + def membership(): + return report.task_report(self.con, "git.example.org/example/project#7")["native_purpose"]["membership"] + + frame(dict(sessionUpdate="turn_completed", prompt_id="done")) + frame(dict(sessionUpdate="tool_call", toolCallId="call"), promptId="done") + ingest() + self.refresh() + rid = "grok:historic-grok:done" + self.assertEqual(membership()[rid]["validation"], "grok_tool_call") + self.native.execute(f"UPDATE {PREFIX}turn_items SET provider_thread_id='wrong'") + self.refresh() + self.assertEqual(membership(), {}) + self.native.execute(f"UPDATE {PREFIX}turn_items SET provider_thread_id='pt-grok'," + "payload_json=json_set(payload_json,'$.nativeItemRef.strength','weak')") + self.refresh() + self.assertEqual(membership(), {}) + self.native.execute(f"UPDATE {PREFIX}turn_items SET payload_json=?", (json.dumps(item),)) + self.refresh() + frame(dict(sessionUpdate="tool_call", toolCallId="call"), promptId="another") + ingest() + self.assertEqual(membership(), {}) + def test_invalid_scope_and_cross_driver_evidence(self): self.provider("claudeAgent") self.run_turn("c", "claudeAgent", dict(PURPOSE, version=True), [ From d13e4698c49e3166626b08da5f1dddc6812fc5f4 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:16:19 +0100 Subject: [PATCH 06/44] wip: reject quarantined ownership and filter published cost evidence --- agent_observer/adapters/codex.py | 10 +++++----- agent_observer/publish.py | 11 ++++++++--- tests/test_native_response.py | 15 +++++++++++++++ tests/test_publish.py | 14 ++++++++++++++ 4 files changed, 42 insertions(+), 8 deletions(-) diff --git a/agent_observer/adapters/codex.py b/agent_observer/adapters/codex.py index e8fbf05..e46dd04 100644 --- a/agent_observer/adapters/codex.py +++ b/agent_observer/adapters/codex.py @@ -1600,11 +1600,6 @@ def _ingest_usage(r: _Reader, obj: dict) -> None: th = th_raw if isinstance(th_raw, dict) else {} rid = f"{HARNESS}:{p['response_id']}" turn_id = f"{HARNESS}:{p['turn_id']}" if p.get("turn_id") else None - native_turn = native_response.identifier(p.get("turn_id")) - if (native_turn and (r.thread_id or r.session_id) - and native_response.identifier(p.get("response_id")) - and p.get("thread_id") in (None, r.thread_id)): - native_response.record(r.con, r.src.source_id, r.session_key, rid, native_turn) cur = r.con.execute( "INSERT OR IGNORE INTO responses(response_id, source_id, harness," " session_key, thread_id, turn_id, root_turn_id, session_id," @@ -1647,6 +1642,11 @@ def _ingest_usage(r: _Reader, obj: dict) -> None: r.usage_context_seen.add(rid) r.stats["responses_inserted"] += 1 _note_occurrence(r, "response", rid, obj, model=r.model, effort=r.effort) + native_turn = native_response.identifier(p.get("turn_id")) + if (native_turn and (r.thread_id or r.session_id) + and native_response.identifier(p.get("response_id")) + and p.get("thread_id") in (None, r.thread_id)): + native_response.record(r.con, r.src.source_id, r.session_key, rid, native_turn) if turn_id: r.con.execute( "INSERT OR IGNORE INTO turns(turn_id, source_id, session_key," diff --git a/agent_observer/publish.py b/agent_observer/publish.py index c11b3e1..efa5425 100644 --- a/agent_observer/publish.py +++ b/agent_observer/publish.py @@ -222,6 +222,7 @@ def summarize(con, session_keys: set, label: str, task_id: str | None = None, "time": rep["time"], "native_cost": rep["native_cost"], "native_cost_shared": rep["native_cost_shared"], + "native_cost_billed_shared": rep["native_cost_billed_shared"], "estimated_cost": rep["estimated_cost"], "estimated_cost_shared": rep["estimated_cost_shared"], "total_cost": rep["total_cost"], @@ -433,14 +434,18 @@ def render(summary: dict, target: str | None = None) -> str: _counted(sessions, "session", "sessions"), wall] lines = [MARKER, f"### {title}", "", " · ".join(parts), ""] native = summary.get("native_purpose") or {} - if native.get("runs"): + if native.get("runs") or native.get("deliveries"): lines.append(f"Outcome: {_safe_field(summary['task_id'])}. " "Only responses with proved ownership enter the native subtotal.") if native.get("coverage_gaps"): lines.append("Full outcome cost unknown. Native coverage: " + ", ".join(_safe_field(g.replace("_", " ")) for g in native["coverage_gaps"]) + ".") for pr in native["deliveries"]: - lines.append(f"Delivery PR: {_safe_field(pr['url'])}") + reference = _safe_ref(pr["url"]) + if reference is not None: + lines.append(f"Delivery PR: {reference}") + else: + lines.append("Delivery PR: [reference withheld]") lines.append("") if not task: lines += [f"_{_safe_field(summary.get('session_note') or 'Session scope only.')} " @@ -524,7 +529,7 @@ def render(summary: dict, target: str | None = None) -> str: lines.append("- Prices: no sourced price schedule, so the estimate is unknown.") if est.get("coverage_note"): lines.append(f"- {_safe_field(est['coverage_note'])}.") - natives = [summary.get("native_cost") or {}, summary.get("native_cost_shared") or {}] + natives = [summary.get("native_cost") or {}, summary.get("native_cost_billed_shared") or {}] known = sum(n.get("known_responses", 0) or 0 for n in natives) if not known: lines.append("- Harness-reported cost: none reported.") diff --git a/tests/test_native_response.py b/tests/test_native_response.py index a831062..394ba53 100644 --- a/tests/test_native_response.py +++ b/tests/test_native_response.py @@ -78,6 +78,21 @@ def test_codex_atomic_conflict_and_legacy_snapshot(self): (legacy["session_key"],)) self.assertEqual(native_response.inputs(self.con, legacy["session_key"]), {}) + def test_quarantined_codex_conflict_cannot_supply_a_turn(self): + rows = [json.loads(line) for line in Path(fixture("codex-mini.jsonl")).read_text().splitlines()] + atomic = next(row for row in rows if row["type"] == "token_usage_record") + path = Path(self.tmp.name, "rollout.jsonl") + rid = "codex:" + atomic["payload"]["response_id"] + turn = atomic["payload"].pop("turn_id") + write_records(path, rows) + key = codex.import_codex_file(self.con, str(path))["session_key"] + atomic["payload"].update(turn_id=turn) + atomic["payload"]["usage"]["input_tokens"] += 1 + write_records(path, [atomic], "a") + stats = codex.import_codex_file(self.con, str(path)) + self.assertGreater(stats["malformed"], 0) + self.assertNotIn(rid, native_response.inputs(self.con, key)) + def test_opencode_requires_same_session_user_parent_and_replaces_snapshot(self): path = Path(self.tmp.name, "opencode.db") build_native(str(path)) diff --git a/tests/test_publish.py b/tests/test_publish.py index 68eff7a..389c728 100644 --- a/tests/test_publish.py +++ b/tests/test_publish.py @@ -95,6 +95,20 @@ def test_render_marks_unknown_counters_honestly(self): self.assertIn("| unknown (claude) | 1 | unknown |", body) self.assertIn("| claude-fable-5-1 (claude) | 2 | >=1,234 (lower bound) |", body) + def test_delivery_reference_privacy_and_excluded_cost_in_a_task_publication(self): + summary = publish.summarize(self.con, {"claude:s1"}, "task T") + summary.update(scope_kind="task", task_id="org/repo#1", + native_cost_shared={"known_responses": 2, "known_subtotal_usd": 84}, + native_cost_billed_shared={"known_responses": 0}, + native_purpose={"runs": [{}], "deliveries": [ + {"url": "https://internal.example/private/project/pull/42"}, + {"url": "https://github.com/org/repo/pull/12"}]}) + body = publish.render(summary) + self.assertNotIn("internal.example", body) + self.assertIn("Delivery PR: https://github.com/org/repo/pull/12", body) + self.assertIn("Harness-reported cost: none reported.", body) + self.assertNotIn("$84", body) + def test_second_publish_edits_the_same_owned_comment(self): gh = PublishGh([]) with mock.patch.object(publish, "_gh", gh): From 581beb0669cbc2e05b58f63a13a52cc7db550b55 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:17:21 +0100 Subject: [PATCH 07/44] wip: document the Grok completion witnesses --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 95884b4..da50120 100644 --- a/README.md +++ b/README.md @@ -520,6 +520,10 @@ lists the native responses joined to that purpose, even before a delivery PR exists. The `native_purpose` section identifies each run, the input that joins a response to it, delivery PRs, provider counter checks, and gaps in coverage. A planner serving two Issues can have responses for each in the same session. +For Grok, a session update can connect the prompt index to the completion ID. +A tool call can also supply that connection when Chromeria and Grok record +the same call ID for the turn. A tool-free response without either witness +stays unplaced. A provider turn can reconcile while the full outcome cost remains unknown. Chromeria v1 records observed background causes for some drivers and has no From 3e766ad7d05532db9797f0c2c03db644a9fb52a5 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:19:25 +0100 Subject: [PATCH 08/44] wip: label delivery scope independently of run membership --- agent_observer/publish.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/agent_observer/publish.py b/agent_observer/publish.py index efa5425..e430651 100644 --- a/agent_observer/publish.py +++ b/agent_observer/publish.py @@ -435,8 +435,7 @@ def render(summary: dict, target: str | None = None) -> str: lines = [MARKER, f"### {title}", "", " · ".join(parts), ""] native = summary.get("native_purpose") or {} if native.get("runs") or native.get("deliveries"): - lines.append(f"Outcome: {_safe_field(summary['task_id'])}. " - "Only responses with proved ownership enter the native subtotal.") + lines.append(f"Outcome: {_safe_field(summary['task_id'])}.") if native.get("coverage_gaps"): lines.append("Full outcome cost unknown. Native coverage: " + ", ".join(_safe_field(g.replace("_", " ")) for g in native["coverage_gaps"]) + ".") From 2eb191ed9cd43f6ce5f166bb6fee4f835d41b385 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:20:36 +0100 Subject: [PATCH 09/44] wip: retain Claude ancestry only for accepted records --- agent_observer/adapters/claude.py | 2 +- tests/test_native_response.py | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index b8a0610..c749f88 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -411,8 +411,8 @@ def import_claude_file(con: sqlite3.Connection, path: str, line) continue try: - _record_ancestry(r, obj) _ingest(r, obj, ordinal) + _record_ancestry(r, obj) if obj.get("type") == "queue-operation": con.execute("DELETE FROM import_errors WHERE harness=? AND source_path=?" " AND ordinal_num=? AND error='unsupported_schema'", diff --git a/tests/test_native_response.py b/tests/test_native_response.py index 394ba53..c265aef 100644 --- a/tests/test_native_response.py +++ b/tests/test_native_response.py @@ -29,6 +29,16 @@ def claude_response(uuid, parent, response_id): class NativeResponseTest(LedgerCase): + def test_quarantined_claude_copy_cannot_add_a_second_parent(self): + path = Path(self.tmp.name, "s.jsonl") + rejected = claude_response("copy", "b", "mid") + rejected["message"]["usage"]["output_tokens"] = 99 + write_records(path, [claude_user("a"), claude_user("b"), + claude_response("original", "a", "mid"), rejected]) + imported = claude.import_claude_file(self.con, str(path)) + self.assertGreater(imported["malformed"], 0) + self.assertEqual(native_response.inputs(self.con, "claude:s")["claude:mid"], {"a"}) + def test_claude_out_of_order_tool_chain_cycle_and_competing_streams(self): path = Path(self.tmp.name, "s.jsonl") write_records(path, [ From 9ff55dbfdd02c54f4e7520109c82a4e259b65f42 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:19:21 +0100 Subject: [PATCH 10/44] wip: keep forge identity in legacy checkout placement --- agent_observer/placement.py | 77 +++++++++++++++++++++++++----------- tests/test_placement.py | 79 +++++++++++++++++++++++++++++++++++-- 2 files changed, 129 insertions(+), 27 deletions(-) diff --git a/agent_observer/placement.py b/agent_observer/placement.py index 1b15683..a09c8a1 100644 --- a/agent_observer/placement.py +++ b/agent_observer/placement.py @@ -20,7 +20,12 @@ CALL_FOLLOWS_RESPONSE = {"claude": True, "codex": False} PATH_RE = re.compile(r"(?(){}\[\],=]*") -REMOTE_RE = re.compile(r"[:/]([\w.-]+/[\w.-]+?)(?:\.git)?/?$") +REMOTE_RE = re.compile( + r"(?:(?:https?|ssh|git)://(?:[^/\s@]+@)?(?P[a-z0-9.-]+(?::[0-9]+)?)/" + r"|(?:[^/:\s@]+@)?(?P[a-z0-9.-]+):)" + r"(?P[\w.-]+/[\w.-]+?)(?:\.git)?/?", + re.IGNORECASE | re.ASCII, +) def _git(root: str, *args: str) -> str | None: @@ -38,13 +43,17 @@ def _checkout(path: str, roots: dict) -> tuple: if os.path.exists(os.path.join(root, ".git")): if root not in roots: remote = _git(root, "remote", "get-url", "origin") or "" - match = REMOTE_RE.search(remote) - branch = _git(root, "rev-parse", "--abbrev-ref", "HEAD") if match else None - roots[root] = (match.group(1) if match else None, - branch if branch != "HEAD" else None) + match = REMOTE_RE.fullmatch(remote) + if match: + host = match["url_host"] or match["scp_host"] + branch = _git(root, "rev-parse", "--abbrev-ref", "HEAD") + roots[root] = (host.lower(), match["repository"].lower(), + branch if branch != "HEAD" else None) + else: + roots[root] = (None, None, None) return roots[root] root = os.path.dirname(root) - return None, None + return None, None, None def _legacy_session(con, session_key): @@ -61,15 +70,22 @@ def _legacy_session(con, session_key): def _task_heads(con, task_ids): by_head = {} - if "head_branch" not in {r["name"] for r in con.execute("PRAGMA table_info(t3_links)")}: + columns = {r["name"] for r in con.execute("PRAGMA table_info(t3_links)")} + if not {"host", "head_branch"} <= columns: return by_head for task in task_ids: - repo, _, number = task.rpartition("#") + coordinate, separator, number = task.rpartition("#") + parts = coordinate.lower().split("/") + if not separator or len(parts) not in (2, 3): + continue + # T3 task IDs omit the host for GitHub and prefix it for other forges. + host = parts[0] if len(parts) == 3 else "github.com" + repo = "/".join(parts[-2:]) for row in con.execute( "SELECT DISTINCT head_branch FROM t3_links WHERE kind='pr'" - " AND repository=? AND number=? AND head_branch IS NOT NULL", - (repo, number)): - by_head.setdefault((repo, row["head_branch"]), set()).add(task) + " AND host=? COLLATE NOCASE AND repository=? COLLATE NOCASE" + " AND number=? AND head_branch IS NOT NULL", (host, repo, number)): + by_head.setdefault((host, repo, row["head_branch"]), set()).add(task) return by_head @@ -140,7 +156,8 @@ def _session_paths(con, session_key, harness): def _observations(con, session_key): return {(r["event_id"], r["path_digest"]): - (r["response_id"], r["repository"], r["branch"]) + (r["response_id"], r["host"] if "host" in r.keys() else None, + r["repository"], r["branch"]) for r in con.execute( "SELECT o.* FROM events e JOIN response_checkouts o ON e.id=o.event_id" " WHERE e.session_key=?", (session_key,))} @@ -172,8 +189,13 @@ def read_placements(con, session_key: str) -> dict | None: observed = observations.get(key) if observed is None or observed[0] != rid: pending.add(rid) + continue + _, host, repo, branch = observed + if host is None and repo is not None and branch is not None: + # A hostless historical head could belong to a competing PR. + pending.add(rid) else: - matches[rid].update(heads.get(observed[1:], ())) + matches[rid].update(heads.get((host, repo, branch), ())) return {rid: next(iter(owners)) if rid not in pending and len(owners) == 1 else None for rid, owners in matches.items()} @@ -184,14 +206,20 @@ def read_placements(con, session_key: str) -> dict | None: def record_shared_checkouts(con) -> int: """Observe each event/path once. Reimports can revise its response witness.""" - con.execute( - "CREATE TABLE IF NOT EXISTS response_checkouts(" - " event_id INTEGER NOT NULL REFERENCES events(id) ON DELETE CASCADE," - " path_digest BLOB NOT NULL, response_id TEXT, repository TEXT, branch TEXT," - " PRIMARY KEY(event_id, path_digest))") + # Serialize the schema check and migration across syncs. + with con: + if not con.in_transaction: + con.execute("BEGIN IMMEDIATE") + con.execute( + "CREATE TABLE IF NOT EXISTS response_checkouts(" + " event_id INTEGER NOT NULL REFERENCES events(id) ON DELETE CASCADE," + " path_digest BLOB NOT NULL, response_id TEXT, host TEXT," + " repository TEXT, branch TEXT, PRIMARY KEY(event_id, path_digest))") + columns = {r["name"] for r in con.execute("PRAGMA table_info(response_checkouts)")} + if "host" not in columns: + con.execute("ALTER TABLE response_checkouts ADD COLUMN host TEXT") shared = [r[0] for r in con.execute( "SELECT session_key FROM session_assignments GROUP BY session_key HAVING COUNT(*) > 1")] - con.commit() roots = {} for session_key in shared: legacy = _legacy_session(con, session_key) @@ -204,17 +232,18 @@ def record_shared_checkouts(con) -> int: for key, (rid, path) in paths.items(): observed = observations.get(key) if observed is None: - repo, branch = _checkout(path, roots) + host, repo, branch = _checkout(path, roots) elif observed[0] != rid: - repo, branch = observed[1:] + host, repo, branch = observed[1:] else: continue - changed.append((*key, rid, repo, branch)) + changed.append((*key, rid, host, repo, branch)) # No git subprocess runs under the ledger write lock. On a racing # sync the first checkout observation wins, including a missing one. with con: con.executemany( - "INSERT INTO response_checkouts(event_id,path_digest,response_id,repository,branch)" - " VALUES(?,?,?,?,?) ON CONFLICT(event_id,path_digest) DO UPDATE" + "INSERT INTO response_checkouts" + " (event_id,path_digest,response_id,host,repository,branch)" + " VALUES(?,?,?,?,?,?) ON CONFLICT(event_id,path_digest) DO UPDATE" " SET response_id=excluded.response_id", changed) return len(shared) diff --git a/tests/test_placement.py b/tests/test_placement.py index 3390172..d521cc7 100644 --- a/tests/test_placement.py +++ b/tests/test_placement.py @@ -1,11 +1,12 @@ """A session shared by several PRs splits per response by checkout (#43).""" +import hashlib import io import json import os import shutil import subprocess -from contextlib import redirect_stdout +from contextlib import closing, redirect_stdout from unittest.mock import patch from agent_observer import cli, db, placement, report @@ -45,11 +46,11 @@ def setUp(self): " head_branch) VALUES('t','pr','github.com',?,?,?,?)", (f"o/{repo}", n, f"https://github.com/o/{repo}/pull/{n}", branch)) - def session(self, harness, calls): + def session(self, harness, calls, *, tasks=("o/alpha#1", "o/beta#2")): """calls: (response ordinal, tool-call ordinal, target) per response.""" key = f"{harness}:s" db.upsert_session(self.con, key, harness, "s", None, project_dir="/nowhere") - for task in ("o/alpha#1", "o/beta#2"): + for task in tasks: self.con.execute("INSERT INTO session_assignments(session_key, task_id," " evidence, created_at) VALUES(?,?,'t3',0)", (key, task)) for i, (resp, call, target) in enumerate(calls): @@ -105,6 +106,78 @@ def test_removed_worktree_still_places_from_recorded_checkouts(self): placed = placement.read_placements(self.con, "claude:s") self.assertEqual((placed["r0"], placed["r1"]), ("o/alpha#1", "o/beta#2")) + def test_checkout_on_another_forge_does_not_credit_github(self): + root = self.checkouts["alpha"] + _git("-C", root, "remote", "set-url", "origin", "git@forge.example:o/alpha.git") + key = self.claude_session() + placement.record_shared_checkouts(self.con) + placed = placement.read_placements(self.con, key) + self.assertIsNone(placed["r0"]) + self.assertEqual(placed["r1"], "o/beta#2") + + def test_same_repository_and_head_on_two_forges(self): + github = self.checkouts["alpha"] + hosted = os.path.join(self.tmp.name, "hosted-alpha") + shutil.copytree(github, hosted) + _git("-C", hosted, "remote", "set-url", "origin", "https://FORGE.example/o/alpha.git") + task = "forge.example/o/alpha#1" + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (task,)) + self.con.execute( + "INSERT INTO t3_links(thread_id,kind,host,repository,number,url,head_branch)" + " VALUES('t','pr','Forge.Example','o/alpha',1," + " 'https://forge.example/o/alpha/pull/1','fix/a')") + key = self.session("claude", [ + (1, 2, f"ls {github}"), + (3, 4, f"ls {hosted}"), + (5, 6, f"diff {github}/f {hosted}/f"), + ], tasks=("o/alpha#1", task)) + expected = {"r0": "o/alpha#1", "r1": task, "r2": None} + placement.record_shared_checkouts(self.con) + self.assertEqual(placement.read_placements(self.con, key), expected) + shutil.rmtree(github) + shutil.rmtree(hosted) + with closing(db.connect_read_only(self.db_path)) as ro, patch.object( + placement, "_git", side_effect=AssertionError("report ran git")): + self.assertEqual(placement.read_placements(ro, key), expected) + for task_id, response in (("o/alpha#1", "r0"), (task, "r1")): + measured = report.task_report(ro, task_id, schedule=SCHEDULE)["measured"] + self.assertEqual(measured["attributed_responses"], [response]) + self.assertEqual(measured["unplaced_responses"], ["r2"]) + + def test_pr_head_from_another_forge_cannot_supply_a_github_match(self): + root = self.checkouts["alpha"] + _git("-C", root, "checkout", "-q", "-b", "fix/hosted") + self.con.execute( + "INSERT INTO t3_links(thread_id,kind,host,repository,number,url,head_branch)" + " VALUES('t','pr','forge.example','o/alpha',1," + " 'https://forge.example/o/alpha/pull/1','fix/hosted')") + key = self.claude_session() + placement.record_shared_checkouts(self.con) + self.assertIsNone(placement.read_placements(self.con, key)["r0"]) + + def test_historical_checkout_without_host_cannot_supply_or_hide_a_match(self): + alpha, beta = self.checkouts["alpha"], self.checkouts["beta"] + key = self.session("claude", [ + (1, 2, f"diff {alpha}/f {beta}/f"), + (3, 4, f"ls {alpha}/f"), + ]) + self.con.execute( + "CREATE TABLE response_checkouts(" + " event_id INTEGER NOT NULL REFERENCES events(id) ON DELETE CASCADE," + " path_digest BLOB NOT NULL, response_id TEXT, repository TEXT, branch TEXT," + " PRIMARY KEY(event_id, path_digest))") + event_id = self.con.execute("SELECT id FROM events WHERE native_id='e0'").fetchone()[0] + digest = hashlib.sha256(f"{alpha}/f".encode()).digest() + self.con.execute("INSERT INTO response_checkouts VALUES(?,?,'r0','o/alpha','fix/old')", + (event_id, digest)) + self.con.commit() + with closing(db.connect_read_only(self.db_path)) as ro: + self.assertIsNone(placement.read_placements(ro, key).get("r0")) + for _ in range(2): + placement.record_shared_checkouts(self.con) + self.assertEqual(placement.read_placements(self.con, key), + {"r0": None, "r1": "o/alpha#1"}) + def test_without_head_branches_the_session_stays_shared_whole(self): self.claude_session() self.con.execute("UPDATE t3_links SET head_branch=NULL") From 00c682ed027401bc2a24fb5637b72fa725a860c6 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:21:23 +0100 Subject: [PATCH 11/44] wip: require accepted Grok completion counters for native ownership --- agent_observer/adapters/grok.py | 17 ++++++++++++----- tests/test_native_response.py | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/agent_observer/adapters/grok.py b/agent_observer/adapters/grok.py index 32ad90d..f2ed58e 100644 --- a/agent_observer/adapters/grok.py +++ b/agent_observer/adapters/grok.py @@ -1718,10 +1718,6 @@ def _get_chat() -> dict: # yields no turn model and keeps updates unparsed. updates_records = _load_jsonl_records(updates_path) \ if updates_path and os.path.isfile(updates_path) else [] - if updates_records is not None and updates_src is not None: - _record_prompt_bridges(r, updates_src, updates_records) - con.execute("INSERT OR IGNORE INTO grok_bridge_sources VALUES(?)", - (updates_src.source_id,)) if updates_records is not None: try: _spawns = _extract_spawns_from_records(updates_records) @@ -1874,6 +1870,10 @@ def _replay_error(ordinal: int, category: str, line: str = "") -> None: " WHERE session_key=?", (json.dumps(evidence, sort_keys=True) if evidence else None, version, r.session_key)) _store_meta(con, r.session_key, summary_fp, chat_fp_current, chat) + if updates_records is not None and updates_src is not None: + _record_prompt_bridges(r, updates_src, updates_records) + con.execute("INSERT OR IGNORE INTO grok_bridge_sources VALUES(?)", + (updates_src.source_id,)) if updates_src is not None: stats.update(updates_src.finish(session_id=r.native_sid)) if events_src is not None: @@ -2948,7 +2948,14 @@ def _record_prompt_bridges(r, src, records): ids = {_valid_native_id(update[k]) for k in ("prompt_id", "promptId") if k in update} if len(ids) == 1 and None not in ids: pid, = ids - witnesses.add((pid, "")) # A scoped completion, independent of input order. + try: + counters = _validated_usage_counters(update) + except _AdapterError: + continue + row = r.con.execute("SELECT * FROM responses WHERE session_key=? AND response_id=?", + (r.session_key, f"{r.session_key}:{pid}")).fetchone() + if row and all(value is None or row[name] == value for name, value in counters.items()): + witnesses.add((pid, "")) # An accepted, scoped completion. elif kind == "tool_call": meta = params.get("_meta") pid = _valid_native_id(meta.get("promptId")) if isinstance(meta, dict) else None diff --git a/tests/test_native_response.py b/tests/test_native_response.py index c265aef..4290e17 100644 --- a/tests/test_native_response.py +++ b/tests/test_native_response.py @@ -162,6 +162,24 @@ def frame(data, **meta): grok.import_grok_session(self.con, str(source_dirs[2])) self.assertEqual(native_response.inputs(self.con, key), {}) + def test_grok_quarantined_completion_cannot_supply_session_scope(self): + path = Path(self.tmp.name, "sid") + path.mkdir() + completed = {"sessionUpdate": "turn_completed", "prompt_id": "p", "usage": {"inputTokens": 4}} + chunk = {"sessionUpdate": "user_message_chunk", "_meta": {"promptIndex": 2}, + "content": {"type": "text", "text": "question"}} + def frame(session, update, **meta): + return {"method": "session/update", "params": {"sessionId": session, "update": update, "_meta": meta}} + records = [frame("sid", completed), frame("sid", chunk, promptId="p")] + write_records(path / "updates.jsonl", records) + grok.import_grok_session(self.con, str(path)) + self.assertEqual(native_response.inputs(self.con, "grok:sid"), {"grok:sid:p": {"prompt:2"}}) + records[0]["params"]["sessionId"] = None + records.append(frame("sid", dict(completed, usage={"inputTokens": "malformed"}))) + write_records(path / "updates.jsonl", records) + grok.import_grok_session(self.con, str(path), full=True) + self.assertEqual(native_response.inputs(self.con, "grok:sid"), {}) + def test_opencode_different_copies_preserve_competing_native_parents(self): for copy, parent in enumerate(("msg_u1", "msg_u2")): path = Path(self.tmp.name, f"copy-{copy}.db") From 77ae9cdd5cf548c04d5bf81a371b058a4cdbb91c Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:22:00 +0100 Subject: [PATCH 12/44] wip: preserve native purpose evidence across T3 sources --- agent_observer/adapters/t3.py | 9 + agent_observer/adapters/t3_purpose.py | 234 +++++++++++++++++++------- tests/test_t3_purpose.py | 120 ++++++++++++- 3 files changed, 303 insertions(+), 60 deletions(-) diff --git a/agent_observer/adapters/t3.py b/agent_observer/adapters/t3.py index 00edc4c..88deee9 100644 --- a/agent_observer/adapters/t3.py +++ b/agent_observer/adapters/t3.py @@ -1215,6 +1215,13 @@ def _bind_trees(con: sqlite3.Connection, threads: dict, sessions = _tree_sessions(con, threads, roots) aware_roots = {_lineage_root(t, lineage) for t in aware_threads} protected = {row[0] for row in con.execute("SELECT session_key FROM t3_purpose_sessions")} + # When a run has contradictory purposes, neither candidate can regain + # whole-session credit through an unrelated legacy tree for that task. + disputed_tasks = {r[0] for r in con.execute( + "SELECT DISTINCT s.task_id FROM t3_source_runs s LEFT JOIN t3_purpose_runs r USING(run_id)" + " WHERE r.run_id IS NULL AND s.task_id IS NOT NULL")} + con.executemany("DELETE FROM session_assignments WHERE task_id=? AND evidence GLOB 't3:*:https://*'", + ((task,) for task in disputed_tasks)) # Historical/rotated sessions can outlive their cursor and their tree. # This read proves previous whole-session placement unsafe for these keys. con.execute("DELETE FROM session_assignments WHERE evidence GLOB 't3:*:https://*'" @@ -1240,6 +1247,8 @@ def _bind_trees(con: sqlite3.Connection, threads: dict, (task_id, repository, task_id, link["url"], HARNESS, db.now())) tasks += cur.rowcount + if task_id in disputed_tasks: + continue for session_key in sorted(sessions.get(root, set()) - protected): wanted.add((session_key, task_id)) cur = con.execute( diff --git a/agent_observer/adapters/t3_purpose.py b/agent_observer/adapters/t3_purpose.py index 4d5b043..bb82165 100644 --- a/agent_observer/adapters/t3_purpose.py +++ b/agent_observer/adapters/t3_purpose.py @@ -8,7 +8,9 @@ from datetime import datetime import json +import os import re +import sqlite3 from typing import NamedTuple from .. import db @@ -188,12 +190,20 @@ def _rows(native, tables, name, where="", args=()): yield row, _obj(payload) -def _insert(con, table, *values): - con.execute("INSERT OR IGNORE INTO t3_purpose_" + table + " VALUES(" - + ",".join("?" for _ in values) + ")", values) +class Snapshot(NamedTuple): + con: sqlite3.Connection + path: str + def insert(self, table, *values): + values = (self.path, *values) + self.con.execute(f"INSERT INTO t3_source_{table} VALUES(" + + ",".join("?" for _ in values) + ")", values) -def _participant(con, run, thread, kind, participant, *, child=None, child_run=None, remote=None, + def task(self, ref): + return _task(self.con, ref) + + +def _participant(snapshot, run, thread, kind, participant, *, child=None, child_run=None, remote=None, status=None, group=None, declaration=None): remote = _obj(remote) scope, reason, ref, provenance = _purpose(declaration) @@ -201,8 +211,8 @@ def _participant(con, run, thread, kind, participant, *, child=None, child_run=N if declaration is not None: declared = dict(scope=scope, reason=reason, reference=ref, provenance=provenance) if ref: - _task(con, ref) - _insert(con, "participants", run, thread, kind, _id(participant), _id(remote.get("threadId") or child), + snapshot.task(ref) + snapshot.insert("participants", run, thread, kind, _id(participant), _id(remote.get("threadId") or child), _id(child_run or remote.get("runId")), _id(remote.get("environmentId")), _enum(status, STATES), _id(group), _enum(remote.get("availability"), ("current", "stale", "unsupported", "lost")), _json(declared)) @@ -239,7 +249,7 @@ def _strong(value, driver): return _id(ref.get("nativeId")) -def _deliveries(con, native, tables): +def _deliveries(snapshot, native, tables): aware = set() for row, p in _rows(native, tables, "threads"): thread = _id(row.get("thread_id")) @@ -251,12 +261,12 @@ def _deliveries(con, native, tables): purpose, pr = _reference(d.get("purpose")), _reference(d.get("pullRequest")) at = _date(d.get("declaredAt")) if _v1(d) and purpose and pr and pr["kind"] == "pr" and at: - _insert(con, "deliveries", _task(con, purpose), thread, pr["host"], + snapshot.insert("deliveries", snapshot.task(purpose), thread, pr["host"], pr["repository"], pr["number"], _url(pr), at) return aware -def _runs(con, native, tables): +def _runs(snapshot, native, tables): runs = {} for row, p in _rows(native, tables, "runs"): run, thread = _id(row.get("run_id")), _id(row.get("thread_id")) @@ -265,11 +275,11 @@ def _runs(con, native, tables): purpose = _purpose(p.get("purpose")) if _matches( row, p, ("run_id", "id"), ("thread_id", "threadId")) else INVALID scope, reason, ref, provenance = purpose - key = _task(con, ref) if ref else None + key = snapshot.task(ref) if ref else None coords = ref or {} status = _enum(row.get("status"), STATES) version = _obj(p.get("purpose")).get("version") - _insert(con, "runs", run, thread, key, scope, reason, coords.get("host"), + snapshot.insert("runs", run, thread, key, scope, reason, coords.get("host"), coords.get("repository"), coords.get("kind"), coords.get("number"), _json(provenance), status, version if _number(version) else None, _id(p.get("activeAttemptId"))) @@ -277,15 +287,15 @@ def _runs(con, native, tables): delivery = _obj(_obj(p.get("delegatedCompletion")).get("delivery")) for task in _list(delivery.get("taskIds")): if _id(task): - _participant(con, run, thread, "completion_member", task) + _participant(snapshot, run, thread, "completion_member", task) for cause in map(_obj, _list(delivery.get("purposeCauses"))): if _id(cause.get("taskId")) and _id(cause.get("runId")): - _participant(con, run, thread, "completion_cause", cause["taskId"], + _participant(snapshot, run, thread, "completion_cause", cause["taskId"], child_run=cause["runId"], declaration=cause.get("purpose")) for work in map(_obj, _list(p.get("restartCancelledBackgroundWork"))): category = _enum(work.get("kind"), ("subagent", "shell", "monitor", "task")) if category: - _participant(con, run, thread, "cancelled_" + category, work.get("id"), status="cancelled") + _participant(snapshot, run, thread, "cancelled_" + category, work.get("id"), status="cancelled") return runs @@ -324,19 +334,19 @@ def _usage(value, context=False): return _json(result) -def _capabilities(con, native, tables): +def _capabilities(snapshot, native, tables): for row, p in _rows(native, tables, "provider_sessions"): session = _id(row.get("provider_session_id")) cap = _obj(_obj(p.get("capabilities")).get("purposeEvidence")) if session and session == p.get("id") and _v1(cap): - _insert(con, "capabilities", session, _enum(p.get("driver"), DRIVERS), + snapshot.insert("capabilities", session, _enum(p.get("driver"), DRIVERS), _enum(cap.get("nativeInputs"), ("native_turn", "input_echo", "admitted_message", "unsupported")), _enum(cap.get("childSegments"), ("initial_turn_only", "initial_input_only", "causes_only", "unsupported")), _enum(cap.get("backgroundInventory"), ("observed_causes", "unsupported")), _enum(cap.get("nativeUsageFinality"), ("main_agent_only", "unavailable"))) -def _providers(con, native, tables, runs, segments): +def _providers(snapshot, native, tables, runs, segments): providers = {} for row, p in _rows(native, tables, "provider_threads"): pt = _id(row.get("provider_thread_id")) @@ -352,12 +362,12 @@ def _providers(con, native, tables, runs, segments): for task in map(_obj, _list(p.get("pendingBackgroundTasks"))): run = _id(task.get("runId")) if run in runs and runs[run][0] == thread and _id(task.get("taskId")): - _participant(con, run, thread, "pending_background", task["taskId"], + _participant(snapshot, run, thread, "pending_background", task["taskId"], child=task.get("childThreadId"), remote={"environmentId": task.get("childEnvironmentId")}) return providers -def _subagents(con, native, tables, runs, segments): +def _subagents(snapshot, native, tables, runs, segments): children = {} for row, p in _rows(native, tables, "subagents"): child = _id(row.get("subagent_id")) @@ -371,15 +381,15 @@ def _subagents(con, native, tables, runs, segments): run = _id(row["run_id"]) if run in runs and runs[run][0] == thread: remote = _obj(p.get("remoteChild")) - _participant(con, run, thread, origin, child, child=p.get("childThreadId"), remote=remote, + _participant(snapshot, run, thread, origin, child, child=p.get("childThreadId"), remote=remote, status=p.get("status"), group=p.get("runGroupId"), declaration=p.get("purpose")) completion = _obj(p.get("completionSource")) if _id(completion.get("runId")): - _participant(con, run, thread, "child_completion", child, child=p.get("childThreadId"), + _participant(snapshot, run, thread, "child_completion", child, child=p.get("childThreadId"), remote=remote, child_run=completion["runId"], declaration=completion.get("purpose")) for member in map(_obj, _list(_obj(p.get("workflow")).get("agents"))): if _number(member.get("index")): - _insert(con, "workflow_members", thread, child, member["index"], + snapshot.insert("workflow_members", thread, child, member["index"], member["attempt"] if _number(member.get("attempt")) else None, _id(member.get("agentId")), _id(member.get("childThreadId")), _enum(member.get("state"), ("queued", "running", "completed", "failed")), @@ -392,7 +402,7 @@ def _subagents(con, native, tables, runs, segments): return children -def _expected_children(con, native, tables, runs): +def _expected_children(snapshot, native, tables, runs): # A subagent turn item names the expected child even if its own projection # or the remote ledger is missing. Avoid reading unrelated text/tool items. for row, p in _rows(native, tables, "turn_items", " WHERE type='subagent'"): @@ -403,11 +413,11 @@ def _expected_children(con, native, tables, runs): or not _id(p.get("subagentId"))): continue remote = _obj(p.get("remoteChild")) - _participant(con, run, row["thread_id"], "subagent_item", p["subagentId"], + _participant(snapshot, run, row["thread_id"], "subagent_item", p["subagentId"], child=p.get("childThreadId"), remote=remote, status=p.get("status")) -def _attempts(con, native, tables, runs, providers): +def _attempts(snapshot, native, tables, runs, providers): attempts = {} for row, p in _rows(native, tables, "run_attempts"): aid, run = _id(row.get("attempt_id")), _id(row.get("run_id")) @@ -428,14 +438,14 @@ def _attempts(con, native, tables, runs, providers): sid = _id(p.get("nativeThreadId")) if sid: key = f"{DRIVERS[driver]}:{sid}" - _insert(con, "sessions", run, key) + snapshot.insert("sessions", run, key) attempts[aid] = (run, provider.thread, pt, root, turn, driver, sid, "nativeThreadId" in p) - _insert(con, "attempts", aid, run, pt, turn, _enum(p.get("status"), STATES), + snapshot.insert("attempts", aid, run, pt, turn, _enum(p.get("status"), STATES), key, provider.session if valid else None) return attempts -def _grok_call_refs(con, native, tables, owner, columns): +def _grok_call_refs(snapshot, native, tables, owner, columns): if "provider_turn_id" not in columns: return key, run, thread, pt, turn = owner @@ -447,11 +457,11 @@ def _grok_call_refs(con, native, tables, owner, columns): ("turn_item_id", "id"), ("type", "type"))): continue call = _strong(item.get("nativeItemRef"), "grok") - if call: - _insert(con, "grok_calls", key, call, turn) + if call and _id(row["turn_item_id"]): + snapshot.insert("grok_calls", key, call, turn, row["turn_item_id"]) -def _turns(con, native, tables, attempts): +def _turns(snapshot, native, tables, attempts): item_columns = {r[1] for r in native.execute("PRAGMA table_info(orchestration_v2_projection_turn_items)")} for row, p in _rows(native, tables, "provider_turns", " WHERE run_attempt_id IS NOT NULL"): aid = _id(row.get("run_attempt_id")) @@ -471,11 +481,11 @@ def _turns(con, native, tables, attempts): else: sid = turn_sid or sid key = f"{DRIVERS[driver]}:{sid}" if sid else None - _insert(con, "turns", turn, aid, run, key, _enum(p.get("status"), STATES), + snapshot.insert("turns", turn, aid, run, key, _enum(p.get("status"), STATES), _usage(p.get("turnTokenUsage")), _usage(p.get("tokenUsage"), context=True)) if not key: continue - _insert(con, "sessions", run, key) + snapshot.insert("sessions", run, key) witnesses = set() for i in map(_obj, _list(p.get("nativeInputs"))): identity = _id(i.get("nativeId")) @@ -483,13 +493,13 @@ def _turns(con, native, tables, attempts): if identity and _v1(i) and INPUT_TYPES.get(driver) == pair: witnesses.add((identity, *pair)) if driver == "grok": - _grok_call_refs(con, native, tables, (key, run, thread, pt, turn), item_columns) + _grok_call_refs(snapshot, native, tables, (key, run, thread, pt, turn), item_columns) identity = _strong(p.get("nativeTurnRef"), driver) if identity and re.fullmatch(r"prompt:(0|[1-9][0-9]{0,15})", identity) and int(identity[7:]) <= MAX_INT: witnesses.add((identity, "message", "grok_prompt_index")) if p.get("promptDropped") is not True: for identity, kind, validation in sorted(witnesses): - _insert(con, "inputs", run, key, identity, kind, validation, aid, turn, None) + snapshot.insert("inputs", run, key, identity, kind, validation, aid, turn, None) # Native unresolved reasons are open strings. Only known codes can leave the source. @@ -525,7 +535,7 @@ def _boundary(value): return {"state": "unresolved", "reason": _enum(b.get("reason"), REASONS) or "unknown"} -def _segments(con, rows, runs, children): +def _segments(snapshot, rows, runs, children): child_boundaries = {} # An enclosing subagent's runId names its original launch. Each segment # carries its own initiating run or earlier segment, including on resume. @@ -545,8 +555,8 @@ def _segments(con, rows, runs, children): else: segments[key] = data - destinations = {(r[0], r[1]) for r in con.execute( - "SELECT run_id,session_key FROM t3_purpose_sessions")} + destinations = {(r[0], r[1]) for r in snapshot.con.execute( + "SELECT run_id,session_key FROM t3_source_sessions WHERE source_path=?", (snapshot.path,))} resolved = {} # Resolve exact predecessor edges independent of projection table order. # Unresolved edges, cycles, crossed scopes and crossed sessions stay gaps. @@ -588,8 +598,8 @@ def _segments(con, rows, runs, children): child = _id(p.get("nativeChildId")) run = resolved.get(key) ref = purpose[2] - _insert(con, "segments", owner, thread, segment, subagent, run, - _task(con, ref) if ref else None, + snapshot.insert("segments", owner, thread, segment, subagent, run, + snapshot.task(ref) if ref else None, kind, driver, sid, operation, child, _json(source), _json(boundary), _enum(p.get("status"), ("running", "ended", "roster_absent", "interrupted", "unknown")), _enum(p.get("usageFinality"), ("unreconciled",)), @@ -602,7 +612,7 @@ def _segments(con, rows, runs, children): if driver not in ("codex", "opencode"): continue child_key = f"{DRIVERS[driver]}:{child}" - _insert(con, "sessions", run, child_key) + snapshot.insert("sessions", run, child_key) # Current native contracts certify only Codex child turn boundaries # and OpenCode child input boundaries. Claude task ids are reusable. if driver == "codex" and boundary["state"] == "native_turns": @@ -615,7 +625,7 @@ def _segments(con, rows, runs, children): continue child_thread, child_pt = children[(thread, subagent)] for identity in sorted(set(ids)): - _insert(con, "inputs", run, child_key, identity, input_kind, + snapshot.insert("inputs", run, child_key, identity, input_kind, "segment_" + boundary["state"], None, None, segment) if child_thread and child_pt: lookup = (child_thread, child_pt, driver, child, identity) @@ -623,7 +633,7 @@ def _segments(con, rows, runs, children): return child_boundaries -def _child_turns(con, native, tables, boundaries, providers): +def _child_turns(snapshot, native, tables, boundaries, providers): if not boundaries: return for row, p in _rows(native, tables, "provider_turns", " WHERE run_attempt_id IS NULL"): @@ -640,31 +650,137 @@ def _child_turns(con, native, tables, boundaries, providers): if not native_id or not _v1(i) or (i.get("kind"), i.get("validation")) != INPUT_TYPES.get(driver): continue for run, segment in boundaries.get((thread, pt, driver, sid, native_id), ()): - _insert(con, "child_turns", run, segment, turn, f"{DRIVERS[driver]}:{sid}", + snapshot.insert("child_turns", run, segment, turn, f"{DRIVERS[driver]}:{sid}", _enum(p.get("status"), STATES), _usage(p.get("turnTokenUsage")), _usage(p.get("tokenUsage"), context=True)) +# In a snapshot the primary key identifies the native object. Across snapshots +# an object's immutable coordinates must agree. Different mutable readings +# leave that field unknown until the snapshots agree again. +MUTABLE = { + "runs": {"status", "active_attempt_id"}, + "attempts": {"status"}, + "turns": {"status", "usage_json", "context_usage_json"}, + "segments": {"status", "observed_at", "notice_ids_json", "wake_dispositions_json"}, + "child_turns": {"status", "usage_json", "context_usage_json"}, +} -def refresh(con, native, tables): - """Replace the evidence under the caller's snapshot and ledger savepoint.""" + +def _source_tables(con, path): + # The previous writer replaced the *whole* mirror, then recorded its path + # and import time in the same savepoint. Preserve that last source on upgrade. + prior = con.execute("SELECT path,imported_at FROM sources WHERE harness='t3'" + " ORDER BY imported_at DESC LIMIT 2").fetchall() + old_path = (os.path.realpath(prior[0][0]) if prior and + (len(prior) == 1 or prior[0][1] != prior[1][1]) else None) for table, columns in TABLES.items(): - con.execute(f"CREATE TABLE IF NOT EXISTS t3_purpose_{table} ({columns})") - con.execute(f"DELETE FROM t3_purpose_{table}") + mirror, source = f"t3_purpose_{table}", f"t3_source_{table}" + con.execute(f"CREATE TABLE IF NOT EXISTS {mirror} ({columns})") + if not db._has_table(con, source): + con.execute(f"CREATE TABLE {source} AS SELECT CAST(NULL AS TEXT) AS source_path," + f" * FROM {mirror} WHERE 0") + if table == "grok_calls": + con.execute(f"ALTER TABLE {source} ADD COLUMN turn_item_id TEXT") + con.execute(f"CREATE INDEX {source}_path ON {source}(source_path)") + if old_path and old_path != path: + extra = ",NULL" if table == "grok_calls" else "" + con.execute(f"INSERT INTO {source} SELECT ?,*{extra} FROM {mirror}", (old_path,)) + con.execute(f"DELETE FROM {source} WHERE source_path=?", (path,)) + + +def _materialize(con, table): + mirror, source = f"t3_purpose_{table}", f"t3_source_{table}" + info = con.execute(f"PRAGMA table_info({mirror})").fetchall() + names = [row["name"] for row in info] + keys = [row["name"] for row in info if row["pk"]] + mutable = MUTABLE.get(table, set()) + con.execute(f"DELETE FROM {mirror}") + if not keys: + con.execute(f"INSERT INTO {mirror} SELECT DISTINCT {','.join(names)} FROM {source}") + return + + def agreed(name): + # COUNT ignores NULL. Missing and present values also disagree. + return (f"CASE WHEN count({name})=count(*) AND min({name})=max({name})" + f" THEN min({name}) END" if name in mutable else name) + + immutable = [name for name in names if name not in mutable and name not in keys] + having = (f" HAVING count(DISTINCT json_array({','.join(immutable)}))=1" if immutable else "") + con.execute(f"INSERT INTO {mirror} SELECT {','.join(map(agreed, names))}" + f" FROM {source} GROUP BY {','.join(keys)}{having}") + + +def _exclude_disputed_calls(con): + # A turn item is immutable even when two copies disagree about its call + # ID. Do not let either version establish a call-to-completion bridge. + con.execute("""WITH disputed AS ( + SELECT turn_item_id FROM t3_source_grok_calls WHERE turn_item_id IS NOT NULL + GROUP BY turn_item_id HAVING count(DISTINCT json_array(session_key,call_id,provider_turn_id))>1 + ) + DELETE FROM t3_purpose_grok_calls WHERE (session_key,call_id) IN ( + SELECT session_key,call_id FROM t3_source_grok_calls WHERE turn_item_id IN disputed)""") + + +def _exclude_disputed_inputs(con): + # Inputs are parsed under source-local parents. Withhold the native input + # on every path if one parent key has contradictory immutable coordinates. + # This also prevents a different claimant from winning by elimination. + con.execute("""WITH disputed_segment_runs AS ( + -- A nested segment can inherit the disputed segment as a predecessor. + SELECT s.run_id FROM t3_source_segments s LEFT JOIN t3_purpose_segments t + USING(thread_id,owner_id,segment_id) WHERE t.owner_id IS NULL + ), turn_sources AS ( + SELECT provider_turn_id,count(DISTINCT source_path) AS copies + FROM t3_source_turns GROUP BY provider_turn_id + ), disputed_inputs AS ( + SELECT i.session_key,i.native_id FROM t3_source_inputs i + LEFT JOIN t3_purpose_runs r ON r.run_id=i.run_id + LEFT JOIN t3_purpose_attempts a ON a.attempt_id=i.attempt_id + LEFT JOIN t3_purpose_turns t ON t.provider_turn_id=i.provider_turn_id + WHERE r.run_id IS NULL OR (i.attempt_id IS NOT NULL AND a.attempt_id IS NULL) + OR (i.provider_turn_id IS NOT NULL AND t.provider_turn_id IS NULL) + OR (i.segment_id IS NOT NULL AND i.run_id IN disputed_segment_runs) + UNION + -- Only source-local turn/input joins can witness a response. In + -- particular a Grok call in one copy cannot borrow another copy's + -- prompt index when its own turn has no such index. + SELECT i.session_key,i.native_id FROM t3_source_inputs i JOIN turn_sources USING(provider_turn_id) + GROUP BY i.session_key,i.native_id,i.provider_turn_id + HAVING count(DISTINCT i.source_path) Date: Wed, 25 Nov 2026 19:22:12 +0100 Subject: [PATCH 13/44] wip: reconcile explicit capture with native report and trace ownership --- agent_observer/outcome.py | 202 +++++++++++++++++++++++++++----------- agent_observer/report.py | 137 ++++++++++++-------------- tests/test_outcome.py | 117 ++++++++++++++++++++++ 3 files changed, 326 insertions(+), 130 deletions(-) diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index aa79a7e..86df212 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -1,6 +1,7 @@ """Read immutable purpose and native response witnesses in one ledger snapshot.""" from collections import defaultdict +from dataclasses import dataclass, field import json from .db import _has_table @@ -16,8 +17,7 @@ def sessions(con, task_id): def active(con, task_id): return _has_table(con, "t3_purpose_runs") and con.execute( - "SELECT 1 FROM t3_purpose_runs WHERE task_id=? " - "UNION ALL SELECT 1 FROM t3_purpose_deliveries WHERE task_id=? LIMIT 1", (task_id, task_id) + "SELECT 1 FROM t3_purpose_runs WHERE task_id=? LIMIT 1", (task_id,) ).fetchone() is not None @@ -25,10 +25,30 @@ def legacy_link(evidence): return evidence == "t3" or (evidence or "").startswith("t3:") -def evidence(con, task_id, scope): - """A response belongs to one execution only if both native joins agree.""" - from . import native_response +@dataclass +class Ownership: + """Task ownership within the inspected sessions, with canonical witnesses kept separately.""" + native: dict | None = None + # Response partitions are needed only where native and explicit scope meet. + owners: dict = field(default_factory=dict) + turns: set = field(default_factory=set) + claude_capture_turns: dict = field(default_factory=dict) + whole: set = field(default_factory=set) + +def evidence(con, task_id, scope): + """Resolve report and event scope from the same native and explicit claims.""" + result = Ownership() + result.whole.update(key for key, ev in con.execute( + "SELECT session_key,evidence FROM session_assignments WHERE task_id=?", (task_id,)) + if not legacy_link(ev)) + result.turns.update((key, turn) for key, turn in con.execute( + "SELECT s.session_key,s.turn_id FROM assignments a JOIN user_messages s " + "ON a.user_message_id=s.native_id WHERE a.task_id=? AND s.is_genuine=1 " + "AND s.session_key IS NOT NULL AND s.turn_id IS NOT NULL", + (task_id,))) + if not _has_table(con, "t3_purpose_runs"): + return result runs = [dict(r) for r in con.execute( "SELECT * FROM t3_purpose_runs WHERE task_id=? ORDER BY run_id", (task_id,))] deliveries = [dict(r) for r in con.execute( @@ -36,8 +56,6 @@ def evidence(con, task_id, scope): reference_conflict = len({r["kind"] for r in runs}) > 1 session_runs = {} members = {} - ownership = {} - turn_keys = set() conflicts = set() for key in sorted(scope): by_run = dict(con.execute( @@ -46,58 +64,126 @@ def evidence(con, task_id, scope): if not by_run: continue session_runs[key] = sorted(by_run) - by_input = defaultdict(set) - for run, native_id, turn, segment, validation in con.execute( - "SELECT run_id,native_id,provider_turn_id,segment_id,validation FROM t3_purpose_inputs " - "WHERE session_key=?", (key,)): - by_input[native_id].add((run, turn, segment, validation)) - whole = {r["task_id"] for r in con.execute( - "SELECT task_id, evidence FROM session_assignments WHERE session_key=?", (key,)) - if not legacy_link(r["evidence"])} - claimed_inputs = defaultdict(set) - for msg, alias, turn, owner in con.execute( - "SELECT s.native_id,s.alias_id,s.turn_id,a.task_id FROM assignments a " - "JOIN user_messages s ON a.user_message_id=s.native_id WHERE s.session_key=?", (key,)): - for identity in (msg, alias, turn): - if identity: + _session_ownership(con, key, task_id, by_run, reference_conflict, result, members, conflicts) + + if runs or deliveries or session_runs: + result.native = {"version": 1, "task_id": task_id, "runs": runs, "deliveries": deliveries, + "membership": members, "sessions": session_runs, "conflicting_responses": sorted(conflicts), + "conflicting_reference_kinds": reference_conflict} + return result + + +def _session_ownership(con, key, task_id, by_run, reference_conflict, result, members, conflicts): + from . import native_response + + by_input = defaultdict(set) + for run, native_id, turn, segment, validation in con.execute( + "SELECT run_id,native_id,provider_turn_id,segment_id,validation FROM t3_purpose_inputs " + "WHERE session_key=?", (key,)): + by_input[native_id].add((run, turn, segment, validation)) + whole = {r["task_id"] for r in con.execute( + "SELECT task_id, evidence FROM session_assignments WHERE session_key=?", (key,)) + if not legacy_link(r["evidence"])} + harness = key.partition(":")[0] + claimed_turns = defaultdict(set) + claimed_inputs = defaultdict(set) + input_turns = defaultdict(set) + for msg, alias, turn, owner in con.execute( + "SELECT s.native_id,s.alias_id,s.turn_id,a.task_id FROM user_messages s " + "LEFT JOIN assignments a ON a.user_message_id=s.native_id WHERE s.session_key=? AND s.is_genuine=1", + (key,)): + if owner and turn: + claimed_turns[turn].add(owner) + # Claude and OpenCode identify inputs by message, Codex by turn. + for identity in ((msg, alias, turn) if harness == "codex" else (msg, alias)): + if identity: + if owner: claimed_inputs[identity].add(owner) - harness = key.partition(":")[0] - call_witnesses = set() - if harness == "grok": - from .adapters import grok - responses, call_witnesses = grok.response_witnesses(con, key) - else: - responses = native_response.inputs(con, key) - for rid, input_ids in responses.items(): - candidates = {run for identity in input_ids for run in by_input.get(identity, ())} - if not candidates: - continue - if len(input_ids) != 1 or len(candidates) != 1: - conflicts.add(rid) - continue - run, turn, segment, validation = next(iter(candidates)) - owner = by_run.get(run) - native_id = next(iter(input_ids)) - assignment_id = f"{key}:{native_id}" if harness == "grok" else f"{harness}:{native_id}" - claims = whole | claimed_inputs.get(assignment_id, set()) - if (reference_conflict and owner == task_id) or (claims and claims != {owner}): - conflicts.add(rid) - continue - ownership[rid] = owner - if owner == task_id: - if rid in call_witnesses: - validation = "grok_tool_call" - members[rid] = {"run_id": run, "session_key": key, "native_input_id": native_id, - "provider_turn_id": turn, "segment_id": segment, "validation": validation} - if harness == "codex": - turn_keys.add((key, "codex:" + native_id)) - elif harness == "grok": - turn_keys.add((key, rid)) - - return ({"version": 1, "task_id": task_id, "runs": runs, "deliveries": deliveries, - "membership": members, "sessions": session_runs, "conflicting_responses": sorted(conflicts), - "conflicting_reference_kinds": reference_conflict}, - ownership, turn_keys) + if turn: + input_turns[identity].add(turn) + call_witnesses = set() + if harness == "grok": + from .adapters import grok + responses, call_witnesses = grok.response_witnesses(con, key) + else: + responses = native_response.inputs(con, key) + # In a contested whole session, only events on resolved turns can be + # shown. Untagged events cannot be separated between the claimants. + exclusive = whole == {task_id} and set(by_run.values()) == {task_id} + prefix = key if harness == "grok" else harness + blocked_turns = set() + for native_id, candidates in by_input.items(): + identity = f"{prefix}:{native_id}" + input_owners = {by_run.get(entry[0]) for entry in candidates} + claims = whole | claimed_inputs[identity] + if (len(candidates) > 1 or input_owners != {task_id} + or claims - {task_id} or reference_conflict): + blocked_turns.update(input_turns[identity]) + if harness == "codex": + blocked_turns.add(identity) + exclusive = False + for rid, display_turn in con.execute( + "SELECT response_id,turn_id FROM responses WHERE session_key=? AND is_overlap=0", (key,)): + input_ids = responses.get(rid, set()) + identities = {f"{prefix}:{identity}" for identity in input_ids} + candidates = {candidate for identity in input_ids for candidate in by_input.get(identity, ())} + claims = whole.copy() + for identity in identities: + claims.update(claimed_inputs[identity]) + if not identities: + claims.update(claimed_turns[display_turn]) + if len(identities) > 1 and not candidates and claims - whole: + # Competing input witnesses cannot prove a captured turn. + conflicts.add(rid) + for identity in identities: + blocked_turns.update(input_turns[identity]) + exclusive = False + continue + if not candidates: + result.owners[rid] = claims + if task_id in claims: + turns = {t for identity in identities for t in input_turns[identity]} + if not turns and display_turn: + turns.add(display_turn) + result.turns.update((key, t) for t in turns) + if harness == "claude": + result.claude_capture_turns[rid] = turns + continue + + run, turn, segment, validation = next(iter(candidates)) + owner = by_run.get(run) + disputed = (len(input_ids) != 1 or len(candidates) != 1 + or (reference_conflict and owner == task_id) + or (claims and claims != {owner})) + if disputed or owner != task_id: + for identity in identities: + blocked_turns.update(input_turns[identity]) + if harness == "codex": + blocked_turns.update(identities) + elif harness == "grok": + blocked_turns.add(rid) + elif harness == "claude": + # Even a tool from this response can carry another prompt's + # display turn. Keep only literal events on that mixed turn. + blocked_turns.add(display_turn) + if disputed: + conflicts.add(rid) + exclusive = False + continue + result.owners[rid] = {owner} if owner else set() + if owner == task_id: + native_id, = input_ids + if rid in call_witnesses: + validation = "grok_tool_call" + members[rid] = {"run_id": run, "session_key": key, "native_input_id": native_id, + "provider_turn_id": turn, "segment_id": segment, "validation": validation} + if harness == "codex": + result.turns.add((key, "codex:" + native_id)) + elif harness == "grok": + result.turns.add((key, rid)) + if not exclusive: + result.whole.discard(key) + result.turns.difference_update((key, turn) for turn in blocked_turns) def _normalized_counters(row): diff --git a/agent_observer/report.py b/agent_observer/report.py index d517c7b..3fd7e99 100644 --- a/agent_observer/report.py +++ b/agent_observer/report.py @@ -271,13 +271,9 @@ def _snapshot_id(payload: dict) -> str: return hashlib.sha256(canonical.encode("utf-8")).hexdigest() -def _task_turn_ids(con: sqlite3.Connection, task_id: str, - turn_sub: dict, whole: dict) -> set: - """Turns owned by the task: bound submission turns plus whole sessions.""" - bound = {a["user_message_id"] for a in con.execute( - "SELECT user_message_id FROM assignments WHERE task_id=?", - (task_id,))} - owned = {t for t, s in turn_sub.items() if s in bound} +def _task_turn_ids(con: sqlite3.Connection, turns: set, whole: set) -> set: + """Turn IDs for diagnostics, including turns in wholly owned sessions.""" + owned = {turn for _, turn in turns} whole_keys = sorted(whole) if whole_keys: placeholders = ",".join("?" * len(whole_keys)) @@ -295,7 +291,7 @@ def _task_turn_ids(con: sqlite3.Connection, task_id: str, def _task_diagnostics(con: sqlite3.Connection, scope_keys: set, - whole: dict, task_turns: set) -> dict: + whole: set, task_turns: set) -> dict: """Task-scoped diagnostics and time, with session context labeled. Incidents whose evidence resolves only to task-owned turns are @@ -432,7 +428,8 @@ def phase(value): by_session.setdefault(a["session_key"], set()).add(phase(a.get("stage"))) def selected(row): - if row["session_key"] in native_sessions and (row["session_key"], row["turn_id"]) not in native_turns: + if (row["session_key"] in native_sessions and row["session_key"] not in whole + and (row["session_key"], row["turn_id"]) not in native_turns): return "unclassified" labels = by_turn.get(row["turn_id"]) or by_session.get(row["session_key"]) or {"unclassified"} return next(iter(labels)) if len(labels) == 1 else "mixed" @@ -448,7 +445,7 @@ def selected(row): harness = _session_harness(con, key) for event in con.execute("SELECT * FROM events WHERE session_key=?", (key,)): if key in native_sessions: - owned = (key, event["turn_id"]) in native_turns + owned = key in whole or (key, event["turn_id"]) in native_turns else: owned = key in whole or event["turn_id"] in turns label = selected(event) if owned else "session context" @@ -527,14 +524,10 @@ def task_report(con: sqlite3.Connection, task_id: str, whole = {r["session_key"]: r["evidence"] for r in con.execute( "SELECT session_key, evidence FROM session_assignments WHERE task_id=?", (task_id,))} - native = None - purpose_owners = {} - native_turns = set() - canonical = outcome.active(con, task_id) - if canonical or (_has_table(con, "t3_purpose_sessions") and any( - con.execute("SELECT 1 FROM t3_purpose_sessions WHERE session_key=? LIMIT 1", - (key,)).fetchone() for key in scope_keys)): - native, purpose_owners, native_turns = outcome.evidence(con, task_id, scope_keys) + ownership = outcome.evidence(con, task_id, scope_keys) + native = ownership.native + canonical = bool(native and native["runs"]) + if native: whole = {k: v for k, v in whole.items() if not outcome.legacy_link(v) or (not canonical and k not in native["sessions"])} legacy_links = {key for key, ev in whole.items() if outcome.legacy_link(ev)} @@ -564,16 +557,16 @@ def task_report(con: sqlite3.Connection, task_id: str, continue key, rid = r["session_key"], r["response_id"] if native and key in native["sessions"]: - owner = purpose_owners.get(rid) - if rid in conflicts: + owners = ownership.owners.get(rid) + if rid in conflicts or not owners: unplaced.append(dict(r)) - continue - if owner == task_id: + elif task_id not in owners: + elsewhere.append(dict(r)) + elif len(owners) > 1: + shared.append(dict(r)) + else: attributed.append(dict(r)) - continue - if rid in purpose_owners or canonical or (key not in whole and not bound_subs): - (elsewhere if owner else unplaced).append(dict(r)) - continue + continue if r["session_key"] in whole: placed = placements.get(r["session_key"]) if placed is not None: @@ -683,18 +676,17 @@ def child_session(identity): unmeasured_attributed.add(key) elif subs: unmeasured_shared.add(key) - inventory_gaps = outcome.check_inventory(con, native, attributed) if canonical else False + has_purpose = native and (canonical or native["deliveries"]) + inventory_gaps = outcome.check_inventory(con, native, attributed) if has_purpose else False unavailable_usage = bool(unbound_usage or conflicts or inventory_gaps or legacy_links or not scope_keys or missing_sessions or empty_sessions or unbound_children or unbound_delegations or whole_conflicts) cutoff = _source_cutoff(con, scope_keys) - explicit_whole = {k: ev for k, ev in whole.items() if k not in legacy_links} - task_turns = _task_turn_ids(con, task_id, turn_sub, explicit_whole) - task_turns.update(turn for _, turn in native_turns) - diagnostics = _task_diagnostics(con, scope_keys, explicit_whole, task_turns) + task_turns = _task_turn_ids(con, ownership.turns, ownership.whole) + diagnostics = _task_diagnostics(con, scope_keys, ownership.whole, task_turns) phases, activity_context, activity_context_coverage = _phase_report( - con, task_id, attributed, set(explicit_whole)-whole_shared, task_turn_rows, schedule, - unmeasured_attributed, native["sessions"] if native else (), native_turns) + con, task_id, attributed, ownership.whole - whole_shared, task_turn_rows, schedule, + unmeasured_attributed, native["sessions"] if native else (), ownership.turns) def _resp_tuple(r) -> list: return [r.get("response_id"), r.get("harness"), r.get("model"), @@ -825,6 +817,7 @@ def _resp_tuple(r) -> list: }, "native_cost": native_cost, "native_cost_shared": _native_cost(shared), + "native_cost_billed_shared": _native_cost(billed_shared), "estimated_cost": estimated, "estimated_cost_shared": shared_estimated, "subscription_note": "Router quota readings are account evidence, " @@ -906,7 +899,7 @@ def _resp_tuple(r) -> list: report["coverage"]["unavailable_sources"] = unavailable_sources report["total_cost"] = _total_cost( con, task_id, total_estimated, attributed, billed_shared, joint, whole) - if canonical and inventory_gaps and total_estimated.get("priced_responses"): + if inventory_gaps and total_estimated.get("priced_responses"): subtotal = total_estimated["estimated_cost_usd_partial"] amount = "under $0.01" if 0 < subtotal < 0.005 else f"${subtotal:,.2f}" report["total_cost"].update(usd=None, observed_subtotal_usd=subtotal, @@ -985,33 +978,27 @@ def _total_cost(con, task_id, estimate, attributed, shared, joint, def timeline(con: sqlite3.Connection, task_id: str | None = None, turn_id: str | None = None, family: str | None = None, limit: int = 200, session_key: str | None = None) -> dict: - turn_sub = _turn_submission(con) - task_turns: set[str] | None = None - if task_id is not None: - bound = {a["user_message_id"] for a in con.execute( - "SELECT user_message_id FROM assignments WHERE task_id=?", - (task_id,))} - task_turns = {t for t, s in turn_sub.items() if s in bound} q = "SELECT * FROM events WHERE 1=1" args: list = [] if session_key: q += " AND session_key=?" args.append(session_key) - if turn_id: - q += " AND turn_id=?" - args.append(turn_id) + literal_events = set() trace_scope = {} - if task_turns is not None: - canonical = outcome.active(con, task_id) - native_turns = set() - claude_event_ids = [] - if canonical: - native, _, native_turns = outcome.evidence(con, task_id, outcome.sessions(con, task_id)) + if task_id is not None: + ownership = outcome.evidence(con, task_id, task_sessions(con, task_id)) + native = ownership.native + excluded_events = set() + if native: matches = {rid: member for rid, member in native["membership"].items() if (not session_key or member["session_key"] == session_key) and (not turn_id or turn_id == (rid if member["session_key"].startswith("grok:") else member["session_key"].partition(":")[0] + ":" + member["native_input_id"]))} - for key in sorted({m["session_key"] for m in matches.values() if m["session_key"].startswith("claude:")}): + conflicts = set(native["conflicting_responses"]) + for key in native["sessions"]: + if (not key.startswith("claude:") or (session_key and key != session_key) + or not _has_table(con, "claude_response_ancestry")): + continue # Claude gives each text event the transcript UUID and block # index. Its parent chain proves the response independently of # the display turn that may have been retouched. @@ -1020,38 +1007,44 @@ def timeline(con: sqlite3.Connection, task_id: str | None = None, "ON e.source_id=a.source_id AND e.session_key=a.session_key " "AND a.uuid=substr(e.native_id,1,instr(e.native_id,':')-1) " "WHERE e.session_key=? AND e.family='assistant_message'", (key,)): - if rid in matches: - claude_event_ids.append(event_id) - trace_scope = {"native_response_count": len(matches), - "native_responses": {rid: matches[rid] for rid in sorted(matches)[:limit]}} - # Display turns can be retouched after import. Use only native - # session/turn pairs in an exact outcome timeline. - task_turns.clear() - whole = [] if canonical else sorted(r["session_key"] for r in con.execute( - "SELECT session_key FROM session_assignments WHERE task_id=? AND evidence<>'t3' AND evidence NOT LIKE 't3:%'", - (task_id,))) - if not task_turns and not whole and not native_turns and not claude_event_ids: + capture_turns = ownership.claude_capture_turns.get(rid) + if rid in matches or (capture_turns is not None and (not turn_id or turn_id in capture_turns)): + literal_events.add(event_id) + elif (capture_turns is not None or rid in native["membership"] or rid in conflicts + or (rid in ownership.owners and task_id not in ownership.owners[rid])): + excluded_events.add(event_id) + if native["runs"]: + trace_scope = {"native_response_count": len(matches), + "native_responses": {rid: matches[rid] for rid in sorted(matches)[:limit]}} + if not ownership.turns and not ownership.whole and not literal_events: return {**trace_scope, "events": [], "returned": 0, "total": 0, "truncated": False, "note": "no bound turns; timeline empty", "join": {"calls": 0, "results": 0, "joined_call_ids": [], "unmatched_results": [], "unanswered_calls": []}} clauses = [] - if claude_event_ids: + if excluded_events: + q += " AND id NOT IN (SELECT value FROM json_each(?))" + args.append(json.dumps(sorted(excluded_events))) + if literal_events: clauses.append("id IN (SELECT value FROM json_each(?))") - args.append(json.dumps(claude_event_ids)) - if native_turns: - pairs = sorted(native_turns) + args.append(json.dumps(sorted(literal_events))) + if ownership.turns: + pairs = sorted(ownership.turns) clauses.append("(session_key, turn_id) IN (VALUES " + ",".join(["(?,?)"] * len(pairs)) + ")") for pair in pairs: args.extend(pair) - if task_turns: - clauses.append(f"turn_id IN ({','.join('?' * len(task_turns))})") - args.extend(sorted(task_turns)) - if whole: - clauses.append(f"session_key IN ({','.join('?' * len(whole))})") - args.extend(whole) + if ownership.whole: + clauses.append(f"session_key IN ({','.join('?' * len(ownership.whole))})") + args.extend(sorted(ownership.whole)) q += " AND (" + " OR ".join(clauses) + ")" + if turn_id: + if literal_events: + q += " AND (turn_id=? OR id IN (SELECT value FROM json_each(?)))" + args.extend((turn_id, json.dumps(sorted(literal_events)))) + else: + q += " AND turn_id=?" + args.append(turn_id) if family: q += " AND family=?" args.append(family) diff --git a/tests/test_outcome.py b/tests/test_outcome.py index ed08526..d25ffef 100644 --- a/tests/test_outcome.py +++ b/tests/test_outcome.py @@ -111,3 +111,120 @@ def test_delivery_survives_missing_run_with_unknown_cost(self): self.assertEqual(rep["native_purpose"]["deliveries"][0]["number"], 42) self.assertIn("purpose_run_unavailable", rep["native_purpose"]["coverage_gaps"]) self.assertIsNone(rep["total_cost"]["usd"]) + + def assign(self, task, prompt): + self.con.execute("INSERT INTO assignments(user_message_id,task_id,created_at)" + " VALUES(?,?,0)", ("codex:msg-mini-sub-" + prompt, task)) + + def test_capture_alongside_native_turn(self): + self.assign(self.task, "02") + rep = report.task_report(self.con, self.task) + self.assertEqual(rep["measured"]["attributed_responses"], + ["codex:resp-mini-001", "codex:resp-mini-002", "codex:resp-mini-003"]) + self.assertNotIn("codex:resp-mini-003", rep["native_purpose"]["membership"]) + trace = report.timeline(self.con, self.task, turn_id="codex:turn-mini-bbb") + self.assertEqual({e["native_id"] for e in trace["events"]}, + {"call-mini-spawn-01", "task_complete:turn-mini-bbb"}) + self.assertEqual(trace["native_response_count"], 0) + self.assertTrue(rep["reconciles"]) + + def test_conflicting_capture_without_native_run(self): + other = "example/repo#12" + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (other,)) + self.assign(other, "01") + self.assign(other, "02") + for task in (other, self.task): + rep = report.task_report(self.con, task) + self.assertEqual(rep["measured"]["unplaced_responses"], + ["codex:resp-mini-001", "codex:resp-mini-002"]) + self.assertTrue(rep["reconciles"]) + trace = report.timeline(self.con, task) + if task == other: + self.assertEqual(rep["measured"]["attributed_responses"], ["codex:resp-mini-003"]) + self.assertEqual({e["native_id"] for e in trace["events"]}, + {"call-mini-spawn-01", "task_complete:turn-mini-bbb"}) + else: + self.assertEqual(rep["measured"]["other_task_responses"], ["codex:resp-mini-003"]) + self.assertFalse(trace["events"]) + + def test_router_whole_session_conflict_only_exposes_uncontested_turn(self): + other = "router-job" + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (other,)) + self.con.execute("INSERT INTO session_assignments VALUES(?,?,'router:job',0)", (self.session, other)) + for task in (other, self.task): + rep = report.task_report(self.con, task) + self.assertEqual(rep["measured"]["unplaced_responses"], + ["codex:resp-mini-001", "codex:resp-mini-002"]) + self.assertTrue(rep["reconciles"]) + trace = report.timeline(self.con, task) + if task == other: + self.assertEqual(rep["measured"]["attributed_responses"], ["codex:resp-mini-003"]) + self.assertEqual({e["native_id"] for e in trace["events"]}, + {"call-mini-spawn-01", "task_complete:turn-mini-bbb"}) + else: + self.assertFalse(trace["events"]) + + def test_compatible_router_binding_keeps_whole_session_events(self): + self.con.execute("INSERT INTO session_assignments VALUES(?,?,'router:job',0)", (self.session, self.task)) + self.con.execute("INSERT INTO events(session_key,turn_id,native_id,family) " + "VALUES('codex:unrelated','codex:turn-mini-aaa','foreign-call','tool_call')") + rep = report.task_report(self.con, self.task) + self.assertEqual(rep["attributed"]["responses"], 3) + task_trace = report.timeline(self.con, self.task) + session_trace = report.timeline(self.con, session_key=self.session) + self.assertEqual([e["id"] for e in task_trace["events"]], [e["id"] for e in session_trace["events"]]) + self.assertEqual(task_trace["native_response_count"], 2) + + def test_claude_display_turn_cannot_override_native_ancestry_in_capture_trace(self): + from pathlib import Path + from agent_observer.adapters import claude + from tests.test_native_response import claude_response, claude_user, write_records + + path = Path(self.tmp.name, "s.jsonl") + answers = [claude_response("answer-a", "a", "first"), claude_response("answer-b", "b", "second")] + for answer in answers: + answer["message"]["content"] = [{"type": "text", "text": "answer"}] + answers[0]["message"]["content"].append({"type": "tool_use", "id": "foreign-call", "name": "Read"}) + # Both assistant events carry the latest display turn, but their parents differ. + write_records(path, [claude_user("a"), claude_user("b"), *answers]) + claude.import_claude_file(self.con, str(path)) + self.con.execute("INSERT INTO t3_purpose_sessions VALUES('a','claude:s')") + self.con.execute("INSERT INTO t3_purpose_inputs(run_id,session_key,native_id,kind,validation)" + " VALUES('a','claude:s','a','message','claude_prompt_echo')") + other = "example/repo#12" + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (other,)) + self.con.execute("INSERT INTO assignments(user_message_id,task_id,created_at) VALUES('claude:b',?,0)", + (other,)) + for task, expected, excluded in ((self.task, "first", "second"), (other, "second", "first")): + rep = report.task_report(self.con, task) + self.assertIn("claude:" + expected, rep["measured"]["attributed_responses"]) + self.assertIn("claude:" + excluded, rep["measured"]["other_task_responses"]) + trace = report.timeline(self.con, task, session_key="claude:s", family="assistant_message") + self.assertEqual([e["native_id"] for e in trace["events"]], + ["answer-a:0" if task == self.task else "answer-b:0"]) + selected = report.timeline(self.con, task, session_key="claude:s", + turn_id="claude:a" if task == self.task else "claude:b") + self.assertEqual([e["native_id"] for e in selected["events"]], + ["answer-a:0" if task == self.task else "answer-b:0"]) + + def test_delivery_alone_preserves_legacy_placement_and_capture_trace(self): + from unittest.mock import patch + self.con.execute("DELETE FROM t3_purpose_runs") + other = "example/repo#12" + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (other,)) + self.con.executemany("INSERT INTO session_assignments VALUES(?,?,'t3',0)", + [(self.session, self.task), (self.session, other)]) + placed = {"codex:resp-mini-001": self.task, "codex:resp-mini-002": other} + with patch("agent_observer.placement.read_placements", return_value=placed): + before = report.task_report(self.con, self.task) + self.con.execute("INSERT INTO t3_purpose_deliveries VALUES(?, 'planner', 'github.com'," + "'example/repo',42,'https://github.com/example/repo/pull/42','now')", (self.task,)) + after = report.task_report(self.con, self.task) + self.assertEqual(before["measured"]["attributed_responses"], ["codex:resp-mini-001"]) + self.assertEqual(after["measured"], before["measured"]) + self.assertIn("purpose_run_unavailable", after["native_purpose"]["coverage_gaps"]) + self.assign(self.task, "02") + trace = report.timeline(self.con, self.task) + self.assertEqual({e["native_id"] for e in trace["events"]}, + {"call-mini-spawn-01", "task_complete:turn-mini-bbb"}) + self.assertNotIn("native_response_count", trace) From 90098ec16bc887e5dcd617277eb299907a3debc7 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:23:59 +0100 Subject: [PATCH 14/44] wip: expose conflicting native run snapshots in outcome reports --- agent_observer/adapters/t3_purpose.py | 1 + agent_observer/cli.py | 6 +++--- agent_observer/outcome.py | 11 +++++++++-- agent_observer/publish.py | 2 +- agent_observer/report.py | 2 +- tests/test_t3_purpose.py | 4 ++++ 6 files changed, 19 insertions(+), 7 deletions(-) diff --git a/agent_observer/adapters/t3_purpose.py b/agent_observer/adapters/t3_purpose.py index bb82165..47b39e6 100644 --- a/agent_observer/adapters/t3_purpose.py +++ b/agent_observer/adapters/t3_purpose.py @@ -756,6 +756,7 @@ def refresh(con, native, tables): """Replace one source and publish the consensus under the caller's savepoint.""" path = native.execute("PRAGMA database_list").fetchone()[2] _source_tables(con, path) + con.execute("CREATE INDEX IF NOT EXISTS t3_source_runs_task ON t3_source_runs(task_id,run_id)") snapshot = Snapshot(con, path) con.execute("CREATE INDEX IF NOT EXISTS t3_purpose_runs_task ON t3_purpose_runs(task_id)") con.execute("CREATE INDEX IF NOT EXISTS t3_purpose_inputs_native" diff --git a/agent_observer/cli.py b/agent_observer/cli.py index 1aa6ab4..aae0bc2 100644 --- a/agent_observer/cli.py +++ b/agent_observer/cli.py @@ -173,9 +173,9 @@ def _text(payload) -> str: f"session span {r.get('time', {}).get('session_span_s')} " f"({r.get('time', {}).get('session_span_label')})", ] - if r.get("native_purpose", {}).get("runs"): - native = r["native_purpose"] - lines.append(f" native purpose: {len(native['runs'])} runs; " + native = r.get("native_purpose") or {} + if native.get("runs") or native.get("deliveries") or native.get("conflicting_source_runs"): + lines.append(f" native purpose: {len(native['runs'])} runs, " f"{len(native['membership'])} joined responses") if native.get("coverage_gaps"): lines.append(" native coverage: " + ", ".join(native["coverage_gaps"])) diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index 86df212..18dcc33 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -53,6 +53,11 @@ def evidence(con, task_id, scope): "SELECT * FROM t3_purpose_runs WHERE task_id=? ORDER BY run_id", (task_id,))] deliveries = [dict(r) for r in con.execute( "SELECT * FROM t3_purpose_deliveries WHERE task_id=? ORDER BY declared_at, url, thread_id", (task_id,))] + disputed_runs = [] + if _has_table(con, "t3_source_runs"): + disputed_runs = [r[0] for r in con.execute( + "SELECT DISTINCT s.run_id FROM t3_source_runs s LEFT JOIN t3_purpose_runs r USING(run_id) " + "WHERE s.task_id=? AND r.run_id IS NULL ORDER BY s.run_id", (task_id,))] reference_conflict = len({r["kind"] for r in runs}) > 1 session_runs = {} members = {} @@ -66,10 +71,10 @@ def evidence(con, task_id, scope): session_runs[key] = sorted(by_run) _session_ownership(con, key, task_id, by_run, reference_conflict, result, members, conflicts) - if runs or deliveries or session_runs: + if runs or deliveries or session_runs or disputed_runs: result.native = {"version": 1, "task_id": task_id, "runs": runs, "deliveries": deliveries, "membership": members, "sessions": session_runs, "conflicting_responses": sorted(conflicts), - "conflicting_reference_kinds": reference_conflict} + "conflicting_reference_kinds": reference_conflict, "conflicting_source_runs": disputed_runs} return result @@ -257,6 +262,8 @@ def check_inventory(con, native, rows): "USING(response_id) WHERE r.session_key=?", (key,))) gaps = set() main_gaps = set() + if native["conflicting_source_runs"]: + main_gaps.add("conflicting_native_run_records") if not native["runs"]: main_gaps.add("purpose_run_unavailable") checks = [] diff --git a/agent_observer/publish.py b/agent_observer/publish.py index e430651..630bc92 100644 --- a/agent_observer/publish.py +++ b/agent_observer/publish.py @@ -434,7 +434,7 @@ def render(summary: dict, target: str | None = None) -> str: _counted(sessions, "session", "sessions"), wall] lines = [MARKER, f"### {title}", "", " · ".join(parts), ""] native = summary.get("native_purpose") or {} - if native.get("runs") or native.get("deliveries"): + if native.get("runs") or native.get("deliveries") or native.get("conflicting_source_runs"): lines.append(f"Outcome: {_safe_field(summary['task_id'])}.") if native.get("coverage_gaps"): lines.append("Full outcome cost unknown. Native coverage: " + diff --git a/agent_observer/report.py b/agent_observer/report.py index 3fd7e99..7c05487 100644 --- a/agent_observer/report.py +++ b/agent_observer/report.py @@ -676,7 +676,7 @@ def child_session(identity): unmeasured_attributed.add(key) elif subs: unmeasured_shared.add(key) - has_purpose = native and (canonical or native["deliveries"]) + has_purpose = native and (canonical or native["deliveries"] or native["conflicting_source_runs"]) inventory_gaps = outcome.check_inventory(con, native, attributed) if has_purpose else False unavailable_usage = bool(unbound_usage or conflicts or inventory_gaps or legacy_links or not scope_keys or missing_sessions or empty_sessions diff --git a/tests/test_t3_purpose.py b/tests/test_t3_purpose.py index 052821d..cb393ab 100644 --- a/tests/test_t3_purpose.py +++ b/tests/test_t3_purpose.py @@ -305,6 +305,10 @@ def credited(n): refresh_other() self.assertEqual(self.values("SELECT task_id FROM session_assignments WHERE session_key='codex:historic'"), []) self.assertEqual((credited(7), credited(8)), ([], [])) + for n in (7, 8): + native = report.task_report(self.con, f"example/project#{n}")["native_purpose"] + self.assertEqual(native["conflicting_source_runs"], ["a"]) + self.assertIn("conflicting_native_run_records", native["coverage_gaps"]) self.assertEqual(self.refresh()["failed"], []) self.assertEqual((credited(7), credited(8)), ([], [])) From 6ced7aa8927350d187f68ae7140b090c43200171 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:27:52 +0100 Subject: [PATCH 15/44] wip: withhold explicit credit when retained source identities disagree --- agent_observer/adapters/t3_purpose.py | 1 + agent_observer/outcome.py | 22 ++++++++++++++++++++-- tests/test_t3_purpose.py | 6 ++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/agent_observer/adapters/t3_purpose.py b/agent_observer/adapters/t3_purpose.py index 47b39e6..1f0313c 100644 --- a/agent_observer/adapters/t3_purpose.py +++ b/agent_observer/adapters/t3_purpose.py @@ -757,6 +757,7 @@ def refresh(con, native, tables): path = native.execute("PRAGMA database_list").fetchone()[2] _source_tables(con, path) con.execute("CREATE INDEX IF NOT EXISTS t3_source_runs_task ON t3_source_runs(task_id,run_id)") + con.execute("CREATE INDEX IF NOT EXISTS t3_source_inputs_session ON t3_source_inputs(session_key,native_id)") snapshot = Snapshot(con, path) con.execute("CREATE INDEX IF NOT EXISTS t3_purpose_runs_task ON t3_purpose_runs(task_id)") con.execute("CREATE INDEX IF NOT EXISTS t3_purpose_inputs_native" diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index 18dcc33..018d192 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -10,9 +10,14 @@ def sessions(con, task_id): if not _has_table(con, "t3_purpose_runs"): return set() - return {row[0] for row in con.execute( + keys = {row[0] for row in con.execute( "SELECT DISTINCT s.session_key FROM t3_purpose_sessions s " "JOIN t3_purpose_runs r USING(run_id) WHERE r.task_id=?", (task_id,))} + if _has_table(con, "t3_source_runs"): + keys.update(row[0] for row in con.execute( + "SELECT DISTINCT s.session_key FROM t3_source_runs r JOIN t3_purpose_sessions s USING(run_id) " + "WHERE r.task_id=?", (task_id,))) + return keys def active(con, task_id): @@ -66,6 +71,11 @@ def evidence(con, task_id, scope): by_run = dict(con.execute( "SELECT r.run_id, r.task_id FROM t3_purpose_sessions s " "JOIN t3_purpose_runs r USING(run_id) WHERE s.session_key=?", (key,))) + if _has_table(con, "t3_source_runs"): + for run, in con.execute( + "SELECT DISTINCT s.run_id FROM t3_purpose_sessions s JOIN t3_source_runs x USING(run_id) " + "LEFT JOIN t3_purpose_runs r USING(run_id) WHERE s.session_key=? AND r.run_id IS NULL", (key,)): + by_run[run] = None if not by_run: continue session_runs[key] = sorted(by_run) @@ -86,6 +96,14 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me "SELECT run_id,native_id,provider_turn_id,segment_id,validation FROM t3_purpose_inputs " "WHERE session_key=?", (key,)): by_input[native_id].add((run, turn, segment, validation)) + if _has_table(con, "t3_source_inputs"): + for native_id, in con.execute( + "SELECT DISTINCT s.native_id FROM t3_source_inputs s WHERE s.session_key=? " + "AND NOT EXISTS (SELECT 1 FROM t3_purpose_inputs i " + "WHERE i.session_key=s.session_key AND i.native_id=s.native_id)", (key,)): + # A rejected identity still contradicts explicit or whole-session + # credit. Carry it through the same report and event filters. + by_input[native_id].add((None, None, None, "conflicting_snapshot")) whole = {r["task_id"] for r in con.execute( "SELECT task_id, evidence FROM session_assignments WHERE session_key=?", (key,)) if not legacy_link(r["evidence"])} @@ -157,7 +175,7 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me run, turn, segment, validation = next(iter(candidates)) owner = by_run.get(run) - disputed = (len(input_ids) != 1 or len(candidates) != 1 + disputed = (validation == "conflicting_snapshot" or len(input_ids) != 1 or len(candidates) != 1 or (reference_conflict and owner == task_id) or (claims and claims != {owner})) if disputed or owner != task_id: diff --git a/tests/test_t3_purpose.py b/tests/test_t3_purpose.py index cb393ab..b521ece 100644 --- a/tests/test_t3_purpose.py +++ b/tests/test_t3_purpose.py @@ -312,6 +312,12 @@ def credited(n): self.assertEqual(self.refresh()["failed"], []) self.assertEqual((credited(7), credited(8)), ([], [])) + self.con.execute("INSERT INTO assignments(user_message_id,task_id,created_at) " + "SELECT native_id,'example/project#7',0 FROM user_messages WHERE turn_id='codex:turn-mini-aaa'") + disputed = report.task_report(self.con, "example/project#7") + self.assertEqual(disputed["native_purpose"]["conflicting_responses"], expected) + self.assertEqual(credited(7), []) + self.assertFalse(report.timeline(self.con, "example/project#7", turn_id="codex:turn-mini-aaa")["events"]) other.execute(f"DELETE FROM {PREFIX}runs WHERE run_id='a'") refresh_other() self.assertEqual((credited(7), credited(8)), (expected, [])) From 673286b6be1b22c5062234af979e1c9c55c6708d Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:31:57 +0100 Subject: [PATCH 16/44] wip: withhold private forge coordinates from published task labels --- agent_observer/publish.py | 14 ++++++++++++-- tests/test_publish.py | 5 +++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/agent_observer/publish.py b/agent_observer/publish.py index 630bc92..c469f69 100644 --- a/agent_observer/publish.py +++ b/agent_observer/publish.py @@ -102,6 +102,15 @@ def _safe_ref(value) -> str | None: return None +def _task_label(task_id): + """GitHub outcome IDs use owner/repo#number. Other forges include their host.""" + if isinstance(task_id, str): + repository, _, number = task_id.rpartition("#") + if number.isdecimal() and "/" in repository and not _REPO_RE.fullmatch(repository): + return "reference withheld" + return _safe_field(task_id) + + def _fmt(n) -> str: return "unknown" if n is None else f"{int(n):,}" @@ -434,8 +443,9 @@ def render(summary: dict, target: str | None = None) -> str: _counted(sessions, "session", "sessions"), wall] lines = [MARKER, f"### {title}", "", " · ".join(parts), ""] native = summary.get("native_purpose") or {} + task_label = _task_label(summary.get("task_id")) if native.get("runs") or native.get("deliveries") or native.get("conflicting_source_runs"): - lines.append(f"Outcome: {_safe_field(summary['task_id'])}.") + lines.append(f"Outcome: {task_label}.") if native.get("coverage_gaps"): lines.append("Full outcome cost unknown. Native coverage: " + ", ".join(_safe_field(g.replace("_", " ")) for g in native["coverage_gaps"]) + ".") @@ -465,7 +475,7 @@ def render(summary: dict, target: str | None = None) -> str: versions = ", ".join(_safe_field(v) for v in summary['agentsmd_versions']) or "unknown" if task: acceptance = summary.get("acceptance_state") or "unknown" - lines.append(f"- Task `{_safe_field(summary.get('task_id'))}`: outcome " + lines.append(f"- Task `{task_label}`: outcome " f"{_safe_field(acceptance)} (recorded acceptance only; a finished " f"process never implies it).") outcome = summary.get("outcome") or {} diff --git a/tests/test_publish.py b/tests/test_publish.py index 389c728..25575da 100644 --- a/tests/test_publish.py +++ b/tests/test_publish.py @@ -108,6 +108,11 @@ def test_delivery_reference_privacy_and_excluded_cost_in_a_task_publication(self self.assertIn("Delivery PR: https://github.com/org/repo/pull/12", body) self.assertIn("Harness-reported cost: none reported.", body) self.assertNotIn("$84", body) + summary["task_id"] = "internal.example/team/private-repo#11" + private = publish.render(summary) + self.assertNotIn("internal.example", private) + self.assertNotIn("private-repo", private) + self.assertIn("Outcome: reference withheld", private) def test_second_publish_edits_the_same_owned_comment(self): gh = PublishGh([]) From 4b3b7453e2d665d4a828db6df51c1a3a93ad5abd Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:35:31 +0100 Subject: [PATCH 17/44] wip: preserve explicit captures on legacy-linked sessions --- agent_observer/report.py | 120 +++++++++++++++++++-------------------- tests/test_outcome.py | 68 ++++++++++++++++++++++ 2 files changed, 125 insertions(+), 63 deletions(-) diff --git a/agent_observer/report.py b/agent_observer/report.py index 7c05487..c8a9d9f 100644 --- a/agent_observer/report.py +++ b/agent_observer/report.py @@ -2,6 +2,7 @@ from __future__ import annotations +from collections import defaultdict import hashlib import json import sqlite3 @@ -228,17 +229,16 @@ def task_sessions(con: sqlite3.Connection, task_id: str) -> set: def _turn_submission(con: sqlite3.Connection) -> dict: - """Map turn_id to the genuine submission that started it. + """Map each session and turn to the genuine submission that started it. One turn follows one genuine user submission; the mapping uses the submission turn_id recorded at import. Tool results and assistant rows never create submissions. """ mapping = {} - for s in con.execute( - "SELECT native_id, turn_id FROM user_messages WHERE is_genuine=1"): - if s["turn_id"] and s["turn_id"] not in mapping: - mapping[s["turn_id"]] = s["native_id"] + for key, turn, msg in con.execute( + "SELECT session_key,turn_id,native_id FROM user_messages WHERE is_genuine=1 AND turn_id IS NOT NULL"): + mapping.setdefault((key, turn), msg) return mapping @@ -531,26 +531,32 @@ def task_report(con: sqlite3.Connection, task_id: str, whole = {k: v for k, v in whole.items() if not outcome.legacy_link(v) or (not canonical and k not in native["sessions"])} legacy_links = {key for key, ev in whole.items() if outcome.legacy_link(ev)} - whole_shared = {r["session_key"] for r in con.execute( - "SELECT session_key FROM session_assignments GROUP BY session_key" - " HAVING COUNT(DISTINCT task_id) > 1")} - whole_conflicts = {r["session_key"] for r in con.execute( - "SELECT DISTINCT w.session_key FROM session_assignments w JOIN user_messages s" - " ON s.session_key=w.session_key JOIN assignments a ON a.user_message_id=s.native_id" - " WHERE a.task_id<>w.task_id") if r["session_key"] in scope_keys} - whole_shared |= whole_conflicts + session_owners = defaultdict(set) + linked_tasks = defaultdict(set) + for key, owner, evidence in con.execute("SELECT session_key,task_id,evidence FROM session_assignments"): + if key in scope_keys: + claims = linked_tasks if outcome.legacy_link(evidence) else session_owners + claims[key].add(owner) + prompt_owners = defaultdict(set) + assigned_anywhere = set() + for key, msg, owner in con.execute( + "SELECT s.session_key,s.native_id,a.task_id FROM assignments a " + "JOIN user_messages s ON s.native_id=a.user_message_id WHERE s.is_genuine=1"): + if key in scope_keys: + prompt_owners[key].add(owner) + assigned_anywhere.add(msg) + whole_conflicts = {key for key, owners in session_owners.items() + if prompt_owners[key] and len(owners | prompt_owners[key]) > 1} + whole_shared = whole_conflicts | {key for key, owners in session_owners.items() if len(owners) > 1} responses = _responses(con, scope_keys) attributed, shared, unassigned = [], [], [] - # A session shared by several PRs is split per response by the checkout - # its tool calls worked in (#43); None keeps whole-session sharing. - placements = {key: _place(con, key) for key in whole_shared & set(whole) - if key not in whole_conflicts and not canonical - and not (native and key in native["sessions"])} + # A legacy checkout can place the remainder after explicit ownership. + placements = {key: _place(con, key) for key in legacy_links + if len(linked_tasks[key]) > 1 and key not in session_owners} unplaced, elsewhere = [], [] missing_submissions = [] - assigned_anywhere = {r["user_message_id"] for r in - con.execute("SELECT user_message_id " - "FROM assignments").fetchall()} + sharing_tasks = set() + legacy_shared = set() conflicts = set(native["conflicting_responses"]) if native else set() for r in responses: if r["is_overlap"]: @@ -564,34 +570,42 @@ def task_report(con: sqlite3.Connection, task_id: str, elsewhere.append(dict(r)) elif len(owners) > 1: shared.append(dict(r)) + sharing_tasks.update(owners) else: attributed.append(dict(r)) continue - if r["session_key"] in whole: - placed = placements.get(r["session_key"]) - if placed is not None: - owner = placed.get(r["response_id"]) - (attributed if owner == task_id else - unplaced if owner is None else elsewhere).append(dict(r)) - continue - if key in whole_shared: + sub = turn_sub.get((key, r["turn_id"])) + if sub in bound_subs: + if sub in joint or key in whole_conflicts: shared.append(dict(r)) - elif key in legacy_links: - unplaced.append(dict(r)) + if sub in joint: + sharing_tasks.update(joint[sub]["tasks"]) + sharing_tasks.update(session_owners.get(key, ())) else: attributed.append(dict(r)) - continue - sub = turn_sub.get(r["turn_id"]) - if sub is None: - unassigned.append(dict(r)) - elif sub in bound_subs: - if sub in joint or r["session_key"] in whole_conflicts: + elif task_id in session_owners.get(key, ()): + # Keep the existing whole-session pool when several records bind + # the session and this response has no explicit capture. + if key in whole_shared or key in linked_tasks: shared.append(dict(r)) + sharing_tasks.update(session_owners[key] | prompt_owners[key] | linked_tasks.get(key, set())) else: attributed.append(dict(r)) + elif key in linked_tasks and (sub in assigned_anywhere or key in session_owners): + elsewhere.append(dict(r)) + elif key in legacy_links: + placed = placements.get(key) + if placed is not None: + owner = placed.get(rid) + (attributed if owner == task_id else unplaced if owner is None else elsewhere).append(dict(r)) + elif len(linked_tasks[key]) > 1 and not prompt_owners[key]: + shared.append(dict(r)) + legacy_shared.add(rid) + else: + unplaced.append(dict(r)) else: unassigned.append(dict(r)) - if sub not in assigned_anywhere and sub not in missing_submissions: + if sub is not None and sub not in assigned_anywhere and sub not in missing_submissions: missing_submissions.append(sub) # Sessions are known but nothing is bound: the scope holds measured @@ -672,7 +686,7 @@ def child_session(identity): subs = prompt_sessions.get(key, set()) if key in shared_owned: unmeasured_shared.add(key) - elif key in whole or any(s not in joint for s in subs): + elif key in ownership.whole or any(s not in joint for s in subs): unmeasured_attributed.add(key) elif subs: unmeasured_shared.add(key) @@ -744,7 +758,7 @@ def _resp_tuple(r) -> list: snapshot = _snapshot_id(snapshot_payload) estimated = _pricing.price_scope(attributed, schedule) shared_estimated = _pricing.price_scope(shared, schedule) - billed_shared = [] if canonical else [r for r in shared if r["session_key"] not in legacy_links] + billed_shared = [] if canonical else [r for r in shared if r["response_id"] not in legacy_shared] total_estimated = _pricing.price_scope(attributed + billed_shared, schedule) unplaced_estimated = _pricing.price_scope(unplaced, schedule) for estimate in (estimated, shared_estimated, total_estimated, unplaced_estimated): @@ -898,7 +912,7 @@ def _resp_tuple(r) -> list: report["coverage"]["unavailable_sessions"] = unavailable_sessions report["coverage"]["unavailable_sources"] = unavailable_sources report["total_cost"] = _total_cost( - con, task_id, total_estimated, attributed, billed_shared, joint, whole) + task_id, total_estimated, attributed, billed_shared, sharing_tasks) if inventory_gaps and total_estimated.get("priced_responses"): subtotal = total_estimated["estimated_cost_usd_partial"] amount = "under $0.01" if 0 < subtotal < 0.005 else f"${subtotal:,.2f}" @@ -931,33 +945,13 @@ def _money(estimate: dict) -> str: return prefix + text -def _total_cost(con, task_id, estimate, attributed, shared, joint, - whole) -> dict: +def _total_cost(task_id, estimate, attributed, shared, sharing_tasks) -> dict: """One total for the task's work: its own usage plus the whole shared pool. Shared usage is never divided, so every task drawing on a pool counts it whole: the total is right for one task, and sums across tasks overlap by the shared part. ``shared_with_tasks`` names those tasks. """ - turn_sub = _turn_submission(con) - others: set = set() - seen_sessions: set = set() - for r in shared: - key = r["session_key"] - if key not in seen_sessions: - # Whole-session owners, and prompt owners that conflict with them. - seen_sessions.add(key) - for row in con.execute( - "SELECT task_id FROM session_assignments WHERE session_key=?" - " UNION SELECT a.task_id FROM assignments a JOIN user_messages s" - " ON a.user_message_id=s.native_id WHERE s.session_key=?" - " AND ? IN (SELECT session_key FROM session_assignments)", - (key, key, key)): - others.add(row["task_id"]) - sub = turn_sub.get(r.get("turn_id")) - if key not in whole and sub in joint: - others.update(joint[sub]["tasks"]) - others.discard(task_id) # Nothing priced is unknown, even when missing usage marks the estimate # partial: an empty subtotal must never read as a numeric zero. status = estimate["status"] if estimate.get("priced_responses") else "unknown" @@ -969,7 +963,7 @@ def _total_cost(con, task_id, estimate, attributed, shared, joint, "status": status, "responses": len(attributed) + len(shared), "shared_responses": len(shared), - "shared_with_tasks": sorted(others), + "shared_with_tasks": sorted(sharing_tasks - {task_id}) if shared else [], "models": model_usage(attributed + shared), "estimate": estimate, } diff --git a/tests/test_outcome.py b/tests/test_outcome.py index d25ffef..b91e759 100644 --- a/tests/test_outcome.py +++ b/tests/test_outcome.py @@ -228,3 +228,71 @@ def test_delivery_alone_preserves_legacy_placement_and_capture_trace(self): self.assertEqual({e["native_id"] for e in trace["events"]}, {"call-mini-spawn-01", "task_complete:turn-mini-bbb"}) self.assertNotIn("native_response_count", trace) + + def test_legacy_navigation_preserves_captured_turn_in_every_view(self): + self.con.execute("DELETE FROM t3_purpose_runs") + other = "example/repo#12" + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (other,)) + self.assign(self.task, "01") + first = ["codex:resp-mini-001", "codex:resp-mini-002"] + self.con.execute("INSERT INTO session_assignments VALUES(?,?,'t3',0)", (self.session, self.task)) + mine = report.task_report(self.con, self.task) + self.assertEqual(mine["measured"]["attributed_responses"], first) + self.assertEqual(mine["measured"]["unplaced_responses"], ["codex:resp-mini-003"]) + self.assertEqual(mine["total_cost"]["responses"], 2) + self.assertEqual(report.timeline(self.con, self.task)["returned"], 2) + + self.con.execute("INSERT INTO session_assignments VALUES(?,?,'t3:thread',0)", (self.session, other)) + linked = report.task_report(self.con, other) + self.assertEqual(linked["measured"]["other_task_responses"], first) + self.assertEqual(linked["total_cost"]["responses"], 0) + self.assertFalse(report.timeline(self.con, other)["events"]) + self.assign(other, "02") + for task, owned, elsewhere, turn in ((self.task, first, ["codex:resp-mini-003"], "aaa"), + (other, ["codex:resp-mini-003"], first, "bbb")): + rep = report.task_report(self.con, task) + self.assertEqual(rep["measured"]["attributed_responses"], owned) + self.assertEqual(rep["measured"]["other_task_responses"], elsewhere) + self.assertFalse(rep["coverage"]["conflicting_sessions"]) + self.assertTrue(rep["reconciles"]) + self.assertEqual({e["turn_id"] for e in report.timeline(self.con, task)["events"]}, + {"codex:turn-mini-" + turn}) + + def test_legacy_links_do_not_join_or_hide_an_explicit_shared_pool(self): + self.con.execute("DELETE FROM t3_purpose_runs") + partner, observer = "example/repo#12", "example/repo#13" + for task in (partner, observer): + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (task,)) + for task in (self.task, partner): + self.assign(task, "01") + self.con.execute("UPDATE assignments SET shared=1") + self.con.execute("UPDATE responses SET cost_usd=CASE WHEN turn_id='codex:turn-mini-aaa' THEN 1 ELSE 100 END") + for task in (self.task, partner, observer): + self.con.execute("INSERT INTO session_assignments VALUES(?,?,'t3:planner',0)", (self.session, task)) + for task, peer in ((self.task, partner), (partner, self.task)): + rep = report.task_report(self.con, task) + self.assertEqual(rep["shared_joint"]["responses"], 2) + self.assertEqual(rep["total_cost"]["shared_responses"], 2) + self.assertEqual(rep["total_cost"]["shared_with_tasks"], [peer]) + self.assertEqual(rep["native_cost_billed_shared"]["total_usd"], 2) + self.assertEqual(report.timeline(self.con, task)["returned"], 2) + rep = report.task_report(self.con, observer) + self.assertEqual(rep["total_cost"]["responses"], 0) + self.assertEqual(rep["measured"]["other_task_responses"], ["codex:resp-mini-001", "codex:resp-mini-002"]) + self.assertFalse(report.timeline(self.con, observer)["events"]) + self.assertEqual(rep["native_cost_billed_shared"]["total_usd"], 0) + + def test_linked_session_reusing_a_captured_turn_id_stays_unplaced(self): + self.con.execute("DELETE FROM t3_purpose_runs") + self.assign(self.task, "01") + key = "codex:other-session" + self.con.execute("INSERT INTO session_assignments VALUES(?,?,'t3',0)", (key, self.task)) + self.con.execute("INSERT INTO responses(response_id,source_id,session_key,turn_id)" + " SELECT 'foreign-response',source_id,?,turn_id FROM responses WHERE response_id=?", + (key, "codex:resp-mini-001")) + self.con.execute("INSERT INTO events(session_key,turn_id,native_id,family)" + " VALUES(?,'codex:turn-mini-aaa','foreign-event','tool_call')", (key,)) + rep = report.task_report(self.con, self.task) + self.assertEqual(rep["measured"]["unplaced_responses"], ["foreign-response"]) + self.assertEqual(rep["total_cost"]["responses"], 2) + self.assertFalse(report.timeline(self.con, self.task, session_key=key)["events"]) From f212fa7384bebb3744908654087960625d2cc6dd Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:37:48 +0100 Subject: [PATCH 18/44] wip: observe checkouts when native events first import --- agent_observer/adapters/claude.py | 10 +- agent_observer/adapters/codex.py | 10 +- agent_observer/cli.py | 5 +- agent_observer/ingest.py | 22 +++- agent_observer/placement.py | 112 ++++++++---------- tests/test_codex_fork.py | 10 +- tests/test_placement.py | 189 ++++++++++++++++++++---------- 7 files changed, 222 insertions(+), 136 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index c749f88..f4c84b2 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -19,7 +19,7 @@ import sqlite3 from collections import defaultdict, deque -from .. import db, native_response, privacy, intervention_evidence +from .. import db, intervention_evidence, native_response, placement, privacy from ..identity import SessionIdentity, skill_from_path from ..ingest import (JsonlSource, MissingNativeId, fingerprint, insert_event, iso_ts, text_hash) @@ -302,6 +302,8 @@ def __init__(self, con, src: JsonlSource, stats: dict): self.con = con self.src = src self.stats = stats + self.first_new_ordinal = src.first_new_ordinal() + self.checkout_events = [] self.native_session = src.row["session_id"] self.agent_id = src.row["thread_id"] self.identity = SessionIdentity() @@ -329,7 +331,10 @@ def event(self, family, native_id, ordinal, ts, **kw): insert_event(self.con, self.stats, source_id=self.src.source_id, session_key=self.session_key, family=family, native_id=native_id, ordinal=ordinal, ts=ts, - turn_id=self.turn, update=self.src.privacy_stale, **kw) + turn_id=self.turn, update=self.src.privacy_stale, + checkout_events=self.checkout_events + if self.first_new_ordinal is not None + and ordinal >= self.first_new_ordinal else None, **kw) def import_claude_file(con: sqlite3.Connection, path: str, @@ -446,6 +451,7 @@ def import_claude_file(con: sqlite3.Connection, path: str, (_IMPORT_VERSION, src.end_offset, src.source_id)) stats["session_key"] = r.session_key con.commit() + placement.observe_new_checkouts(con, r.checkout_events) return stats diff --git a/agent_observer/adapters/codex.py b/agent_observer/adapters/codex.py index e46dd04..2d80e6f 100644 --- a/agent_observer/adapters/codex.py +++ b/agent_observer/adapters/codex.py @@ -18,7 +18,7 @@ import os import sqlite3 -from .. import db, native_response, privacy +from .. import db, native_response, placement, privacy from ..identity import SessionIdentity, skill_from_path from ..ingest import (JsonlSource, MissingNativeId, fingerprint, insert_event, iso_ts, stored_path, text_hash) @@ -371,6 +371,8 @@ def __init__(self, con: sqlite3.Connection, src: JsonlSource, stats: dict): self.con = con self.src = src self.stats = stats + self.first_new_ordinal = src.first_new_ordinal() + self.checkout_events = [] self.session_id = src.row["session_id"] self.thread_id = src.row["thread_id"] self.thread_source = src.row["thread_source"] @@ -482,7 +484,10 @@ def event(self, obj, family, native_id, *, legacy_id=None, **kw): native_id=native_id, ordinal=self.record_position, ts=iso_ts(obj.get("timestamp")), update=self.src.privacy_stale and same_source, - migrate_ordinal=first and same_source, **kw) + migrate_ordinal=first and same_source, + checkout_events=self.checkout_events + if self.first_new_ordinal is not None + and self.record_position >= self.first_new_ordinal else None, **kw) event_id = prior["id"] if prior is not None else None if event_id is None: stored = self.con.execute( @@ -971,6 +976,7 @@ def import_codex_file(con: sqlite3.Connection, path: str, stats["moved_rows_with"] = sorted(settle) stats["session_key"] = reader.session_key con.commit() + placement.observe_new_checkouts(con, reader.checkout_events) return stats diff --git a/agent_observer/cli.py b/agent_observer/cli.py index aae0bc2..cf44a8d 100644 --- a/agent_observer/cli.py +++ b/agent_observer/cli.py @@ -1074,9 +1074,8 @@ def _sync(con, ns) -> int: row[key] = (row.get(key) or 0) + value elif key not in row: row[key] = value - # Placement runs once, after every harness import and the T3 refresh, - # so sessions imported later in this run are visible (#80). The refresh - # merge must not add shared_sessions a second time. + # Count shared sessions after the T3 refresh. Native adapters record + # checkout evidence as they import events, regardless of link order. if "t3" in wanted: for row in results: if row.get("harness") == "t3" and "skipped" not in row: diff --git a/agent_observer/ingest.py b/agent_observer/ingest.py index a6eb05d..fa7af8e 100644 --- a/agent_observer/ingest.py +++ b/agent_observer/ingest.py @@ -27,6 +27,7 @@ from . import privacy from .command_status import pending_pr_checks from .db import now +from .placement import CHECKOUT_EVENT_FAMILIES TAIL_BYTES = 4096 @@ -93,6 +94,7 @@ def __init__(self, con: sqlite3.Connection, harness: str, path: str, "SELECT * FROM sources WHERE harness=? AND path=?", (harness, path)).fetchone() self.row = row + self.new_source = row is None self.start_offset = 0 self.unchanged = False stored_version = (row["privacy_version"] @@ -215,6 +217,22 @@ def recheck_unchanged(self) -> bool: def incremental(self) -> bool: return self.start_offset > 0 + def first_new_ordinal(self) -> int | None: + """First record eligible for live evidence, even during a parser replay.""" + if self.new_source: + return 0 + offset = self.start_offset + if not offset: + # Full, privacy and parser replays can still include a verified append. + offset, _ = self._check_at(self.row, self.size, self.mtime_ns, self.ino) + if offset: + return self.row["ordinal_max"] + 1 + if (self.row["read_offset"] == 0 and self.row["ordinal_max"] == -1 + and self.row["ino"] == self.ino and self.row["mtime_ns"] is not None + and self.size >= self.row["size_bytes"]): + return 0 # The same file previously contained no complete records. + return None + def records(self): """Yield (ordinal, obj, raw_line) for complete lines after the start. @@ -313,7 +331,7 @@ def insert_event(con: sqlite3.Connection, stats: dict, *, source_id: int, duration_ms=None, size_bytes=None, truncated=None, fingerprint=None, detail=None, update: bool = False, migrate_ordinal: bool = False, - reconcile: bool = False) -> None: + reconcile: bool = False, checkout_events: list | None = None) -> None: """Insert one event under its natural key; a repeat is a no-op. Every protected field passes through agent_observer/privacy.py rule 6: @@ -399,6 +417,8 @@ def insert_event(con: sqlite3.Connection, stats: dict, *, source_id: int, stats["events_duplicate"] = stats.get("events_duplicate", 0) + 1 else: stats["events_inserted"] = stats.get("events_inserted", 0) + 1 + if checkout_events is not None and safe_target and family in CHECKOUT_EVENT_FAMILIES: + checkout_events.append((cur.lastrowid, safe_target)) def fingerprint(*parts: object) -> str: diff --git a/agent_observer/placement.py b/agent_observer/placement.py index a09c8a1..1792603 100644 --- a/agent_observer/placement.py +++ b/agent_observer/placement.py @@ -1,7 +1,7 @@ """Legacy checkout placement for sessions shared by T3 PR links. -Sync records what checkout each tool path was observed in, with its event -and response. Reports match those observations against the current PR links. +Native import records the checkout of each new event's tool paths. Reports +join those immutable observations to the current response and PR evidence. A checkout path can be reused without changing an earlier observation. """ @@ -18,6 +18,8 @@ # Claude writes tool_use in the response record. Codex reports usage after # the response's items. CALL_FOLLOWS_RESPONSE = {"claude": True, "codex": False} +CHECKOUT_EVENT_FAMILIES = ("tool_call", "read", "skill_read", "file_change") +CHECKOUT_EVENT_PARAMS = ",".join("?" for _ in CHECKOUT_EVENT_FAMILIES) PATH_RE = re.compile(r"(?(){}\[\],=]*") REMOTE_RE = re.compile( @@ -121,8 +123,14 @@ def _occurrence_owners(con, session_key, live_ids): if len(owners) == 1} +def _path_keys(target): + for path in PATH_RE.findall(target or ""): + # Bind evidence to the safe target without persisting the path again. + yield hashlib.sha256(path.encode()).digest(), path + + def _session_paths(con, session_key, harness): - """Current response ids and tool paths with their native call owners.""" + """Current response ids and event/path keys with their response owners.""" responses = con.execute( "SELECT response_id, ordinal_num FROM responses WHERE session_key=?" " AND is_overlap=0 ORDER BY ordinal_num", (session_key,)).fetchall() @@ -135,8 +143,8 @@ def _session_paths(con, session_key, harness): paths = {} for call in con.execute( "SELECT id, ordinal_num, target FROM events WHERE session_key=?" - " AND family IN ('tool_call','read','skill_read','file_change')", - (session_key,)): + f" AND family IN ({CHECKOUT_EVENT_PARAMS})", + (session_key, *CHECKOUT_EVENT_FAMILIES)): rid = None if owners is not None: rid = owners.get(str(call["id"])) @@ -147,19 +155,17 @@ def _session_paths(con, session_key, harness): index = bisect.bisect_left(ordinals, call["ordinal_num"]) if 0 <= index < len(timed): rid = timed[index]["response_id"] - for path in PATH_RE.findall(call["target"] or ""): - # Bind the observation to this path without retaining tool inputs. - digest = hashlib.sha256(path.encode()).digest() - paths[call["id"], digest] = (rid, path) + if rid is not None: + for digest, _ in _path_keys(call["target"]): + paths[call["id"], digest] = rid return ids, paths def _observations(con, session_key): return {(r["event_id"], r["path_digest"]): - (r["response_id"], r["host"] if "host" in r.keys() else None, - r["repository"], r["branch"]) + (r["host"], r["repository"], r["branch"]) for r in con.execute( - "SELECT o.* FROM events e JOIN response_checkouts o ON e.id=o.event_id" + "SELECT o.* FROM events e JOIN event_checkouts o ON e.id=o.event_id" " WHERE e.session_key=?", (session_key,))} @@ -174,28 +180,21 @@ def read_placements(con, session_key: str) -> dict | None: if legacy is None: return None harness, tasks = legacy - if not _has_table(con, "response_checkouts"): - return {} heads = _task_heads(con, tasks) if not heads: return None + if not _has_table(con, "event_checkouts"): + return {} ids, paths = _session_paths(con, session_key, harness) observations = _observations(con, session_key) matches = {rid: set() for rid in ids} pending = set() - for key, (rid, _) in paths.items(): - if rid is None: - continue + for key, rid in paths.items(): observed = observations.get(key) - if observed is None or observed[0] != rid: - pending.add(rid) - continue - _, host, repo, branch = observed - if host is None and repo is not None and branch is not None: - # A hostless historical head could belong to a competing PR. + if observed is None: pending.add(rid) else: - matches[rid].update(heads.get((host, repo, branch), ())) + matches[rid].update(heads.get(observed, ())) return {rid: next(iter(owners)) if rid not in pending and len(owners) == 1 else None for rid, owners in matches.items()} @@ -204,46 +203,31 @@ def read_placements(con, session_key: str) -> dict | None: place_session = read_placements -def record_shared_checkouts(con) -> int: - """Observe each event/path once. Reimports can revise its response witness.""" - # Serialize the schema check and migration across syncs. +def observe_new_checkouts(con, events) -> None: + """Observe only events inserted from new native records in this import.""" + roots = {} + observations = {} + for event_id, target in events: + for digest, path in _path_keys(target): + observations[event_id, digest] = _checkout(path, roots) + if not observations: + return + # The native import committed before running Git. An interruption can + # leave a gap, which later imports cannot fill from a reused checkout. with con: - if not con.in_transaction: - con.execute("BEGIN IMMEDIATE") con.execute( - "CREATE TABLE IF NOT EXISTS response_checkouts(" + "CREATE TABLE IF NOT EXISTS event_checkouts(" " event_id INTEGER NOT NULL REFERENCES events(id) ON DELETE CASCADE," - " path_digest BLOB NOT NULL, response_id TEXT, host TEXT," - " repository TEXT, branch TEXT, PRIMARY KEY(event_id, path_digest))") - columns = {r["name"] for r in con.execute("PRAGMA table_info(response_checkouts)")} - if "host" not in columns: - con.execute("ALTER TABLE response_checkouts ADD COLUMN host TEXT") - shared = [r[0] for r in con.execute( - "SELECT session_key FROM session_assignments GROUP BY session_key HAVING COUNT(*) > 1")] - roots = {} - for session_key in shared: - legacy = _legacy_session(con, session_key) - if legacy is None: - continue - harness, _ = legacy - _, paths = _session_paths(con, session_key, harness) - observations = _observations(con, session_key) - changed = [] - for key, (rid, path) in paths.items(): - observed = observations.get(key) - if observed is None: - host, repo, branch = _checkout(path, roots) - elif observed[0] != rid: - host, repo, branch = observed[1:] - else: - continue - changed.append((*key, rid, host, repo, branch)) - # No git subprocess runs under the ledger write lock. On a racing - # sync the first checkout observation wins, including a missing one. - with con: - con.executemany( - "INSERT INTO response_checkouts" - " (event_id,path_digest,response_id,host,repository,branch)" - " VALUES(?,?,?,?,?,?) ON CONFLICT(event_id,path_digest) DO UPDATE" - " SET response_id=excluded.response_id", changed) - return len(shared) + " path_digest BLOB NOT NULL, host TEXT, repository TEXT, branch TEXT," + " PRIMARY KEY(event_id,path_digest))") + con.executemany( + "INSERT OR IGNORE INTO event_checkouts(event_id,path_digest,host,repository,branch)" + " SELECT ?,?,?,?,? WHERE EXISTS(SELECT 1 FROM events WHERE id=?)", + ((*key, *checkout, key[0]) for key, checkout in observations.items())) + + +def record_shared_checkouts(con) -> int: + """Return the T3 sync counter. Native import records checkout evidence.""" + return con.execute( + "SELECT COUNT(*) FROM (SELECT 1 FROM session_assignments" + " GROUP BY session_key HAVING COUNT(*) > 1)").fetchone()[0] diff --git a/tests/test_codex_fork.py b/tests/test_codex_fork.py index 0db31cc..3c2fb6c 100644 --- a/tests/test_codex_fork.py +++ b/tests/test_codex_fork.py @@ -617,7 +617,7 @@ def _bind(self, con): "commit", "-q", "--allow-empty", "-m", "start"]): subprocess.run(["git", *args], check=True, capture_output=True) - def test_upgrade_keeps_parent_input_and_read_attribution(self): + def test_upgrade_keeps_parent_input_and_read_evidence(self): for user_id in (None, "parent-input"): with self.subTest(user_id=user_id): if os.path.exists(self.db_path): @@ -644,14 +644,16 @@ def test_upgrade_keeps_parent_input_and_read_attribution(self): self.assertIn("retained parent input", shown["text"]) placement.record_shared_checkouts(con) placed = placement.read_placements(con, "codex:parent") - self.assertEqual(placed["codex:parent-r1"], "o/alpha#1") - self.assertEqual(placed["codex:parent-r2"], "o/beta#2") + # The old importer recorded no timely checkout evidence. + # The retained native reads alone cannot prove their forge or head. + self.assertIsNone(placed.get("codex:parent-r1")) + self.assertIsNone(placed.get("codex:parent-r2")) for i, repo in enumerate(("alpha", "beta"), 1): measured = report.task_report( con, f"o/{repo}#{i}", schedule={"models": {}})[ "measured"] self.assertIn(f"codex:parent-r{i}", - measured["attributed_responses"]) + measured["unplaced_responses"]) reads = con.execute( "SELECT e.family FROM codex_occurrences o" " JOIN events e ON e.id = o.row_key" diff --git a/tests/test_placement.py b/tests/test_placement.py index d521cc7..442dc7c 100644 --- a/tests/test_placement.py +++ b/tests/test_placement.py @@ -11,6 +11,7 @@ from agent_observer import cli, db, placement, report from agent_observer.adapters import t3 as t3_adapter +from agent_observer.adapters.claude import import_claude_file from agent_observer.adapters.codex import import_codex_file from tests.helpers import LedgerCase @@ -46,13 +47,14 @@ def setUp(self): " head_branch) VALUES('t','pr','github.com',?,?,?,?)", (f"o/{repo}", n, f"https://github.com/o/{repo}/pull/{n}", branch)) - def session(self, harness, calls, *, tasks=("o/alpha#1", "o/beta#2")): + def session(self, harness, calls, *, tasks=("o/alpha#1", "o/beta#2"), missing=()): """calls: (response ordinal, tool-call ordinal, target) per response.""" key = f"{harness}:s" db.upsert_session(self.con, key, harness, "s", None, project_dir="/nowhere") for task in tasks: self.con.execute("INSERT INTO session_assignments(session_key, task_id," " evidence, created_at) VALUES(?,?,'t3',0)", (key, task)) + new_events = [] for i, (resp, call, target) in enumerate(calls): self.con.execute( "INSERT INTO responses(response_id, source_id, harness, session_key," @@ -60,10 +62,14 @@ def session(self, harness, calls, *, tasks=("o/alpha#1", "o/beta#2")): " VALUES(?,?,?,?,?,'m',100,10,110)", (f"r{i}", self.source, harness, key, resp)) if target is not None: - self.con.execute( + event = self.con.execute( "INSERT INTO events(source_id, session_key, ordinal_num, family," " native_id, name, target) VALUES(?,?,?,'tool_call',?,'Bash',?)", (self.source, key, call, f"e{i}", target)) + if i not in missing and harness in placement.CALL_FOLLOWS_RESPONSE: + new_events.append((event.lastrowid, target)) + self.con.commit() + placement.observe_new_checkouts(self.con, new_events) return key def claude_session(self): @@ -106,6 +112,95 @@ def test_removed_worktree_still_places_from_recorded_checkouts(self): placed = placement.read_placements(self.con, "claude:s") self.assertEqual((placed["r0"], placed["r1"]), ("o/alpha#1", "o/beta#2")) + def _append_claude_call(self, path, session, response, root): + record = {"type": "assistant", "sessionId": session, "message": { + "id": response, "model": "m", "usage": {"input_tokens": 10, "output_tokens": 2}, + "content": [{"type": "tool_use", "id": f"call-{response}", "name": "Bash", + "input": {"command": f"cat {root}/x.py"}}], + }} + with open(path, "a") as fh: + fh.write(json.dumps(record) + "\n") + + def _assign(self, key, task): + self.con.execute( + "INSERT INTO session_assignments(session_key,task_id,evidence,created_at)" + " VALUES(?,?,'t3',0)", (key, task)) + + def test_late_link_keeps_the_first_imports_checkout_after_path_reuse(self): + for session, t3_first in (("t3-first", True), ("native-first", False)): + with self.subTest(order=session): + key = f"claude:{session}" + path = os.path.join(self.tmp.name, f"{session}.jsonl") + root = self.checkouts["alpha"] + _git("-C", root, "checkout", "-q", "fix/a") + _git("-C", root, "remote", "set-url", "origin", "git@github.com:o/alpha.git") + self.con.execute("DELETE FROM t3_links WHERE number=2") + if t3_first: + self._assign(key, "o/alpha#1") + self._append_claude_call(path, session, f"{session}-1", root) + import_claude_file(self.con, path) + if not t3_first: + self._assign(key, "o/alpha#1") + placement.record_shared_checkouts(self.con) + _git("-C", root, "checkout", "-q", "-B", "fix/b") + _git("-C", root, "remote", "set-url", "origin", "git@github.com:o/beta.git") + self.con.execute( + "INSERT INTO t3_links(thread_id,kind,host,repository,number,url,head_branch)" + " VALUES('t','pr','github.com','o/beta',2," + " 'https://github.com/o/beta/pull/2','fix/b')") + self._assign(key, "o/beta#2") + self._append_claude_call(path, session, f"{session}-2", root) + self.assertTrue(import_claude_file(self.con, path)["incremental"]) + placement.record_shared_checkouts(self.con) + self.assertEqual(placement.read_placements(self.con, key), { + f"claude:{session}-1": "o/alpha#1", f"claude:{session}-2": "o/beta#2"}) + + def test_replay_of_old_ledger_captures_only_verified_new_records(self): + key = "claude:old-ledger" + path = os.path.join(self.tmp.name, "old-ledger.jsonl") + root = self.checkouts["alpha"] + self._append_claude_call(path, "old-ledger", "before", root) + # Simulate an older writer that indexed the native rows without observing Git. + with patch.object(placement, "observe_new_checkouts"): + import_claude_file(self.con, path) + # Its parser also missed the tool call. Recovering an event from the + # old prefix still cannot make an observation of today's checkout timely. + self.con.execute("DELETE FROM events WHERE native_id='call-before'") + for task in ("o/alpha#1", "o/beta#2"): + self._assign(key, task) + _git("-C", root, "checkout", "-q", "-b", "fix/b") + _git("-C", root, "remote", "set-url", "origin", "git@github.com:o/beta.git") + with patch.object(placement, "_git", side_effect=AssertionError("old checkout scanned")): + self.assertEqual(import_claude_file(self.con, path, full=True)["events_inserted"], 1) + placement.record_shared_checkouts(self.con) + self.assertIsNone(placement.read_placements(self.con, key).get("claude:before")) + + self._append_claude_call(path, "old-ledger", "after", root) + # A parser-driven replay must still admit a provably appended record. + self.con.execute("UPDATE sources SET claude_usage_version=0") + self.assertFalse(import_claude_file(self.con, path)["incremental"]) + self.assertEqual(placement.read_placements(self.con, key), { + "claude:before": None, "claude:after": "o/beta#2"}) + + def test_codex_observes_call_before_usage_arrives(self): + key = "codex:placement-review" + path, _ = self._continuation_files("live") + with open(path) as fh: + records = fh.readlines()[:4] + with open(path, "w") as fh: + fh.writelines(records[:3]) + fh.write(records[3].rstrip("\n")) + import_codex_file(self.con, path) + self.assertEqual(self.con.execute("SELECT COUNT(*) FROM responses").fetchone()[0], 0) + self._bind_placement_tasks(self.con) + shutil.rmtree(self.checkouts["alpha"]) + with open(path, "a") as fh: + fh.write("\n") + with patch.object(placement, "_git", side_effect=AssertionError("checkout scanned again")): + self.assertTrue(import_codex_file(self.con, path)["incremental"]) + self.assertEqual(placement.read_placements(self.con, key), + {"codex:r1": "o/alpha#1"}) + def test_checkout_on_another_forge_does_not_credit_github(self): root = self.checkouts["alpha"] _git("-C", root, "remote", "set-url", "origin", "git@forge.example:o/alpha.git") @@ -155,21 +250,23 @@ def test_pr_head_from_another_forge_cannot_supply_a_github_match(self): placement.record_shared_checkouts(self.con) self.assertIsNone(placement.read_placements(self.con, key)["r0"]) - def test_historical_checkout_without_host_cannot_supply_or_hide_a_match(self): - alpha, beta = self.checkouts["alpha"], self.checkouts["beta"] + def test_historical_checkout_without_import_provenance_cannot_place(self): + alpha = self.checkouts["alpha"] key = self.session("claude", [ - (1, 2, f"diff {alpha}/f {beta}/f"), + (1, 2, f"ls {alpha}/f"), (3, 4, f"ls {alpha}/f"), - ]) + ], missing=(0,)) self.con.execute( "CREATE TABLE response_checkouts(" " event_id INTEGER NOT NULL REFERENCES events(id) ON DELETE CASCADE," - " path_digest BLOB NOT NULL, response_id TEXT, repository TEXT, branch TEXT," + " path_digest BLOB NOT NULL, response_id TEXT, host TEXT," + " repository TEXT, branch TEXT," " PRIMARY KEY(event_id, path_digest))") event_id = self.con.execute("SELECT id FROM events WHERE native_id='e0'").fetchone()[0] digest = hashlib.sha256(f"{alpha}/f".encode()).digest() - self.con.execute("INSERT INTO response_checkouts VALUES(?,?,'r0','o/alpha','fix/old')", - (event_id, digest)) + self.con.execute( + "INSERT INTO response_checkouts VALUES(?,?,'r0','github.com','o/alpha','fix/a')", + (event_id, digest)) self.con.commit() with closing(db.connect_read_only(self.db_path)) as ro: self.assertIsNone(placement.read_placements(ro, key).get("r0")) @@ -212,29 +309,31 @@ def test_reused_checkout_path_preserves_old_and_new_response_witnesses(self): _git("-C", root, "remote", "set-url", "origin", "git@github.com:o/beta.git") self.con.execute("INSERT INTO responses(response_id,source_id,session_key," " ordinal_num) VALUES('new',?,?,10)", (self.source, key)) - self.con.execute("INSERT INTO events(session_key,ordinal_num,family,native_id,target)" - " VALUES(?,11,'read','new-call',?)", (key, root)) + event = self.con.execute( + "INSERT INTO events(session_key,ordinal_num,family,native_id,target)" + " VALUES(?,11,'read','new-call',?)", (key, root)) self.assertIsNone(placement.read_placements(self.con, key)["new"]) - placement.record_shared_checkouts(self.con) + self.con.commit() + placement.observe_new_checkouts(self.con, [(event.lastrowid, root)]) shutil.rmtree(root) placement.record_shared_checkouts(self.con) placed = placement.read_placements(self.con, key) self.assertEqual((placed["r0"], placed["new"]), ("o/alpha#1", "o/beta#2")) def test_removed_checkout_without_response_evidence_does_not_place(self): - key = self.claude_session() + key = self.session("claude", [(1, 2, f"ls {self.checkouts['alpha']}")], missing=(0,)) root = self.checkouts["alpha"] self.con.execute("INSERT INTO checkouts(root,repository,branch,seen_at)" " VALUES(?,'o/alpha','fix/a',0)", (root,)) shutil.rmtree(root) self.assertEqual(placement.read_placements(self.con, key), {}) placement.record_shared_checkouts(self.con) - self.assertIsNone(placement.read_placements(self.con, key)["r0"]) + self.assertEqual(placement.read_placements(self.con, key), {}) def test_checkout_without_origin_cannot_gain_a_retroactive_match(self): - key = self.claude_session() root = self.checkouts["alpha"] _git("-C", root, "remote", "remove", "origin") + key = self.claude_session() placement.record_shared_checkouts(self.con) _git("-C", root, "remote", "add", "origin", "git@github.com:o/alpha.git") placement.record_shared_checkouts(self.con) @@ -704,53 +803,23 @@ def write(name, response, total): placement.record_shared_checkouts(con) self.assertEqual(placement.read_placements(con, key), ambiguous) - def test_shared_checkout_is_resolved_once_per_sync(self): - # Two shared sessions in one record_shared_checkouts share a root. - # A per-session roots map would ask git twice for that root. + def test_checkout_is_resolved_once_for_new_events_in_one_import(self): root = self.checkouts["alpha"] + path = os.path.join(self.tmp.name, "same-root.jsonl") for n in (1, 2): - key = f"claude:s{n}" - db.upsert_session(self.con, key, "claude", f"s{n}", None, - project_dir="/nowhere") - for task in ("o/alpha#1", "o/beta#2"): - self.con.execute( - "INSERT INTO session_assignments(session_key, task_id," - " evidence, created_at) VALUES(?,?,'t3',0)", (key, task)) - self.con.execute( - "INSERT INTO responses(response_id, source_id, harness," - " session_key, ordinal_num, model, input_tokens," - " output_tokens, total_tokens)" - " VALUES(?,?,?,?,?,'m',100,10,110)", - (f"once{n}", self.source, "claude", key, 1)) - self.con.execute( - "INSERT INTO events(source_id, session_key, ordinal_num," - " family, native_id, name, target)" - " VALUES(?,?,?,'tool_call',?,'Bash',?)", - (self.source, key, 2, f"once-e{n}", f"ls {root}")) - calls = [] - real = placement._git - - def wrapped(checkout, *args): - calls.append((checkout, args)) - return real(checkout, *args) - - placement._git = wrapped - try: - self.assertEqual(placement.record_shared_checkouts(self.con), 2) - finally: - placement._git = real - self.assertEqual( - [c for c in calls if c == (root, ("remote", "get-url", "origin"))], - [(root, ("remote", "get-url", "origin"))]) - self.assertEqual( - [c for c in calls if c == (root, ("rev-parse", "--abbrev-ref", "HEAD"))], - [(root, ("rev-parse", "--abbrev-ref", "HEAD"))]) - for n in (1, 2): - self.assertEqual(placement.read_placements(self.con, f"claude:s{n}"), - {f"once{n}": "o/alpha#1"}) + self._append_claude_call(path, "same-root", f"r{n}", root) + with patch.object(placement, "_git", wraps=placement._git) as git: + import_claude_file(self.con, path) + self.assertEqual([call.args for call in git.call_args_list], [ + (root, "remote", "get-url", "origin"), + (root, "rev-parse", "--abbrev-ref", "HEAD")]) def test_live_git_runs_outside_an_open_write(self): - key = self.claude_session() + key = "claude:transaction" + path = os.path.join(self.tmp.name, "transaction.jsonl") + self._append_claude_call(path, "transaction", "r0", self.checkouts["alpha"]) + for task in ("o/alpha#1", "o/beta#2"): + self._assign(key, task) self.assertTrue(self.con.in_transaction) real = placement._git @@ -759,11 +828,11 @@ def check_transaction(root, *args): return real(root, *args) with patch.object(placement, "_git", side_effect=check_transaction) as git: - placement.record_shared_checkouts(self.con) + import_claude_file(self.con, path) self.assertTrue(git.called) other = db.connect_read_only(self.db_path) self.addCleanup(other.close) - self.assertEqual(placement.read_placements(other, key)["r0"], "o/alpha#1") + self.assertEqual(placement.read_placements(other, key)["claude:r0"], "o/alpha#1") def test_sync_records_shared_sessions_once_after_refresh(self): calls = [] From 78f87008feb1289187810da7c22e8bafc4707b27 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:41:37 +0100 Subject: [PATCH 19/44] wip: verify legacy tree context stays outside both task bills --- tests/test_t3.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tests/test_t3.py b/tests/test_t3.py index 468bd61..7a85989 100644 --- a/tests/test_t3.py +++ b/tests/test_t3.py @@ -368,15 +368,17 @@ def test_tree_tasks_and_shared_ownership(self): "unit": "USD per million tokens", "models": {}}) self.assertEqual(shared["attributed"]["responses"], 0) - self.assertEqual(shared["unplaced_shared"]["responses"], 4) + self.assertEqual(shared["shared_joint"]["responses"], 4) self.assertEqual(shared["unassigned_in_scope"]["responses"], 0) self.assertTrue(shared["reconciles"]) - # Never divided: the same whole responses sit under both tasks. + # Without PR head evidence both tasks show the same session context. + # Neither outcome bills these four responses. other = report.task_report(self.con, "example/alpha#3", schedule=shared["price_schedule"]) self.assertEqual( - sorted(shared["measured"]["unplaced_responses"]), - sorted(other["measured"]["unplaced_responses"])) + shared["measured"]["shared_responses"], other["measured"]["shared_responses"]) + self.assertEqual(other["total_cost"]["shared_responses"], 0) + self.assertIsNone(shared["total_cost"]["usd"]) solo = report.task_report(self.con, "example/alpha#9", schedule=shared["price_schedule"]) self.assertEqual(solo["attributed"]["responses"], 0) From b33e3b0acdbee7eae66ffc1140ae0ef168e230ee Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:48:03 +0100 Subject: [PATCH 20/44] wip: exclude disputed Grok calls and describe native task ownership --- agent_observer/adapters/grok.py | 17 +++++++++++++++-- agent_observer/outcome.py | 8 +++++++- agent_observer/publish.py | 9 ++++----- tests/test_publish.py | 5 +++++ tests/test_t3_purpose.py | 12 ++++++++++++ 5 files changed, 43 insertions(+), 8 deletions(-) diff --git a/agent_observer/adapters/grok.py b/agent_observer/adapters/grok.py index f2ed58e..7a7c865 100644 --- a/agent_observer/adapters/grok.py +++ b/agent_observer/adapters/grok.py @@ -2982,7 +2982,7 @@ def _record_prompt_bridges(r, src, records): def response_witnesses(con, session_key): if not db._has_table(con, "grok_prompt_bridges"): - return {}, set() + return {}, set(), set() completed = set() indexes = {} calls = {} @@ -3013,6 +3013,19 @@ def response_witnesses(con, session_key): if index is not None: indexes.setdefault(index, set()).update(pids) tool_witnesses.update(f"{session_key}:{pid}" for pid in pids) + if db._has_table(con, "t3_source_grok_calls"): + # A rejected projection cannot grant ownership, but its literal + # call still identifies which completion a competing capture must exclude. + for call, in con.execute( + "SELECT DISTINCT s.call_id FROM t3_source_grok_calls s " + "LEFT JOIN t3_purpose_grok_calls c USING(session_key,call_id,provider_turn_id) " + "LEFT JOIN t3_source_inputs i ON i.source_path=s.source_path AND i.session_key=s.session_key " + "AND i.provider_turn_id=s.provider_turn_id AND i.validation='grok_prompt_index' " + "LEFT JOIN t3_purpose_inputs a ON a.session_key=i.session_key AND a.native_id=i.native_id " + "AND a.provider_turn_id=i.provider_turn_id AND a.validation=i.validation " + "WHERE s.session_key=? AND (c.call_id IS NULL OR (i.native_id IS NOT NULL AND a.native_id IS NULL))", + (session_key,)): + disputed.update(calls.get(call, ())) # One native index claiming two different prompt ids is contradictory, # including when the two claims came from different copies. disputed.update(pid for pids in indexes.values() if len(pids) > 1 for pid in pids) @@ -3024,7 +3037,7 @@ def response_witnesses(con, session_key): result = {rid: refs[rid] for rid, in con.execute( "SELECT response_id FROM responses WHERE session_key=? AND is_overlap=0", (session_key,) ) if rid in refs} - return result, tool_witnesses.intersection(result) + return result, tool_witnesses.intersection(result), {f"{session_key}:{pid}" for pid in disputed} def response_inputs(con, session_key): diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index 018d192..49e4550 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -125,9 +125,10 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me if turn: input_turns[identity].add(turn) call_witnesses = set() + disputed_completions = set() if harness == "grok": from .adapters import grok - responses, call_witnesses = grok.response_witnesses(con, key) + responses, call_witnesses, disputed_completions = grok.response_witnesses(con, key) else: responses = native_response.inputs(con, key) # In a contested whole session, only events on resolved turns can be @@ -147,6 +148,11 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me exclusive = False for rid, display_turn in con.execute( "SELECT response_id,turn_id FROM responses WHERE session_key=? AND is_overlap=0", (key,)): + if rid in disputed_completions: + conflicts.add(rid) + blocked_turns.add(rid) + exclusive = False + continue input_ids = responses.get(rid, set()) identities = {f"{prefix}:{identity}" for identity in input_ids} candidates = {candidate for identity in input_ids for candidate in by_input.get(identity, ())} diff --git a/agent_observer/publish.py b/agent_observer/publish.py index c469f69..92d1ef5 100644 --- a/agent_observer/publish.py +++ b/agent_observer/publish.py @@ -501,12 +501,11 @@ def render(summary: dict, target: str | None = None) -> str: f"so sums across PRs overlap.") unplaced = total.get("unplaced") or {} if unplaced.get("responses"): - lines.append(f"- Not counted: {unplaced['responses']:,} responses " - f"({_safe_field(unplaced.get('text') or 'unknown')}) in sessions " - f"shared with other PRs that worked in no single PR's checkout.") + lines.append(f"- Ownership is unresolved for {unplaced['responses']:,} responses " + f"({_safe_field(unplaced.get('text') or 'unknown')}). They are excluded from this total.") if unplaced.get("other_task_responses"): - lines.append(f"- {unplaced['other_task_responses']:,} responses in these " - f"sessions worked on other PRs and are counted there.") + lines.append(f"- {unplaced['other_task_responses']:,} responses belong to other tasks " + "and are excluded from this total.") unassigned = (summary.get("unassigned_in_scope") or {}).get("responses", 0) if unassigned: lines.append(f"- {unassigned:,} responses in these sessions belong to no " diff --git a/tests/test_publish.py b/tests/test_publish.py index 25575da..26cb562 100644 --- a/tests/test_publish.py +++ b/tests/test_publish.py @@ -113,6 +113,11 @@ def test_delivery_reference_privacy_and_excluded_cost_in_a_task_publication(self self.assertNotIn("internal.example", private) self.assertNotIn("private-repo", private) self.assertIn("Outcome: reference withheld", private) + summary["total_cost"] = {"unplaced": {"responses": 2, "other_task_responses": 3}} + scoped = publish.render(summary) + self.assertIn("Ownership is unresolved for 2 responses", scoped) + self.assertIn("3 responses belong to other tasks", scoped) + self.assertNotIn("checkout", scoped) def test_second_publish_edits_the_same_owned_comment(self): gh = PublishGh([]) diff --git a/tests/test_t3_purpose.py b/tests/test_t3_purpose.py index b521ece..b3b32c8 100644 --- a/tests/test_t3_purpose.py +++ b/tests/test_t3_purpose.py @@ -139,6 +139,18 @@ def membership(): other = sqlite3.connect(other_path) self.addCleanup(other.close) self.native.backup(other) + task = "git.example.org/example/project#7" + self.con.execute("INSERT INTO session_assignments VALUES(?,?,'capture',1)", ("grok:" + sid, task)) + other.execute(f"""UPDATE {PREFIX}runs SET payload_json=json_set( + payload_json,'$.purpose.scope.reference.number',8) WHERE run_id='g'""") + other.commit() + self.assertEqual(t3.sync(self.con, source=other_path)["failed"], []) + rep = report.task_report(self.con, task) + self.assertIn(rid, rep["native_purpose"]["conflicting_responses"]) + self.assertEqual(rep["attributed"]["responses"], 0) + self.assertFalse(report.timeline(self.con, task)["events"]) + other.execute(f"""UPDATE {PREFIX}runs SET payload_json=json_set( + payload_json,'$.purpose.scope.reference.number',7) WHERE run_id='g'""") other.execute(f"""UPDATE {PREFIX}turn_items SET payload_json=json_set( payload_json,'$.nativeItemRef.nativeId','a-different-call')""") other.commit() From 51f27776eaf1dca5c579185723a10390423f4660 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:53:10 +0100 Subject: [PATCH 21/44] wip: expose sync-time checkout observations separately from outcome ownership --- README.md | 7 ++++--- agent_observer/report.py | 10 ++++++++-- docs/contracts.md | 11 ++++++----- tests/test_outcome.py | 10 +++++++--- 4 files changed, 25 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index da50120..3f8b630 100644 --- a/README.md +++ b/README.md @@ -529,9 +529,10 @@ A provider turn can reconcile while the full outcome cost remains unknown. Chromeria v1 records observed background causes for some drivers and has no background inventory for others. A missing child boundary or unavailable price leaves any priced work as a subtotal. The same scope appears in -`publish --task`. For legacy shared PR sessions, sync captures checkout -evidence per response while the checkout exists. Retiring the checkout -preserves those observations. +`publish --task`. For legacy PR links, `legacy_checkout_observations` +shows which checkout Observer saw when it imported a tool call. The observation +survives checkout retirement. A path can change hands before import, so a +matching PR head alone leaves the response outside the bill. Put `observer_task_id` in related Router jobs' prepared task JSON to connect them to one Observer task. `sync` binds their dedicated worker and dispatcher diff --git a/agent_observer/report.py b/agent_observer/report.py index c8a9d9f..82ff20a 100644 --- a/agent_observer/report.py +++ b/agent_observer/report.py @@ -7,7 +7,7 @@ import json import sqlite3 -from . import codex_order, outcome +from . import codex_order, outcome, placement from .db import _has_table BUCKETS = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", @@ -550,9 +550,12 @@ def task_report(con: sqlite3.Connection, task_id: str, whole_shared = whole_conflicts | {key for key, owners in session_owners.items() if len(owners) > 1} responses = _responses(con, scope_keys) attributed, shared, unassigned = [], [], [] - # A legacy checkout can place the remainder after explicit ownership. + # A link can supply session context while the individual owners remain unknown. placements = {key: _place(con, key) for key in legacy_links if len(linked_tasks[key]) > 1 and key not in session_owners} + checkout_records = {} + for key in sorted(legacy_links): + checkout_records.update(placement.checkout_observations(con, key)) unplaced, elsewhere = [], [] missing_submissions = [] sharing_tasks = set() @@ -719,6 +722,7 @@ def _resp_tuple(r) -> list: unavailable_sources = list( source_availability.get("unavailable_sources") or []) snapshot_payload = { + **({"legacy_checkout_observations": checkout_records} if checkout_records else {}), "price_schedule": schedule, "phases": phases, "activity_session_context": activity_context, @@ -891,6 +895,8 @@ def _resp_tuple(r) -> list: report["reconciles"] = responses_reconcile and totals_reconcile if legacy_links: report["coverage"]["legacy_thread_links"] = sorted(legacy_links) + if checkout_records: + report["legacy_checkout_observations"] = {"basis": "first_native_import", "responses": checkout_records} if native: report["native_purpose"] = native report["unbound_usage"] = unbound_usage diff --git a/docs/contracts.md b/docs/contracts.md index c982d1a..f5a4b55 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -541,11 +541,12 @@ re-read every sync; workload bindings are durable ledger rows. (`origin='t3'`); every ledger session in the tree (cursor sessions plus Claude subagent children plus rotated sessions found by turn uuid) binds whole to every tree task as historical session context. A thread link alone cannot place a response. - In a multi-link tree, a Claude or Codex response belongs to one PR when - the paths its tool calls name lie in a checkout of that PR's repository - on its head branch (T3 snapshot `headBranch`). Sync records that observation - against the individual event, path digest and response. Reports read the ledger. A response - matching no PR or several stays unplaced and outside every headline. + For new Claude or Codex events, the importer can observe the forge, + repository and branch of a checkout named by a tool path. Reports join + those observations to individual responses and list matching PR heads in + `legacy_checkout_observations`. A path can change owners before its first + import. These observations establish which checkout Observer saw at sync. + Billing requires independent evidence of the response's owner. Whole-session sharing from links stays visible outside the outcome cost. Ghostty bodies and unknown cursor shapes are skipped. - Outcomes come from the PR snapshot (`merged` completes); exit codes are diff --git a/tests/test_outcome.py b/tests/test_outcome.py index b91e759..4afaf42 100644 --- a/tests/test_outcome.py +++ b/tests/test_outcome.py @@ -214,13 +214,17 @@ def test_delivery_alone_preserves_legacy_placement_and_capture_trace(self): self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (other,)) self.con.executemany("INSERT INTO session_assignments VALUES(?,?,'t3',0)", [(self.session, self.task), (self.session, other)]) - placed = {"codex:resp-mini-001": self.task, "codex:resp-mini-002": other} - with patch("agent_observer.placement.read_placements", return_value=placed): + observed = {"codex:resp-mini-001": [{"host": "github.com", "repository": "example/repo", + "branch": "topic", "candidate_tasks": [self.task]}]} + with patch("agent_observer.placement.checkout_observations", return_value=observed): before = report.task_report(self.con, self.task) self.con.execute("INSERT INTO t3_purpose_deliveries VALUES(?, 'planner', 'github.com'," "'example/repo',42,'https://github.com/example/repo/pull/42','now')", (self.task,)) after = report.task_report(self.con, self.task) - self.assertEqual(before["measured"]["attributed_responses"], ["codex:resp-mini-001"]) + self.assertEqual(before["measured"]["attributed_responses"], []) + self.assertEqual(after["legacy_checkout_observations"], + {"basis": "first_native_import", "responses": observed}) + self.assertIsNone(after["total_cost"]["usd"]) self.assertEqual(after["measured"], before["measured"]) self.assertIn("purpose_run_unavailable", after["native_purpose"]["coverage_gaps"]) self.assign(self.task, "02") From 7b04b0e7b8040bc7ad1f5a18e558aac6c44554a5 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:50:14 +0100 Subject: [PATCH 22/44] wip: require native checkout evidence for legacy placement --- agent_observer/adapters/claude.py | 10 +- agent_observer/adapters/codex.py | 10 +- agent_observer/cli.py | 3 +- agent_observer/ingest.py | 22 +- agent_observer/placement.py | 228 +---------- tests/test_placement.py | 602 ++++++------------------------ 6 files changed, 138 insertions(+), 737 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index f4c84b2..c749f88 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -19,7 +19,7 @@ import sqlite3 from collections import defaultdict, deque -from .. import db, intervention_evidence, native_response, placement, privacy +from .. import db, native_response, privacy, intervention_evidence from ..identity import SessionIdentity, skill_from_path from ..ingest import (JsonlSource, MissingNativeId, fingerprint, insert_event, iso_ts, text_hash) @@ -302,8 +302,6 @@ def __init__(self, con, src: JsonlSource, stats: dict): self.con = con self.src = src self.stats = stats - self.first_new_ordinal = src.first_new_ordinal() - self.checkout_events = [] self.native_session = src.row["session_id"] self.agent_id = src.row["thread_id"] self.identity = SessionIdentity() @@ -331,10 +329,7 @@ def event(self, family, native_id, ordinal, ts, **kw): insert_event(self.con, self.stats, source_id=self.src.source_id, session_key=self.session_key, family=family, native_id=native_id, ordinal=ordinal, ts=ts, - turn_id=self.turn, update=self.src.privacy_stale, - checkout_events=self.checkout_events - if self.first_new_ordinal is not None - and ordinal >= self.first_new_ordinal else None, **kw) + turn_id=self.turn, update=self.src.privacy_stale, **kw) def import_claude_file(con: sqlite3.Connection, path: str, @@ -451,7 +446,6 @@ def import_claude_file(con: sqlite3.Connection, path: str, (_IMPORT_VERSION, src.end_offset, src.source_id)) stats["session_key"] = r.session_key con.commit() - placement.observe_new_checkouts(con, r.checkout_events) return stats diff --git a/agent_observer/adapters/codex.py b/agent_observer/adapters/codex.py index 2d80e6f..e46dd04 100644 --- a/agent_observer/adapters/codex.py +++ b/agent_observer/adapters/codex.py @@ -18,7 +18,7 @@ import os import sqlite3 -from .. import db, native_response, placement, privacy +from .. import db, native_response, privacy from ..identity import SessionIdentity, skill_from_path from ..ingest import (JsonlSource, MissingNativeId, fingerprint, insert_event, iso_ts, stored_path, text_hash) @@ -371,8 +371,6 @@ def __init__(self, con: sqlite3.Connection, src: JsonlSource, stats: dict): self.con = con self.src = src self.stats = stats - self.first_new_ordinal = src.first_new_ordinal() - self.checkout_events = [] self.session_id = src.row["session_id"] self.thread_id = src.row["thread_id"] self.thread_source = src.row["thread_source"] @@ -484,10 +482,7 @@ def event(self, obj, family, native_id, *, legacy_id=None, **kw): native_id=native_id, ordinal=self.record_position, ts=iso_ts(obj.get("timestamp")), update=self.src.privacy_stale and same_source, - migrate_ordinal=first and same_source, - checkout_events=self.checkout_events - if self.first_new_ordinal is not None - and self.record_position >= self.first_new_ordinal else None, **kw) + migrate_ordinal=first and same_source, **kw) event_id = prior["id"] if prior is not None else None if event_id is None: stored = self.con.execute( @@ -976,7 +971,6 @@ def import_codex_file(con: sqlite3.Connection, path: str, stats["moved_rows_with"] = sorted(settle) stats["session_key"] = reader.session_key con.commit() - placement.observe_new_checkouts(con, reader.checkout_events) return stats diff --git a/agent_observer/cli.py b/agent_observer/cli.py index cf44a8d..ebf8a27 100644 --- a/agent_observer/cli.py +++ b/agent_observer/cli.py @@ -1074,8 +1074,7 @@ def _sync(con, ns) -> int: row[key] = (row.get(key) or 0) + value elif key not in row: row[key] = value - # Count shared sessions after the T3 refresh. Native adapters record - # checkout evidence as they import events, regardless of link order. + # Count shared sessions after the T3 refresh. if "t3" in wanted: for row in results: if row.get("harness") == "t3" and "skipped" not in row: diff --git a/agent_observer/ingest.py b/agent_observer/ingest.py index fa7af8e..a6eb05d 100644 --- a/agent_observer/ingest.py +++ b/agent_observer/ingest.py @@ -27,7 +27,6 @@ from . import privacy from .command_status import pending_pr_checks from .db import now -from .placement import CHECKOUT_EVENT_FAMILIES TAIL_BYTES = 4096 @@ -94,7 +93,6 @@ def __init__(self, con: sqlite3.Connection, harness: str, path: str, "SELECT * FROM sources WHERE harness=? AND path=?", (harness, path)).fetchone() self.row = row - self.new_source = row is None self.start_offset = 0 self.unchanged = False stored_version = (row["privacy_version"] @@ -217,22 +215,6 @@ def recheck_unchanged(self) -> bool: def incremental(self) -> bool: return self.start_offset > 0 - def first_new_ordinal(self) -> int | None: - """First record eligible for live evidence, even during a parser replay.""" - if self.new_source: - return 0 - offset = self.start_offset - if not offset: - # Full, privacy and parser replays can still include a verified append. - offset, _ = self._check_at(self.row, self.size, self.mtime_ns, self.ino) - if offset: - return self.row["ordinal_max"] + 1 - if (self.row["read_offset"] == 0 and self.row["ordinal_max"] == -1 - and self.row["ino"] == self.ino and self.row["mtime_ns"] is not None - and self.size >= self.row["size_bytes"]): - return 0 # The same file previously contained no complete records. - return None - def records(self): """Yield (ordinal, obj, raw_line) for complete lines after the start. @@ -331,7 +313,7 @@ def insert_event(con: sqlite3.Connection, stats: dict, *, source_id: int, duration_ms=None, size_bytes=None, truncated=None, fingerprint=None, detail=None, update: bool = False, migrate_ordinal: bool = False, - reconcile: bool = False, checkout_events: list | None = None) -> None: + reconcile: bool = False) -> None: """Insert one event under its natural key; a repeat is a no-op. Every protected field passes through agent_observer/privacy.py rule 6: @@ -417,8 +399,6 @@ def insert_event(con: sqlite3.Connection, stats: dict, *, source_id: int, stats["events_duplicate"] = stats.get("events_duplicate", 0) + 1 else: stats["events_inserted"] = stats.get("events_inserted", 0) + 1 - if checkout_events is not None and safe_target and family in CHECKOUT_EVENT_FAMILIES: - checkout_events.append((cur.lastrowid, safe_target)) def fingerprint(*parts: object) -> str: diff --git a/agent_observer/placement.py b/agent_observer/placement.py index 1792603..be67118 100644 --- a/agent_observer/placement.py +++ b/agent_observer/placement.py @@ -1,233 +1,37 @@ -"""Legacy checkout placement for sessions shared by T3 PR links. +"""Keep unproven legacy T3 checkout attribution out of task totals. -Native import records the checkout of each new event's tool paths. Reports -join those immutable observations to the current response and PR evidence. -A checkout path can be reused without changing an earlier observation. +Claude tool records carry a working directory and branch, without a forge +or repository identity. Codex records Git identity at session start and +a working directory at command execution, without binding the two. Neither +source proves the checkout of a specific call. Legacy checkout tables were +populated from live Git and cannot supply that missing native evidence. """ from __future__ import annotations -import bisect -import hashlib -import os -import re -import subprocess - -from .db import _has_table - -# Claude writes tool_use in the response record. Codex reports usage after -# the response's items. -CALL_FOLLOWS_RESPONSE = {"claude": True, "codex": False} -CHECKOUT_EVENT_FAMILIES = ("tool_call", "read", "skill_read", "file_change") -CHECKOUT_EVENT_PARAMS = ",".join("?" for _ in CHECKOUT_EVENT_FAMILIES) - -PATH_RE = re.compile(r"(?(){}\[\],=]*") -REMOTE_RE = re.compile( - r"(?:(?:https?|ssh|git)://(?:[^/\s@]+@)?(?P[a-z0-9.-]+(?::[0-9]+)?)/" - r"|(?:[^/:\s@]+@)?(?P[a-z0-9.-]+):)" - r"(?P[\w.-]+/[\w.-]+?)(?:\.git)?/?", - re.IGNORECASE | re.ASCII, -) - - -def _git(root: str, *args: str) -> str | None: - try: - out = subprocess.run(["git", "-C", root, *args], capture_output=True, - text=True, timeout=5, check=False) - except (OSError, subprocess.SubprocessError): - return None - return out.stdout.strip() if out.returncode == 0 else None - - -def _checkout(path: str, roots: dict) -> tuple: - root = os.path.normpath(os.path.expanduser(path)) - while root != os.path.dirname(root): - if os.path.exists(os.path.join(root, ".git")): - if root not in roots: - remote = _git(root, "remote", "get-url", "origin") or "" - match = REMOTE_RE.fullmatch(remote) - if match: - host = match["url_host"] or match["scp_host"] - branch = _git(root, "rev-parse", "--abbrev-ref", "HEAD") - roots[root] = (host.lower(), match["repository"].lower(), - branch if branch != "HEAD" else None) - else: - roots[root] = (None, None, None) - return roots[root] - root = os.path.dirname(root) - return None, None, None +def read_placements(con, session_key: str) -> dict | None: + """An empty map leaves legacy Codex/Claude responses unplaced. -def _legacy_session(con, session_key): + None delegates other assignment types and harnesses to the caller. + """ rows = con.execute( - "SELECT s.harness, a.evidence, a.task_id FROM sessions s" + "SELECT s.harness, a.evidence FROM sessions s" " JOIN session_assignments a USING(session_key) WHERE s.session_key=?", (session_key,)).fetchall() - if (len(rows) < 2 or rows[0]["harness"] not in CALL_FOLLOWS_RESPONSE - or any(r["evidence"] != "t3" and not r["evidence"].startswith("t3:") - for r in rows)): - return None - return rows[0]["harness"], [r["task_id"] for r in rows] - - -def _task_heads(con, task_ids): - by_head = {} - columns = {r["name"] for r in con.execute("PRAGMA table_info(t3_links)")} - if not {"host", "head_branch"} <= columns: - return by_head - for task in task_ids: - coordinate, separator, number = task.rpartition("#") - parts = coordinate.lower().split("/") - if not separator or len(parts) not in (2, 3): - continue - # T3 task IDs omit the host for GitHub and prefix it for other forges. - host = parts[0] if len(parts) == 3 else "github.com" - repo = "/".join(parts[-2:]) - for row in con.execute( - "SELECT DISTINCT head_branch FROM t3_links WHERE kind='pr'" - " AND host=? COLLATE NOCASE AND repository=? COLLATE NOCASE" - " AND number=? AND head_branch IS NOT NULL", (host, repo, number)): - by_head.setdefault((host, repo, row["head_branch"]), set()).add(task) - return by_head - - -def _has_occurrences(con, session_key: str) -> bool: - return _has_table(con, "codex_occurrences") and con.execute( - "SELECT 1 FROM codex_occurrences WHERE session_key=? LIMIT 1", - (session_key,)).fetchone() is not None - - -def _occurrence_owners(con, session_key, live_ids): - """A call's owner is the next live response in each witnessing source. - - A source with no following response supplies no witness. Disagreeing - witnesses leave the call unplaced, regardless of import order. - """ - witnesses = {} - sources = con.execute( - "SELECT DISTINCT source_id FROM codex_occurrences WHERE session_key=?", - (session_key,)) - for source in sources: - following = None - for row in con.execute( - "SELECT row_kind, row_key FROM codex_occurrences" - " WHERE session_key=? AND source_id=? AND row_kind IN ('response','event')" - " ORDER BY record_position DESC, row_kind DESC", - (session_key, source["source_id"])): - if row["row_kind"] == "response": - if row["row_key"] in live_ids: - following = row["row_key"] - elif following is not None: - witnesses.setdefault(row["row_key"], set()).add(following) - return {event: next(iter(owners)) for event, owners in witnesses.items() - if len(owners) == 1} - - -def _path_keys(target): - for path in PATH_RE.findall(target or ""): - # Bind evidence to the safe target without persisting the path again. - yield hashlib.sha256(path.encode()).digest(), path - - -def _session_paths(con, session_key, harness): - """Current response ids and event/path keys with their response owners.""" - responses = con.execute( - "SELECT response_id, ordinal_num FROM responses WHERE session_key=?" - " AND is_overlap=0 ORDER BY ordinal_num", (session_key,)).fetchall() - ids = [r["response_id"] for r in responses] - timed = [r for r in responses if r["ordinal_num"] is not None] - ordinals = [r["ordinal_num"] for r in timed] - owners = None - if harness == "codex" and _has_occurrences(con, session_key): - owners = _occurrence_owners(con, session_key, set(ids)) - paths = {} - for call in con.execute( - "SELECT id, ordinal_num, target FROM events WHERE session_key=?" - f" AND family IN ({CHECKOUT_EVENT_PARAMS})", - (session_key, *CHECKOUT_EVENT_FAMILIES)): - rid = None - if owners is not None: - rid = owners.get(str(call["id"])) - elif call["ordinal_num"] is not None: - if CALL_FOLLOWS_RESPONSE[harness]: - index = bisect.bisect_right(ordinals, call["ordinal_num"]) - 1 - else: - index = bisect.bisect_left(ordinals, call["ordinal_num"]) - if 0 <= index < len(timed): - rid = timed[index]["response_id"] - if rid is not None: - for digest, _ in _path_keys(call["target"]): - paths[call["id"], digest] = rid - return ids, paths - - -def _observations(con, session_key): - return {(r["event_id"], r["path_digest"]): - (r["host"], r["repository"], r["branch"]) - for r in con.execute( - "SELECT o.* FROM events e JOIN event_checkouts o ON e.id=o.event_id" - " WHERE e.session_key=?", (session_key,))} - - -def read_placements(con, session_key: str) -> dict | None: - """Read response_id -> sole matching PR, or None for an unplaced response. - - None leaves whole-session sharing to the caller. An empty map leaves - every response unplaced on a ledger without observations. Only current - call/response pairings count, even between syncs. - """ - legacy = _legacy_session(con, session_key) - if legacy is None: - return None - harness, tasks = legacy - heads = _task_heads(con, tasks) - if not heads: - return None - if not _has_table(con, "event_checkouts"): + if (len(rows) >= 2 and rows[0]["harness"] in ("claude", "codex") + and all(r["evidence"] == "t3" or r["evidence"].startswith("t3:") + for r in rows)): return {} - ids, paths = _session_paths(con, session_key, harness) - observations = _observations(con, session_key) - matches = {rid: set() for rid in ids} - pending = set() - for key, rid in paths.items(): - observed = observations.get(key) - if observed is None: - pending.add(rid) - else: - matches[rid].update(heads.get(observed, ())) - return {rid: next(iter(owners)) if rid not in pending and len(owners) == 1 else None - for rid, owners in matches.items()} + return None # Compatibility for callers using the original report helper. place_session = read_placements -def observe_new_checkouts(con, events) -> None: - """Observe only events inserted from new native records in this import.""" - roots = {} - observations = {} - for event_id, target in events: - for digest, path in _path_keys(target): - observations[event_id, digest] = _checkout(path, roots) - if not observations: - return - # The native import committed before running Git. An interruption can - # leave a gap, which later imports cannot fill from a reused checkout. - with con: - con.execute( - "CREATE TABLE IF NOT EXISTS event_checkouts(" - " event_id INTEGER NOT NULL REFERENCES events(id) ON DELETE CASCADE," - " path_digest BLOB NOT NULL, host TEXT, repository TEXT, branch TEXT," - " PRIMARY KEY(event_id,path_digest))") - con.executemany( - "INSERT OR IGNORE INTO event_checkouts(event_id,path_digest,host,repository,branch)" - " SELECT ?,?,?,?,? WHERE EXISTS(SELECT 1 FROM events WHERE id=?)", - ((*key, *checkout, key[0]) for key, checkout in observations.items())) - - def record_shared_checkouts(con) -> int: - """Return the T3 sync counter. Native import records checkout evidence.""" + """Return the legacy T3 sync counter.""" return con.execute( "SELECT COUNT(*) FROM (SELECT 1 FROM session_assignments" " GROUP BY session_key HAVING COUNT(*) > 1)").fetchone()[0] diff --git a/tests/test_placement.py b/tests/test_placement.py index 442dc7c..eafd150 100644 --- a/tests/test_placement.py +++ b/tests/test_placement.py @@ -1,4 +1,4 @@ -"""A session shared by several PRs splits per response by checkout (#43).""" +"""Legacy T3 checkout gaps and native Codex occurrence retention.""" import hashlib import io @@ -47,353 +47,129 @@ def setUp(self): " head_branch) VALUES('t','pr','github.com',?,?,?,?)", (f"o/{repo}", n, f"https://github.com/o/{repo}/pull/{n}", branch)) - def session(self, harness, calls, *, tasks=("o/alpha#1", "o/beta#2"), missing=()): - """calls: (response ordinal, tool-call ordinal, target) per response.""" - key = f"{harness}:s" - db.upsert_session(self.con, key, harness, "s", None, project_dir="/nowhere") - for task in tasks: - self.con.execute("INSERT INTO session_assignments(session_key, task_id," - " evidence, created_at) VALUES(?,?,'t3',0)", (key, task)) - new_events = [] - for i, (resp, call, target) in enumerate(calls): - self.con.execute( - "INSERT INTO responses(response_id, source_id, harness, session_key," - " ordinal_num, model, input_tokens, output_tokens, total_tokens)" - " VALUES(?,?,?,?,?,'m',100,10,110)", - (f"r{i}", self.source, harness, key, resp)) - if target is not None: - event = self.con.execute( - "INSERT INTO events(source_id, session_key, ordinal_num, family," - " native_id, name, target) VALUES(?,?,?,'tool_call',?,'Bash',?)", - (self.source, key, call, f"e{i}", target)) - if i not in missing and harness in placement.CALL_FOLLOWS_RESPONSE: - new_events.append((event.lastrowid, target)) - self.con.commit() - placement.observe_new_checkouts(self.con, new_events) - return key - - def claude_session(self): - a, b = self.checkouts["alpha"], self.checkouts["beta"] - return self.session("claude", [ - (1, 2, f"cd {a} && git status"), # alpha - (3, 4, f"python3 {b}/x.py"), # beta - (5, 6, f"diff {a}/f {b}/f"), # both: unplaced - (7, 8, "gh pr list"), # none: unplaced - (9, None, None), # no tool call: unplaced - ]) - - def test_each_pr_counts_only_its_own_responses_and_totals_reconcile(self): - self.claude_session() - placement.record_shared_checkouts(self.con) - alpha = report.task_report(self.con, "o/alpha#1", schedule=SCHEDULE) - beta = report.task_report(self.con, "o/beta#2", schedule=SCHEDULE) - self.assertEqual(alpha["measured"]["attributed_responses"], ["r0"]) - self.assertEqual(beta["measured"]["attributed_responses"], ["r1"]) - self.assertEqual(alpha["measured"]["unplaced_responses"], ["r2", "r3", "r4"]) - self.assertEqual(alpha["measured"]["other_task_responses"], ["r1"]) - self.assertEqual(alpha["shared_joint"]["responses"], 0) - self.assertEqual(alpha["total_cost"]["responses"], 1) - self.assertEqual(alpha["total_cost"]["unplaced"]["responses"], 3) - self.assertTrue(alpha["reconciles"]) - self.assertTrue(beta["reconciles"]) - - def test_codex_calls_belong_to_the_next_response(self): - a, b = self.checkouts["alpha"], self.checkouts["beta"] - self.session("codex", [(2, 1, f"ls {a}"), (4, 3, f"ls {b}")]) - placement.record_shared_checkouts(self.con) - placed = placement.read_placements(self.con, "codex:s") - self.assertEqual(placed, {"r0": "o/alpha#1", "r1": "o/beta#2"}) - - def test_removed_worktree_still_places_from_recorded_checkouts(self): - self.claude_session() - self.assertEqual(placement.record_shared_checkouts(self.con), 1) - for root in self.checkouts.values(): - shutil.rmtree(root) - placed = placement.read_placements(self.con, "claude:s") - self.assertEqual((placed["r0"], placed["r1"]), ("o/alpha#1", "o/beta#2")) - - def _append_claude_call(self, path, session, response, root): - record = {"type": "assistant", "sessionId": session, "message": { - "id": response, "model": "m", "usage": {"input_tokens": 10, "output_tokens": 2}, - "content": [{"type": "tool_use", "id": f"call-{response}", "name": "Bash", - "input": {"command": f"cat {root}/x.py"}}], - }} - with open(path, "a") as fh: - fh.write(json.dumps(record) + "\n") - - def _assign(self, key, task): + def _assign(self, key, task, evidence="t3"): self.con.execute( "INSERT INTO session_assignments(session_key,task_id,evidence,created_at)" - " VALUES(?,?,'t3',0)", (key, task)) - - def test_late_link_keeps_the_first_imports_checkout_after_path_reuse(self): - for session, t3_first in (("t3-first", True), ("native-first", False)): - with self.subTest(order=session): - key = f"claude:{session}" - path = os.path.join(self.tmp.name, f"{session}.jsonl") - root = self.checkouts["alpha"] - _git("-C", root, "checkout", "-q", "fix/a") - _git("-C", root, "remote", "set-url", "origin", "git@github.com:o/alpha.git") - self.con.execute("DELETE FROM t3_links WHERE number=2") - if t3_first: - self._assign(key, "o/alpha#1") - self._append_claude_call(path, session, f"{session}-1", root) - import_claude_file(self.con, path) - if not t3_first: - self._assign(key, "o/alpha#1") - placement.record_shared_checkouts(self.con) - _git("-C", root, "checkout", "-q", "-B", "fix/b") - _git("-C", root, "remote", "set-url", "origin", "git@github.com:o/beta.git") - self.con.execute( - "INSERT INTO t3_links(thread_id,kind,host,repository,number,url,head_branch)" - " VALUES('t','pr','github.com','o/beta',2," - " 'https://github.com/o/beta/pull/2','fix/b')") - self._assign(key, "o/beta#2") - self._append_claude_call(path, session, f"{session}-2", root) - self.assertTrue(import_claude_file(self.con, path)["incremental"]) - placement.record_shared_checkouts(self.con) - self.assertEqual(placement.read_placements(self.con, key), { - f"claude:{session}-1": "o/alpha#1", f"claude:{session}-2": "o/beta#2"}) - - def test_replay_of_old_ledger_captures_only_verified_new_records(self): - key = "claude:old-ledger" - path = os.path.join(self.tmp.name, "old-ledger.jsonl") + " VALUES(?,?,?,0)", (key, task, evidence)) + + def _assert_unplaced(self, con, responses): + alpha = report.task_report(con, "o/alpha#1", schedule=SCHEDULE) + beta = report.task_report(con, "o/beta#2", schedule=SCHEDULE) + for task in (alpha, beta): + self.assertEqual(task["measured"]["unplaced_responses"], responses) + self.assertEqual(task["measured"]["attributed_responses"], []) + self.assertEqual(task["total_cost"]["responses"], 0) + self.assertTrue(task["reconciles"]) + + def test_first_import_after_path_reuse_leaves_claude_call_unplaced(self): + key = "claude:delayed" + path = os.path.join(self.tmp.name, "delayed.jsonl") root = self.checkouts["alpha"] - self._append_claude_call(path, "old-ledger", "before", root) - # Simulate an older writer that indexed the native rows without observing Git. - with patch.object(placement, "observe_new_checkouts"): - import_claude_file(self.con, path) - # Its parser also missed the tool call. Recovering an event from the - # old prefix still cannot make an observation of today's checkout timely. - self.con.execute("DELETE FROM events WHERE native_id='call-before'") - for task in ("o/alpha#1", "o/beta#2"): - self._assign(key, task) + native = [ + {"type": "assistant", "sessionId": "delayed", "cwd": root, "gitBranch": "fix/a", + "message": {"id": "before", "model": "m", "usage": {"input_tokens": 10, + "output_tokens": 2}, + "content": [{"type": "tool_use", "id": "call-before", "name": "Bash", + "input": {"command": f"cd {root} && gh pr edit 1" + " --repo o/alpha --title Revised"}}]}}, + {"type": "user", "sessionId": "delayed", "uuid": "result", + "message": {"content": [{"type": "tool_result", "tool_use_id": "call-before", + "content": "https://github.com/o/alpha/pull/1"}]}, + "toolUseResult": {"gitOperation": {"pr": {"action": "edited", "number": 1, + "url": "https://github.com/o/alpha/pull/1"}}}}, + {"type": "pr-link", "sessionId": "delayed", "prNumber": 1, + "prRepository": "o/alpha", "prUrl": "https://github.com/o/alpha/pull/1"}, + ] + with open(path, "w") as stream: + for row in native: + stream.write(json.dumps(row) + "\n") + _git("-C", root, "checkout", "-q", "-b", "fix/b") _git("-C", root, "remote", "set-url", "origin", "git@github.com:o/beta.git") - with patch.object(placement, "_git", side_effect=AssertionError("old checkout scanned")): - self.assertEqual(import_claude_file(self.con, path, full=True)["events_inserted"], 1) - placement.record_shared_checkouts(self.con) - self.assertIsNone(placement.read_placements(self.con, key).get("claude:before")) - - self._append_claude_call(path, "old-ledger", "after", root) - # A parser-driven replay must still admit a provably appended record. - self.con.execute("UPDATE sources SET claude_usage_version=0") - self.assertFalse(import_claude_file(self.con, path)["incremental"]) - self.assertEqual(placement.read_placements(self.con, key), { - "claude:before": None, "claude:after": "o/beta#2"}) - - def test_codex_observes_call_before_usage_arrives(self): - key = "codex:placement-review" - path, _ = self._continuation_files("live") - with open(path) as fh: - records = fh.readlines()[:4] - with open(path, "w") as fh: - fh.writelines(records[:3]) - fh.write(records[3].rstrip("\n")) - import_codex_file(self.con, path) - self.assertEqual(self.con.execute("SELECT COUNT(*) FROM responses").fetchone()[0], 0) - self._bind_placement_tasks(self.con) - shutil.rmtree(self.checkouts["alpha"]) - with open(path, "a") as fh: - fh.write("\n") - with patch.object(placement, "_git", side_effect=AssertionError("checkout scanned again")): - self.assertTrue(import_codex_file(self.con, path)["incremental"]) - self.assertEqual(placement.read_placements(self.con, key), - {"codex:r1": "o/alpha#1"}) - - def test_checkout_on_another_forge_does_not_credit_github(self): - root = self.checkouts["alpha"] - _git("-C", root, "remote", "set-url", "origin", "git@forge.example:o/alpha.git") - key = self.claude_session() - placement.record_shared_checkouts(self.con) - placed = placement.read_placements(self.con, key) - self.assertIsNone(placed["r0"]) - self.assertEqual(placed["r1"], "o/beta#2") - - def test_same_repository_and_head_on_two_forges(self): - github = self.checkouts["alpha"] - hosted = os.path.join(self.tmp.name, "hosted-alpha") - shutil.copytree(github, hosted) - _git("-C", hosted, "remote", "set-url", "origin", "https://FORGE.example/o/alpha.git") - task = "forge.example/o/alpha#1" - self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (task,)) - self.con.execute( - "INSERT INTO t3_links(thread_id,kind,host,repository,number,url,head_branch)" - " VALUES('t','pr','Forge.Example','o/alpha',1," - " 'https://forge.example/o/alpha/pull/1','fix/a')") - key = self.session("claude", [ - (1, 2, f"ls {github}"), - (3, 4, f"ls {hosted}"), - (5, 6, f"diff {github}/f {hosted}/f"), - ], tasks=("o/alpha#1", task)) - expected = {"r0": "o/alpha#1", "r1": task, "r2": None} - placement.record_shared_checkouts(self.con) - self.assertEqual(placement.read_placements(self.con, key), expected) - shutil.rmtree(github) - shutil.rmtree(hosted) - with closing(db.connect_read_only(self.db_path)) as ro, patch.object( - placement, "_git", side_effect=AssertionError("report ran git")): - self.assertEqual(placement.read_placements(ro, key), expected) - for task_id, response in (("o/alpha#1", "r0"), (task, "r1")): - measured = report.task_report(ro, task_id, schedule=SCHEDULE)["measured"] - self.assertEqual(measured["attributed_responses"], [response]) - self.assertEqual(measured["unplaced_responses"], ["r2"]) - - def test_pr_head_from_another_forge_cannot_supply_a_github_match(self): + self._assign(key, "o/alpha#1") + # Late link and replay cannot use the new checkout to place the old call. + with patch.object(subprocess, "run", side_effect=AssertionError("import ran Git")): + self.assertEqual(import_claude_file(self.con, path)["malformed"], 0) + self.assertEqual(self.con.execute( + "SELECT COUNT(*) FROM events WHERE family='tool_call'").fetchone()[0], 1) + self._assign(key, "o/beta#2") + self.assertEqual(placement.record_shared_checkouts(self.con), 1) + self.assertEqual(import_claude_file(self.con, path, full=True)["malformed"], 0) + self._assert_unplaced(self.con, ["claude:before"]) + + def test_codex_session_git_and_literal_pr_target_leave_call_unplaced(self): + key = "codex:target" root = self.checkouts["alpha"] - _git("-C", root, "checkout", "-q", "-b", "fix/hosted") - self.con.execute( - "INSERT INTO t3_links(thread_id,kind,host,repository,number,url,head_branch)" - " VALUES('t','pr','forge.example','o/alpha',1," - " 'https://forge.example/o/alpha/pull/1','fix/hosted')") - key = self.claude_session() - placement.record_shared_checkouts(self.con) - self.assertIsNone(placement.read_placements(self.con, key)["r0"]) - - def test_historical_checkout_without_import_provenance_cannot_place(self): - alpha = self.checkouts["alpha"] - key = self.session("claude", [ - (1, 2, f"ls {alpha}/f"), - (3, 4, f"ls {alpha}/f"), - ], missing=(0,)) - self.con.execute( - "CREATE TABLE response_checkouts(" - " event_id INTEGER NOT NULL REFERENCES events(id) ON DELETE CASCADE," - " path_digest BLOB NOT NULL, response_id TEXT, host TEXT," - " repository TEXT, branch TEXT," - " PRIMARY KEY(event_id, path_digest))") - event_id = self.con.execute("SELECT id FROM events WHERE native_id='e0'").fetchone()[0] - digest = hashlib.sha256(f"{alpha}/f".encode()).digest() + path = os.path.join(self.tmp.name, "target.jsonl") + command = "gh pr view 1 --repo github.com/o/alpha" + rows = [ + {"type": "session_meta", "payload": { + "id": "target", "cwd": root, "thread_source": "user", "git": { + "repository_url": "https://github.com/o/alpha.git", + "branch": "fix/a", "commit_hash": "a" * 40}}}, + {"type": "turn_context", "payload": {"cwd": root, "model": "m"}}, + {"type": "event_msg", "payload": {"type": "item_completed", "item": { + "type": "CommandExecution", "id": "call-target", "cwd": root, + "command": ["/bin/bash", "-lc", command], "exit_code": 0, + "status": "completed", "parsed_cmd": [], + }}}, + {"type": "token_usage_record", "payload": { + "response_id": "target-r", "thread_id": "target", + "usage": {"input_tokens": 10, "output_tokens": 2, "total_tokens": 12}}}, + ] + with open(path, "w") as stream: + for row in rows: + stream.write(json.dumps(row) + "\n") + self._assign(key, "o/alpha#1") + self._assign(key, "o/beta#2") + with patch.object(subprocess, "run", side_effect=AssertionError("import ran Git")): + self.assertEqual(import_codex_file(self.con, path)["events_inserted"], 1) + self._assert_unplaced(self.con, ["codex:target-r"]) + + def test_old_live_git_tables_cannot_credit_a_response_in_read_only_reports(self): + key = "claude:s" + db.upsert_session(self.con, key, "claude", "s", self.source) + for task in ("o/alpha#1", "o/beta#2"): + self._assign(key, task) self.con.execute( - "INSERT INTO response_checkouts VALUES(?,?,'r0','github.com','o/alpha','fix/a')", - (event_id, digest)) - self.con.commit() - with closing(db.connect_read_only(self.db_path)) as ro: - self.assertIsNone(placement.read_placements(ro, key).get("r0")) - for _ in range(2): - placement.record_shared_checkouts(self.con) - self.assertEqual(placement.read_placements(self.con, key), - {"r0": None, "r1": "o/alpha#1"}) - - def test_without_head_branches_the_session_stays_shared_whole(self): - self.claude_session() - self.con.execute("UPDATE t3_links SET head_branch=NULL") - placement.record_shared_checkouts(self.con) - alpha = report.task_report(self.con, "o/alpha#1", schedule=SCHEDULE) - self.assertEqual(alpha["shared_joint"]["responses"], 5) - self.assertEqual(alpha["attributed"]["responses"], 0) - - def test_heads_linked_after_checkout_retirement_use_the_original_observation(self): - key = self.claude_session() - self.con.execute("UPDATE t3_links SET head_branch=NULL") - placement.record_shared_checkouts(self.con) - shutil.rmtree(self.checkouts["alpha"]) - self.con.execute("UPDATE t3_links SET head_branch='fix/a' WHERE number=1") - self.assertEqual(placement.read_placements(self.con, key)["r0"], "o/alpha#1") - - def test_unsupported_harness_stays_shared_whole(self): - self.session("opencode", [(1, 2, f"ls {self.checkouts['alpha']}")]) - self.assertIsNone(placement.read_placements(self.con, "opencode:s")) - - def test_detached_checkout_matches_no_pr(self): - _git("-C", self.checkouts["alpha"], "checkout", "-q", "--detach") - key = self.claude_session() - placement.record_shared_checkouts(self.con) - self.assertIsNone(placement.read_placements(self.con, key)["r0"]) - - def test_reused_checkout_path_preserves_old_and_new_response_witnesses(self): - key = self.claude_session() - placement.record_shared_checkouts(self.con) + "INSERT INTO responses(response_id,source_id,harness,session_key,ordinal_num," + " model,input_tokens,output_tokens,total_tokens) VALUES('r0',?,'claude',?,1,'m',10,2,12)", + (self.source, key)) root = self.checkouts["alpha"] - _git("-C", root, "checkout", "-q", "-b", "fix/b") - _git("-C", root, "remote", "set-url", "origin", "git@github.com:o/beta.git") - self.con.execute("INSERT INTO responses(response_id,source_id,session_key," - " ordinal_num) VALUES('new',?,?,10)", (self.source, key)) + target = root + "/file" event = self.con.execute( - "INSERT INTO events(session_key,ordinal_num,family,native_id,target)" - " VALUES(?,11,'read','new-call',?)", (key, root)) - self.assertIsNone(placement.read_placements(self.con, key)["new"]) - self.con.commit() - placement.observe_new_checkouts(self.con, [(event.lastrowid, root)]) - shutil.rmtree(root) - placement.record_shared_checkouts(self.con) - placed = placement.read_placements(self.con, key) - self.assertEqual((placed["r0"], placed["new"]), ("o/alpha#1", "o/beta#2")) - - def test_removed_checkout_without_response_evidence_does_not_place(self): - key = self.session("claude", [(1, 2, f"ls {self.checkouts['alpha']}")], missing=(0,)) - root = self.checkouts["alpha"] + "INSERT INTO events(source_id,session_key,ordinal_num,family,native_id,name,target)" + " VALUES(?,?,2,'tool_call','call-a','Bash',?)", (self.source, key, "cat " + target)) + digest = hashlib.sha256(target.encode()).digest() self.con.execute("INSERT INTO checkouts(root,repository,branch,seen_at)" " VALUES(?,'o/alpha','fix/a',0)", (root,)) - shutil.rmtree(root) - self.assertEqual(placement.read_placements(self.con, key), {}) - placement.record_shared_checkouts(self.con) - self.assertEqual(placement.read_placements(self.con, key), {}) - - def test_checkout_without_origin_cannot_gain_a_retroactive_match(self): - root = self.checkouts["alpha"] - _git("-C", root, "remote", "remove", "origin") - key = self.claude_session() - placement.record_shared_checkouts(self.con) - _git("-C", root, "remote", "add", "origin", "git@github.com:o/alpha.git") - placement.record_shared_checkouts(self.con) - self.assertIsNone(placement.read_placements(self.con, key)["r0"]) - - def test_identical_heads_are_ambiguous_even_if_linked_after_sync(self): - key = self.claude_session() - placement.record_shared_checkouts(self.con) - self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES('o/alpha#3',0)") - self.con.execute("INSERT INTO session_assignments VALUES(?,'o/alpha#3','t3',0)", (key,)) - self.con.execute("INSERT INTO t3_links(thread_id,kind,host,repository,number,url," - " head_branch) VALUES('t','pr','github.com','o/alpha',3,'url','fix/a')") - placed = placement.read_placements(self.con, key) - self.assertIsNone(placed["r0"]) - self.assertEqual(placed["r1"], "o/beta#2") - - def test_explicit_session_owner_preserves_whole_sharing(self): - key = self.claude_session() - placement.record_shared_checkouts(self.con) - self.con.execute("UPDATE session_assignments SET evidence='router:job'" - " WHERE task_id='o/alpha#1'") - self.assertIsNone(placement.read_placements(self.con, key)) - alpha = report.task_report(self.con, "o/alpha#1", schedule=SCHEDULE) - self.assertEqual(alpha["shared_joint"]["responses"], 5) - - def test_read_only_ledger_still_splits(self): - # publish and task open the ledger read-only (cli.py). - self.claude_session() - placement.record_shared_checkouts(self.con) - self.con.commit() - ro = db.connect_read_only(self.db_path) - try: - alpha = report.task_report(ro, "o/alpha#1", schedule=SCHEDULE) - finally: - ro.close() - self.assertEqual(alpha["measured"]["attributed_responses"], ["r0"]) - - def test_report_uses_only_ledger_reads_and_keeps_its_snapshot(self): - self.claude_session() - placement.record_shared_checkouts(self.con) - ro = db.connect_read_only(self.db_path) - self.addCleanup(ro.close) - statements = [] - ro.set_trace_callback(statements.append) - self.con.execute("UPDATE responses SET input_tokens=1100, total_tokens=1110" - " WHERE response_id='r0'") + self.con.execute("CREATE TABLE response_checkouts(event_id,path_digest,response_id," + " host,repository,branch)") + self.con.execute("INSERT INTO response_checkouts VALUES(?,?,'r0','github.com','o/alpha','fix/a')", + (event.lastrowid, digest)) + self.con.execute("CREATE TABLE event_checkouts(event_id,path_digest,host,repository,branch)") + self.con.execute("INSERT INTO event_checkouts VALUES(?,?,'github.com','o/alpha','fix/a')", + (event.lastrowid, digest)) self.con.commit() - with patch.object(placement, "_git", side_effect=AssertionError("report ran git")): - alpha = report.task_report(ro, "o/alpha#1", schedule=SCHEDULE) - self.assertTrue(ro.in_transaction) - self.assertEqual({s.split()[0].upper() for s in statements} - - {"SELECT", "WITH", "PRAGMA"}, set()) - self.assertTrue(alpha["reconciles"]) - self.assertEqual(alpha["attributed"]["total_tokens"], 110) - self.assertEqual(alpha["scope"]["total_tokens"], 550) - - def test_repeated_usage_keeps_the_first_response_on_its_task(self): - # An exact later copy of the first response must not take its - # chronology. Placement then assigns both calls to one response - # and both task reports lose their attributed response. + shutil.rmtree(root) + with closing(db.connect_read_only(self.db_path)) as ro, patch.object( + subprocess, "run", side_effect=AssertionError("report ran Git")): + statements = [] + ro.set_trace_callback(statements.append) + self._assert_unplaced(ro, ["r0"]) + self.assertTrue(ro.in_transaction) + self.assertEqual({sql.split()[0].upper() for sql in statements} + - {"SELECT", "WITH", "PRAGMA"}, set()) + + def test_non_legacy_assignments_and_unsupported_harness_keep_caller_behavior(self): + for harness, evidence in (("claude", "router:job"), ("opencode", "t3")): + key = f"{harness}:s" + db.upsert_session(self.con, key, harness, "s", self.source) + self._assign(key, "o/alpha#1", evidence) + self._assign(key, "o/beta#2") + self.assertIsNone(placement.read_placements(self.con, key)) + + def test_repeated_usage_keeps_the_first_response_position(self): alpha = self.checkouts["alpha"] beta = self.checkouts["beta"] path = os.path.join(self.tmp.name, "placement.jsonl") @@ -435,15 +211,6 @@ def usage(name, total): stored = dict(self.con.execute( "SELECT response_id, ordinal_num FROM responses")) self.assertEqual(stored, {"codex:r1": 3, "codex:r2": 6}) - placement.record_shared_checkouts(self.con) - self.assertEqual(placement.read_placements(self.con, key), { - "codex:r1": "o/alpha#1", "codex:r2": "o/beta#2"}) - alpha_report = report.task_report(self.con, "o/alpha#1", schedule=SCHEDULE) - beta_report = report.task_report(self.con, "o/beta#2", schedule=SCHEDULE) - self.assertEqual(alpha_report["measured"]["attributed_responses"], - ["codex:r1"]) - self.assertEqual(beta_report["measured"]["attributed_responses"], - ["codex:r2"]) # A privacy reimport still adopts the original file position once, # and the exact repeat later in the same file does not move it again. self.con.execute("UPDATE sources SET privacy_version=8") @@ -453,9 +220,6 @@ def usage(name, total): self.assertEqual(self.con.execute( "SELECT ordinal_num FROM responses WHERE response_id='codex:r1'" ).fetchone()[0], 3) - placement.record_shared_checkouts(self.con) - self.assertEqual(placement.read_placements(self.con, key), { - "codex:r1": "o/alpha#1", "codex:r2": "o/beta#2"}) def test_repeated_fallback_snapshot_keeps_its_first_position(self): path = os.path.join(self.tmp.name, "fallback.jsonl") @@ -484,10 +248,7 @@ def test_repeated_fallback_snapshot_keeps_its_first_position(self): ("codex:fallback-review:tc:100",)).fetchone() self.assertEqual(tuple(row), (2, "model-a")) - def test_repeated_tool_call_keeps_the_first_call_on_its_task(self): - # A brand-new source is privacy-stale. An exact later copy of the - # same tool call must not take the original call's chronology, or - # the call falls after every response and the task report loses it. + def test_repeated_tool_call_keeps_the_first_call_position(self): alpha = self.checkouts["alpha"] beta = self.checkouts["beta"] path = os.path.join(self.tmp.name, "calls.jsonl") @@ -530,15 +291,6 @@ def usage(name, total): stored = dict(self.con.execute( "SELECT native_id, ordinal_num FROM events")) self.assertEqual(stored, {"call-a": 2, "call-b": 5}) - placement.record_shared_checkouts(self.con) - self.assertEqual(placement.read_placements(self.con, key), { - "codex:r1": "o/alpha#1", "codex:r2": "o/beta#2"}) - alpha_report = report.task_report(self.con, "o/alpha#1", schedule=SCHEDULE) - beta_report = report.task_report(self.con, "o/beta#2", schedule=SCHEDULE) - self.assertEqual(alpha_report["measured"]["attributed_responses"], - ["codex:r1"]) - self.assertEqual(beta_report["measured"]["attributed_responses"], - ["codex:r2"]) event = self.con.execute( "SELECT id, source_id FROM events WHERE native_id='call-a'").fetchone() self.con.execute( @@ -555,14 +307,8 @@ def usage(name, total): self.assertEqual(self.con.execute( "SELECT intervention_id FROM verdicts").fetchone()[0], f"ev:{key}/tool_call/call-a") - placement.record_shared_checkouts(self.con) - self.assertEqual(placement.read_placements(self.con, key)["codex:r1"], - "o/alpha#1") def test_continuation_keeps_the_original_call_and_response(self): - # The same native call in a second rollout of this session is not - # a new occurrence. Its file position must not replace the call - # that already owns the first response. alpha = self.checkouts["alpha"] beta = self.checkouts["beta"] path = os.path.join(self.tmp.name, "calls.jsonl") @@ -624,17 +370,6 @@ def owned(table, key_column, native): (3, "calls.jsonl")) self.assertEqual(owned("responses", "response_id", "codex:r2"), (6, "calls.jsonl")) - placement.record_shared_checkouts(self.con) - self.assertEqual(placement.read_placements(self.con, key), { - "codex:r1": "o/alpha#1", "codex:r2": "o/beta#2"}) - alpha_report = report.task_report( - self.con, "o/alpha#1", schedule=SCHEDULE) - beta_report = report.task_report( - self.con, "o/beta#2", schedule=SCHEDULE) - self.assertEqual(alpha_report["measured"]["attributed_responses"], - ["codex:r1"]) - self.assertEqual(beta_report["measured"]["attributed_responses"], - ["codex:r2"]) self.assertEqual(self.con.execute( "SELECT COUNT(*) FROM import_errors").fetchone()[0], 0) @@ -687,21 +422,11 @@ def usage(name, total): fh.write(json.dumps(rec) + "\n") return path, continuation - def _assert_public_placement(self, con): - key = "codex:placement-review" + def _assert_occurrences(self, con): self.assertEqual(con.execute( "SELECT COUNT(*) FROM events WHERE native_id='call-a'").fetchone()[0], 1) self.assertEqual(con.execute( "SELECT COUNT(*) FROM responses WHERE is_overlap=0").fetchone()[0], 2) - placement.record_shared_checkouts(con) - self.assertEqual(placement.read_placements(con, key), { - "codex:r1": "o/alpha#1", "codex:r2": "o/beta#2"}) - alpha_report = report.task_report(con, "o/alpha#1", schedule=SCHEDULE) - beta_report = report.task_report(con, "o/beta#2", schedule=SCHEDULE) - self.assertEqual(alpha_report["measured"]["attributed_responses"], - ["codex:r1"]) - self.assertEqual(beta_report["measured"]["attributed_responses"], - ["codex:r2"]) for table, column, native in ( ("events", "native_id", "call-a"), ("events", "native_id", "call-b"), @@ -723,7 +448,7 @@ def _assert_public_placement(self, con): (row["source_id"], kind, row_key, row["ordinal_num"])).fetchone() self.assertIsNotNone(seen) - def test_reverse_continuation_still_places_the_original_response(self): + def test_reverse_continuation_preserves_native_occurrences(self): # The duplicate-only file is imported first. Its call has no # response after it, so it cannot take the original response. path, continuation = self._continuation_files("reverse") @@ -731,108 +456,13 @@ def test_reverse_continuation_still_places_the_original_response(self): for full in (False, True, False): import_codex_file(self.con, continuation, full=full) import_codex_file(self.con, path, full=full) - self._assert_public_placement(self.con) + self._assert_occurrences(self.con) calls = report.timeline( self.con, session_key=key, family="tool_call", limit=1) self.assertEqual( [event["native_id"] for event in calls["events"]], ["call-a"]) self.assertEqual(self.con.execute( "SELECT COUNT(*) FROM import_errors").fetchone()[0], 0) - self.assertTrue(key) - - def test_competing_response_witnesses_leave_the_call_unplaced(self): - # Each file pairs the same call with a different response. Neither - # import order picks one of those responses. - alpha = self.checkouts["alpha"] - - def call(): - return {"type": "response_item", "payload": { - "type": "function_call", "call_id": "call-a", "name": "exec_command", - "arguments": json.dumps({"cmd": "cat " + os.path.join(alpha, "x.py")})}} - - def usage(name, total): - return {"type": "token_usage_record", "payload": { - "response_id": name, "thread_id": "placement-review", - "usage": {"input_tokens": total - 2, "output_tokens": 2, - "total_tokens": total}}} - - def write(name, response, total): - path = os.path.join(self.tmp.name, name) - rows = [ - {"type": "session_meta", "payload": { - "id": "placement-review", "thread_source": "user", "cwd": "/w"}}, - {"type": "turn_context", "payload": {"model": "model-a"}}, - call(), - usage(response, total), - ] - for ordinal, rec in enumerate(rows): - rec["ordinal"] = ordinal - with open(path, "w") as fh: - for rec in rows: - fh.write(json.dumps(rec) + "\n") - return path - - first = write("compete-a.jsonl", "r1", 12) - second = write("compete-b.jsonl", "r2", 22) - key = self._bind_placement_tasks(self.con) - other = db.connect(os.path.join(self.tmp.name, "compete-reverse.db")) - self.addCleanup(other.close) - db.init_db(other) - t3_adapter._ensure_tables(other) - for n, (repo, branch) in enumerate((("alpha", "fix/a"), ("beta", "fix/b")), 1): - task = f"o/{repo}#{n}" - other.execute("INSERT INTO tasks(task_id, project, title, created_at)" - " VALUES(?,?,?,0)", (task, f"o/{repo}", task)) - other.execute( - "INSERT INTO t3_links(thread_id, kind, host, repository, number, url," - " head_branch) VALUES('t','pr','github.com',?,?,?,?)", - (f"o/{repo}", n, f"https://github.com/o/{repo}/pull/{n}", branch)) - self._bind_placement_tasks(other) - for con, order in ((self.con, (first, second)), (other, (second, first))): - import_codex_file(con, order[0]) - placement.record_shared_checkouts(con) - self.assertEqual(list(placement.read_placements(con, key).values()), ["o/alpha#1"]) - import_codex_file(con, order[1]) - # A Codex-only import can invalidate a sync's witness before - # the placement recorder next runs. - ambiguous = {"codex:r1": None, "codex:r2": None} - self.assertEqual(placement.read_placements(con, key), ambiguous) - for full in (False, True, False): - for path in order: - import_codex_file(con, path, full=full) - placement.record_shared_checkouts(con) - self.assertEqual(placement.read_placements(con, key), ambiguous) - - def test_checkout_is_resolved_once_for_new_events_in_one_import(self): - root = self.checkouts["alpha"] - path = os.path.join(self.tmp.name, "same-root.jsonl") - for n in (1, 2): - self._append_claude_call(path, "same-root", f"r{n}", root) - with patch.object(placement, "_git", wraps=placement._git) as git: - import_claude_file(self.con, path) - self.assertEqual([call.args for call in git.call_args_list], [ - (root, "remote", "get-url", "origin"), - (root, "rev-parse", "--abbrev-ref", "HEAD")]) - - def test_live_git_runs_outside_an_open_write(self): - key = "claude:transaction" - path = os.path.join(self.tmp.name, "transaction.jsonl") - self._append_claude_call(path, "transaction", "r0", self.checkouts["alpha"]) - for task in ("o/alpha#1", "o/beta#2"): - self._assign(key, task) - self.assertTrue(self.con.in_transaction) - real = placement._git - - def check_transaction(root, *args): - self.assertFalse(self.con.in_transaction) - return real(root, *args) - - with patch.object(placement, "_git", side_effect=check_transaction) as git: - import_claude_file(self.con, path) - self.assertTrue(git.called) - other = db.connect_read_only(self.db_path) - self.addCleanup(other.close) - self.assertEqual(placement.read_placements(other, key)["claude:r0"], "o/alpha#1") def test_sync_records_shared_sessions_once_after_refresh(self): calls = [] From af784d6daefb7fabb0c0b19a5615ffc93cd6f36f Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 19:53:35 +0100 Subject: [PATCH 23/44] wip: retain first-import checkout observations for diagnostics only --- agent_observer/adapters/claude.py | 10 +- agent_observer/adapters/codex.py | 10 +- agent_observer/cli.py | 1 + agent_observer/ingest.py | 22 ++- agent_observer/placement.py | 237 ++++++++++++++++++++++++++++-- tests/test_placement.py | 68 +++++++-- 6 files changed, 318 insertions(+), 30 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index c749f88..f4c84b2 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -19,7 +19,7 @@ import sqlite3 from collections import defaultdict, deque -from .. import db, native_response, privacy, intervention_evidence +from .. import db, intervention_evidence, native_response, placement, privacy from ..identity import SessionIdentity, skill_from_path from ..ingest import (JsonlSource, MissingNativeId, fingerprint, insert_event, iso_ts, text_hash) @@ -302,6 +302,8 @@ def __init__(self, con, src: JsonlSource, stats: dict): self.con = con self.src = src self.stats = stats + self.first_new_ordinal = src.first_new_ordinal() + self.checkout_events = [] self.native_session = src.row["session_id"] self.agent_id = src.row["thread_id"] self.identity = SessionIdentity() @@ -329,7 +331,10 @@ def event(self, family, native_id, ordinal, ts, **kw): insert_event(self.con, self.stats, source_id=self.src.source_id, session_key=self.session_key, family=family, native_id=native_id, ordinal=ordinal, ts=ts, - turn_id=self.turn, update=self.src.privacy_stale, **kw) + turn_id=self.turn, update=self.src.privacy_stale, + checkout_events=self.checkout_events + if self.first_new_ordinal is not None + and ordinal >= self.first_new_ordinal else None, **kw) def import_claude_file(con: sqlite3.Connection, path: str, @@ -446,6 +451,7 @@ def import_claude_file(con: sqlite3.Connection, path: str, (_IMPORT_VERSION, src.end_offset, src.source_id)) stats["session_key"] = r.session_key con.commit() + placement.observe_new_checkouts(con, r.checkout_events) return stats diff --git a/agent_observer/adapters/codex.py b/agent_observer/adapters/codex.py index e46dd04..2d80e6f 100644 --- a/agent_observer/adapters/codex.py +++ b/agent_observer/adapters/codex.py @@ -18,7 +18,7 @@ import os import sqlite3 -from .. import db, native_response, privacy +from .. import db, native_response, placement, privacy from ..identity import SessionIdentity, skill_from_path from ..ingest import (JsonlSource, MissingNativeId, fingerprint, insert_event, iso_ts, stored_path, text_hash) @@ -371,6 +371,8 @@ def __init__(self, con: sqlite3.Connection, src: JsonlSource, stats: dict): self.con = con self.src = src self.stats = stats + self.first_new_ordinal = src.first_new_ordinal() + self.checkout_events = [] self.session_id = src.row["session_id"] self.thread_id = src.row["thread_id"] self.thread_source = src.row["thread_source"] @@ -482,7 +484,10 @@ def event(self, obj, family, native_id, *, legacy_id=None, **kw): native_id=native_id, ordinal=self.record_position, ts=iso_ts(obj.get("timestamp")), update=self.src.privacy_stale and same_source, - migrate_ordinal=first and same_source, **kw) + migrate_ordinal=first and same_source, + checkout_events=self.checkout_events + if self.first_new_ordinal is not None + and self.record_position >= self.first_new_ordinal else None, **kw) event_id = prior["id"] if prior is not None else None if event_id is None: stored = self.con.execute( @@ -971,6 +976,7 @@ def import_codex_file(con: sqlite3.Connection, path: str, stats["moved_rows_with"] = sorted(settle) stats["session_key"] = reader.session_key con.commit() + placement.observe_new_checkouts(con, reader.checkout_events) return stats diff --git a/agent_observer/cli.py b/agent_observer/cli.py index ebf8a27..00f14ee 100644 --- a/agent_observer/cli.py +++ b/agent_observer/cli.py @@ -1074,6 +1074,7 @@ def _sync(con, ns) -> int: row[key] = (row.get(key) or 0) + value elif key not in row: row[key] = value + # Native imports capture checkout diagnostics independently of T3 links. # Count shared sessions after the T3 refresh. if "t3" in wanted: for row in results: diff --git a/agent_observer/ingest.py b/agent_observer/ingest.py index a6eb05d..96df8cf 100644 --- a/agent_observer/ingest.py +++ b/agent_observer/ingest.py @@ -27,6 +27,7 @@ from . import privacy from .command_status import pending_pr_checks from .db import now +from .placement import CHECKOUT_EVENT_FAMILIES TAIL_BYTES = 4096 @@ -93,6 +94,7 @@ def __init__(self, con: sqlite3.Connection, harness: str, path: str, "SELECT * FROM sources WHERE harness=? AND path=?", (harness, path)).fetchone() self.row = row + self.new_source = row is None self.start_offset = 0 self.unchanged = False stored_version = (row["privacy_version"] @@ -215,6 +217,22 @@ def recheck_unchanged(self) -> bool: def incremental(self) -> bool: return self.start_offset > 0 + def first_new_ordinal(self) -> int | None: + """First record eligible for import-time diagnostics, even during a replay.""" + if self.new_source: + return 0 + offset = self.start_offset + if not offset: + # Full, privacy and parser replays can still include a verified append. + offset, _ = self._check_at(self.row, self.size, self.mtime_ns, self.ino) + if offset: + return self.row["ordinal_max"] + 1 + if (self.row["read_offset"] == 0 and self.row["ordinal_max"] == -1 + and self.row["ino"] == self.ino and self.row["mtime_ns"] is not None + and self.size >= self.row["size_bytes"]): + return 0 # The same file previously contained no complete records. + return None + def records(self): """Yield (ordinal, obj, raw_line) for complete lines after the start. @@ -313,7 +331,7 @@ def insert_event(con: sqlite3.Connection, stats: dict, *, source_id: int, duration_ms=None, size_bytes=None, truncated=None, fingerprint=None, detail=None, update: bool = False, migrate_ordinal: bool = False, - reconcile: bool = False) -> None: + reconcile: bool = False, checkout_events: list | None = None) -> None: """Insert one event under its natural key; a repeat is a no-op. Every protected field passes through agent_observer/privacy.py rule 6: @@ -399,6 +417,8 @@ def insert_event(con: sqlite3.Connection, stats: dict, *, source_id: int, stats["events_duplicate"] = stats.get("events_duplicate", 0) + 1 else: stats["events_inserted"] = stats.get("events_inserted", 0) + 1 + if checkout_events is not None and safe_target and family in CHECKOUT_EVENT_FAMILIES: + checkout_events.append((cur.lastrowid, safe_target)) def fingerprint(*parts: object) -> str: diff --git a/agent_observer/placement.py b/agent_observer/placement.py index be67118..3e95c4e 100644 --- a/agent_observer/placement.py +++ b/agent_observer/placement.py @@ -1,27 +1,209 @@ -"""Keep unproven legacy T3 checkout attribution out of task totals. +"""First-native-import checkout diagnostics for legacy T3 sessions. -Claude tool records carry a working directory and branch, without a forge -or repository identity. Codex records Git identity at session start and -a working directory at command execution, without binding the two. Neither -source proves the checkout of a specific call. Legacy checkout tables were -populated from live Git and cannot supply that missing native evidence. +The observation describes the checkout at import. Claude's call directory +and branch lack repository identity. Codex's Git identity is session-scoped. +Neither source proves the checkout where a specific historical call ran. """ from __future__ import annotations +import bisect +import hashlib +import os +import re +import subprocess + +from .db import _has_table + +# Claude writes tool_use in the response record. Codex reports usage after +# the response's items. +CALL_FOLLOWS_RESPONSE = {"claude": True, "codex": False} +CHECKOUT_EVENT_FAMILIES = ("tool_call", "read", "skill_read", "file_change") +CHECKOUT_EVENT_PARAMS = ",".join("?" for _ in CHECKOUT_EVENT_FAMILIES) + +PATH_RE = re.compile(r"(?(){}\[\],=]*") +REMOTE_RE = re.compile( + r"(?:(?:https?|ssh|git)://(?:[^/\s@]+@)?(?P[a-z0-9.-]+(?::[0-9]+)?)/" + r"|(?:[^/:\s@]+@)?(?P[a-z0-9.-]+):)" + r"(?P[\w.-]+/[\w.-]+?)(?:\.git)?/?", + re.IGNORECASE | re.ASCII, +) + + +def _git(root: str, *args: str) -> str | None: + try: + out = subprocess.run(["git", "-C", root, *args], capture_output=True, + text=True, timeout=5, check=False) + except (OSError, subprocess.SubprocessError): + return None + return out.stdout.strip() if out.returncode == 0 else None + + +def _checkout(path: str, roots: dict) -> tuple: + root = os.path.normpath(os.path.expanduser(path)) + while root != os.path.dirname(root): + if os.path.exists(os.path.join(root, ".git")): + if root not in roots: + remote = _git(root, "remote", "get-url", "origin") or "" + match = REMOTE_RE.fullmatch(remote) + if match: + host = match["url_host"] or match["scp_host"] + branch = _git(root, "rev-parse", "--abbrev-ref", "HEAD") + roots[root] = (host.lower(), match["repository"].lower(), + branch if branch != "HEAD" else None) + else: + roots[root] = (None, None, None) + return roots[root] + root = os.path.dirname(root) + return None, None, None + + +def _session_tasks(con, session_key): + return con.execute( + "SELECT a.task_id, a.evidence FROM session_assignments a WHERE a.session_key=?", + (session_key,)).fetchall() + + +def _task_heads(con, task_ids): + by_head = {} + columns = {r["name"] for r in con.execute("PRAGMA table_info(t3_links)")} + if not {"host", "head_branch"} <= columns: + return by_head + for task in task_ids: + coordinate, separator, number = task.rpartition("#") + parts = coordinate.lower().split("/") + if not separator or len(parts) not in (2, 3): + continue + # T3 task IDs omit the host for GitHub and prefix it for other forges. + host = parts[0] if len(parts) == 3 else "github.com" + repo = "/".join(parts[-2:]) + for row in con.execute( + "SELECT DISTINCT head_branch FROM t3_links WHERE kind='pr'" + " AND host=? COLLATE NOCASE AND repository=? COLLATE NOCASE" + " AND number=? AND head_branch<>''", (host, repo, number)): + by_head.setdefault((host, repo, row["head_branch"]), set()).add(task) + return by_head + + +def _has_occurrences(con, session_key: str) -> bool: + return _has_table(con, "codex_occurrences") and con.execute( + "SELECT 1 FROM codex_occurrences WHERE session_key=? LIMIT 1", + (session_key,)).fetchone() is not None + + +def _occurrence_owners(con, session_key, live_ids): + """Pair a call with the next live response in each witnessing source. + + A source with no following response supplies no witness. Disagreeing + witnesses leave the call unpaired, regardless of import order. + """ + witnesses = {} + sources = con.execute( + "SELECT DISTINCT source_id FROM codex_occurrences WHERE session_key=?", + (session_key,)) + for source in sources: + following = None + for row in con.execute( + "SELECT row_kind, row_key FROM codex_occurrences" + " WHERE session_key=? AND source_id=? AND row_kind IN ('response','event')" + " ORDER BY record_position DESC, row_kind DESC", + (session_key, source["source_id"])): + if row["row_kind"] == "response": + if row["row_key"] in live_ids: + following = row["row_key"] + elif following is not None: + witnesses.setdefault(row["row_key"], set()).add(following) + return {event: next(iter(owners)) for event, owners in witnesses.items() + if len(owners) == 1} + + +def _path_keys(target): + for path in PATH_RE.findall(target or ""): + # Bind evidence to the safe target without persisting the path again. + yield hashlib.sha256(path.encode()).digest(), path + + +def _session_paths(con, session_key, harness): + """Current response ids and event/path keys with their response owners.""" + responses = con.execute( + "SELECT response_id, ordinal_num FROM responses WHERE session_key=?" + " AND is_overlap=0 ORDER BY ordinal_num", (session_key,)).fetchall() + ids = [r["response_id"] for r in responses] + timed = [r for r in responses if r["ordinal_num"] is not None] + ordinals = [r["ordinal_num"] for r in timed] + owners = None + if harness == "codex" and _has_occurrences(con, session_key): + owners = _occurrence_owners(con, session_key, set(ids)) + paths = {} + for call in con.execute( + "SELECT id, ordinal_num, target FROM events WHERE session_key=?" + f" AND family IN ({CHECKOUT_EVENT_PARAMS})", + (session_key, *CHECKOUT_EVENT_FAMILIES)): + rid = None + if owners is not None: + rid = owners.get(str(call["id"])) + elif call["ordinal_num"] is not None: + if CALL_FOLLOWS_RESPONSE[harness]: + index = bisect.bisect_right(ordinals, call["ordinal_num"]) - 1 + else: + index = bisect.bisect_left(ordinals, call["ordinal_num"]) + if 0 <= index < len(timed): + rid = timed[index]["response_id"] + if rid is not None: + for digest, _ in _path_keys(call["target"]): + paths[call["id"], digest] = rid + return paths + + +def _observations(con, session_key): + return {(r["event_id"], r["path_digest"]): + (r["host"], r["repository"], r["branch"]) + for r in con.execute( + "SELECT o.* FROM events e JOIN event_checkouts o ON e.id=o.event_id" + " WHERE e.session_key=? AND o.host<>'' AND o.repository<>''" + " AND o.branch<>''", (session_key,))} + + +def checkout_observations(con, session_key: str) -> dict: + """Read complete first-import coordinates and current PR candidates by response.""" + if not _has_table(con, "event_checkouts"): + return {} + session = con.execute("SELECT harness FROM sessions WHERE session_key=?", + (session_key,)).fetchone() + if session is None or session["harness"] not in CALL_FOLLOWS_RESPONSE: + return {} + observations = _observations(con, session_key) + if not observations: + return {} + heads = _task_heads(con, [row["task_id"] for row in _session_tasks(con, session_key) + if _is_legacy_link(row["evidence"])]) + by_response = {} + for key, rid in _session_paths(con, session_key, session["harness"]).items(): + if key in observations: + by_response.setdefault(rid, set()).add(observations[key]) + return {rid: [{"host": host, "repository": repo, "branch": branch, + "candidate_tasks": sorted(heads.get((host, repo, branch), ()))} + for host, repo, branch in sorted(checkouts)] + for rid, checkouts in sorted(by_response.items())} + + +def _is_legacy_link(evidence): + return evidence == "t3" or evidence.startswith("t3:") + def read_placements(con, session_key: str) -> dict | None: - """An empty map leaves legacy Codex/Claude responses unplaced. + """Keep shared legacy PR usage unplaced wherever a PR advertises a head. - None delegates other assignment types and harnesses to the caller. + None delegates shared context and other assignment types to the caller. + Checkout diagnostics cannot grant ownership. """ - rows = con.execute( - "SELECT s.harness, a.evidence FROM sessions s" - " JOIN session_assignments a USING(session_key) WHERE s.session_key=?", - (session_key,)).fetchall() - if (len(rows) >= 2 and rows[0]["harness"] in ("claude", "codex") - and all(r["evidence"] == "t3" or r["evidence"].startswith("t3:") - for r in rows)): + session = con.execute("SELECT harness FROM sessions WHERE session_key=?", + (session_key,)).fetchone() + if session is None or session["harness"] not in CALL_FOLLOWS_RESPONSE: + return None + tasks = _session_tasks(con, session_key) + if (len(tasks) >= 2 and all(_is_legacy_link(row["evidence"]) for row in tasks) + and _task_heads(con, [row["task_id"] for row in tasks])): return {} return None @@ -30,8 +212,31 @@ def read_placements(con, session_key: str) -> dict | None: place_session = read_placements +def observe_new_checkouts(con, events) -> None: + """Capture diagnostics only for events inserted from new native records.""" + roots = {} + observations = {} + for event_id, target in events: + for digest, path in _path_keys(target): + observations[event_id, digest] = _checkout(path, roots) + if not observations: + return + # The native import committed before running Git. An interruption can + # leave a gap, which later imports cannot fill from a reused checkout. + with con: + con.execute( + "CREATE TABLE IF NOT EXISTS event_checkouts(" + " event_id INTEGER NOT NULL REFERENCES events(id) ON DELETE CASCADE," + " path_digest BLOB NOT NULL, host TEXT, repository TEXT, branch TEXT," + " PRIMARY KEY(event_id,path_digest))") + con.executemany( + "INSERT OR IGNORE INTO event_checkouts(event_id,path_digest,host,repository,branch)" + " SELECT ?,?,?,?,? WHERE EXISTS(SELECT 1 FROM events WHERE id=?)", + ((*key, *checkout, key[0]) for key, checkout in observations.items())) + + def record_shared_checkouts(con) -> int: - """Return the legacy T3 sync counter.""" + """Return the T3 sync counter. Native import records checkout diagnostics.""" return con.execute( "SELECT COUNT(*) FROM (SELECT 1 FROM session_assignments" " GROUP BY session_key HAVING COUNT(*) > 1)").fetchone()[0] diff --git a/tests/test_placement.py b/tests/test_placement.py index eafd150..54f2145 100644 --- a/tests/test_placement.py +++ b/tests/test_placement.py @@ -87,15 +87,26 @@ def test_first_import_after_path_reuse_leaves_claude_call_unplaced(self): _git("-C", root, "checkout", "-q", "-b", "fix/b") _git("-C", root, "remote", "set-url", "origin", "git@github.com:o/beta.git") self._assign(key, "o/alpha#1") - # Late link and replay cannot use the new checkout to place the old call. - with patch.object(subprocess, "run", side_effect=AssertionError("import ran Git")): - self.assertEqual(import_claude_file(self.con, path)["malformed"], 0) - self.assertEqual(self.con.execute( - "SELECT COUNT(*) FROM events WHERE family='tool_call'").fetchone()[0], 1) - self._assign(key, "o/beta#2") - self.assertEqual(placement.record_shared_checkouts(self.con), 1) + self.assertEqual(import_claude_file(self.con, path)["malformed"], 0) + self.assertEqual(self.con.execute( + "SELECT COUNT(*) FROM events WHERE family='tool_call'").fetchone()[0], 1) + observed = {"claude:before": [{"host": "github.com", "repository": "o/beta", + "branch": "fix/b", "candidate_tasks": []}]} + self.assertEqual(placement.checkout_observations(self.con, key), observed) + self._assign(key, "o/beta#2") + self.assertEqual(placement.record_shared_checkouts(self.con), 1) + _git("-C", root, "checkout", "-q", "fix/a") + _git("-C", root, "remote", "set-url", "origin", "git@github.com:o/alpha.git") + # Replaying after reuse never changes what was first observed. + with patch.object(subprocess, "run", side_effect=AssertionError("replay ran Git")): self.assertEqual(import_claude_file(self.con, path, full=True)["malformed"], 0) self._assert_unplaced(self.con, ["claude:before"]) + observed["claude:before"][0]["candidate_tasks"] = ["o/beta#2"] + shutil.rmtree(root) + with closing(db.connect_read_only(self.db_path)) as ro, patch.object( + subprocess, "run", side_effect=AssertionError("report ran Git")): + self.assertEqual(placement.checkout_observations(ro, key), observed) + self._assert_unplaced(ro, ["claude:before"]) def test_codex_session_git_and_literal_pr_target_leave_call_unplaced(self): key = "codex:target" @@ -126,7 +137,7 @@ def test_codex_session_git_and_literal_pr_target_leave_call_unplaced(self): self.assertEqual(import_codex_file(self.con, path)["events_inserted"], 1) self._assert_unplaced(self.con, ["codex:target-r"]) - def test_old_live_git_tables_cannot_credit_a_response_in_read_only_reports(self): + def test_old_and_hostless_observations_stay_out_of_diagnostics_and_totals(self): key = "claude:s" db.upsert_session(self.con, key, "claude", "s", self.source) for task in ("o/alpha#1", "o/beta#2"): @@ -148,7 +159,7 @@ def test_old_live_git_tables_cannot_credit_a_response_in_read_only_reports(self) self.con.execute("INSERT INTO response_checkouts VALUES(?,?,'r0','github.com','o/alpha','fix/a')", (event.lastrowid, digest)) self.con.execute("CREATE TABLE event_checkouts(event_id,path_digest,host,repository,branch)") - self.con.execute("INSERT INTO event_checkouts VALUES(?,?,'github.com','o/alpha','fix/a')", + self.con.execute("INSERT INTO event_checkouts VALUES(?,?,NULL,'o/alpha','fix/a')", (event.lastrowid, digest)) self.con.commit() shutil.rmtree(root) @@ -156,6 +167,7 @@ def test_old_live_git_tables_cannot_credit_a_response_in_read_only_reports(self) subprocess, "run", side_effect=AssertionError("report ran Git")): statements = [] ro.set_trace_callback(statements.append) + self.assertEqual(placement.checkout_observations(ro, key), {}) self._assert_unplaced(ro, ["r0"]) self.assertTrue(ro.in_transaction) self.assertEqual({sql.split()[0].upper() for sql in statements} @@ -169,6 +181,44 @@ def test_non_legacy_assignments_and_unsupported_harness_keep_caller_behavior(sel self._assign(key, "o/beta#2") self.assertIsNone(placement.read_placements(self.con, key)) + def test_shared_links_without_pr_heads_stay_context(self): + key = "claude:no-head" + db.upsert_session(self.con, key, "claude", "no-head", self.source) + for task in ("o/alpha#1", "o/beta#2"): + self._assign(key, task) + self.con.execute("UPDATE t3_links SET head_branch=NULL") + self.assertIsNone(placement.read_placements(self.con, key)) + + def test_diagnostics_keep_same_head_candidates_separate_by_forge(self): + key = "codex:placement-review" + hosted_root = self.checkouts["beta"] + _git("-C", hosted_root, "checkout", "-q", "-b", "fix/a") + _git("-C", hosted_root, "remote", "set-url", "origin", + "https://forge.example/o/alpha.git") + path, _ = self._continuation_files("forge") + import_codex_file(self.con, path) + # PR links can arrive after the native import. Same-head PRs on one + # forge remain visible as multiple candidates, without task credit. + self._assign(key, "o/alpha#1") + for host, number, task in (("github.com", 3, "o/alpha#3"), + ("forge.example", 1, "forge.example/o/alpha#1")): + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (task,)) + self._assign(key, task) + self.con.execute( + "INSERT INTO t3_links(thread_id,kind,host,repository,number,url,head_branch)" + " VALUES('t','pr',?,'o/alpha',?,?,'fix/a')", + (host, number, f"https://{host}/o/alpha/pull/{number}")) + self.assertEqual(placement.checkout_observations(self.con, key), { + "codex:r1": [{"host": "github.com", "repository": "o/alpha", + "branch": "fix/a", "candidate_tasks": ["o/alpha#1", "o/alpha#3"]}], + "codex:r2": [{"host": "forge.example", "repository": "o/alpha", + "branch": "fix/a", "candidate_tasks": ["forge.example/o/alpha#1"]}], + }) + for task in ("o/alpha#1", "o/alpha#3", "forge.example/o/alpha#1"): + result = report.task_report(self.con, task, schedule=SCHEDULE) + self.assertEqual(result["measured"]["unplaced_responses"], ["codex:r1", "codex:r2"]) + self.assertEqual(result["total_cost"]["responses"], 0) + def test_repeated_usage_keeps_the_first_response_position(self): alpha = self.checkouts["alpha"] beta = self.checkouts["beta"] From 53729b2d3ce2aaefdf72f7a32a6261704272f6d5 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 20:11:31 +0100 Subject: [PATCH 24/44] wip: distinguish non-GitHub issue and PR task identities Requirements and who asked: #105 R4 calls for distinct outcome accounting and historical task links. Deleted: no new task tables, CLI option, or inferred manual-capture migration. Bottleneck: the adapter discarded kind before ledger key lookup. Checked myself: Chromeria TrackingReference and purposeScopesEqual at 502c86c92c, both import orders with Codex and T3 fixtures, task show and publish dry-run, retained-snapshot replay and historical checkout diagnostics. --- README.md | 6 +- agent_observer/adapters/t3.py | 19 ++--- agent_observer/adapters/t3_purpose.py | 27 +++++-- agent_observer/placement.py | 9 ++- docs/contracts.md | 3 +- tests/test_placement.py | 11 ++- tests/test_t3_purpose.py | 100 ++++++++++++++++++++++++-- 7 files changed, 154 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 3f8b630..d15747f 100644 --- a/README.md +++ b/README.md @@ -517,7 +517,11 @@ Intervention text, problem lines and session attributes stay on this machine: For a Chromeria run with a declared Issue or PR purpose, use its reference as the task ID. For example, `agent-observer task show --task owner/repo#12 --json` lists the native responses joined to that purpose, even before a delivery PR -exists. The `native_purpose` section identifies each run, the input that joins +exists. On hosts other than github.com, use `forge.example/owner/repo/issue#12` +or `forge.example/owner/repo/pr#12`. Historical IDs such as +`forge.example/owner/repo#12` remain available for earlier captures. Observer +keeps those captures under the original ID because they recorded no kind. +The `native_purpose` section identifies each run, the input that joins a response to it, delivery PRs, provider counter checks, and gaps in coverage. A planner serving two Issues can have responses for each in the same session. For Grok, a session update can connect the prompt index to the completion ID. diff --git a/agent_observer/adapters/t3.py b/agent_observer/adapters/t3.py index 88deee9..2a096db 100644 --- a/agent_observer/adapters/t3.py +++ b/agent_observer/adapters/t3.py @@ -25,7 +25,7 @@ through their turn-start uuids in ``submissions``. - legacy thread trees: child ids of the form ``sub..`` (nesting allowed) group under their root. Every PR or Issue linked - anywhere in a tree becomes one task (``#``); every native + anywhere in a tree becomes one task (host and kind qualify non-GitHub keys); every native session in the tree is wholly bound to every tree task through ``session_assignments``. A one-link tree attributes exclusively; a multi-link tree lands in the shared joint bucket under the existing @@ -318,11 +318,14 @@ def _valid_id(value) -> str | None: def _valid_link(host, repository, number, url) -> tuple | None: - if not isinstance(host, str) or not host or len(host) > 253: + if not isinstance(host, str) or not host or "/" in host or len(host) > 253: return None if not isinstance(repository, str) or not repository \ or len(repository) > 200 or "/" not in repository: return None + # A GitHub link must not impersonate a host-prefixed task ID. + if host.lower() == "github.com" and repository.count("/") != 1: + return None if isinstance(number, bool) or not isinstance(number, int) or number <= 0: return None if not isinstance(url, str) or not url.startswith("https://") \ @@ -1235,16 +1238,15 @@ def _bind_trees(con: sqlite3.Connection, threads: dict, bound = 0 wanted: set = set() for root, root_links in tree_links.items(): - seen: dict[tuple, dict] = {} + seen: dict[str, dict] = {} for link in root_links: - seen.setdefault((link["host"], link["repository"], link["number"]), link) - for (host, repository, number), link in sorted(seen.items()): - task_id = t3_purpose.task_id(con, host, repository, number) + seen.setdefault(t3_purpose.task_id(con, link), link) + for task_id, link in sorted(seen.items()): cur = con.execute( "INSERT OR IGNORE INTO tasks(task_id, project, title," " issue_url, origin, created_at)" " VALUES(?,?,?,?,?,?)", - (task_id, repository, task_id, link["url"], HARNESS, + (task_id, link["repository"], task_id, link["url"], HARNESS, db.now())) tasks += cur.rowcount if task_id in disputed_tasks: @@ -1334,8 +1336,7 @@ def _write_outcomes(con: sqlite3.Connection, links: list) -> int: """ per_task: dict[str, list] = {} for link in links: - per_task.setdefault( - t3_purpose.task_id(con, link["host"], link["repository"], link["number"]), []).append(link) + per_task.setdefault(t3_purpose.task_id(con, link), []).append(link) written = 0 for task_id in sorted(per_task): task = con.execute("SELECT origin FROM tasks WHERE task_id=?", diff --git a/agent_observer/adapters/t3_purpose.py b/agent_observer/adapters/t3_purpose.py index 1f0313c..906c26a 100644 --- a/agent_observer/adapters/t3_purpose.py +++ b/agent_observer/adapters/t3_purpose.py @@ -114,9 +114,10 @@ def _reference(value): return dict(host=host.lower(), repository=repo.lower(), kind=kind, number=n) -def task_id(con, host, repository, number): - prefix = "" if host.lower() == "github.com" else host.lower() + "/" - canonical = f"{prefix}{repository.lower()}#{number}" +def task_id(con, ref): + host, repo = ref["host"].lower(), ref["repository"].lower() + coordinate = repo if host == "github.com" else f"{host}/{repo}/{ref['kind']}" + canonical = f"{coordinate}#{ref['number']}" if con.execute("SELECT 1 FROM tasks WHERE task_id=?", (canonical,)).fetchone(): return canonical # Existing GitHub links used the repository's original capitalization. @@ -132,7 +133,7 @@ def _url(ref): def _task(con, ref): - key = task_id(con, ref["host"], ref["repository"], ref["number"]) + key = task_id(con, ref) con.execute("INSERT OR IGNORE INTO tasks(task_id,project,title,issue_url,origin,created_at)" " VALUES(?,?,?,?, 't3',?)", (key, ref["repository"], key, _url(ref), db.now())) return key @@ -689,6 +690,23 @@ def _source_tables(con, path): con.execute(f"DELETE FROM {source} WHERE source_path=?", (path,)) +def _upgrade_retained_run_keys(con): + # Other source files may have rotated away. A run retained its full + # reference, and only a resolved segment proved it had that run's purpose. + # Old delivery rows retained the delivery PR but lost the purpose kind. + for row in con.execute(""" + SELECT DISTINCT host,repository,kind,number,task_id FROM t3_source_runs + WHERE host <> 'github.com' AND task_id = host || '/' || repository || '#' || number + COLLATE NOCASE""").fetchall(): + new = _task(con, row) + args = (new, row["task_id"], row["kind"]) + con.execute("""UPDATE t3_source_segments AS s SET task_id=? + WHERE task_id=? AND EXISTS ( + SELECT 1 FROM t3_source_runs r WHERE r.source_path=s.source_path + AND r.run_id=s.run_id AND r.task_id=s.task_id AND r.kind=?)""", args) + con.execute("UPDATE t3_source_runs SET task_id=? WHERE task_id=? AND kind=?", args) + + def _materialize(con, table): mirror, source = f"t3_purpose_{table}", f"t3_source_{table}" info = con.execute(f"PRAGMA table_info({mirror})").fetchall() @@ -763,6 +781,7 @@ def refresh(con, native, tables): con.execute("CREATE INDEX IF NOT EXISTS t3_purpose_inputs_native" " ON t3_purpose_inputs(session_key,native_id)") con.execute("CREATE INDEX IF NOT EXISTS t3_purpose_inputs_run ON t3_purpose_inputs(run_id)") + _upgrade_retained_run_keys(con) aware = _deliveries(snapshot, native, tables) runs = _runs(snapshot, native, tables) if runs: diff --git a/agent_observer/placement.py b/agent_observer/placement.py index 3e95c4e..55f3a12 100644 --- a/agent_observer/placement.py +++ b/agent_observer/placement.py @@ -72,11 +72,18 @@ def _task_heads(con, task_ids): for task in task_ids: coordinate, separator, number = task.rpartition("#") parts = coordinate.lower().split("/") + historical_host_key = len(parts) == 3 + if len(parts) == 4 and parts[-1] == "pr": + parts.pop() if not separator or len(parts) not in (2, 3): continue - # T3 task IDs omit the host for GitHub and prefix it for other forges. + # Three components also cover historical host-prefixed task IDs. host = parts[0] if len(parts) == 3 else "github.com" repo = "/".join(parts[-2:]) + if historical_host_key and con.execute( + "SELECT 1 FROM t3_links WHERE kind='issue' AND host=? COLLATE NOCASE" + " AND repository=? COLLATE NOCASE AND number=? LIMIT 1", (host, repo, number)).fetchone(): + continue # This key could refer to the Issue. for row in con.execute( "SELECT DISTINCT head_branch FROM t3_links WHERE kind='pr'" " AND host=? COLLATE NOCASE AND repository=? COLLATE NOCASE" diff --git a/docs/contracts.md b/docs/contracts.md index f5a4b55..ac23611 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -537,7 +537,8 @@ re-read every sync; workload bindings are durable ledger rows. and interrupt verdicts fail closed; unlisted records (typed prompts, Router `sdk-cli` workers) never move; unknown stays unknown. - Legacy thread trees: `sub..` ids (nesting allowed) group under - their root. Each linked PR or Issue becomes one `repo#N` task + their root. Each linked PR or Issue becomes one task (on github.com, + `owner/repo#N`; elsewhere, `host/owner/repo/issue#N` or `host/owner/repo/pr#N`) (`origin='t3'`); every ledger session in the tree (cursor sessions plus Claude subagent children plus rotated sessions found by turn uuid) binds whole to every tree task as historical session context. A thread link alone cannot place a response. diff --git a/tests/test_placement.py b/tests/test_placement.py index 54f2145..c42d049 100644 --- a/tests/test_placement.py +++ b/tests/test_placement.py @@ -208,12 +208,21 @@ def test_diagnostics_keep_same_head_candidates_separate_by_forge(self): "INSERT INTO t3_links(thread_id,kind,host,repository,number,url,head_branch)" " VALUES('t','pr',?,'o/alpha',?,?,'fix/a')", (host, number, f"https://{host}/o/alpha/pull/{number}")) + for kind in ("pr", "issue"): + task = f"forge.example/o/alpha/{kind}#1" + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (task,)) + self._assign(key, task) self.assertEqual(placement.checkout_observations(self.con, key), { "codex:r1": [{"host": "github.com", "repository": "o/alpha", "branch": "fix/a", "candidate_tasks": ["o/alpha#1", "o/alpha#3"]}], "codex:r2": [{"host": "forge.example", "repository": "o/alpha", - "branch": "fix/a", "candidate_tasks": ["forge.example/o/alpha#1"]}], + "branch": "fix/a", "candidate_tasks": ["forge.example/o/alpha#1", + "forge.example/o/alpha/pr#1"]}], }) + self.con.execute("INSERT INTO t3_links(thread_id,kind,host,repository,number,url)" + " VALUES('t','issue','forge.example','o/alpha',1,'https://forge.example/o/alpha/issues/1')") + self.assertEqual(placement.checkout_observations(self.con, key)["codex:r2"][0]["candidate_tasks"], + ["forge.example/o/alpha/pr#1"]) for task in ("o/alpha#1", "o/alpha#3", "forge.example/o/alpha#1"): result = report.task_report(self.con, task, schedule=SCHEDULE) self.assertEqual(result["measured"]["unplaced_responses"], ["codex:r1", "codex:r2"]) diff --git a/tests/test_t3_purpose.py b/tests/test_t3_purpose.py index b3b32c8..ab84393 100644 --- a/tests/test_t3_purpose.py +++ b/tests/test_t3_purpose.py @@ -4,7 +4,7 @@ import sqlite3 from pathlib import Path -from agent_observer import report +from agent_observer import publish, report from agent_observer.adapters import grok, t3 from tests.helpers import LedgerCase from tests.test_t3_v2 import write_v2 @@ -92,11 +92,103 @@ def test_literal_inputs_and_deliveries_survive_without_local_sessions(self): self.assertEqual(self.values("SELECT session_key FROM t3_purpose_sessions WHERE run_id='b'"), [("codex:historic-codex",)]) self.assertEqual(self.values("SELECT task_id FROM tasks ORDER BY task_id"), [ - ("example/project#7",), ("git.example.org/example/project#7",)]) + ("example/project#7",), ("git.example.org/example/project/issue#7",)]) self.assertEqual(self.values("SELECT task_id,url FROM t3_purpose_deliveries"), [ ("example/project#7", "https://github.com/example/project/pull/99")]) self.assertNotIn("private sentence", "\n".join(self.con.iterdump())) + def _check_separate_number_spaces(self, kinds): + self.sync("codex-mini.jsonl") + for table in ("runs", "run_attempts", "provider_turns"): + self.native.execute(f"DELETE FROM {PREFIX}{table}") + host, repo = "forge.example:8443", "example/project" + base = f"https://{host}/{repo}" + issue = dict(REF, host=host) + delivery = dict(version=1, purpose=issue, pullRequest=dict(issue, kind="pr"), declaredAt=TIME) + for kind in kinds: + turn = "turn-mini-aaa" if kind == "issue" else "turn-mini-bbb" + self.run_turn(kind, "codex", dict(PURPOSE, scope=dict(type="single", reference=dict(issue, kind=kind))), + [dict(version=1, kind="turn", nativeId=turn, validation="codex_turn_started")]) + self.native.execute(f"UPDATE {PREFIX}run_attempts SET payload_json=json_set(" + "payload_json,'$.nativeThreadId','sess-fixture-mini-01')") + self.assertEqual(self.refresh()["failed"], []) + self.native.execute(f"UPDATE {PREFIX}threads SET payload_json=?", + (json.dumps(dict(id="t", purposeDeliveries=[delivery])),)) + self.native.execute("CREATE TABLE projection_thread_pull_requests(thread_id,host,repository," + "number,url,source,linked_at,snapshot_json)") + self.native.execute("CREATE TABLE fork_thread_issue_links(thread_id,host,repository,number," + "url,source,linked_at)") + self.native.execute("INSERT INTO projection_thread_pull_requests VALUES('t',?,?,7,?," + "'agent',?,?)", (host, repo, base + "/pull/7", TIME, '{"state":"merged"}')) + self.native.execute("INSERT INTO fork_thread_issue_links VALUES('t',?,?,7,?,'agent',?)", + (host, repo, base + "/issues/7", TIME)) + # A malformed GitHub navigation key must not mark the private Issue complete. + self.native.execute("INSERT INTO projection_thread_pull_requests VALUES('t','github.com',?,7,?," + "'agent',?,?)", (f"{host}/{repo}/issue", "https://github.com/o/p/pull/7", + TIME, '{"state":"merged"}')) + self.assertEqual(self.refresh()["failed"], []) + expected = {"issue": ["codex:resp-mini-001", "codex:resp-mini-002"], + "pr": ["codex:resp-mini-003"]} + for kind in kinds: + key = f"{host}/{repo}/{kind}#7" + rep = report.task_report(self.con, key) + self.assertEqual(rep["measured"]["attributed_responses"], expected[kind]) + native = rep["native_purpose"] + self.assertEqual([r["kind"] for r in native["runs"]], [kind]) + self.assertEqual([r["url"] for r in native["deliveries"]], + [base + "/pull/7"] if kind == "issue" else []) + self.assertEqual(rep["acceptance_state"], "unknown" if kind == "issue" else "complete") + body = publish.render(publish.summarize(self.con, set(), key, task_id=key)) + self.assertNotIn(host, body) + self.assertNotIn(repo, body) + self.assertIn("Outcome: reference withheld", body) + self.assertEqual(self.values("SELECT * FROM session_assignments"), []) + + def test_issue_then_pr_on_same_forge_coordinate(self): + self._check_separate_number_spaces(("issue", "pr")) + + def test_pr_then_issue_with_old_manual_capture(self): + self._check_separate_number_spaces(("pr", "issue")) + old = "forge.example:8443/example/project#7" + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (old,)) + self.con.execute("INSERT INTO assignments(user_message_id,task_id,created_at)" + " VALUES('codex:msg-mini-sub-01',?,0)", (old,)) + self.assertEqual(self.refresh()["failed"], []) + for key in (old, "forge.example:8443/example/project/issue#7"): + rep = report.task_report(self.con, key) + self.assertEqual(rep["measured"]["attributed_responses"], []) + self.assertEqual(rep["measured"]["unplaced_responses"], ["codex:resp-mini-001", "codex:resp-mini-002"]) + self.assertEqual(self.values("SELECT task_id FROM assignments"), [(old,)]) + + def test_rotated_snapshot_upgrades_only_retained_typed_evidence(self): + self._check_separate_number_spaces(("issue", "pr")) + # Recreate the shape written before the upgrade. The old delivery row + # retained the destination PR and no kind for its originating purpose. + old = "forge.example:8443/example/project#7" + url = "https://forge.example:8443/example/project/pull/7" + self.con.execute("INSERT INTO tasks(task_id,issue_url,created_at) VALUES(?,?,0)", (old, url)) + self.con.execute("UPDATE t3_source_runs SET task_id=?", (old,)) + self.con.execute("UPDATE t3_source_deliveries SET task_id=?", (old,)) + self.con.execute("DELETE FROM outcomes WHERE task_id LIKE 'forge.example:%'") + self.con.execute("DELETE FROM tasks WHERE task_id LIKE 'forge.example:%/%/%/%'") + for run in ("issue", "pr", None): + self.con.execute("INSERT INTO t3_source_segments(source_path,thread_id,owner_id,segment_id,run_id,task_id)" + " VALUES(?,'t','owner',?,?,?)", (self.path, run or "unresolved", run, old)) + other = write_v2(os.path.join(self.tmp.name, "other.sqlite")) + for _ in range(2): + self.assertEqual(t3.sync(self.con, source=other)["failed"], []) + for kind in ("issue", "pr"): + key = f"forge.example:8443/example/project/{kind}#7" + native = report.task_report(self.con, key)["native_purpose"] + self.assertEqual([r["kind"] for r in native["runs"]], [kind]) + self.assertEqual(native["deliveries"], []) + self.assertEqual(self.con.execute("SELECT task_id FROM t3_purpose_segments WHERE segment_id=?", + (kind,)).fetchone()[0], key) + historical = report.task_report(self.con, old) + self.assertEqual(historical["task"]["issue_url"], url) + self.assertEqual([d["url"] for d in historical["native_purpose"]["deliveries"]], [url]) + self.assertEqual(self.values("SELECT task_id FROM t3_purpose_segments WHERE run_id IS NULL"), [(old,)]) + def test_corrupt_joins_and_unvalidated_grok_stay_gaps(self): self.native.execute(f"UPDATE {PREFIX}provider_turns SET thread_id='other' WHERE run_attempt_id='attempt-a'") self.native.execute(f"""UPDATE {PREFIX}provider_turns SET payload_json=json_set( @@ -122,7 +214,7 @@ def ingest(): (root / "updates.jsonl").write_text("\n".join(records) + "\n") grok.import_grok_session(self.con, str(root), full=True) def membership(): - return report.task_report(self.con, "git.example.org/example/project#7")["native_purpose"]["membership"] + return report.task_report(self.con, "git.example.org/example/project/issue#7")["native_purpose"]["membership"] frame(dict(sessionUpdate="turn_completed", prompt_id="done")) frame(dict(sessionUpdate="tool_call", toolCallId="call"), promptId="done") @@ -139,7 +231,7 @@ def membership(): other = sqlite3.connect(other_path) self.addCleanup(other.close) self.native.backup(other) - task = "git.example.org/example/project#7" + task = "git.example.org/example/project/issue#7" self.con.execute("INSERT INTO session_assignments VALUES(?,?,'capture',1)", ("grok:" + sid, task)) other.execute(f"""UPDATE {PREFIX}runs SET payload_json=json_set( payload_json,'$.purpose.scope.reference.number',8) WHERE run_id='g'""") From cd7828af9a6b0309ff55e79cf1391dd6de0b84e9 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 20:17:05 +0100 Subject: [PATCH 25/44] wip: reconcile task trace and cost with literal response ownership Issue #105, R4 consumer component. Keep disputed Claude ancestry unplaced under explicit capture. Connect Claude events and OpenCode parts to their literal responses and use those edges for task trace and phase activity. Keep navigation-only links out of Router and joint capture totals. Requirements and who asked: the Issue #105 integration owner requested the four response ownership fixes from R4. Deleted: display-turn attribution for message-owned events and shared billing inferred from navigation. Bottleneck: reports and trace lost native ancestry or discarded the link from an event to its measured response. Checked myself: five R4 assertions failed on af784d6. On this component, 229 isolated tests passed. CLI task show and trace selected one Claude call on A, zero on B, and five OpenCode calls on the admitted input. Proof command (bash): python -m unittest tests.test_{outcome,native_response,opencode,claude,claude_queue,claude_queue_binding,t3_purpose,capture,router,t3,close_loop,phase_pricing,pr_checks_pending,schema3} TMPDIR, T3CODE_HOME and GIT_CEILING_DIRECTORIES pointed at disposable fixture storage. Full integration proof, private replay and independent exact-head review belong to the parent. --- agent_observer/adapters/claude.py | 45 +++++++-- agent_observer/adapters/opencode.py | 122 ++++++++++-------------- agent_observer/native_response.py | 47 ++++++++++ agent_observer/outcome.py | 109 ++++++++++++++-------- agent_observer/report.py | 70 +++++++------- tests/test_outcome.py | 139 ++++++++++++++++++++++++++-- 6 files changed, 372 insertions(+), 160 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index f4c84b2..6c2f8a7 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -106,7 +106,7 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 6 # Replay UUID ancestry from existing sources. +_IMPORT_VERSION = 7 # Replay literal event-to-message edges from existing sources. def _ensure_native_kinds(con) -> None: @@ -312,6 +312,7 @@ def __init__(self, con, src: JsonlSource, stats: dict): self.last_ts = None self.turn = None self.pending: dict = {} + self.message_events = [] # Message ids whose native final block (stop_reason) has been seen, # either earlier in this import or in the already-imported file # prefix. A row is updated while its message streams; once final, @@ -335,6 +336,8 @@ def event(self, family, native_id, ordinal, ts, **kw): checkout_events=self.checkout_events if self.first_new_ordinal is not None and ordinal >= self.first_new_ordinal else None, **kw) + if family in {"tool_call", "assistant_message"}: + self.message_events.append((family, native_id)) def import_claude_file(con: sqlite3.Connection, path: str, @@ -389,6 +392,7 @@ def import_claude_file(con: sqlite3.Connection, path: str, _ensure_native_kinds(con) _seed_queue_identity(r) _prepare_ancestry(r) + native_response.prepare_events(con, src.source_id, replace=not src.incremental) # Durable per-response finality is authoritative for accepted final # rows. It covers copied sources, full reimports and incremental # appends. The file prefix is never authority on its own, so a malformed @@ -416,6 +420,7 @@ def import_claude_file(con: sqlite3.Connection, path: str, line) continue try: + r.message_events.clear() _ingest(r, obj, ordinal) _record_ancestry(r, obj) if obj.get("type") == "queue-operation": @@ -1088,7 +1093,7 @@ def _prepare_ancestry(r): def _record_ancestry(r, obj): uuid = native_response.identifier(obj.get("uuid")) - if (not uuid or not r.native_session or obj.get("sessionId") != r.native_session + if (not r.native_session or obj.get("sessionId") != r.native_session or (obj.get("agentId") and obj["agentId"] != r.agent_id)): return parent = native_response.identifier(obj.get("parentUuid")) @@ -1113,6 +1118,8 @@ def _record_ancestry(r, obj): mid = native_response.identifier(message.get("id")) if mid and message.get("model") != "": response_id = f"{HARNESS}:{mid}" + for family, event_id in r.message_events: + native_response.record_event(r.con, r.src.source_id, r.session_key, family, event_id, response_id) elif kind == "attachment" and isinstance(obj.get("attachment"), dict): if obj["attachment"].get("type") == "queued_command": # A consumed queued input has its own identity. A missing identity @@ -1122,6 +1129,8 @@ def _record_ancestry(r, obj): return elif kind not in ("system", "progress"): return + if not uuid: + return r.con.execute("INSERT OR IGNORE INTO claude_response_ancestry" "(session_key,uuid,parent,input_id,response_id,source_id)" " VALUES(?,?,?,?,?,?)", @@ -1129,19 +1138,25 @@ def _record_ancestry(r, obj): input_id, response_id, r.src.source_id)) -def response_inputs(con, session_key): +def response_witnesses(con, session_key): """Resolve every UUID once, stopping each chain at its nearest native input. A missing parent or cycle leaves that chain unresolved. Multiple observed parents must all resolve, and competing inputs survive for the consumer. """ if not db._has_table(con, "claude_response_ancestry"): - return {} + return {}, set() parents, children, anchors, blocks = (defaultdict(set) for _ in range(4)) + seen, disputed = set(), set() for uuid, parent, input_id, response_id in con.execute( "SELECT DISTINCT uuid,parent,input_id,response_id FROM claude_response_ancestry" " WHERE session_key=?", (session_key,) ): + # DISTINCT collapses identical copies. Another row for the same + # UUID contradicts its parent, input identity or message identity. + if uuid in seen: + disputed.add(uuid) + seen.add(uuid) if input_id: anchors[uuid].add(input_id) elif parent: @@ -1149,6 +1164,14 @@ def response_inputs(con, session_key): children[parent].add(uuid) if response_id: blocks[response_id].add(uuid) + # Contradictory copies of any ancestor also dispute its descendants, + # even when a missing parent keeps the ordinary walk from reaching them. + pending = deque(disputed) + while pending: + for child in children.get(pending.popleft(), ()): + if child not in disputed: + disputed.add(child) + pending.append(child) # Process an interior node only after all its parents have resolved. ready = deque(uuid for uuid in anchors if uuid not in parents) resolved = set() @@ -1161,9 +1184,19 @@ def response_inputs(con, session_key): if not parents[child]: ready.append(child) results = {} + conflicts = set() for response_id, in con.execute("SELECT response_id FROM responses" " WHERE session_key=? AND is_overlap=0", (session_key,)): nodes = blocks.get(response_id) - if nodes and nodes <= resolved: + if not nodes: + continue + if nodes & disputed or (nodes & resolved and nodes - resolved): + conflicts.add(response_id) + if nodes <= resolved: results[response_id] = set.union(*(anchors[node] for node in nodes)) - return results + return results, conflicts + + +def response_inputs(con, session_key): + witnesses, conflicts = response_witnesses(con, session_key) + return {rid: ids for rid, ids in witnesses.items() if rid not in conflicts} diff --git a/agent_observer/adapters/opencode.py b/agent_observer/adapters/opencode.py index 4fccc8b..de1ce1d 100644 --- a/agent_observer/adapters/opencode.py +++ b/agent_observer/adapters/opencode.py @@ -14,6 +14,7 @@ from __future__ import annotations +from functools import partial import json import os import sqlite3 @@ -336,7 +337,7 @@ def _upsert_event(con: sqlite3.Connection, stats: dict, *, source_id: int, session_key: str, family: str, native_id, ordinal=None, ts=None, turn_id=None, name=None, target=None, status=None, duration_ms=None, size_bytes=None, truncated=None, - fingerprint=None, detail=None) -> None: + fingerprint=None, detail=None, response_id=None) -> None: """Insert one event under its natural key; mutable rows update in place. Rule 6 via agent_observer/privacy.py for every protected field: @@ -353,6 +354,8 @@ def _upsert_event(con: sqlite3.Connection, stats: dict, *, source_id: int, native = privacy.filter_native_id(family, native_id) if not native: raise ValueError(f"{family} event missing native identity") + if response_id: + native_response.record_event(con, source_id, session_key, family, native, response_id) safe_name = privacy.filter_event_name(family, name) safe_status = privacy.filter_event_status(family, status) safe_target = privacy.filter_target(target, family) or None @@ -410,7 +413,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, session_key = f"{HARNESS}:{sess_id}" msg_n, msg_m = _count_max(native, "message", sess_id) part_n, part_m = _count_max(native, "part", sess_id) - fp = fingerprint("native-parent-v1", sess.get("time_updated"), msg_m, part_m, msg_n, part_n) + fp = fingerprint("native-parent-and-parts-v2", sess.get("time_updated"), msg_m, part_m, msg_n, part_n) row = con.execute( "SELECT * FROM sources WHERE harness=? AND path=?", (HARNESS, src_path)).fetchone() @@ -502,6 +505,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, parsed_messages.append((index, msg, data)) roles[msg_id] = data.get("role") native_response.prepare(con, source_id, replace=True) + native_response.prepare_events(con, source_id, replace=True) ordinal = 0 for index, msg, data in parsed_messages: ordinal += 1 @@ -512,8 +516,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, for part in parts: ordinal += 1 _ingest_part(con, stats, identity, src_path, source_id, - session_key, sess, roles, part, ordinal, - privacy_stale=privacy_stale) + session_key, roles, part, ordinal) if sess.get("time_compacting") is not None: insert_event(con, stats, source_id=source_id, session_key=session_key, family="compaction", @@ -569,6 +572,7 @@ def _ingest_message(con, native, stats, identity, src_path, source_id, _upsert_event(con, stats, source_id=source_id, session_key=session_key, family="lifecycle", native_id=msg_id, ordinal=ordinal, ts=ts, + response_id=_assistant_id(roles, msg_id), name="turn_aborted" if error.get("name") == "MessageAbortedError" else "error", status="interrupted" if error.get("name") == "MessageAbortedError" else (str(code) if isinstance(code, int) and not isinstance(code, bool) else None), @@ -772,9 +776,14 @@ def _ingest_submission(con, stats, identity, src_path, source_id, stats["user_messages_inserted"] += 1 +def _assistant_id(roles, message_id): + if roles.get(message_id) == "assistant" and native_response.identifier(message_id): + return f"{HARNESS}:{message_id}" + return None + + def _ingest_part(con, stats, identity, src_path, source_id, session_key, - sess, roles, part, ordinal, - privacy_stale: bool = False) -> None: + roles, part, ordinal) -> None: raw = part.get("data") if isinstance(part, dict) else None part_id = part.get("id") if isinstance(part, dict) else None if raw is None: @@ -798,6 +807,8 @@ def _ingest_part(con, stats, identity, src_path, source_id, session_key, _oops(con, stats, src_path, ordinal, "missing_id", _record_line(raw, data)) return + event = partial(_upsert_event, con, stats, source_id=source_id, session_key=session_key, + response_id=_assistant_id(roles, part.get("message_id")), ordinal=ordinal, ts=ts) if ptype == "text": if roles.get(part.get("message_id")) != "assistant": return # User text is indexed once under its message id. @@ -814,25 +825,17 @@ def _ingest_part(con, stats, identity, src_path, source_id, session_key, (session_key, "assistant_message", native)).fetchone() if text or exists: excerpt = privacy.assistant_excerpt(text) - _upsert_event(con, stats, source_id=source_id, session_key=session_key, - family="assistant_message", native_id=part_id, - ordinal=ordinal, ts=ts, name="assistant_message", - size_bytes=len(text), fingerprint=text_hash(text), - detail={"excerpt": excerpt} if excerpt else None) + event(family="assistant_message", native_id=part_id, + name="assistant_message", + size_bytes=len(text), fingerprint=text_hash(text), + detail={"excerpt": excerpt} if excerpt else None) elif ptype == "tool": - _ingest_tool(con, stats, identity, src_path, source_id, - session_key, sess, roles, part, data, ordinal, ts, - line=_record_line(raw, data)) + _ingest_tool(con, stats, identity, src_path, event, data, ordinal, + line=_record_line(raw, data)) elif ptype == "patch": - _ingest_patch(con, stats, source_id, session_key, part, data, - ordinal, ts) + _ingest_patch(event, part, data) elif ptype == "compaction": - # Rule 6 via the core writer: closed name set. update=True lets a - # privacy-stale re-import repopulate a cleared row in place. - insert_event(con, stats, source_id=source_id, - session_key=session_key, family="compaction", - native_id=part_id, ordinal=ordinal, ts=ts, - name="compaction", update=privacy_stale) + event(family="compaction", native_id=part_id, name="compaction") elif isinstance(ptype, str) and ptype in _KNOWN_QUIET_PART_TYPES: # text, reasoning, step checkpoints and file data URLs carry no # ledger event: user text is handled per message, and file data, @@ -849,8 +852,7 @@ def _ingest_part(con, stats, identity, src_path, source_id, session_key, _record_line(raw, data)) -def _ingest_tool(con, stats, identity, src_path, source_id, session_key, - sess, roles, part, data, ordinal, ts, +def _ingest_tool(con, stats, identity, src_path, event, data, ordinal, line: str = "") -> None: # Native tool/call/skill names must be strings: dicts, lists, # booleans, numbers and other objects fall back to "unknown" and are @@ -872,27 +874,19 @@ def _ingest_tool(con, stats, identity, src_path, source_id, session_key, default=str)[:4000]) except (TypeError, ValueError): arg_fp = fingerprint(tool) - # Rule 6: the tool_call family keeps no detail; the message linkage - # some older imports stored is dropped rather than persisted. The name - # passes through privacy.filter_event_name inside _upsert_event, so - # free-text tool names never persist. - _upsert_event(con, stats, source_id=source_id, session_key=session_key, - family="tool_call", native_id=call_id, ordinal=ordinal, - ts=ts, name=tool[:200], target=target, - fingerprint=arg_fp, detail=None) + # The message identity belongs to the source witness. Tool detail stays empty. + event(family="tool_call", native_id=call_id, name=tool[:200], target=target, + fingerprint=arg_fp, detail=None) if status is None or ( isinstance(status, str) and status in _INCOMPLETE_TOOL_STATUSES): # No terminal result yet; a later snapshot must add it. pass elif status in ("completed", "error"): result_status = "ok" if status == "completed" else "error" - _upsert_event(con, stats, source_id=source_id, - session_key=session_key, family="tool_result", - native_id=call_id, ordinal=ordinal, ts=ts, - name=tool[:200], target=target, - status=result_status, duration_ms=_duration_ms(state), - size_bytes=_output_size(output), - detail=None) + event(family="tool_result", native_id=call_id, name=tool[:200], target=target, + status=result_status, duration_ms=_duration_ms(state), + size_bytes=_output_size(output), + detail=None) elif isinstance(status, str): _oops(con, stats, src_path, ordinal, "unknown_record", line) else: @@ -911,21 +905,15 @@ def _ingest_tool(con, stats, identity, src_path, source_id, session_key, # Rule 6: skill_read target holds only the validated skill # identifier, never the installed path. The file path lives # only in detail skill_path. - _upsert_event(con, stats, source_id=source_id, - session_key=session_key, family=family, - native_id=call_id, ordinal=ordinal, ts=ts, - name=os.path.basename(target)[:200], target=safe_skill, - status="ok", size_bytes=_output_size(output), - fingerprint=fingerprint(target), - detail={"skill": raw_skill, "skill_path": target}) + event(family=family, native_id=call_id, name=os.path.basename(target)[:200], target=safe_skill, + status="ok", size_bytes=_output_size(output), + fingerprint=fingerprint(target), + detail={"skill": raw_skill, "skill_path": target}) else: - _upsert_event(con, stats, source_id=source_id, - session_key=session_key, family=family, - native_id=call_id, ordinal=ordinal, ts=ts, - name=os.path.basename(target)[:200], target=target, - status="ok", size_bytes=_output_size(output), - fingerprint=fingerprint(target), - detail=None) + event(family=family, native_id=call_id, name=os.path.basename(target)[:200], target=target, + status="ok", size_bytes=_output_size(output), + fingerprint=fingerprint(target), + detail=None) if tool == "skill": raw_name = tool_input.get("name") if isinstance(raw_name, str) and raw_name: @@ -949,22 +937,15 @@ def _ingest_tool(con, stats, identity, src_path, source_id, session_key, # Rule 6: skill_invoke target holds only the validated skill # identifier; the installed SKILL.md path lives only in detail # skill_path when the native invocation supplies a directory. - _upsert_event(con, stats, source_id=source_id, - session_key=session_key, family="skill_invoke", - native_id=call_id, ordinal=ordinal, ts=ts, - name=safe_skill, target=safe_skill, - detail={"skill_path": skill_path} if skill_path else None) + event(family="skill_invoke", native_id=call_id, name=safe_skill, target=safe_skill, + detail={"skill_path": skill_path} if skill_path else None) if tool in ("edit", "write", "patch") and target: - _upsert_event(con, stats, source_id=source_id, - session_key=session_key, family="file_change", - native_id=call_id, ordinal=ordinal, ts=ts, - name=tool[:200], target=target, - fingerprint=fingerprint(tool, target), - detail=None) + event(family="file_change", native_id=call_id, name=tool[:200], target=target, + fingerprint=fingerprint(tool, target), + detail=None) -def _ingest_patch(con, stats, source_id, session_key, part, data, ordinal, - ts) -> None: +def _ingest_patch(event, part, data) -> None: digest = data.get("hash") files = data.get("files") file_list = files if isinstance(files, list) else [] @@ -986,8 +967,7 @@ def _ingest_patch(con, stats, source_id, session_key, part, data, ordinal, # Rule 6: the file_change family keeps only path lists, so an # arbitrary native hash is omitted, never coerced. The fingerprint # column keeps only our own fixed-format generated digest. - _upsert_event(con, stats, source_id=source_id, session_key=session_key, - family="file_change", native_id=part_id, - ordinal=ordinal, ts=ts, name="patch", target=target, - fingerprint=fingerprint("patch", digest, file_list), - detail={"paths": valid_paths} if valid_paths else None) + event(family="file_change", native_id=part_id, + name="patch", target=target, + fingerprint=fingerprint("patch", digest, file_list), + detail={"paths": valid_paths} if valid_paths else None) diff --git a/agent_observer/native_response.py b/agent_observer/native_response.py index 12e0880..288f29e 100644 --- a/agent_observer/native_response.py +++ b/agent_observer/native_response.py @@ -60,3 +60,50 @@ def inputs(con: sqlite3.Connection, session_key: str) -> dict[str, set[str]]: for response_id, turn_id in codex.legacy_response_inputs(con, session_key): found[response_id].add(turn_id) return dict(found) + + +def prepare_events(con, source_id, *, replace): + con.execute(""" + CREATE TABLE IF NOT EXISTS native_response_events ( + session_key TEXT NOT NULL, family TEXT NOT NULL, native_id TEXT NOT NULL, + response_id TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), + PRIMARY KEY(session_key, family, native_id, response_id, source_id) + ) WITHOUT ROWID""") + con.execute("CREATE INDEX IF NOT EXISTS native_response_event_source ON native_response_events(source_id)") + if replace: + con.execute("DELETE FROM native_response_events WHERE source_id=?", (source_id,)) + + +def record_event(con, source_id, session_key, family, native_id, response_id): + con.execute("INSERT OR IGNORE INTO native_response_events" + "(session_key,family,native_id,response_id,source_id) VALUES(?,?,?,?,?)", + (session_key, family, native_id, response_id, source_id)) + + +def event_responses(con, session_key): + """Return literal event associations, including competing copies and unmatched calls.""" + edges = defaultdict(set) + if db._has_table(con, "native_response_events"): + for family, native_id, rid in con.execute( + "SELECT DISTINCT family,native_id,response_id FROM native_response_events WHERE session_key=?", + (session_key,)): + edges[family, native_id].add(rid) + claude = session_key.startswith("claude:") + legacy_text = defaultdict(set) + if claude and db._has_table(con, "claude_response_ancestry"): + # Pre-event-edge ledgers still retain the UUID of each text block. + for source, uuid, rid in con.execute( + "SELECT a.source_id,a.uuid,a.response_id FROM claude_response_ancestry a " + "JOIN sources s ON s.id=a.source_id WHERE a.session_key=? AND a.response_id<>'' " + "AND s.claude_usage_version<7", (session_key,)): + legacy_text[source, uuid].add(rid) + for event, source, family, native_id in con.execute( + "SELECT id,source_id,family,native_id FROM events WHERE session_key=?", (session_key,)): + if claude and family == "assistant_message": + yield event, edges[family, native_id] | legacy_text[source, native_id.rpartition(":")[0]] + elif claude and family in {"tool_result", "permission", "skill_invoke", "file_change"}: + yield event, edges["tool_call", native_id] + elif claude and family in {"read", "skill_read"} and native_id.endswith(":read"): + yield event, edges["tool_call", native_id[:-5]] + else: + yield event, edges[family, native_id] diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index 49e4550..59bda76 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -4,6 +4,7 @@ from dataclasses import dataclass, field import json +from . import native_response from .db import _has_table @@ -34,12 +35,28 @@ def legacy_link(evidence): class Ownership: """Task ownership within the inspected sessions, with canonical witnesses kept separately.""" native: dict | None = None - # Response partitions are needed only where native and explicit scope meet. + # Explicit and native claims resolved against the same literal response. owners: dict = field(default_factory=dict) turns: set = field(default_factory=set) - claude_capture_turns: dict = field(default_factory=dict) + response_turns: dict = field(default_factory=dict) + literal_sessions: set = field(default_factory=set) + conflicts: set = field(default_factory=set) whole: set = field(default_factory=set) + def event_turns(self, con, key): + """Literal event partitions. None excludes, an empty set admits session scope only.""" + if key not in self.literal_sessions: + return + for event, responses in native_response.event_responses(con, key): + turns = None + if len(responses) <= 1: + rid = next(iter(responses), None) + turns = self.response_turns.get((key, rid)) + if key in self.whole and rid not in self.owners and rid not in self.conflicts: + # Whole-session capture includes events without a usage row. + turns = set() + yield event, turns + def evidence(con, task_id, scope): """Resolve report and event scope from the same native and explicit claims.""" @@ -53,6 +70,9 @@ def evidence(con, task_id, scope): "AND s.session_key IS NOT NULL AND s.turn_id IS NOT NULL", (task_id,))) if not _has_table(con, "t3_purpose_runs"): + for key in scope: + if key.startswith(("claude:", "opencode:")): + _session_ownership(con, key, task_id, {}, False, result, {}) return result runs = [dict(r) for r in con.execute( "SELECT * FROM t3_purpose_runs WHERE task_id=? ORDER BY run_id", (task_id,))] @@ -66,7 +86,6 @@ def evidence(con, task_id, scope): reference_conflict = len({r["kind"] for r in runs}) > 1 session_runs = {} members = {} - conflicts = set() for key in sorted(scope): by_run = dict(con.execute( "SELECT r.run_id, r.task_id FROM t3_purpose_sessions s " @@ -76,34 +95,34 @@ def evidence(con, task_id, scope): "SELECT DISTINCT s.run_id FROM t3_purpose_sessions s JOIN t3_source_runs x USING(run_id) " "LEFT JOIN t3_purpose_runs r USING(run_id) WHERE s.session_key=? AND r.run_id IS NULL", (key,)): by_run[run] = None - if not by_run: + if by_run: + session_runs[key] = sorted(by_run) + elif not key.startswith(("claude:", "opencode:")): continue - session_runs[key] = sorted(by_run) - _session_ownership(con, key, task_id, by_run, reference_conflict, result, members, conflicts) + _session_ownership(con, key, task_id, by_run, reference_conflict, result, members) if runs or deliveries or session_runs or disputed_runs: result.native = {"version": 1, "task_id": task_id, "runs": runs, "deliveries": deliveries, - "membership": members, "sessions": session_runs, "conflicting_responses": sorted(conflicts), + "membership": members, "sessions": session_runs, "conflicting_responses": sorted(result.conflicts), "conflicting_reference_kinds": reference_conflict, "conflicting_source_runs": disputed_runs} return result -def _session_ownership(con, key, task_id, by_run, reference_conflict, result, members, conflicts): - from . import native_response - +def _session_ownership(con, key, task_id, by_run, reference_conflict, result, members): by_input = defaultdict(set) - for run, native_id, turn, segment, validation in con.execute( - "SELECT run_id,native_id,provider_turn_id,segment_id,validation FROM t3_purpose_inputs " - "WHERE session_key=?", (key,)): - by_input[native_id].add((run, turn, segment, validation)) - if _has_table(con, "t3_source_inputs"): - for native_id, in con.execute( - "SELECT DISTINCT s.native_id FROM t3_source_inputs s WHERE s.session_key=? " - "AND NOT EXISTS (SELECT 1 FROM t3_purpose_inputs i " - "WHERE i.session_key=s.session_key AND i.native_id=s.native_id)", (key,)): - # A rejected identity still contradicts explicit or whole-session - # credit. Carry it through the same report and event filters. - by_input[native_id].add((None, None, None, "conflicting_snapshot")) + if by_run: + for run, native_id, turn, segment, validation in con.execute( + "SELECT run_id,native_id,provider_turn_id,segment_id,validation FROM t3_purpose_inputs " + "WHERE session_key=?", (key,)): + by_input[native_id].add((run, turn, segment, validation)) + if _has_table(con, "t3_source_inputs"): + for native_id, in con.execute( + "SELECT DISTINCT s.native_id FROM t3_source_inputs s WHERE s.session_key=? " + "AND NOT EXISTS (SELECT 1 FROM t3_purpose_inputs i " + "WHERE i.session_key=s.session_key AND i.native_id=s.native_id)", (key,)): + # A rejected identity still contradicts explicit or whole-session + # credit. Carry it through the same report and event filters. + by_input[native_id].add((None, None, None, "conflicting_snapshot")) whole = {r["task_id"] for r in con.execute( "SELECT task_id, evidence FROM session_assignments WHERE session_key=?", (key,)) if not legacy_link(r["evidence"])} @@ -124,16 +143,24 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me claimed_inputs[identity].add(owner) if turn: input_turns[identity].add(turn) + literal_messages = harness in {"claude", "opencode"} + if not by_run and not whole and not claimed_inputs: + return + if literal_messages: + result.literal_sessions.add(key) call_witnesses = set() disputed_completions = set() - if harness == "grok": + if harness == "claude": + from .adapters import claude + responses, disputed_completions = claude.response_witnesses(con, key) + elif harness == "grok": from .adapters import grok responses, call_witnesses, disputed_completions = grok.response_witnesses(con, key) else: responses = native_response.inputs(con, key) # In a contested whole session, only events on resolved turns can be # shown. Untagged events cannot be separated between the claimants. - exclusive = whole == {task_id} and set(by_run.values()) == {task_id} + exclusive = not by_run or (whole == {task_id} and set(by_run.values()) == {task_id}) prefix = key if harness == "grok" else harness blocked_turns = set() for native_id, candidates in by_input.items(): @@ -148,35 +175,35 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me exclusive = False for rid, display_turn in con.execute( "SELECT response_id,turn_id FROM responses WHERE session_key=? AND is_overlap=0", (key,)): - if rid in disputed_completions: - conflicts.add(rid) - blocked_turns.add(rid) + input_ids = responses.get(rid, set()) + if rid in disputed_completions or len(input_ids) > 1: + result.conflicts.add(rid) + blocked_turns.update((display_turn, rid)) + for identity in input_ids: + qualified = f"{prefix}:{identity}" + blocked_turns.update(input_turns[qualified]) + if harness == "codex": + blocked_turns.add(qualified) exclusive = False continue - input_ids = responses.get(rid, set()) identities = {f"{prefix}:{identity}" for identity in input_ids} candidates = {candidate for identity in input_ids for candidate in by_input.get(identity, ())} claims = whole.copy() for identity in identities: claims.update(claimed_inputs[identity]) - if not identities: + if not identities and not literal_messages: claims.update(claimed_turns[display_turn]) - if len(identities) > 1 and not candidates and claims - whole: - # Competing input witnesses cannot prove a captured turn. - conflicts.add(rid) - for identity in identities: - blocked_turns.update(input_turns[identity]) - exclusive = False - continue if not candidates: result.owners[rid] = claims if task_id in claims: turns = {t for identity in identities for t in input_turns[identity]} - if not turns and display_turn: + if literal_messages: + turns.update(identities) + elif not turns and display_turn: turns.add(display_turn) result.turns.update((key, t) for t in turns) - if harness == "claude": - result.claude_capture_turns[rid] = turns + if literal_messages: + result.response_turns[key, rid] = turns continue run, turn, segment, validation = next(iter(candidates)) @@ -196,12 +223,14 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me # display turn. Keep only literal events on that mixed turn. blocked_turns.add(display_turn) if disputed: - conflicts.add(rid) + result.conflicts.add(rid) exclusive = False continue result.owners[rid] = {owner} if owner else set() if owner == task_id: native_id, = input_ids + if literal_messages: + result.response_turns[key, rid] = identities if rid in call_witnesses: validation = "grok_tool_call" members[rid] = {"run_id": run, "session_key": key, "native_input_id": native_id, diff --git a/agent_observer/report.py b/agent_observer/report.py index 82ff20a..9700393 100644 --- a/agent_observer/report.py +++ b/agent_observer/report.py @@ -403,8 +403,9 @@ def _is_mcp_result(event) -> bool: def _phase_report(con, task_id, rows, whole, attempts, schedule, - unmeasured=frozenset(), native_sessions=(), native_turns=()): + unmeasured=frozenset(), native_sessions=(), ownership=None): from . import pricing, analysis + ownership = ownership or outcome.Ownership() by_turn, by_session = {}, {} def phase(value): @@ -416,7 +417,7 @@ def phase(value): return "review" return "unclassified" - for a in con.execute("SELECT s.turn_id,a.phase FROM assignments a JOIN user_messages s" + for a in con.execute("SELECT COALESCE(s.turn_id,s.native_id) AS turn_id,a.phase FROM assignments a JOIN user_messages s" " ON s.native_id=a.user_message_id WHERE a.task_id=?", (task_id,)): if a["turn_id"] and a["phase"]: by_turn.setdefault(a["turn_id"], set()).add(phase(a["phase"])) @@ -427,28 +428,36 @@ def phase(value): if a.get("session_key") in whole and a.get("harness") == "router": by_session.setdefault(a["session_key"], set()).add(phase(a.get("stage"))) - def selected(row): - if (row["session_key"] in native_sessions and row["session_key"] not in whole - and (row["session_key"], row["turn_id"]) not in native_turns): - return "unclassified" - labels = by_turn.get(row["turn_id"]) or by_session.get(row["session_key"]) or {"unclassified"} + def selected(row, literal_turns=None): + if literal_turns is None: + if (row["session_key"] in native_sessions and row["session_key"] not in whole + and (row["session_key"], row["turn_id"]) not in ownership.turns): + return "unclassified" + literal_turns = (row["turn_id"],) + labels = {label for turn in literal_turns for label in by_turn.get(turn, ())} + labels = labels or by_session.get(row["session_key"]) or {"unclassified"} return next(iter(labels)) if len(labels) == 1 else "mixed" groups = {} for row in rows: - groups.setdefault(selected(row), []).append(row) + literal_turns = ownership.response_turns.get((row["session_key"], row["response_id"])) + groups.setdefault(selected(row, literal_turns), []).append(row) activities = {} contributors: dict[str, dict[str, str | None]] = {} turns = {r["turn_id"] for r in rows if r["turn_id"]} # Exclusively owned whole sessions count even without responses (#127). for key in sorted({r["session_key"] for r in rows} | set(whole)): harness = _session_harness(con, key) + event_turns = dict(ownership.event_turns(con, key)) for event in con.execute("SELECT * FROM events WHERE session_key=?", (key,)): - if key in native_sessions: - owned = key in whole or (key, event["turn_id"]) in native_turns + literal_turns = event_turns.get(event["id"]) + if event["id"] in event_turns: + owned = literal_turns is not None + elif key in native_sessions: + owned = key in whole or (key, event["turn_id"]) in ownership.turns else: owned = key in whole or event["turn_id"] in turns - label = selected(event) if owned else "session context" + label = selected(event, literal_turns) if owned else "session context" # Capability comes from the event's own native session, never # from the importer that attributed it (Router). contributors.setdefault(label, {})[key] = harness @@ -560,12 +569,12 @@ def task_report(con: sqlite3.Connection, task_id: str, missing_submissions = [] sharing_tasks = set() legacy_shared = set() - conflicts = set(native["conflicting_responses"]) if native else set() + conflicts = ownership.conflicts for r in responses: if r["is_overlap"]: continue key, rid = r["session_key"], r["response_id"] - if native and key in native["sessions"]: + if rid in conflicts or rid in ownership.owners or (native and key in native["sessions"]): owners = ownership.owners.get(rid) if rid in conflicts or not owners: unplaced.append(dict(r)) @@ -589,9 +598,9 @@ def task_report(con: sqlite3.Connection, task_id: str, elif task_id in session_owners.get(key, ()): # Keep the existing whole-session pool when several records bind # the session and this response has no explicit capture. - if key in whole_shared or key in linked_tasks: + if key in whole_shared: shared.append(dict(r)) - sharing_tasks.update(session_owners[key] | prompt_owners[key] | linked_tasks.get(key, set())) + sharing_tasks.update(session_owners[key] | prompt_owners[key]) else: attributed.append(dict(r)) elif key in linked_tasks and (sub in assigned_anywhere or key in session_owners): @@ -703,7 +712,7 @@ def child_session(identity): diagnostics = _task_diagnostics(con, scope_keys, ownership.whole, task_turns) phases, activity_context, activity_context_coverage = _phase_report( con, task_id, attributed, ownership.whole - whole_shared, task_turn_rows, schedule, - unmeasured_attributed, native["sessions"] if native else (), ownership.turns) + unmeasured_attributed, native["sessions"] if native else (), ownership) def _resp_tuple(r) -> list: return [r.get("response_id"), r.get("harness"), r.get("model"), @@ -762,7 +771,7 @@ def _resp_tuple(r) -> list: snapshot = _snapshot_id(snapshot_payload) estimated = _pricing.price_scope(attributed, schedule) shared_estimated = _pricing.price_scope(shared, schedule) - billed_shared = [] if canonical else [r for r in shared if r["response_id"] not in legacy_shared] + billed_shared = [r for r in shared if r["response_id"] not in legacy_shared] total_estimated = _pricing.price_scope(attributed + billed_shared, schedule) unplaced_estimated = _pricing.price_scope(unplaced, schedule) for estimate in (estimated, shared_estimated, total_estimated, unplaced_estimated): @@ -994,28 +1003,17 @@ def timeline(con: sqlite3.Connection, task_id: str | None = None, if (not session_key or member["session_key"] == session_key) and (not turn_id or turn_id == (rid if member["session_key"].startswith("grok:") else member["session_key"].partition(":")[0] + ":" + member["native_input_id"]))} - conflicts = set(native["conflicting_responses"]) - for key in native["sessions"]: - if (not key.startswith("claude:") or (session_key and key != session_key) - or not _has_table(con, "claude_response_ancestry")): - continue - # Claude gives each text event the transcript UUID and block - # index. Its parent chain proves the response independently of - # the display turn that may have been retouched. - for event_id, rid in con.execute( - "SELECT DISTINCT e.id,a.response_id FROM events e JOIN claude_response_ancestry a " - "ON e.source_id=a.source_id AND e.session_key=a.session_key " - "AND a.uuid=substr(e.native_id,1,instr(e.native_id,':')-1) " - "WHERE e.session_key=? AND e.family='assistant_message'", (key,)): - capture_turns = ownership.claude_capture_turns.get(rid) - if rid in matches or (capture_turns is not None and (not turn_id or turn_id in capture_turns)): - literal_events.add(event_id) - elif (capture_turns is not None or rid in native["membership"] or rid in conflicts - or (rid in ownership.owners and task_id not in ownership.owners[rid])): - excluded_events.add(event_id) if native["runs"]: trace_scope = {"native_response_count": len(matches), "native_responses": {rid: matches[rid] for rid in sorted(matches)[:limit]}} + for key in ownership.literal_sessions: + if session_key and key != session_key: + continue + for event, turns in ownership.event_turns(con, key): + if turns is not None and (not turn_id or turn_id in turns): + literal_events.add(event) + else: + excluded_events.add(event) if not ownership.turns and not ownership.whole and not literal_events: return {**trace_scope, "events": [], "returned": 0, "total": 0, "truncated": False, diff --git a/tests/test_outcome.py b/tests/test_outcome.py index 4afaf42..8809be5 100644 --- a/tests/test_outcome.py +++ b/tests/test_outcome.py @@ -1,11 +1,14 @@ """Exercise shared-planner reports with native usage and independent purpose rows.""" from contextlib import closing +from pathlib import Path import json import sqlite3 from agent_observer import publish, report -from agent_observer.adapters import t3_purpose +from agent_observer.adapters import claude, opencode, t3_purpose +from tests.test_native_response import claude_response, claude_user, write_records +from tests.test_opencode import build_native from tests.helpers import LedgerCase @@ -176,10 +179,6 @@ def test_compatible_router_binding_keeps_whole_session_events(self): self.assertEqual(task_trace["native_response_count"], 2) def test_claude_display_turn_cannot_override_native_ancestry_in_capture_trace(self): - from pathlib import Path - from agent_observer.adapters import claude - from tests.test_native_response import claude_response, claude_user, write_records - path = Path(self.tmp.name, "s.jsonl") answers = [claude_response("answer-a", "a", "first"), claude_response("answer-b", "b", "second")] for answer in answers: @@ -204,8 +203,8 @@ def test_claude_display_turn_cannot_override_native_ancestry_in_capture_trace(se ["answer-a:0" if task == self.task else "answer-b:0"]) selected = report.timeline(self.con, task, session_key="claude:s", turn_id="claude:a" if task == self.task else "claude:b") - self.assertEqual([e["native_id"] for e in selected["events"]], - ["answer-a:0" if task == self.task else "answer-b:0"]) + self.assertCountEqual([e["native_id"] for e in selected["events"]], + ["foreign-call", "answer-a:0"] if task == self.task else ["answer-b:0"]) def test_delivery_alone_preserves_legacy_placement_and_capture_trace(self): from unittest.mock import patch @@ -300,3 +299,129 @@ def test_linked_session_reusing_a_captured_turn_id_stays_unplaced(self): self.assertEqual(rep["measured"]["unplaced_responses"], ["foreign-response"]) self.assertEqual(rep["total_cost"]["responses"], 2) self.assertFalse(report.timeline(self.con, self.task, session_key=key)["events"]) + + def project_input(self, session, native_id, validation): + self.con.execute("INSERT INTO t3_purpose_sessions VALUES('a',?)", (session,)) + self.con.execute("INSERT INTO t3_purpose_inputs(run_id,session_key,native_id,kind,validation)" + " VALUES('a',?,?,'message',?)", (session, native_id, validation)) + + def test_disputed_claude_parent_never_refunds_usage_to_router(self): + path = Path(self.tmp.name, "original.jsonl") + response = claude_response("reply", "a", "mid") + response["message"]["content"] = [{"type": "text", "text": "answer"}, + {"type": "tool_use", "id": "call", "name": "Read"}] + write_records(path, [claude_user("a"), response]) + claude.import_claude_file(self.con, str(path)) + self.project_input("claude:s", "a", "claude_prompt_echo") + self.assertIn("claude:mid", report.task_report(self.con, self.task)["measured"]["attributed_responses"]) + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES('router-job',0)") + self.con.execute("INSERT INTO session_assignments VALUES('claude:s','router-job','router:job',0)") + copy = Path(self.tmp.name, "copy.jsonl") + response["parentUuid"] = "missing" + write_records(copy, [response]) + claude.import_claude_file(self.con, str(copy)) + for owner in ("router-job", self.task): + rep = report.task_report(self.con, owner) + self.assertIn("claude:mid", rep["native_purpose"]["conflicting_responses"]) + self.assertIn("claude:mid", rep["measured"]["unplaced_responses"]) + self.assertFalse(report.timeline(self.con, owner, session_key="claude:s")["events"]) + self.con.execute("DELETE FROM session_assignments WHERE task_id='router-job'") + response["parentUuid"] = "a" + write_records(copy, [response]) + claude.import_claude_file(self.con, str(copy), full=True) + self.assertIn("claude:mid", report.task_report(self.con, self.task)["measured"]["attributed_responses"]) + + def test_claude_calls_and_results_follow_later_response_to_earlier_prompt(self): + path = Path(self.tmp.name, "s.jsonl") + self.con.execute("DELETE FROM t3_purpose_sessions") + rows = [claude_user("b"), claude_user("a")] + for prompt in ("a", "b"): + answer = claude_response("reply-" + prompt, prompt, "msg-" + prompt) + call = prompt + "-call" + answer["message"]["content"] = [{"type": "tool_use", "name": "Read", "id": call, + "input": {"file_path": "/fixture.txt"}}] + rows.extend([answer, claude_user("result-" + prompt, "reply-" + prompt, + [{"type": "tool_result", "tool_use_id": call, "content": "ok"}])]) + write_records(path, rows) + claude.import_claude_file(self.con, str(path)) + self.project_input("claude:s", "a", "claude_prompt_echo") + self.con.execute("INSERT INTO assignments(user_message_id,task_id,created_at) VALUES('claude:a',?,0)", + (self.task,)) + for task, prompt in ((self.task, "a"), ("capture-b", "b")): + if prompt == "b": + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (task,)) + self.con.execute("INSERT INTO assignments(user_message_id,task_id,created_at)" + " VALUES('claude:b',?,0)", (task,)) + task_report = report.task_report(self.con, task) + self.assertEqual(sum(p["activity"].get("tool_calls", 0) for p in task_report["phases"]), 1) + self.assertEqual(task_report["activity_session_context"]["tool_calls"], 1) + measured = task_report["measured"] + self.assertIn("claude:msg-" + prompt, measured["attributed_responses"]) + self.assertIn("claude:msg-b" if prompt == "a" else "claude:msg-a", + measured["unplaced_responses" if prompt == "a" else "other_task_responses"]) + for turn in (None, "claude:" + prompt): + trace = report.timeline(self.con, task, turn_id=turn, session_key="claude:s") + self.assertEqual({(e["family"], e["native_id"]) for e in trace["events"]}, + {("tool_call", prompt + "-call"), ("tool_result", prompt + "-call"), + ("read", prompt + "-call:read")}) + wrong_turn = "claude:b" if prompt == "a" else "claude:a" + self.assertFalse(report.timeline(self.con, task, turn_id=wrong_turn, session_key="claude:s")["events"]) + + def test_router_session_survives_navigation_and_separate_canonical_run(self): + self.con.execute("DELETE FROM t3_purpose_sessions") + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES('navigator',0)") + self.con.executemany("INSERT INTO session_assignments VALUES(?,?,?,0)", + [(self.session, self.task, "router:job"), (self.session, "navigator", "t3")]) + path = Path(self.tmp.name, "s.jsonl") + write_records(path, [claude_user("a"), claude_response("reply", "a", "mid")]) + claude.import_claude_file(self.con, str(path)) + self.project_input("claude:s", "a", "claude_prompt_echo") + rep = report.task_report(self.con, self.task) + expected = ["codex:resp-mini-001", "codex:resp-mini-002", "codex:resp-mini-003"] + self.assertEqual(rep["measured"]["attributed_responses"], ["claude:mid", *expected]) + self.assertEqual(rep["total_cost"]["responses"], 4) + self.assertEqual(report.task_report(self.con, "navigator")["measured"]["other_task_responses"], expected) + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES('partner',0)") + self.con.execute("INSERT INTO session_assignments VALUES(?,'partner','router:job',0)", (self.session,)) + joint = report.task_report(self.con, self.task) + self.assertEqual(joint["total_cost"]["shared_responses"], 3) + self.assertEqual(joint["total_cost"]["shared_with_tasks"], ["partner"]) + + def test_opencode_parts_follow_message_for_native_and_capture(self): + path = Path(self.tmp.name, "oc.db") + build_native(str(path)) + with closing(sqlite3.connect(path)) as source, source: + source.execute("UPDATE message SET data=json_set(data,'$.parentID','msg_u1') WHERE id='msg_a1'") + source.execute("INSERT INTO part SELECT 'text1',message_id,session_id,time_created,time_updated," + "? FROM part WHERE id='p_read1'", (json.dumps({"type": "text", "text": "answer"}),)) + opencode.sync(self.con, source=str(path)) + key = "opencode:ses_parent" + self.project_input(key, "msg_u1", "opencode_admitted_message") + for native in (True, False): + if not native: + self.con.execute("DELETE FROM t3_purpose_sessions WHERE session_key=?", (key,)) + self.con.execute("INSERT INTO assignments(user_message_id,task_id,created_at)" + " VALUES('opencode:msg_u1',?,0)", (self.task,)) + self.assertIn("opencode:msg_a1", report.task_report(self.con, self.task)["measured"]["attributed_responses"]) + for turn in (None, "opencode:msg_u1"): + trace = report.timeline(self.con, self.task, turn_id=turn, session_key=key) + self.assertEqual(trace["native_response_count"], int(native)) + events = {(e["family"], e["native_id"]) for e in trace["events"]} + self.assertTrue({("read", "call_read1"), ("tool_call", "call_read1"), + ("tool_result", "call_read1"), ("assistant_message", "text1"), + ("file_change", "p_patch1")} <= events, events) + self.assertNotIn(("tool_call", "call_run1"), events) + self.assertFalse(report.timeline(self.con, self.task, turn_id="opencode:unknown", session_key=key)["events"]) + + def test_event_edge_cannot_reuse_an_owned_response_from_another_session(self): + for sid in ("s", "other"): + answer = claude_response("reply", "a", "same-message-id") + answer["message"]["content"] = [{"type": "tool_use", "id": sid + "-call", "name": "Read"}] + records = [dict(row, sessionId=sid) for row in (claude_user("a"), answer)] + path = Path(self.tmp.name, sid + ".jsonl") + write_records(path, records) + claude.import_claude_file(self.con, str(path)) + self.project_input("claude:s", "a", "claude_prompt_echo") + self.con.execute("INSERT INTO t3_purpose_sessions VALUES('a','claude:other')") + trace = report.timeline(self.con, self.task, turn_id="claude:a", family="tool_call") + self.assertEqual([e["native_id"] for e in trace["events"]], ["s-call"]) From 6b9ee848116f79ba8988235524acb537f0e00dd2 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 20:36:04 +0100 Subject: [PATCH 26/44] wip: preserve task coverage and reconcile source-owned measurements Requirements and who asked: the #105 integration owner requested the three consumer repairs from independent review R5. Deleted: session-wide completion inferred from partial capture and ownership inferred across OpenCode copies. Bottleneck: the report lost unresolved inputs, and the ledger previously retained only one mutable payload per OpenCode response. Checked myself: original reproductions failed on cd7828a. Eight focused fixture tests pass. Read-only ledgers created by 75ed333 and cd7828a retain the Claude call and the independent OpenCode response; both copied-store orders exclude the disputed cost. --- agent_observer/adapters/claude.py | 8 +- agent_observer/adapters/opencode.py | 196 ++++++++++++++++++--------- agent_observer/native_response.py | 56 +++++--- agent_observer/outcome.py | 43 +++++- agent_observer/report.py | 19 ++- tests/test_evidence_coverage.py | 201 ++++++++++++++++++++++++++++ 6 files changed, 428 insertions(+), 95 deletions(-) create mode 100644 tests/test_evidence_coverage.py diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index 6c2f8a7..0eeb94a 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -1148,6 +1148,7 @@ def response_witnesses(con, session_key): return {}, set() parents, children, anchors, blocks = (defaultdict(set) for _ in range(4)) seen, disputed = set(), set() + recorded_parents = set() for uuid, parent, input_id, response_id in con.execute( "SELECT DISTINCT uuid,parent,input_id,response_id FROM claude_response_ancestry" " WHERE session_key=?", (session_key,) @@ -1160,6 +1161,7 @@ def response_witnesses(con, session_key): if input_id: anchors[uuid].add(input_id) elif parent: + recorded_parents.add(uuid) parents[uuid].add(parent) children[parent].add(uuid) if response_id: @@ -1194,9 +1196,13 @@ def response_witnesses(con, session_key): conflicts.add(response_id) if nodes <= resolved: results[response_id] = set.union(*(anchors[node] for node in nodes)) + elif nodes & recorded_parents: + # An empty witness set means a recorded, unresolved parent. + # Only an absent key can use historical explicit turn capture. + results[response_id] = set() return results, conflicts def response_inputs(con, session_key): witnesses, conflicts = response_witnesses(con, session_key) - return {rid: ids for rid, ids in witnesses.items() if rid not in conflicts} + return {rid: ids for rid, ids in witnesses.items() if ids and rid not in conflicts} diff --git a/agent_observer/adapters/opencode.py b/agent_observer/adapters/opencode.py index de1ce1d..414c8c5 100644 --- a/agent_observer/adapters/opencode.py +++ b/agent_observer/adapters/opencode.py @@ -173,10 +173,13 @@ def sync(con: sqlite3.Connection, root: str | None = None, full: bool = False, totals["failed"].append({"path": abs_path, "error": str(exc)}) return totals for row in rows: + con.execute("SAVEPOINT opencode_session") try: stats = import_session(con, native, abs_path, dict(row), full=full) except (OSError, sqlite3.DatabaseError) as exc: + con.execute("ROLLBACK TO opencode_session") + con.execute("RELEASE opencode_session") totals["failed"].append( {"path": f"{abs_path}#{row.get('id')}", "error": str(exc)}) continue @@ -277,60 +280,111 @@ def _int_or_none(value): else None -def _upsert_response(con: sqlite3.Connection, stats: dict, src_path: str, - *, response_id: str, source_id, session_key, session_id, - ordinal, ts, model, provider, effort, values: dict, - total, semantics, cost_usd, line: str = "") -> None: - existing = con.execute( - "SELECT * FROM responses WHERE response_id=?", - (response_id,)).fetchone() - if existing is None: - con.execute( - "INSERT INTO responses(response_id, source_id, harness," - " session_key, session_id, ordinal_num, ts, model, provider, effort," - " input_tokens, cached_input_tokens, cache_write_input_tokens," - " output_tokens, reasoning_output_tokens, total_tokens, semantics," - " cost_usd) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", - (response_id, source_id, HARNESS, session_key, - session_id, ordinal, ts, model, - provider, effort, - values["input_tokens"], values["cached_input_tokens"], - values["cache_write_input_tokens"], values["output_tokens"], - values["reasoning_output_tokens"], total, semantics, cost_usd)) - stats["responses_inserted"] = stats.get("responses_inserted", 0) + 1 - return - # Immutable identity: the same response id must stay in its session. - if (existing["session_key"] != session_key - or existing["session_id"] != session_id): - _oops(con, stats, src_path, ordinal, "usage_conflict", line) - stats["responses_duplicate"] = stats.get("responses_duplicate", 0) + 1 - return - new_fields = { - "ordinal_num": ordinal, "ts": ts, "model": model, "provider": provider, - "effort": effort, "input_tokens": values["input_tokens"], - "cached_input_tokens": values["cached_input_tokens"], - "cache_write_input_tokens": values["cache_write_input_tokens"], - "output_tokens": values["output_tokens"], - "reasoning_output_tokens": values["reasoning_output_tokens"], - "total_tokens": total, "semantics": semantics, "cost_usd": cost_usd, - "source_id": source_id, - } - changed = any(existing[col] != val for col, val in new_fields.items()) - if not changed: - stats["responses_duplicate"] = stats.get("responses_duplicate", 0) + 1 +_MEASUREMENT_FIELDS = ("model", "provider", "effort", "input_tokens", "output_tokens", + "cached_input_tokens", "cache_write_input_tokens", "reasoning_output_tokens", + "total_tokens", "cost_usd") + + +def _prepare_observations(con, session_key, source_id): + # A snapshot replaces only this store's observations. Keep the projection + # fields needed to restore a surviving copy when another store changes. + con.execute("""CREATE TABLE IF NOT EXISTS opencode_response_observations ( + session_key TEXT NOT NULL, response_id TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), + parent TEXT, measurement TEXT NOT NULL, ts REAL, ordinal_num INTEGER, + PRIMARY KEY(session_key,response_id,source_id)) WITHOUT ROWID""") + con.execute("CREATE INDEX IF NOT EXISTS opencode_observation_source ON opencode_response_observations(source_id)") + # Preserve the one payload a pre-upgrade ledger actually retained before + # another copy can replace its projection. Only its own edge accompanies it. + for row in con.execute( + "SELECT r.* FROM responses r JOIN sources s ON s.id=r.source_id WHERE r.session_key=? " + "AND r.source_id<>? AND s.sha256 NOT LIKE 'oc3:%' AND NOT EXISTS " + "(SELECT 1 FROM opencode_response_observations o WHERE o.session_key=r.session_key " + "AND o.response_id=r.response_id AND o.source_id=r.source_id)", (session_key, source_id)): + parent = con.execute( + "SELECT input_id FROM native_response_inputs WHERE session_key=? AND response_id=? AND source_id=?", + (session_key, row["response_id"], row["source_id"])).fetchone() + measurement = {name: row[name] for name in _MEASUREMENT_FIELDS} + _observe_response(con, session_key, row["response_id"], row["source_id"], parent[0] if parent else None, + measurement, row["ts"], row["ordinal_num"]) + con.execute("DELETE FROM opencode_response_observations WHERE source_id=?", (source_id,)) + + +def _project_observations(con, stats, session_key, session_id): + # The path selects a stable locator only. Membership and measurements + # are usable together only where the copies agree (response_witnesses). + groups = {} + for row in con.execute( + "SELECT o.*,s.path FROM opencode_response_observations o JOIN sources s ON s.id=o.source_id " + "WHERE session_key=? ORDER BY response_id,s.path", (session_key,)): + groups.setdefault(row["response_id"], []).append(row) + for rid, copies in groups.items(): + copy = copies[0] + data = json.loads(copy["measurement"]) + for other in copies[1:]: + for field, value in json.loads(other["measurement"]).items(): + if data[field] != value: + data[field] = None + _project_response(con, stats, rid, session_key, session_id, copy, data) + # Previously observed ids without a surviving copy retain their historical + # ledger row. Their input witness has been removed in this transaction. + + +def response_witnesses(con, session_key): + """Resolve the parent and the measured payload as a single source observation.""" + witnesses = {} + conflicts = set() + payload_sources = {} + observations = {} + if db._has_table(con, "opencode_response_observations"): + for rid, source, parent, measurement in con.execute( + "SELECT o.response_id,o.source_id,o.parent,o.measurement FROM opencode_response_observations o " + "JOIN responses r USING(session_key,response_id) WHERE o.session_key=? AND r.is_overlap=0", (session_key,)): + payload_sources.setdefault(rid, set()).add(source) + observations.setdefault(rid, set()).add((parent, measurement)) + if parent: + witnesses.setdefault(rid, set()).add(parent) + for rid, variants in observations.items(): + # Competing proved parents are returned together. A missing parent + # or incompatible payload additionally invalidates the measurement. + if len(variants) > 1 and (any(parent is None for parent, _ in variants) + or len({payload for _, payload in variants}) > 1): + conflicts.add(rid) + + # Old imports recorded edges but kept only the last copy's payload. + # An edge from a copy whose measurement was lost cannot vouch for it. + measured = dict(con.execute("SELECT response_id,source_id FROM responses WHERE session_key=?", (session_key,))) + for rid, input_id, source, measured_source in native_response.stored_inputs(con, session_key): + if source not in payload_sources.get(rid, {measured_source}): + conflicts.add(rid) + witnesses.setdefault(rid, set()).add(input_id) + if db._has_table(con, "native_response_events"): + for rid, source in con.execute( + "SELECT DISTINCT e.response_id,e.source_id FROM native_response_events e " + "JOIN sources s ON s.id=e.source_id WHERE e.session_key=? AND s.sha256 NOT LIKE 'oc3:%'", + (session_key,)): + if rid in measured and source not in payload_sources.get(rid, {measured[rid]}): + conflicts.add(rid) + return witnesses, conflicts + + +def _project_response(con, stats, rid, session_key, session_id, locator, measurement): + fields = ("source_id", "ordinal_num", "ts", "semantics", *_MEASUREMENT_FIELDS) + values = (locator["source_id"], locator["ordinal_num"], locator["ts"], SEMANTICS, + *(measurement[k] for k in _MEASUREMENT_FIELDS)) + # Identity was validated before the source observation was accepted. + columns = ",".join(fields) + row = con.execute(f"SELECT {columns} FROM responses WHERE response_id=?", (rid,)).fetchone() + if row and tuple(row) == values: + stats["responses_duplicate"] += 1 return - con.execute( - "UPDATE responses SET source_id=?, ordinal_num=?, ts=?, model=?," - " provider=?, effort=?, input_tokens=?, cached_input_tokens=?," - " cache_write_input_tokens=?, output_tokens=?," - " reasoning_output_tokens=?, total_tokens=?, semantics=?, cost_usd=?" - " WHERE response_id=?", - (source_id, ordinal, ts, model, provider, effort, - values["input_tokens"], values["cached_input_tokens"], - values["cache_write_input_tokens"], values["output_tokens"], - values["reasoning_output_tokens"], total, semantics, cost_usd, - response_id)) - stats["responses_inserted"] = stats.get("responses_inserted", 0) + 1 + if row: + con.execute(f"UPDATE responses SET ({columns})=({','.join('?' for _ in fields)}) WHERE response_id=?", + (*values, rid)) + else: + con.execute(f"INSERT INTO responses(response_id,harness,session_key,session_id,{columns}) " + f"VALUES({','.join('?' for _ in range(4 + len(fields)))})", + (rid, HARNESS, session_key, session_id, *values)) + stats["responses_inserted"] += 1 def _upsert_event(con: sqlite3.Connection, stats: dict, *, source_id: int, @@ -413,7 +467,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, session_key = f"{HARNESS}:{sess_id}" msg_n, msg_m = _count_max(native, "message", sess_id) part_n, part_m = _count_max(native, "part", sess_id) - fp = fingerprint("native-parent-and-parts-v2", sess.get("time_updated"), msg_m, part_m, msg_n, part_n) + fp = "oc3:" + fingerprint(sess.get("time_updated"), msg_m, part_m, msg_n, part_n) row = con.execute( "SELECT * FROM sources WHERE harness=? AND path=?", (HARNESS, src_path)).fetchone() @@ -506,6 +560,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, roles[msg_id] = data.get("role") native_response.prepare(con, source_id, replace=True) native_response.prepare_events(con, source_id, replace=True) + _prepare_observations(con, session_key, source_id) ordinal = 0 for index, msg, data in parsed_messages: ordinal += 1 @@ -513,6 +568,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, session_key, sess, msg, data, index, ordinal, by_message.get(msg.get("id"), []), roles=roles, privacy_stale=privacy_stale) + _project_observations(con, stats, session_key, sess_id) for part in parts: ordinal += 1 _ingest_part(con, stats, identity, src_path, source_id, @@ -642,19 +698,29 @@ def _ingest_response(con, stats, src_path, source_id, session_key, sess, if all(v is not None for v in values.values()): total = sum(values.values()) cost = data.get("cost") - cost_usd = cost if isinstance(cost, (int, float)) \ + cost_usd = float(cost) if isinstance(cost, (int, float)) \ and not isinstance(cost, bool) else None parent = native_response.identifier(data.get("parentID")) - if parent and roles.get(parent) == "user" and native_response.identifier(msg["id"]): - native_response.record(con, source_id, session_key, f"{HARNESS}:{msg['id']}", parent) - _upsert_response( - con, stats, src_path, response_id=f"{HARNESS}:{msg.get('id')}", - source_id=source_id, session_key=session_key, - session_id=sess.get("id"), ordinal=index, ts=ts, - model=data.get("modelID"), provider=data.get("providerID"), - effort=data.get("variant"), values=values, total=total, - semantics=SEMANTICS, cost_usd=cost_usd, - line=_record_line(msg.get("data"), data)) + if roles.get(parent) != "user" or not native_response.identifier(msg["id"]): + parent = None + rid = f"{HARNESS}:{msg['id']}" + existing = con.execute("SELECT session_key,session_id FROM responses WHERE response_id=?", (rid,)).fetchone() + if existing and tuple(existing) != (session_key, sess.get("id")): + _oops(con, stats, src_path, ordinal, "usage_conflict", _record_line(msg.get("data"), data)) + stats["responses_duplicate"] += 1 + return + if any(data.get(k) is not None and not isinstance(data[k], str) for k in ("modelID", "providerID", "variant")): + _oops(con, stats, src_path, ordinal, "malformed_usage", _record_line(msg.get("data"), data)) + return + measurement = dict(values, total_tokens=total, model=data.get("modelID"), provider=data.get("providerID"), + effort=data.get("variant"), cost_usd=cost_usd) + _observe_response(con, session_key, rid, source_id, parent, measurement, ts, index) + + +def _observe_response(con, session_key, rid, source_id, parent, measurement, ts, index): + con.execute("INSERT INTO opencode_response_observations" + "(session_key,response_id,source_id,parent,measurement,ts,ordinal_num) VALUES(?,?,?,?,?,?,?)", + (session_key, rid, source_id, parent, json.dumps(measurement, sort_keys=True), ts, index)) def _ingest_submission(con, stats, identity, src_path, source_id, diff --git a/agent_observer/native_response.py b/agent_observer/native_response.py index 288f29e..be173ce 100644 --- a/agent_observer/native_response.py +++ b/agent_observer/native_response.py @@ -47,14 +47,13 @@ def inputs(con: sqlite3.Connection, session_key: str) -> dict[str, set[str]]: if session_key.startswith("grok:"): from .adapters import grok return grok.response_inputs(con, session_key) + if session_key.startswith("opencode:"): + from .adapters import opencode + witnesses, conflicts = opencode.response_witnesses(con, session_key) + return {rid: ids for rid, ids in witnesses.items() if rid not in conflicts} found = defaultdict(set) - if db._has_table(con, "native_response_inputs"): - for response_id, input_id in con.execute( - "SELECT DISTINCT i.response_id,i.input_id FROM native_response_inputs i" - " JOIN responses r USING(session_key,response_id)" - " WHERE i.session_key=? AND r.is_overlap=0", (session_key,) - ): - found[response_id].add(input_id) + for response_id, input_id, _, _ in stored_inputs(con, session_key): + found[response_id].add(input_id) if session_key.startswith("codex:"): from .adapters import codex for response_id, turn_id in codex.legacy_response_inputs(con, session_key): @@ -62,6 +61,14 @@ def inputs(con: sqlite3.Connection, session_key: str) -> dict[str, set[str]]: return dict(found) +def stored_inputs(con, session_key): + if db._has_table(con, "native_response_inputs"): + yield from con.execute( + "SELECT i.response_id,i.input_id,i.source_id,r.source_id FROM native_response_inputs i" + " JOIN responses r USING(session_key,response_id)" + " WHERE i.session_key=? AND r.is_overlap=0", (session_key,)) + + def prepare_events(con, source_id, *, replace): con.execute(""" CREATE TABLE IF NOT EXISTS native_response_events ( @@ -83,11 +90,24 @@ def record_event(con, source_id, session_key, family, native_id, response_id): def event_responses(con, session_key): """Return literal event associations, including competing copies and unmatched calls.""" edges = defaultdict(set) + opencode = session_key.startswith("opencode:") + edge_sources = defaultdict(set) if db._has_table(con, "native_response_events"): - for family, native_id, rid in con.execute( - "SELECT DISTINCT family,native_id,response_id FROM native_response_events WHERE session_key=?", + for family, native_id, rid, source in con.execute( + "SELECT family,native_id,response_id,source_id FROM native_response_events WHERE session_key=?", (session_key,)): edges[family, native_id].add(rid) + if opencode: + edge_sources[family, native_id].add(source) + measured_sources = defaultdict(set) + if opencode: + for rid, source in con.execute("SELECT response_id,source_id FROM responses WHERE session_key=?", + (session_key,)): + measured_sources[rid].add(source) + if db._has_table(con, "opencode_response_observations"): + for rid, source in con.execute("SELECT response_id,source_id FROM opencode_response_observations " + "WHERE session_key=?", (session_key,)): + measured_sources[rid].add(source) claude = session_key.startswith("claude:") legacy_text = defaultdict(set) if claude and db._has_table(con, "claude_response_ancestry"): @@ -97,13 +117,19 @@ def event_responses(con, session_key): "JOIN sources s ON s.id=a.source_id WHERE a.session_key=? AND a.response_id<>'' " "AND s.claude_usage_version<7", (session_key,)): legacy_text[source, uuid].add(rid) - for event, source, family, native_id in con.execute( - "SELECT id,source_id,family,native_id FROM events WHERE session_key=?", (session_key,)): + for event, source, family, native_id, turn in con.execute( + "SELECT id,source_id,family,native_id,turn_id FROM events WHERE session_key=?", (session_key,)): if claude and family == "assistant_message": - yield event, edges[family, native_id] | legacy_text[source, native_id.rpartition(":")[0]] + yield event, turn, edges[family, native_id] | legacy_text[source, native_id.rpartition(":")[0]] elif claude and family in {"tool_result", "permission", "skill_invoke", "file_change"}: - yield event, edges["tool_call", native_id] + yield event, turn, edges["tool_call", native_id] elif claude and family in {"read", "skill_read"} and native_id.endswith(":read"): - yield event, edges["tool_call", native_id[:-5]] + yield event, turn, edges["tool_call", native_id[:-5]] else: - yield event, edges[family, native_id] + linked = edges[family, native_id] + if opencode and linked and (source not in edge_sources[family, native_id] or any( + rid in measured_sources and source not in measured_sources[rid] for rid in linked)): + # A copied event cannot borrow a different source's association or measurement. + yield event, turn, None + else: + yield event, turn, linked diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index 59bda76..b2773d8 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -38,6 +38,8 @@ class Ownership: # Explicit and native claims resolved against the same literal response. owners: dict = field(default_factory=dict) turns: set = field(default_factory=set) + missing_by_response: dict = field(default_factory=dict) + legacy_event_turns: set = field(default_factory=set) response_turns: dict = field(default_factory=dict) literal_sessions: set = field(default_factory=set) conflicts: set = field(default_factory=set) @@ -47,12 +49,14 @@ def event_turns(self, con, key): """Literal event partitions. None excludes, an empty set admits session scope only.""" if key not in self.literal_sessions: return - for event, responses in native_response.event_responses(con, key): + for event, display_turn, responses in native_response.event_responses(con, key): turns = None - if len(responses) <= 1: + if responses is not None and len(responses) <= 1: rid = next(iter(responses), None) turns = self.response_turns.get((key, rid)) - if key in self.whole and rid not in self.owners and rid not in self.conflicts: + if not responses and (key, display_turn) in self.legacy_event_turns: + turns = {display_turn} + if turns is None and key in self.whole and rid not in self.owners and rid not in self.conflicts: # Whole-session capture includes events without a usage row. turns = set() yield event, turns @@ -128,17 +132,21 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me if not legacy_link(r["evidence"])} harness = key.partition(":")[0] claimed_turns = defaultdict(set) + prompt_ids = defaultdict(set) claimed_inputs = defaultdict(set) input_turns = defaultdict(set) for msg, alias, turn, owner in con.execute( "SELECT s.native_id,s.alias_id,s.turn_id,a.task_id FROM user_messages s " "LEFT JOIN assignments a ON a.user_message_id=s.native_id WHERE s.session_key=? AND s.is_genuine=1", (key,)): - if owner and turn: - claimed_turns[turn].add(owner) + if turn: + prompt_ids[turn].add(msg) + if owner: + claimed_turns[turn].add(owner) # Claude and OpenCode identify inputs by message, Codex by turn. for identity in ((msg, alias, turn) if harness == "codex" else (msg, alias)): if identity: + prompt_ids[identity].add(msg) if owner: claimed_inputs[identity].add(owner) if turn: @@ -153,6 +161,9 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me if harness == "claude": from .adapters import claude responses, disputed_completions = claude.response_witnesses(con, key) + elif harness == "opencode": + from .adapters import opencode + responses, disputed_completions = opencode.response_witnesses(con, key) elif harness == "grok": from .adapters import grok responses, call_witnesses, disputed_completions = grok.response_witnesses(con, key) @@ -163,6 +174,7 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me exclusive = not by_run or (whole == {task_id} and set(by_run.values()) == {task_id}) prefix = key if harness == "grok" else harness blocked_turns = set() + unsafe_display = set() for native_id, candidates in by_input.items(): identity = f"{prefix}:{native_id}" input_owners = {by_run.get(entry[0]) for entry in candidates} @@ -187,19 +199,33 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me exclusive = False continue identities = {f"{prefix}:{identity}" for identity in input_ids} + if identities and display_turn not in identities and not any( + display_turn in input_turns[identity] for identity in identities): + unsafe_display.add(display_turn) candidates = {candidate for identity in input_ids for candidate in by_input.get(identity, ())} claims = whole.copy() for identity in identities: claims.update(claimed_inputs[identity]) - if not identities and not literal_messages: + # Only an explicit capture may use the historical display turn. + # A session with native run evidence must resolve its literal input. + legacy_capture = not by_run and rid not in responses + if not identities and (not literal_messages or legacy_capture): claims.update(claimed_turns[display_turn]) if not candidates: result.owners[rid] = claims + if not claims: + missing = {msg for identity in identities for msg in prompt_ids[identity]} + if legacy_capture: + missing.update(prompt_ids[display_turn]) + if missing: + result.missing_by_response[rid] = missing + if task_id not in claims: + unsafe_display.add(display_turn) if task_id in claims: turns = {t for identity in identities for t in input_turns[identity]} if literal_messages: turns.update(identities) - elif not turns and display_turn: + if not turns and display_turn and (not literal_messages or legacy_capture): turns.add(display_turn) result.turns.update((key, t) for t in turns) if literal_messages: @@ -239,6 +265,9 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me result.turns.add((key, "codex:" + native_id)) elif harness == "grok": result.turns.add((key, rid)) + if literal_messages and not by_run: + result.legacy_event_turns.update((key, turn) for turn, owners in claimed_turns.items() + if task_id in owners and turn not in blocked_turns and turn not in unsafe_display) if not exclusive: result.whole.discard(key) result.turns.difference_update((key, turn) for turn in blocked_turns) diff --git a/agent_observer/report.py b/agent_observer/report.py index 9700393..a7e7bae 100644 --- a/agent_observer/report.py +++ b/agent_observer/report.py @@ -254,8 +254,9 @@ def _source_cutoff(con: sqlite3.Connection, scope_keys: set) -> float | None: return None placeholders = ",".join("?" * len(keys)) tables = ["responses", "events", "user_messages", "sessions"] - if _has_table(con, "codex_occurrences"): - tables.append("codex_occurrences") + for table in ("codex_occurrences", "opencode_response_observations"): + if _has_table(con, table): + tables.append(table) backing = " UNION ".join( f"SELECT DISTINCT source_id FROM {table}" f" WHERE session_key IN ({placeholders})" for table in tables) @@ -566,7 +567,7 @@ def task_report(con: sqlite3.Connection, task_id: str, for key in sorted(legacy_links): checkout_records.update(placement.checkout_observations(con, key)) unplaced, elsewhere = [], [] - missing_submissions = [] + missing_submissions = sorted({msg for ids in ownership.missing_by_response.values() for msg in ids}) sharing_tasks = set() legacy_shared = set() conflicts = ownership.conflicts @@ -576,7 +577,10 @@ def task_report(con: sqlite3.Connection, task_id: str, key, rid = r["session_key"], r["response_id"] if rid in conflicts or rid in ownership.owners or (native and key in native["sessions"]): owners = ownership.owners.get(rid) - if rid in conflicts or not owners: + if (rid in ownership.missing_by_response and key not in legacy_links + and not (native and key in native["sessions"])): + unassigned.append(dict(r)) + elif rid in conflicts or not owners: unplaced.append(dict(r)) elif task_id not in owners: elsewhere.append(dict(r)) @@ -603,7 +607,7 @@ def task_report(con: sqlite3.Connection, task_id: str, sharing_tasks.update(session_owners[key] | prompt_owners[key]) else: attributed.append(dict(r)) - elif key in linked_tasks and (sub in assigned_anywhere or key in session_owners): + elif sub in assigned_anywhere or key in session_owners: elsewhere.append(dict(r)) elif key in legacy_links: placed = placements.get(key) @@ -704,7 +708,8 @@ def child_session(identity): unmeasured_shared.add(key) has_purpose = native and (canonical or native["deliveries"] or native["conflicting_source_runs"]) inventory_gaps = outcome.check_inventory(con, native, attributed) if has_purpose else False - unavailable_usage = bool(unbound_usage or conflicts or inventory_gaps or legacy_links + unresolved_usage = bool(unplaced or unassigned) + unavailable_usage = bool(unresolved_usage or conflicts or inventory_gaps or legacy_links or not scope_keys or missing_sessions or empty_sessions or unbound_children or unbound_delegations or whole_conflicts) cutoff = _source_cutoff(con, scope_keys) @@ -928,7 +933,7 @@ def _resp_tuple(r) -> list: report["coverage"]["unavailable_sources"] = unavailable_sources report["total_cost"] = _total_cost( task_id, total_estimated, attributed, billed_shared, sharing_tasks) - if inventory_gaps and total_estimated.get("priced_responses"): + if (inventory_gaps or unresolved_usage) and total_estimated.get("priced_responses"): subtotal = total_estimated["estimated_cost_usd_partial"] amount = "under $0.01" if 0 < subtotal < 0.005 else f"${subtotal:,.2f}" report["total_cost"].update(usd=None, observed_subtotal_usd=subtotal, diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py new file mode 100644 index 0000000..ba7fa91 --- /dev/null +++ b/tests/test_evidence_coverage.py @@ -0,0 +1,201 @@ +"""Regression fixtures for task ownership across partial capture and copied stores.""" + +from contextlib import closing +import json +from pathlib import Path +import sqlite3 + +from agent_observer import report +from agent_observer.adapters import claude, opencode, t3_purpose +from tests.helpers import LedgerCase +from tests.test_cli import run +from tests.test_native_response import claude_response, claude_user, write_records +from tests.test_opencode import build_native + + +class EvidenceCoverageTest(LedgerCase): + def setUp(self): + super().setUp() + self.con.executemany("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", [("A",), ("B",)]) + + def assign(self, task, message): + self.con.execute("INSERT INTO assignments(user_message_id,task_id,created_at) VALUES(?,?,0)", + (message, task)) + + def draft(self): + self.con.commit() + result = run(self.db_path, "publish", "--task", "A", "--dry-run", "--json") + self.assertEqual(result.returncode, 0, result.stderr) + return json.loads(result.stdout) + + def import_claude(self, legacy=False): + rows = [claude_user("b"), claude_user("a")] + for prompt in ("a", "b"): + response = claude_response("reply-" + prompt, prompt, "msg-" + prompt) + response["message"].update(model="claude-haiku-4-5", + usage=dict(input_tokens=10, output_tokens=5, cache_creation_input_tokens=0, + cache_read_input_tokens=0), + content=[{"type": "tool_use", "id": prompt + "-call", "name": "Read"}]) + if legacy: + del response["parentUuid"] + rows = [claude_user("a"), response] + break + rows.append(response) + path = Path(self.tmp.name, "claude.jsonl") + write_records(path, rows) + claude.import_claude_file(self.con, str(path)) + self.assign("A", "claude:a") + return path + + def test_missing_literal_capture_survives_partial_session(self): + self.import_claude() + rep = report.task_report(self.con, "A") + self.assertEqual(rep["missing_assignments"], ["claude:b"]) + self.assertEqual(rep["measured"]["unassigned_responses"], ["claude:msg-b"]) + self.assertIsNone(rep["total_cost"]["usd"]) + self.assertGreater(rep["total_cost"]["observed_subtotal_usd"], 0) + self.assertFalse(rep["complete"]) + draft = self.draft() + self.assertIn("Evidence complete: no", draft["body"]) + self.assertIn("Estimated cost unknown", draft["body"]) + self.assertEqual(draft["summary"]["total_cost"], rep["total_cost"]) + self.assertEqual([e["native_id"] for e in report.timeline(self.con, "A")["events"]], ["a-call"]) + self.assign("B", "claude:b") + rep = report.task_report(self.con, "A") + self.assertEqual(rep["measured"]["other_task_responses"], ["claude:msg-b"]) + self.assertEqual(rep["missing_assignments"], []) + self.assertTrue(rep["complete"]) + self.assertGreater(rep["total_cost"]["usd"], 0) + + def test_legacy_explicit_capture_with_and_without_source(self): + source = self.import_claude(legacy=True) + for old in (False, True): + with self.subTest(ledger_only=old): + if old: + self.con.execute("DROP TABLE claude_response_ancestry") + self.con.execute("DROP TABLE native_response_events") + self.con.execute("UPDATE sources SET claude_usage_version=5") + source.unlink() + self.con.execute("PRAGMA query_only=ON") + rep = report.task_report(self.con, "A") + self.assertEqual(rep["measured"]["attributed_responses"], ["claude:msg-a"]) + self.assertEqual(rep["total_cost"]["responses"], 1) + self.assertEqual([e["native_id"] for e in report.timeline( + self.con, "A", turn_id="claude:a")["events"]], ["a-call"]) + + def project_input(self, session, message, validation): + with closing(sqlite3.connect(":memory:")) as source: + t3_purpose.refresh(self.con, source, set()) + self.con.execute("INSERT INTO t3_purpose_runs(run_id,thread_id,task_id,scope)" + " VALUES('run','thread','A','single')") + self.con.execute("INSERT INTO t3_purpose_sessions VALUES('run',?)", (session,)) + self.con.execute("INSERT INTO t3_purpose_inputs(run_id,session_key,native_id,kind,validation)" + " VALUES('run',?,?,'message',?)", (session, message, validation)) + + def test_native_input_without_response_parent_cannot_use_display_turn(self): + self.import_claude(legacy=True) + self.project_input("claude:s", "a", "claude_prompt_echo") + rep = report.task_report(self.con, "A") + self.assertEqual(rep["measured"]["unplaced_responses"], ["claude:msg-a"]) + self.assertEqual(rep["native_purpose"]["membership"], {}) + self.assertFalse(report.timeline(self.con, "A")["events"]) + + def opencode_store(self, name, parent, cost, output, independent=False): + path = Path(self.tmp.name, name + ".db") + build_native(str(path)) + with closing(sqlite3.connect(path)) as source, source: + source.execute("UPDATE message SET data=json_set(data,'$.parentID',?,'$.cost',?," + "'$.tokens.output',?) WHERE id='msg_a1'", (parent, cost, output)) + if independent: + source.execute("INSERT INTO message SELECT 'msg_unique',session_id,time_created,time_updated," + "json_set(data,'$.cost',0.10,'$.tokens.output',3) FROM message WHERE id='msg_a1'") + return str(path) + + def check_opencode_copies(self, reversed_order): + first = self.opencode_store("original", "msg_u1", 0.20, 50, independent=True) + second = self.opencode_store("copy", None, 7.25, 500) + paths = [second, first] if reversed_order else [first, second] + for path in paths: + self.assertFalse(opencode.sync(self.con, source=path)["failed"]) + self.assign("A", "opencode:msg_u1") + for canonical in (False, True): + if canonical: + self.project_input("opencode:ses_parent", "msg_u1", "opencode_admitted_message") + rep = report.task_report(self.con, "A") + self.assertEqual(rep["measured"]["attributed_responses"], ["opencode:msg_unique"]) + self.assertEqual(rep["measured"]["unplaced_responses"], ["opencode:msg_a1"]) + self.assertEqual(rep["native_cost"]["known_subtotal_usd"], 0.10) + self.assertEqual(rep["attributed"]["output_tokens"], 3) + trace = report.timeline(self.con, "A") + self.assertFalse(trace["events"]) + if canonical: + self.assertEqual(set(trace["native_responses"]), {"opencode:msg_unique"}) + draft = self.draft() + self.assertEqual(draft["summary"]["usage"]["output_tokens"], 3) + self.assertEqual(draft["summary"]["native_cost"]["known_subtotal_usd"], 0.10) + with closing(sqlite3.connect(second)) as source, source: + source.execute("UPDATE message SET time_updated=time_updated+1," + "data=json_set(data,'$.parentID','msg_u1','$.cost',0.20,'$.tokens.output',50)" + " WHERE id='msg_a1'") + source.execute("UPDATE session SET time_updated=time_updated+1 WHERE id='ses_parent'") + opencode.sync(self.con, source=second) + rep = report.task_report(self.con, "A") + self.assertEqual(rep["total_cost"]["responses"], 2) + self.assertEqual(rep["attributed"]["output_tokens"], 53) + self.assertAlmostEqual(rep["native_cost"]["known_subtotal_usd"], 0.30) + self.assertIn("call_read1", [e["native_id"] for e in report.timeline(self.con, "A")["events"]]) + + def test_opencode_proved_then_parentless_copy(self): + self.check_opencode_copies(False) + + def test_opencode_parentless_then_proved_copy(self): + self.check_opencode_copies(True) + + def test_unresolved_literal_parent_cannot_use_legacy_capture(self): + path = self.import_claude(legacy=True) + records = [json.loads(line) for line in path.read_text().splitlines()] + records[1]["parentUuid"] = "unseen" + write_records(path, records) + claude.import_claude_file(self.con, str(path), full=True) + self.assertEqual(report.task_report(self.con, "A")["attributed"]["responses"], 0) + self.assertFalse(report.timeline(self.con, "A")["events"]) + + def test_copies_must_agree_on_both_parent_and_measurement(self): + first = self.opencode_store("one", "msg_u1", 0.20, 50) + second = self.opencode_store("two", None, 0.20, 50) + opencode.sync(self.con, source=first) + self.assign("A", "opencode:msg_u1") + for parent, cost, expected in ((None, 0.20, 0), ("msg_u1", 7.25, 0), ("msg_u1", 0.20, 1)): + with self.subTest(parent=parent, cost=cost): + with closing(sqlite3.connect(second)) as source, source: + source.execute("UPDATE message SET data=json_set(data,'$.parentID',?,'$.cost',?) " + "WHERE id='msg_a1'", (parent, cost)) + opencode.sync(self.con, source=second, full=True) + rep = report.task_report(self.con, "A") + self.assertEqual(rep["attributed"]["responses"], expected) + self.assertEqual(rep["total_cost"]["responses"], expected) + self.assertEqual(bool(report.timeline(self.con, "A")["events"]), bool(expected)) + + def test_read_only_old_opencode_ledger_with_overwritten_payload(self): + first = self.opencode_store("older", "msg_u1", 0.20, 50, independent=True) + second = self.opencode_store("newer", None, 7.25, 500) + for path in (first, second): + opencode.sync(self.con, source=path) + self.assign("A", "opencode:msg_u1") + # Before source observations, both edges came from the first store + # and msg_a1's one surviving payload came from the second store. + key = "opencode:ses_parent" + self.con.execute("INSERT INTO native_response_inputs SELECT session_key,response_id,parent,source_id " + "FROM opencode_response_observations WHERE parent IS NOT NULL") + self.con.execute("UPDATE responses SET source_id=(SELECT id FROM sources WHERE path=?)," + "output_tokens=500,total_tokens=516,cost_usd=7.25 WHERE response_id='opencode:msg_a1'", + (second + "#ses_parent",)) + self.con.execute("DROP TABLE opencode_response_observations") + self.con.execute("UPDATE sources SET sha256='old'") + for path in (first, second): + Path(path).unlink() + self.con.execute("PRAGMA query_only=ON") + rep = report.task_report(self.con, "A") + self.assertEqual(rep["measured"]["attributed_responses"], ["opencode:msg_unique"]) + self.assertEqual(rep["native_cost"]["known_subtotal_usd"], 0.10) + self.assertFalse(report.timeline(self.con, "A", session_key=key)["events"]) From 7b736f29a755ee153952ed9f65aacb19fe64df7e Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 20:50:11 +0100 Subject: [PATCH 27/44] wip: preserve ownership evidence when a native record is malformed --- agent_observer/adapters/claude.py | 23 ++++++++- agent_observer/adapters/opencode.py | 76 ++++++++++++++++------------- agent_observer/outcome.py | 3 ++ tests/test_evidence_coverage.py | 55 +++++++++++++++++++++ 4 files changed, 122 insertions(+), 35 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index 0eeb94a..b82c708 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -106,7 +106,7 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 7 # Replay literal event-to-message edges from existing sources. +_IMPORT_VERSION = 8 # Distinguish unusable ancestry from historical records without an edge. def _ensure_native_kinds(con) -> None: @@ -1086,9 +1086,14 @@ def _prepare_ancestry(r): ) WITHOUT ROWID""") r.con.execute("CREATE INDEX IF NOT EXISTS claude_ancestry_source" " ON claude_response_ancestry(source_id)") + r.con.execute("""CREATE TABLE IF NOT EXISTS claude_invalid_ancestry ( + source_id INTEGER NOT NULL REFERENCES sources(id), session_key TEXT NOT NULL, + uuid TEXT NOT NULL, response_id TEXT NOT NULL, + PRIMARY KEY(session_key, source_id, uuid, response_id)) WITHOUT ROWID""") if not r.src.incremental: r.con.execute("DELETE FROM claude_response_ancestry WHERE source_id=?", (r.src.source_id,)) + r.con.execute("DELETE FROM claude_invalid_ancestry WHERE source_id=?", (r.src.source_id,)) def _record_ancestry(r, obj): @@ -1129,6 +1134,13 @@ def _record_ancestry(r, obj): return elif kind not in ("system", "progress"): return + # A supplied edge needs both endpoints. Keep its independently valid + # identities so a damaged copy cannot turn into historical display capture. + if not input_id and "parentUuid" in obj and (not uuid or not parent): + if uuid or response_id: + r.con.execute("INSERT OR IGNORE INTO claude_invalid_ancestry VALUES(?,?,?,?)", + (r.src.source_id, r.session_key, uuid or "", response_id)) + return if not uuid: return r.con.execute("INSERT OR IGNORE INTO claude_response_ancestry" @@ -1148,6 +1160,14 @@ def response_witnesses(con, session_key): return {}, set() parents, children, anchors, blocks = (defaultdict(set) for _ in range(4)) seen, disputed = set(), set() + conflicts = set() + if db._has_table(con, "claude_invalid_ancestry"): + for uuid, response_id in con.execute( + "SELECT uuid,response_id FROM claude_invalid_ancestry WHERE session_key=?", (session_key,)): + if uuid: + disputed.add(uuid) + if response_id: + conflicts.add(response_id) recorded_parents = set() for uuid, parent, input_id, response_id in con.execute( "SELECT DISTINCT uuid,parent,input_id,response_id FROM claude_response_ancestry" @@ -1186,7 +1206,6 @@ def response_witnesses(con, session_key): if not parents[child]: ready.append(child) results = {} - conflicts = set() for response_id, in con.execute("SELECT response_id FROM responses" " WHERE session_key=? AND is_overlap=0", (session_key,)): nodes = blocks.get(response_id) diff --git a/agent_observer/adapters/opencode.py b/agent_observer/adapters/opencode.py index 414c8c5..085af54 100644 --- a/agent_observer/adapters/opencode.py +++ b/agent_observer/adapters/opencode.py @@ -297,7 +297,7 @@ def _prepare_observations(con, session_key, source_id): # another copy can replace its projection. Only its own edge accompanies it. for row in con.execute( "SELECT r.* FROM responses r JOIN sources s ON s.id=r.source_id WHERE r.session_key=? " - "AND r.source_id<>? AND s.sha256 NOT LIKE 'oc3:%' AND NOT EXISTS " + "AND r.source_id<>? AND s.sha256 NOT GLOB 'oc[34]:*' AND NOT EXISTS " "(SELECT 1 FROM opencode_response_observations o WHERE o.session_key=r.session_key " "AND o.response_id=r.response_id AND o.source_id=r.source_id)", (session_key, source_id)): parent = con.execute( @@ -318,10 +318,16 @@ def _project_observations(con, stats, session_key, session_id): "WHERE session_key=? ORDER BY response_id,s.path", (session_key,)): groups.setdefault(row["response_id"], []).append(row) for rid, copies in groups.items(): - copy = copies[0] - data = json.loads(copy["measurement"]) - for other in copies[1:]: - for field, value in json.loads(other["measurement"]).items(): + measured = [(row, json.loads(row["measurement"])) for row in copies if row["measurement"] != "null"] + # A rejected payload has a durable ownership witness, but cannot + # create a billable row. An all-zero lifecycle record has no usage. + if not measured or all(data["total_tokens"] == 0 for _, data in measured): + if not con.execute("SELECT 1 FROM responses WHERE session_key=? AND response_id=?", + (session_key, rid)).fetchone(): + continue + copy, data = measured[0] if measured else (copies[0], dict.fromkeys(_MEASUREMENT_FIELDS)) + for _, other in measured[1:]: + for field, value in other.items(): if data[field] != value: data[field] = None _project_response(con, stats, rid, session_key, session_id, copy, data) @@ -338,9 +344,12 @@ def response_witnesses(con, session_key): if db._has_table(con, "opencode_response_observations"): for rid, source, parent, measurement in con.execute( "SELECT o.response_id,o.source_id,o.parent,o.measurement FROM opencode_response_observations o " - "JOIN responses r USING(session_key,response_id) WHERE o.session_key=? AND r.is_overlap=0", (session_key,)): + "LEFT JOIN responses r USING(session_key,response_id) WHERE o.session_key=? AND coalesce(r.is_overlap,0)=0", + (session_key,)): payload_sources.setdefault(rid, set()).add(source) observations.setdefault(rid, set()).add((parent, measurement)) + if measurement == "null": + conflicts.add(rid) if parent: witnesses.setdefault(rid, set()).add(parent) for rid, variants in observations.items(): @@ -360,7 +369,7 @@ def response_witnesses(con, session_key): if db._has_table(con, "native_response_events"): for rid, source in con.execute( "SELECT DISTINCT e.response_id,e.source_id FROM native_response_events e " - "JOIN sources s ON s.id=e.source_id WHERE e.session_key=? AND s.sha256 NOT LIKE 'oc3:%'", + "JOIN sources s ON s.id=e.source_id WHERE e.session_key=? AND s.sha256 NOT GLOB 'oc[34]:*'", (session_key,)): if rid in measured and source not in payload_sources.get(rid, {measured[rid]}): conflicts.add(rid) @@ -467,7 +476,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, session_key = f"{HARNESS}:{sess_id}" msg_n, msg_m = _count_max(native, "message", sess_id) part_n, part_m = _count_max(native, "part", sess_id) - fp = "oc3:" + fingerprint(sess.get("time_updated"), msg_m, part_m, msg_n, part_n) + fp = "oc4:" + fingerprint(sess.get("time_updated"), msg_m, part_m, msg_n, part_n) row = con.execute( "SELECT * FROM sources WHERE harness=? AND path=?", (HARNESS, src_path)).fetchone() @@ -651,6 +660,26 @@ def _ingest_response(con, stats, src_path, source_id, session_key, sess, timing = data.get("time") if isinstance(data.get("time"), dict) else {} if timing.get("completed") is None: return + parent = native_response.identifier(data.get("parentID")) + if roles.get(parent) != "user" or not native_response.identifier(msg["id"]): + parent = None + rid = f"{HARNESS}:{msg['id']}" + existing = con.execute("SELECT session_key,session_id FROM responses WHERE response_id=?", (rid,)).fetchone() + if existing and tuple(existing) != (session_key, sess.get("id")): + _oops(con, stats, src_path, ordinal, "usage_conflict", _record_line(msg.get("data"), data)) + stats["responses_duplicate"] += 1 + return + try: + measurement = _measurement(data) + except ValueError: + _oops(con, stats, src_path, ordinal, "malformed_usage", _record_line(msg.get("data"), data)) + if not native_response.identifier(msg["id"]): + return + measurement = None + _observe_response(con, session_key, rid, source_id, parent, measurement, ts, index) + + +def _measurement(data): raw_tokens = data.get("tokens") if raw_tokens is None: tokens: dict = {} @@ -659,18 +688,14 @@ def _ingest_response(con, stats, src_path, source_id, session_key, sess, else: # A present non-object tokens block is malformed usage, never # silently unknown; quarantine before any response insert. - _oops(con, stats, src_path, ordinal, "malformed_usage", - _record_line(msg.get("data"), data)) - return + raise ValueError("malformed_usage") raw_cache = tokens.get("cache") if raw_cache is None: cache: dict = {} elif isinstance(raw_cache, dict): cache = raw_cache else: - _oops(con, stats, src_path, ordinal, "malformed_usage", - _record_line(msg.get("data"), data)) - return + raise ValueError("malformed_usage") # A present counter must be a non-boolean integer; only a missing # key stays unknown and maps to NULL. An explicitly present null, # bool, string, float, list or other non-integer quarantines the @@ -688,33 +713,18 @@ def _ingest_response(con, stats, src_path, source_id, session_key, sess, continue raw = container[key] if not isinstance(raw, int) or isinstance(raw, bool): - _oops(con, stats, src_path, ordinal, "malformed_usage", - _record_line(msg.get("data"), data)) - return + raise ValueError("malformed_usage") values[field] = raw - if all(v == 0 for v in values.values()): - return total = None if all(v is not None for v in values.values()): total = sum(values.values()) cost = data.get("cost") cost_usd = float(cost) if isinstance(cost, (int, float)) \ and not isinstance(cost, bool) else None - parent = native_response.identifier(data.get("parentID")) - if roles.get(parent) != "user" or not native_response.identifier(msg["id"]): - parent = None - rid = f"{HARNESS}:{msg['id']}" - existing = con.execute("SELECT session_key,session_id FROM responses WHERE response_id=?", (rid,)).fetchone() - if existing and tuple(existing) != (session_key, sess.get("id")): - _oops(con, stats, src_path, ordinal, "usage_conflict", _record_line(msg.get("data"), data)) - stats["responses_duplicate"] += 1 - return if any(data.get(k) is not None and not isinstance(data[k], str) for k in ("modelID", "providerID", "variant")): - _oops(con, stats, src_path, ordinal, "malformed_usage", _record_line(msg.get("data"), data)) - return - measurement = dict(values, total_tokens=total, model=data.get("modelID"), provider=data.get("providerID"), - effort=data.get("variant"), cost_usd=cost_usd) - _observe_response(con, session_key, rid, source_id, parent, measurement, ts, index) + raise ValueError("malformed_usage") + return dict(values, total_tokens=total, model=data.get("modelID"), provider=data.get("providerID"), + effort=data.get("variant"), cost_usd=cost_usd) def _observe_response(con, session_key, rid, source_id, parent, measurement, ts, index): diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index b2773d8..c016c2d 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -164,6 +164,9 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me elif harness == "opencode": from .adapters import opencode responses, disputed_completions = opencode.response_witnesses(con, key) + # A malformed native measurement can leave an ownership dispute + # without any projected usage row. It still makes coverage incomplete. + result.conflicts.update(disputed_completions) elif harness == "grok": from .adapters import grok responses, call_witnesses, disputed_completions = grok.response_witnesses(con, key) diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py index ba7fa91..684a3ae 100644 --- a/tests/test_evidence_coverage.py +++ b/tests/test_evidence_coverage.py @@ -151,6 +151,61 @@ def test_opencode_proved_then_parentless_copy(self): def test_opencode_parentless_then_proved_copy(self): self.check_opencode_copies(True) + def test_malformed_refresh_preserves_competing_parent(self): + first = self.opencode_store("one", "msg_u1", 0.20, 50, independent=True) + second = self.opencode_store("two", "other", 0.20, 50) + with closing(sqlite3.connect(second)) as source, source: + source.execute("INSERT INTO message SELECT 'other',session_id,time_created,time_updated,data " + "FROM message WHERE id='msg_u1'") + for path in (first, second): + opencode.sync(self.con, source=path) + self.assign("A", "opencode:msg_u1") + self.assertEqual(report.task_report(self.con, "A")["attributed"]["responses"], 1) + with closing(sqlite3.connect(second)) as source, source: + source.execute("UPDATE message SET data=json_set(data,'$.tokens.output','bad') WHERE id='msg_a1'") + source.execute("UPDATE session SET time_updated=time_updated+1 WHERE id='ses_parent'") + refresh = opencode.sync(self.con, source=second) + self.assertEqual(refresh["failed"], []) + self.assertEqual(refresh["malformed"], 1) + rep = report.task_report(self.con, "A") + self.assertEqual(rep["measured"]["attributed_responses"], ["opencode:msg_unique"]) + self.assertEqual(rep["measured"]["unplaced_responses"], ["opencode:msg_a1"]) + self.assertFalse(report.timeline(self.con, "A")["events"]) + draft = self.draft() + self.assertIn("Evidence complete: no", draft["body"]) + self.assertEqual(draft["summary"]["native_cost"]["known_subtotal_usd"], 0.10) + with closing(sqlite3.connect(second)) as source, source: + source.execute("UPDATE message SET data=json_set(data,'$.tokens.output',50,'$.parentID','msg_u1') " + "WHERE id='msg_a1'") + source.execute("UPDATE session SET time_updated=time_updated+1 WHERE id='ses_parent'") + opencode.sync(self.con, source=second) + self.assertAlmostEqual(report.task_report(self.con, "A")["native_cost"]["known_subtotal_usd"], 0.30) + + def check_unusable_claude_ancestry(self, field, value): + path = self.import_claude() + self.assign("B", "claude:b") + rows = [json.loads(line) for line in path.read_text().splitlines()] + response = rows[-1] + self.assertEqual(response["parentUuid"], "b") + if value is None: + del response[field] + else: + response[field] = value + write_records(path, rows) + claude.import_claude_file(self.con, str(path), full=True) + rep = report.task_report(self.con, "A") + self.assertEqual(rep["measured"]["attributed_responses"], ["claude:msg-a"]) + self.assertEqual(rep["measured"]["unplaced_responses"], ["claude:msg-b"]) + self.assertFalse(report.task_report(self.con, "B")["measured"]["attributed_responses"]) + self.assertEqual([e["native_id"] for e in report.timeline(self.con, "A")["events"]], ["a-call"]) + self.assertIn("Evidence complete: no", self.draft()["body"]) + + def test_claude_parent_without_node_cannot_fall_back_to_display_turn(self): + self.check_unusable_claude_ancestry("uuid", None) + + def test_claude_malformed_parent_cannot_fall_back_to_display_turn(self): + self.check_unusable_claude_ancestry("parentUuid", "bad parent") + def test_unresolved_literal_parent_cannot_use_legacy_capture(self): path = self.import_claude(legacy=True) records = [json.loads(line) for line in path.read_text().splitlines()] From eaa8cfbd5ccdeb09fb7a69846d819884afb3e08b Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 21:01:19 +0100 Subject: [PATCH 28/44] wip: retain unresolved source identities and withhold incomplete totals --- agent_observer/adapters/claude.py | 39 +++++++++++++++-- agent_observer/adapters/opencode.py | 66 ++++++++++++++++++++--------- agent_observer/outcome.py | 6 +-- agent_observer/report.py | 2 +- tests/test_evidence_coverage.py | 60 ++++++++++++++++++++++++++ 5 files changed, 144 insertions(+), 29 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index b82c708..6c8f027 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -106,7 +106,7 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 8 # Distinguish unusable ancestry from historical records without an edge. +_IMPORT_VERSION = 9 # Replay usable identities alongside rejected measurements. def _ensure_native_kinds(con) -> None: @@ -428,9 +428,11 @@ def import_claude_file(con: sqlite3.Connection, path: str, " AND ordinal_num=? AND error='unsupported_schema'", (HARNESS, path, ordinal)) except _UsageConflict: + _record_ancestry(r, obj, rejected="usage_conflict") stats["malformed"] += 1 src.error(ordinal, "usage_conflict", line) except _MalformedUsage: + _record_ancestry(r, obj, rejected="malformed_usage") stats["malformed"] += 1 src.error(ordinal, "malformed_usage", line) except MissingNativeId: @@ -440,6 +442,8 @@ def import_claude_file(con: sqlite3.Connection, path: str, stats["malformed"] += 1 src.error(ordinal, "unsupported_schema", line) except (KeyError, TypeError, ValueError, AttributeError): + if obj.get("type") == "assistant": + _record_ancestry(r, obj, rejected="schema_error") stats["malformed"] += 1 src.error(ordinal, "schema_error", line) if r.native_session: @@ -1090,13 +1094,18 @@ def _prepare_ancestry(r): source_id INTEGER NOT NULL REFERENCES sources(id), session_key TEXT NOT NULL, uuid TEXT NOT NULL, response_id TEXT NOT NULL, PRIMARY KEY(session_key, source_id, uuid, response_id)) WITHOUT ROWID""") + r.con.execute("""CREATE TABLE IF NOT EXISTS claude_rejected_measurements ( + session_key TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), + uuid TEXT NOT NULL, parent TEXT NOT NULL, response_id TEXT NOT NULL, reason TEXT NOT NULL, + PRIMARY KEY(session_key, source_id, uuid, parent, response_id, reason)) WITHOUT ROWID""") if not r.src.incremental: r.con.execute("DELETE FROM claude_response_ancestry WHERE source_id=?", (r.src.source_id,)) r.con.execute("DELETE FROM claude_invalid_ancestry WHERE source_id=?", (r.src.source_id,)) + r.con.execute("DELETE FROM claude_rejected_measurements WHERE source_id=?", (r.src.source_id,)) -def _record_ancestry(r, obj): +def _record_ancestry(r, obj, rejected=None): uuid = native_response.identifier(obj.get("uuid")) if (not r.native_session or obj.get("sessionId") != r.native_session or (obj.get("agentId") and obj["agentId"] != r.agent_id)): @@ -1123,8 +1132,9 @@ def _record_ancestry(r, obj): mid = native_response.identifier(message.get("id")) if mid and message.get("model") != "": response_id = f"{HARNESS}:{mid}" - for family, event_id in r.message_events: - native_response.record_event(r.con, r.src.source_id, r.session_key, family, event_id, response_id) + if not rejected: + for family, event_id in r.message_events: + native_response.record_event(r.con, r.src.source_id, r.session_key, family, event_id, response_id) elif kind == "attachment" and isinstance(obj.get("attachment"), dict): if obj["attachment"].get("type") == "queued_command": # A consumed queued input has its own identity. A missing identity @@ -1141,6 +1151,10 @@ def _record_ancestry(r, obj): r.con.execute("INSERT OR IGNORE INTO claude_invalid_ancestry VALUES(?,?,?,?)", (r.src.source_id, r.session_key, uuid or "", response_id)) return + if rejected and response_id: + r.con.execute("INSERT OR IGNORE INTO claude_rejected_measurements VALUES(?,?,?,?,?,?)", + (r.session_key, r.src.source_id, uuid or "", parent or "", response_id, rejected)) + return if not uuid: return r.con.execute("INSERT OR IGNORE INTO claude_response_ancestry" @@ -1169,6 +1183,7 @@ def response_witnesses(con, session_key): if response_id: conflicts.add(response_id) recorded_parents = set() + accepted = set() for uuid, parent, input_id, response_id in con.execute( "SELECT DISTINCT uuid,parent,input_id,response_id FROM claude_response_ancestry" " WHERE session_key=?", (session_key,) @@ -1186,6 +1201,22 @@ def response_witnesses(con, session_key): children[parent].add(uuid) if response_id: blocks[response_id].add(uuid) + accepted.add((uuid, parent, response_id)) + if db._has_table(con, "claude_rejected_measurements"): + for uuid, parent, rid, reason, same_source in con.execute( + "SELECT q.uuid,q.parent,q.response_id,q.reason,EXISTS (SELECT 1 FROM claude_response_ancestry a " + "WHERE a.source_id=q.source_id AND a.session_key=q.session_key AND a.response_id=q.response_id) " + "FROM claude_rejected_measurements q WHERE q.session_key=?", + (session_key,)): + # Rejected measurements cannot grant ownership. A later usable + # block can confirm the same edge. A counter conflict on a new + # block cannot revise an already finalized response either. + if ((uuid, parent, rid) in accepted + or (reason == "usage_conflict" and same_source and uuid not in seen)): + continue + conflicts.add(rid) + if uuid: + disputed.add(uuid) # Contradictory copies of any ancestor also dispute its descendants, # even when a missing parent keeps the ordinary walk from reaching them. pending = deque(disputed) diff --git a/agent_observer/adapters/opencode.py b/agent_observer/adapters/opencode.py index 085af54..1f4f6d9 100644 --- a/agent_observer/adapters/opencode.py +++ b/agent_observer/adapters/opencode.py @@ -285,7 +285,7 @@ def _int_or_none(value): "total_tokens", "cost_usd") -def _prepare_observations(con, session_key, source_id): +def _prepare_observations(con, session_key, source_id, *, messages_read): # A snapshot replaces only this store's observations. Keep the projection # fields needed to restore a surviving copy when another store changes. con.execute("""CREATE TABLE IF NOT EXISTS opencode_response_observations ( @@ -297,7 +297,7 @@ def _prepare_observations(con, session_key, source_id): # another copy can replace its projection. Only its own edge accompanies it. for row in con.execute( "SELECT r.* FROM responses r JOIN sources s ON s.id=r.source_id WHERE r.session_key=? " - "AND r.source_id<>? AND s.sha256 NOT GLOB 'oc[34]:*' AND NOT EXISTS " + "AND r.source_id<>? AND s.sha256 NOT GLOB 'oc[3-5]:*' AND NOT EXISTS " "(SELECT 1 FROM opencode_response_observations o WHERE o.session_key=r.session_key " "AND o.response_id=r.response_id AND o.source_id=r.source_id)", (session_key, source_id)): parent = con.execute( @@ -306,7 +306,15 @@ def _prepare_observations(con, session_key, source_id): measurement = {name: row[name] for name in _MEASUREMENT_FIELDS} _observe_response(con, session_key, row["response_id"], row["source_id"], parent[0] if parent else None, measurement, row["ts"], row["ordinal_num"]) - con.execute("DELETE FROM opencode_response_observations WHERE source_id=?", (source_id,)) + if messages_read: + con.execute("DELETE FROM opencode_response_observations WHERE source_id=?", (source_id,)) + else: + # A failed read cannot establish that the store removed a witness. + con.execute("UPDATE opencode_response_observations SET measurement='null' WHERE source_id=?", (source_id,)) + con.execute("INSERT OR IGNORE INTO opencode_response_observations " + "(session_key,response_id,source_id,measurement,ts,ordinal_num) " + "SELECT session_key,response_id,source_id,'null',ts,ordinal_num FROM responses " + "WHERE session_key=? AND source_id=?", (session_key, source_id)) def _project_observations(con, stats, session_key, session_id): @@ -318,7 +326,8 @@ def _project_observations(con, stats, session_key, session_id): "WHERE session_key=? ORDER BY response_id,s.path", (session_key,)): groups.setdefault(row["response_id"], []).append(row) for rid, copies in groups.items(): - measured = [(row, json.loads(row["measurement"])) for row in copies if row["measurement"] != "null"] + payloads = ((row, json.loads(row["measurement"])) for row in copies) + measured = [(row, data) for row, data in payloads if isinstance(data, dict)] # A rejected payload has a durable ownership witness, but cannot # create a billable row. An all-zero lifecycle record has no usage. if not measured or all(data["total_tokens"] == 0 for _, data in measured): @@ -342,13 +351,15 @@ def response_witnesses(con, session_key): payload_sources = {} observations = {} if db._has_table(con, "opencode_response_observations"): - for rid, source, parent, measurement in con.execute( - "SELECT o.response_id,o.source_id,o.parent,o.measurement FROM opencode_response_observations o " + for rid, source, parent, measurement, projected in con.execute( + "SELECT o.response_id,o.source_id,o.parent,o.measurement,r.response_id FROM opencode_response_observations o " "LEFT JOIN responses r USING(session_key,response_id) WHERE o.session_key=? AND coalesce(r.is_overlap,0)=0", (session_key,)): + if measurement == '"unfinished"' and not projected: + continue payload_sources.setdefault(rid, set()).add(source) observations.setdefault(rid, set()).add((parent, measurement)) - if measurement == "null": + if measurement == "null" or (projected and measurement == '"unfinished"'): conflicts.add(rid) if parent: witnesses.setdefault(rid, set()).add(parent) @@ -369,7 +380,7 @@ def response_witnesses(con, session_key): if db._has_table(con, "native_response_events"): for rid, source in con.execute( "SELECT DISTINCT e.response_id,e.source_id FROM native_response_events e " - "JOIN sources s ON s.id=e.source_id WHERE e.session_key=? AND s.sha256 NOT GLOB 'oc[34]:*'", + "JOIN sources s ON s.id=e.source_id WHERE e.session_key=? AND s.sha256 NOT GLOB 'oc[3-5]:*'", (session_key,)): if rid in measured and source not in payload_sources.get(rid, {measured[rid]}): conflicts.add(rid) @@ -476,7 +487,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, session_key = f"{HARNESS}:{sess_id}" msg_n, msg_m = _count_max(native, "message", sess_id) part_n, part_m = _count_max(native, "part", sess_id) - fp = "oc4:" + fingerprint(sess.get("time_updated"), msg_m, part_m, msg_n, part_n) + fp = "oc5:" + fingerprint(sess.get("time_updated"), msg_m, part_m, msg_n, part_n) row = con.execute( "SELECT * FROM sources WHERE harness=? AND path=?", (HARNESS, src_path)).fetchone() @@ -533,6 +544,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, _oops(con, stats, src_path, None, "source_unreadable") messages = [] complete = False + messages_read = complete try: parts = _fetch_dicts( native, "part", @@ -549,27 +561,35 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, by_message.setdefault(part.get("message_id"), []).append(part) roles: dict[str, str | None] = {} parsed_messages: list[tuple] = [] + unreadable = [] for index, msg in enumerate(messages): raw = msg.get("data") msg_id = msg.get("id") - if not msg_id or raw is None: + if not msg_id: _oops(con, stats, src_path, index, "schema_error") continue try: - data = json.loads(raw) + data = json.loads(raw) if raw is not None else None except (json.JSONDecodeError, TypeError, UnicodeDecodeError): _oops(con, stats, src_path, index, "malformed_json", _record_line(raw)) - continue - if not isinstance(data, dict): - _oops(con, stats, src_path, index, "schema_error", - _record_line(raw, data)) - continue - parsed_messages.append((index, msg, data)) - roles[msg_id] = data.get("role") + else: + if isinstance(data, dict): + parsed_messages.append((index, msg, data)) + roles[msg_id] = data.get("role") + if roles[msg_id] in ("assistant", "user"): + continue + else: + _oops(con, stats, src_path, index, "schema_error", _record_line(raw, data)) + # The SQLite primary key survives damage to the JSON body. Keep + # it even when this store is read before a measurable copy. + if native_response.identifier(msg_id): + unreadable.append((msg_id, index)) native_response.prepare(con, source_id, replace=True) native_response.prepare_events(con, source_id, replace=True) - _prepare_observations(con, session_key, source_id) + _prepare_observations(con, session_key, source_id, messages_read=messages_read) + for msg_id, index in unreadable: + _observe_response(con, session_key, f"{HARNESS}:{msg_id}", source_id, None, None, None, index) ordinal = 0 for index, msg, data in parsed_messages: ordinal += 1 @@ -658,8 +678,6 @@ def _ingest_message(con, native, stats, identity, src_path, source_id, def _ingest_response(con, stats, src_path, source_id, session_key, sess, msg, data, index, ts, ordinal, roles) -> None: timing = data.get("time") if isinstance(data.get("time"), dict) else {} - if timing.get("completed") is None: - return parent = native_response.identifier(data.get("parentID")) if roles.get(parent) != "user" or not native_response.identifier(msg["id"]): parent = None @@ -669,6 +687,12 @@ def _ingest_response(con, stats, src_path, source_id, session_key, sess, _oops(con, stats, src_path, ordinal, "usage_conflict", _record_line(msg.get("data"), data)) stats["responses_duplicate"] += 1 return + if timing.get("completed") is None: + # A provisional copy cannot attest that another copy's measurement + # is final. The unfinished observation alone creates no usage row. + if native_response.identifier(msg["id"]): + _observe_response(con, session_key, rid, source_id, parent, "unfinished", ts, index) + return try: measurement = _measurement(data) except ValueError: diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index c016c2d..ad8def9 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -164,14 +164,14 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me elif harness == "opencode": from .adapters import opencode responses, disputed_completions = opencode.response_witnesses(con, key) - # A malformed native measurement can leave an ownership dispute - # without any projected usage row. It still makes coverage incomplete. - result.conflicts.update(disputed_completions) elif harness == "grok": from .adapters import grok responses, call_witnesses, disputed_completions = grok.response_witnesses(con, key) else: responses = native_response.inputs(con, key) + # Rejected native records can leave an ownership dispute without a + # projected usage row. It still makes coverage incomplete. + result.conflicts.update(disputed_completions) # In a contested whole session, only events on resolved turns can be # shown. Untagged events cannot be separated between the claimants. exclusive = not by_run or (whole == {task_id} and set(by_run.values()) == {task_id}) diff --git a/agent_observer/report.py b/agent_observer/report.py index a7e7bae..289e64d 100644 --- a/agent_observer/report.py +++ b/agent_observer/report.py @@ -933,7 +933,7 @@ def _resp_tuple(r) -> list: report["coverage"]["unavailable_sources"] = unavailable_sources report["total_cost"] = _total_cost( task_id, total_estimated, attributed, billed_shared, sharing_tasks) - if (inventory_gaps or unresolved_usage) and total_estimated.get("priced_responses"): + if unavailable_usage and total_estimated.get("priced_responses"): subtotal = total_estimated["estimated_cost_usd_partial"] amount = "under $0.01" if 0 < subtotal < 0.005 else f"${subtotal:,.2f}" report["total_cost"].update(usd=None, observed_subtotal_usd=subtotal, diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py index 684a3ae..e814071 100644 --- a/tests/test_evidence_coverage.py +++ b/tests/test_evidence_coverage.py @@ -206,6 +206,66 @@ def test_claude_parent_without_node_cannot_fall_back_to_display_turn(self): def test_claude_malformed_parent_cannot_fall_back_to_display_turn(self): self.check_unusable_claude_ancestry("parentUuid", "bad parent") + def test_unreadable_opencode_message_still_disputes_its_copy(self): + first = self.opencode_store("one", "msg_u1", 0.20, 50, independent=True) + second = self.opencode_store("two", "other", 0.20, 50) + with closing(sqlite3.connect(second)) as source, source: + source.execute("INSERT INTO message SELECT 'other',session_id,time_created,time_updated,data " + "FROM message WHERE id='msg_u1'") + for path in (first, second): + opencode.sync(self.con, source=path) + self.assign("A", "opencode:msg_u1") + self.assertEqual(report.task_report(self.con, "A")["attributed"]["responses"], 1) + with closing(sqlite3.connect(second)) as source, source: + source.execute("UPDATE message SET data='{' WHERE id='msg_a1'") + source.execute("UPDATE session SET time_updated=time_updated+1 WHERE id='ses_parent'") + self.assertEqual(opencode.sync(self.con, source=second)["malformed"], 1) + rep = report.task_report(self.con, "A") + self.assertEqual(rep["measured"]["attributed_responses"], ["opencode:msg_unique"]) + self.assertFalse(report.timeline(self.con, "A")["events"]) + self.assertEqual(rep["native_cost"]["known_subtotal_usd"], 0.10) + self.assertIn("Evidence complete: no", self.draft()["body"]) + with closing(sqlite3.connect(first)) as original: + data = json.loads(original.execute("SELECT data FROM message WHERE id='msg_a1'").fetchone()[0]) + del data["time"]["completed"] + with closing(sqlite3.connect(second)) as source, source: + source.execute("UPDATE message SET data=? WHERE id='msg_a1'", (json.dumps(data),)) + opencode.sync(self.con, source=second, full=True) + self.assertEqual(report.task_report(self.con, "A")["measured"]["attributed_responses"], ["opencode:msg_unique"]) + + def test_rejected_claude_counters_do_not_resolve_conflicting_parents(self): + path = self.import_claude() + self.assign("B", "claude:b") + rows = [json.loads(line) for line in path.read_text().splitlines()] + response = rows[-1] + response["parentUuid"] = "a" + copy = path.with_name("copy.jsonl") + write_records(copy, rows) + claude.import_claude_file(self.con, str(copy)) + self.assertFalse(report.task_report(self.con, "B")["attributed"]["responses"]) + response["message"]["usage"]["output_tokens"] = "bad" + write_records(copy, rows) + claude.import_claude_file(self.con, str(copy), full=True) + self.assertFalse(report.task_report(self.con, "B")["attributed"]["responses"]) + self.assertFalse(report.timeline(self.con, "B")["events"]) + self.assertIn("Evidence complete: no", self.draft()["body"]) + response["message"]["usage"]["output_tokens"] = 5 + response["parentUuid"] = "b" + write_records(copy, rows) + claude.import_claude_file(self.con, str(copy), full=True) + self.assertEqual(report.task_report(self.con, "B")["measured"]["attributed_responses"], ["claude:msg-b"]) + + def test_missing_usage_row_keeps_priced_subtotal_separate(self): + self.import_claude(legacy=True) + only = self.opencode_store("damaged", "msg_u1", 0.20, "bad") + opencode.sync(self.con, source=only) + self.assign("A", "opencode:msg_u1") + rep = report.task_report(self.con, "A") + self.assertFalse(rep["complete"]) + self.assertIsNone(rep["total_cost"]["usd"]) + self.assertGreater(rep["total_cost"]["observed_subtotal_usd"], 0) + self.assertIn("Estimated cost unknown", self.draft()["body"]) + def test_unresolved_literal_parent_cannot_use_legacy_capture(self): path = self.import_claude(legacy=True) records = [json.loads(line) for line in path.read_text().splitlines()] From 7c808179fadb38f481d1fb3adf64f90de5b36dcc Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 21:05:53 +0100 Subject: [PATCH 29/44] wip: bound legacy capture and missing usage to their source evidence Integrate additional source-replay coverage from local WIP 62fb0cc and retain the seventh-review fixes for rejected measurements and unknown totals. --- agent_observer/adapters/claude.py | 168 ++++++++++++++++++--------- agent_observer/adapters/opencode.py | 174 +++++++++++++++------------- agent_observer/native_response.py | 7 +- agent_observer/outcome.py | 35 ++++-- agent_observer/report.py | 8 +- tests/test_evidence_coverage.py | 162 ++++++++++++++++++++++++++ 6 files changed, 411 insertions(+), 143 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index 6c8f027..eb38d1c 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -106,7 +106,7 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 9 # Replay usable identities alongside rejected measurements. +_IMPORT_VERSION = 10 # Replay usable identities alongside rejected measurements. def _ensure_native_kinds(con) -> None: @@ -446,6 +446,8 @@ def import_claude_file(con: sqlite3.Connection, path: str, _record_ancestry(r, obj, rejected="schema_error") stats["malformed"] += 1 src.error(ordinal, "schema_error", line) + con.executemany("INSERT OR IGNORE INTO claude_ancestry_sources VALUES(?,?)", + ((key, src.source_id) for key in r.linked_sessions)) if r.native_session: fields = {"started_at": r.first_ts, "ended_at": r.last_ts, **r.meta, **r.identity.fields(con)} @@ -1086,23 +1088,33 @@ def _prepare_ancestry(r): session_key TEXT NOT NULL, uuid TEXT NOT NULL, parent TEXT NOT NULL, input_id TEXT NOT NULL, response_id TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), + link_status TEXT NOT NULL DEFAULT 'unknown', PRIMARY KEY(session_key, uuid, parent, input_id, response_id, source_id) ) WITHOUT ROWID""") + if "link_status" not in {col[1] for col in r.con.execute("PRAGMA table_info(claude_response_ancestry)")}: + r.con.execute("ALTER TABLE claude_response_ancestry ADD COLUMN link_status TEXT NOT NULL DEFAULT 'unknown'") r.con.execute("CREATE INDEX IF NOT EXISTS claude_ancestry_source" " ON claude_response_ancestry(source_id)") - r.con.execute("""CREATE TABLE IF NOT EXISTS claude_invalid_ancestry ( - source_id INTEGER NOT NULL REFERENCES sources(id), session_key TEXT NOT NULL, - uuid TEXT NOT NULL, response_id TEXT NOT NULL, - PRIMARY KEY(session_key, source_id, uuid, response_id)) WITHOUT ROWID""") + r.con.execute("""CREATE TABLE IF NOT EXISTS claude_ancestry_sources ( + session_key TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), + PRIMARY KEY(session_key,source_id)) WITHOUT ROWID""") r.con.execute("""CREATE TABLE IF NOT EXISTS claude_rejected_measurements ( session_key TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), uuid TEXT NOT NULL, parent TEXT NOT NULL, response_id TEXT NOT NULL, reason TEXT NOT NULL, PRIMARY KEY(session_key, source_id, uuid, parent, response_id, reason)) WITHOUT ROWID""") + r.linked_sessions = set() if not r.src.incremental: - r.con.execute("DELETE FROM claude_response_ancestry WHERE source_id=?", - (r.src.source_id,)) - r.con.execute("DELETE FROM claude_invalid_ancestry WHERE source_id=?", (r.src.source_id,)) + if r.src.row["claude_usage_version"] in (6, 7, 8, 9): + r.con.execute("INSERT OR IGNORE INTO claude_ancestry_sources " + "SELECT DISTINCT session_key,source_id FROM claude_response_ancestry " + "WHERE source_id=? AND parent<>''", (r.src.source_id,)) + if db._has_table(r.con, "claude_invalid_ancestry"): + r.con.execute("INSERT OR IGNORE INTO claude_ancestry_sources " + "SELECT session_key,source_id FROM claude_invalid_ancestry WHERE source_id=?", + (r.src.source_id,)) + r.con.execute("DELETE FROM claude_invalid_ancestry WHERE source_id=?", (r.src.source_id,)) r.con.execute("DELETE FROM claude_rejected_measurements WHERE source_id=?", (r.src.source_id,)) + r.con.execute("DELETE FROM claude_response_ancestry WHERE source_id=?", (r.src.source_id,)) def _record_ancestry(r, obj, rejected=None): @@ -1144,24 +1156,49 @@ def _record_ancestry(r, obj, rejected=None): return elif kind not in ("system", "progress"): return - # A supplied edge needs both endpoints. Keep its independently valid - # identities so a damaged copy cannot turn into historical display capture. - if not input_id and "parentUuid" in obj and (not uuid or not parent): - if uuid or response_id: - r.con.execute("INSERT OR IGNORE INTO claude_invalid_ancestry VALUES(?,?,?,?)", - (r.src.source_id, r.session_key, uuid or "", response_id)) + if not uuid and not response_id and "parentUuid" not in obj and "uuid" not in obj: return + invalid = ((not uuid and ("uuid" in obj or obj.get("parentUuid") is not None)) + or (not parent and obj.get("parentUuid") is not None)) + if invalid: + status = "invalid" + elif parent: + status = "linked" + elif "parentUuid" in obj and not input_id: + status = "root" + else: + status = "absent" + # Erasing the last parent on rewrite cannot turn this source into a + # pre-ancestry format. Remember the format independently of ownership. + if status != "absent": + r.linked_sessions.add(r.session_key) if rejected and response_id: r.con.execute("INSERT OR IGNORE INTO claude_rejected_measurements VALUES(?,?,?,?,?,?)", (r.session_key, r.src.source_id, uuid or "", parent or "", response_id, rejected)) return - if not uuid: - return - r.con.execute("INSERT OR IGNORE INTO claude_response_ancestry" - "(session_key,uuid,parent,input_id,response_id,source_id)" - " VALUES(?,?,?,?,?,?)", - (r.session_key, uuid, "" if input_id else parent or "", - input_id, response_id, r.src.source_id)) + r.con.execute("INSERT INTO claude_response_ancestry" + "(session_key,uuid,parent,input_id,response_id,source_id,link_status)" + " VALUES(?,?,?,?,?,?,?) ON CONFLICT DO UPDATE SET link_status=" + "CASE WHEN link_status='invalid' OR excluded.link_status='invalid' THEN 'invalid' " + "WHEN link_status='linked' OR excluded.link_status='linked' THEN 'linked' " + "WHEN link_status='root' OR excluded.link_status='root' THEN 'root' ELSE excluded.link_status END", + (r.session_key, uuid or "", "" if input_id else parent or "", + input_id, response_id, r.src.source_id, status)) + + +def legacy_capture_sources(con, session_key): + """Sources with historical turn capture, or positive evidence of a parentless format.""" + legacy = {r[0] for r in con.execute( + "SELECT DISTINCT e.source_id FROM events e JOIN sources s ON s.id=e.source_id " + "WHERE e.session_key=? AND COALESCE(s.claude_usage_version,0)<6", (session_key,))} + if "link_status" in {c[1] for c in con.execute("PRAGMA table_info(claude_response_ancestry)")}: + legacy.update(r[0] for r in con.execute( + "SELECT source_id FROM claude_response_ancestry WHERE session_key=? GROUP BY source_id " + "HAVING MIN(link_status='absent' AND parent='') AND MAX(response_id<>'')", (session_key,))) + if db._has_table(con, "claude_ancestry_sources"): + legacy.difference_update(source for source, in con.execute( + "SELECT source_id FROM claude_ancestry_sources WHERE session_key=?", (session_key,))) + return legacy def response_witnesses(con, session_key): @@ -1171,9 +1208,53 @@ def response_witnesses(con, session_key): parents must all resolve, and competing inputs survive for the consumer. """ if not db._has_table(con, "claude_response_ancestry"): - return {}, set() + unresolved = {rid: set() for rid, in con.execute( + "SELECT r.response_id FROM responses r JOIN sources s ON s.id=r.source_id " + "WHERE r.session_key=? AND r.is_overlap=0 AND s.claude_usage_version>=6", (session_key,))} + return unresolved, set() parents, children, anchors, blocks = (defaultdict(set) for _ in range(4)) - seen, disputed = set(), set() + seen, disputed = {}, set() + legacy_sources = legacy_capture_sources(con, session_key) + accepted = set() + recorded_blocks = set() + unlinked = defaultdict(set) + unusable, unlocated, linked_responses = set(), set(), set() + columns = {col[1] for col in con.execute("PRAGMA table_info(claude_response_ancestry)")} + status_column = "link_status" if "link_status" in columns else "'unknown'" + for uuid, parent, input_id, rid, source, status in con.execute( + f"SELECT uuid,parent,input_id,response_id,source_id,{status_column} " + "FROM claude_response_ancestry WHERE session_key=?", (session_key,)): + if rid and uuid: + recorded_blocks.add((rid, source)) + accepted.add((uuid, parent, rid)) + if rid and status == "absent": + unlinked[rid].add(source) + if rid and parent: + linked_responses.add(rid) + if rid and status in {"root", "invalid"}: + unusable.add(rid) + if not uuid: + if rid: + unlocated.add(rid) + continue # No graph vertex. The response still has a source observation. + edge = (parent, input_id, rid) + if seen.setdefault(uuid, edge) != edge: + disputed.add(uuid) + if input_id: + anchors[uuid].add(input_id) + elif parent: + parents[uuid].add(parent) + children[parent].add(uuid) + if rid: + blocks[rid].add(uuid) + if db._has_table(con, "native_response_events"): + # Version 7 kept an event edge even when it dropped the response's + # malformed graph position. That copy cannot validate another copy. + for rid, source in con.execute( + "SELECT DISTINCT e.response_id,e.source_id FROM native_response_events e JOIN sources s ON s.id=e.source_id " + "WHERE e.session_key=? AND s.claude_usage_version BETWEEN 7 AND 9", (session_key,)): + if (rid, source) not in recorded_blocks: + unlocated.add(rid) conflicts = set() if db._has_table(con, "claude_invalid_ancestry"): for uuid, response_id in con.execute( @@ -1182,26 +1263,6 @@ def response_witnesses(con, session_key): disputed.add(uuid) if response_id: conflicts.add(response_id) - recorded_parents = set() - accepted = set() - for uuid, parent, input_id, response_id in con.execute( - "SELECT DISTINCT uuid,parent,input_id,response_id FROM claude_response_ancestry" - " WHERE session_key=?", (session_key,) - ): - # DISTINCT collapses identical copies. Another row for the same - # UUID contradicts its parent, input identity or message identity. - if uuid in seen: - disputed.add(uuid) - seen.add(uuid) - if input_id: - anchors[uuid].add(input_id) - elif parent: - recorded_parents.add(uuid) - parents[uuid].add(parent) - children[parent].add(uuid) - if response_id: - blocks[response_id].add(uuid) - accepted.add((uuid, parent, response_id)) if db._has_table(con, "claude_rejected_measurements"): for uuid, parent, rid, reason, same_source in con.execute( "SELECT q.uuid,q.parent,q.response_id,q.reason,EXISTS (SELECT 1 FROM claude_response_ancestry a " @@ -1237,18 +1298,19 @@ def response_witnesses(con, session_key): if not parents[child]: ready.append(child) results = {} - for response_id, in con.execute("SELECT response_id FROM responses" - " WHERE session_key=? AND is_overlap=0", (session_key,)): - nodes = blocks.get(response_id) - if not nodes: - continue - if nodes & disputed or (nodes & resolved and nodes - resolved): + for response_id, source, version in con.execute( + "SELECT r.response_id,r.source_id,s.claude_usage_version FROM responses r " + "JOIN sources s ON s.id=r.source_id WHERE r.session_key=? AND r.is_overlap=0", (session_key,)): + nodes = blocks[response_id] + if nodes & disputed or (nodes & resolved and (nodes - resolved or response_id in unlocated)): conflicts.add(response_id) - if nodes <= resolved: + elif nodes and nodes <= resolved: results[response_id] = set.union(*(anchors[node] for node in nodes)) - elif nodes & recorded_parents: - # An empty witness set means a recorded, unresolved parent. - # Only an absent key can use historical explicit turn capture. + elif (response_id in unusable or response_id in linked_responses or unlinked[response_id] - legacy_sources + or ((version or 0) >= 6 and source not in unlinked[response_id])): + # Only a positively observed parentless record from a legacy source + # can fall back to its captured display turn. Versions 6/7 lost the + # distinction between absent and malformed parents until replay. results[response_id] = set() return results, conflicts diff --git a/agent_observer/adapters/opencode.py b/agent_observer/adapters/opencode.py index 1f4f6d9..02eb3d8 100644 --- a/agent_observer/adapters/opencode.py +++ b/agent_observer/adapters/opencode.py @@ -285,7 +285,7 @@ def _int_or_none(value): "total_tokens", "cost_usd") -def _prepare_observations(con, session_key, source_id, *, messages_read): +def _prepare_observations(con, session_key, source_id, *, identities_complete): # A snapshot replaces only this store's observations. Keep the projection # fields needed to restore a surviving copy when another store changes. con.execute("""CREATE TABLE IF NOT EXISTS opencode_response_observations ( @@ -297,7 +297,7 @@ def _prepare_observations(con, session_key, source_id, *, messages_read): # another copy can replace its projection. Only its own edge accompanies it. for row in con.execute( "SELECT r.* FROM responses r JOIN sources s ON s.id=r.source_id WHERE r.session_key=? " - "AND r.source_id<>? AND s.sha256 NOT GLOB 'oc[3-5]:*' AND NOT EXISTS " + "AND r.source_id<>? AND s.sha256 NOT GLOB 'oc[3-6]:*' AND NOT EXISTS " "(SELECT 1 FROM opencode_response_observations o WHERE o.session_key=r.session_key " "AND o.response_id=r.response_id AND o.source_id=r.source_id)", (session_key, source_id)): parent = con.execute( @@ -306,15 +306,13 @@ def _prepare_observations(con, session_key, source_id, *, messages_read): measurement = {name: row[name] for name in _MEASUREMENT_FIELDS} _observe_response(con, session_key, row["response_id"], row["source_id"], parent[0] if parent else None, measurement, row["ts"], row["ordinal_num"]) - if messages_read: + if identities_complete: con.execute("DELETE FROM opencode_response_observations WHERE source_id=?", (source_id,)) else: - # A failed read cannot establish that the store removed a witness. - con.execute("UPDATE opencode_response_observations SET measurement='null' WHERE source_id=?", (source_id,)) - con.execute("INSERT OR IGNORE INTO opencode_response_observations " - "(session_key,response_id,source_id,measurement,ts,ordinal_num) " - "SELECT session_key,response_id,source_id,'null',ts,ordinal_num FROM responses " - "WHERE session_key=? AND source_id=?", (session_key, source_id)) + # A row with no usable id could be any missing row from this store. + # Refresh the identifiable rows below; no old counters or parent win by default. + con.execute("UPDATE opencode_response_observations SET measurement=?,parent=NULL WHERE source_id=?", + (json.dumps("unknown_message"), source_id)) def _project_observations(con, stats, session_key, session_id): @@ -328,13 +326,12 @@ def _project_observations(con, stats, session_key, session_id): for rid, copies in groups.items(): payloads = ((row, json.loads(row["measurement"])) for row in copies) measured = [(row, data) for row, data in payloads if isinstance(data, dict)] - # A rejected payload has a durable ownership witness, but cannot - # create a billable row. An all-zero lifecycle record has no usage. - if not measured or all(data["total_tokens"] == 0 for _, data in measured): - if not con.execute("SELECT 1 FROM responses WHERE session_key=? AND response_id=?", - (session_key, rid)).fetchone(): - continue - copy, data = measured[0] if measured else (copies[0], dict.fromkeys(_MEASUREMENT_FIELDS)) + if not measured: + # An observed completed response whose current counters are invalid + # no longer has an atomic usage row. Its native identity survives. + con.execute("DELETE FROM responses WHERE session_key=? AND response_id=?", (session_key, rid)) + continue + copy, data = measured[0] for _, other in measured[1:]: for field, value in other.items(): if data[field] != value: @@ -350,29 +347,32 @@ def response_witnesses(con, session_key): conflicts = set() payload_sources = {} observations = {} + malformed = {} + measured = dict(con.execute("SELECT response_id,source_id FROM responses WHERE session_key=? AND is_overlap=0", + (session_key,))) if db._has_table(con, "opencode_response_observations"): - for rid, source, parent, measurement, projected in con.execute( - "SELECT o.response_id,o.source_id,o.parent,o.measurement,r.response_id FROM opencode_response_observations o " - "LEFT JOIN responses r USING(session_key,response_id) WHERE o.session_key=? AND coalesce(r.is_overlap,0)=0", - (session_key,)): - if measurement == '"unfinished"' and not projected: - continue - payload_sources.setdefault(rid, set()).add(source) + for rid, source, parent, measurement in con.execute( + "SELECT response_id,source_id,parent,measurement FROM opencode_response_observations " + "WHERE session_key=?", (session_key,)): observations.setdefault(rid, set()).add((parent, measurement)) - if measurement == "null" or (projected and measurement == '"unfinished"'): - conflicts.add(rid) - if parent: - witnesses.setdefault(rid, set()).add(parent) + if measurement in _INVALID_OBSERVATIONS: + malformed[rid] = set() + if rid in measured: + payload_sources.setdefault(rid, set()).add(source) for rid, variants in observations.items(): - # Competing proved parents are returned together. A missing parent - # or incompatible payload additionally invalidates the measurement. + if rid not in measured and rid not in malformed: + continue + parents = {parent for parent, _ in variants if parent} + if rid in malformed: + malformed[rid] = parents + if rid in measured and parents: + witnesses[rid] = parents if len(variants) > 1 and (any(parent is None for parent, _ in variants) or len({payload for _, payload in variants}) > 1): conflicts.add(rid) # Old imports recorded edges but kept only the last copy's payload. # An edge from a copy whose measurement was lost cannot vouch for it. - measured = dict(con.execute("SELECT response_id,source_id FROM responses WHERE session_key=?", (session_key,))) for rid, input_id, source, measured_source in native_response.stored_inputs(con, session_key): if source not in payload_sources.get(rid, {measured_source}): conflicts.add(rid) @@ -380,11 +380,22 @@ def response_witnesses(con, session_key): if db._has_table(con, "native_response_events"): for rid, source in con.execute( "SELECT DISTINCT e.response_id,e.source_id FROM native_response_events e " - "JOIN sources s ON s.id=e.source_id WHERE e.session_key=? AND s.sha256 NOT GLOB 'oc[3-5]:*'", + "JOIN sources s ON s.id=e.source_id WHERE e.session_key=? AND s.sha256 NOT GLOB 'oc[4-6]:*'", (session_key,)): if rid in measured and source not in payload_sources.get(rid, {measured[rid]}): conflicts.add(rid) - return witnesses, conflicts + return witnesses, conflicts, malformed + + +def has_unlocated_usage_error(con, session_key): + # Older adapters quarantined a malformed usage record by ordinal only. + # Keep the session's cost open without guessing which message failed. + return con.execute( + "SELECT 1 FROM sources s WHERE s.harness=? AND s.session_id=? AND " + "(s.sha256=? OR (s.sha256 NOT GLOB 'oc[4-6]:*' AND EXISTS (SELECT 1 FROM import_errors e " + "WHERE e.harness=s.harness AND e.source_path=s.path AND e.error='malformed_usage' " + "AND instr(','||e.line_excerpt||',', ',tokens,')>0))) LIMIT 1", + (HARNESS, session_key.partition(":")[2], _UNLOCATED_SNAPSHOT)).fetchone() is not None def _project_response(con, stats, rid, session_key, session_id, locator, measurement): @@ -487,7 +498,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, session_key = f"{HARNESS}:{sess_id}" msg_n, msg_m = _count_max(native, "message", sess_id) part_n, part_m = _count_max(native, "part", sess_id) - fp = "oc5:" + fingerprint(sess.get("time_updated"), msg_m, part_m, msg_n, part_n) + fp = "oc6:" + fingerprint(sess.get("time_updated"), msg_m, part_m, msg_n, part_n) row = con.execute( "SELECT * FROM sources WHERE harness=? AND path=?", (HARNESS, src_path)).fetchone() @@ -534,6 +545,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, " detail_json=NULL WHERE source_id=?", (source_id,)) complete = True + messages_read = True try: messages = _fetch_dicts( native, "message", @@ -543,8 +555,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, except sqlite3.Error: _oops(con, stats, src_path, None, "source_unreadable") messages = [] - complete = False - messages_read = complete + messages_read = complete = False try: parts = _fetch_dicts( native, "part", @@ -561,35 +572,30 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, by_message.setdefault(part.get("message_id"), []).append(part) roles: dict[str, str | None] = {} parsed_messages: list[tuple] = [] - unreadable = [] + identities_complete = messages_read and all(native_response.identifier(msg.get("id")) for msg in messages) + native_response.prepare(con, source_id, replace=identities_complete) + native_response.prepare_events(con, source_id, replace=complete) + _prepare_observations(con, session_key, source_id, identities_complete=identities_complete) for index, msg in enumerate(messages): raw = msg.get("data") msg_id = msg.get("id") - if not msg_id: - _oops(con, stats, src_path, index, "schema_error") + if not native_response.identifier(msg_id): + _oops(con, stats, src_path, index, "missing_id") continue + error = "schema_error" try: - data = json.loads(raw) if raw is not None else None + data = json.loads(raw) except (json.JSONDecodeError, TypeError, UnicodeDecodeError): - _oops(con, stats, src_path, index, "malformed_json", - _record_line(raw)) - else: - if isinstance(data, dict): - parsed_messages.append((index, msg, data)) - roles[msg_id] = data.get("role") - if roles[msg_id] in ("assistant", "user"): - continue - else: - _oops(con, stats, src_path, index, "schema_error", _record_line(raw, data)) - # The SQLite primary key survives damage to the JSON body. Keep - # it even when this store is read before a measurable copy. - if native_response.identifier(msg_id): - unreadable.append((msg_id, index)) - native_response.prepare(con, source_id, replace=True) - native_response.prepare_events(con, source_id, replace=True) - _prepare_observations(con, session_key, source_id, messages_read=messages_read) - for msg_id, index in unreadable: - _observe_response(con, session_key, f"{HARNESS}:{msg_id}", source_id, None, None, None, index) + data = None + if raw is not None: + error = "malformed_json" + if not isinstance(data, dict): + _oops(con, stats, src_path, index, error, _record_line(raw, data)) + _observe_response(con, session_key, f"{HARNESS}:{msg_id}", source_id, None, + "unknown_message", iso_ts(msg.get("time_created")), index) + continue + parsed_messages.append((index, msg, data)) + roles[msg_id] = data.get("role") ordinal = 0 for index, msg, data in parsed_messages: ordinal += 1 @@ -625,10 +631,13 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, # Only a complete read advances the privacy version. An unreadable or # partially read source keeps its old version so the next sync retries. new_version = privacy.PRIVACY_VERSION if complete else stored_version + snapshot = fp if complete else "" + if not identities_complete: + snapshot = _UNLOCATED_SNAPSHOT con.execute( "UPDATE sources SET sha256=?, size_bytes=?, imported_at=?," " import_ms=?, session_id=?, privacy_version=? WHERE id=?", - (fp if complete else "", size_bytes, db.now(), + (snapshot, size_bytes, db.now(), int((time.monotonic() - started) * 1000), sess_id, new_version, source_id)) con.commit() @@ -667,17 +676,22 @@ def _ingest_message(con, native, stats, identity, src_path, source_id, _ingest_response(con, stats, src_path, source_id, session_key, sess, msg, data, index, ts, ordinal, roles) elif role == "user": + # A copy that calls this same message a user input contradicts an + # assistant observation, including when the user copy is imported first. + _observe_response(con, session_key, f"{HARNESS}:{msg_id}", source_id, None, + "user_message", ts, index) _ingest_submission(con, stats, identity, src_path, source_id, session_key, sess, msg, data, index, ts, msg_parts, ordinal) else: _oops(con, stats, src_path, ordinal, "unknown_record", _record_line(msg.get("data"), data)) + _observe_response(con, session_key, f"{HARNESS}:{msg_id}", source_id, None, + "unknown_message", ts, index) def _ingest_response(con, stats, src_path, source_id, session_key, sess, msg, data, index, ts, ordinal, roles) -> None: - timing = data.get("time") if isinstance(data.get("time"), dict) else {} parent = native_response.identifier(data.get("parentID")) if roles.get(parent) != "user" or not native_response.identifier(msg["id"]): parent = None @@ -687,23 +701,23 @@ def _ingest_response(con, stats, src_path, source_id, session_key, sess, _oops(con, stats, src_path, ordinal, "usage_conflict", _record_line(msg.get("data"), data)) stats["responses_duplicate"] += 1 return - if timing.get("completed") is None: - # A provisional copy cannot attest that another copy's measurement - # is final. The unfinished observation alone creates no usage row. - if native_response.identifier(msg["id"]): - _observe_response(con, session_key, rid, source_id, parent, "unfinished", ts, index) - return - try: - measurement = _measurement(data) - except ValueError: + measurement = _measurement(data) + if measurement == _MALFORMED_USAGE: _oops(con, stats, src_path, ordinal, "malformed_usage", _record_line(msg.get("data"), data)) - if not native_response.identifier(msg["id"]): - return - measurement = None _observe_response(con, session_key, rid, source_id, parent, measurement, ts, index) +# The observation holds either the measured fields or a reason they are unavailable. +_MAX_COUNTER = (1 << 63) - 1 # SQLite INTEGER. +_UNLOCATED_SNAPSHOT = "oc6:unlocated" # Never matches a complete snapshot fingerprint. +_MALFORMED_USAGE = "malformed_usage" +_INVALID_OBSERVATIONS = {"null", json.dumps(_MALFORMED_USAGE), json.dumps("unknown_message")} + + def _measurement(data): + timing = data.get("time") if isinstance(data.get("time"), dict) else {} + if timing.get("completed") is None: + return "unmeasured" raw_tokens = data.get("tokens") if raw_tokens is None: tokens: dict = {} @@ -712,14 +726,14 @@ def _measurement(data): else: # A present non-object tokens block is malformed usage, never # silently unknown; quarantine before any response insert. - raise ValueError("malformed_usage") + return _MALFORMED_USAGE raw_cache = tokens.get("cache") if raw_cache is None: cache: dict = {} elif isinstance(raw_cache, dict): cache = raw_cache else: - raise ValueError("malformed_usage") + return _MALFORMED_USAGE # A present counter must be a non-boolean integer; only a missing # key stays unknown and maps to NULL. An explicitly present null, # bool, string, float, list or other non-integer quarantines the @@ -736,23 +750,27 @@ def _measurement(data): values[field] = None continue raw = container[key] - if not isinstance(raw, int) or isinstance(raw, bool): - raise ValueError("malformed_usage") + if type(raw) is not int or not 0 <= raw <= _MAX_COUNTER: + return _MALFORMED_USAGE values[field] = raw + if all(v == 0 for v in values.values()): + return "unmeasured" total = None if all(v is not None for v in values.values()): total = sum(values.values()) + if total > _MAX_COUNTER: + return _MALFORMED_USAGE cost = data.get("cost") cost_usd = float(cost) if isinstance(cost, (int, float)) \ and not isinstance(cost, bool) else None if any(data.get(k) is not None and not isinstance(data[k], str) for k in ("modelID", "providerID", "variant")): - raise ValueError("malformed_usage") + return _MALFORMED_USAGE return dict(values, total_tokens=total, model=data.get("modelID"), provider=data.get("providerID"), effort=data.get("variant"), cost_usd=cost_usd) def _observe_response(con, session_key, rid, source_id, parent, measurement, ts, index): - con.execute("INSERT INTO opencode_response_observations" + con.execute("INSERT OR REPLACE INTO opencode_response_observations" "(session_key,response_id,source_id,parent,measurement,ts,ordinal_num) VALUES(?,?,?,?,?,?,?)", (session_key, rid, source_id, parent, json.dumps(measurement, sort_keys=True), ts, index)) diff --git a/agent_observer/native_response.py b/agent_observer/native_response.py index be173ce..7b5900b 100644 --- a/agent_observer/native_response.py +++ b/agent_observer/native_response.py @@ -49,7 +49,7 @@ def inputs(con: sqlite3.Connection, session_key: str) -> dict[str, set[str]]: return grok.response_inputs(con, session_key) if session_key.startswith("opencode:"): from .adapters import opencode - witnesses, conflicts = opencode.response_witnesses(con, session_key) + witnesses, conflicts, _ = opencode.response_witnesses(con, session_key) return {rid: ids for rid, ids in witnesses.items() if rid not in conflicts} found = defaultdict(set) for response_id, input_id, _, _ in stored_inputs(con, session_key): @@ -109,6 +109,9 @@ def event_responses(con, session_key): "WHERE session_key=?", (session_key,)): measured_sources[rid].add(source) claude = session_key.startswith("claude:") + if claude: + from .adapters.claude import legacy_capture_sources + legacy_sources = legacy_capture_sources(con, session_key) legacy_text = defaultdict(set) if claude and db._has_table(con, "claude_response_ancestry"): # Pre-event-edge ledgers still retain the UUID of each text block. @@ -119,6 +122,8 @@ def event_responses(con, session_key): legacy_text[source, uuid].add(rid) for event, source, family, native_id, turn in con.execute( "SELECT id,source_id,family,native_id,turn_id FROM events WHERE session_key=?", (session_key,)): + if claude and source not in legacy_sources: + turn = None # An event without a literal edge cannot inherit its display turn. if claude and family == "assistant_message": yield event, turn, edges[family, native_id] | legacy_text[source, native_id.rpartition(":")[0]] elif claude and family in {"tool_result", "permission", "skill_invoke", "file_change"}: diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index ad8def9..7c33fae 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -43,6 +43,8 @@ class Ownership: response_turns: dict = field(default_factory=dict) literal_sessions: set = field(default_factory=set) conflicts: set = field(default_factory=set) + unavailable_usage: set = field(default_factory=set) + unlocated_usage_sessions: set = field(default_factory=set) whole: set = field(default_factory=set) def event_turns(self, con, key): @@ -107,7 +109,10 @@ def evidence(con, task_id, scope): if runs or deliveries or session_runs or disputed_runs: result.native = {"version": 1, "task_id": task_id, "runs": runs, "deliveries": deliveries, - "membership": members, "sessions": session_runs, "conflicting_responses": sorted(result.conflicts), + "membership": members, "sessions": session_runs, + "unavailable_response_usage": sorted(result.unavailable_usage), + "unlocated_usage_sessions": sorted(result.unlocated_usage_sessions), + "conflicting_responses": sorted(result.conflicts), "conflicting_reference_kinds": reference_conflict, "conflicting_source_runs": disputed_runs} return result @@ -158,20 +163,21 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me result.literal_sessions.add(key) call_witnesses = set() disputed_completions = set() + malformed = {} if harness == "claude": from .adapters import claude responses, disputed_completions = claude.response_witnesses(con, key) + result.conflicts.update(disputed_completions) elif harness == "opencode": from .adapters import opencode - responses, disputed_completions = opencode.response_witnesses(con, key) + responses, disputed_completions, malformed = opencode.response_witnesses(con, key) + if opencode.has_unlocated_usage_error(con, key): + result.unlocated_usage_sessions.add(key) elif harness == "grok": from .adapters import grok responses, call_witnesses, disputed_completions = grok.response_witnesses(con, key) else: responses = native_response.inputs(con, key) - # Rejected native records can leave an ownership dispute without a - # projected usage row. It still makes coverage incomplete. - result.conflicts.update(disputed_completions) # In a contested whole session, only events on resolved turns can be # shown. Untagged events cannot be separated between the claimants. exclusive = not by_run or (whole == {task_id} and set(by_run.values()) == {task_id}) @@ -188,9 +194,11 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me if harness == "codex": blocked_turns.add(identity) exclusive = False - for rid, display_turn in con.execute( - "SELECT response_id,turn_id FROM responses WHERE session_key=? AND is_overlap=0", (key,)): - input_ids = responses.get(rid, set()) + measured_turns = dict(con.execute( + "SELECT response_id,turn_id FROM responses WHERE session_key=? AND is_overlap=0", (key,))) + for rid in measured_turns.keys() | malformed.keys(): + display_turn = measured_turns.get(rid) + input_ids = responses.get(rid, malformed.get(rid, set())) if rid in disputed_completions or len(input_ids) > 1: result.conflicts.add(rid) blocked_turns.update((display_turn, rid)) @@ -206,7 +214,10 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me display_turn in input_turns[identity] for identity in identities): unsafe_display.add(display_turn) candidates = {candidate for identity in input_ids for candidate in by_input.get(identity, ())} - claims = whole.copy() + unresolved_ancestry = harness == "claude" and rid in responses and not input_ids + claims = set() if unresolved_ancestry else whole.copy() + if unresolved_ancestry: + exclusive = False for identity in identities: claims.update(claimed_inputs[identity]) # Only an explicit capture may use the historical display turn. @@ -262,12 +273,16 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me result.response_turns[key, rid] = identities if rid in call_witnesses: validation = "grok_tool_call" + if rid not in measured_turns: + continue members[rid] = {"run_id": run, "session_key": key, "native_input_id": native_id, "provider_turn_id": turn, "segment_id": segment, "validation": validation} if harness == "codex": result.turns.add((key, "codex:" + native_id)) elif harness == "grok": result.turns.add((key, rid)) + result.unavailable_usage.update(rid for rid in malformed + if not result.owners.get(rid) or task_id in result.owners[rid]) if literal_messages and not by_run: result.legacy_event_turns.update((key, turn) for turn, owners in claimed_turns.items() if task_id in owners and turn not in blocked_turns and turn not in unsafe_display) @@ -406,6 +421,8 @@ def check_inventory(con, native, rows): gaps.add("segment_final_usage_unreconciled") if native["conflicting_reference_kinds"]: gaps.add("conflicting_reference_kinds") + if native["unavailable_response_usage"] or native["unlocated_usage_sessions"]: + gaps.add("native_response_usage_unavailable") if native["conflicting_responses"]: gaps.add("conflicting_response_ownership") native["turn_checks"] = checks diff --git a/agent_observer/report.py b/agent_observer/report.py index 289e64d..1a8febb 100644 --- a/agent_observer/report.py +++ b/agent_observer/report.py @@ -708,7 +708,7 @@ def child_session(identity): unmeasured_shared.add(key) has_purpose = native and (canonical or native["deliveries"] or native["conflicting_source_runs"]) inventory_gaps = outcome.check_inventory(con, native, attributed) if has_purpose else False - unresolved_usage = bool(unplaced or unassigned) + unresolved_usage = bool(unplaced or unassigned or ownership.unavailable_usage or ownership.unlocated_usage_sessions) unavailable_usage = bool(unresolved_usage or conflicts or inventory_gaps or legacy_links or not scope_keys or missing_sessions or empty_sessions or unbound_children or unbound_delegations or whole_conflicts) @@ -741,7 +741,9 @@ def _resp_tuple(r) -> list: "phases": phases, "activity_session_context": activity_context, "activity_session_context_coverage": activity_context_coverage, - "coverage_evidence": {"missing_submissions": sorted(missing_submissions), + "coverage_evidence": {"unavailable_response_usage": sorted(ownership.unavailable_usage), + "unlocated_usage_sessions": sorted(ownership.unlocated_usage_sessions), + "missing_submissions": sorted(missing_submissions), "conflicting_sessions": sorted(whole_conflicts), "joint": joint, "whole_shared": sorted(whole_shared), "missing_sessions": missing_sessions, @@ -858,6 +860,8 @@ def _resp_tuple(r) -> list: "coverage": { "no_measured_sessions": not scope_keys, "unbound_usage": list(unbound_usage), + "unlocated_usage_sessions": sorted(ownership.unlocated_usage_sessions), + "unavailable_response_usage": sorted(ownership.unavailable_usage), "conflicting_sessions": sorted(whole_conflicts), "missing_sessions": missing_sessions, "sessions_without_usage": empty_sessions, diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py index e814071..5796323 100644 --- a/tests/test_evidence_coverage.py +++ b/tests/test_evidence_coverage.py @@ -104,6 +104,8 @@ def opencode_store(self, name, parent, cost, output, independent=False): path = Path(self.tmp.name, name + ".db") build_native(str(path)) with closing(sqlite3.connect(path)) as source, source: + # These task scopes exercise only the two copies of the parent. + source.execute("DELETE FROM session WHERE parent_id IS NOT NULL") source.execute("UPDATE message SET data=json_set(data,'$.parentID',?,'$.cost',?," "'$.tokens.output',?) WHERE id='msg_a1'", (parent, cost, output)) if independent: @@ -314,3 +316,163 @@ def test_read_only_old_opencode_ledger_with_overwritten_payload(self): self.assertEqual(rep["measured"]["attributed_responses"], ["opencode:msg_unique"]) self.assertEqual(rep["native_cost"]["known_subtotal_usd"], 0.10) self.assertFalse(report.timeline(self.con, "A", session_key=key)["events"]) + + def check_malformed_claude(self, mutate): + path = self.import_claude() + self.assign("B", "claude:b") + rows = [json.loads(line) for line in path.read_text().splitlines()] + mutate(rows[-1]) + write_records(path, rows) + claude.import_claude_file(self.con, str(path), full=True) + path.unlink() + for canonical in (False, True): + if canonical: + self.project_input("claude:s", "a", "claude_prompt_echo") + self.con.execute("PRAGMA query_only=ON") + for task in ("A", "B"): + rep = report.task_report(self.con, task) + self.assertEqual(rep["measured"]["unplaced_responses"], ["claude:msg-b"]) + self.assertNotIn("b-call", [e["native_id"] for e in report.timeline(self.con, task)["events"]]) + draft = self.draft() + self.assertEqual(draft["summary"]["total_cost"]["responses"], 1) + self.assertIn("Evidence complete: no", draft["body"]) + + def test_claude_response_with_parent_but_no_block_uuid(self): + self.check_malformed_claude(lambda row: row.pop("uuid")) + + def test_claude_response_with_malformed_parent(self): + self.check_malformed_claude(lambda row: row.update(parentUuid={"invalid": True})) + + def test_claude_response_with_missing_link_in_modern_source(self): + self.check_malformed_claude(lambda row: row.pop("parentUuid")) + + def check_malformed_opencode(self, bad_first): + good = self.opencode_store("good", "msg_u1", 0.20, 50, independent=True) + bad = self.opencode_store("bad", "msg_other", 0.20, 50) + with closing(sqlite3.connect(bad)) as source, source: + source.execute("INSERT INTO message SELECT 'msg_other',session_id,time_created,time_updated,data " + "FROM message WHERE id='msg_u1'") + if not bad_first: + for path in (good, bad): + opencode.sync(self.con, source=path) + self.assign("A", "opencode:msg_u1") + self.assertEqual(report.task_report(self.con, "A")["attributed"]["output_tokens"], 3) + with closing(sqlite3.connect(bad)) as source, source: + source.execute("UPDATE message SET data=json_set(data,'$.tokens.output','invalid') WHERE id='msg_a1'") + source.execute("UPDATE session SET time_updated=time_updated+1") + self.assertGreater(opencode.sync(self.con, source=bad)["malformed"], 0) + opencode.sync(self.con, source=good) + if bad_first: + self.assign("A", "opencode:msg_u1") + for canonical in (False, True): + if canonical: + self.project_input("opencode:ses_parent", "msg_u1", "opencode_admitted_message") + for path in (bad, good): + opencode.sync(self.con, source=path, full=True) + self.con.execute("PRAGMA query_only=ON") + rep = report.task_report(self.con, "A") + self.assertEqual(rep["measured"]["unplaced_responses"], ["opencode:msg_a1"]) + self.assertEqual(rep["attributed"]["output_tokens"], 3) + self.assertIsNone(rep["native_cost"]["total_usd"]) + self.assertEqual(rep["native_cost"]["known_subtotal_usd"], 0.10) + self.assertFalse(report.timeline(self.con, "A")["events"]) + draft = self.draft() + self.assertIn("Evidence complete: no", draft["body"]) + self.assertEqual(draft["summary"]["native_cost"], rep["native_cost"]) + + def test_malformed_opencode_refresh_preserves_dispute(self): + self.check_malformed_opencode(False) + + def test_malformed_opencode_first_preserves_dispute(self): + self.check_malformed_opencode(True) + + def test_malformed_only_opencode_input_keeps_its_gap_local(self): + path = self.opencode_store("single", "msg_u1", .20, 50, independent=True) + with closing(sqlite3.connect(path)) as source, source: + source.execute("INSERT INTO message SELECT 'other',session_id,time_created,time_updated,data " + "FROM message WHERE id='msg_u1'") + source.execute("INSERT INTO part SELECT 'other-text','other',session_id,time_created,time_updated,data " + "FROM part WHERE message_id='msg_u1' LIMIT 1") + source.execute("UPDATE message SET data=json_set(data,'$.tokens.output','bad','$.parentID','other') " + "WHERE id='msg_a1'") + opencode.sync(self.con, source=path) + self.assign("A", "opencode:msg_u1") + self.assign("B", "opencode:other") + a, b = [report.task_report(self.con, task) for task in ("A", "B")] + self.assertEqual(a["native_cost"]["total_usd"], 0.10) + self.assertEqual(a["coverage"]["unavailable_response_usage"], []) + self.assertTrue(a["complete"]) + self.assertEqual(b["coverage"]["unavailable_response_usage"], ["opencode:msg_a1"]) + self.assertIsNone(b["native_cost"]["total_usd"]) + self.assertFalse(b["complete"]) + + def test_claude_invalid_copy_and_correction_in_both_orders(self): + self.import_claude() + self.assign("B", "claude:b") + path = Path(self.tmp.name, "claude.jsonl") + other = Path(self.tmp.name, "copy.jsonl") + rows = [json.loads(line) for line in path.read_text().splitlines()] + bad = dict(rows[-1], uuid=None) + for order in ((other, path), (path, other)): + write_records(other, [bad]) + for source in order: + claude.import_claude_file(self.con, str(source), full=True) + rep = report.task_report(self.con, "B") + self.assertIn("claude:msg-b", rep["measured"]["unplaced_responses"]) + self.assertFalse(report.timeline(self.con, "B")["events"]) + write_records(other, [rows[-1]]) + claude.import_claude_file(self.con, str(other), full=True) + self.assertEqual(report.task_report(self.con, "B")["measured"]["attributed_responses"], ["claude:msg-b"]) + + def test_unreadable_opencode_identity_cannot_release_previous_dispute(self): + good = self.opencode_store("good", "msg_u1", 0.20, 50, independent=True) + bad = self.opencode_store("bad", None, 7.25, 500) + for source in (good, bad): + opencode.sync(self.con, source=source) + self.assign("A", "opencode:msg_u1") + for sql in ("UPDATE message SET id=NULL WHERE id='msg_a1'", + "UPDATE message SET id='msg_a1',data='broken' WHERE id IS NULL"): + with closing(sqlite3.connect(bad)) as source, source: + source.execute(sql) + for _ in range(2): + opencode.sync(self.con, source=bad, full=True) + rep = report.task_report(self.con, "A") + self.assertEqual(rep["measured"]["attributed_responses"], ["opencode:msg_unique"]) + self.assertIsNone(rep["native_cost"]["total_usd"]) + self.assertEqual(rep["native_cost"]["known_subtotal_usd"], 0.10) + with closing(sqlite3.connect(good)) as source: + valid = source.execute("SELECT data FROM message WHERE id='msg_a1'").fetchone()[0] + with closing(sqlite3.connect(bad)) as source, source: + source.execute("UPDATE message SET data=? WHERE id='msg_a1'", (valid,)) + opencode.sync(self.con, source=bad, full=True) + rep = report.task_report(self.con, "A") + self.assertTrue(rep["complete"]) + self.assertAlmostEqual(rep["native_cost"]["total_usd"], 0.30) + self.assertEqual(rep["attributed"]["output_tokens"], 53) + + def test_unmeasured_claude_event_with_a_parent_cannot_inherit_display_turn(self): + path = self.import_claude(legacy=True) + rows = [json.loads(line) for line in path.read_text().splitlines()] + rows[1]["parentUuid"] = "a" + foreign = claude_response("foreign", "b", "ignored") + del foreign["message"]["id"] + foreign["message"]["content"] = [{"type": "tool_use", "id": "foreign-call", "name": "Read"}] + write_records(path, [claude_user("b"), rows[0], rows[1], foreign]) + claude.import_claude_file(self.con, str(path), full=True) + self.assertNotIn("foreign-call", [e["native_id"] for e in report.timeline(self.con, "A")["events"]]) + + def test_erasing_last_claude_parent_does_not_turn_source_into_legacy(self): + path = self.import_claude(legacy=True) + rows = [json.loads(line) for line in path.read_text().splitlines()] + rows.insert(0, claude_user("b")) + rows[-1]["parentUuid"] = "b" + write_records(path, rows) + claude.import_claude_file(self.con, str(path), full=True) + self.assign("B", "claude:b") + self.assertEqual(report.task_report(self.con, "B")["attributed"]["responses"], 1) + del rows[-1]["parentUuid"] + write_records(path, rows) + for _ in range(2): + claude.import_claude_file(self.con, str(path), full=True) + self.assertEqual(report.task_report(self.con, "A")["measured"]["unplaced_responses"], ["claude:msg-a"]) + self.assertFalse(report.timeline(self.con, "A")["events"]) From 758d06638a66cd1dc2a5c5018d10b0ee3083fa16 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 21:12:04 +0100 Subject: [PATCH 30/44] wip: reconcile final measurements and preserve incomplete response evidence --- agent_observer/adapters/claude.py | 80 +++++++++++++++++++++++++++-- agent_observer/adapters/opencode.py | 5 +- agent_observer/outcome.py | 4 ++ tests/test_evidence_coverage.py | 76 +++++++++++++++++++++++++++ 4 files changed, 158 insertions(+), 7 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index eb38d1c..ff4f784 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -106,7 +106,7 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 10 # Replay usable identities alongside rejected measurements. +_IMPORT_VERSION = 11 # Replay source-specific final measurements and ownership evidence. def _ensure_native_kinds(con) -> None: @@ -411,9 +411,11 @@ def import_claude_file(con: sqlite3.Connection, path: str, "SELECT turn_id FROM user_messages WHERE session_key=? AND kind='genuine'" " ORDER BY ts DESC LIMIT 1", (r.session_key,)).fetchone() r.turn = row["turn_id"] if row else None + unreadable = False for ordinal, obj, line in src.records(): stats["lines"] += 1 if obj is None or not isinstance(obj, dict): + unreadable = True stats["malformed"] += 1 src.error(ordinal, "malformed_json" if obj is None else "unknown_record", @@ -446,6 +448,19 @@ def import_claude_file(con: sqlite3.Connection, path: str, _record_ancestry(r, obj, rejected="schema_error") stats["malformed"] += 1 src.error(ordinal, "schema_error", line) + if unreadable: + con.execute("INSERT OR IGNORE INTO claude_unreadable_sources VALUES(?,?)", (r.session_key, src.source_id)) + if not src.incremental: + con.execute("INSERT OR IGNORE INTO claude_final_observations SELECT * FROM temp.claude_prior_finals") + con.execute("""INSERT OR IGNORE INTO claude_rejected_measurements + SELECT p.session_key,p.source_id,p.uuid,p.parent,p.response_id,'unreadable_record' + FROM claude_prior_edges p WHERE NOT EXISTS ( + SELECT 1 FROM claude_response_ancestry a WHERE a.source_id=p.source_id + AND a.session_key=p.session_key AND a.uuid=p.uuid AND a.parent=p.parent + AND a.response_id=p.response_id)""") + if not src.incremental: + con.execute("DROP TABLE temp.claude_prior_edges") + con.execute("DROP TABLE temp.claude_prior_finals") con.executemany("INSERT OR IGNORE INTO claude_ancestry_sources VALUES(?,?)", ((key, src.source_id) for key in r.linked_sessions)) if r.native_session: @@ -565,6 +580,33 @@ def _stored_counters(r: _Reader, rid: str) -> dict: return dict(row) if row is not None else {} +def _matching_corrected_finals(r, rid, payload): + # A single later block cannot revise immutable final usage. Independent + # copies, including the original measured source, can establish a correction. + rows = r.con.execute( + "SELECT o.source_id,o.payload,r.source_id AS original FROM claude_final_observations o " + "JOIN responses r USING(session_key,response_id) WHERE o.session_key=? AND o.response_id=?", + (r.session_key, rid)).fetchall() + return (len({row["source_id"] for row in rows}) > 1 and all(row["payload"] == payload for row in rows) + and any(row["source_id"] == row["original"] for row in rows)) + + +def conflicting_final_measurements(con, session_key): + """A task can bill a final row only when its source measurements agree.""" + if not db._has_table(con, "claude_final_observations"): + return set() + fields = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", + "reasoning_output_tokens", "total_tokens", "model") + mismatch = [f"json_extract(o.payload,'$.{name}') IS NOT r.{name}" for name in fields] + # Earlier final blocks may omit the subsequently supplied cache TTL detail. + for name in ("cache_write_5m_tokens", "cache_write_1h_tokens"): + value = f"json_extract(o.payload,'$.{name}')" + mismatch.append(f"({value} IS NOT NULL AND r.{name} IS NOT NULL AND {value}<>r.{name})") + return {rid for rid, in con.execute( + "SELECT DISTINCT o.response_id FROM claude_final_observations o JOIN responses r USING(session_key,response_id) " + "WHERE o.session_key=? AND (" + " OR ".join(mismatch) + ")", (session_key,))} + + def _ingest_usage_row(r: _Reader, obj: dict, ordinal: int, ts, mid: str, model, values: dict, final: bool) -> None: """One streamed usage block for a message id. @@ -576,10 +618,21 @@ def _ingest_usage_row(r: _Reader, obj: dict, ordinal: int, ts, mid: str, duplicate is a no-op and any differing counters are quarantined. A malformed final block never reaches here, so it never finalizes.""" rid = f"{HARNESS}:{mid}" + if final: + payload = json.dumps(dict(values, model=model), sort_keys=True) + r.con.execute("INSERT OR IGNORE INTO claude_final_observations VALUES(?,?,?,?)", + (r.session_key, rid, r.src.source_id, payload)) if mid in r.finalized or _is_finalized(r.con, rid): r.finalized.add(mid) seen = _stored_counters(r, rid) ttl_keys = ("cache_write_5m_tokens", "cache_write_1h_tokens") + if final and _matching_corrected_finals(r, rid, payload): + # All fields come from the validated usage parser, never from JSON keys. + names = tuple(k for k in values if k not in ttl_keys or values[k] is not None) + r.con.execute("UPDATE responses SET model=?," + ",".join(f"{k}=?" for k in names) + + " WHERE session_key=? AND response_id=?", + (model, *(values[k] for k in names), r.session_key, rid)) + seen = values if any(seen.get(k) != v for k, v in values.items() if k not in ttl_keys): raise _UsageConflict("usage conflict") if not final: @@ -1102,8 +1155,25 @@ def _prepare_ancestry(r): session_key TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), uuid TEXT NOT NULL, parent TEXT NOT NULL, response_id TEXT NOT NULL, reason TEXT NOT NULL, PRIMARY KEY(session_key, source_id, uuid, parent, response_id, reason)) WITHOUT ROWID""") + r.con.execute("""CREATE TABLE IF NOT EXISTS claude_final_observations ( + session_key TEXT NOT NULL, response_id TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), + payload TEXT NOT NULL, PRIMARY KEY(session_key,response_id,source_id,payload)) WITHOUT ROWID""") + r.con.execute("CREATE INDEX IF NOT EXISTS claude_final_observation_source ON claude_final_observations(source_id)") + r.con.execute("""CREATE TABLE IF NOT EXISTS claude_unreadable_sources ( + session_key TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), + PRIMARY KEY(session_key,source_id)) WITHOUT ROWID""") r.linked_sessions = set() if not r.src.incremental: + # Keep identities only until the replacement proves it could read + # every row. A broken line cannot silently retract a competing copy. + r.con.execute("CREATE TEMP TABLE claude_prior_edges AS " + "SELECT session_key,source_id,uuid,parent,response_id FROM claude_response_ancestry " + "WHERE source_id=? AND response_id<>'' UNION " + "SELECT session_key,source_id,uuid,parent,response_id FROM claude_rejected_measurements " + "WHERE source_id=?", (r.src.source_id, r.src.source_id)) + r.con.execute("CREATE TEMP TABLE claude_prior_finals AS SELECT session_key,response_id,source_id,payload " + "FROM claude_final_observations WHERE source_id=?", (r.src.source_id,)) + r.con.execute("DELETE FROM claude_unreadable_sources WHERE source_id=?", (r.src.source_id,)) if r.src.row["claude_usage_version"] in (6, 7, 8, 9): r.con.execute("INSERT OR IGNORE INTO claude_ancestry_sources " "SELECT DISTINCT session_key,source_id FROM claude_response_ancestry " @@ -1114,6 +1184,7 @@ def _prepare_ancestry(r): (r.src.source_id,)) r.con.execute("DELETE FROM claude_invalid_ancestry WHERE source_id=?", (r.src.source_id,)) r.con.execute("DELETE FROM claude_rejected_measurements WHERE source_id=?", (r.src.source_id,)) + r.con.execute("DELETE FROM claude_final_observations WHERE source_id=?", (r.src.source_id,)) r.con.execute("DELETE FROM claude_response_ancestry WHERE source_id=?", (r.src.source_id,)) @@ -1144,9 +1215,8 @@ def _record_ancestry(r, obj, rejected=None): mid = native_response.identifier(message.get("id")) if mid and message.get("model") != "": response_id = f"{HARNESS}:{mid}" - if not rejected: - for family, event_id in r.message_events: - native_response.record_event(r.con, r.src.source_id, r.session_key, family, event_id, response_id) + for family, event_id in r.message_events: + native_response.record_event(r.con, r.src.source_id, r.session_key, family, event_id, response_id) elif kind == "attachment" and isinstance(obj.get("attachment"), dict): if obj["attachment"].get("type") == "queued_command": # A consumed queued input has its own identity. A missing identity @@ -1272,7 +1342,7 @@ def response_witnesses(con, session_key): # Rejected measurements cannot grant ownership. A later usable # block can confirm the same edge. A counter conflict on a new # block cannot revise an already finalized response either. - if ((uuid, parent, rid) in accepted + if (reason != "unreadable_record" and (uuid, parent, rid) in accepted or (reason == "usage_conflict" and same_source and uuid not in seen)): continue conflicts.add(rid) diff --git a/agent_observer/adapters/opencode.py b/agent_observer/adapters/opencode.py index 02eb3d8..532ff3e 100644 --- a/agent_observer/adapters/opencode.py +++ b/agent_observer/adapters/opencode.py @@ -711,13 +711,14 @@ def _ingest_response(con, stats, src_path, source_id, session_key, sess, _MAX_COUNTER = (1 << 63) - 1 # SQLite INTEGER. _UNLOCATED_SNAPSHOT = "oc6:unlocated" # Never matches a complete snapshot fingerprint. _MALFORMED_USAGE = "malformed_usage" -_INVALID_OBSERVATIONS = {"null", json.dumps(_MALFORMED_USAGE), json.dumps("unknown_message")} +_INVALID_OBSERVATIONS = {"null", json.dumps(_MALFORMED_USAGE), json.dumps("unknown_message"), + json.dumps("unfinished")} def _measurement(data): timing = data.get("time") if isinstance(data.get("time"), dict) else {} if timing.get("completed") is None: - return "unmeasured" + return "unfinished" raw_tokens = data.get("tokens") if raw_tokens is None: tokens: dict = {} diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index 7c33fae..927db33 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -167,7 +167,11 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me if harness == "claude": from .adapters import claude responses, disputed_completions = claude.response_witnesses(con, key) + disputed_completions |= claude.conflicting_final_measurements(con, key) result.conflicts.update(disputed_completions) + if _has_table(con, "claude_unreadable_sources") and con.execute( + "SELECT 1 FROM claude_unreadable_sources WHERE session_key=? LIMIT 1", (key,)).fetchone(): + result.unlocated_usage_sessions.add(key) elif harness == "opencode": from .adapters import opencode responses, disputed_completions, malformed = opencode.response_witnesses(con, key) diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py index 5796323..2fbc682 100644 --- a/tests/test_evidence_coverage.py +++ b/tests/test_evidence_coverage.py @@ -106,6 +106,7 @@ def opencode_store(self, name, parent, cost, output, independent=False): with closing(sqlite3.connect(path)) as source, source: # These task scopes exercise only the two copies of the parent. source.execute("DELETE FROM session WHERE parent_id IS NOT NULL") + source.execute("DELETE FROM message WHERE id='msg_a_unf'") source.execute("UPDATE message SET data=json_set(data,'$.parentID',?,'$.cost',?," "'$.tokens.output',?) WHERE id='msg_a1'", (parent, cost, output)) if independent: @@ -476,3 +477,78 @@ def test_erasing_last_claude_parent_does_not_turn_source_into_legacy(self): claude.import_claude_file(self.con, str(path), full=True) self.assertEqual(report.task_report(self.con, "A")["measured"]["unplaced_responses"], ["claude:msg-a"]) self.assertFalse(report.timeline(self.con, "A")["events"]) + + def test_claude_disagreeing_final_measurements_in_both_orders(self): + path = self.import_claude() + self.assign("B", "claude:b") + rows = [json.loads(line) for line in path.read_text().splitlines()] + other = path.with_name("final-copy.jsonl") + for first, second, rid in ((path, other, "high-first"), (other, path, "low-first")): + with self.subTest(rid=rid): + response = dict(rows[-1], uuid=rid, message=dict(rows[-1]["message"], id=rid)) + for loc, count in ((first, 90000 if rid == "high-first" else 5000), + (second, 5000 if rid == "high-first" else 90000)): + response["message"]["usage"]["output_tokens"] = count + write_records(loc, [*rows[:2], response]) + claude.import_claude_file(self.con, str(loc), full=True) + rep = report.task_report(self.con, "B") + self.assertNotIn("claude:" + rid, rep["measured"]["attributed_responses"]) + self.assertIn("claude:" + rid, rep["measured"]["unplaced_responses"]) + self.assertIsNone(rep["total_cost"]["usd"]) + # Repair the first copy to the second final. A first-import + # preference would preserve the wrong measurement here. + first.write_bytes(second.read_bytes()) + claude.import_claude_file(self.con, str(first), full=True) + rep = report.task_report(self.con, "B") + self.assertIn("claude:" + rid, rep["measured"]["attributed_responses"]) + self.assertEqual(self.con.execute("SELECT output_tokens FROM responses WHERE response_id=?", + ("claude:" + rid,)).fetchone()[0], count) + + def test_unfinished_opencode_message_keeps_owned_total_open(self): + path = self.opencode_store("pending", "msg_u1", 0.20, 50, independent=True) + with closing(sqlite3.connect(path)) as source, source: + source.execute("UPDATE message SET data=json_remove(data,'$.time.completed') WHERE id='msg_a1'") + opencode.sync(self.con, source=path) + self.assign("A", "opencode:msg_u1") + rep = report.task_report(self.con, "A") + self.assertEqual(rep["measured"]["attributed_responses"], ["opencode:msg_unique"]) + self.assertFalse(rep["complete"]) + self.assertIsNone(rep["native_cost"]["total_usd"]) + self.assertEqual(rep["native_cost"]["known_subtotal_usd"], 0.10) + self.assertIn("Evidence complete: no", self.draft()["body"]) + with closing(sqlite3.connect(path)) as source, source: + source.execute("UPDATE message SET data=json_set(data,'$.time.completed',123) WHERE id='msg_a1'") + opencode.sync(self.con, source=path, full=True) + self.assertAlmostEqual(report.task_report(self.con, "A")["native_cost"]["total_usd"], 0.30) + + def test_rejected_claude_event_has_no_display_turn_fallback(self): + path = Path(self.tmp.name, "initial.jsonl") + a, b = [claude_response("reply-" + p, p, "msg-" + p) for p in ("a", "b")] + for response, call in ((a, "a-call"), (b, "b-call")): + response["message"]["content"] = [{"type": "tool_use", "id": call, "name": "Read"}] + b["message"]["usage"]["output_tokens"] = "bad" + write_records(path, [claude_user("b"), claude_user("a"), a, b]) + claude.import_claude_file(self.con, str(path)) + self.assign("A", "claude:a") + self.assign("B", "claude:b") + self.assertEqual([e["native_id"] for e in report.timeline(self.con, "A")["events"]], ["a-call"]) + self.assertFalse(report.timeline(self.con, "B")["events"]) + + def test_unreadable_claude_line_cannot_erase_a_dispute(self): + path = self.import_claude() + self.assign("B", "claude:b") + rows = [json.loads(line) for line in path.read_text().splitlines()] + copy = path.with_name("damaged.jsonl") + rows[-1]["parentUuid"] = "a" + write_records(copy, rows) + claude.import_claude_file(self.con, str(copy), full=True) + write_records(copy, rows[:-1]) + with copy.open("a") as source: + source.write("{\n") + for _ in range(2): + claude.import_claude_file(self.con, str(copy), full=True) + self.assertFalse(report.task_report(self.con, "B")["attributed"]["responses"]) + rows[-1]["parentUuid"] = "b" + write_records(copy, rows) + claude.import_claude_file(self.con, str(copy), full=True) + self.assertEqual(report.task_report(self.con, "B")["attributed"]["responses"], 1) From 0a06da1997bebd389d08a7d46f2aec7f1b634d7c Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 21:15:04 +0100 Subject: [PATCH 31/44] wip: finish fixture usage before testing source removal --- tests/test_source_availability.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/tests/test_source_availability.py b/tests/test_source_availability.py index d3c23e7..baf30c1 100644 --- a/tests/test_source_availability.py +++ b/tests/test_source_availability.py @@ -6,6 +6,7 @@ import sqlite3 import subprocess import sys +from contextlib import closing from agent_observer import db, lookup, report from agent_observer.adapters import grok, opencode @@ -145,9 +146,18 @@ def _bind_all(self, task): for row in self.con.execute("SELECT DISTINCT session_key FROM user_messages"): self._own_session(row[0], task) - def test_deleted_opencode_session_is_not_available(self): + def _completed_opencode_source(self): native_path = os.path.join(self.tmp.name, "opencode.db") build_native(native_path) + with closing(sqlite3.connect(native_path)) as native, native: + native.execute("UPDATE message SET data=json_set(data,'$.time.completed',?) WHERE id='msg_a_unf'", + (T0 + 60,)) + native.execute("UPDATE part SET data=json_set(data,'$.state.status','completed','$.state.time.end',?) " + "WHERE id='p_run1'", (T0 + 59,)) + return native_path + + def test_deleted_opencode_session_is_not_available(self): + native_path = self._completed_opencode_source() opencode.sync(self.con, source=native_path) self.con.commit() self._bind_all("T-OC") @@ -440,8 +450,7 @@ def test_second_eventless_loss_changes_the_snapshot(self): self.assertNotEqual(mid["snapshot_id"], after["snapshot_id"]) def test_eventless_gap_makes_a_mixed_task_partial(self): - native_path = os.path.join(self.tmp.name, "opencode.db") - build_native(native_path) + native_path = self._completed_opencode_source() opencode.sync(self.con, source=native_path) self.con.commit() self._bind_all("T-MIX") From 57328e00773ceddf3bde804313f29c8b6778bf91 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 21:19:38 +0100 Subject: [PATCH 32/44] wip: require a usable native final before clearing a billing gap --- agent_observer/adapters/claude.py | 35 +++++++++++++++++++--- agent_observer/adapters/opencode.py | 31 ++++++++++++++------ tests/test_evidence_coverage.py | 45 ++++++++++++++++++++++++++++- tests/test_source_availability.py | 1 + 4 files changed, 98 insertions(+), 14 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index ff4f784..aa9378a 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -106,7 +106,7 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 11 # Replay source-specific final measurements and ownership evidence. +_IMPORT_VERSION = 12 # Replay incomplete finals independently of their surviving identity. def _ensure_native_kinds(con) -> None: @@ -421,6 +421,11 @@ def import_claude_file(con: sqlite3.Connection, path: str, "malformed_json" if obj is None else "unknown_record", line) continue + if obj.get("type") == "assistant": + message = obj.get("message") + if (not isinstance(message, dict) or (message.get("model") != "" and ( + not native_response.identifier(message.get("id")) or message.get("role", "assistant") != "assistant"))): + unreadable = True try: r.message_events.clear() _ingest(r, obj, ordinal) @@ -459,6 +464,17 @@ def import_claude_file(con: sqlite3.Connection, path: str, AND a.session_key=p.session_key AND a.uuid=p.uuid AND a.parent=p.parent AND a.response_id=p.response_id)""") if not src.incremental: + # Seeing the same message again without any final measurement cannot + # retract a previous final. Retain the gap until this source attests it. + con.execute("""INSERT OR IGNORE INTO claude_rejected_measurements + SELECT a.session_key,a.source_id,a.uuid,a.parent,a.response_id,'missing_final_usage' + FROM claude_response_ancestry a JOIN ( + SELECT session_key,source_id,response_id FROM temp.claude_prior_finals UNION + SELECT session_key,source_id,response_id FROM temp.claude_prior_edges + WHERE reason IN ('missing_final_usage','malformed_final_usage') + ) p USING(session_key,source_id,response_id) + WHERE NOT EXISTS (SELECT 1 FROM claude_final_observations f WHERE f.session_key=a.session_key + AND f.source_id=a.source_id AND f.response_id=a.response_id)""") con.execute("DROP TABLE temp.claude_prior_edges") con.execute("DROP TABLE temp.claude_prior_finals") con.executemany("INSERT OR IGNORE INTO claude_ancestry_sources VALUES(?,?)", @@ -602,9 +618,15 @@ def conflicting_final_measurements(con, session_key): for name in ("cache_write_5m_tokens", "cache_write_1h_tokens"): value = f"json_extract(o.payload,'$.{name}')" mismatch.append(f"({value} IS NOT NULL AND r.{name} IS NOT NULL AND {value}<>r.{name})") - return {rid for rid, in con.execute( + conflicts = {rid for rid, in con.execute( "SELECT DISTINCT o.response_id FROM claude_final_observations o JOIN responses r USING(session_key,response_id) " "WHERE o.session_key=? AND (" + " OR ".join(mismatch) + ")", (session_key,))} + conflicts.update(rid for rid, in con.execute( + "SELECT DISTINCT q.response_id FROM claude_rejected_measurements q WHERE q.session_key=? " + "AND q.reason IN ('missing_final_usage','malformed_final_usage') AND NOT EXISTS (" + "SELECT 1 FROM claude_final_observations f WHERE f.session_key=q.session_key " + "AND f.source_id=q.source_id AND f.response_id=q.response_id)", (session_key,))) + return conflicts def _ingest_usage_row(r: _Reader, obj: dict, ordinal: int, ts, mid: str, @@ -1167,9 +1189,9 @@ def _prepare_ancestry(r): # Keep identities only until the replacement proves it could read # every row. A broken line cannot silently retract a competing copy. r.con.execute("CREATE TEMP TABLE claude_prior_edges AS " - "SELECT session_key,source_id,uuid,parent,response_id FROM claude_response_ancestry " + "SELECT session_key,source_id,uuid,parent,response_id,'' AS reason FROM claude_response_ancestry " "WHERE source_id=? AND response_id<>'' UNION " - "SELECT session_key,source_id,uuid,parent,response_id FROM claude_rejected_measurements " + "SELECT session_key,source_id,uuid,parent,response_id,reason FROM claude_rejected_measurements " "WHERE source_id=?", (r.src.source_id, r.src.source_id)) r.con.execute("CREATE TEMP TABLE claude_prior_finals AS SELECT session_key,response_id,source_id,payload " "FROM claude_final_observations WHERE source_id=?", (r.src.source_id,)) @@ -1215,6 +1237,11 @@ def _record_ancestry(r, obj, rejected=None): mid = native_response.identifier(message.get("id")) if mid and message.get("model") != "": response_id = f"{HARNESS}:{mid}" + if message.get("stop_reason") is not None: + if rejected == "malformed_usage": + rejected = "malformed_final_usage" + elif not rejected and not message.get("usage"): + rejected = "missing_final_usage" for family, event_id in r.message_events: native_response.record_event(r.con, r.src.source_id, r.session_key, family, event_id, response_id) elif kind == "attachment" and isinstance(obj.get("attachment"), dict): diff --git a/agent_observer/adapters/opencode.py b/agent_observer/adapters/opencode.py index 532ff3e..0890c5b 100644 --- a/agent_observer/adapters/opencode.py +++ b/agent_observer/adapters/opencode.py @@ -297,7 +297,7 @@ def _prepare_observations(con, session_key, source_id, *, identities_complete): # another copy can replace its projection. Only its own edge accompanies it. for row in con.execute( "SELECT r.* FROM responses r JOIN sources s ON s.id=r.source_id WHERE r.session_key=? " - "AND r.source_id<>? AND s.sha256 NOT GLOB 'oc[3-6]:*' AND NOT EXISTS " + "AND r.source_id<>? AND s.sha256 NOT GLOB 'oc[3-7]:*' AND NOT EXISTS " "(SELECT 1 FROM opencode_response_observations o WHERE o.session_key=r.session_key " "AND o.response_id=r.response_id AND o.source_id=r.source_id)", (session_key, source_id)): parent = con.execute( @@ -380,7 +380,7 @@ def response_witnesses(con, session_key): if db._has_table(con, "native_response_events"): for rid, source in con.execute( "SELECT DISTINCT e.response_id,e.source_id FROM native_response_events e " - "JOIN sources s ON s.id=e.source_id WHERE e.session_key=? AND s.sha256 NOT GLOB 'oc[4-6]:*'", + "JOIN sources s ON s.id=e.source_id WHERE e.session_key=? AND s.sha256 NOT GLOB 'oc[4-7]:*'", (session_key,)): if rid in measured and source not in payload_sources.get(rid, {measured[rid]}): conflicts.add(rid) @@ -392,10 +392,10 @@ def has_unlocated_usage_error(con, session_key): # Keep the session's cost open without guessing which message failed. return con.execute( "SELECT 1 FROM sources s WHERE s.harness=? AND s.session_id=? AND " - "(s.sha256=? OR (s.sha256 NOT GLOB 'oc[4-6]:*' AND EXISTS (SELECT 1 FROM import_errors e " + "(s.sha256 GLOB 'oc[4-7]:unlocated' OR (s.sha256 NOT GLOB 'oc[4-7]:*' AND EXISTS (SELECT 1 FROM import_errors e " "WHERE e.harness=s.harness AND e.source_path=s.path AND e.error='malformed_usage' " "AND instr(','||e.line_excerpt||',', ',tokens,')>0))) LIMIT 1", - (HARNESS, session_key.partition(":")[2], _UNLOCATED_SNAPSHOT)).fetchone() is not None + (HARNESS, session_key.partition(":")[2])).fetchone() is not None def _project_response(con, stats, rid, session_key, session_id, locator, measurement): @@ -498,7 +498,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, session_key = f"{HARNESS}:{sess_id}" msg_n, msg_m = _count_max(native, "message", sess_id) part_n, part_m = _count_max(native, "part", sess_id) - fp = "oc6:" + fingerprint(sess.get("time_updated"), msg_m, part_m, msg_n, part_n) + fp = "oc7:" + fingerprint(sess.get("time_updated"), msg_m, part_m, msg_n, part_n) row = con.execute( "SELECT * FROM sources WHERE harness=? AND path=?", (HARNESS, src_path)).fetchone() @@ -652,8 +652,9 @@ def _ingest_message(con, native, stats, identity, src_path, source_id, timing = data.get("time") if isinstance(data.get("time"), dict) else {} completed = timing.get("completed") created = timing.get("created") - ts = iso_ts(completed if completed is not None else - (created if created is not None else msg.get("time_created"))) + ts = _completion_time(completed) + if ts is None: + ts = iso_ts(created if created is not None else msg.get("time_created")) error = data.get("error") if isinstance(error, dict): detail = error.get("data") if isinstance(error.get("data"), dict) \ @@ -709,16 +710,28 @@ def _ingest_response(con, stats, src_path, source_id, session_key, sess, # The observation holds either the measured fields or a reason they are unavailable. _MAX_COUNTER = (1 << 63) - 1 # SQLite INTEGER. -_UNLOCATED_SNAPSHOT = "oc6:unlocated" # Never matches a complete snapshot fingerprint. +_UNLOCATED_SNAPSHOT = "oc7:unlocated" # Never matches a complete snapshot fingerprint. _MALFORMED_USAGE = "malformed_usage" _INVALID_OBSERVATIONS = {"null", json.dumps(_MALFORMED_USAGE), json.dumps("unknown_message"), - json.dumps("unfinished")} + json.dumps("unfinished"), json.dumps("unmeasured")} + + +def _completion_time(value): + if isinstance(value, bool) or not isinstance(value, (int, float, str)): + return None + try: + ts = iso_ts(value) + except (OverflowError, OSError, ValueError): + return None + return ts if ts is not None and 0 <= ts < 253402300800 else None def _measurement(data): timing = data.get("time") if isinstance(data.get("time"), dict) else {} if timing.get("completed") is None: return "unfinished" + if _completion_time(timing["completed"]) is None: + return _MALFORMED_USAGE raw_tokens = data.get("tokens") if raw_tokens is None: tokens: dict = {} diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py index 2fbc682..9601fb4 100644 --- a/tests/test_evidence_coverage.py +++ b/tests/test_evidence_coverage.py @@ -106,7 +106,8 @@ def opencode_store(self, name, parent, cost, output, independent=False): with closing(sqlite3.connect(path)) as source, source: # These task scopes exercise only the two copies of the parent. source.execute("DELETE FROM session WHERE parent_id IS NOT NULL") - source.execute("DELETE FROM message WHERE id='msg_a_unf'") + source.execute("DELETE FROM part WHERE message_id IN ('msg_a_unf','msg_a_err')") + source.execute("DELETE FROM message WHERE id IN ('msg_a_unf','msg_a_err')") source.execute("UPDATE message SET data=json_set(data,'$.parentID',?,'$.cost',?," "'$.tokens.output',?) WHERE id='msg_a1'", (parent, cost, output)) if independent: @@ -552,3 +553,45 @@ def test_unreadable_claude_line_cannot_erase_a_dispute(self): write_records(copy, rows) claude.import_claude_file(self.con, str(copy), full=True) self.assertEqual(report.task_report(self.con, "B")["attributed"]["responses"], 1) + + def test_losing_measurement_or_message_cannot_clear_claude_final_dispute(self): + path = self.import_claude() + self.assign("B", "claude:b") + rows = [json.loads(line) for line in path.read_text().splitlines()] + other = path.with_name("changed.jsonl") + msg = rows[-1]["message"] + msg["usage"]["output_tokens"] = 90000 + write_records(other, rows) + claude.import_claude_file(self.con, str(other)) + self.assertFalse(report.task_report(self.con, "B")["attributed"]["responses"]) + del msg["usage"] + for replacement in (msg, [], None): + with self.subTest(message_type=type(replacement).__name__): + rows[-1]["message"] = replacement + write_records(other, rows) + for _ in range(2): + claude.import_claude_file(self.con, str(other), full=True) + self.assertFalse(report.task_report(self.con, "B")["attributed"]["responses"]) + self.assertFalse(report.timeline(self.con, "B")["events"]) + other.write_bytes(path.read_bytes()) + claude.import_claude_file(self.con, str(other), full=True) + self.assertEqual(report.task_report(self.con, "B")["attributed"]["responses"], 1) + + def test_zero_counters_and_invalid_completion_time_withhold_opencode_cost(self): + path = self.opencode_store("unmeasured", "msg_u1", .20, 50, independent=True) + with closing(sqlite3.connect(path)) as src: + original = json.loads(src.execute("SELECT data FROM message WHERE id='msg_a1'").fetchone()[0]) + opencode.sync(self.con, source=path) + self.assign("A", "opencode:msg_u1") + zero = dict(original, tokens={"input": 0, "output": 0, "reasoning": 0, "cache": {"read": 0, "write": 0}}) + invalid_times = [dict(original, time={"completed": v}) for v in (False, True, -1, "broken", {})] + for record in [zero, *invalid_times]: + with self.subTest(record=record["time"]["completed"]): + with closing(sqlite3.connect(path)) as src, src: + src.execute("UPDATE message SET data=? WHERE id='msg_a1'", (json.dumps(record),)) + opencode.sync(self.con, source=path, full=True) + rep = report.task_report(self.con, "A") + self.assertFalse(rep["complete"]) + self.assertIsNone(rep["native_cost"]["total_usd"]) + self.assertEqual(rep["native_cost"]["known_subtotal_usd"], .10) + self.assertIn("Evidence complete: no", self.draft()["body"]) diff --git a/tests/test_source_availability.py b/tests/test_source_availability.py index baf30c1..9b5b337 100644 --- a/tests/test_source_availability.py +++ b/tests/test_source_availability.py @@ -150,6 +150,7 @@ def _completed_opencode_source(self): native_path = os.path.join(self.tmp.name, "opencode.db") build_native(native_path) with closing(sqlite3.connect(native_path)) as native, native: + native.execute("UPDATE message SET data=json_set(data,'$.tokens.output',1) WHERE id='msg_a_err'") native.execute("UPDATE message SET data=json_set(data,'$.time.completed',?) WHERE id='msg_a_unf'", (T0 + 60,)) native.execute("UPDATE part SET data=json_set(data,'$.state.status','completed','$.state.time.end',?) " From bdd8d87f25742d4e25d0daf5235600868b420a7b Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 21:27:43 +0100 Subject: [PATCH 33/44] wip: retain final obligations across provisional source replays --- agent_observer/adapters/claude.py | 55 +++++++++++++++++++++-------- agent_observer/adapters/opencode.py | 26 +++++++------- agent_observer/outcome.py | 11 +++--- tests/test_evidence_coverage.py | 55 +++++++++++++++++++++++++++-- 4 files changed, 114 insertions(+), 33 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index aa9378a..d3da9e9 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -106,7 +106,7 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 12 # Replay incomplete finals independently of their surviving identity. +_IMPORT_VERSION = 13 # Replay incomplete finals independently of their surviving identity. def _ensure_native_kinds(con) -> None: @@ -464,17 +464,15 @@ def import_claude_file(con: sqlite3.Connection, path: str, AND a.session_key=p.session_key AND a.uuid=p.uuid AND a.parent=p.parent AND a.response_id=p.response_id)""") if not src.incremental: - # Seeing the same message again without any final measurement cannot - # retract a previous final. Retain the gap until this source attests it. - con.execute("""INSERT OR IGNORE INTO claude_rejected_measurements - SELECT a.session_key,a.source_id,a.uuid,a.parent,a.response_id,'missing_final_usage' - FROM claude_response_ancestry a JOIN ( - SELECT session_key,source_id,response_id FROM temp.claude_prior_finals UNION - SELECT session_key,source_id,response_id FROM temp.claude_prior_edges - WHERE reason IN ('missing_final_usage','malformed_final_usage') - ) p USING(session_key,source_id,response_id) - WHERE NOT EXISTS (SELECT 1 FROM claude_final_observations f WHERE f.session_key=a.session_key - AND f.source_id=a.source_id AND f.response_id=a.response_id)""") + if not unreadable: + # A complete snapshot may remove a message altogether. Any + # surviving copy of that message, accepted or quarantined, keeps + # this source's obligation to supply its previously declared final. + con.execute("""DELETE FROM claude_expected_finals WHERE source_id=? + AND (session_key,response_id) NOT IN ( + SELECT session_key,response_id FROM claude_response_ancestry WHERE source_id=? + UNION SELECT session_key,response_id FROM claude_rejected_measurements WHERE source_id=? + )""", (src.source_id, src.source_id, src.source_id)) con.execute("DROP TABLE temp.claude_prior_edges") con.execute("DROP TABLE temp.claude_prior_finals") con.executemany("INSERT OR IGNORE INTO claude_ancestry_sources VALUES(?,?)", @@ -621,6 +619,11 @@ def conflicting_final_measurements(con, session_key): conflicts = {rid for rid, in con.execute( "SELECT DISTINCT o.response_id FROM claude_final_observations o JOIN responses r USING(session_key,response_id) " "WHERE o.session_key=? AND (" + " OR ".join(mismatch) + ")", (session_key,))} + if db._has_table(con, "claude_expected_finals"): + conflicts.update(rid for rid, in con.execute( + "SELECT e.response_id FROM claude_expected_finals e WHERE e.session_key=? AND NOT EXISTS (" + "SELECT 1 FROM claude_final_observations f WHERE f.session_key=e.session_key " + "AND f.source_id=e.source_id AND f.response_id=e.response_id)", (session_key,))) conflicts.update(rid for rid, in con.execute( "SELECT DISTINCT q.response_id FROM claude_rejected_measurements q WHERE q.session_key=? " "AND q.reason IN ('missing_final_usage','malformed_final_usage') AND NOT EXISTS (" @@ -629,6 +632,15 @@ def conflicting_final_measurements(con, session_key): return conflicts +def provisional_responses(con, session_key): + if not db._has_table(con, _FINALITY_TABLE): + return set() + return {rid for rid, in con.execute( + f"SELECT r.response_id FROM responses r JOIN sources s ON s.id=r.source_id " + f"WHERE r.session_key=? AND r.is_overlap=0 AND s.claude_usage_version>=13 AND NOT EXISTS (" + f"SELECT 1 FROM {_FINALITY_TABLE} f WHERE f.response_id=r.response_id)", (session_key,))} + + def _ingest_usage_row(r: _Reader, obj: dict, ordinal: int, ts, mid: str, model, values: dict, final: bool) -> None: """One streamed usage block for a message id. @@ -719,6 +731,11 @@ def _ingest_usage_row(r: _Reader, obj: dict, ordinal: int, ts, mid: str, r.finalized.add(mid) +def _final_stop(message): + reason = message.get("stop_reason") + return isinstance(reason, str) and bool(reason.strip()) + + def _assistant(r: _Reader, obj: dict, ordinal: int, ts) -> None: message = obj.get("message") if message is None: @@ -774,7 +791,7 @@ def _assistant(r: _Reader, obj: dict, ordinal: int, ts) -> None: # never finalize, so a later valid block still inserts normally. values = _usage_values(usage_raw) _ingest_usage_row(r, obj, ordinal, ts, mid, model, values, - message.get("stop_reason") is not None) + _final_stop(message)) def _submission(r: _Reader, native_id, ordinal, ts, kind: str, text: str, @@ -1181,6 +1198,14 @@ def _prepare_ancestry(r): session_key TEXT NOT NULL, response_id TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), payload TEXT NOT NULL, PRIMARY KEY(session_key,response_id,source_id,payload)) WITHOUT ROWID""") r.con.execute("CREATE INDEX IF NOT EXISTS claude_final_observation_source ON claude_final_observations(source_id)") + if not db._has_table(r.con, "claude_expected_finals"): + r.con.execute("""CREATE TABLE claude_expected_finals ( + source_id INTEGER NOT NULL REFERENCES sources(id), session_key TEXT NOT NULL, response_id TEXT NOT NULL, + PRIMARY KEY(session_key,source_id,response_id)) WITHOUT ROWID""") + r.con.execute("""INSERT OR IGNORE INTO claude_expected_finals + SELECT source_id,session_key,response_id FROM claude_final_observations UNION + SELECT source_id,session_key,response_id FROM claude_rejected_measurements + WHERE reason IN ('missing_final_usage','malformed_final_usage','unreadable_record')""") r.con.execute("""CREATE TABLE IF NOT EXISTS claude_unreadable_sources ( session_key TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), PRIMARY KEY(session_key,source_id)) WITHOUT ROWID""") @@ -1237,7 +1262,9 @@ def _record_ancestry(r, obj, rejected=None): mid = native_response.identifier(message.get("id")) if mid and message.get("model") != "": response_id = f"{HARNESS}:{mid}" - if message.get("stop_reason") is not None: + if _final_stop(message): + r.con.execute("INSERT OR IGNORE INTO claude_expected_finals VALUES(?,?,?)", + (r.src.source_id, r.session_key, response_id)) if rejected == "malformed_usage": rejected = "malformed_final_usage" elif not rejected and not message.get("usage"): diff --git a/agent_observer/adapters/opencode.py b/agent_observer/adapters/opencode.py index 0890c5b..c39b598 100644 --- a/agent_observer/adapters/opencode.py +++ b/agent_observer/adapters/opencode.py @@ -297,7 +297,7 @@ def _prepare_observations(con, session_key, source_id, *, identities_complete): # another copy can replace its projection. Only its own edge accompanies it. for row in con.execute( "SELECT r.* FROM responses r JOIN sources s ON s.id=r.source_id WHERE r.session_key=? " - "AND r.source_id<>? AND s.sha256 NOT GLOB 'oc[3-7]:*' AND NOT EXISTS " + "AND r.source_id<>? AND s.sha256 NOT GLOB 'oc[3-8]:*' AND NOT EXISTS " "(SELECT 1 FROM opencode_response_observations o WHERE o.session_key=r.session_key " "AND o.response_id=r.response_id AND o.source_id=r.source_id)", (session_key, source_id)): parent = con.execute( @@ -347,7 +347,9 @@ def response_witnesses(con, session_key): conflicts = set() payload_sources = {} observations = {} - malformed = {} + unavailable = {rid: set() for rid, in con.execute( + "SELECT response_id FROM responses WHERE session_key=? AND is_overlap=0 AND total_tokens IS NULL", + (session_key,))} measured = dict(con.execute("SELECT response_id,source_id FROM responses WHERE session_key=? AND is_overlap=0", (session_key,))) if db._has_table(con, "opencode_response_observations"): @@ -356,15 +358,15 @@ def response_witnesses(con, session_key): "WHERE session_key=?", (session_key,)): observations.setdefault(rid, set()).add((parent, measurement)) if measurement in _INVALID_OBSERVATIONS: - malformed[rid] = set() + unavailable[rid] = set() if rid in measured: payload_sources.setdefault(rid, set()).add(source) for rid, variants in observations.items(): - if rid not in measured and rid not in malformed: + if rid not in measured and rid not in unavailable: continue parents = {parent for parent, _ in variants if parent} - if rid in malformed: - malformed[rid] = parents + if rid in unavailable: + unavailable[rid] = parents if rid in measured and parents: witnesses[rid] = parents if len(variants) > 1 and (any(parent is None for parent, _ in variants) @@ -380,11 +382,11 @@ def response_witnesses(con, session_key): if db._has_table(con, "native_response_events"): for rid, source in con.execute( "SELECT DISTINCT e.response_id,e.source_id FROM native_response_events e " - "JOIN sources s ON s.id=e.source_id WHERE e.session_key=? AND s.sha256 NOT GLOB 'oc[4-7]:*'", + "JOIN sources s ON s.id=e.source_id WHERE e.session_key=? AND s.sha256 NOT GLOB 'oc[4-8]:*'", (session_key,)): if rid in measured and source not in payload_sources.get(rid, {measured[rid]}): conflicts.add(rid) - return witnesses, conflicts, malformed + return witnesses, conflicts, unavailable def has_unlocated_usage_error(con, session_key): @@ -392,7 +394,7 @@ def has_unlocated_usage_error(con, session_key): # Keep the session's cost open without guessing which message failed. return con.execute( "SELECT 1 FROM sources s WHERE s.harness=? AND s.session_id=? AND " - "(s.sha256 GLOB 'oc[4-7]:unlocated' OR (s.sha256 NOT GLOB 'oc[4-7]:*' AND EXISTS (SELECT 1 FROM import_errors e " + "(s.sha256 GLOB 'oc[4-8]:unlocated' OR (s.sha256 NOT GLOB 'oc[4-8]:*' AND EXISTS (SELECT 1 FROM import_errors e " "WHERE e.harness=s.harness AND e.source_path=s.path AND e.error='malformed_usage' " "AND instr(','||e.line_excerpt||',', ',tokens,')>0))) LIMIT 1", (HARNESS, session_key.partition(":")[2])).fetchone() is not None @@ -498,7 +500,7 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, session_key = f"{HARNESS}:{sess_id}" msg_n, msg_m = _count_max(native, "message", sess_id) part_n, part_m = _count_max(native, "part", sess_id) - fp = "oc7:" + fingerprint(sess.get("time_updated"), msg_m, part_m, msg_n, part_n) + fp = "oc8:" + fingerprint(sess.get("time_updated"), msg_m, part_m, msg_n, part_n) row = con.execute( "SELECT * FROM sources WHERE harness=? AND path=?", (HARNESS, src_path)).fetchone() @@ -710,7 +712,7 @@ def _ingest_response(con, stats, src_path, source_id, session_key, sess, # The observation holds either the measured fields or a reason they are unavailable. _MAX_COUNTER = (1 << 63) - 1 # SQLite INTEGER. -_UNLOCATED_SNAPSHOT = "oc7:unlocated" # Never matches a complete snapshot fingerprint. +_UNLOCATED_SNAPSHOT = "oc8:unlocated" # Never matches a complete snapshot fingerprint. _MALFORMED_USAGE = "malformed_usage" _INVALID_OBSERVATIONS = {"null", json.dumps(_MALFORMED_USAGE), json.dumps("unknown_message"), json.dumps("unfinished"), json.dumps("unmeasured")} @@ -767,7 +769,7 @@ def _measurement(data): if type(raw) is not int or not 0 <= raw <= _MAX_COUNTER: return _MALFORMED_USAGE values[field] = raw - if all(v == 0 for v in values.values()): + if not any(v is not None and v > 0 for v in values.values()): return "unmeasured" total = None if all(v is not None for v in values.values()): diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index 927db33..4de3e7e 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -163,10 +163,11 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me result.literal_sessions.add(key) call_witnesses = set() disputed_completions = set() - malformed = {} + unavailable = {} if harness == "claude": from .adapters import claude responses, disputed_completions = claude.response_witnesses(con, key) + unavailable = {rid: responses.get(rid, set()) for rid in claude.provisional_responses(con, key)} disputed_completions |= claude.conflicting_final_measurements(con, key) result.conflicts.update(disputed_completions) if _has_table(con, "claude_unreadable_sources") and con.execute( @@ -174,7 +175,7 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me result.unlocated_usage_sessions.add(key) elif harness == "opencode": from .adapters import opencode - responses, disputed_completions, malformed = opencode.response_witnesses(con, key) + responses, disputed_completions, unavailable = opencode.response_witnesses(con, key) if opencode.has_unlocated_usage_error(con, key): result.unlocated_usage_sessions.add(key) elif harness == "grok": @@ -200,9 +201,9 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me exclusive = False measured_turns = dict(con.execute( "SELECT response_id,turn_id FROM responses WHERE session_key=? AND is_overlap=0", (key,))) - for rid in measured_turns.keys() | malformed.keys(): + for rid in measured_turns.keys() | unavailable.keys(): display_turn = measured_turns.get(rid) - input_ids = responses.get(rid, malformed.get(rid, set())) + input_ids = responses.get(rid, unavailable.get(rid, set())) if rid in disputed_completions or len(input_ids) > 1: result.conflicts.add(rid) blocked_turns.update((display_turn, rid)) @@ -285,7 +286,7 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me result.turns.add((key, "codex:" + native_id)) elif harness == "grok": result.turns.add((key, rid)) - result.unavailable_usage.update(rid for rid in malformed + result.unavailable_usage.update(rid for rid in unavailable if not result.owners.get(rid) or task_id in result.owners[rid]) if literal_messages and not by_run: result.legacy_event_turns.update((key, turn) for turn, owners in claimed_turns.items() diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py index 9601fb4..c8549fc 100644 --- a/tests/test_evidence_coverage.py +++ b/tests/test_evidence_coverage.py @@ -585,8 +585,9 @@ def test_zero_counters_and_invalid_completion_time_withhold_opencode_cost(self): self.assign("A", "opencode:msg_u1") zero = dict(original, tokens={"input": 0, "output": 0, "reasoning": 0, "cache": {"read": 0, "write": 0}}) invalid_times = [dict(original, time={"completed": v}) for v in (False, True, -1, "broken", {})] - for record in [zero, *invalid_times]: - with self.subTest(record=record["time"]["completed"]): + no_counters = [dict(original, tokens=tokens) for tokens in ({}, {"cache": {}}, None)] + for record in [zero, *invalid_times, *no_counters]: + with self.subTest(time=record["time"], tokens=record["tokens"]): with closing(sqlite3.connect(path)) as src, src: src.execute("UPDATE message SET data=? WHERE id='msg_a1'", (json.dumps(record),)) opencode.sync(self.con, source=path, full=True) @@ -595,3 +596,53 @@ def test_zero_counters_and_invalid_completion_time_withhold_opencode_cost(self): self.assertIsNone(rep["native_cost"]["total_usd"]) self.assertEqual(rep["native_cost"]["known_subtotal_usd"], .10) self.assertIn("Evidence complete: no", self.draft()["body"]) + + def test_provisional_claude_copy_cannot_retract_an_observed_final(self): + path = self.import_claude() + self.assign("B", "claude:b") + rows = [json.loads(line) for line in path.read_text().splitlines()] + other = path.with_name("withdrawn.jsonl") + msg = rows[-1]["message"] + msg["usage"]["output_tokens"] = 90000 + write_records(other, rows) + claude.import_claude_file(self.con, str(other)) + self.assertFalse(report.task_report(self.con, "B")["attributed"]["responses"]) + provisional = dict(msg, stop_reason=None) + for message in (provisional, dict(msg, usage=None), [], provisional, provisional): + rows[-1]["message"] = message + write_records(other, rows) + claude.import_claude_file(self.con, str(other), full=True) + rep = report.task_report(self.con, "B") + self.assertFalse(rep["attributed"]["responses"]) + self.assertFalse(rep["complete"]) + self.assertFalse(report.timeline(self.con, "B")["events"]) + other.write_bytes(path.read_bytes()) + claude.import_claude_file(self.con, str(other), full=True) + self.assertTrue(report.task_report(self.con, "B")["complete"]) + + def test_partial_measurements_contribute_observations_without_closing_the_total(self): + path = self.opencode_store("partial", "msg_u1", 0.20, 50) + with closing(sqlite3.connect(path)) as source, source: + source.execute("UPDATE message SET data=json_remove(data,'$.tokens.input') WHERE id='msg_a1'") + opencode.sync(self.con, source=path) + self.assign("A", "opencode:msg_u1") + rep = report.task_report(self.con, "A") + self.assertEqual(rep["attributed"]["output_tokens"], 50) + self.assertFalse(rep["complete"]) + self.assertIsNone(rep["native_cost"]["total_usd"]) + self.assertEqual(rep["native_cost"]["known_subtotal_usd"], 0.20) + + def test_claude_provisional_usage_is_an_observation_until_its_first_final(self): + path = Path(self.tmp.name, "stream.jsonl") + response = claude_response("block", "p", "streamed") + response["message"]["stop_reason"] = None + write_records(path, [claude_user("p"), response]) + claude.import_claude_file(self.con, str(path)) + self.assign("A", "claude:p") + rep = report.task_report(self.con, "A") + self.assertEqual(rep["attributed"]["output_tokens"], 1) + self.assertFalse(rep["complete"]) + response["message"]["stop_reason"] = "end_turn" + write_records(path, [response], mode="a") + claude.import_claude_file(self.con, str(path)) + self.assertTrue(report.task_report(self.con, "A")["complete"]) From 55a5b4a79e7281c3281805cb4ff4b7a6805e2369 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 21:29:25 +0100 Subject: [PATCH 34/44] wip: keep incomplete Claude final counters out of complete totals --- agent_observer/adapters/claude.py | 20 +++++++++++--------- agent_observer/outcome.py | 2 +- tests/test_evidence_coverage.py | 18 ++++++++++++++++++ 3 files changed, 30 insertions(+), 10 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index d3da9e9..34249ca 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -98,10 +98,10 @@ class _UnsupportedSchema(ValueError): def _valid_counter(value) -> bool: - """Only NULL or a real integer counter; booleans are malformed.""" + """A known counter is a nonnegative SQLite INTEGER.""" if value is None: return True - return isinstance(value, int) and not isinstance(value, bool) + return type(value) is int and 0 <= value <= (1 << 63) - 1 _FINALITY_TABLE = "claude_response_finality" @@ -556,8 +556,7 @@ def _usage_values(usage) -> dict: raise _MalformedUsage("malformed usage counter") # service_tier and any other unrecognized metadata are ignored: they # never validate or invalidate a usage block. - if not any(k in usage for k in _CLAUDE_COUNTER_KEYS) and \ - "thinking_tokens" not in details: + if all(usage.get(k) is None for k in _CLAUDE_COUNTER_KEYS) and thinking is None: raise _MalformedUsage("malformed usage") ttl = usage.get("cache_creation") if ttl is not None and not isinstance(ttl, dict): @@ -572,6 +571,9 @@ def _usage_values(usage) -> dict: and five + hour != total_write: raise _MalformedUsage("inconsistent cache creation counters") values = [usage.get(k) for k in _CLAUDE_COUNTER_KEYS] + total = sum(values) if all(type(v) is int for v in values) else None + if not _valid_counter(total): + raise _MalformedUsage("invalid total token count") return { "input_tokens": usage.get("input_tokens"), "cached_input_tokens": usage.get("cache_read_input_tokens"), @@ -580,8 +582,7 @@ def _usage_values(usage) -> dict: "cache_write_1h_tokens": hour, "output_tokens": usage.get("output_tokens"), "reasoning_output_tokens": details.get("thinking_tokens"), - "total_tokens": sum(values) - if all(type(v) is int for v in values) else None, + "total_tokens": total, } @@ -632,13 +633,14 @@ def conflicting_final_measurements(con, session_key): return conflicts -def provisional_responses(con, session_key): +def responses_without_final_usage(con, session_key): if not db._has_table(con, _FINALITY_TABLE): return set() return {rid for rid, in con.execute( f"SELECT r.response_id FROM responses r JOIN sources s ON s.id=r.source_id " - f"WHERE r.session_key=? AND r.is_overlap=0 AND s.claude_usage_version>=13 AND NOT EXISTS (" - f"SELECT 1 FROM {_FINALITY_TABLE} f WHERE f.response_id=r.response_id)", (session_key,))} + f"WHERE r.session_key=? AND r.is_overlap=0 AND s.claude_usage_version>=13 " + f"AND (r.total_tokens IS NULL OR NOT EXISTS (SELECT 1 FROM {_FINALITY_TABLE} f " + f"WHERE f.response_id=r.response_id))", (session_key,))} def _ingest_usage_row(r: _Reader, obj: dict, ordinal: int, ts, mid: str, diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index 4de3e7e..0a4eaa2 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -167,7 +167,7 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me if harness == "claude": from .adapters import claude responses, disputed_completions = claude.response_witnesses(con, key) - unavailable = {rid: responses.get(rid, set()) for rid in claude.provisional_responses(con, key)} + unavailable = {rid: responses.get(rid, set()) for rid in claude.responses_without_final_usage(con, key)} disputed_completions |= claude.conflicting_final_measurements(con, key) result.conflicts.update(disputed_completions) if _has_table(con, "claude_unreadable_sources") and con.execute( diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py index c8549fc..2bba869 100644 --- a/tests/test_evidence_coverage.py +++ b/tests/test_evidence_coverage.py @@ -635,6 +635,7 @@ def test_partial_measurements_contribute_observations_without_closing_the_total( def test_claude_provisional_usage_is_an_observation_until_its_first_final(self): path = Path(self.tmp.name, "stream.jsonl") response = claude_response("block", "p", "streamed") + response["message"]["usage"].update(input_tokens=0, cache_read_input_tokens=0, cache_creation_input_tokens=0) response["message"]["stop_reason"] = None write_records(path, [claude_user("p"), response]) claude.import_claude_file(self.con, str(path)) @@ -646,3 +647,20 @@ def test_claude_provisional_usage_is_an_observation_until_its_first_final(self): write_records(path, [response], mode="a") claude.import_claude_file(self.con, str(path)) self.assertTrue(report.task_report(self.con, "A")["complete"]) + + def test_claude_final_with_unavailable_counters_cannot_close_the_bill(self): + path = Path(self.tmp.name, "only-final.jsonl") + message = claude_response("block", "p", "partial") + message["message"]["usage"] = {"output_tokens": None} + write_records(path, [claude_user("p"), message]) + claude.import_claude_file(self.con, str(path)) + self.assign("A", "claude:p") + rep = report.task_report(self.con, "A") + self.assertEqual(rep["attributed"]["responses"], 0) + self.assertFalse(rep["complete"]) + message["message"]["usage"]["output_tokens"] = 8 + write_records(path, [claude_user("p"), message]) + claude.import_claude_file(self.con, str(path), full=True) + rep = report.task_report(self.con, "A") + self.assertEqual(rep["attributed"]["output_tokens"], 8) + self.assertFalse(rep["complete"]) From b4851cfcdeced8a2e9f139e0348526e16d6b9c33 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 21:43:06 +0100 Subject: [PATCH 35/44] wip: preserve disputed Claude finals across torn replay and complete partial counters --- agent_observer/adapters/claude.py | 59 +++++++++++++++++---------- agent_observer/ingest.py | 2 + tests/test_evidence_coverage.py | 66 +++++++++++++++++++++++++++++++ 3 files changed, 106 insertions(+), 21 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index e5edf62..1675744 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -106,7 +106,7 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 13 # Replay incomplete finals independently of their surviving identity. +_IMPORT_VERSION = 14 # Reconcile partial final measurements on a fully readable snapshot. def _ensure_native_kinds(con) -> None: @@ -387,6 +387,11 @@ def import_claude_file(con: sqlite3.Connection, path: str, "session_key": session_key, }) return stats + if src.incremental and db._has_table(con, "claude_unreadable_sources") and con.execute( + "SELECT 1 FROM claude_unreadable_sources WHERE source_id=? LIMIT 1", (src.source_id,)).fetchone(): + # Re-evaluate the previously unreadable bytes and their old witnesses + # together, including when the writer merely finishes its last line. + src.start_offset = src.end_offset = 0 r = _Reader(con, src, stats) _ensure_finality_table(con) _ensure_native_kinds(con) @@ -453,6 +458,7 @@ def import_claude_file(con: sqlite3.Connection, path: str, _record_ancestry(r, obj, rejected="schema_error") stats["malformed"] += 1 src.error(ordinal, "schema_error", line) + unreadable = unreadable or src.incomplete_record or src.end_offset < src.size if unreadable: con.execute("INSERT OR IGNORE INTO claude_unreadable_sources VALUES(?,?)", (r.session_key, src.source_id)) if not src.incremental: @@ -611,20 +617,22 @@ def conflicting_final_measurements(con, session_key): if not db._has_table(con, "claude_final_observations"): return set() fields = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", - "reasoning_output_tokens", "total_tokens", "model") - mismatch = [f"json_extract(o.payload,'$.{name}') IS NOT r.{name}" for name in fields] - # Earlier final blocks may omit the subsequently supplied cache TTL detail. - for name in ("cache_write_5m_tokens", "cache_write_1h_tokens"): + "reasoning_output_tokens", "total_tokens", "cache_write_5m_tokens", "cache_write_1h_tokens") + mismatch = ["json_extract(o.payload,'$.model') IS NOT r.model"] + for name in fields: value = f"json_extract(o.payload,'$.{name}')" - mismatch.append(f"({value} IS NOT NULL AND r.{name} IS NOT NULL AND {value}<>r.{name})") + mismatch.append(f"({value} IS NOT NULL AND {value} IS NOT r.{name})") conflicts = {rid for rid, in con.execute( "SELECT DISTINCT o.response_id FROM claude_final_observations o JOIN responses r USING(session_key,response_id) " "WHERE o.session_key=? AND (" + " OR ".join(mismatch) + ")", (session_key,))} if db._has_table(con, "claude_expected_finals"): + complete = "" + if "requires_complete" in {c[1] for c in con.execute("PRAGMA table_info(claude_expected_finals)")}: + complete = " AND (e.requires_complete=0 OR json_extract(f.payload,'$.total_tokens') IS NOT NULL)" conflicts.update(rid for rid, in con.execute( "SELECT e.response_id FROM claude_expected_finals e WHERE e.session_key=? AND NOT EXISTS (" "SELECT 1 FROM claude_final_observations f WHERE f.session_key=e.session_key " - "AND f.source_id=e.source_id AND f.response_id=e.response_id)", (session_key,))) + "AND f.source_id=e.source_id AND f.response_id=e.response_id" + complete + ")", (session_key,))) conflicts.update(rid for rid, in con.execute( "SELECT DISTINCT q.response_id FROM claude_rejected_measurements q WHERE q.session_key=? " "AND q.reason IN ('missing_final_usage','malformed_final_usage') AND NOT EXISTS (" @@ -651,39 +659,42 @@ def _ingest_usage_row(r: _Reader, obj: dict, ordinal: int, ts, mid: str, is still streaming and non-final. Finality persists per response in a durable adapter table keyed by response_id, so a stale copied source or a full reimport can never overwrite a finalized row: an exact later - duplicate is a no-op and any differing counters are quarantined. A + duplicate is a no-op, compatible finals can supply missing fields, and + disagreements between measured counters are quarantined. A malformed final block never reaches here, so it never finalizes.""" rid = f"{HARNESS}:{mid}" if final: payload = json.dumps(dict(values, model=model), sort_keys=True) r.con.execute("INSERT OR IGNORE INTO claude_final_observations VALUES(?,?,?,?)", (r.session_key, rid, r.src.source_id, payload)) + if values["total_tokens"] is not None: + r.con.execute("""INSERT INTO claude_expected_finals(source_id,session_key,response_id,requires_complete) + VALUES(?,?,?,1) ON CONFLICT DO UPDATE SET requires_complete=1""", + (r.src.source_id, r.session_key, rid)) if mid in r.finalized or _is_finalized(r.con, rid): r.finalized.add(mid) seen = _stored_counters(r, rid) ttl_keys = ("cache_write_5m_tokens", "cache_write_1h_tokens") - if final and _matching_corrected_finals(r, rid, payload): + if final and values["total_tokens"] is not None and _matching_corrected_finals(r, rid, payload): # All fields come from the validated usage parser, never from JSON keys. names = tuple(k for k in values if k not in ttl_keys or values[k] is not None) r.con.execute("UPDATE responses SET model=?," + ",".join(f"{k}=?" for k in names) + " WHERE session_key=? AND response_id=?", (model, *(values[k] for k in names), r.session_key, rid)) seen = values - if any(seen.get(k) != v for k, v in values.items() if k not in ttl_keys): - raise _UsageConflict("usage conflict") if not final: - # A replayed provisional block cannot supply final TTL metadata. + if any(seen.get(k) != v for k, v in values.items() if k not in ttl_keys): + raise _UsageConflict("usage conflict") r.stats["responses_duplicate"] += 1 return - if any(seen.get(k) is not None and values[k] is not None - and seen[k] != values[k] for k in ttl_keys): + if any(seen.get(k) is not None and v is not None and seen[k] != v for k, v in values.items()): raise _UsageConflict("usage conflict") - # Enrich legacy finalized rows without replacing accepted usage or - # losing known TTL metadata when copied records omit it. - con = r.con - con.execute("UPDATE responses SET cache_write_5m_tokens=COALESCE(cache_write_5m_tokens,?)," - "cache_write_1h_tokens=COALESCE(cache_write_1h_tokens,?) WHERE response_id=?", - (values[ttl_keys[0]], values[ttl_keys[1]], rid)) + # Only the native parser can supply a total. Never sum fields + # assembled across partial measurements. + additions = {k: v for k, v in values.items() if seen.get(k) is None and v is not None} + if additions: + r.con.execute("UPDATE responses SET " + ",".join(f"{k}=?" for k in additions) + + " WHERE session_key=? AND response_id=?", (*additions.values(), r.session_key, rid)) r.stats["responses_duplicate"] += 1 return cur = r.con.execute( @@ -1208,6 +1219,11 @@ def _prepare_ancestry(r): SELECT source_id,session_key,response_id FROM claude_final_observations UNION SELECT source_id,session_key,response_id FROM claude_rejected_measurements WHERE reason IN ('missing_final_usage','malformed_final_usage','unreadable_record')""") + if "requires_complete" not in {c[1] for c in r.con.execute("PRAGMA table_info(claude_expected_finals)")}: + r.con.execute("ALTER TABLE claude_expected_finals ADD COLUMN requires_complete INTEGER NOT NULL DEFAULT 0") + r.con.execute("""UPDATE claude_expected_finals SET requires_complete=1 WHERE + (source_id,session_key,response_id) IN (SELECT source_id,session_key,response_id + FROM claude_final_observations WHERE json_extract(payload,'$.total_tokens') IS NOT NULL)""") r.con.execute("""CREATE TABLE IF NOT EXISTS claude_unreadable_sources ( session_key TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), PRIMARY KEY(session_key,source_id)) WITHOUT ROWID""") @@ -1265,7 +1281,8 @@ def _record_ancestry(r, obj, rejected=None): if mid and message.get("model") != "": response_id = f"{HARNESS}:{mid}" if _final_stop(message): - r.con.execute("INSERT OR IGNORE INTO claude_expected_finals VALUES(?,?,?)", + r.con.execute("INSERT OR IGNORE INTO claude_expected_finals(source_id,session_key,response_id)" + " VALUES(?,?,?)", (r.src.source_id, r.session_key, response_id)) if rejected == "malformed_usage": rejected = "malformed_final_usage" diff --git a/agent_observer/ingest.py b/agent_observer/ingest.py index 96df8cf..e7e5e09 100644 --- a/agent_observer/ingest.py +++ b/agent_observer/ingest.py @@ -121,6 +121,7 @@ def __init__(self, con: sqlite3.Connection, harness: str, path: str, self.row = row self.source_id = row["id"] self.end_offset = self.start_offset + self.incomplete_record = False def _check_at(self, row, size: int, mtime_ns: int, ino: int) -> tuple[int, bool]: @@ -245,6 +246,7 @@ def records(self): position = self.start_offset for raw in fh: if not raw.endswith(b"\n"): + self.incomplete_record = True break position += len(raw) text = raw.decode("utf-8", "replace") diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py index 2bba869..c4592df 100644 --- a/tests/test_evidence_coverage.py +++ b/tests/test_evidence_coverage.py @@ -664,3 +664,69 @@ def test_claude_final_with_unavailable_counters_cannot_close_the_bill(self): rep = report.task_report(self.con, "A") self.assertEqual(rep["attributed"]["output_tokens"], 8) self.assertFalse(rep["complete"]) + + def test_torn_final_line_preserves_dispute_until_a_readable_repair(self): + path = self.import_claude() + self.assign("B", "claude:b") + other = path.with_name("torn.jsonl") + rows = [json.loads(line) for line in path.read_text().splitlines()] + rows[-1]["message"]["usage"]["output_tokens"] = 90000 + write_records(other, rows) + claude.import_claude_file(self.con, str(other)) + write_records(other, rows[:-1]) + tail = json.dumps(rows[-1]) + with other.open("a") as out: + out.write(tail[:24]) + for _ in range(2): + claude.import_claude_file(self.con, str(other)) + self.assertFalse(report.task_report(self.con, "B")["attributed"]["responses"]) + self.assertFalse(report.timeline(self.con, "B")["events"]) + rows[-1]["message"]["usage"]["output_tokens"] = 5 + with other.open("a") as out: + out.write(json.dumps(rows[-1])[24:] + "\n") + claude.import_claude_file(self.con, str(other)) + self.assertTrue(report.task_report(self.con, "B")["complete"]) + + def check_completed_partial_final(self, append): + p = Path(self.tmp.name, "partial-final.jsonl") + msg = claude_response("reply", "p", "mid") + usage = {"output_tokens": 90000, "cache_read_input_tokens": 0, "cache_creation_input_tokens": 0} + msg["message"].update(model="claude-haiku-4-5", usage=usage, + content=[{"type": "tool_use", "id": "call", "name": "Read"}]) + write_records(p, [claude_user("p"), msg]) + claude.import_claude_file(self.con, str(p)) + self.assign("A", "claude:p") + before = report.task_report(self.con, "A") + self.assertEqual(before["attributed"]["output_tokens"], 90000) + self.assertFalse(before["complete"]) + usage["input_tokens"] = 11 + write_records(p, [msg] if append else [claude_user("p"), msg], mode="a" if append else "w") + claude.import_claude_file(self.con, str(p)) + after = report.task_report(self.con, "A") + self.assertTrue(after["complete"]) + self.assertEqual(after["attributed"]["total_tokens"], 90011) + self.assertEqual([e["native_id"] for e in report.timeline(self.con, "A")["events"]], ["call"]) + + def test_appended_final_enriches_missing_counter(self): + self.check_completed_partial_final(True) + + def test_rewritten_final_enriches_missing_counter(self): + self.check_completed_partial_final(False) + + def test_partial_copy_cannot_retract_its_disputed_counter(self): + path = self.import_claude() + self.assign("B", "claude:b") + rows = [json.loads(line) for line in path.read_text().splitlines()] + copy = path.with_name("partial-copy.jsonl") + usage = rows[-1]["message"]["usage"] + for output in (90000, None, 5): + with self.subTest(output=output): + if output is None: + del usage["output_tokens"] + else: + usage["output_tokens"] = output + write_records(copy, rows) + claude.import_claude_file(self.con, str(copy)) + rep = report.task_report(self.con, "B") + self.assertEqual(rep["complete"], output == 5) + self.assertEqual(rep["attributed"]["responses"], int(output == 5)) From 603df40754b66883e4c00b0ccd293f0bf36dd56f Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 21:53:09 +0100 Subject: [PATCH 36/44] wip: reconcile disputed final fields and validate combined cache counts --- agent_observer/adapters/claude.py | 104 ++++++++++++++++++++++++------ tests/test_evidence_coverage.py | 101 +++++++++++++++++++++++++++++ 2 files changed, 184 insertions(+), 21 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index 1675744..55d55fb 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -106,7 +106,7 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 14 # Reconcile partial final measurements on a fully readable snapshot. +_IMPORT_VERSION = 15 # Reconcile source-specific final fields and their cache split. def _ensure_native_kinds(con) -> None: @@ -479,8 +479,25 @@ def import_claude_file(con: sqlite3.Connection, path: str, SELECT session_key,response_id FROM claude_response_ancestry WHERE source_id=? UNION SELECT session_key,response_id FROM claude_rejected_measurements WHERE source_id=? )""", (src.source_id, src.source_id, src.source_id)) + # A replacement can revise a field by measuring it again. Omitting + # the field cannot settle a disagreement, even across partial finals. + con.execute("""INSERT OR IGNORE INTO claude_retained_final_fields + SELECT p.session_key,p.response_id,p.source_id,j.key,j.value + FROM claude_prior_finals p JOIN claude_expected_finals e USING(session_key,response_id,source_id), + json_each(p.payload) j WHERE j.value IS NOT NULL AND NOT EXISTS ( + SELECT 1 FROM claude_final_observations o WHERE o.session_key=p.session_key + AND o.response_id=p.response_id AND o.source_id=p.source_id + AND json_extract(o.payload,'$.'||j.key) IS NOT NULL)""") con.execute("DROP TABLE temp.claude_prior_edges") con.execute("DROP TABLE temp.claude_prior_finals") + # Retained values supply negative evidence only. A readable removal of + # the response, or a new measurement for this field, retires that value. + con.execute("""DELETE FROM claude_retained_final_fields AS p WHERE p.source_id=? AND ( + NOT EXISTS (SELECT 1 FROM claude_expected_finals e WHERE e.session_key=p.session_key + AND e.response_id=p.response_id AND e.source_id=p.source_id) OR EXISTS ( + SELECT 1 FROM claude_final_observations o WHERE o.session_key=p.session_key + AND o.response_id=p.response_id AND o.source_id=p.source_id + AND json_extract(o.payload,'$.'||p.field) IS NOT NULL))""", (src.source_id,)) con.executemany("INSERT OR IGNORE INTO claude_ancestry_sources VALUES(?,?)", ((key, src.source_id) for key in r.linked_sessions)) if r.native_session: @@ -535,6 +552,13 @@ def _ingest(r: _Reader, obj: dict, ordinal: int) -> None: raise _UnsupportedSchema(f"unsupported record type: {kind!r}") +def _cache_consistent(total, five, hour): + if total is None: + return five is None or hour is None or _valid_counter(five + hour) + return ((five is None or five <= total) and (hour is None or hour <= total) + and (five is None or hour is None or five + hour == total)) + + def _usage_values(usage) -> dict: """Native usage buckets with unknown preserved as NULL. @@ -573,8 +597,7 @@ def _usage_values(usage) -> dict: if not _valid_counter(five) or not _valid_counter(hour): raise _MalformedUsage("malformed cache creation counter") total_write = usage.get("cache_creation_input_tokens") - if five is not None and hour is not None and total_write is not None \ - and five + hour != total_write: + if not _cache_consistent(total_write, five, hour): raise _MalformedUsage("inconsistent cache creation counters") values = [usage.get(k) for k in _CLAUDE_COUNTER_KEYS] total = sum(values) if all(type(v) is int for v in values) else None @@ -601,15 +624,34 @@ def _stored_counters(r: _Reader, rid: str) -> dict: return dict(row) if row is not None else {} -def _matching_corrected_finals(r, rid, payload): - # A single later block cannot revise immutable final usage. Independent - # copies, including the original measured source, can establish a correction. +def _corroborated_final(r, rid, seen): + """A changed counter needs matching measurements from its original source and a copy.""" rows = r.con.execute( - "SELECT o.source_id,o.payload,r.source_id AS original FROM claude_final_observations o " + "SELECT o.source_id,o.payload,r.source_id AS original,r.model FROM claude_final_observations o " "JOIN responses r USING(session_key,response_id) WHERE o.session_key=? AND o.response_id=?", (r.session_key, rid)).fetchall() - return (len({row["source_id"] for row in rows}) > 1 and all(row["payload"] == payload for row in rows) - and any(row["source_id"] == row["original"] for row in rows)) + sources = {row["source_id"] for row in rows} + if len(sources) < 2 or rows[0]["original"] not in sources: + return None + agreed = {} + witnesses = defaultdict(set) + for row in rows: + for field, value in json.loads(row["payload"]).items(): + if value is None or (field != "model" and field not in seen): + continue + if field in agreed and agreed[field] != value: + return None + agreed[field] = value + witnesses[field].add(row["source_id"]) + # A single native final must actually have measured the full total. + # Its constituent counters, when revised, must also be corroborated. + if "total_tokens" not in agreed: + return None + for field, old in dict(seen, model=rows[0]["model"]).items(): + if field != "total_tokens" and old is not None and field in agreed and old != agreed[field]: + if len(witnesses[field]) < 2 or rows[0]["original"] not in witnesses[field]: + return None + return agreed def conflicting_final_measurements(con, session_key): @@ -625,6 +667,17 @@ def conflicting_final_measurements(con, session_key): conflicts = {rid for rid, in con.execute( "SELECT DISTINCT o.response_id FROM claude_final_observations o JOIN responses r USING(session_key,response_id) " "WHERE o.session_key=? AND (" + " OR ".join(mismatch) + ")", (session_key,))} + if db._has_table(con, "claude_retained_final_fields"): + column = "CASE p.field " + " ".join(f"WHEN '{name}' THEN r.{name}" for name in (*fields, "model")) + " END" + conflicts.update(rid for rid, in con.execute( + "SELECT DISTINCT p.response_id FROM claude_retained_final_fields p " + "JOIN responses r USING(session_key,response_id) WHERE p.session_key=? AND p.value IS NOT " + column, + (session_key,))) + # Read-only ledgers may already contain an incoherent pre-version-15 row. + conflicts.update(rid for rid, in con.execute( + "SELECT response_id FROM responses WHERE session_key=? AND (cache_write_5m_tokens>cache_write_input_tokens " + "OR cache_write_1h_tokens>cache_write_input_tokens " + "OR cache_write_1h_tokens<>cache_write_input_tokens-cache_write_5m_tokens)", (session_key,))) if db._has_table(con, "claude_expected_finals"): complete = "" if "requires_complete" in {c[1] for c in con.execute("PRAGMA table_info(claude_expected_finals)")}: @@ -675,26 +728,30 @@ def _ingest_usage_row(r: _Reader, obj: dict, ordinal: int, ts, mid: str, r.finalized.add(mid) seen = _stored_counters(r, rid) ttl_keys = ("cache_write_5m_tokens", "cache_write_1h_tokens") - if final and values["total_tokens"] is not None and _matching_corrected_finals(r, rid, payload): - # All fields come from the validated usage parser, never from JSON keys. - names = tuple(k for k in values if k not in ttl_keys or values[k] is not None) - r.con.execute("UPDATE responses SET model=?," + ",".join(f"{k}=?" for k in names) - + " WHERE session_key=? AND response_id=?", - (model, *(values[k] for k in names), r.session_key, rid)) - seen = values if not final: if any(seen.get(k) != v for k, v in values.items() if k not in ttl_keys): raise _UsageConflict("usage conflict") r.stats["responses_duplicate"] += 1 return - if any(seen.get(k) is not None and v is not None and seen[k] != v for k, v in values.items()): + corrected = _corroborated_final(r, rid, seen) + supplied = corrected if corrected is not None else {k: v for k, v in values.items() if v is not None} + combined = {**seen, **supplied} + if not _cache_consistent(combined.get("cache_write_input_tokens"), *(combined.get(k) for k in ttl_keys)): + raise _UsageConflict("usage conflict") + changes = {k: v for k, v in supplied.items() if seen.get(k) != v} + revisions = {k for k in changes if seen.get(k) is not None} + # Version 14 could already have combined incompatible cache fields. + # A coherent complete measurement can repair those fields on replay. + repair_cache = (values["total_tokens"] is not None and + not _cache_consistent(seen.get("cache_write_input_tokens"), *(seen.get(k) for k in ttl_keys)) + and revisions <= {*ttl_keys, "cache_write_input_tokens", "total_tokens"}) + if revisions and corrected is None and not repair_cache: raise _UsageConflict("usage conflict") # Only the native parser can supply a total. Never sum fields # assembled across partial measurements. - additions = {k: v for k, v in values.items() if seen.get(k) is None and v is not None} - if additions: - r.con.execute("UPDATE responses SET " + ",".join(f"{k}=?" for k in additions) - + " WHERE session_key=? AND response_id=?", (*additions.values(), r.session_key, rid)) + if changes: + r.con.execute("UPDATE responses SET " + ",".join(f"{k}=?" for k in changes) + + " WHERE session_key=? AND response_id=?", (*changes.values(), r.session_key, rid)) r.stats["responses_duplicate"] += 1 return cur = r.con.execute( @@ -1211,6 +1268,11 @@ def _prepare_ancestry(r): session_key TEXT NOT NULL, response_id TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), payload TEXT NOT NULL, PRIMARY KEY(session_key,response_id,source_id,payload)) WITHOUT ROWID""") r.con.execute("CREATE INDEX IF NOT EXISTS claude_final_observation_source ON claude_final_observations(source_id)") + r.con.execute("""CREATE TABLE IF NOT EXISTS claude_retained_final_fields ( + session_key TEXT NOT NULL, response_id TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), + field TEXT NOT NULL, value NOT NULL, + PRIMARY KEY(session_key,response_id,source_id,field,value)) WITHOUT ROWID""") + r.con.execute("CREATE INDEX IF NOT EXISTS claude_retained_field_source ON claude_retained_final_fields(source_id)") if not db._has_table(r.con, "claude_expected_finals"): r.con.execute("""CREATE TABLE claude_expected_finals ( source_id INTEGER NOT NULL REFERENCES sources(id), session_key TEXT NOT NULL, response_id TEXT NOT NULL, diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py index c4592df..9b1741e 100644 --- a/tests/test_evidence_coverage.py +++ b/tests/test_evidence_coverage.py @@ -730,3 +730,104 @@ def test_partial_copy_cannot_retract_its_disputed_counter(self): rep = report.task_report(self.con, "B") self.assertEqual(rep["complete"], output == 5) self.assertEqual(rep["attributed"]["responses"], int(output == 5)) + + def check_withdrawn_field(self, ttl): + path = Path(self.tmp.name, "original.jsonl") + response = claude_response("reply", "b", "response") + usage = dict(input_tokens=10, output_tokens=5, cache_read_input_tokens=0, + cache_creation_input_tokens=10 if ttl else 0) + if ttl: + usage["cache_creation"] = {"ephemeral_5m_input_tokens": 10, "ephemeral_1h_input_tokens": 0} + response["message"].update(usage=usage, model="claude-haiku-4-5", + content=[{"type": "tool_use", "id": "b-call", "name": "Read"}]) + rows = [claude_user("b"), response] + write_records(path, rows) + claude.import_claude_file(self.con, str(path)) + self.assign("B", "claude:b") + rid = "claude:" + rows[-1]["message"]["id"] + call = rows[-1]["message"]["content"][0]["id"] + copy = path.with_name("competing.jsonl") + if ttl: + usage["cache_creation"] = {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 10} + else: + del usage["input_tokens"] + usage["output_tokens"] = 90000 + for step in ("different", "withdrawn", "repeat", "restored"): + if step == "withdrawn": + if ttl: + del usage["cache_creation"] + else: + usage["input_tokens"] = 10 + del usage["output_tokens"] + if step == "restored": + rows = [json.loads(line) for line in path.read_text().splitlines()] + write_records(copy, rows) + claude.import_claude_file(self.con, str(copy)) + with self.subTest(step=step): + rep = report.task_report(self.con, "B") + self.assertEqual(rid in rep["measured"]["attributed_responses"], step == "restored") + self.assertEqual(call in [e["native_id"] for e in report.timeline(self.con, "B")["events"]], + step == "restored") + if step != "restored": + self.assertIsNone(rep["total_cost"]["usd"]) + + def test_withdrawing_partial_disputed_output_does_not_resolve_it(self): + self.check_withdrawn_field(False) + + def test_withdrawing_disputed_cache_split_does_not_resolve_it(self): + self.check_withdrawn_field(True) + + def check_contradictory_cache_enrichment(self, append): + path = Path(self.tmp.name, "cache.jsonl") + msg = claude_response("reply", "p", "cache") + usage = dict(input_tokens=5, output_tokens=7, cache_read_input_tokens=0, + cache_creation=dict(ephemeral_5m_input_tokens=100000, ephemeral_1h_input_tokens=0)) + msg["message"].update(model="claude-haiku-4-5", usage=usage, + content=[{"type": "tool_use", "id": "cache-call", "name": "Read"}]) + write_records(path, [claude_user("p"), msg]) + claude.import_claude_file(self.con, str(path)) + self.assign("A", "claude:p") + del usage["cache_creation"] + usage["cache_creation_input_tokens"] = 0 + write_records(path, [msg] if append else [claude_user("p"), msg], mode="a" if append else "w") + claude.import_claude_file(self.con, str(path)) + rep = report.task_report(self.con, "A") + self.assertFalse(rep["attributed"]["responses"]) + self.assertFalse(rep["complete"]) + self.assertIsNone(rep["total_cost"]["usd"]) + self.assertFalse(report.timeline(self.con, "A")["events"]) + self.assertIn("Evidence complete: no", self.draft()["body"]) + # A readable replacement with the matching aggregate can still seal the bill. + usage["cache_creation_input_tokens"] = 100000 + write_records(path, [claude_user("p"), msg]) + claude.import_claude_file(self.con, str(path)) + rep = report.task_report(self.con, "A") + self.assertTrue(rep["complete"]) + self.assertEqual(rep["attributed"]["total_tokens"], 100012) + + def test_appending_incompatible_cache_components_withholds_usage(self): + self.check_contradictory_cache_enrichment(True) + + def test_rewriting_incompatible_cache_components_withholds_usage(self): + self.check_contradictory_cache_enrichment(False) + + def test_complete_copy_and_corrected_partial_confirm_the_same_measurement(self): + partial = Path(self.tmp.name, "first.jsonl") + complete = Path(self.tmp.name, "second.jsonl") + msg = claude_response("reply", "p", "id") + rows = [claude_user("p"), msg] + usage = dict(output_tokens=90000, cache_read_input_tokens=0, cache_creation_input_tokens=0) + msg["message"].update(usage=usage, model="claude-haiku-4-5") + write_records(partial, rows) + claude.import_claude_file(self.con, str(partial)) + self.assign("A", "claude:p") + usage.update(output_tokens=5, input_tokens=10) + write_records(complete, rows) + claude.import_claude_file(self.con, str(complete)) + self.assertFalse(report.task_report(self.con, "A")["attributed"]["responses"]) + del usage["input_tokens"] + write_records(partial, rows) + claude.import_claude_file(self.con, str(partial)) + rep = report.task_report(self.con, "A") + self.assertTrue(rep["complete"]) + self.assertEqual(rep["attributed"]["total_tokens"], 15) From ce4217dd3b3ccb1b083d85f1e9c8adb7ba592478 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 22:05:00 +0100 Subject: [PATCH 37/44] wip: rebuild Claude response accounting when a measured source withdraws --- agent_observer/adapters/claude.py | 125 ++++++++++++++++++++++++------ tests/test_evidence_coverage.py | 44 +++++++++++ 2 files changed, 146 insertions(+), 23 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index 55d55fb..61c2aa9 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -106,7 +106,7 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 15 # Reconcile source-specific final fields and their cache split. +_IMPORT_VERSION = 16 # Rebuild measurements from surviving finals after a source withdrawal. def _ensure_native_kinds(con) -> None: @@ -433,6 +433,7 @@ def import_claude_file(con: sqlite3.Connection, path: str, unreadable = True try: r.message_events.clear() + r.final_location = None _ingest(r, obj, ordinal) _record_ancestry(r, obj) if obj.get("type") == "queue-operation": @@ -474,11 +475,15 @@ def import_claude_file(con: sqlite3.Connection, path: str, # A complete snapshot may remove a message altogether. Any # surviving copy of that message, accepted or quarantined, keeps # this source's obligation to supply its previously declared final. - con.execute("""DELETE FROM claude_expected_finals WHERE source_id=? + retired = """ WHERE source_id=? AND (session_key,response_id) NOT IN ( SELECT session_key,response_id FROM claude_response_ancestry WHERE source_id=? UNION SELECT session_key,response_id FROM claude_rejected_measurements WHERE source_id=? - )""", (src.source_id, src.source_id, src.source_id)) + )""" + ids = (src.source_id,) * 3 + con.execute("INSERT OR IGNORE INTO claude_withdrawn_finals SELECT session_key,response_id " + "FROM claude_expected_finals" + retired, ids) + con.execute("DELETE FROM claude_expected_finals" + retired, ids) # A replacement can revise a field by measuring it again. Omitting # the field cannot settle a disagreement, even across partial finals. con.execute("""INSERT OR IGNORE INTO claude_retained_final_fields @@ -498,6 +503,7 @@ def import_claude_file(con: sqlite3.Connection, path: str, SELECT 1 FROM claude_final_observations o WHERE o.session_key=p.session_key AND o.response_id=p.response_id AND o.source_id=p.source_id AND json_extract(o.payload,'$.'||p.field) IS NOT NULL))""", (src.source_id,)) + _reproject_withdrawn_finals(r) con.executemany("INSERT OR IGNORE INTO claude_ancestry_sources VALUES(?,?)", ((key, src.source_id) for key in r.linked_sessions)) if r.native_session: @@ -624,6 +630,20 @@ def _stored_counters(r: _Reader, rid: str) -> dict: return dict(row) if row is not None else {} +def _agreeing_fields(rows, fields): + agreed = {} + witnesses = defaultdict(set) + for row in rows: + for field, value in json.loads(row["payload"]).items(): + if value is None or field not in fields: + continue + if field in agreed and agreed[field] != value: + return None, witnesses + agreed[field] = value + witnesses[field].add(row["source_id"]) + return agreed, witnesses + + def _corroborated_final(r, rid, seen): """A changed counter needs matching measurements from its original source and a copy.""" rows = r.con.execute( @@ -633,19 +653,10 @@ def _corroborated_final(r, rid, seen): sources = {row["source_id"] for row in rows} if len(sources) < 2 or rows[0]["original"] not in sources: return None - agreed = {} - witnesses = defaultdict(set) - for row in rows: - for field, value in json.loads(row["payload"]).items(): - if value is None or (field != "model" and field not in seen): - continue - if field in agreed and agreed[field] != value: - return None - agreed[field] = value - witnesses[field].add(row["source_id"]) + agreed, witnesses = _agreeing_fields(rows, {*seen, "model"}) # A single native final must actually have measured the full total. # Its constituent counters, when revised, must also be corroborated. - if "total_tokens" not in agreed: + if not agreed or "total_tokens" not in agreed: return None for field, old in dict(seen, model=rows[0]["model"]).items(): if field != "total_tokens" and old is not None and field in agreed and old != agreed[field]: @@ -654,6 +665,40 @@ def _corroborated_final(r, rid, seen): return agreed +def _reproject_withdrawn_finals(r): + """A readable removal retires every counter and locator supplied only by that source.""" + con = r.con + for key, rid in con.execute("SELECT session_key,response_id FROM claude_withdrawn_finals " + "WHERE session_key=?", (r.session_key,)).fetchall(): + copies = con.execute("SELECT o.source_id,o.payload,u.source_id AS unreadable FROM claude_final_observations o " + "LEFT JOIN claude_unreadable_sources u USING(session_key,source_id) " + "WHERE o.session_key=? AND o.response_id=?", (key, rid)).fetchall() + blocks = con.execute("SELECT b.* FROM claude_final_blocks b JOIN sources s ON s.id=b.source_id " + "WHERE b.session_key=? AND b.response_id=? ORDER BY s.path,b.ordinal_num", + (key, rid)).fetchall() + if (not copies or any(c["unreadable"] for c in copies) + or {c["source_id"] for c in copies} != {b["source_id"] for b in blocks}): + continue + fields = (*_stored_counters(r, rid), "model") + agreed, witnessed = _agreeing_fields(copies, fields) + if not agreed or not _cache_consistent(agreed.get("cache_write_input_tokens"), + agreed.get("cache_write_5m_tokens"), agreed.get("cache_write_1h_tokens")): + continue + if all(b["link_status"] == "absent" for b in blocks) and len({b["turn_id"] for b in blocks}) > 1: + continue + # Prefer a native block from a copy that measured the complete total. + block = next((b for b in blocks if b["source_id"] in witnessed["total_tokens"]), blocks[0]) + con.execute("UPDATE responses SET " + ",".join(f"{field}=?" for field in fields) + + ",source_id=?,turn_id=?,ordinal_num=?,ts=? WHERE session_key=? AND response_id=?", + (*(agreed.get(field) for field in fields), block["source_id"], block["turn_id"], + block["ordinal_num"], block["ts"], key, rid)) + # Only a block with validated final usage can regain its recorded + # ancestry. Other rejected blocks and unusable parents stay disputed. + for b in blocks: + _save_edge(con, key, b["uuid"], b["parent"], "", rid, b["source_id"], b["link_status"]) + con.execute("DELETE FROM claude_withdrawn_finals WHERE session_key=? AND response_id=?", (key, rid)) + + def conflicting_final_measurements(con, session_key): """A task can bill a final row only when its source measurements agree.""" if not db._has_table(con, "claude_final_observations"): @@ -673,6 +718,9 @@ def conflicting_final_measurements(con, session_key): "SELECT DISTINCT p.response_id FROM claude_retained_final_fields p " "JOIN responses r USING(session_key,response_id) WHERE p.session_key=? AND p.value IS NOT " + column, (session_key,))) + if db._has_table(con, "claude_withdrawn_finals"): + conflicts.update(rid for rid, in con.execute( + "SELECT response_id FROM claude_withdrawn_finals WHERE session_key=?", (session_key,))) # Read-only ledgers may already contain an incoherent pre-version-15 row. conflicts.update(rid for rid, in con.execute( "SELECT response_id FROM responses WHERE session_key=? AND (cache_write_5m_tokens>cache_write_input_tokens " @@ -697,11 +745,15 @@ def conflicting_final_measurements(con, session_key): def responses_without_final_usage(con, session_key): if not db._has_table(con, _FINALITY_TABLE): return set() + missing = "" + if db._has_table(con, "claude_final_observations"): + missing = (" OR NOT EXISTS (SELECT 1 FROM claude_final_observations o WHERE o.session_key=r.session_key " + "AND o.response_id=r.response_id AND json_extract(o.payload,'$.total_tokens') IS NOT NULL)") return {rid for rid, in con.execute( f"SELECT r.response_id FROM responses r JOIN sources s ON s.id=r.source_id " f"WHERE r.session_key=? AND r.is_overlap=0 AND s.claude_usage_version>=13 " f"AND (r.total_tokens IS NULL OR NOT EXISTS (SELECT 1 FROM {_FINALITY_TABLE} f " - f"WHERE f.response_id=r.response_id))", (session_key,))} + f"WHERE f.response_id=r.response_id)" + missing + ")", (session_key,))} def _ingest_usage_row(r: _Reader, obj: dict, ordinal: int, ts, mid: str, @@ -717,6 +769,7 @@ def _ingest_usage_row(r: _Reader, obj: dict, ordinal: int, ts, mid: str, malformed final block never reaches here, so it never finalizes.""" rid = f"{HARNESS}:{mid}" if final: + r.final_location = (ordinal, ts) payload = json.dumps(dict(values, model=model), sort_keys=True) r.con.execute("INSERT OR IGNORE INTO claude_final_observations VALUES(?,?,?,?)", (r.session_key, rid, r.src.source_id, payload)) @@ -1273,6 +1326,23 @@ def _prepare_ancestry(r): field TEXT NOT NULL, value NOT NULL, PRIMARY KEY(session_key,response_id,source_id,field,value)) WITHOUT ROWID""") r.con.execute("CREATE INDEX IF NOT EXISTS claude_retained_field_source ON claude_retained_final_fields(source_id)") + r.con.execute("""CREATE TABLE IF NOT EXISTS claude_final_blocks ( + session_key TEXT NOT NULL, response_id TEXT NOT NULL, source_id INTEGER NOT NULL REFERENCES sources(id), + uuid TEXT NOT NULL, parent TEXT NOT NULL, link_status TEXT NOT NULL, turn_id TEXT, ordinal_num INTEGER NOT NULL, + ts REAL, PRIMARY KEY(session_key,response_id,source_id,ordinal_num)) WITHOUT ROWID""") + r.con.execute("CREATE INDEX IF NOT EXISTS claude_block_source ON claude_final_blocks(source_id)") + if not db._has_table(r.con, "claude_withdrawn_finals"): + r.con.execute("""CREATE TABLE claude_withdrawn_finals ( + session_key TEXT NOT NULL,response_id TEXT NOT NULL, PRIMARY KEY(session_key,response_id)) WITHOUT ROWID""") + # A pre-version-16 ledger could already have removed a source while + # retaining its total or its location in the materialized response. + r.con.execute("""INSERT INTO claude_withdrawn_finals SELECT r.session_key,r.response_id FROM responses r + WHERE r.harness='claude' AND EXISTS (SELECT 1 FROM claude_final_observations o + WHERE o.session_key=r.session_key AND o.response_id=r.response_id) + AND (NOT EXISTS (SELECT 1 FROM claude_final_observations o WHERE o.session_key=r.session_key + AND o.response_id=r.response_id AND o.source_id=r.source_id) OR (r.total_tokens IS NOT NULL + AND NOT EXISTS (SELECT 1 FROM claude_final_observations o WHERE o.session_key=r.session_key + AND o.response_id=r.response_id AND json_extract(o.payload,'$.total_tokens') IS NOT NULL)))""") if not db._has_table(r.con, "claude_expected_finals"): r.con.execute("""CREATE TABLE claude_expected_finals ( source_id INTEGER NOT NULL REFERENCES sources(id), session_key TEXT NOT NULL, response_id TEXT NOT NULL, @@ -1291,6 +1361,7 @@ def _prepare_ancestry(r): PRIMARY KEY(session_key,source_id)) WITHOUT ROWID""") r.linked_sessions = set() if not r.src.incremental: + r.con.execute("DELETE FROM claude_final_blocks WHERE source_id=?", (r.src.source_id,)) # Keep identities only until the replacement proves it could read # every row. A broken line cannot silently retract a competing copy. r.con.execute("CREATE TEMP TABLE claude_prior_edges AS " @@ -1377,18 +1448,26 @@ def _record_ancestry(r, obj, rejected=None): # pre-ancestry format. Remember the format independently of ownership. if status != "absent": r.linked_sessions.add(r.session_key) + if response_id and r.final_location is not None: + r.con.execute("INSERT OR REPLACE INTO claude_final_blocks VALUES(?,?,?,?,?,?,?,?,?)", + (r.session_key, response_id, r.src.source_id, uuid or "", parent or "", status, + r.turn, *r.final_location)) if rejected and response_id: r.con.execute("INSERT OR IGNORE INTO claude_rejected_measurements VALUES(?,?,?,?,?,?)", (r.session_key, r.src.source_id, uuid or "", parent or "", response_id, rejected)) return - r.con.execute("INSERT INTO claude_response_ancestry" - "(session_key,uuid,parent,input_id,response_id,source_id,link_status)" - " VALUES(?,?,?,?,?,?,?) ON CONFLICT DO UPDATE SET link_status=" - "CASE WHEN link_status='invalid' OR excluded.link_status='invalid' THEN 'invalid' " - "WHEN link_status='linked' OR excluded.link_status='linked' THEN 'linked' " - "WHEN link_status='root' OR excluded.link_status='root' THEN 'root' ELSE excluded.link_status END", - (r.session_key, uuid or "", "" if input_id else parent or "", - input_id, response_id, r.src.source_id, status)) + _save_edge(r.con, r.session_key, uuid or "", "" if input_id else parent or "", + input_id, response_id, r.src.source_id, status) + + +def _save_edge(con, session, uuid, parent, input_id, response_id, source, status): + con.execute("INSERT INTO claude_response_ancestry" + "(session_key,uuid,parent,input_id,response_id,source_id,link_status)" + " VALUES(?,?,?,?,?,?,?) ON CONFLICT DO UPDATE SET link_status=" + "CASE WHEN link_status='invalid' OR excluded.link_status='invalid' THEN 'invalid' " + "WHEN link_status='linked' OR excluded.link_status='linked' THEN 'linked' " + "WHEN link_status='root' OR excluded.link_status='root' THEN 'root' ELSE excluded.link_status END", + (session, uuid, parent, input_id, response_id, source, status)) def legacy_capture_sources(con, session_key): diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py index 9b1741e..cb1debc 100644 --- a/tests/test_evidence_coverage.py +++ b/tests/test_evidence_coverage.py @@ -831,3 +831,47 @@ def test_complete_copy_and_corrected_partial_confirm_the_same_measurement(self): rep = report.task_report(self.con, "A") self.assertTrue(rep["complete"]) self.assertEqual(rep["attributed"]["total_tokens"], 15) + + def check_removed_claude_final(self, remove_complete, complete_first): + a = Path(self.tmp.name, "partial.jsonl") + b = Path(self.tmp.name, "complete.jsonl") + msg = claude_response("reply", "p", "id") + msg["message"].update(model="claude-haiku-4-5", content=[{"type": "tool_use", "id": "call", "name": "Read"}]) + common = dict(output_tokens=5, cache_read_input_tokens=0) + partial = dict(common, cache_creation_input_tokens=0) if remove_complete else dict( + common, input_tokens=10, cache_creation={"ephemeral_5m_input_tokens": 100000, "ephemeral_1h_input_tokens": 0}) + for path, counters in [(a, partial), (b, dict(common, input_tokens=10, cache_creation_input_tokens=0))]: + msg["message"]["usage"] = counters + write_records(path, [claude_user("p"), msg]) + for path in ([b, a] if complete_first else [a, b]): + claude.import_claude_file(self.con, str(path)) + self.assign("A", "claude:p") + self.assertEqual(report.task_report(self.con, "A")["complete"], remove_complete) + removed, survivor = (b, a) if remove_complete else (a, b) + write_records(removed, [claude_user("p")]) + claude.import_claude_file(self.con, str(removed)) + for repeat in (False, True): + if repeat: + self.assertEqual(claude.import_claude_file(self.con, str(survivor), full=True)["malformed"], 0) + with self.subTest(reimport=repeat): + rep = report.task_report(self.con, "A") + self.assertEqual(rep["attributed"]["responses"], 1) + self.assertEqual(rep["complete"], not remove_complete) + self.assertEqual(rep["total_cost"]["usd"] is None, remove_complete) + self.assertEqual([e["native_id"] for e in report.timeline(self.con, "A")["events"]], ["call"]) + measured = self.con.execute("SELECT total_tokens,input_tokens,output_tokens,cache_write_5m_tokens " + "FROM responses WHERE response_id='claude:id'").fetchone() + self.assertEqual(tuple(measured), (None, None, 5, None) if remove_complete else (15, 10, 5, None)) + self.assertIn("Evidence complete: " + ("no" if remove_complete else "yes"), self.draft()["body"]) + + def test_remove_complete_copy_imported_first(self): + self.check_removed_claude_final(True, True) + + def test_remove_complete_copy_imported_second(self): + self.check_removed_claude_final(True, False) + + def test_remove_competing_cache_split_imported_first(self): + self.check_removed_claude_final(False, False) + + def test_remove_competing_cache_split_imported_second(self): + self.check_removed_claude_final(False, True) From 1782f2a20dcad81a111a58bf34747bc16f115342 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 22:13:32 +0100 Subject: [PATCH 38/44] wip: retire unsupported ledger fields and require current legacy event receipts --- agent_observer/adapters/claude.py | 61 ++++++++++++++++++++++--------- agent_observer/native_response.py | 21 ++++++++++- tests/test_evidence_coverage.py | 48 ++++++++++++++++++++++++ 3 files changed, 111 insertions(+), 19 deletions(-) diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index 61c2aa9..78d6ecd 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -106,7 +106,9 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 16 # Rebuild measurements from surviving finals after a source withdrawal. +_IMPORT_VERSION = 17 # Recheck every priced field and the source of each legacy trace event. +_FINAL_FIELDS = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", + "reasoning_output_tokens", "total_tokens", "cache_write_5m_tokens", "cache_write_1h_tokens", "model") def _ensure_native_kinds(con) -> None: @@ -336,6 +338,9 @@ def event(self, family, native_id, ordinal, ts, **kw): checkout_events=self.checkout_events if self.first_new_ordinal is not None and ordinal >= self.first_new_ordinal else None, **kw) + self.con.execute("INSERT OR IGNORE INTO claude_event_observations(source_id,event_id,turn_id) " + "SELECT ?,id,? FROM events WHERE session_key=? AND family=? AND native_id=?", + (self.src.source_id, self.turn or "", self.session_key, family, native_id)) if family in {"tool_call", "assistant_message"}: self.message_events.append((family, native_id)) @@ -699,25 +704,47 @@ def _reproject_withdrawn_finals(r): con.execute("DELETE FROM claude_withdrawn_finals WHERE session_key=? AND response_id=?", (key, rid)) +def _unsupported_projections(con, scope, args): + """Older projections may contain individual fields supplied only by a removed source.""" + gaps = [] + retained = db._has_table(con, "claude_retained_final_fields") + for field in _FINAL_FIELDS: + gap = (f"r.{field} IS NOT NULL AND NOT EXISTS (SELECT 1 FROM claude_final_observations o " + "WHERE o.session_key=r.session_key AND o.response_id=r.response_id " + f"AND json_extract(o.payload,'$.{field}') IS NOT NULL)") + if retained: + gap += (" AND NOT EXISTS (SELECT 1 FROM claude_retained_final_fields f WHERE f.session_key=r.session_key " + f"AND f.response_id=r.response_id AND f.field='{field}' AND f.value=r.{field})") + gaps.append("(" + gap + ")") + gaps.append("NOT EXISTS (SELECT 1 FROM claude_final_observations o WHERE o.session_key=r.session_key " + "AND o.response_id=r.response_id AND o.source_id=r.source_id)") + return con.execute("SELECT r.session_key,r.response_id FROM responses r WHERE r.harness='claude' AND " + scope + + " AND EXISTS (SELECT 1 FROM claude_final_observations o WHERE o.session_key=r.session_key " + "AND o.response_id=r.response_id) AND (" + " OR ".join(gaps) + ")", args) + + def conflicting_final_measurements(con, session_key): """A task can bill a final row only when its source measurements agree.""" if not db._has_table(con, "claude_final_observations"): return set() - fields = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", - "reasoning_output_tokens", "total_tokens", "cache_write_5m_tokens", "cache_write_1h_tokens") mismatch = ["json_extract(o.payload,'$.model') IS NOT r.model"] - for name in fields: + for name in _FINAL_FIELDS: + if name == "model": + continue value = f"json_extract(o.payload,'$.{name}')" mismatch.append(f"({value} IS NOT NULL AND {value} IS NOT r.{name})") conflicts = {rid for rid, in con.execute( "SELECT DISTINCT o.response_id FROM claude_final_observations o JOIN responses r USING(session_key,response_id) " "WHERE o.session_key=? AND (" + " OR ".join(mismatch) + ")", (session_key,))} if db._has_table(con, "claude_retained_final_fields"): - column = "CASE p.field " + " ".join(f"WHEN '{name}' THEN r.{name}" for name in (*fields, "model")) + " END" + column = "CASE p.field " + " ".join(f"WHEN '{name}' THEN r.{name}" for name in _FINAL_FIELDS) + " END" conflicts.update(rid for rid, in con.execute( "SELECT DISTINCT p.response_id FROM claude_retained_final_fields p " "JOIN responses r USING(session_key,response_id) WHERE p.session_key=? AND p.value IS NOT " + column, (session_key,))) + conflicts.update(rid for _, rid in _unsupported_projections( + con, "r.session_key=? AND r.source_id IN (SELECT id FROM sources WHERE claude_usage_version BETWEEN 11 AND 16)", + (session_key,))) if db._has_table(con, "claude_withdrawn_finals"): conflicts.update(rid for rid, in con.execute( "SELECT response_id FROM claude_withdrawn_finals WHERE session_key=?", (session_key,))) @@ -1331,18 +1358,17 @@ def _prepare_ancestry(r): uuid TEXT NOT NULL, parent TEXT NOT NULL, link_status TEXT NOT NULL, turn_id TEXT, ordinal_num INTEGER NOT NULL, ts REAL, PRIMARY KEY(session_key,response_id,source_id,ordinal_num)) WITHOUT ROWID""") r.con.execute("CREATE INDEX IF NOT EXISTS claude_block_source ON claude_final_blocks(source_id)") - if not db._has_table(r.con, "claude_withdrawn_finals"): - r.con.execute("""CREATE TABLE claude_withdrawn_finals ( - session_key TEXT NOT NULL,response_id TEXT NOT NULL, PRIMARY KEY(session_key,response_id)) WITHOUT ROWID""") - # A pre-version-16 ledger could already have removed a source while - # retaining its total or its location in the materialized response. - r.con.execute("""INSERT INTO claude_withdrawn_finals SELECT r.session_key,r.response_id FROM responses r - WHERE r.harness='claude' AND EXISTS (SELECT 1 FROM claude_final_observations o - WHERE o.session_key=r.session_key AND o.response_id=r.response_id) - AND (NOT EXISTS (SELECT 1 FROM claude_final_observations o WHERE o.session_key=r.session_key - AND o.response_id=r.response_id AND o.source_id=r.source_id) OR (r.total_tokens IS NOT NULL - AND NOT EXISTS (SELECT 1 FROM claude_final_observations o WHERE o.session_key=r.session_key - AND o.response_id=r.response_id AND json_extract(o.payload,'$.total_tokens') IS NOT NULL)))""") + r.con.execute("""CREATE TABLE IF NOT EXISTS claude_withdrawn_finals ( + session_key TEXT NOT NULL,response_id TEXT NOT NULL, PRIMARY KEY(session_key,response_id)) WITHOUT ROWID""") + r.con.execute("""CREATE TABLE IF NOT EXISTS claude_event_observations ( + source_id INTEGER NOT NULL REFERENCES sources(id),event_id INTEGER NOT NULL REFERENCES events(id) ON DELETE CASCADE, + turn_id TEXT NOT NULL, PRIMARY KEY(event_id,source_id,turn_id)) WITHOUT ROWID""") + r.con.execute("CREATE INDEX IF NOT EXISTS claude_event_observation_source ON claude_event_observations(source_id)") + if r.src.row["claude_usage_version"] and r.src.row["claude_usage_version"] < _IMPORT_VERSION: + stale = _unsupported_projections(r.con, + "(r.source_id=? OR (r.session_key,r.response_id) IN (SELECT session_key,response_id " + "FROM claude_final_observations WHERE source_id=?))", (r.src.source_id, r.src.source_id)) + r.con.executemany("INSERT OR IGNORE INTO claude_withdrawn_finals VALUES(?,?)", stale) if not db._has_table(r.con, "claude_expected_finals"): r.con.execute("""CREATE TABLE claude_expected_finals ( source_id INTEGER NOT NULL REFERENCES sources(id), session_key TEXT NOT NULL, response_id TEXT NOT NULL, @@ -1361,6 +1387,7 @@ def _prepare_ancestry(r): PRIMARY KEY(session_key,source_id)) WITHOUT ROWID""") r.linked_sessions = set() if not r.src.incremental: + r.con.execute("DELETE FROM claude_event_observations WHERE source_id=?", (r.src.source_id,)) r.con.execute("DELETE FROM claude_final_blocks WHERE source_id=?", (r.src.source_id,)) # Keep identities only until the replacement proves it could read # every row. A broken line cannot silently retract a competing copy. diff --git a/agent_observer/native_response.py b/agent_observer/native_response.py index 7b5900b..6740b4e 100644 --- a/agent_observer/native_response.py +++ b/agent_observer/native_response.py @@ -109,9 +109,19 @@ def event_responses(con, session_key): "WHERE session_key=?", (session_key,)): measured_sources[rid].add(source) claude = session_key.startswith("claude:") + current_events = defaultdict(set) + indexed_sources = set() if claude: from .adapters.claude import legacy_capture_sources legacy_sources = legacy_capture_sources(con, session_key) + if db._has_table(con, "claude_event_observations"): + indexed_sources.update(s for s, in con.execute( + "SELECT DISTINCT e.source_id FROM events e JOIN sources s ON e.source_id=s.id " + "WHERE e.session_key=? AND s.claude_usage_version>=17", (session_key,))) + for event, source, turn in con.execute( + "SELECT o.event_id,o.source_id,o.turn_id FROM claude_event_observations o " + "JOIN events e ON e.id=o.event_id WHERE e.session_key=?", (session_key,)): + current_events[event].add((source, turn or None)) legacy_text = defaultdict(set) if claude and db._has_table(con, "claude_response_ancestry"): # Pre-event-edge ledgers still retain the UUID of each text block. @@ -122,8 +132,15 @@ def event_responses(con, session_key): legacy_text[source, uuid].add(rid) for event, source, family, native_id, turn in con.execute( "SELECT id,source_id,family,native_id,turn_id FROM events WHERE session_key=?", (session_key,)): - if claude and source not in legacy_sources: - turn = None # An event without a literal edge cannot inherit its display turn. + if claude: + observations = current_events.get(event, set()) + if source in indexed_sources and not observations and not edges[family, native_id]: + yield event, None, None # No current source contains this archived event. + continue + locations = {t if s in legacy_sources else None for s, t in observations} + if source not in indexed_sources: + locations.add(turn if source in legacy_sources else None) + turn = next(iter(locations)) if len(locations) == 1 else None if claude and family == "assistant_message": yield event, turn, edges[family, native_id] | legacy_text[source, native_id.rpartition(":")[0]] elif claude and family in {"tool_result", "permission", "skill_invoke", "file_change"}: diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py index cb1debc..ec0d0ab 100644 --- a/tests/test_evidence_coverage.py +++ b/tests/test_evidence_coverage.py @@ -875,3 +875,51 @@ def test_remove_competing_cache_split_imported_first(self): def test_remove_competing_cache_split_imported_second(self): self.check_removed_claude_final(False, True) + + def test_upgrade_retires_cache_split_with_live_original_total(self): + a = Path(self.tmp.name, "aggregate.jsonl") + b = Path(self.tmp.name, "split.jsonl") + user = claude_user("p") + msg = claude_response("reply", "p", "id") + usage = dict(input_tokens=10, output_tokens=5, cache_read_input_tokens=0, cache_creation_input_tokens=100000) + msg["message"].update(model="claude-haiku-4-5", usage=usage) + write_records(a, [user, msg]) + claude.import_claude_file(self.con, str(a)) + self.assign("A", "claude:p") + del usage["input_tokens"] + usage["cache_creation"] = {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 100000} + write_records(b, [user, msg]) + claude.import_claude_file(self.con, str(b)) + priced = report.task_report(self.con, "A")["total_cost"]["usd"] + self.assertAlmostEqual(priced, .200035) + write_records(b, [user]) + claude.import_claude_file(self.con, str(b)) + # Version 15 lost the supporting copy but left its TTL fields and + # the original source id on the materialized response. + self.con.execute("UPDATE responses SET cache_write_5m_tokens=0,cache_write_1h_tokens=100000") + self.con.execute("UPDATE sources SET claude_usage_version=15") + for source in (a, b): + claude.import_claude_file(self.con, str(source)) + rep = report.task_report(self.con, "A") + self.assertEqual(rep["attributed"]["total_tokens"], 100015) + self.assertIsNone(rep["total_cost"]["usd"]) + self.assertIn("Estimated cost unknown", self.draft()["body"]) + + def test_legacy_trace_uses_events_present_in_surviving_copies(self): + user = claude_user("p") + msg = claude_response("reply", "p", "id") + del msg["parentUuid"] + a = Path(self.tmp.name, "first.jsonl") + b = Path(self.tmp.name, "second.jsonl") + for path, call in ((a, "retired-call"), (b, "surviving-call")): + msg["message"]["content"] = [{"type": "tool_use", "id": call, "name": "Read"}] + write_records(path, [user, msg]) + claude.import_claude_file(self.con, str(path)) + self.assign("A", "claude:p") + msg["uuid"] = "new-reply" + msg["message"].update(id="independent", content=[{"type":"tool_use", "id":"independent-call", "name":"Read"}]) + write_records(a, [user, msg]) + claude.import_claude_file(self.con, str(a)) + for turn in (None, "claude:p"): + self.assertEqual({e["native_id"] for e in report.timeline(self.con, "A", turn_id=turn)["events"]}, + {"independent-call", "surviving-call"}) From 926e01bdef7f5c5a5dcb0388680dad29fd725d11 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 22:27:37 +0100 Subject: [PATCH 39/44] wip: reconcile Codex atomic turn and measurement witnesses per source --- agent_observer/adapters/claude.py | 21 +++- agent_observer/adapters/codex.py | 40 +++++-- agent_observer/adapters/codex_atomic.py | 153 ++++++++++++++++++++++++ agent_observer/outcome.py | 9 ++ tests/test_codex_atomic.py | 89 ++++++++++++++ tests/test_evidence_coverage.py | 20 ++++ 6 files changed, 315 insertions(+), 17 deletions(-) create mode 100644 agent_observer/adapters/codex_atomic.py create mode 100644 tests/test_codex_atomic.py diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index 78d6ecd..6358baa 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -106,7 +106,7 @@ def _valid_counter(value) -> bool: _FINALITY_TABLE = "claude_response_finality" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 17 # Recheck every priced field and the source of each legacy trace event. +_IMPORT_VERSION = 18 # Resume historical capture at the last prompt in this source. _FINAL_FIELDS = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", "reasoning_output_tokens", "total_tokens", "cache_write_5m_tokens", "cache_write_1h_tokens", "model") @@ -416,10 +416,8 @@ def import_claude_file(con: sqlite3.Connection, path: str, except sqlite3.DatabaseError: pass if src.incremental and src.row["session_id"]: - # Resume the turn the previous import ended in. - row = con.execute( - "SELECT turn_id FROM user_messages WHERE session_key=? AND kind='genuine'" - " ORDER BY ts DESC LIMIT 1", (r.session_key,)).fetchone() + row = con.execute("SELECT turn_id FROM claude_source_turns WHERE source_id=?", + (src.source_id,)).fetchone() r.turn = row["turn_id"] if row else None unreadable = False for ordinal, obj, line in src.records(): @@ -509,6 +507,13 @@ def import_claude_file(con: sqlite3.Connection, path: str, AND o.response_id=p.response_id AND o.source_id=p.source_id AND json_extract(o.payload,'$.'||p.field) IS NOT NULL))""", (src.source_id,)) _reproject_withdrawn_finals(r) + if not src.incremental and not unreadable: + for rid, turn in con.execute("""SELECT response_id,MIN(turn_id) FROM claude_final_blocks + WHERE source_id=? AND link_status='absent' GROUP BY response_id + HAVING COUNT(DISTINCT COALESCE(turn_id,''))=1""", (src.source_id,)): + con.execute("UPDATE responses SET turn_id=? WHERE source_id=? AND response_id=? AND turn_id IS NOT ?", + (turn, src.source_id, rid, turn)) + con.execute("INSERT OR REPLACE INTO claude_source_turns VALUES(?,?)", (src.source_id, r.turn)) con.executemany("INSERT OR IGNORE INTO claude_ancestry_sources VALUES(?,?)", ((key, src.source_id) for key in r.linked_sessions)) if r.native_session: @@ -1364,6 +1369,8 @@ def _prepare_ancestry(r): source_id INTEGER NOT NULL REFERENCES sources(id),event_id INTEGER NOT NULL REFERENCES events(id) ON DELETE CASCADE, turn_id TEXT NOT NULL, PRIMARY KEY(event_id,source_id,turn_id)) WITHOUT ROWID""") r.con.execute("CREATE INDEX IF NOT EXISTS claude_event_observation_source ON claude_event_observations(source_id)") + r.con.execute("""CREATE TABLE IF NOT EXISTS claude_source_turns ( + source_id INTEGER PRIMARY KEY REFERENCES sources(id),turn_id TEXT)""") if r.src.row["claude_usage_version"] and r.src.row["claude_usage_version"] < _IMPORT_VERSION: stale = _unsupported_projections(r.con, "(r.source_id=? OR (r.session_key,r.response_id) IN (SELECT session_key,response_id " @@ -1567,6 +1574,10 @@ def response_witnesses(con, session_key): if (rid, source) not in recorded_blocks: unlocated.add(rid) conflicts = set() + if db._has_table(con, "claude_final_blocks"): + conflicts.update(rid for rid, in con.execute("""SELECT response_id FROM claude_final_blocks + WHERE session_key=? AND link_status='absent' GROUP BY response_id + HAVING COUNT(DISTINCT COALESCE(turn_id,''))>1""", (session_key,))) if db._has_table(con, "claude_invalid_ancestry"): for uuid, response_id in con.execute( "SELECT uuid,response_id FROM claude_invalid_ancestry WHERE session_key=?", (session_key,)): diff --git a/agent_observer/adapters/codex.py b/agent_observer/adapters/codex.py index 81a2e5c..114af82 100644 --- a/agent_observer/adapters/codex.py +++ b/agent_observer/adapters/codex.py @@ -18,6 +18,7 @@ import sqlite3 from .. import db, native_response, placement, privacy +from . import codex_atomic from ..identity import SessionIdentity, skill_from_path from ..ingest import (JsonlSource, MissingNativeId, fingerprint, insert_event, iso_ts, stored_path, text_hash) @@ -61,7 +62,7 @@ def _occurrences_ready(row) -> bool: HARNESS = "codex" -_CONTEXT_VERSION = 7 # Record literal turn witnesses from every atomic occurrence. +_CONTEXT_VERSION = 8 # Keep the literal turn and measurement together across source snapshots. SEMANTICS = "codex:input_includes_cached,output_includes_reasoning" # Older rollouts carry usage only in token_count events: last_token_usage per # response and a cumulative total that repeats when nothing new happened. @@ -816,7 +817,11 @@ def import_codex_file(con: sqlite3.Connection, path: str, "session_key": session_key, }) return stats + if src.incremental and db._has_table(con, "codex_incomplete_sources") and con.execute( + "SELECT 1 FROM codex_incomplete_sources WHERE source_id=?", (src.source_id,)).fetchone(): + src.start_offset = src.end_offset = 0 reader = _Reader(con, src, stats) + codex_atomic.prepare(reader) native_response.prepare(con, src.source_id, replace=not src.incremental) _ensure_cumulative_table(con) own = _first_meta(path) @@ -888,6 +893,7 @@ def import_codex_file(con: sqlite3.Connection, path: str, for ordinal, obj, line in src.records(): stats["lines"] += 1 if obj is None or not isinstance(obj, dict): + reader.unreadable_atomic = True stats["malformed"] += 1 src.error(ordinal, "malformed_json" if obj is None else "unknown_record", @@ -912,10 +918,18 @@ def import_codex_file(con: sqlite3.Connection, path: str, src.error(ordinal, "missing_id", line) continue except _UnsupportedSchema: + if (not isinstance(obj.get("type"), str) or + isinstance(obj.get("payload"), dict) and "response_id" in obj["payload"]): + reader.unreadable_atomic = True stats["malformed"] += 1 src.error(ordinal, "unsupported_schema", line) continue except (KeyError, TypeError, ValueError, AttributeError): + if obj.get("type") == "token_usage_record": + if isinstance(obj.get("payload"), dict): + codex_atomic.observe(reader, obj, None) + else: + reader.unreadable_atomic = True stats["malformed"] += 1 src.error(ordinal, "schema_error", line) continue @@ -923,6 +937,7 @@ def import_codex_file(con: sqlite3.Connection, path: str, if ts is not None: reader.first_ts = ts if reader.first_ts is None else min(reader.first_ts, ts) reader.last_ts = ts if reader.last_ts is None else max(reader.last_ts, ts) + codex_atomic.finish(reader) _flush_token_counts(reader) _resolve_legacy_user_messages(reader) if not src.privacy_stale: @@ -1599,14 +1614,23 @@ def _ingest_usage(r: _Reader, obj: dict) -> None: u_raw = p.get("usage") tt_raw = p.get("turn_token_usage") th_raw = p.get("thread_token_usage") - _validate_bucket(u_raw) - _validate_bucket(tt_raw) - _validate_bucket(th_raw) + try: + for bucket in (u_raw, tt_raw, th_raw): + _validate_bucket(bucket) + if bucket and any(v is not None and not 0 <= v < 2**63 + for v in (bucket.get(k) for k in _CODEX_BUCKET_KEYS)): + raise _MalformedUsage("invalid atomic counter") + except _MalformedUsage: + codex_atomic.observe(r, obj, None) + raise u = u_raw if isinstance(u_raw, dict) else {} tt = tt_raw if isinstance(tt_raw, dict) else {} th = th_raw if isinstance(th_raw, dict) else {} rid = f"{HARNESS}:{p['response_id']}" turn_id = f"{HARNESS}:{p['turn_id']}" if p.get("turn_id") else None + want = {k: u.get(k) for k in _CODEX_BUCKET_KEYS} + want.update(turn_total_tokens=tt.get("total_tokens"), thread_total_tokens=th.get("total_tokens")) + codex_atomic.observe(r, obj, want) cur = r.con.execute( "INSERT OR IGNORE INTO responses(response_id, source_id, harness," " session_key, thread_id, turn_id, root_turn_id, session_id," @@ -1631,14 +1655,6 @@ def _ingest_usage(r: _Reader, obj: dict) -> None: " total_tokens, turn_total_tokens, thread_total_tokens" " FROM responses WHERE response_id=?", (rid,)).fetchone() seen = dict(existing) if existing is not None else {} - want = {"input_tokens": u.get("input_tokens"), - "cached_input_tokens": u.get("cached_input_tokens"), - "cache_write_input_tokens": u.get("cache_write_input_tokens"), - "output_tokens": u.get("output_tokens"), - "reasoning_output_tokens": u.get("reasoning_output_tokens"), - "total_tokens": u.get("total_tokens"), - "turn_total_tokens": tt.get("total_tokens"), - "thread_total_tokens": th.get("total_tokens")} if seen != want: raise _UsageConflict("usage conflict") _migrate_response_position(r, rid, r.record_position) diff --git a/agent_observer/adapters/codex_atomic.py b/agent_observer/adapters/codex_atomic.py new file mode 100644 index 0000000..d97e07c --- /dev/null +++ b/agent_observer/adapters/codex_atomic.py @@ -0,0 +1,153 @@ +"""Source observations for task attribution of Codex token_usage_record atoms.""" + +import json +from collections import defaultdict + +from .. import db, native_response +from ..ingest import iso_ts + + +FIELDS = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", + "reasoning_output_tokens", "total_tokens", "turn_total_tokens", "thread_total_tokens", "model") + + +def prepare(r): + con = r.con + con.execute("""CREATE TABLE IF NOT EXISTS codex_atomic_observations ( + source_id INTEGER NOT NULL REFERENCES sources(id), session_key TEXT NOT NULL, response_id TEXT NOT NULL, + input_id TEXT NOT NULL, measurement TEXT NOT NULL, position INTEGER NOT NULL, ts REAL, effort TEXT, + thread_id TEXT, root_turn_id TEXT, session_id TEXT, + PRIMARY KEY(source_id,session_key,response_id,input_id,measurement)) WITHOUT ROWID""") + con.execute("CREATE INDEX IF NOT EXISTS codex_atomic_response ON codex_atomic_observations(response_id,session_key)") + con.execute("CREATE INDEX IF NOT EXISTS codex_atomic_session ON codex_atomic_observations(session_key,response_id)") + con.execute("""CREATE TABLE IF NOT EXISTS codex_incomplete_sources ( + source_id INTEGER PRIMARY KEY REFERENCES sources(id),session_key TEXT NOT NULL,legacy_dispute INTEGER NOT NULL)""") + r.atomic_ids = set() + r.unreadable_atomic = False + if not r.src.incremental: + con.execute("CREATE TEMP TABLE prior_codex_atoms AS SELECT * FROM codex_atomic_observations WHERE source_id=?", + (r.src.source_id,)) + # A previous parser recorded the literal turn only after its counters + # passed validation. On a damaged upgrade that turn is negative evidence. + if r.src.row["codex_context_version"] == 7 and db._has_table(con, "native_response_inputs"): + con.execute("""INSERT INTO prior_codex_atoms SELECT source_id,session_key,response_id,input_id,'',-1,NULL,NULL,NULL,NULL,NULL + FROM native_response_inputs WHERE source_id=?""", (r.src.source_id,)) + con.execute("DELETE FROM codex_atomic_observations WHERE source_id=?", (r.src.source_id,)) + + +def observe(r, obj, counters): + p = obj["payload"] + mid = native_response.identifier(p.get("response_id")) + if not mid: + r.unreadable_atomic = True + return + rid = "codex:" + mid + turn = native_response.identifier(p.get("turn_id")) or "" + if not (r.thread_id or r.session_id) or p.get("thread_id") not in (None, r.thread_id): + counters = None + payload = json.dumps(dict(counters, model=r.model), sort_keys=True) if counters is not None else "" + r.atomic_ids.add(rid) + r.con.execute("INSERT OR IGNORE INTO codex_atomic_observations VALUES(?,?,?,?,?,?,?,?,?,?,?)", + (r.src.source_id, r.session_key, rid, turn, payload, r.record_position, + iso_ts(obj.get("timestamp")), r.effort, + *(native_response.identifier(p.get(k)) for k in ("thread_id", "root_turn_id", "session_id")))) + + +def finish(r): + con, src = r.con, r.src + incomplete = r.unreadable_atomic or src.incomplete_record or src.end_offset < src.size + if incomplete: + legacy = (src.row["codex_context_version"] == 7 and con.execute( + "SELECT 1 FROM import_errors WHERE harness='codex' AND source_path=? AND error='usage_conflict' LIMIT 1", + (src.path,)).fetchone() is not None) + con.execute("INSERT INTO codex_incomplete_sources VALUES(?,?,?) ON CONFLICT(source_id) DO UPDATE SET " + "legacy_dispute=MAX(legacy_dispute,excluded.legacy_dispute)", (src.source_id, r.session_key, legacy)) + elif not src.incremental: + con.execute("DELETE FROM codex_incomplete_sources WHERE source_id=?", (src.source_id,)) + if not src.incremental: + r.atomic_ids.update(rid for rid, in con.execute("SELECT DISTINCT response_id FROM prior_codex_atoms")) + if incomplete: + con.execute("INSERT OR IGNORE INTO codex_atomic_observations SELECT * FROM prior_codex_atoms") + con.execute("DROP TABLE temp.prior_codex_atoms") + for rid in r.atomic_ids: + _reconcile(con, rid, src.source_id) + + +def _reconcile(con, rid, refreshing): + copies = con.execute("""SELECT o.*,i.source_id AS incomplete FROM codex_atomic_observations o + JOIN sources s ON s.id=o.source_id LEFT JOIN codex_incomplete_sources i ON i.source_id=o.source_id + WHERE o.response_id=? ORDER BY s.path,o.position""", (rid,)).fetchall() + signatures = {(o["session_key"], o["input_id"], o["measurement"]) for o in copies} + if len(signatures) != 1 or not copies[0]["measurement"] or any(o["incomplete"] for o in copies): + return + first = copies[0] + row = con.execute("SELECT r.*,s.codex_context_version AS version FROM responses r JOIN sources s " + "ON s.id=r.source_id WHERE r.response_id=?", (rid,)).fetchone() + if row is None or row["session_key"] != first["session_key"]: + return + source = next((o for o in copies if o["source_id"] == row["source_id"]), first) + if source["source_id"] != row["source_id"] and row["source_id"] != refreshing and (row["version"] or 0) < 8: + return # The original pre-upgrade source has not been replayed. + measured = json.loads(source["measurement"]) + turn = "codex:" + source["input_id"] if source["input_id"] else None + if (row["source_id"] != source["source_id"] or row["turn_id"] != turn or + any(row[k] != measured[k] for k in FIELDS)): + con.execute("UPDATE responses SET " + ",".join(f"{k}=?" for k in FIELDS) + + ",source_id=?,turn_id=?,ordinal_num=?,ts=?,effort=?,thread_id=?,root_turn_id=?,session_id=? " + "WHERE response_id=?", + (*(measured[k] for k in FIELDS), source["source_id"], turn, + source["position"], source["ts"], source["effort"], source["thread_id"], + source["root_turn_id"], source["session_id"], rid)) + if source["input_id"]: + for o in copies: + native_response.record(con, o["source_id"], o["session_key"], rid, o["input_id"]) + + +def disputes(con, session_key, semantics): + """Only current agreeing source measurements can support positive ownership.""" + if "codex_context_version" not in {c[1] for c in con.execute("PRAGMA table_info(sources)")}: + return {}, False, {} + legacy = con.execute("""SELECT 1 FROM sources s JOIN import_errors e ON e.source_path=s.path + WHERE s.harness='codex' AND e.harness='codex' AND e.error='usage_conflict' AND s.codex_context_version=7 + AND 'codex:'||COALESCE(s.thread_id,s.session_id)=? LIMIT 1""", (session_key,)).fetchone() is not None + historical = {} + if legacy: + historical = {rid: set() for rid, in con.execute("SELECT response_id FROM responses WHERE session_key=? " + "AND semantics=?", (session_key, semantics))} + if not db._has_table(con, "codex_atomic_observations"): + return historical, legacy, {} + groups = defaultdict(list) + columns = ",".join("r." + k for k in FIELDS) + for o in con.execute("SELECT o.*,r.source_id AS measured_source,r.turn_id AS measured_turn," + columns + """ + FROM codex_atomic_observations o + LEFT JOIN responses r ON r.response_id=o.response_id WHERE o.session_key=? OR o.response_id IN ( + SELECT response_id FROM responses WHERE session_key=? AND semantics=?)""", + (session_key, session_key, semantics)): + groups[o["response_id"]].append(o) + conflicts = historical + partial = {} + for rid, copies in groups.items(): + variants = {(o["session_key"], o["input_id"], o["measurement"]) for o in copies} + if (len(variants) > 1 or not copies[0]["measurement"] or + copies[0]["measured_source"] not in {o["source_id"] for o in copies}): + conflicts[rid] = {o["input_id"] for o in copies if o["input_id"]} + else: + values = json.loads(copies[0]["measurement"]) + turn = copies[0]["input_id"] + inputs = {turn} if turn else set() + if (copies[0]["measured_turn"] != ("codex:" + turn if turn else None) + or any(values[k] != copies[0][k] for k in FIELDS)): + conflicts[rid] = inputs + elif any(values[k] is None for k in ("input_tokens", "output_tokens", "total_tokens")): + partial[rid] = inputs + for rid, in con.execute("""SELECT r.response_id FROM responses r JOIN sources s ON s.id=r.source_id + WHERE r.session_key=? AND r.semantics=? AND s.codex_context_version>=8 AND NOT EXISTS ( + SELECT 1 FROM codex_atomic_observations o WHERE o.response_id=r.response_id AND o.session_key=r.session_key)""", + (session_key, semantics)): + conflicts[rid] = set() + incomplete, unidentified = con.execute("SELECT COUNT(*),MAX(legacy_dispute) FROM codex_incomplete_sources " + "WHERE session_key=?", (session_key,)).fetchone() + if unidentified: + for rid, copies in groups.items(): + conflicts[rid] = {o["input_id"] for o in copies if o["input_id"]} + return conflicts, bool(incomplete or legacy), partial diff --git a/agent_observer/outcome.py b/agent_observer/outcome.py index 0a4eaa2..c976706 100644 --- a/agent_observer/outcome.py +++ b/agent_observer/outcome.py @@ -183,6 +183,15 @@ def _session_ownership(con, key, task_id, by_run, reference_conflict, result, me responses, call_witnesses, disputed_completions = grok.response_witnesses(con, key) else: responses = native_response.inputs(con, key) + if harness == "codex": + from .adapters import codex, codex_atomic + conflicts, incomplete, unavailable = codex_atomic.disputes(con, key, codex.SEMANTICS) + disputed_completions.update(conflicts) + result.conflicts.update(conflicts) + for rid, turns in conflicts.items(): + responses.setdefault(rid, set()).update(turns) + if incomplete: + result.unlocated_usage_sessions.add(key) # In a contested whole session, only events on resolved turns can be # shown. Untagged events cannot be separated between the claimants. exclusive = not by_run or (whole == {task_id} and set(by_run.values()) == {task_id}) diff --git a/tests/test_codex_atomic.py b/tests/test_codex_atomic.py new file mode 100644 index 0000000..309f621 --- /dev/null +++ b/tests/test_codex_atomic.py @@ -0,0 +1,89 @@ +"""Task accounting for separate copies of a Codex atomic response.""" + +from contextlib import closing +import json +from pathlib import Path +import sqlite3 + +from agent_observer import report +from agent_observer.adapters import codex, t3_purpose +from tests.helpers import LedgerCase, fixture +from tests.test_native_response import write_records + + +class CodexAtomicTest(LedgerCase): + def setUp(self): + super().setUp() + rows = [json.loads(s) for s in Path(fixture("codex-mini.jsonl")).read_text().splitlines()] + self.meta = rows[0] + self.context = next(r for r in rows if r["type"] == "turn_context") + self.atom = next(r for r in rows if r["type"] == "token_usage_record") + self.key = "codex:sess-fixture-mini-01" + with closing(sqlite3.connect(":memory:")) as src: + t3_purpose.refresh(self.con, src, set()) + for task in ("A", "B"): + self.con.execute("INSERT INTO tasks(task_id,created_at) VALUES(?,0)", (task,)) + self.con.execute("INSERT INTO t3_purpose_runs(run_id,thread_id,task_id,scope) VALUES(?,'planner',?,'single')", + (task, task)) + self.con.execute("INSERT INTO t3_purpose_sessions VALUES(?,?)", (task, self.key)) + self.con.execute("INSERT INTO t3_purpose_inputs(run_id,session_key,native_id,kind,validation) " + "VALUES(?,?,?,'turn','codex_turn_started')", (task, self.key, task)) + + def source(self, name, turn, total, *, torn=False): + path = Path(self.tmp.name, name + ".jsonl") + self.context["payload"].update(turn_id=turn, model="gpt-5-mini") + self.atom["payload"].update(turn_id=turn, root_turn_id=turn) + output = total - 1000 if isinstance(total, int) else total + self.atom["payload"]["usage"].update(total_tokens=total, output_tokens=output) + write_records(path, [self.meta, self.context]) + with path.open("a") as fh: + line = json.dumps(self.atom) + fh.write(line[:24] if torn else line + "\n") + codex.import_codex_file(self.con, str(path)) + return path + + def check_owners(self, a, b): + for task, expected in (("A", a), ("B", b)): + rep = report.task_report(self.con, task) + self.assertEqual(rep["attributed"]["responses"], int(expected is not None), task) + if expected is None: + self.assertIsNone(rep["total_cost"]["usd"], task) + self.assertFalse(rep["total_cost"]["estimate"]["priced_responses"], task) + else: + self.assertEqual(rep["attributed"]["total_tokens"], expected, task) + + def test_torn_and_invalid_copy_cannot_withdraw_a_competing_turn(self): + self.source("first", "A", 1100) + self.source("second", "B", 1100) + self.check_owners(None, None) + for _ in range(2): + self.source("second", "B", 1100, torn=True) + self.check_owners(None, None) + self.source("second", "B", "bad") + self.check_owners(None, None) + self.source("second", "A", 1100) + self.check_owners(1100, None) + + def check_conflict(self, reverse): + copies = [("first", "A", 1100), ("second", "B", 91100)] + for args in (reversed(copies) if reverse else copies): + self.source(*args) + self.check_owners(None, None) + # Correct the first source to the second. Its prior winner must not + # decide who receives the independently corroborated response. + self.source("first", "B", 91100) + self.check_owners(None, 91100) + + def test_low_count_copy_first(self): + self.check_conflict(False) + + def test_high_count_copy_first(self): + self.check_conflict(True) + + def test_readable_removal_can_restore_other_sources_turn_and_counters(self): + first = self.source("first", "A", 1100) + self.source("second", "B", 91100) + self.check_owners(None, None) + write_records(first, [self.meta]) + codex.import_codex_file(self.con, str(first)) + self.check_owners(None, 91100) diff --git a/tests/test_evidence_coverage.py b/tests/test_evidence_coverage.py index ec0d0ab..6119818 100644 --- a/tests/test_evidence_coverage.py +++ b/tests/test_evidence_coverage.py @@ -923,3 +923,23 @@ def test_legacy_trace_uses_events_present_in_surviving_copies(self): for turn in (None, "claude:p"): self.assertEqual({e["native_id"] for e in report.timeline(self.con, "A", turn_id=turn)["events"]}, {"independent-call", "surviving-call"}) + + def test_legacy_append_resumes_the_prompt_in_its_own_source(self): + files = [Path(self.tmp.name, task + ".jsonl") for task in ("A", "B")] + for index, (task, path) in enumerate(zip(("A", "B"), files), 1): + prompt = dict(claude_user(task), timestamp=f"2026-11-25T08:00:0{index}Z") + response = claude_response("reply-" + task, task, "id-" + task) + del response["parentUuid"] + write_records(path, [prompt, response]) + claude.import_claude_file(self.con, str(path)) + self.assign(task, "claude:" + task) + late = claude_response("late", "A", "late") + del late["parentUuid"] + late["message"]["content"] = [{"type":"tool_use", "id":"late-call", "name":"Read"}] + write_records(files[0], [late], mode="a") + claude.import_claude_file(self.con, str(files[0])) + for task in ("A", "B"): + self.assertEqual("claude:late" in report.task_report(self.con, task)["measured"]["attributed_responses"], + task == "A") + self.assertEqual("late-call" in [e["native_id"] for e in report.timeline(self.con, task)["events"]], + task == "A") From d731b98ba18f998d29a731a5663fbedf3d5c4d69 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 22:30:52 +0100 Subject: [PATCH 40/44] wip: preserve Codex incremental append and immutable accounting guarantees --- agent_observer/adapters/codex.py | 4 ++-- agent_observer/adapters/codex_atomic.py | 19 +++++++++++++++---- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/agent_observer/adapters/codex.py b/agent_observer/adapters/codex.py index 114af82..6af0ab9 100644 --- a/agent_observer/adapters/codex.py +++ b/agent_observer/adapters/codex.py @@ -62,7 +62,7 @@ def _occurrences_ready(row) -> bool: HARNESS = "codex" -_CONTEXT_VERSION = 8 # Keep the literal turn and measurement together across source snapshots. +_CONTEXT_VERSION = 9 # Distinguish an unfinished append from an unreadable replacement. SEMANTICS = "codex:input_includes_cached,output_includes_reasoning" # Older rollouts carry usage only in token_count events: last_token_usage per # response and a cumulative total that repeats when nothing new happened. @@ -818,7 +818,7 @@ def import_codex_file(con: sqlite3.Connection, path: str, }) return stats if src.incremental and db._has_table(con, "codex_incomplete_sources") and con.execute( - "SELECT 1 FROM codex_incomplete_sources WHERE source_id=?", (src.source_id,)).fetchone(): + "SELECT 1 FROM codex_incomplete_sources WHERE source_id=? AND replay", (src.source_id,)).fetchone(): src.start_offset = src.end_offset = 0 reader = _Reader(con, src, stats) codex_atomic.prepare(reader) diff --git a/agent_observer/adapters/codex_atomic.py b/agent_observer/adapters/codex_atomic.py index d97e07c..2d783a3 100644 --- a/agent_observer/adapters/codex_atomic.py +++ b/agent_observer/adapters/codex_atomic.py @@ -21,7 +21,10 @@ def prepare(r): con.execute("CREATE INDEX IF NOT EXISTS codex_atomic_response ON codex_atomic_observations(response_id,session_key)") con.execute("CREATE INDEX IF NOT EXISTS codex_atomic_session ON codex_atomic_observations(session_key,response_id)") con.execute("""CREATE TABLE IF NOT EXISTS codex_incomplete_sources ( - source_id INTEGER PRIMARY KEY REFERENCES sources(id),session_key TEXT NOT NULL,legacy_dispute INTEGER NOT NULL)""") + source_id INTEGER PRIMARY KEY REFERENCES sources(id),session_key TEXT NOT NULL,legacy_dispute INTEGER NOT NULL, + replay INTEGER NOT NULL DEFAULT 1)""") + if "replay" not in {c[1] for c in con.execute("PRAGMA table_info(codex_incomplete_sources)")}: + con.execute("ALTER TABLE codex_incomplete_sources ADD COLUMN replay INTEGER NOT NULL DEFAULT 1") r.atomic_ids = set() r.unreadable_atomic = False if not r.src.incremental: @@ -60,9 +63,12 @@ def finish(r): legacy = (src.row["codex_context_version"] == 7 and con.execute( "SELECT 1 FROM import_errors WHERE harness='codex' AND source_path=? AND error='usage_conflict' LIMIT 1", (src.path,)).fetchone() is not None) - con.execute("INSERT INTO codex_incomplete_sources VALUES(?,?,?) ON CONFLICT(source_id) DO UPDATE SET " - "legacy_dispute=MAX(legacy_dispute,excluded.legacy_dispute)", (src.source_id, r.session_key, legacy)) - elif not src.incremental: + replay = r.unreadable_atomic or (not src.incremental and con.execute( + "SELECT 1 FROM prior_codex_atoms LIMIT 1").fetchone() is not None) + con.execute("INSERT INTO codex_incomplete_sources VALUES(?,?,?,?) ON CONFLICT(source_id) DO UPDATE SET " + "legacy_dispute=MAX(legacy_dispute,excluded.legacy_dispute),replay=excluded.replay", + (src.source_id, r.session_key, legacy, replay)) + else: con.execute("DELETE FROM codex_incomplete_sources WHERE source_id=?", (src.source_id,)) if not src.incremental: r.atomic_ids.update(rid for rid, in con.execute("SELECT DISTINCT response_id FROM prior_codex_atoms")) @@ -89,6 +95,11 @@ def _reconcile(con, rid, refreshing): if source["source_id"] != row["source_id"] and row["source_id"] != refreshing and (row["version"] or 0) < 8: return # The original pre-upgrade source has not been replayed. measured = json.loads(source["measurement"]) + if (source["source_id"] == row["source_id"] and len({o["source_id"] for o in copies}) == 1 + and any(row[k] is not None and row[k] != measured[k] for k in FIELDS if k != "model")): + # One rewritten native atom cannot independently revise immutable + # counters. The task view withholds it while the raw ledger keeps it. + return turn = "codex:" + source["input_id"] if source["input_id"] else None if (row["source_id"] != source["source_id"] or row["turn_id"] != turn or any(row[k] != measured[k] for k in FIELDS)): From ac5c5c7f9e0fb5e091f1a5565dca7864ad4d5d13 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 22:37:29 +0100 Subject: [PATCH 41/44] wip: compare native Codex measurements independently of ambient model context --- agent_observer/adapters/codex_atomic.py | 39 ++++++++++++++++--------- tests/test_codex_atomic.py | 25 +++++++++++++++- 2 files changed, 49 insertions(+), 15 deletions(-) diff --git a/agent_observer/adapters/codex_atomic.py b/agent_observer/adapters/codex_atomic.py index 2d783a3..34a1d41 100644 --- a/agent_observer/adapters/codex_atomic.py +++ b/agent_observer/adapters/codex_atomic.py @@ -7,8 +7,18 @@ from ..ingest import iso_ts -FIELDS = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", - "reasoning_output_tokens", "total_tokens", "turn_total_tokens", "thread_total_tokens", "model") +COUNTERS = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", "output_tokens", + "reasoning_output_tokens", "total_tokens", "turn_total_tokens", "thread_total_tokens") + + +def _signature(observation): + # The turn and counters come from the atom. The surrounding model context + # belongs to the source position and may differ for an exact repeat. + measured = observation["measurement"] + if measured: + values = json.loads(measured) + measured = tuple(values[k] for k in COUNTERS) + return observation["session_key"], observation["input_id"], measured def prepare(r): @@ -83,7 +93,7 @@ def _reconcile(con, rid, refreshing): copies = con.execute("""SELECT o.*,i.source_id AS incomplete FROM codex_atomic_observations o JOIN sources s ON s.id=o.source_id LEFT JOIN codex_incomplete_sources i ON i.source_id=o.source_id WHERE o.response_id=? ORDER BY s.path,o.position""", (rid,)).fetchall() - signatures = {(o["session_key"], o["input_id"], o["measurement"]) for o in copies} + signatures = {_signature(o) for o in copies} if len(signatures) != 1 or not copies[0]["measurement"] or any(o["incomplete"] for o in copies): return first = copies[0] @@ -95,19 +105,20 @@ def _reconcile(con, rid, refreshing): if source["source_id"] != row["source_id"] and row["source_id"] != refreshing and (row["version"] or 0) < 8: return # The original pre-upgrade source has not been replayed. measured = json.loads(source["measurement"]) - if (source["source_id"] == row["source_id"] and len({o["source_id"] for o in copies}) == 1 - and any(row[k] is not None and row[k] != measured[k] for k in FIELDS if k != "model")): + same_source = source["source_id"] == row["source_id"] + if (same_source and len({o["source_id"] for o in copies}) == 1 + and any(row[k] is not None and row[k] != measured[k] for k in COUNTERS)): # One rewritten native atom cannot independently revise immutable # counters. The task view withholds it while the raw ledger keeps it. return turn = "codex:" + source["input_id"] if source["input_id"] else None - if (row["source_id"] != source["source_id"] or row["turn_id"] != turn or - any(row[k] != measured[k] for k in FIELDS)): - con.execute("UPDATE responses SET " + ",".join(f"{k}=?" for k in FIELDS) + - ",source_id=?,turn_id=?,ordinal_num=?,ts=?,effort=?,thread_id=?,root_turn_id=?,session_id=? " + if not same_source or row["turn_id"] != turn or any(row[k] != measured[k] for k in COUNTERS): + con.execute("UPDATE responses SET " + ",".join(f"{k}=?" for k in COUNTERS) + + ",source_id=?,turn_id=?,ordinal_num=?,ts=?,model=?,effort=?,thread_id=?,root_turn_id=?,session_id=? " "WHERE response_id=?", - (*(measured[k] for k in FIELDS), source["source_id"], turn, - source["position"], source["ts"], source["effort"], source["thread_id"], + (*(measured[k] for k in COUNTERS), source["source_id"], turn, + source["position"], source["ts"], row["model"] if same_source else measured["model"], + row["effort"] if same_source else source["effort"], source["thread_id"], source["root_turn_id"], source["session_id"], rid)) if source["input_id"]: for o in copies: @@ -128,7 +139,7 @@ def disputes(con, session_key, semantics): if not db._has_table(con, "codex_atomic_observations"): return historical, legacy, {} groups = defaultdict(list) - columns = ",".join("r." + k for k in FIELDS) + columns = ",".join("r." + k for k in COUNTERS) for o in con.execute("SELECT o.*,r.source_id AS measured_source,r.turn_id AS measured_turn," + columns + """ FROM codex_atomic_observations o LEFT JOIN responses r ON r.response_id=o.response_id WHERE o.session_key=? OR o.response_id IN ( @@ -138,7 +149,7 @@ def disputes(con, session_key, semantics): conflicts = historical partial = {} for rid, copies in groups.items(): - variants = {(o["session_key"], o["input_id"], o["measurement"]) for o in copies} + variants = {_signature(o) for o in copies} if (len(variants) > 1 or not copies[0]["measurement"] or copies[0]["measured_source"] not in {o["source_id"] for o in copies}): conflicts[rid] = {o["input_id"] for o in copies if o["input_id"]} @@ -147,7 +158,7 @@ def disputes(con, session_key, semantics): turn = copies[0]["input_id"] inputs = {turn} if turn else set() if (copies[0]["measured_turn"] != ("codex:" + turn if turn else None) - or any(values[k] != copies[0][k] for k in FIELDS)): + or any(values[k] != copies[0][k] for k in COUNTERS)): conflicts[rid] = inputs elif any(values[k] is None for k in ("input_tokens", "output_tokens", "total_tokens")): partial[rid] = inputs diff --git a/tests/test_codex_atomic.py b/tests/test_codex_atomic.py index 309f621..6cfc7db 100644 --- a/tests/test_codex_atomic.py +++ b/tests/test_codex_atomic.py @@ -31,7 +31,7 @@ def setUp(self): def source(self, name, turn, total, *, torn=False): path = Path(self.tmp.name, name + ".jsonl") - self.context["payload"].update(turn_id=turn, model="gpt-5-mini") + self.context["payload"].update(turn_id=turn, model="gpt-5.6-luna") self.atom["payload"].update(turn_id=turn, root_turn_id=turn) output = total - 1000 if isinstance(total, int) else total self.atom["payload"]["usage"].update(total_tokens=total, output_tokens=output) @@ -87,3 +87,26 @@ def test_readable_removal_can_restore_other_sources_turn_and_counters(self): write_records(first, [self.meta]) codex.import_codex_file(self.con, str(first)) self.check_owners(None, 91100) + + def check_repeat_context(self, append): + first = self.source("first", "A", 1100) + original = report.task_report(self.con, "A")["total_cost"]["estimate"]["estimated_cost_usd_partial"] + self.assertGreater(original, 0) + if append: + copy = first + self.context["payload"]["model"] = "gpt-6-astra" + write_records(first, [self.context, self.atom], mode="a") + else: + copy = first.with_name("no-model.jsonl") + write_records(copy, [self.meta, self.atom]) + for full in (False, True): + codex.import_codex_file(self.con, str(copy), full=full) + self.check_owners(1100, None) + estimate = report.task_report(self.con, "A")["total_cost"]["estimate"] + self.assertEqual(estimate["estimated_cost_usd_partial"], original) + + def test_repeated_atom_after_model_switch_keeps_its_original_charge(self): + self.check_repeat_context(True) + + def test_contextless_duplicate_keeps_its_original_charge(self): + self.check_repeat_context(False) From d4ecc25575467b4fbf24b433fb3542220f62ff0f Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 22:44:22 +0100 Subject: [PATCH 42/44] wip: reconcile observed Codex responses when a partial append finishes --- agent_observer/adapters/codex.py | 2 +- agent_observer/adapters/codex_atomic.py | 7 ++++++- tests/test_codex_atomic.py | 18 ++++++++++++++++++ 3 files changed, 25 insertions(+), 2 deletions(-) diff --git a/agent_observer/adapters/codex.py b/agent_observer/adapters/codex.py index 6af0ab9..a7c03c2 100644 --- a/agent_observer/adapters/codex.py +++ b/agent_observer/adapters/codex.py @@ -62,7 +62,7 @@ def _occurrences_ready(row) -> bool: HARNESS = "codex" -_CONTEXT_VERSION = 9 # Distinguish an unfinished append from an unreadable replacement. +_CONTEXT_VERSION = 10 # Recover atoms deferred while a formerly incomplete source was growing. SEMANTICS = "codex:input_includes_cached,output_includes_reasoning" # Older rollouts carry usage only in token_count events: last_token_usage per # response and a cumulative total that repeats when nothing new happened. diff --git a/agent_observer/adapters/codex_atomic.py b/agent_observer/adapters/codex_atomic.py index 34a1d41..567f34c 100644 --- a/agent_observer/adapters/codex_atomic.py +++ b/agent_observer/adapters/codex_atomic.py @@ -79,7 +79,12 @@ def finish(r): "legacy_dispute=MAX(legacy_dispute,excluded.legacy_dispute),replay=excluded.replay", (src.source_id, r.session_key, legacy, replay)) else: - con.execute("DELETE FROM codex_incomplete_sources WHERE source_id=?", (src.source_id,)) + cleared = con.execute("DELETE FROM codex_incomplete_sources WHERE source_id=?", (src.source_id,)).rowcount + if cleared and src.incremental: + # Another source may have withdrawn a conflicting copy while this + # tail was unfinished. Revisit its stored atoms without rereading the file. + r.atomic_ids.update(rid for rid, in con.execute( + "SELECT DISTINCT response_id FROM codex_atomic_observations WHERE source_id=?", (src.source_id,))) if not src.incremental: r.atomic_ids.update(rid for rid, in con.execute("SELECT DISTINCT response_id FROM prior_codex_atoms")) if incomplete: diff --git a/tests/test_codex_atomic.py b/tests/test_codex_atomic.py index 6cfc7db..0da535e 100644 --- a/tests/test_codex_atomic.py +++ b/tests/test_codex_atomic.py @@ -110,3 +110,21 @@ def test_repeated_atom_after_model_switch_keeps_its_original_charge(self): def test_contextless_duplicate_keeps_its_original_charge(self): self.check_repeat_context(False) + + def test_finishing_unrelated_tail_reconciles_an_earlier_response(self): + retired = self.source("first", "A", 1100) + surviving = self.source("second", "B", 91100) + trailing = json.dumps(self.context) + "\n" + with surviving.open("a") as fh: + fh.write(trailing[:20]) + codex.import_codex_file(self.con, str(surviving)) + write_records(retired, [self.meta]) + codex.import_codex_file(self.con, str(retired)) + self.check_owners(None, None) + + with surviving.open("a") as fh: + fh.write(trailing[20:]) + result = codex.import_codex_file(self.con, str(surviving)) + self.assertTrue(result["incremental"]) + self.assertEqual(result["lines"], 1) + self.check_owners(None, 91100) From 73698b2d44cd20e3c025b6f8c23bf4a362e40bc7 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 22:55:49 +0100 Subject: [PATCH 43/44] wip: reconcile completed Codex archives with their incomplete source receipts --- agent_observer/adapters/codex.py | 5 +- agent_observer/adapters/codex_atomic.py | 77 ++++++++++++++++++++++--- tests/test_codex_atomic.py | 47 +++++++++++++++ 3 files changed, 119 insertions(+), 10 deletions(-) diff --git a/agent_observer/adapters/codex.py b/agent_observer/adapters/codex.py index a7c03c2..fb3c540 100644 --- a/agent_observer/adapters/codex.py +++ b/agent_observer/adapters/codex.py @@ -768,7 +768,8 @@ def import_codex_file(con: sqlite3.Connection, path: str, "events_duplicate": 0, "compactions": 0, "malformed": 0, } src = JsonlSource(con, HARNESS, path, full=full) - if (src.row["codex_context_version"] != _CONTEXT_VERSION + predecessor = codex_atomic.relocated_source(src) + if (predecessor is not None or src.row["codex_context_version"] != _CONTEXT_VERSION or src.row["codex_context_offset"] != src.row["read_offset"]): # Replay older indexes once to recover literal turn witnesses from copies. src.start_offset = 0 @@ -937,7 +938,7 @@ def import_codex_file(con: sqlite3.Connection, path: str, if ts is not None: reader.first_ts = ts if reader.first_ts is None else min(reader.first_ts, ts) reader.last_ts = ts if reader.last_ts is None else max(reader.last_ts, ts) - codex_atomic.finish(reader) + codex_atomic.finish(reader, predecessor) _flush_token_counts(reader) _resolve_legacy_user_messages(reader) if not src.privacy_stale: diff --git a/agent_observer/adapters/codex_atomic.py b/agent_observer/adapters/codex_atomic.py index 567f34c..9bc5e4f 100644 --- a/agent_observer/adapters/codex_atomic.py +++ b/agent_observer/adapters/codex_atomic.py @@ -1,9 +1,11 @@ """Source observations for task attribution of Codex token_usage_record atoms.""" +import hashlib import json +import os from collections import defaultdict -from .. import db, native_response +from .. import db, lookup, native_response from ..ingest import iso_ts @@ -21,6 +23,40 @@ def _signature(observation): return observation["session_key"], observation["input_id"], measured +def _prefix_digest(path, size): + digest = hashlib.sha256() + with open(path, "rb") as stream: + while size: + chunk = stream.read(min(size, 1024 * 1024)) + if not chunk: + return None + digest.update(chunk) + size -= len(chunk) + return digest.hexdigest() + + +def relocated_source(src): + """Find an incomplete ledger source whose verified archive is this rollout.""" + path = os.path.abspath(src.path) + if (not any(part in path for part in ("/sessions/", "/archived_sessions/")) + or not db._has_table(src.con, "codex_incomplete_sources")): + return None + matches = [] + for row in src.con.execute("""SELECT s.*,i.* FROM codex_incomplete_sources i + JOIN sources s ON s.id=i.source_id WHERE s.id!=? AND s.read_offset>0""", (src.source_id,)): + if os.path.basename(row["path"]) != os.path.basename(path) or not row["tail_sha256"]: + continue + resolved = lookup.resolve_source(row) + if resolved["reason"] != "relocated" or os.path.abspath(resolved["path"]) != path: + continue + row = dict(row) + if row.get("prefix_bytes") is not None: + if not row["prefix_digest"] or _prefix_digest(path, row["prefix_bytes"]) != row["prefix_digest"]: + continue + matches.append(row) + return matches[0] if len(matches) == 1 else None + + def prepare(r): con = r.con con.execute("""CREATE TABLE IF NOT EXISTS codex_atomic_observations ( @@ -32,9 +68,11 @@ def prepare(r): con.execute("CREATE INDEX IF NOT EXISTS codex_atomic_session ON codex_atomic_observations(session_key,response_id)") con.execute("""CREATE TABLE IF NOT EXISTS codex_incomplete_sources ( source_id INTEGER PRIMARY KEY REFERENCES sources(id),session_key TEXT NOT NULL,legacy_dispute INTEGER NOT NULL, - replay INTEGER NOT NULL DEFAULT 1)""") - if "replay" not in {c[1] for c in con.execute("PRAGMA table_info(codex_incomplete_sources)")}: - con.execute("ALTER TABLE codex_incomplete_sources ADD COLUMN replay INTEGER NOT NULL DEFAULT 1") + replay INTEGER NOT NULL DEFAULT 1, prefix_bytes INTEGER, prefix_digest TEXT)""") + columns = {c[1] for c in con.execute("PRAGMA table_info(codex_incomplete_sources)")} + for key, declaration in (("replay", "INTEGER NOT NULL DEFAULT 1"), ("prefix_bytes", "INTEGER"), ("prefix_digest", "TEXT")): + if key not in columns: + con.execute(f"ALTER TABLE codex_incomplete_sources ADD COLUMN {key} {declaration}") r.atomic_ids = set() r.unreadable_atomic = False if not r.src.incremental: @@ -66,7 +104,7 @@ def observe(r, obj, counters): *(native_response.identifier(p.get(k)) for k in ("thread_id", "root_turn_id", "session_id")))) -def finish(r): +def finish(r, predecessor): con, src = r.con, r.src incomplete = r.unreadable_atomic or src.incomplete_record or src.end_offset < src.size if incomplete: @@ -75,10 +113,23 @@ def finish(r): (src.path,)).fetchone() is not None) replay = r.unreadable_atomic or (not src.incremental and con.execute( "SELECT 1 FROM prior_codex_atoms LIMIT 1").fetchone() is not None) - con.execute("INSERT INTO codex_incomplete_sources VALUES(?,?,?,?) ON CONFLICT(source_id) DO UPDATE SET " - "legacy_dispute=MAX(legacy_dispute,excluded.legacy_dispute),replay=excluded.replay", - (src.source_id, r.session_key, legacy, replay)) + con.execute("INSERT INTO codex_incomplete_sources(source_id,session_key,legacy_dispute,replay," + "prefix_bytes,prefix_digest) VALUES(?,?,?,?,?,?) ON CONFLICT(source_id) DO UPDATE SET " + "session_key=excluded.session_key,legacy_dispute=MAX(legacy_dispute,excluded.legacy_dispute)," + "replay=excluded.replay,prefix_bytes=excluded.prefix_bytes,prefix_digest=excluded.prefix_digest", + (src.source_id, r.session_key, legacy, replay, src.size, _prefix_digest(src.path, src.size))) else: + if predecessor is not None and predecessor["session_key"] == r.session_key and ( + predecessor.get("prefix_digest") or _historical_atoms_survive(con, predecessor["id"], src.source_id)): + # The archive was read from the start. Its source now owns the current + # observations, including withdrawals. Keep the old raw ledger locators. + old = predecessor["id"] + r.atomic_ids.update(rid for rid, in con.execute( + "SELECT DISTINCT response_id FROM codex_atomic_observations WHERE source_id=?", (old,))) + con.execute("DELETE FROM codex_atomic_observations WHERE source_id=?", (old,)) + con.execute("DELETE FROM native_response_inputs WHERE source_id=?", (old,)) + con.execute("DELETE FROM codex_incomplete_sources WHERE source_id=?", (old,)) + con.execute("UPDATE sources SET codex_context_offset=NULL WHERE id=?", (old,)) cleared = con.execute("DELETE FROM codex_incomplete_sources WHERE source_id=?", (src.source_id,)).rowcount if cleared and src.incremental: # Another source may have withdrawn a conflicting copy while this @@ -94,6 +145,16 @@ def finish(r): _reconcile(con, rid, src.source_id) +def _historical_atoms_survive(con, original, archive): + # Older incomplete receipts have only the tail hash at the read offset. + # A same-name copy must additionally account for every observed atom. + def observations(source_id): + return {(o["response_id"], _signature(o)) for o in con.execute( + "SELECT * FROM codex_atomic_observations WHERE source_id=?", (source_id,))} + previous = observations(original) + return bool(previous) and previous <= observations(archive) + + def _reconcile(con, rid, refreshing): copies = con.execute("""SELECT o.*,i.source_id AS incomplete FROM codex_atomic_observations o JOIN sources s ON s.id=o.source_id LEFT JOIN codex_incomplete_sources i ON i.source_id=o.source_id diff --git a/tests/test_codex_atomic.py b/tests/test_codex_atomic.py index 0da535e..e76461f 100644 --- a/tests/test_codex_atomic.py +++ b/tests/test_codex_atomic.py @@ -2,8 +2,10 @@ from contextlib import closing import json +import os from pathlib import Path import sqlite3 +from unittest.mock import patch from agent_observer import report from agent_observer.adapters import codex, t3_purpose @@ -128,3 +130,48 @@ def test_finishing_unrelated_tail_reconciles_an_earlier_response(self): self.assertTrue(result["incremental"]) self.assertEqual(result["lines"], 1) self.check_owners(None, 91100) + + def check_archived_tail(self, import_copy_first): + live = Path(self.tmp.name, "sessions") + archive = live.with_name("archived_sessions") + live.mkdir() + archive.mkdir() + with (patch.object(codex, "DEFAULT_ROOT", str(live)), + patch.object(codex, "ARCHIVE_ROOT", str(archive)), + patch.dict(os.environ, {"T3CODE_HOME": self.tmp.name})): + first = self.source("sessions/rollout-first", "A", 1100) + second = self.source("sessions/rollout-second", "B", 91100) + tail = json.dumps(self.context) + "\n" + with second.open("a") as fh: + fh.write(tail[:20]) + codex.import_codex_file(self.con, str(second)) + write_records(first, [self.meta]) + codex.import_codex_file(self.con, str(first)) + self.check_owners(None, None) + target = archive / second.name + completed = second.read_bytes() + tail[20:].encode() + if import_copy_first: + target.write_bytes(completed) + codex.sync(self.con, source=str(target)) + self.check_owners(None, None) + second.unlink() + codex.sync(self.con, source=str(first)) + self.check_owners(None, None) + if not import_copy_first: + # The indexed complete lines agree, but this same-name copy + # replaces the torn bytes with a different well-formed record. + target.write_bytes(completed[:-len(tail.encode())] + b'{"type":"unrelated","payload":{}}\n') + codex.sync(self.con) + self.check_owners(None, None) + target.write_bytes(completed) + for full in (False, True): + codex.sync(self.con, full=full) + self.check_owners(None, 91100) + native = report.task_report(self.con, "B")["native_purpose"] + self.assertEqual(native["unlocated_usage_sessions"], []) + + def test_completed_archive_recovers_a_previously_incomplete_source(self): + self.check_archived_tail(False) + + def test_already_indexed_archive_recovers_when_the_live_copy_vanishes(self): + self.check_archived_tail(True) From 76e87208415b0b4f98d29a19d1ad4f140cb29ac3 Mon Sep 17 00:00:00 2001 From: Luke Maj Date: Wed, 25 Nov 2026 22:57:58 +0100 Subject: [PATCH 44/44] wip: verify legacy Codex file identity before clearing a torn receipt --- agent_observer/adapters/codex_atomic.py | 4 ++++ tests/test_codex_atomic.py | 29 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/agent_observer/adapters/codex_atomic.py b/agent_observer/adapters/codex_atomic.py index 9bc5e4f..86aff15 100644 --- a/agent_observer/adapters/codex_atomic.py +++ b/agent_observer/adapters/codex_atomic.py @@ -53,6 +53,10 @@ def relocated_source(src): if row.get("prefix_bytes") is not None: if not row["prefix_digest"] or _prefix_digest(path, row["prefix_bytes"]) != row["prefix_digest"]: continue + elif row["ino"] != src.ino: + # Legacy receipts did not hash the torn line. Matching complete + # records in a different file cannot identify its missing tail. + continue matches.append(row) return matches[0] if len(matches) == 1 else None diff --git a/tests/test_codex_atomic.py b/tests/test_codex_atomic.py index e76461f..fe6132f 100644 --- a/tests/test_codex_atomic.py +++ b/tests/test_codex_atomic.py @@ -175,3 +175,32 @@ def test_completed_archive_recovers_a_previously_incomplete_source(self): def test_already_indexed_archive_recovers_when_the_live_copy_vanishes(self): self.check_archived_tail(True) + + def test_historical_archive_must_identify_the_missing_file(self): + live = Path(self.tmp.name, "sessions") + archive = live.with_name("archived_sessions") + live.mkdir() + archive.mkdir() + with patch.object(codex, "DEFAULT_ROOT", str(live)), patch.object(codex, "ARCHIVE_ROOT", str(archive)): + original = self.source("sessions/rollout-original", "A", 1100) + pending = self.source("sessions/rollout-pending", "B", 91100) + prefix = pending.read_bytes() + tail = json.dumps(self.context) + "\n" + with pending.open("a") as fh: + fh.write(tail[:20]) + codex.sync(self.con, source=str(pending)) + # The previous parser recorded the inode and complete atoms but + # did not fingerprint the bytes of the unfinished line. + self.con.execute("UPDATE codex_incomplete_sources SET prefix_bytes=NULL,prefix_digest=NULL") + write_records(original, [self.meta]) + codex.sync(self.con, source=str(original)) + target = archive / pending.name + target.write_bytes(prefix + b'{"type":"turn_context","payload":{"effort":"high"}}\n') + with pending.open("a") as fh: + fh.write(tail[20:]) + saved = pending.rename(live.with_name("saved")) + codex.sync(self.con, source=str(target)) + self.check_owners(None, None) + saved.replace(target) + codex.sync(self.con, source=str(target)) + self.check_owners(None, 91100)