File size: 9,088 Bytes
a1b575d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""A typed analysis graph that replaces transcript replay.

Motivation is a measurement, not an aesthetic. On BioMysteryBench with a 25-step budget,
a step costs a median **9,267 tokens** while contributing only **~400 tokens** of genuinely
new content (921 chars of tool output plus 684 chars of command). Roughly 96% of the spend
is the loop re-sending its own history, so cost grows as O(T^2) and the step budget binds
long before the task is finished -- 75% of attempts exhaust it, and the median *correct*
answer uses every step it is given.

This module makes the conditioning context a bounded, structured summary instead. A node
stores an artifact **handle** (a path) rather than the artifact, so the graph stays small
regardless of how much data the analysis touches. Step cost becomes O(B) for a rendering
budget B, and the total becomes O(T*B): at the measured rate of new content, a 4k-token
state supports roughly 100 steps for the token cost that buys 25 today.

The graph is also what makes verification composable: each node carries the checks that
its own artifact must satisfy (see `vera.checks`), so a dense progress signal falls out of
the structure rather than being bolted on.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Iterable, Sequence

from .checks import CheckResult, rho

# Node kinds, ordered by their position in a typical analysis pipeline. Used only for
# rendering and weighting; the graph itself imposes no ordering constraint.
KINDS = ("load", "qc", "transform", "test", "interpret", "answer")

# Rough chars-per-token for budget accounting. Deliberately conservative: overestimating
# tokens truncates a little early, which is safe, whereas underestimating overflows the
# context, which is not.
CHARS_PER_TOKEN = 3.5


@dataclass(frozen=True)
class Node:
    """One step of an analysis, with its artifact and the checks it must satisfy.

    Attributes:
        id: Short unique handle, e.g. ``n7``.
        kind: One of `KINDS`.
        summary: One line stating what this node established. This is what the model
            reads on later steps, so it must carry the *finding*, not the activity
            ("14,203 of 34,460 cells pass QC", not "ran QC").
        artifact: Path to the produced file, or "" if the node produced only a scalar.
            Never the contents -- holding contents here would reintroduce the O(T^2)
            cost this module exists to remove.
        parents: Ids of nodes this one consumed.
        command: The shell command that produced it, for provenance and replay.
        checks: Consistency checks over this node's artifact.
    """

    id: str
    kind: str
    summary: str
    artifact: str = ""
    parents: tuple[str, ...] = ()
    command: str = ""
    checks: tuple[CheckResult, ...] = ()

    def __post_init__(self) -> None:
        if self.kind not in KINDS:
            raise ValueError(f"unknown node kind {self.kind!r}; expected one of {KINDS}")

    @property
    def rho(self) -> float:
        """Verification score of this node: the fraction of its checks that passed."""
        return rho(self.checks)

    def render(self) -> str:
        """One-line rendering for the model-facing state summary."""
        n_ok = sum(c.passed for c in self.checks)
        mark = f"{n_ok}/{len(self.checks)}" if self.checks else "unverified"
        parents = f" <- {','.join(self.parents)}" if self.parents else ""
        art = f" [{self.artifact}]" if self.artifact else ""
        return f"({self.id}) {self.kind}: {self.summary}{art} checks={mark}{parents}"


