Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
47 changes: 47 additions & 0 deletions docs/instrumentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,53 @@ 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_<severity>`, `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 |
| `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.
`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
`(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
Expand Down
85 changes: 81 additions & 4 deletions scripts/cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

from __future__ import annotations

import uuid
from collections.abc import Callable
from dataclasses import dataclass, field

Expand All @@ -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

Expand All @@ -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."""
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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 = {
Expand All @@ -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,
Expand All @@ -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,
)
15 changes: 14 additions & 1 deletion scripts/run_cycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
88 changes: 86 additions & 2 deletions scripts/telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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
Expand All @@ -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",
)
},
}
Expand All @@ -234,6 +252,32 @@
"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. 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",
}),
"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
Expand Down Expand Up @@ -777,6 +821,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 {
Expand Down
Loading
Loading