diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index fd7bc16..6964b2b 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-observer", - "version": "1.6.0", + "version": "1.7.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 3740327..2e5d50f 100644 --- a/.codex-plugin/plugin.json +++ b/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-observer", - "version": "1.6.0", + "version": "1.7.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 83cf6cc..3fb3436 100644 --- a/.grok-plugin/plugin.json +++ b/.grok-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agent-observer", - "version": "1.6.0", + "version": "1.7.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 4d219bf..3ad10ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## [1.7.0] - 2026-11-25 + +### Added + +- Report native Issue and PR response ownership and show incomplete outcome costs. + ## [1.6.0] - 2026-11-25 ### Added diff --git a/README.md b/README.md index 130f0d7..7ffadab 100644 --- a/README.md +++ b/README.md @@ -514,6 +514,30 @@ 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. 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. +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 +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 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 sessions using Router records, preserving captured task metadata and outcomes. diff --git a/VERSION b/VERSION index dc1e644..bd8bf88 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.6.0 +1.7.0 diff --git a/agent_observer/adapters/claude.py b/agent_observer/adapters/claude.py index eb26574..6358baa 100644 --- a/agent_observer/adapters/claude.py +++ b/agent_observer/adapters/claude.py @@ -16,8 +16,9 @@ import json import os import sqlite3 +from collections import defaultdict, deque -from .. import db, 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) @@ -97,15 +98,17 @@ 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" _NATIVE_KINDS_TABLE = "claude_native_kinds" -_IMPORT_VERSION = 5 # Replay T3 completion-report parsing once (#142). +_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") def _ensure_native_kinds(con) -> None: @@ -301,6 +304,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() @@ -309,6 +314,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, @@ -328,7 +334,15 @@ 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) + 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)) def import_claude_file(con: sqlite3.Connection, path: str, @@ -378,10 +392,17 @@ 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) _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 @@ -395,29 +416,39 @@ 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(): 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", 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() + r.final_location = None _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'", (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: @@ -427,8 +458,64 @@ 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) + 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: + 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: + 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. + 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=? + )""" + 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 + 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,)) + _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: fields = {"started_at": r.first_ts, "ended_at": r.last_ts, **r.meta, **r.identity.fields(con)} @@ -443,6 +530,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 @@ -480,6 +568,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. @@ -507,8 +602,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): @@ -519,10 +613,12 @@ 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 + 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"), @@ -531,8 +627,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, } @@ -545,6 +640,154 @@ 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( + "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() + sources = {row["source_id"] for row in rows} + if len(sources) < 2 or rows[0]["original"] not in sources: + return None + 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 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]: + if len(witnesses[field]) < 2 or rows[0]["original"] not in witnesses[field]: + return None + 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 _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() + mismatch = ["json_extract(o.payload,'$.model') IS NOT r.model"] + 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 _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,))) + # 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)")}: + 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" + 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 (" + "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 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)" + missing + ")", (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. @@ -553,28 +796,47 @@ 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: + 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)) + 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 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): + 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") - # 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. + 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( @@ -624,6 +886,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: @@ -679,7 +946,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, @@ -1060,3 +1327,316 @@ 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), + 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_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.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_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)") + 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)") + 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)") + 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 " + "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, + 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')""") + 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""") + 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. + r.con.execute("CREATE TEMP TABLE claude_prior_edges AS " + "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,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,)) + 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 " + "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_final_observations 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): + 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)): + 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}" + if _final_stop(message): + 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" + 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): + 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 + 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 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 + _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): + """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): + """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"): + 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() + 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_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,)): + if uuid: + disputed.add(uuid) + if response_id: + conflicts.add(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 (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) + 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) + 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() + 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, 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) + elif nodes and nodes <= resolved: + results[response_id] = set.union(*(anchors[node] for node in nodes)) + 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 + + +def response_inputs(con, session_key): + witnesses, conflicts = response_witnesses(con, session_key) + return {rid: ids for rid, ids in witnesses.items() if ids and rid not in conflicts} diff --git a/agent_observer/adapters/codex.py b/agent_observer/adapters/codex.py index d9b2c23..fb3c540 100644 --- a/agent_observer/adapters/codex.py +++ b/agent_observer/adapters/codex.py @@ -17,7 +17,8 @@ import os import sqlite3 -from .. import db, privacy +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,6 +62,7 @@ def _occurrences_ready(row) -> bool: HARNESS = "codex" +_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. @@ -371,6 +373,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 +486,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( @@ -761,10 +768,10 @@ 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 + 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, 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,7 +818,12 @@ 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=? AND replay", (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) boundary = _history_file_boundary(path, own) if own is not None else None @@ -882,6 +894,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", @@ -906,10 +919,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 @@ -917,6 +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, predecessor) _flush_token_counts(reader) _resolve_legacy_user_messages(reader) if not src.privacy_stale: @@ -961,9 +983,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) @@ -971,6 +993,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 @@ -1592,14 +1615,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," @@ -1624,14 +1656,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) @@ -1642,6 +1666,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," @@ -2192,3 +2221,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/codex_atomic.py b/agent_observer/adapters/codex_atomic.py new file mode 100644 index 0000000..86aff15 --- /dev/null +++ b/agent_observer/adapters/codex_atomic.py @@ -0,0 +1,245 @@ +"""Source observations for task attribution of Codex token_usage_record atoms.""" + +import hashlib +import json +import os +from collections import defaultdict + +from .. import db, lookup, native_response +from ..ingest import iso_ts + + +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 _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 + 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 + + +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, + 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: + 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, predecessor): + 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) + 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(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 + # 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: + 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 _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 + WHERE o.response_id=? ORDER BY s.path,o.position""", (rid,)).fetchall() + 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] + 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"]) + 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 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 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: + 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 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 ( + 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 = {_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"]} + 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 COUNTERS)): + 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/adapters/grok.py b/agent_observer/adapters/grok.py index 00135f7..b3a73b7 100644 --- a/agent_observer/adapters/grok.py +++ b/agent_observer/adapters/grok.py @@ -1607,6 +1607,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=replay) 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=?", @@ -1960,6 +1969,10 @@ def _replay_error(ordinal: int, category: str, line: str = "") -> None: "(SELECT version FROM agentsmd_versions WHERE sha256=sessions.instructions_sha256), ?)" " WHERE session_key=?", (json.dumps(evidence, sort_keys=True) if evidence else None, version, r.session_key)) + 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 not metadata_errors: _store_meta(con, r.session_key, summary_fp, chat_fp_current, chat, metadata_imported_at) else: @@ -3076,3 +3089,124 @@ 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): + """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, + 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 + 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 + 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): + 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_witnesses(con, session_key): + if not db._has_table(con, "grok_prompt_bridges"): + return {}, set(), 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.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) + 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) + eligible = completed - disputed + refs = {} + for ref, pids in indexes.items(): + for pid in pids & eligible: + refs.setdefault(f"{session_key}:{pid}", set()).add(ref) + 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), {f"{session_key}:{pid}" for pid in disputed} + + +def response_inputs(con, session_key): + return response_witnesses(con, session_key)[0] diff --git a/agent_observer/adapters/opencode.py b/agent_observer/adapters/opencode.py index 4e433d1..2e3766e 100644 --- a/agent_observer/adapters/opencode.py +++ b/agent_observer/adapters/opencode.py @@ -14,12 +14,13 @@ from __future__ import annotations +from functools import partial import json import os 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 from .discovery import path_info @@ -174,10 +175,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 @@ -278,67 +282,151 @@ 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, *, 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 ( + 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 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( + "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"]) + if identities_complete: + con.execute("DELETE FROM opencode_response_observations WHERE source_id=?", (source_id,)) + else: + # 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): + # 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(): + payloads = ((row, json.loads(row["measurement"])) for row in copies) + measured = [(row, data) for row, data in payloads if isinstance(data, dict)] + 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: + 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 = {} + 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"): + 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 in _INVALID_OBSERVATIONS: + 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 unavailable: + continue + parents = {parent for parent, _ in variants if parent} + 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) + 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. + 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 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, unavailable + + +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 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 + + +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, 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: @@ -355,6 +443,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 @@ -412,7 +502,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 = "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() @@ -459,6 +549,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", @@ -468,7 +559,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 = False try: parts = _fetch_dicts( native, "part", @@ -485,21 +576,27 @@ 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] = [] + 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 or raw is None: - _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) except (json.JSONDecodeError, TypeError, UnicodeDecodeError): - _oops(con, stats, src_path, index, "malformed_json", - _record_line(raw)) - continue + data = None + if raw is not None: + error = "malformed_json" if not isinstance(data, dict): - _oops(con, stats, src_path, index, "schema_error", - _record_line(raw, data)) + _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") @@ -509,12 +606,12 @@ def import_session(con: sqlite3.Connection, native: sqlite3.Connection, _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) + _project_observations(con, stats, session_key, sess_id) 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", @@ -538,10 +635,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, size_bytes, db.now(), + (snapshot, size_bytes, db.now(), int((time.monotonic() - started) * 1000), sess_id, new_version, source_id)) con.commit() @@ -551,13 +651,14 @@ 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") 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) \ @@ -570,6 +671,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), @@ -577,21 +679,63 @@ 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": + # 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) -> None: + msg, data, index, ts, ordinal, roles) -> 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 + measurement = _measurement(data) + if measurement == _MALFORMED_USAGE: + _oops(con, stats, src_path, ordinal, "malformed_usage", _record_line(msg.get("data"), data)) + _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 = "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")} + + +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 + return "unfinished" + if _completion_time(timing["completed"]) is None: + return _MALFORMED_USAGE raw_tokens = data.get("tokens") if raw_tokens is None: tokens: dict = {} @@ -600,18 +744,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 + return _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 + 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 @@ -628,27 +768,29 @@ def _ingest_response(con, stats, src_path, source_id, session_key, sess, values[field] = None 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 + 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 + 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()): total = sum(values.values()) + if total > _MAX_COUNTER: + return _MALFORMED_USAGE 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 - _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 any(data.get(k) is not None and not isinstance(data[k], str) for k in ("modelID", "providerID", "variant")): + 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 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)) def _ingest_submission(con, stats, identity, src_path, source_id, @@ -770,9 +912,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: @@ -796,6 +943,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. @@ -812,25 +961,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, @@ -847,8 +988,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 @@ -870,27 +1010,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: @@ -909,21 +1041,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: @@ -947,22 +1073,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 [] @@ -984,8 +1103,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/adapters/t3.py b/agent_observer/adapters/t3.py index 787d846..674fc89 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 + 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 - 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 from .discovery import path_info # A PR head branch as T3 snapshots it; anything else is not stored. @@ -76,7 +79,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"), @@ -150,24 +153,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," @@ -316,11 +321,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://") \ @@ -347,13 +355,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) @@ -366,8 +383,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( @@ -377,8 +394,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: @@ -882,14 +904,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)", @@ -1177,13 +1199,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( @@ -1201,23 +1219,42 @@ 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")} + # 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://*'" + " 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] = {} + seen: dict[str, 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(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 - for session_key in sorted(sessions.get(root, set())): + 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( "INSERT OR IGNORE INTO session_assignments(session_key," @@ -1230,11 +1267,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" @@ -1302,8 +1339,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) + 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 new file mode 100644 index 0000000..906c26a --- /dev/null +++ b/agent_observer/adapters/t3_purpose.py @@ -0,0 +1,807 @@ +"""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 os +import re +import sqlite3 +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""", + "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)""", + "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, 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. + # 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) + 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="", args=()): + if PROJECTION + name not in tables: + return + for row in native.execute("SELECT * FROM " + PROJECTION + name + where, args): + row = dict(row) + try: + payload = json.loads(row.pop("payload_json", None)) + except (ValueError, TypeError, RecursionError): + payload = None + yield row, _obj(payload) + + +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 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) + declared = None + if declaration is not None: + declared = dict(scope=scope, reason=reason, reference=ref, provenance=provenance) + if ref: + 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)) + + +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(snapshot, 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: + snapshot.insert("deliveries", snapshot.task(purpose), thread, pr["host"], + pr["repository"], pr["number"], _url(pr), at) + return aware + + +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")) + 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 = snapshot.task(ref) if ref else None + coords = ref or {} + status = _enum(row.get("status"), STATES) + version = _obj(p.get("purpose")).get("version") + 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"))) + runs[run] = (thread, purpose) + delivery = _obj(_obj(p.get("delegatedCompletion")).get("delivery")) + for task in _list(delivery.get("taskIds")): + if _id(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(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(snapshot, 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(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): + 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(snapshot, 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(snapshot, run, thread, "pending_background", task["taskId"], + child=task.get("childThreadId"), remote={"environmentId": task.get("childEnvironmentId")}) + return providers + + +def _subagents(snapshot, 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(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(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")): + 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")), + 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(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'"): + 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(snapshot, run, row["thread_id"], "subagent_item", p["subagentId"], + child=p.get("childThreadId"), remote=remote, status=p.get("status")) + + +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")) + 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}" + snapshot.insert("sessions", run, key) + attempts[aid] = (run, provider.thread, pt, root, turn, driver, sid, "nativeThreadId" in p) + 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(snapshot, 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 and _id(row["turn_item_id"]): + snapshot.insert("grok_calls", key, call, turn, row["turn_item_id"]) + + +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")) + 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 + 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 + snapshot.insert("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": + _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): + snapshot.insert("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(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. + 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 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. + 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] + 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",)), + _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}" + 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": + 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)): + 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) + child_boundaries.setdefault(lookup, set()).add((run, segment)) + return child_boundaries + + +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"): + 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), ()): + 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 _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(): + 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 _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() + 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) str: f"session span {r.get('time', {}).get('session_span_s')} " f"({r.get('time', {}).get('session_span_label')})", ] + 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"])) + 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( @@ -210,6 +218,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']}") @@ -1083,9 +1093,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. + # Native imports capture checkout diagnostics independently of T3 links. + # 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 a6eb05d..e7e5e09 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"] @@ -119,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]: @@ -215,6 +218,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. @@ -227,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") @@ -313,7 +333,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 +419,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/native_response.py b/agent_observer/native_response.py new file mode 100644 index 0000000..6740b4e --- /dev/null +++ b/agent_observer/native_response.py @@ -0,0 +1,157 @@ +"""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) + 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) + 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): + found[response_id].add(turn_id) + 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 ( + 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) + opencode = session_key.startswith("opencode:") + edge_sources = defaultdict(set) + if db._has_table(con, "native_response_events"): + 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:") + 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. + 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, turn in con.execute( + "SELECT id,source_id,family,native_id,turn_id FROM events WHERE session_key=?", (session_key,)): + 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"}: + yield event, turn, edges["tool_call", native_id] + elif claude and family in {"read", "skill_read"} and native_id.endswith(":read"): + yield event, turn, edges["tool_call", native_id[:-5]] + else: + 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 new file mode 100644 index 0000000..c976706 --- /dev/null +++ b/agent_observer/outcome.py @@ -0,0 +1,445 @@ +"""Read immutable purpose and native response witnesses in one ledger snapshot.""" + +from collections import defaultdict +from dataclasses import dataclass, field +import json + +from . import native_response +from .db import _has_table + + +def sessions(con, task_id): + if not _has_table(con, "t3_purpose_runs"): + return set() + 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): + 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 legacy_link(evidence): + return evidence == "t3" or (evidence or "").startswith("t3:") + + +@dataclass +class Ownership: + """Task ownership within the inspected sessions, with canonical witnesses kept separately.""" + native: dict | None = None + # 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) + 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): + """Literal event partitions. None excludes, an empty set admits session scope only.""" + if key not in self.literal_sessions: + return + for event, display_turn, responses in native_response.event_responses(con, key): + turns = None + if responses is not None and len(responses) <= 1: + rid = next(iter(responses), None) + turns = self.response_turns.get((key, rid)) + 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 + + +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"): + 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,))] + 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 = {} + 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 _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 by_run: + session_runs[key] = sorted(by_run) + elif not key.startswith(("claude:", "opencode:")): + continue + _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, + "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 + + +def _session_ownership(con, key, task_id, by_run, reference_conflict, result, members): + by_input = defaultdict(set) + 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"])} + 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 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: + 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() + 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.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( + "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, unavailable = 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) + 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}) + 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} + 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 + 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() | unavailable.keys(): + display_turn = measured_turns.get(rid) + 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)) + 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 + 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, ())} + 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. + # 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) + 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: + result.response_turns[key, rid] = turns + continue + + run, turn, segment, validation = next(iter(candidates)) + owner = by_run.get(run) + 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: + 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: + 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" + 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 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() + 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) + + +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() + if native["conflicting_source_runs"]: + main_gaps.add("conflicting_native_run_records") + if not native["runs"]: + main_gaps.add("purpose_run_unavailable") + 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 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) + 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["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 + 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/placement.py b/agent_observer/placement.py index ecf395f..55f3a12 100644 --- a/agent_observer/placement.py +++ b/agent_observer/placement.py @@ -1,34 +1,33 @@ -"""Place each response of a session shared by several PRs on one PR (#43). +"""First-native-import checkout diagnostics for legacy T3 sessions. -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. +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 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} +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"[:/]([\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: @@ -40,268 +39,211 @@ def _git(root: str, *args: str) -> str | None: return out.stdout.strip() if out.returncode == 0 else None -def _known_checkouts(con) -> list: +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 root, repository, branch FROM checkouts ORDER BY length(root) DESC" - ).fetchall() - + "SELECT a.task_id, a.evidence FROM session_assignments a WHERE a.session_key=?", + (session_key,)).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 _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("/") + 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 + # 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" + " AND number=? AND head_branch<>''", (host, repo, number)): + by_head.setdefault((host, repo, row["head_branch"]), set()).add(task) + return by_head -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 _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 _end_write(con) -> None: - """Commit an open write so the next git call is outside it. +def _occurrence_owners(con, session_key, live_ids): + """Pair a call with the next live response in each witnessing source. - 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. + A source with no following response supplies no witness. Disagreeing + witnesses leave the call unpaired, regardless of import order. """ - 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 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 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 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. - - 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. + 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: + """Keep shared legacy PR usage unplaced wherever a PR advertises a head. + + None delegates shared context and other assignment types to the caller. + Checkout diagnostics cannot grant ownership. """ - session = con.execute("SELECT harness, project_dir FROM sessions WHERE session_key=?", + 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 - 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) - 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"] - 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()} + 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 -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 +# Compatibility for callers using the original report helper. +place_session = read_placements -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. - - 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. - """ - 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: - 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()} - - -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 +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: - """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) - con.commit() - return len(shared) + """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/agent_observer/publish.py b/agent_observer/publish.py index 1e8ef3f..92d1ef5 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):,}" @@ -222,11 +231,14 @@ 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"], "subscription_note": rep["subscription_note"], }) + if "native_purpose" in rep: + out["native_purpose"] = rep["native_purpose"] else: out.update({ "scope_kind": "session", @@ -430,6 +442,20 @@ 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 {} + 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: {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"]) + ".") + for pr in native["deliveries"]: + 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.')} " f"Finished processes never imply an accepted task outcome._", ""] @@ -449,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 {} @@ -475,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 " @@ -512,7 +537,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/agent_observer/report.py b/agent_observer/report.py index af0f1b6..1a8febb 100644 --- a/agent_observer/report.py +++ b/agent_observer/report.py @@ -2,11 +2,12 @@ from __future__ import annotations +from collections import defaultdict import hashlib import json import sqlite3 -from . import codex_order +from . import codex_order, outcome, placement from .db import _has_table BUCKETS = ("input_tokens", "cached_input_tokens", "cache_write_input_tokens", @@ -215,9 +216,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 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", (task_id,))} @@ -225,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 @@ -251,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) @@ -268,13 +272,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)) @@ -292,7 +292,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 @@ -404,8 +404,9 @@ def _is_mcp_result(event) -> bool: def _phase_report(con, task_id, rows, whole, attempts, schedule, - unmeasured=frozenset()): + unmeasured=frozenset(), native_sessions=(), ownership=None): from . import pricing, analysis + ownership = ownership or outcome.Ownership() by_turn, by_session = {}, {} def phase(value): @@ -417,7 +418,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"])) @@ -428,22 +429,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): - 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,)): - label = ("session context" if key not in whole and event["turn_id"] not in turns - else selected(event)) + 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, 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 @@ -519,63 +534,102 @@ 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,))} - 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 + 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)} + 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} + # 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 = [] - assigned_anywhere = {r["user_message_id"] for r in - con.execute("SELECT user_message_id " - "FROM assignments").fetchall()} + 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 for r in responses: if r["is_overlap"]: 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 - (shared if r["session_key"] in whole_shared else attributed).append(dict(r)) + 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 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)) + elif len(owners) > 1: + shared.append(dict(r)) + sharing_tasks.update(owners) + 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: + 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)) + if sub in joint: + sharing_tasks.update(joint[sub]["tasks"]) + sharing_tasks.update(session_owners.get(key, ())) else: attributed.append(dict(r)) + 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: + shared.append(dict(r)) + sharing_tasks.update(session_owners[key] | prompt_owners[key]) + else: + attributed.append(dict(r)) + elif 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 # 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 +659,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,))} @@ -648,18 +702,22 @@ 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) - unavailable_usage = bool(not scope_keys or missing_sessions or empty_sessions + 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 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) 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) + 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(whole)-whole_shared, task_turn_rows, schedule, - unmeasured_attributed) + con, task_id, attributed, ownership.whole - whole_shared, task_turn_rows, schedule, + unmeasured_attributed, native["sessions"] if native else (), ownership) def _resp_tuple(r) -> list: return [r.get("response_id"), r.get("harness"), r.get("model"), @@ -678,11 +736,14 @@ 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, "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, @@ -712,16 +773,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 = [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): 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: @@ -786,6 +851,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, " @@ -794,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, @@ -843,6 +911,12 @@ 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 checkout_records: + report["legacy_checkout_observations"] = {"basis": "first_native_import", "responses": checkout_records} + if native: + report["native_purpose"] = native report["unbound_usage"] = unbound_usage report["source_availability"] = { "status": source_availability["status"], @@ -862,7 +936,12 @@ 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) + task_id, total_estimated, attributed, billed_shared, sharing_tasks) + 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, + text=f"unknown (observed priced subtotal {amount})") report["total_cost"]["unplaced"] = { "text": _money(unplaced_estimated) if unplaced else None, "responses": len(unplaced), @@ -873,11 +952,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: @@ -894,45 +969,25 @@ 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" 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, "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, } @@ -941,39 +996,62 @@ 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) - 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=?", - (task_id,))) - if not task_turns and not whole: - return {"events": [], "returned": 0, "total": 0, + literal_events = set() + trace_scope = {} + 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"]))} + 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, "note": "no bound turns; timeline empty", "join": {"calls": 0, "results": 0, "joined_call_ids": [], "unmatched_results": [], "unanswered_calls": []}} clauses = [] - 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 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(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 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) @@ -985,6 +1063,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 +1106,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..ac23611 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -536,17 +536,19 @@ 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 - their root. Each linked PR or Issue becomes one `repo#N` task +- Legacy thread trees: `sub..` ids (nesting allowed) group under + 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. One-link trees attribute exclusively. - 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 - matching no PR or several stays unplaced and outside every headline. - Other harnesses, and links without a head branch, keep whole sharing. + whole to every tree task as historical session context. A thread link alone cannot place a response. + 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 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_codex_atomic.py b/tests/test_codex_atomic.py new file mode 100644 index 0000000..fe6132f --- /dev/null +++ b/tests/test_codex_atomic.py @@ -0,0 +1,206 @@ +"""Task accounting for separate copies of a Codex atomic response.""" + +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 +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.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) + 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) + + 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) + + 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) + + 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) + + 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) diff --git a/tests/test_codex_fork.py b/tests/test_codex_fork.py index fe52cbc..3c2fb6c 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,26 +596,28 @@ 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)) - - def test_upgrade_keeps_parent_input_and_read_attribution(self): + 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_evidence(self): for user_id in (None, "parent-input"): with self.subTest(user_id=user_id): if os.path.exists(self.db_path): @@ -640,15 +642,18 @@ 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") - self.assertEqual(placed["codex:parent-r1"], "o/alpha#1") - self.assertEqual(placed["codex:parent-r2"], "o/beta#2") + placement.record_shared_checkouts(con) + placed = placement.read_placements(con, "codex:parent") + # 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_evidence_coverage.py b/tests/test_evidence_coverage.py new file mode 100644 index 0000000..6119818 --- /dev/null +++ b/tests/test_evidence_coverage.py @@ -0,0 +1,945 @@ +"""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: + # 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 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: + 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_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_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()] + 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"]) + + 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"]) + + 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) + + 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", {})] + 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) + 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"]) + + 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"]["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)) + 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"]) + + 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"]) + + 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)) + + 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) + + 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) + + 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"}) + + 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") diff --git a/tests/test_native_response.py b/tests/test_native_response.py new file mode 100644 index 0000000..4290e17 --- /dev/null +++ b/tests/test_native_response.py @@ -0,0 +1,200 @@ +"""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_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, [ + 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_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)) + 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_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") + 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), {}) diff --git a/tests/test_outcome.py b/tests/test_outcome.py new file mode 100644 index 0000000..8809be5 --- /dev/null +++ b/tests/test_outcome.py @@ -0,0 +1,427 @@ +"""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 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 + + +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.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)" + " 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"]) + + 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"]) + + 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): + 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.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 + 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)]) + 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"], []) + 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") + 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) + + 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"]) + + 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"]) diff --git a/tests/test_placement.py b/tests/test_placement.py index 485c4aa..c42d049 100644 --- a/tests/test_placement.py +++ b/tests/test_placement.py @@ -1,14 +1,17 @@ -"""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 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 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 @@ -44,148 +47,188 @@ 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): - """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"): - 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): - 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: - 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)) - 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() - 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}")]) - placed = placement.place_session(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() + def _assign(self, key, task, evidence="t3"): + self.con.execute( + "INSERT INTO session_assignments(session_key,task_id,evidence,created_at)" + " 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"] + 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") + self._assign(key, "o/alpha#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) - for root in self.checkouts.values(): - shutil.rmtree(root) - placed = placement.place_session(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") - 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_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")) + _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_detached_checkout_matches_no_pr(self): + 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", "--detach") - self.assertEqual(placement.checkout_of(self.con, root), ("o/alpha", None)) - - 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() - 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. + 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_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"): + self._assign(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('r0',?,'claude',?,1,'m',10,2,12)", + (self.source, key)) 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)) - - 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_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. - self.claude_session() + target = root + "/file" + event = self.con.execute( + "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,)) + 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(?,?,NULL,'o/alpha','fix/a')", + (event.lastrowid, digest)) self.con.commit() - 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: - alpha = report.task_report(ro, "o/alpha#1", schedule=SCHEDULE) + 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.assertEqual(placement.checkout_observations(ro, key), {}) + self._assert_unplaced(ro, ["r0"]) self.assertTrue(ro.in_transaction) - finally: - placement._git = real - ro.close() - self.assertTrue(bumped) - 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. + 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_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}")) + 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", + "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"]) + 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"] path = os.path.join(self.tmp.name, "placement.jsonl") @@ -227,14 +270,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}) - self.assertEqual(placement.place_session(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") @@ -244,8 +279,6 @@ 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), { - "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") @@ -274,10 +307,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") @@ -320,14 +350,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}) - self.assertEqual(placement.place_session(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( @@ -344,13 +366,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"], - "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") @@ -412,16 +429,6 @@ 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), { - "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) @@ -474,20 +481,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) - self.assertEqual(placement.place_session(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"), @@ -509,7 +507,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") @@ -517,143 +515,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))): - 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}) - - 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. - root = self.checkouts["alpha"] - 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"))]) - row = self.con.execute( - "SELECT repository, branch FROM checkouts WHERE root=?", - (root,)).fetchone() - self.assertEqual((row["repository"], row["branch"]), ("o/alpha", "fix/a")) - - 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")) - self.assertTrue(self.con.in_transaction) - flags = [] - real = placement._git - - def wrapped(checkout, *args): - flags.append(self.con.in_transaction) - return real(checkout, *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")) def test_sync_records_shared_sessions_once_after_refresh(self): calls = [] @@ -681,7 +549,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 diff --git a/tests/test_publish.py b/tests/test_publish.py index 68eff7a..26cb562 100644 --- a/tests/test_publish.py +++ b/tests/test_publish.py @@ -95,6 +95,30 @@ 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) + 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) + 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([]) with mock.patch.object(publish, "_gh", gh): diff --git a/tests/test_source_availability.py b/tests/test_source_availability.py index e9ec2ab..9b5b337 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 @@ -131,16 +132,33 @@ 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): + 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',?) " + "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") @@ -227,6 +245,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 +320,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() @@ -431,8 +451,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") diff --git a/tests/test_t3.py b/tests/test_t3.py index fab75dc..7a85989 100644 --- a/tests/test_t3.py +++ b/tests/test_t3.py @@ -371,15 +371,20 @@ def test_tree_tasks_and_shared_ownership(self): 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"]["shared_responses"]), - sorted(other["measured"]["shared_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"], 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 +709,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)" diff --git a/tests/test_t3_purpose.py b/tests/test_t3_purpose.py new file mode 100644 index 0000000..ab84393 --- /dev/null +++ b/tests/test_t3_purpose.py @@ -0,0 +1,555 @@ +"""Projection fixtures use Chromeria #377's v1 JSON and relational identities.""" +import json +import os +import sqlite3 +from pathlib import Path + +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 + +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/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( + 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_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/issue#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") + legacy = write_v2(os.path.join(self.tmp.name, "legacy.sqlite")) + self.assertEqual(t3.sync(self.con, source=legacy)["failed"], []) + self.assertEqual(membership()[rid]["validation"], "grok_tool_call") + # Independent copies can contradict either the item's literal call + # or its provider turn's literal prompt index. + other_path = os.path.join(self.tmp.name, "other.sqlite") + other = sqlite3.connect(other_path) + self.addCleanup(other.close) + self.native.backup(other) + 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'""") + 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() + self.assertEqual(t3.sync(self.con, source=other_path)["failed"], []) + self.assertEqual(membership(), {}) + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(membership(), {}) + other.execute(f"UPDATE {PREFIX}turn_items SET payload_json=?", (json.dumps(item),)) + other.execute(f"""UPDATE {PREFIX}provider_turns SET payload_json=json_set( + payload_json,'$.nativeTurnRef.nativeId','prompt:4') WHERE provider_turn_id='turn-g'""") + other.commit() + self.assertEqual(t3.sync(self.con, source=other_path)["failed"], []) + self.assertEqual(membership(), {}) + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(membership(), {}) + other.execute(f"DELETE FROM {PREFIX}runs WHERE run_id='g'") + other.commit() + self.assertEqual(t3.sync(self.con, source=other_path)["failed"], []) + 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), [ + 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_duplicate_snapshots_conflict_and_recover_independently(self): + other_path = os.path.join(self.tmp.name, "other.sqlite") + other = sqlite3.connect(other_path) + self.addCleanup(other.close) + self.native.commit() + self.native.backup(other) + self.sync("codex-mini.jsonl") + for source in (self.native, other): + source.execute(f"""UPDATE {PREFIX}provider_turns SET payload_json=json_set( + payload_json,'$.nativeInputs[0].nativeId','turn-mini-aaa') WHERE run_attempt_id='attempt-a'""") + source.execute(f"""UPDATE {PREFIX}run_attempts SET payload_json=json_set( + payload_json,'$.nativeThreadId','sess-fixture-mini-01') WHERE run_id='a'""") + source.commit() + + def refresh_other(): + other.commit() + self.assertEqual(t3.sync(self.con, source=other_path)["failed"], []) + + def credited(n): + return report.task_report(self.con, f"example/project#{n}")["measured"]["attributed_responses"] + + refresh_other() + self.assertEqual(self.refresh()["failed"], []) + expected = ["codex:resp-mini-001", "codex:resp-mini-002"] + self.assertEqual(credited(7), expected) + self.assertEqual(self.values("SELECT count(*) FROM t3_purpose_inputs WHERE run_id='a'"), [(1,)]) + other.execute(f"UPDATE {PREFIX}runs SET status='running' WHERE run_id='a'") + refresh_other() + self.assertEqual(self.values("SELECT status FROM t3_purpose_runs WHERE run_id='a'"), [(None,)]) + self.assertEqual(credited(7), expected) + self.con.execute("INSERT INTO session_assignments VALUES" + "('codex:historic','example/project#7','t3:old:https://github.com/example/project/issues/7',1)") + other.execute(f"""UPDATE {PREFIX}runs SET payload_json=json_set( + payload_json,'$.purpose.scope.reference.number',8) WHERE run_id='a'""") + 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)), ([], [])) + + 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, [])) + self.native.execute(f"UPDATE {PREFIX}runs SET status='interrupted' WHERE run_id='a'") + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT status FROM t3_purpose_runs WHERE run_id='a'"), + [("interrupted",)]) + self.native.execute(f"DELETE FROM {PREFIX}runs") + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT run_id FROM t3_purpose_runs ORDER BY run_id"), [("b",), ("g",)]) + + def test_pre_source_mirror_survives_first_refresh_of_a_different_path(self): + self.assertEqual(self.refresh()["failed"], []) + # A ledger from the earlier schema has the materialized projection and + # its import receipt, but no per-source tables. + for name, in self.values("SELECT name FROM sqlite_master WHERE type='table'" + " AND name GLOB 't3_source_*'"): + self.con.execute(f"DROP TABLE {name}") + legacy = write_v2(os.path.join(self.tmp.name, "legacy.sqlite")) + self.assertEqual(t3.sync(self.con, source=legacy)["failed"], []) + self.assertEqual(self.values("SELECT native_id FROM t3_purpose_inputs ORDER BY native_id"), + [("cx-A",), ("prompt:3",)]) + self.native.execute(f"DELETE FROM {PREFIX}runs WHERE run_id='a'") + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(self.values("SELECT native_id FROM t3_purpose_inputs"), [("prompt:3",)]) + + 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 + 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_selection_in_another_source_keeps_legacy_tree_unbound_until_removed(self): + from agent_observer import db + from tests.test_t3_v2 import CHILD, CX9 + legacy = write_v2(os.path.join(self.tmp.name, "legacy.sqlite")) + 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] + db.upsert_session(self.con, "codex:" + CX9, "codex", CX9, source) + self.row("threads", [CHILD, TIME], dict(id=CHILD, purposeSelection={"version": 1})) + + def bindings(): + return self.values("SELECT task_id FROM session_assignments WHERE task_id='example/beta#5'") + + self.assertEqual(t3.sync(self.con, source=legacy)["failed"], []) + self.assertEqual(bindings(), [("example/beta#5",)]) + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(bindings(), []) + self.assertEqual(t3.sync(self.con, source=legacy)["failed"], []) + self.assertEqual(bindings(), []) + self.native.execute(f"DELETE FROM {PREFIX}threads WHERE thread_id=?", (CHILD,)) + self.assertEqual(self.refresh()["failed"], []) + self.assertEqual(t3.sync(self.con, source=legacy)["failed"], []) + self.assertEqual(bindings(), [("example/beta#5",)]) + + 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()))