From d66851b044d7353da23e8ddfe8aa1bd5cc36d39f Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Wed, 23 Sep 2026 13:29:36 +0200 Subject: [PATCH 1/2] Record structured, correlatable cycle outcomes (#37) What a run went on to produce is now recorded on rows of its own, never on the dispatch rows that hold the pre-routing signals: - verdict rows: status, findings by severity and a reported boolean tests.passed; - the closing cycle row: first-pass approval, whether resolution was needed and its rounds, first and final review verdicts, final approval, the latest test result, fallback stages and contract violations. Every row of one run carries a cycle_id minted per CycleRecorder and validated before anything is dispatched; stage_seq ties a verdict to the dispatch it reports on, and record_kind names dispatch, verdict or cycle. Telemetry.cycle_outcome reassembles a run and reports an unclosed one as unknown. Review outcomes appear only after a review reached APPROVED or CHANGES_REQUESTED, so an absent outcome never reads as approved, passing or zero. Every value goes through FIELD_SPECS. Telemetry schema moves to version 3 additively in payload; version-1 and version-2 rows stay readable and belong to no reassembled cycle. Closes #37 --- CHANGELOG.md | 8 ++ README.md | 9 ++ docs/instrumentation.md | 44 ++++++ scripts/cycle.py | 85 +++++++++++- scripts/run_cycle.py | 15 ++- scripts/telemetry.py | 86 +++++++++++- tests/test_cycle_outcomes.py | 252 +++++++++++++++++++++++++++++++++++ tests/test_stage_signals.py | 2 +- 8 files changed, 493 insertions(+), 8 deletions(-) create mode 100644 tests/test_cycle_outcomes.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 14798668..5107ddcd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ All notable changes to this project are documented here. This project follows ### Added +- Observed cycle outcomes in telemetry (schema 3), on `verdict` and closing + `cycle` rows kept apart from the pre-routing `dispatch` rows: first-pass + approval, whether resolution was needed and its rounds, first and final + review verdicts, findings by severity, a reported test result, final + approval, fallbacks and contract violations. Rows of one run share a + `cycle_id`, `stage_seq` ties a verdict to its dispatch, and + `Telemetry.cycle_outcome` reassembles a run. An outcome nobody reported is + absent, never approved, passing or zero; earlier rows stay readable. (#37) - A minimal profile-selection seam in `scripts/router.py`: `route()` asks a `ProfileSelector` for a profile name among the role's `ROLE_CANDIDATES` and refuses anything else. The existing rules are the default `rule_selector`, diff --git a/README.md b/README.md index 4d042466..33aee703 100644 --- a/README.md +++ b/README.md @@ -393,6 +393,15 @@ attempts reported earlier in the cycle; and, when `--verification available` or automatically. An unknown signal is left out, never recorded as zero. See [Pre-routing signals](docs/instrumentation.md#pre-routing-signals). +What the run went on to produce is recorded on separate rows, never on the +dispatch rows that hold those signals: each verdict row carries the status, +findings by severity and a reported test result, and the closing row carries +first-pass approval, whether resolution was needed and how many rounds it took, +the first and final review verdicts, fallbacks and contract violations. Every +row of one run shares a `cycle_id`, and `stage_seq` ties a verdict to the +dispatch it reports on. An outcome nobody reported is absent, not approved, +passing or zero. See [Cycle outcomes](docs/instrumentation.md#cycle-outcomes). + For a rehearsal that must stay in a disposable linked Git worktree, pass both `--cwd /path/to/worktree` and `--local-only`. The driver refuses to enable this mode for the live repository, runs implementation only, records the resulting diff --git a/docs/instrumentation.md b/docs/instrumentation.md index 084d2240..d9383bae 100644 --- a/docs/instrumentation.md +++ b/docs/instrumentation.md @@ -545,6 +545,50 @@ or file name reaches the store. The classifiers are heuristics over paths: whole word so `processor` is not `sso`, and neither it nor its absence says anything about what the code does. +### Cycle outcomes + +Schema version 3 records what a run went on to produce, on rows of its own. The +pre-routing signals above describe a decision; an outcome written beside them +would leak into any evaluation that reads them, so a `dispatch` row is written +once, before its stage's result is known, and nothing is ever added to it. + +Three payload keys tie a run together, listed in `telemetry.CORRELATION_FIELDS`: + +| Field | Meaning | +|---|---| +| `cycle_id` | minted once per `CycleRecorder`, so two runs of one work item stay apart; validated before anything is dispatched | +| `stage_seq` | the number of the `stage()` call; a rerouted attempt shares its stage's number, and a verdict carries the number of the latest dispatch of its role | +| `record_kind` | `dispatch`, `verdict` or `cycle` | + +Each outcome has one source row, listed in `telemetry.OUTCOME_FIELDS`: + +| Source | Fields | Written when | +|---|---|---| +| `verdict` | `status`, `findings_total`, `findings_blocking`, `findings_`, `tests_passed`, `checks_passed`, `checks_failed` | the stage's structured result is read | +| `cycle` | `first_review_status`, `first_pass_approved`, `resolution_needed`, `resolution_rounds` | a first `review` reported `APPROVED` or `CHANGES_REQUESTED` | +| `cycle` | `final_review_status`, `final_approved` | any review or rereview reported one of those | +| `cycle` | `tests_passed` | a verdict reported a boolean `tests.passed`; the latest one wins | +| `cycle` | `fallback_stages`, `contract_violations` | always: every dispatch of the run went through the recorder | +| `cycle` | `status`, `iterations` | always | + +Unknown is still not a default. A run that stopped before a review reached a +verdict carries no review outcome at all — not unapproved, not zero rounds — +and a review that reported `BLOCKED` settles nothing. A `tests` value that is +not a boolean `passed` is not a test result. `Telemetry.cycle_outcome(repo_id, +cycle_id)` reassembles a run from these rows and reports `closed: false` for one +that never wrote its closing row, whose outcome is then unknown rather than +failed. `resolution_rounds` counts the `resolve` stages the run attempted. + +The routing rules' choice is the `profile` on each `dispatch` row. A later +selector's suggestion can be compared with it, and with the outcome, by +`(cycle_id, stage_seq)`, without that selector being installed while the run is +recorded and without the rows it annotates being rewritten. Nothing records such +a suggestion yet. + +Rows from versions 1 and 2 are read as they were written. They carry no +`cycle_id`, so they group by `repo_id` and `task_id` only and belong to no +reassembled cycle. + ## What an installation gets Skills are instructions and can be duplicated harmlessly; the runtime is the diff --git a/scripts/cycle.py b/scripts/cycle.py index f18a280e..2c23e649 100644 --- a/scripts/cycle.py +++ b/scripts/cycle.py @@ -31,6 +31,7 @@ from __future__ import annotations +import uuid from collections.abc import Callable from dataclasses import dataclass, field @@ -52,7 +53,7 @@ route, ) from stage_signals import CHANGE_OBSERVED_ROLES, RESOLUTION_ROLES, ChangeSignals -from telemetry import Telemetry, routing_decision_fields +from telemetry import Telemetry, routing_decision_fields, validate_reference SCHEMA_VERSION = 1 @@ -65,6 +66,10 @@ "findings_medium", "findings_low", ) +#: Review statuses that settle a round. Anything else leaves the review outcome +#: unknown rather than failed. +TERMINAL_REVIEW_STATUSES = frozenset({"APPROVED", "CHANGES_REQUESTED"}) + @dataclass(frozen=True) class RoleContract: """The workspace boundary a role must receive before it can run.""" @@ -136,8 +141,14 @@ def __init__( local_only: bool = False, change_observer: Callable[[], ChangeSignals | None] | None = None, verification_available: bool | None = None, + cycle_id: str | None = None, ) -> None: self.telemetry = telemetry + # One per run, so two runs of the same work item stay apart. Checked + # now rather than on the first row: a refused id found after a paid + # dispatch leaves a stage nobody can record. + self.cycle_id = validate_reference( + "cycle_id", cycle_id or f"cycle-{uuid.uuid4().hex}") self.repo_id = repo_id self.task_id = task_id self.signals = signals @@ -172,6 +183,13 @@ def __init__( self.prior_findings: dict[str, int] = {} self.iteration = 0 self.stages: list[StageOutcome] = [] + # Correlation and observed outcomes. Kept apart from the pre-routing + # state above, and written only on verdict and closing rows. + self.stage_seq = 0 + self._latest_seq: dict[str, int] = {} + self.first_review_status: str | None = None + self.final_review_status: str | None = None + self.tests_passed: bool | None = None def stage(self, role: str, task: str, **dispatch_kwargs) -> StageOutcome: """Route, dispatch and record. One call, no half-done state. @@ -203,6 +221,8 @@ def stage(self, role: str, task: str, **dispatch_kwargs) -> StageOutcome: f"{role!r} stages must use workspace_policy={workspace_policy.value!r}, " f"not {requested_policy!r}") dispatch_kwargs["workspace_policy"] = workspace_policy + self.stage_seq += 1 + self._latest_seq[role] = self.stage_seq # Observed once per stage, before the first routing: the diff does not # change between an attempt and its reroute. @@ -291,12 +311,26 @@ def record_verdict(self, role: str, status: str, **fields) -> int: f"prior_{key}": fields[key] for key in FINDING_FIELDS if fields.get(key) is not None } - return self.telemetry.record_stage( + # A verdict with no dispatch of its role in this run points at none. + source = ({"stage_seq": self._latest_seq[role]} + if role in self._latest_seq else {}) + row = self.telemetry.record_stage( self.repo_id, self.task_id, role, iteration=self.iteration, status=status, routing_strategy=self.routing_strategy.value, - local_only=self.local_only, **fields, + local_only=self.local_only, + cycle_id=self.cycle_id, record_kind="verdict", + **source, **fields, ) + # Tracked only after the row was accepted, so a refused verdict cannot + # reach the closing row either. + if role in REVIEW_ROLES and status in TERMINAL_REVIEW_STATUSES: + if role == "review" and self.first_review_status is None: + self.first_review_status = status + self.final_review_status = status + if fields.get("tests_passed") is not None: + self.tests_passed = fields["tests_passed"] + return row def next_iteration(self) -> int: self.iteration += 1 @@ -309,9 +343,48 @@ def close(self, final_status: str, **fields) -> int: iteration=self.iteration, status=final_status, iterations=self.iteration, routing_strategy=self.routing_strategy.value, - local_only=self.local_only, **fields, + local_only=self.local_only, + cycle_id=self.cycle_id, record_kind="cycle", + **{**self.observed_outcome(), **fields}, ) + def observed_outcome(self) -> dict: + """What this run showed, and nothing it did not. + + The review outcomes exist only once a review reached a verdict: a cycle + that stopped before one has not been approved, has not failed its first + pass and has not needed zero rounds — it has not been judged. Fallbacks + and contract violations are always known, because every dispatch in the + run went through this recorder. + """ + attempts = [result for stage in self.stages for _, result in stage.attempts] + outcome = { + "fallback_stages": sum( + 1 for stage in self.stages + if stage.decision is not None and stage.decision.used_fallback + ), + "contract_violations": sum( + 1 for result in attempts + if result.outcome is DispatchOutcome.CONTRACT_VIOLATION + ), + } + first = self.first_review_status + if first is not None: + outcome.update( + first_review_status=first, + first_pass_approved=first == "APPROVED", + resolution_needed=first == "CHANGES_REQUESTED", + resolution_rounds=sum(1 for stage in self.stages if stage.role == "resolve"), + ) + if self.final_review_status is not None: + outcome.update( + final_review_status=self.final_review_status, + final_approved=self.final_review_status == "APPROVED", + ) + if self.tests_passed is not None: + outcome["tests_passed"] = self.tests_passed + return outcome + def _pre_routing(self, role: str, change: ChangeSignals | None) -> dict: """What was known before this routing, with unknown signals left out.""" signals = { @@ -338,6 +411,8 @@ def _record(self, role: str, decision: RoutingDecision, return self.telemetry.record_stage( self.repo_id, self.task_id, role, iteration=self.iteration, + cycle_id=self.cycle_id, stage_seq=self.stage_seq, + record_kind="dispatch", profile=decision.profile, used_fallback=decision.used_fallback, outcome=DispatchOutcome.BLOCKED.value, @@ -350,5 +425,7 @@ def _record(self, role: str, decision: RoutingDecision, self.repo_id, self.task_id, role, decision, result, iteration=self.iteration, local_only=self.local_only, + cycle_id=self.cycle_id, stage_seq=self.stage_seq, + record_kind="dispatch", **signals, ) diff --git a/scripts/run_cycle.py b/scripts/run_cycle.py index 8a11855d..2a672258 100644 --- a/scripts/run_cycle.py +++ b/scripts/run_cycle.py @@ -524,7 +524,8 @@ def advance(role: str, instruction: str = "") -> tuple[Reported, CycleReport | N # agent said it did; the row already says the call returned. The prose # beside it is not recorded: the store holds references and counts. if reported.status: - recorder.record_verdict(role, reported.status, **_findings(reported.payload)) + recorder.record_verdict(role, reported.status, **_findings(reported.payload), + **_tests(reported.payload)) if not reported.completes(role): return reported, stop(reported.explain(role), reported=reported) return reported, None @@ -607,6 +608,18 @@ def _findings(payload: dict | None) -> dict: return out +def _tests(payload: dict | None) -> dict: + """Whether the stage reported its tests passing. Absent is not passing. + + Only a boolean `tests.passed` counts: anything else is a report nobody can + read as a result, and recording it as one would invent a test outcome. + """ + tests = payload.get("tests") if payload else None + if isinstance(tests, dict) and isinstance(tests.get("passed"), bool): + return {"tests_passed": tests["passed"]} + return {} + + def _why(outcome: StageOutcome) -> str: result = outcome.result if result is None: diff --git a/scripts/telemetry.py b/scripts/telemetry.py index 6042f5eb..98f43d50 100644 --- a/scripts/telemetry.py +++ b/scripts/telemetry.py @@ -44,8 +44,10 @@ #: 1: the original stage row. 2: adds the pre-routing signals below, all in #: `payload`, so a version-1 row is still read as it was written; the version -#: only tells a reader which signals the writer could have supplied. -SCHEMA_VERSION = 2 +#: only tells a reader which signals the writer could have supplied. 3: adds the +#: cycle correlation keys and the observed outcomes below, again only in +#: `payload`; a row from an earlier version simply has no cycle to belong to. +SCHEMA_VERSION = 3 APP_DIRNAME = "code-cycle-toolkit" DATABASE_NAME = "telemetry.sqlite" @@ -189,6 +191,20 @@ "verification_available": ("flag", None), "previous_failed_attempts": ("count", None), "resolution_round": ("count", None), + # cycle correlation (schema 3) + "cycle_id": ("identifier", None), + "stage_seq": ("count", None), + "record_kind": ("token", frozenset({"dispatch", "verdict", "cycle"})), + # observed outcomes, written only once they are known (schema 3) + "tests_passed": ("flag", None), + "first_review_status": ("token", frozenset({"APPROVED", "CHANGES_REQUESTED"})), + "final_review_status": ("token", frozenset({"APPROVED", "CHANGES_REQUESTED"})), + "first_pass_approved": ("flag", None), + "resolution_needed": ("flag", None), + "resolution_rounds": ("count", None), + "final_approved": ("flag", None), + "fallback_stages": ("count", None), + "contract_violations": ("count", None), } #: Inclusive bounds for counts that have them. A count outside its range is a @@ -208,6 +224,8 @@ "prior_findings_critical", "prior_findings_high", "prior_findings_medium", "prior_findings_low", "previous_failed_attempts", "resolution_round", + "stage_seq", "resolution_rounds", "fallback_stages", + "contract_violations", ) }, } @@ -234,6 +252,30 @@ "estimated": frozenset({"changed_lines_estimate", "test_count_estimate"}), } +#: What ties a row to one run of one cycle. `cycle_id` is minted once per +#: `CycleRecorder`; `stage_seq` numbers its `stage()` calls, so a rerouted +#: attempt shares the number of the stage it belongs to and a verdict carries the +#: number of the dispatch it reports on. A later suggestion from another selector +#: can point at the same pair without the rows it annotates being rewritten. +CORRELATION_FIELDS = frozenset({"cycle_id", "stage_seq", "record_kind"}) + +#: What was learned after a routing, by the row that is its source. None of it +#: is ever written onto a `dispatch` row: those carry the pre-routing signals, +#: and an outcome beside them would leak into any evaluation that reads them. +#: A field that was not observed is absent, never a default. +OUTCOME_FIELDS: dict[str, frozenset[str]] = { + "verdict": frozenset({ + "status", "findings_total", "findings_blocking", "findings_critical", + "findings_high", "findings_medium", "findings_low", "tests_passed", + "checks_passed", "checks_failed", + }), + "cycle": frozenset({ + "status", "iterations", "first_review_status", "final_review_status", + "first_pass_approved", "resolution_needed", "resolution_rounds", + "final_approved", "tests_passed", "fallback_stages", "contract_violations", + }), +} + #: An identifier is a reference, not a sentence, and not a secret. #: #: What a validator can and cannot do here is worth being exact about, because @@ -777,6 +819,46 @@ def model_drift(self, repo_id: str | None = None) -> list[dict]: }) return drift + def cycle_outcome(self, repo_id: str, cycle_id: str) -> dict | None: + """One run of a cycle, reassembled from its rows. + + Returns `None` for a cycle this store has no rows for — including any + written before schema 3, which carry no `cycle_id`. Otherwise the + outcome holds only what the closing row observed, with `closed` saying + whether there was one: a run that never closed has an unknown outcome, + not an unapproved one. Dispatches and verdicts are listed by + `stage_seq`, the verdicts with the fields they reported and nothing + filled in. + """ + rows = [row for row in self.rows(repo_id) + if row["payload"].get("cycle_id") == cycle_id] + if not rows: + return None + + def fields(row: dict, names: frozenset) -> dict: + merged = {**row["payload"], **{key: row[key] for key in _COLUMNS}} + return {key: merged[key] for key in sorted(names) + if merged.get(key) is not None} + + closing_rows = [row for row in rows if row["payload"].get("record_kind") == "cycle"] + return { + "cycle_id": cycle_id, + "task_id": rows[0]["task_id"], + "closed": bool(closing_rows), + "outcome": fields(closing_rows[-1], OUTCOME_FIELDS["cycle"]) if closing_rows else {}, + "dispatches": [ + {"stage_seq": row["payload"].get("stage_seq"), "role": row["role"], + "profile": row["profile"], "outcome": row["outcome"], + "used_fallback": bool(row["used_fallback"])} + for row in rows if row["payload"].get("record_kind") == "dispatch" + ], + "verdicts": [ + {"stage_seq": row["payload"].get("stage_seq"), "role": row["role"], + **fields(row, OUTCOME_FIELDS["verdict"])} + for row in rows if row["payload"].get("record_kind") == "verdict" + ], + } + def summary(self, repo_id: str) -> dict: rows = self.rows(repo_id) return { diff --git a/tests/test_cycle_outcomes.py b/tests/test_cycle_outcomes.py new file mode 100644 index 00000000..ae5b3d90 --- /dev/null +++ b/tests/test_cycle_outcomes.py @@ -0,0 +1,252 @@ +"""Observed outcomes of a cycle, correlated with its routing and never mixed in.""" + +from __future__ import annotations + +import sys +import tempfile +import unittest +import unittest.mock +from pathlib import Path + + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(ROOT / "tests")) + +import executors as ex # noqa: E402 +import telemetry as tm # noqa: E402 +from test_cycle import CycleTestCase, ScriptedAdapter # noqa: E402 +from test_run_cycle import RunCycleTestCase, Talker, block # noqa: E402 + +OUTCOME_ONLY = set().union(*tm.OUTCOME_FIELDS.values()) +SEVERITIES = dict(findings_critical=0, findings_high=1, findings_medium=1, findings_low=1) + + +class ReconstructionTests(CycleTestCase): + def adapters(self, **kw): + return [ScriptedAdapter("codex", **kw), ScriptedAdapter("claude")] + + def corrected_cycle(self): + recorder = self.recorder(self.adapters()) + recorder.stage("implement", "work") + recorder.record_verdict("implement", "IMPLEMENTED", tests_passed=True) + recorder.stage("review", "review") + recorder.record_verdict("review", "CHANGES_REQUESTED", findings_total=3, + findings_blocking=1, **SEVERITIES) + recorder.next_iteration() + recorder.stage("resolve", "resolve") + recorder.record_verdict("resolve", "RESOLVED", tests_passed=False) + recorder.stage("rereview", "rereview") + recorder.record_verdict("rereview", "APPROVED", findings_total=0) + recorder.close("READY_FOR_MANUAL_MERGE") + return recorder + + def test_a_corrected_cycle_is_reconstructed_from_its_rows(self) -> None: + recorder = self.corrected_cycle() + + cycle = self.store.cycle_outcome("owner/repo", recorder.cycle_id) + + self.assertTrue(cycle["closed"]) + self.assertEqual({ + "status": "READY_FOR_MANUAL_MERGE", "iterations": 1, + "first_review_status": "CHANGES_REQUESTED", "first_pass_approved": False, + "resolution_needed": True, "resolution_rounds": 1, + "final_review_status": "APPROVED", "final_approved": True, + "tests_passed": False, "fallback_stages": 0, "contract_violations": 0, + }, cycle["outcome"]) + review = cycle["verdicts"][1] + self.assertEqual({"stage_seq": 2, "role": "review", "status": "CHANGES_REQUESTED", + "findings_total": 3, "findings_blocking": 1, **SEVERITIES}, review) + + def test_a_verdict_points_at_the_dispatch_it_reports_on(self) -> None: + recorder = self.corrected_cycle() + + cycle = self.store.cycle_outcome("owner/repo", recorder.cycle_id) + + dispatched = {(d["role"], d["stage_seq"]) for d in cycle["dispatches"]} + self.assertEqual([("implement", 1), ("review", 2), ("resolve", 3), ("rereview", 4)], + sorted(dispatched, key=lambda item: item[1])) + for verdict in cycle["verdicts"]: + self.assertIn((verdict["role"], verdict["stage_seq"]), dispatched) + # The rules' choice is on the dispatch row, where a later suggestion can + # be compared with it by (cycle_id, stage_seq). + self.assertEqual("cheap_coder", cycle["dispatches"][0]["profile"]) + + def test_a_first_pass_approval_needed_no_resolution(self) -> None: + recorder = self.recorder(self.adapters()) + recorder.stage("implement", "work") + recorder.stage("review", "review") + recorder.record_verdict("review", "APPROVED", findings_total=0) + recorder.close("READY_FOR_MANUAL_MERGE") + + outcome = self.store.cycle_outcome("owner/repo", recorder.cycle_id)["outcome"] + + self.assertIs(True, outcome["first_pass_approved"]) + self.assertIs(False, outcome["resolution_needed"]) + self.assertEqual(0, outcome["resolution_rounds"]) + self.assertIs(True, outcome["final_approved"]) + + +class UnknownIsNotDefaultTests(CycleTestCase): + def test_a_cycle_that_never_reached_a_verdict_is_not_judged(self) -> None: + recorder = self.recorder([ScriptedAdapter("codex"), ScriptedAdapter("claude")]) + recorder.stage("implement", "work") + recorder.close("HUMAN_INTERVENTION") + + outcome = self.store.cycle_outcome("owner/repo", recorder.cycle_id)["outcome"] + + for absent in ("first_pass_approved", "resolution_needed", "resolution_rounds", + "final_approved", "first_review_status", "tests_passed"): + with self.subTest(field=absent): + self.assertNotIn(absent, outcome) + self.assertEqual(0, outcome["contract_violations"]) + + def test_a_review_that_reported_blocked_is_no_review_outcome(self) -> None: + recorder = self.recorder([ScriptedAdapter("codex"), ScriptedAdapter("claude")]) + recorder.stage("review", "review") + recorder.record_verdict("review", "BLOCKED") + recorder.close("HUMAN_INTERVENTION") + + outcome = self.store.cycle_outcome("owner/repo", recorder.cycle_id)["outcome"] + + self.assertNotIn("first_pass_approved", outcome) + self.assertNotIn("final_approved", outcome) + + def test_a_cycle_that_never_closed_has_no_outcome(self) -> None: + recorder = self.recorder([ScriptedAdapter("codex"), ScriptedAdapter("claude")]) + recorder.stage("review", "review") + recorder.record_verdict("review", "APPROVED") + + cycle = self.store.cycle_outcome("owner/repo", recorder.cycle_id) + + self.assertFalse(cycle["closed"]) + self.assertEqual({}, cycle["outcome"]) + + def test_a_verdict_without_findings_does_not_report_zero(self) -> None: + recorder = self.recorder([ScriptedAdapter("codex"), ScriptedAdapter("claude")]) + recorder.stage("review", "review") + recorder.record_verdict("review", "APPROVED") + + verdict = self.store.cycle_outcome("owner/repo", recorder.cycle_id)["verdicts"][0] + + self.assertEqual({"stage_seq": 1, "role": "review", "status": "APPROVED"}, verdict) + + +class DispatchObservationTests(CycleTestCase): + def test_fallbacks_and_contract_violations_are_counted(self) -> None: + codex = ScriptedAdapter("codex", outcomes=[ + (ex.DispatchOutcome.BLOCKED, "operating_quota"), + (ex.DispatchOutcome.CONTRACT_VIOLATION, None), + ]) + recorder = self.recorder([codex, ScriptedAdapter("claude")]) + recorder.stage("implement", "work") # quota, then the fallback + recorder.availability["codex"] = ex.Availability.READY + recorder.stage("implement", "again") # the wrong model answered + recorder.close("HUMAN_INTERVENTION") + + outcome = self.store.cycle_outcome("owner/repo", recorder.cycle_id)["outcome"] + + self.assertEqual(1, outcome["fallback_stages"]) + self.assertEqual(1, outcome["contract_violations"]) + + +class SeparationTests(CycleTestCase): + def test_dispatch_rows_carry_no_outcome_and_are_never_rewritten(self) -> None: + recorder = self.recorder([ScriptedAdapter("codex"), ScriptedAdapter("claude")]) + recorder.stage("implement", "work") + recorder.stage("review", "review") + before = [row for row in self.store.rows("owner/repo")] + + recorder.record_verdict("review", "APPROVED", findings_total=0, tests_passed=True) + recorder.close("READY_FOR_MANUAL_MERGE") + + after = self.store.rows("owner/repo") + self.assertEqual(before, after[:len(before)]) + for row in before: + with self.subTest(role=row["role"]): + self.assertEqual("dispatch", row["payload"]["record_kind"]) + self.assertIsNone(row["status"]) + self.assertEqual(set(), set(row["payload"]) & OUTCOME_ONLY) + + def test_outcomes_and_pre_routing_signals_do_not_overlap(self) -> None: + pre_routing = set().union(*tm.PRE_ROUTING_SIGNALS.values()) + self.assertEqual(set(), pre_routing & OUTCOME_ONLY) + self.assertEqual(set(), pre_routing & tm.CORRELATION_FIELDS) + self.assertTrue(OUTCOME_ONLY | tm.CORRELATION_FIELDS <= set(tm.FIELD_SPECS)) + + def test_two_runs_of_one_work_item_stay_apart(self) -> None: + first = self.recorder([ScriptedAdapter("codex"), ScriptedAdapter("claude")]) + second = self.recorder([ScriptedAdapter("codex"), ScriptedAdapter("claude")]) + first.stage("implement", "work") + second.stage("implement", "work") + first.close("HUMAN_INTERVENTION") + + self.assertNotEqual(first.cycle_id, second.cycle_id) + self.assertTrue(self.store.cycle_outcome("owner/repo", first.cycle_id)["closed"]) + self.assertFalse(self.store.cycle_outcome("owner/repo", second.cycle_id)["closed"]) + + +class AllowlistTests(CycleTestCase): + def test_outcome_fields_accept_only_their_types(self) -> None: + for field, value in (("first_review_status", "LGTM"), ("final_approved", "yes"), + ("resolution_rounds", -1), ("tests_passed", {"passed": True}), + ("record_kind", "note")): + with self.subTest(field=field), self.assertRaises(tm.TelemetryError): + self.store.record_stage("owner/repo", "API-055", "coordinate", **{field: value}) + + def test_a_cycle_id_is_refused_before_anything_is_dispatched(self) -> None: + codex = ScriptedAdapter("codex") + with self.assertRaises(tm.TelemetryError): + self.recorder([codex, ScriptedAdapter("claude")], cycle_id="sk-live-abc") + with self.assertRaises(tm.TelemetryError): + self.recorder([codex, ScriptedAdapter("claude")], cycle_id="two words") + self.assertEqual([], codex.dispatched) + + def test_an_explicit_cycle_id_is_kept(self) -> None: + recorder = self.recorder([ScriptedAdapter("codex"), ScriptedAdapter("claude")], + cycle_id="run-2026-09-23-1") + recorder.close("HUMAN_INTERVENTION") + + self.assertIsNotNone(self.store.cycle_outcome("owner/repo", "run-2026-09-23-1")) + + +class LegacyRowTests(unittest.TestCase): + def test_rows_from_before_cycles_existed_stay_readable(self) -> None: + with tempfile.TemporaryDirectory() as directory: + store = tm.Telemetry(Path(directory) / "t.sqlite") + with unittest.mock.patch.object(tm, "SCHEMA_VERSION", 2): + store.record_stage("repo", "T-1", "review", status="APPROVED", + changed_files_count=2) + + row = store.rows("repo")[0] + + self.assertEqual(2, row["schema_version"]) + self.assertNotIn("cycle_id", row["payload"]) + self.assertIsNone(store.cycle_outcome("repo", "cycle-anything")) + + +class DriverTests(RunCycleTestCase): + def cycle_row(self): + return [row for row in self.rows() if row["payload"].get("record_kind") == "cycle"][-1] + + def test_a_reported_test_result_reaches_the_verdict_and_the_cycle(self) -> None: + implementer = Talker("codex", block("IMPLEMENTED", tests={"passed": True})) + + report = self.run_cycle(implementer, Talker("claude")) + + self.assertTrue(report.approved) + cycle = self.store.cycle_outcome("owner/api", self.cycle_row()["payload"]["cycle_id"]) + self.assertIs(True, cycle["verdicts"][0]["tests_passed"]) + self.assertIs(True, cycle["outcome"]["tests_passed"]) + self.assertIs(True, cycle["outcome"]["first_pass_approved"]) + + def test_an_unreadable_test_result_is_not_a_pass(self) -> None: + implementer = Talker("codex", block("IMPLEMENTED", tests={"passed": "yes"})) + + self.run_cycle(implementer, Talker("claude")) + + self.assertNotIn("tests_passed", self.cycle_row()["payload"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_stage_signals.py b/tests/test_stage_signals.py index 5344cf99..9f344851 100644 --- a/tests/test_stage_signals.py +++ b/tests/test_stage_signals.py @@ -380,7 +380,7 @@ def test_a_version_1_database_is_read_and_extended(self) -> None: reopened = tm.Telemetry(path) reopened.record_stage("repo", "T-2", "review", changed_files_count=3) rows = reopened.rows("repo") - self.assertEqual([1, 2], [row["schema_version"] for row in rows]) + self.assertEqual([1, tm.SCHEMA_VERSION], [row["schema_version"] for row in rows]) self.assertEqual({}, rows[0]["payload"]) self.assertEqual(3, rows[1]["payload"]["changed_files_count"]) From 78ddf00cac038428dea65feac32ad878f1562ba0 Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Wed, 23 Sep 2026 14:45:00 +0200 Subject: [PATCH 2/2] Promise only the verdict outcomes the driver records (REV-001, #37) No skill's structured result reports check counts, so listing checks_passed and checks_failed as verdict outcomes described data nothing writes. They leave OUTCOME_FIELDS and the documented contract, and stay accepted telemetry fields. A regression test pins the documented verdict outcomes to exactly what run_cycle reads off a structured result. --- docs/instrumentation.md | 5 ++++- scripts/telemetry.py | 6 ++++-- tests/test_cycle_outcomes.py | 13 +++++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/docs/instrumentation.md b/docs/instrumentation.md index d9383bae..4e691bfd 100644 --- a/docs/instrumentation.md +++ b/docs/instrumentation.md @@ -564,7 +564,7 @@ Each outcome has one source row, listed in `telemetry.OUTCOME_FIELDS`: | Source | Fields | Written when | |---|---|---| -| `verdict` | `status`, `findings_total`, `findings_blocking`, `findings_`, `tests_passed`, `checks_passed`, `checks_failed` | the stage's structured result is read | +| `verdict` | `status`, `findings_total`, `findings_blocking`, `findings_`, `tests_passed` | the stage's structured result is read | | `cycle` | `first_review_status`, `first_pass_approved`, `resolution_needed`, `resolution_rounds` | a first `review` reported `APPROVED` or `CHANGES_REQUESTED` | | `cycle` | `final_review_status`, `final_approved` | any review or rereview reported one of those | | `cycle` | `tests_passed` | a verdict reported a boolean `tests.passed`; the latest one wins | @@ -578,6 +578,9 @@ not a boolean `passed` is not a test result. `Telemetry.cycle_outcome(repo_id, cycle_id)` reassembles a run from these rows and reports `closed: false` for one that never wrote its closing row, whose outcome is then unknown rather than failed. `resolution_rounds` counts the `resolve` stages the run attempted. +`checks_passed` and `checks_failed` remain accepted telemetry fields, but no +skill's structured result reports check counts, so they are not a recorded +outcome; CI state stays in the published review comment. The routing rules' choice is the `profile` on each `dispatch` row. A later selector's suggestion can be compared with it, and with the outcome, by diff --git a/scripts/telemetry.py b/scripts/telemetry.py index 98f43d50..f27d73f8 100644 --- a/scripts/telemetry.py +++ b/scripts/telemetry.py @@ -262,12 +262,14 @@ #: What was learned after a routing, by the row that is its source. None of it #: is ever written onto a `dispatch` row: those carry the pre-routing signals, #: and an outcome beside them would leak into any evaluation that reads them. -#: A field that was not observed is absent, never a default. +#: A field that was not observed is absent, never a default. Only what the +#: driver can read off a structured result is listed: `checks_passed` and +#: `checks_failed` stay accepted fields, but no skill reports check counts, so +#: promising them here would describe an outcome nothing records. OUTCOME_FIELDS: dict[str, frozenset[str]] = { "verdict": frozenset({ "status", "findings_total", "findings_blocking", "findings_critical", "findings_high", "findings_medium", "findings_low", "tests_passed", - "checks_passed", "checks_failed", }), "cycle": frozenset({ "status", "iterations", "first_review_status", "final_review_status", diff --git a/tests/test_cycle_outcomes.py b/tests/test_cycle_outcomes.py index ae5b3d90..846fc939 100644 --- a/tests/test_cycle_outcomes.py +++ b/tests/test_cycle_outcomes.py @@ -14,6 +14,7 @@ sys.path.insert(0, str(ROOT / "tests")) import executors as ex # noqa: E402 +import run_cycle as rc # noqa: E402 import telemetry as tm # noqa: E402 from test_cycle import CycleTestCase, ScriptedAdapter # noqa: E402 from test_run_cycle import RunCycleTestCase, Talker, block # noqa: E402 @@ -226,6 +227,18 @@ def test_rows_from_before_cycles_existed_stay_readable(self) -> None: class DriverTests(RunCycleTestCase): + def test_every_documented_verdict_outcome_is_one_the_driver_records(self) -> None: + """REV-001: a documented outcome nothing writes is a promise, not data.""" + payload = { + "status": "CHANGES_REQUESTED", "tests": {"passed": False}, + "checks": {"passed": 4, "failed": 1}, + "unresolved_findings": [{"severity": "high", "blocks_approval": True}], + } + + emitted = {"status", *rc._findings(payload), *rc._tests(payload)} + + self.assertEqual(tm.OUTCOME_FIELDS["verdict"], emitted) + def cycle_row(self): return [row for row in self.rows() if row["payload"].get("record_kind") == "cycle"][-1]