class AnalysisState:
    """The agent's working memory: a DAG of nodes, rendered under a token budget.

    Use `add` after each step and `render` to build the next prompt. `reward` gives the
    dense per-step signal that test-time steering consumes.
    """

    def __init__(self) -> None:
        self._nodes: dict[str, Node] = {}
        self._order: list[str] = []

    def __len__(self) -> int:
        return len(self._nodes)

    def __contains__(self, node_id: object) -> bool:
        return node_id in self._nodes

    def __getitem__(self, node_id: str) -> Node:
        return self._nodes[node_id]

    @property
    def nodes(self) -> tuple[Node, ...]:
        """All nodes, in insertion order."""
        return tuple(self._nodes[i] for i in self._order)

    def add(self, node: Node) -> Node:
        """Insert a node.

        Args:
            node: The node to add.

        Raises:
            ValueError: If the id is already used, or a parent is unknown. Both are
                programming errors that would silently corrupt provenance, so they raise
                rather than being tolerated.
        """
        if node.id in self._nodes:
            raise ValueError(f"duplicate node id {node.id!r}")
        missing = [p for p in node.parents if p not in self._nodes]
        if missing:
            raise ValueError(f"node {node.id!r} references unknown parents {missing}")
        self._nodes[node.id] = node
        self._order.append(node.id)
        return node

    def leaves(self) -> tuple[Node, ...]:
        """Nodes that no other node consumes -- the current analysis frontier."""
        consumed = {p for n in self._nodes.values() for p in n.parents}
        return tuple(self._nodes[i] for i in self._order if i not in consumed)

    def ancestors(self, node_id: str) -> set[str]:
        """Ids of all transitive parents of `node_id` (excluding itself)."""
        seen: set[str] = set()
        stack = list(self._nodes[node_id].parents)
        while stack:
            cur = stack.pop()
            if cur in seen:
                continue
            seen.add(cur)
            stack.extend(self._nodes[cur].parents)
        return seen

    def reward(self, new_nodes: Iterable[Node], weights: dict[str, float] | None = None) -> float:
        """Dense progress signal contributed by this step.

        Args:
            new_nodes: Nodes added at this step.
            weights: Optional per-kind weight. Missing kinds default to 1.0.

        Returns:
            Sum over new nodes of ``weight(kind) * rho(node)``. Zero for no new nodes,
            and zero for nodes carrying no checks -- see `vera.checks.rho`.
        """
        weights = weights or {}
        return sum(weights.get(n.kind, 1.0) * n.rho for n in new_nodes)

    def render(self, budget_tokens: int = 4000) -> str:
        """Render the state as model-facing text, never exceeding `budget_tokens`.

        Priority when the budget binds, highest first: the current frontier (leaves),
        then their ancestors, then everything else by recency. Frontier nodes are what
        the next action builds on, and their ancestors are what makes them interpretable;
        an unrelated early branch is the first thing that can be dropped.

        Args:
            budget_tokens: Cap on the rendering, in tokens (estimated at
                `CHARS_PER_TOKEN` chars per token).

        Returns:
            The rendering. If nodes were dropped, a final line says how many, so the
            model knows its view is partial rather than believing the analysis is smaller
            than it is.
        """
        if not self._nodes:
            return "(no analysis steps yet)"

        # Frontier first, most recent first: when every node is a leaf (parallel
        # branches), the newest is the one the next action builds on. Then the
        # ancestors that make those leaves interpretable, then the rest by recency.
        leaf_ids = [n.id for n in reversed(self.leaves())]
        ordered = list(leaf_ids)
        for lid in leaf_ids:
            ordered.extend(sorted(self.ancestors(lid)))
        rank: dict[str, int] = {}
        for i, nid in enumerate(ordered):
            rank.setdefault(nid, i)
        for i, nid in enumerate(nid for nid in reversed(self._order) if nid not in rank):
            rank[nid] = len(ordered) + i

        budget_chars = int(budget_tokens * CHARS_PER_TOKEN)
        # Reserve room for the elision note up front, so adding it cannot overflow.
        note_tmpl = "\n... %d earlier node(s) elided to fit the state budget"
        reserve = len(note_tmpl % len(self._order))
        fill = max(0, budget_chars - reserve)

        chosen: set[str] = set()
        used = 0
        for nid in sorted(self._order, key=lambda x: rank[x]):
            line = self._nodes[nid].render()
            if used + len(line) + 1 > fill:
                continue
            chosen.add(nid)
            used += len(line) + 1

        # Render in pipeline order, not priority order, so the analysis reads forwards.
        body = "\n".join(self._nodes[nid].render() for nid in self._order if nid in chosen)
        dropped = len(self._order) - len(chosen)
        if dropped:
            body += note_tmpl % dropped
        if not body:
            body = "(state budget too small to render any node)"
        # Belt and braces: the cap is a guarantee callers size their context against.
        return body[:budget_chars]