Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(decisions): one broad, grounded discovery call per update (#2068)

Raghav Chamadiya1a343c0cbe0e
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.md
index e0f660361..5ee4215d0 100644
--- a/docs/layers/DECISIONS.md
+++ b/docs/layers/DECISIONS.md
@@ -57,9 +57,11 @@ history.
| PR bodies | `pr` | Squash-merge and PR commit bodies | A body only qualifies when it looks like a PR description (`## Why`, `## Motivation`, `## Context`, `Closes #`, `Before:` / `After:`). Up to 25 bodies. |
| Code comments | `comment` | Block comments and docstrings on high-centrality files | Bounded to 30 nodes, and to prose carrying a rationale cue ("because", "instead of", "rather than", "trade-off", "we chose", "deliberately"). Centrality-bounded on purpose: comment archaeology across a whole repo is noise. |
-Two more sources sit outside the index-time set: `session` (mined from your
-coding-agent transcripts, below) and `cli` (a decision you typed yourself, the
-most authoritative source there is).
+Three more sources sit outside the index-time set: `session` (deterministic
+gates over your coding-agent transcripts, below), `session_discovery` (one
+broad model pass over the same transcript prose, below, off unless you enable
+it), and `cli` (a decision you typed yourself, the most authoritative source
+there is).
### Controlling capture
@@ -73,6 +75,8 @@ repowise decision config preset local_only
repowise decision source list
repowise decision source set comment --off
repowise decision source set adr --no-llm # keep the parse, skip the model
+repowise decision source set session_discovery --on # the broad lane, opt-in
+repowise decision config discovery --max-sessions 6 # and its per-update budget
repowise decision llm --off # no decision extraction reaches a model
```
@@ -88,12 +92,21 @@ git_archaeology disabled no This source is switched off.
adr deterministic_only no Decision LLM extraction is off. The deterministic stage still runs.
pr disabled no This source is switched off.
comment disabled no This source is switched off.
-session deterministic_only no Decision LLM extraction is off. The deterministic stage still runs.
-cli always_on - Manual entry is always available.
+session deterministic_only no Decision LLM extraction is off. The deterministic stage still runs.
+session_discovery disabled no This source is switched off.
+cli always_on - Manual entry is always available.
+
+ Discovery budget: up to 12 session(s), 30,000 input tokens per update.
```
-The four presets are `off`, `local_only`, `balanced`, and `full`; editing any
-individual switch afterwards reads as `custom`. Mutations take `--dry-run` and
+The presets are `default`, `off`, `local_only`, `balanced`, and `full`; editing
+any individual switch afterwards reads as `custom`. `default` is what a config
+with no `decisions:` block resolves to, and it is deliberately not `full`: a
+source added after those switches existed stays off until you ask for it, so an
+upgrade never starts a model call you did not enable. A stored preset that
+lists its sources is treated the same way: that list is what the preset
+covered when it was written. Re-apply the preset to pick up a source added to
+it since. Mutations take `--dry-run` and
`--format json`, write atomically, and preserve every unrelated key in
`config.yaml`.
@@ -271,6 +284,59 @@ codebase is stored. Turn the pipeline off with
`repowise decision source set session --off`, or keep the transcript reading and
drop only the structuring call with `--no-llm`.
+### Broad session discovery
+
+Those gates are precision-first, and they are the recall bottleneck: a decision
+settled in a paragraph that never opens with "no," or pairs a decision verb
+with a causal cue is invisible to them. `session_discovery` is the recall lane
+beside them, off unless you enable it:
+
+```bash
+repowise decision source set session_discovery --on
+```
+
+Once per update it makes **one** model call over the user and assistant prose
+that update newly read, bounded by `discovery.max_sessions` (default 12) and
+`discovery.max_input_tokens` (default 30,000). It reuses the transcript read
+the `session` source already performs, so enabling it does not read your
+transcripts twice, and it costs one call whether the queue holds one session or
+forty.
+
+Each span of prose it sends carries a stable id, and every candidate must cite
+the ids it rests on. Before anything is stored:
+
+- the cited spans must all be spans that were actually sent;
+- the evidence quote must be verbatim, or near enough that only reflow and
+ articles separate it from the span's own text. The deterministic lane accepts
+ a looser paraphrase because its excerpts are the few sentences its gates
+ already matched; this lane is shown thousands of words, where a partial
+ overlap with some part of them is not evidence of anything;
+- the claim itself must overlap that text on its content words, so a fluent
+ invention riding a real quote is still rejected;
+- a rationale that fails the same check is dropped rather than invented;
+- a path the model names is kept only if the cited turns' tools touched it.
+ Scope is resolved from those files, never from the model, and naming none is
+ an honest repository-wide claim;
+- a claim that bundles two independent choices is flagged for splitting at
+ review, never split by machine.
+
+Everything that survives is a **candidate**. Like the deterministic lane it is
+written `proposed`, needs two distinct sessions to be proposed at all, and only
+`repowise decision confirm` makes it govern. The model's own
+`implemented_and_validated` verdict is evidence for review, not authority.
+
+Zero calls, and a stated reason, on every path that should not call: capture
+off, the source off, `llm: false`, no provider configured, and no new prose
+since the last update. Prose that does not fit one update's budget stays queued
+and is sent oldest-first next time, and a queued span is never aged out unread;
+a provider failure requeues the same prose and retries it on the next two
+updates before retiring it. Switching the source off leaves what is already
+queued in place, to be drained if you switch it back on. New prose is only
+captured while the source is on, so there is no backfill of what was read in
+between. It also depends on the `session` source, which is what reads the
+transcripts; with `session` off, discovery says so rather than reporting an
+empty repository.
+
## Getting decisions back to your agent
Capture is half the loop. The other half is delivery, and it happens at two
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index e3cb8caee..69d27ef3b 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -920,7 +920,8 @@ repowise decision deprecate ID [PATH] # mark deprecated
repowise decision health [PATH] # health dashboard
repowise decision config show [PATH] # the resolved capture policy
-repowise decision config preset NAME [PATH] # off | local_only | balanced | full
+repowise decision config preset NAME [PATH] # default | off | local_only | balanced | full
+repowise decision config discovery [PATH] # budget for the one broad discovery call
repowise decision source list [PATH] # the source registry and its state
repowise decision source set SRC --on|--off # switch one source
repowise decision source set SRC --llm|--no-llm # switch only its model stage
@@ -931,8 +932,15 @@ repowise decision llm --on|--off [PATH] # all decision-extraction mode
| Flag | Description |
|------|-------------|
-| `--dry-run` | Print the change and write nothing. On `config preset`, `source set`, `llm`. |
+| `--dry-run` | Print the change and write nothing. On `config preset`, `config discovery`, `source set`, `llm`. |
| `--format` | `table` (default) or `json`. `json` returns the full source registry. |
+| `--max-sessions` | `config discovery` only: session deltas one broad call may read (1-24, default 12). |
+| `--max-input-tokens` | `config discovery` only: input-token ceiling for one broad call (2000-60000, default 30000). |
+
+`config discovery` with neither budget flag just prints the resolved policy.
+Broad discovery itself is a source, so it is switched with
+`repowise decision source set session_discovery --on|--off`; it is off in the
+`default` policy and on in the `balanced` and `full` presets.
`confirm` is the acceptance event. Nothing else promotes a record to `active`:
extraction, recurrence across sessions, and confidence all stop at `proposed`.
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 3e5f39d14..91d11b678 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -390,7 +390,7 @@ API, and the index pipeline, so all three agree about what will run.
decisions:
enabled: true # master switch for automatic capture
llm: true # master switch for decision-extraction model calls
- preset: balanced # off | local_only | balanced | full
+ preset: balanced # default | off | local_only | balanced | full
sources:
inline_marker: true # WHY:/DECISION: markers
git_archaeology: true # commit messages
@@ -400,17 +400,28 @@ decisions:
session: # long form: run the source, skip its model stage
enabled: true
llm: false
+ session_discovery: true # one broad model pass over new transcript prose
+ discovery: # budget for that one pass, per update
+ max_sessions: 12 # 1-24
+ max_input_tokens: 30000 # 2000-60000
```
Every key is optional. **A config with no `decisions:` block behaves exactly as
-it did before these switches existed**: every source on, model stages on.
+it did before these switches existed**: every source that shipped on is on,
+model stages on. That resolved policy is named `default`. A source added after
+those switches existed (`session_discovery` is the first) stays off until you
+ask for it, so upgrading never starts a model call nobody enabled. The same
+holds for a config that names a preset *and* lists its sources: that list is
+what the preset covered when it was written, so a source added to that preset
+later does not join it retroactively. Re-apply the preset to pick it up.
A source is a bare boolean or a `{enabled, llm}` mapping. The long form only
matters for a source with both a deterministic and a model stage
(`inline_marker`, `adr`, `session`): it keeps the deterministic parse and skips
the model call. A source that is model-only (`git_archaeology`, `pr`,
-`comment`) is skipped entirely when its model stage is off, because running it
-would produce a zero indistinguishable from an empty repository.
+`comment`, `session_discovery`) is skipped entirely when its model stage is
+off, because running it would produce a zero indistinguishable from an empty
+repository.
Unknown keys are reported as warnings rather than discarded, so a typo'd source
name shows up instead of silently reading as a working switch. Retired names
@@ -421,9 +432,10 @@ still loads, it just says which key it ignored.
| Preset | Effect |
|--------|--------|
+| `default` | What a config with no `decisions:` block resolves to. Every long-standing source on, broad discovery off. |
| `off` | No automatic capture. Stored decisions and manual entry keep working. |
| `local_only` | Deterministic capture only. Zero decision-extraction model calls. |
-| `balanced` | The high-signal sources plus session mining; comment archaeology off. |
+| `balanced` | The high-signal sources plus session mining and broad session discovery; comment archaeology off. |
| `full` | Every source, every model stage. |
Editing any individual key after applying a preset drops the `preset` line and
@@ -441,6 +453,8 @@ repowise decision config show # the resolved policy, per source
repowise decision config preset local_only
repowise decision source set comment --off
repowise decision source set adr --no-llm # keep the parse, skip the model
+repowise decision source set session_discovery --on
+repowise decision config discovery --max-sessions 6 --max-input-tokens 12000
repowise decision llm --off
```
@@ -463,6 +477,31 @@ is what makes it govern. Everything stays local: transcripts are read from your
machine, staging lives in `.repowise/sessions/sessions.db`, and only the
distilled decision text about the codebase is stored.
+`session_discovery` is the broad lane beside those gates. Once per update it
+sends the user and assistant prose that update newly read, bounded by
+`discovery.max_sessions` and `discovery.max_input_tokens`, to the model in a
+single call, and asks for durable decisions the gates never surfaced. It reuses
+the transcript read the `session` source already performs, so enabling it does
+not read your transcripts twice.
+
+Every candidate it returns must cite the span ids it rests on, and each cited
+quote is verified against that span's exact text before anything is stored.
+A candidate that cites a span that was not sent, quotes something no span
+says, or names a file the cited turns never touched is rejected and counted,
+never stored. Scope comes from the files those turns' tools touched; the model
+may select among them and may not add one. Everything it produces is a
+candidate: like the deterministic lane it is written `proposed`, and only
+`repowise decision confirm` makes a decision govern.
+
+Prose that does not fit one update's budget is not dropped. It stays queued in
+`.repowise/sessions/sessions.db`, the next update sends it oldest-first, and a
+queued span is never aged out before it is read. A provider failure leaves the
+same prose queued and retries it on the next two updates before retiring it, so
+an outage costs a round rather than the input. Switching the source off leaves
+what is already queued in place; new prose is only captured while the source is
+on, so there is no backfill of what was read while it was off. Discovery reads
+what the `session` source read, so it needs that source on too.
+
Dismissals are sticky: `repowise decision dismiss` keeps the record as a
`dismissed` tombstone, so reindexing never re-proposes the same decision, and
a confirmed (`active`) decision is never walked back to `proposed` by a
diff --git a/packages/cli/src/repowise/cli/commands/decision_config_cmd.py b/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
index bf168cfab..832b3e0c7 100644
--- a/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
@@ -15,6 +15,7 @@ from rich.table import Table
from repowise.cli.helpers import console
from repowise.cli.output import emit_json, format_option, notice_console
from repowise.core.analysis.decisions.policy import (
+ DISCOVERY_BOUNDS,
PRESET_NAMES,
SOURCE_SPECS,
DecisionPolicy,
@@ -101,6 +102,11 @@ def _emit(repo_path: Path, resolution, fmt: str) -> None:
f"[dim]{rt.reason}[/dim]",
)
console.print(table)
+ budget = policy.discovery
+ console.print(
+ f" [dim]Discovery budget: up to {budget.max_sessions} session(s), "
+ f"{budget.max_input_tokens:,} input tokens per update.[/dim]"
+ )
console.print("")
for warning in resolution.warnings:
@@ -162,6 +168,13 @@ def _diff(before: DecisionPolicy, after: DecisionPolicy) -> list[dict[str, str]]
"to": f"enabled={new.enabled if new else '?'} llm={new.llm if new else '?'}",
}
)
+ for key in DISCOVERY_BOUNDS:
+ old_value = getattr(before.discovery, key)
+ new_value = getattr(after.discovery, key)
+ if old_value != new_value:
+ changes.append(
+ {"key": f"discovery.{key}", "from": str(old_value), "to": str(new_value)}
+ )
return changes
@@ -192,7 +205,7 @@ def config_show(path: str | None, fmt: str) -> None:
@click.option("--dry-run", is_flag=True, default=False, help="Show the change; write nothing.")
@format_option()
def config_preset(name: str, path: str | None, dry_run: bool, fmt: str) -> None:
- """Apply a named preset: off, local_only, balanced, full."""
+ """Apply a named preset: default, off, local_only, balanced, full."""
from repowise.cli.commands.decision_cmd import _resolve_decision_repo
from repowise.core.analysis.decisions.policy import preset_policy
@@ -205,6 +218,51 @@ def config_preset(name: str, path: str | None, dry_run: bool, fmt: str) -> None:
# ---------------------------------------------------------------------------
+@config_group.command("discovery")
[email protected]("path", required=False, default=None)
+ "--max-sessions",
+ type=int,
+ default=None,
+ help="Session deltas one broad discovery call may read.",
+)
+ "--max-input-tokens",
+ type=int,
+ default=None,
+ help="Input-token ceiling for one broad discovery call.",
+)
[email protected]("--dry-run", is_flag=True, default=False, help="Show the change; write nothing.")
+@format_option()
+def config_discovery(
+ path: str | None,
+ max_sessions: int | None,
+ max_input_tokens: int | None,
+ dry_run: bool,
+ fmt: str,
+) -> None:
+ """Set the per-update budget for broad session discovery."""
+ from repowise.cli.commands.decision_cmd import _resolve_decision_repo
+
+ repo_path = _resolve_decision_repo(path, fmt)
+ fields = {
+ key: value
+ for key, value in (
+ ("max_sessions", max_sessions),
+ ("max_input_tokens", max_input_tokens),
+ )
+ if value is not None
+ }
+ if not fields:
+ _emit(repo_path, _load(repo_path), fmt)
+ return
+ try:
+ policy = _load(repo_path).policy.with_discovery(**fields)
+ except ValueError as exc:
+ raise click.ClickException(str(exc)) from exc
+ _apply(repo_path, policy, fmt, dry_run)
+
+
@click.group("source")
def source_group() -> None:
"""List and switch individual capture sources."""
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 9bb4e2c5b..bdd86272f 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -1513,7 +1513,11 @@ def run_update(
if decision_policy.source_enabled("session"):
session_provider = provider if decision_policy.llm_allowed("session") else None
session_decisions = run_async(
- mine_session_decisions(repo_path, provider=session_provider)
+ mine_session_decisions(
+ repo_path,
+ provider=session_provider,
+ collect_discovery_spans=decision_policy.llm_allowed("session_discovery"),
+ )
)
if session_decisions and verbose:
promoted_titles = {d.title for d in session_decisions}
@@ -1523,6 +1527,35 @@ def run_update(
if verbose:
console.print(f"[yellow]Session decision mining skipped: {exc}[/yellow]")
+ # The broad lane: at most one model call over the prose the pass above
+ # just read. It runs second because that read is what fills its queue.
+ try:
+ from repowise.core.analysis.decisions.discovery import run_update_discovery
+
+ with cost_tracker.record_as("decision_extraction"):
+ outcome = run_async(
+ run_update_discovery(
+ repo_path,
+ provider=provider,
+ policy=decision_policy,
+ )
+ )
+ session_decisions = [*session_decisions, *outcome.decisions]
+ if outcome.report.status == "failed":
+ degraded.append(f"Session discovery: {outcome.report.reason}")
+ if verbose:
+ funnel = outcome.report
+ console.print(
+ f"Session discovery: {funnel.status}"
+ + (f" ({funnel.reason})" if funnel.reason else "")
+ + f" · {funnel.calls} call(s) · {funnel.candidates_grounded} grounded"
+ + f" · {funnel.spans_deferred} span(s) queued"
+ )
+ except Exception as exc:
+ degraded.append(f"Session discovery: {exc}")
+ if verbose:
+ console.print(f"[yellow]Session discovery skipped: {exc}[/yellow]")
+
# Usage feedback v1: decisions the augment hooks injected into agent
# sessions are judged against those sessions' mined corrections (followed
# -> staleness relaxes, contradicted -> staleness bumps). Pure SQLite over
diff --git a/packages/core/src/repowise/core/analysis/decisions/discovery/__init__.py b/packages/core/src/repowise/core/analysis/decisions/discovery/__init__.py
new file mode 100644
index 000000000..25734afea
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/discovery/__init__.py
@@ -0,0 +1,43 @@
+"""Broad, grounded, one-call decision discovery over transcript deltas.
+
+The deterministic gates in :mod:`repowise.core.sessions.miners.decisions` are
+a high-precision lane and stay exactly as they are. This package is the recall
+lane beside them: one model pass per update over the new session prose those
+gates never show anybody, with every candidate grounded in a quote from a span
+it cites, and nothing it produces able to govern.
+
+Boundaries, in dependency order: :mod:`spans` acquires evidence,
+:mod:`packet` decides what one call sees, :mod:`grounding` decides what
+survives, :mod:`runner` is the only thing that talks to a provider.
+"""
+
+from repowise.core.analysis.decisions.discovery.grounding import (
+ GroundedCandidate,
+ ground_candidates,
+ parse_response,
+)
+from repowise.core.analysis.decisions.discovery.packet import (
+ DiscoveryPacket,
+ build_packet,
+)
+from repowise.core.analysis.decisions.discovery.runner import (
+ DISCOVERY_SOURCE,
+ DiscoveryOutcome,
+ DiscoveryReport,
+ run_update_discovery,
+)
+from repowise.core.analysis.decisions.discovery.spans import ProseSpan, SpanCollector
+
+__all__ = [
+ "DISCOVERY_SOURCE",
+ "DiscoveryOutcome",
+ "DiscoveryPacket",
+ "DiscoveryReport",
+ "GroundedCandidate",
+ "ProseSpan",
+ "SpanCollector",
+ "build_packet",
+ "ground_candidates",
+ "parse_response",
+ "run_update_discovery",
+]
diff --git a/packages/core/src/repowise/core/analysis/decisions/discovery/grounding.py b/packages/core/src/repowise/core/analysis/decisions/discovery/grounding.py
new file mode 100644
index 000000000..08ffa7dc9
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/discovery/grounding.py
@@ -0,0 +1,272 @@
+"""Nothing reaches the store that its cited spans do not say.
+
+The bar is the one the deterministic miner already enforces: a quote must
+verify against the exact text the model was shown, and the claim itself must
+overlap that text. Broad discovery reads far more prose than the gates do, so
+it needs the same gate at a wider mouth, not a looser one.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import dataclass, field
+from typing import Any
+
+from repowise.core.analysis.decisions.discovery.spans import ProseSpan
+from repowise.core.analysis.decisions.provenance import verify_quote
+
+__all__ = [
+ "GroundedCandidate",
+ "GroundingResult",
+ "ground_candidates",
+ "parse_response",
+]
+
+_PUNCT_RE = re.compile(r"[^\w\s]")
+
+#: Claims that say nothing about this repository. A generic maxim costs a
+#: reviewer the same minute as a real decision and teaches nothing.
+_GENERIC_CLAIMS = (
+ "write good code",
+ "follow best practices",
+ "keep the code clean",
+ "add tests",
+ "avoid bugs",
+ "be careful",
+)
+
+#: Below this a "decision" is a fragment, not a rule.
+_MIN_DECISION_CHARS = 20
+
+#: A claim joining independent choices is flagged, never split by machine: a
+#: wrong split files one of them under the other's evidence.
+_SPLIT_MARKERS = ("; ", " and also ", " and, ")
+
+#: Dropped before scoring a claim against its spans. Without this a claim is
+#: carried by its function words: "always deploy to production on fridays"
+#: scores 2/6 on any span containing "to" and "on", which clears a 0.3 gate
+#: while sharing no content with the evidence at all.
+_STOPWORDS = frozenset((
+ "a", "an", "and", "are", "as", "at", "be", "but", "by", "can", "do", "does", "for",
+ "from", "has", "have", "if", "in", "into", "is", "it", "its", "must", "no", "not", "of",
+ "on", "or", "should", "that", "the", "their", "then", "there", "these", "this", "to",
+ "use", "using", "was", "we", "were", "when", "which", "while", "will", "with", "you",
+ "your",
+))
+
+#: Fraction of a claim's content words that must appear in its cited spans.
+_CLAIM_OVERLAP = 0.5
+
+#: Fraction of an evidence quote's tokens that must appear in the cited spans
+#: when it is not an exact substring of them.
+_QUOTE_OVERLAP = 0.9
+
+
+@dataclass(frozen=True, slots=True)
+class GroundedCandidate:
+ """One candidate that survived the gate, with its evidence resolved."""
+
+ title: str
+ decision: str
+ rationale: str
+ kind: str
+ acceptance_basis: str
+ source_quote: str
+ verification: str
+ spans: tuple[ProseSpan, ...]
+ affected_files: tuple[str, ...]
+ needs_split: bool
+
+ @property
+ def session_id(self) -> str | None:
+ return self.spans[0].session_id if self.spans else None
+
+ @property
+ def quotes(self) -> list[str]:
+ return [span.text for span in self.spans]
+
+ def to_structured(self) -> dict[str, Any]:
+ """The staging blob.
+
+ The first six keys are the deterministic lane's field names on purpose:
+ promotion, evidence and confidence read this dict without a second
+ branch for where the candidate came from.
+ """
+ return {
+ "title": self.title,
+ "decision": self.decision,
+ "rationale": self.rationale,
+ "source_quote": self.source_quote,
+ "verification": self.verification,
+ "affected_files": list(self.affected_files),
+ "kind": self.kind,
+ "acceptance_basis": self.acceptance_basis,
+ "needs_split": self.needs_split,
+ "span_ids": [span.span_id for span in self.spans],
+ "discovery": True,
+ }
+
+
+@dataclass(slots=True)
+class GroundingResult:
+ """What one response yielded, and why the rest of it did not."""
+
+ grounded: list[GroundedCandidate] = field(default_factory=list)
+ rejected: dict[str, int] = field(default_factory=dict)
+ returned: int = 0
+ rejected_task_local: int = 0
+ rejected_assistant_only: int = 0
+
+ def reject(self, reason: str) -> None:
+ self.rejected[reason] = self.rejected.get(reason, 0) + 1
+
+
+def parse_response(content: str) -> dict[str, Any] | None:
+ """Parse the model's reply, tolerating fenced or prose-wrapped JSON."""
+ text = (content or "").strip()
+ if text.startswith("```"):
+ text = "\n".join(line for line in text.splitlines() if not line.strip().startswith("```"))
+ try:
+ data = json.loads(text)
+ except json.JSONDecodeError:
+ match = re.search(r"\{.*\}", text, re.DOTALL)
+ if not match:
+ return None
+ try:
+ data = json.loads(match.group())
+ except json.JSONDecodeError:
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def _is_generic(decision: str) -> bool:
+ low = decision.lower()
+ return len(decision) < _MIN_DECISION_CHARS or any(g in low for g in _GENERIC_CLAIMS)
+
+
+def _claim_overlaps(decision: str, plain_source: str) -> bool:
+ """Whether the claim's content words are actually present in the evidence."""
+ words = {w for w in _PUNCT_RE.sub(" ", decision).lower().split() if w not in _STOPWORDS}
+ if not words:
+ return False
+ source = set(plain_source.lower().split())
+ return len(words & source) / len(words) >= _CLAIM_OVERLAP
+
+
+def _as_count(value: Any) -> int:
+ return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else 0
+
+
+def ground_candidates(
+ payload: dict[str, Any] | None,
+ packet_spans: tuple[ProseSpan, ...],
+ known_paths: tuple[str, ...] = (),
+) -> GroundingResult:
+ """Gate every returned candidate against the spans it claims to rest on."""
+ result = GroundingResult()
+ if payload is None:
+ result.reject("malformed")
+ return result
+ result.rejected_task_local = _as_count(payload.get("rejected_task_local"))
+ result.rejected_assistant_only = _as_count(payload.get("rejected_assistant_only"))
+
+ items = payload.get("candidates")
+ if not isinstance(items, list):
+ result.reject("malformed")
+ return result
+
+ by_id = {span.span_id: span for span in packet_spans}
+ selectable = set(known_paths) or {path for span in packet_spans for path in span.files}
+
+ for item in items:
+ result.returned += 1
+ if not isinstance(item, dict):
+ result.reject("malformed")
+ continue
+ candidate = _ground_one(item, by_id, selectable, result)
+ if candidate is not None:
+ result.grounded.append(candidate)
+ return result
+
+
+def _ground_one(
+ item: dict[str, Any],
+ by_id: dict[str, ProseSpan],
+ known_paths: set[str],
+ result: GroundingResult,
+) -> GroundedCandidate | None:
+ title = str(item.get("title") or "").strip()
+ decision = str(item.get("decision") or "").strip()
+ if not title or not decision:
+ result.reject("empty_claim")
+ return None
+ if _is_generic(decision):
+ result.reject("generic_claim")
+ return None
+ if str(item.get("durability") or "durable").strip().lower() != "durable":
+ result.reject("task_local")
+ return None
+
+ raw_ids = item.get("span_ids")
+ ids = list(dict.fromkeys(str(i) for i in raw_ids)) if isinstance(raw_ids, list) else []
+ spans = tuple(by_id[i] for i in ids if i in by_id)
+ # An invented span id is the tell that the rest of the object was invented
+ # too, so the candidate dies rather than falling back to whichever ids did
+ # resolve.
+ if not spans or len(spans) != len(ids):
+ result.reject("unknown_span")
+ return None
+
+ source_text = "\n".join(span.text for span in spans)
+ quote = str(item.get("evidence_quote") or "").strip()
+ # Near-verbatim, not the deterministic lane's 0.6. That lane's excerpts are
+ # the few sentences its gates already matched, so a loose bar is scored
+ # against a small target; this lane shows the model thousands of words,
+ # where 60% token overlap with *some* part of them is not evidence of
+ # anything. Exact-substring alone was measured rejecting 4 of 7 real
+ # candidates over reflow and dropped articles, which is the wrong trade for
+ # a lane that exists to recover recall, so a quote that is all-but-verbatim
+ # still counts and is recorded as `fuzzy` for confidence to discount.
+ verification = verify_quote(quote, source_text, fuzzy_threshold=_QUOTE_OVERLAP)
+ if verification == "unverified":
+ result.reject("unverified_quote")
+ return None
+
+ plain_source = _PUNCT_RE.sub(" ", source_text)
+ if not _claim_overlaps(decision, plain_source):
+ result.reject("ungrounded_claim")
+ return None
+
+ rationale = str(item.get("rationale") or "").strip()
+ if rationale and (
+ verify_quote(_PUNCT_RE.sub(" ", rationale), plain_source, fuzzy_threshold=0.5)
+ == "unverified"
+ ):
+ rationale = "" # never an invented why; the candidate itself still stands
+
+ # Scope is what the model selected from the resolved known-node set, and
+ # nothing else. A path it wrote down that no cited turn touched is dropped;
+ # so is a fallback to whatever files happened to be open, which is how a
+ # repository-wide rule ends up pinned to an unrelated file. Selecting
+ # nothing is an honest repository-wide claim.
+ claimed = item.get("paths")
+ files = (
+ [p for p in claimed if isinstance(p, str) and p in known_paths]
+ if isinstance(claimed, list)
+ else []
+ )
+
+ low = decision.lower()
+ return GroundedCandidate(
+ title=title,
+ decision=decision,
+ rationale=rationale,
+ kind=str(item.get("kind") or "").strip().lower(),
+ acceptance_basis=str(item.get("acceptance_basis") or "").strip().lower(),
+ source_quote=quote,
+ verification=verification,
+ spans=spans,
+ affected_files=tuple(dict.fromkeys(files)),
+ needs_split=any(marker in low for marker in _SPLIT_MARKERS),
+ )
diff --git a/packages/core/src/repowise/core/analysis/decisions/discovery/packet.py b/packages/core/src/repowise/core/analysis/decisions/discovery/packet.py
new file mode 100644
index 000000000..dc3caa345
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/discovery/packet.py
@@ -0,0 +1,215 @@
+"""One packet per update: which spans go in front of the model, and how.
+
+The packet is whole sessions of new prose, oldest first, bounded by a session
+count and an input-token budget. It is deliberately not a cue-word summary:
+the ablation behind this design recovered about 5 of 16 themes for 40% of the
+tokens, so compaction saves the wrong thing.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+from repowise.core.analysis.decisions.discovery.spans import ProseSpan
+
+__all__ = [
+ "PROMPT_TEMPLATE",
+ "SYSTEM_PROMPT",
+ "DiscoveryPacket",
+ "build_packet",
+ "packet_tokens",
+]
+
+#: Characters per token. Deliberately not
+#: :func:`repowise.core.distill.budget.estimate_tokens`, which floors at 4 on
+#: purpose because every distill savings figure is reported on that one scale.
+#: This number bounds a request rather than reporting on one, so it rounds the
+#: other way: transcript prose full of paths, punctuation and code fragments
+#: tokenizes well below the prose rule of thumb, and 4 undercounted a measured
+#: packet by 21%.
+_CHARS_PER_TOKEN = 3
+
+#: Room the instructions and the trailing known-paths list take, in tokens.
+_OVERHEAD_TOKENS = 900
+
+#: What one span costs beyond its text: the id, role and file header around it.
+#: Charged per span because a packet of many short turns is mostly header, and
+#: pricing only the bodies is what overran the budget.
+_SPAN_OVERHEAD_TOKENS = 16
+
+
+def packet_tokens(text: str) -> int:
+ """A pessimistic token ceiling for *text*, for bounding one request."""
+ return (len(text) + _CHARS_PER_TOKEN - 1) // _CHARS_PER_TOKEN
+
+
+SYSTEM_PROMPT = (
+ "You are auditing coding-agent sessions for durable repository decisions. "
+ "Precision matters more than recall. A durable decision is a constraint, "
+ "chosen design, tradeoff, rejected approach, or operating rule that should "
+ "affect future work in this repository. Do not extract the user's immediate "
+ "task, status updates, generic engineering advice, assistant suggestions "
+ "that were never accepted, or temporary branch and worktree instructions. "
+ "Return only valid JSON. Never invent rationale that is not in the spans."
+)
+
+PROMPT_TEMPLATE = """\
+Below are numbered prose spans from recent coding-agent sessions in one \
+repository. Each span is one turn, tagged with its span id and the files that \
+turn's tools touched.
+
+{spans_block}
+
+Known file paths for this packet (you may cite these and no others):
+{paths_block}
+
+Return every durable decision the spans establish, as a JSON object:
+{{
+ "candidates": [
+ {{
+ "title": "short imperative title",
+ "decision": "the rule or choice, grounded in the cited spans",
+ "rationale": "why, only if a span states it; empty string otherwise",
+ "kind": "constraint | design_choice | tradeoff | rejected_approach | operating_rule",
+ "durability": "durable | task_local",
+ "acceptance_basis": "user_explicit | user_correction | implemented_and_validated",
+ "evidence_quote": "one sentence copied verbatim from a cited span",
+ "span_ids": ["the span ids this rests on"],
+ "paths": ["only paths from the known list above"]
+ }}
+ ],
+ "rejected_task_local": 0,
+ "rejected_assistant_only": 0
+}}
+
+Rules:
+- One claim per candidate. If a moment settles two independent things, return \
+two candidates.
+- Reject anything the assistant merely proposed and the user never accepted, \
+anything that was only a plan for that task, and anything whose scope ends \
+with the session. Count those in the rejected counters.
+- The evidence quote must appear verbatim in one of the spans you cite.
+- Do not invent file paths. An empty "paths" list is correct when the spans \
+name none.
+- Return {{"candidates": [], "rejected_task_local": 0, \
+"rejected_assistant_only": 0}} when nothing qualifies.
+"""
+
+
+@dataclass(frozen=True, slots=True)
+class DiscoveryPacket:
+ """The spans one call will see, plus what it is allowed to cite."""
+
+ spans: tuple[ProseSpan, ...]
+ known_paths: tuple[str, ...]
+ prompt: str
+ estimated_tokens: int
+ #: Sessions represented, for the funnel counters.
+ sessions: tuple[str, ...] = field(default=())
+
+ def __bool__(self) -> bool:
+ return bool(self.spans)
+
+
+def _span_cost(span: ProseSpan) -> int:
+ return (
+ packet_tokens(span.text)
+ + packet_tokens(", ".join(span.files[:8]))
+ + _SPAN_OVERHEAD_TOKENS
+ )
+
+
+def _spans_block(spans: tuple[ProseSpan, ...]) -> str:
+ parts: list[str] = []
+ current: str | None = None
+ for span in spans:
+ if span.session_id != current:
+ current = span.session_id
+ parts.append(f"\n===== session {current} =====")
+ files = ", ".join(span.files[:8]) or "(none)"
+ parts.append(f"[span {span.span_id}] {span.role} · files: {files}\n{span.text}")
+ return "\n".join(parts)
+
+
+def build_packet(
+ spans: list[ProseSpan],
+ *,
+ max_sessions: int,
+ max_input_tokens: int,
+) -> DiscoveryPacket:
+ """Take whole sessions off the front of the queue until a bound is hit.
+
+ Sessions are admitted whole so a candidate is never grounded in half a
+ conversation. A session too large to fit on its own is admitted anyway,
+ span-truncated, rather than wedging the queue head forever.
+ """
+ budget = max(0, max_input_tokens - _OVERHEAD_TOKENS)
+ chosen: list[ProseSpan] = []
+ sessions: list[str] = []
+ spent = 0
+ by_session: dict[str, list[ProseSpan]] = {}
+ for span in spans:
+ by_session.setdefault(span.session_id, []).append(span)
+
+ for session_id, session_spans in by_session.items():
+ if len(sessions) >= max_sessions:
+ break
+ cost = sum(_span_cost(span) for span in session_spans)
+ if spent and spent + cost > budget:
+ break
+ if not spent and cost > budget:
+ session_spans = _fit(session_spans, budget)
+ cost = sum(_span_cost(span) for span in session_spans)
+ sessions.append(session_id)
+ chosen.extend(session_spans)
+ spent += cost
+
+ # The per-session estimate is additive and the rendered prompt is not, so
+ # the packet is measured and trimmed until it fits. The budget is a ceiling
+ # the user set, not a target to land near.
+ while True:
+ packet = _render(tuple(chosen), tuple(sessions))
+ if packet.estimated_tokens <= max_input_tokens or len(chosen) <= 1:
+ # One span always survives, even over budget. Collection clips a
+ # span to _SPAN_CHARS, so in practice it fits; refusing to send it
+ # would wedge the queue head on the one item nothing can drain.
+ return packet
+ if len(sessions) > 1:
+ dropped = sessions.pop()
+ chosen = [span for span in chosen if span.session_id != dropped]
+ else:
+ chosen.pop()
+
+
+def _render(spans: tuple[ProseSpan, ...], sessions: tuple[str, ...]) -> DiscoveryPacket:
+ """One packet, with the known-node set its spans are allowed to cite.
+
+ That set is the files those turns' tools actually touched, already
+ repo-relative and repo-scoped at collection. The model may select from it;
+ it may not name a path of its own.
+ """
+ cited = sorted({path for span in spans for path in span.files})
+ prompt = PROMPT_TEMPLATE.format(
+ spans_block=_spans_block(spans),
+ paths_block="\n".join(f"- {path}" for path in cited) or "(none)",
+ )
+ return DiscoveryPacket(
+ spans=spans,
+ known_paths=tuple(cited),
+ prompt=prompt,
+ estimated_tokens=packet_tokens(prompt),
+ sessions=sessions,
+ )
+
+
+def _fit(spans: list[ProseSpan], budget: int) -> list[ProseSpan]:
+ """The longest prefix of one session's spans that fits *budget*."""
+ kept: list[ProseSpan] = []
+ spent = 0
+ for span in spans:
+ cost = _span_cost(span)
+ if kept and spent + cost > budget:
+ break
+ kept.append(span)
+ spent += cost
+ return kept
diff --git a/packages/core/src/repowise/core/analysis/decisions/discovery/runner.py b/packages/core/src/repowise/core/analysis/decisions/discovery/runner.py
new file mode 100644
index 000000000..66532ee8a
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/discovery/runner.py
@@ -0,0 +1,303 @@
+"""The one broad discovery call an update is allowed to make.
+
+Everything here is arranged so that "at most one call" is a property of the
+code rather than a promise: there is exactly one ``provider.generate`` in this
+module, it is not in a loop, and every path that must not call reaches its
+``return`` above it carrying the reason it stopped.
+
+Output is review-only. Candidates land in the session staging store and reach
+``decision_records`` through the same promotion path as the deterministic
+lane, which writes ``proposed`` and nothing else.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+from repowise.core.analysis.decisions.discovery.grounding import (
+ GroundedCandidate,
+ ground_candidates,
+ parse_response,
+)
+from repowise.core.analysis.decisions.discovery.packet import (
+ SYSTEM_PROMPT,
+ build_packet,
+)
+from repowise.core.analysis.decisions.discovery.spans import ProseSpan
+from repowise.core.analysis.decisions.policy import DecisionPolicy
+from repowise.core.sessions.staging import DISCOVERY_KIND, SessionStagingStore
+
+logger = structlog.get_logger(__name__)
+
+__all__ = ["DISCOVERY_SOURCE", "DiscoveryOutcome", "DiscoveryReport", "run_update_discovery"]
+
+#: The policy registry key. It names a *capture lane*, not a stored record
+#: source: promoted candidates keep ``source="session"`` because that is what
+#: the ranking ladder and every stored row already mean by a transcript.
+DISCOVERY_SOURCE = "session_discovery"
+
+#: Output ceiling for one call. The probe's 16-candidate response spent about
+#: 5,000 tokens, and a truncated reply is unparseable rather than partial.
+_MAX_OUTPUT_TOKENS = 6_000
+
+_TEMPERATURE = 0.1
+
+#: Spans read off the queue before the budget is applied. A ceiling on the
+#: query, not on the packet: the packet's own bounds decide what is sent.
+_QUEUE_READ_LIMIT = 2_000
+
+
+@dataclass(slots=True)
+class DiscoveryReport:
+ """The funnel for one update, with no transcript text in it.
+
+ ``status`` is the same three-way vocabulary the index reporting already
+ uses for every other source: it ran, it was not run and here is why, or it
+ failed. A zero from a source that is switched off must never read like a
+ zero from a repository with nothing to find.
+ """
+
+ status: str = "not_run"
+ reason: str = ""
+ calls: int = 0
+ sessions_considered: int = 0
+ spans_considered: int = 0
+ spans_deferred: int = 0
+ spans_retired: int = 0
+ candidates_returned: int = 0
+ candidates_grounded: int = 0
+ candidates_new: int = 0
+ candidates_accreted: int = 0
+ rejected: dict[str, int] = field(default_factory=dict)
+ rejected_task_local: int = 0
+ rejected_assistant_only: int = 0
+ input_tokens: int = 0
+ output_tokens: int = 0
+ latency_ms: int = 0
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "status": self.status,
+ "reason": self.reason,
+ "calls": self.calls,
+ "sessions_considered": self.sessions_considered,
+ "spans_considered": self.spans_considered,
+ "spans_deferred": self.spans_deferred,
+ "spans_retired": self.spans_retired,
+ "candidates_returned": self.candidates_returned,
+ "candidates_grounded": self.candidates_grounded,
+ "candidates_new": self.candidates_new,
+ "candidates_accreted": self.candidates_accreted,
+ "rejected": dict(self.rejected),
+ "rejected_task_local": self.rejected_task_local,
+ "rejected_assistant_only": self.rejected_assistant_only,
+ "input_tokens": self.input_tokens,
+ "output_tokens": self.output_tokens,
+ "latency_ms": self.latency_ms,
+ }
+
+
+@dataclass(slots=True)
+class DiscoveryOutcome:
+ """The report, plus whatever this pass qualified for promotion."""
+
+ report: DiscoveryReport
+ decisions: list[Any] = field(default_factory=list)
+
+
+def candidate_hash(candidate: GroundedCandidate) -> str:
+ """Conservative identity: the claim, plus the evidence it rests on.
+
+ Two extractions of the same claim from the same spans are one candidate;
+ the same claim from different evidence is a second observation of it, which
+ is what accretes review priority through the staging store's title key.
+ """
+ spans = "|".join(sorted(span.span_id for span in candidate.spans))
+ claim = " ".join(candidate.decision.lower().split())
+ return hashlib.sha256(f"{DISCOVERY_KIND}|{claim}|{spans}".encode()).hexdigest()[:16]
+
+
+async def run_update_discovery(
+ repo_path: Path,
+ *,
+ provider: Any | None,
+ policy: DecisionPolicy,
+ now: float | None = None,
+) -> DiscoveryOutcome:
+ """Make zero or one broad discovery call over this update's new prose.
+
+ Runs after the deterministic miner, which is what filled the span queue
+ during its single transcript read. Everything it persists is a candidate.
+ """
+ report = DiscoveryReport()
+ if not policy.enabled:
+ report.reason = "Decision capture is off for this repository."
+ return DiscoveryOutcome(report)
+ if not policy.source_enabled(DISCOVERY_SOURCE):
+ report.reason = "Broad session discovery is switched off."
+ return DiscoveryOutcome(report)
+ if not policy.llm_allowed(DISCOVERY_SOURCE):
+ report.reason = "Decision LLM extraction is off, and this source has no local stage."
+ return DiscoveryOutcome(report)
+ if provider is None:
+ report.status = "skipped_no_provider"
+ report.reason = "No LLM provider is configured."
+ return DiscoveryOutcome(report)
+
+ repo_root = Path(repo_path).resolve()
+ store = SessionStagingStore.open_default(repo_root)
+ try:
+ return await _discover(store, repo_root, provider, policy, report, now)
+ finally:
+ store.close()
+
+
+async def _discover(
+ store: SessionStagingStore,
+ repo_root: Path,
+ provider: Any,
+ policy: DecisionPolicy,
+ report: DiscoveryReport,
+ now: float | None,
+) -> DiscoveryOutcome:
+ queued = store.pending_discovery_spans(_QUEUE_READ_LIMIT)
+ pending_total = store.pending_discovery_count()
+ if not queued:
+ report.status = "empty"
+ report.reason = (
+ "No new session prose since the last update."
+ if policy.source_enabled("session")
+ else "The agent-sessions source that reads transcripts is switched off."
+ )
+ return DiscoveryOutcome(report)
+
+ packet = build_packet(
+ [ProseSpan.from_row(row) for row in queued],
+ max_sessions=policy.discovery.max_sessions,
+ max_input_tokens=policy.discovery.max_input_tokens,
+ )
+ if not packet:
+ # Unreachable while build_packet guarantees one surviving span, and
+ # kept because the failure it guards is a permanently wedged queue:
+ # returning here consumes nothing, so the same head would be rebuilt
+ # into the same empty packet on every future update.
+ report.status = "empty"
+ report.reason = "No session prose fit the discovery budget."
+ return DiscoveryOutcome(report)
+
+ report.sessions_considered = len(packet.sessions)
+ report.spans_considered = len(packet.spans)
+ report.spans_deferred = max(0, pending_total - len(packet.spans))
+ span_ids = [span.span_id for span in packet.spans]
+
+ started = time.monotonic()
+ try:
+ response = await provider.generate(
+ SYSTEM_PROMPT,
+ packet.prompt,
+ max_tokens=_MAX_OUTPUT_TOKENS,
+ temperature=_TEMPERATURE,
+ )
+ except Exception as exc:
+ # Transient by assumption: the spans stay queued and the next update
+ # retries them, bounded, so a provider outage costs a round rather
+ # than the input.
+ report.status = "failed"
+ report.reason = str(exc)
+ report.spans_retired = store.bump_discovery_attempts(span_ids, now=now)
+ report.spans_deferred = pending_total - report.spans_retired
+ store.commit()
+ logger.warning("decision_discovery.llm_failed", error=str(exc))
+ return DiscoveryOutcome(report)
+
+ report.calls = 1
+ report.latency_ms = int((time.monotonic() - started) * 1000)
+ report.input_tokens = getattr(response, "input_tokens", 0) or 0
+ report.output_tokens = getattr(response, "output_tokens", 0) or 0
+
+ grounding = ground_candidates(
+ parse_response(response.content), packet.spans, packet.known_paths
+ )
+ report.candidates_returned = grounding.returned
+ report.candidates_grounded = len(grounding.grounded)
+ report.rejected = dict(grounding.rejected)
+ report.rejected_task_local = grounding.rejected_task_local
+ report.rejected_assistant_only = grounding.rejected_assistant_only
+ report.status = "ran" if grounding.grounded else "empty"
+ if report.status == "empty":
+ report.reason = "The pass found no grounded candidate in this update's prose."
+
+ # The spans were read, so they are spent whatever the model made of them.
+ # A candidate the gate rejected is a permanent rejection, not a retry.
+ store.mark_discovery_consumed(span_ids, now=now)
+ _persist(store, grounding.grounded, report, now)
+ store.commit()
+
+ decisions = _promote(store, repo_root, now)
+ store.commit()
+
+ logger.info("decision_discovery.done", **report.to_dict())
+ return DiscoveryOutcome(report, decisions)
+
+
+def _persist(
+ store: SessionStagingStore,
+ candidates: list[GroundedCandidate],
+ report: DiscoveryReport,
+ now: float | None,
+) -> None:
+ for candidate in candidates:
+ # Accretion is a property of the claim, not of the evidence: spans are
+ # spent after one packet, so the raw hash is always new and only the
+ # title key can say this claim has been seen before.
+ if store.structured_exists(candidate.title, DISCOVERY_KIND):
+ report.candidates_accreted += 1
+ else:
+ report.candidates_new += 1
+ raw_hash = candidate_hash(candidate)
+ store.add_raw(
+ hash_=raw_hash,
+ kind=DISCOVERY_KIND,
+ quotes=candidate.quotes,
+ files=list(candidate.affected_files),
+ session_id=candidate.session_id,
+ now=now,
+ )
+ store.upsert_structured(
+ raw_hash,
+ kind=DISCOVERY_KIND,
+ lane=DISCOVERY_KIND,
+ title=candidate.title,
+ structured=candidate.to_structured(),
+ quotes=candidate.quotes,
+ files=list(candidate.affected_files),
+ session_id=candidate.session_id,
+ now=now,
+ )
+
+
+def _promote(store: SessionStagingStore, repo_root: Path, now: float | None) -> list[Any]:
+ """Emit newly qualified discovery rows through the shared promotion path.
+
+ Restricted to this lane's own rows: the deterministic miner runs its own
+ promotion pass and owns its backlog, and a discovery run must not emit a
+ gate hit under the discovery lane's name because it happened to go second.
+
+ Imported here rather than at module scope: the miner imports this package
+ to collect spans, so a top-level import back into it would be a cycle.
+ """
+ from repowise.core.sessions.miners.decisions import promotion_decisions
+
+ decisions: list[Any] = []
+ for row in store.promotable():
+ if row["kind"] != DISCOVERY_KIND:
+ continue
+ decisions.extend(promotion_decisions(row, repo_root))
+ store.mark_emitted(row["key"], observations=row["observations"], now=now)
+ return decisions
diff --git a/packages/core/src/repowise/core/analysis/decisions/discovery/spans.py b/packages/core/src/repowise/core/analysis/decisions/discovery/spans.py
new file mode 100644
index 000000000..ce26ec1dc
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/decisions/discovery/spans.py
@@ -0,0 +1,156 @@
+"""Prose spans: the input the broad discovery call is grounded in.
+
+A span is one user or assistant turn from a transcript delta, clipped, given a
+stable id, and queued in the session staging store. Spans are collected by
+teeing the event stream the decision miner is already reading, never by a
+second transcript read: the cursor advances as that read happens, so a second
+pass would find nothing left.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from collections import deque
+from collections.abc import Iterable, Iterator
+from dataclasses import dataclass
+from pathlib import Path
+
+from repowise.core.sessions.events import (
+ Event,
+ event_files,
+ is_prose_user_text,
+ relative_files,
+)
+from repowise.core.sessions.staging import SessionStagingStore
+
+__all__ = ["ProseSpan", "SpanCollector", "span_id_for"]
+
+#: Characters kept per span. Long assistant turns are head/tail clipped rather
+#: than truncated: the reasoning that opens a turn and the conclusion that
+#: closes it are both load-bearing, and the middle is usually the diff.
+_SPAN_CHARS = 1_600
+_SPAN_HEAD = 1_100
+_SPAN_TAIL = 400
+_ELLIPSIS = "\n[...]\n"
+
+#: A turn shorter than this carries no decision, only acknowledgement.
+_MIN_SPAN_CHARS = 40
+
+#: Spans kept per session per update. One very long session must not crowd
+#: every other session out of the queue head.
+_MAX_SPANS_PER_SESSION = 60
+
+#: Recently touched files offered alongside a span. A prose turn almost never
+#: carries tool inputs of its own, so pricing scope on the turn alone leaves
+#: every candidate repository-wide; this is the menu the model may select
+#: from. It is deliberately only a menu: nothing here becomes scope unless the
+#: model picks it, so an unrelated file that happened to be open cannot pin a
+#: repository-wide rule to itself.
+_NEARBY_FILES = 6
+
+
+def _clip(text: str) -> str:
+ text = text.strip()
+ if len(text) <= _SPAN_CHARS:
+ return text
+ return text[:_SPAN_HEAD] + _ELLIPSIS + text[-_SPAN_TAIL:]
+
+
+def span_id_for(session_id: str, ts: float | None, text: str) -> str:
+ """A stable id for one span, so a re-read stages it exactly once."""
+ payload = f"{session_id}|{ts or 0.0:.3f}|{text}"
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
+
+
+@dataclass(frozen=True, slots=True)
+class ProseSpan:
+ """One clipped transcript turn, as the packet and the grounder see it."""
+
+ span_id: str
+ session_id: str
+ role: str
+ text: str
+ files: tuple[str, ...]
+ ts: float | None
+
+ @classmethod
+ def from_row(cls, row: dict) -> ProseSpan:
+ return cls(
+ span_id=row["span_id"],
+ session_id=row["session_id"],
+ role=row["role"],
+ text=row["text"],
+ files=tuple(row["files"]),
+ ts=row["ts"],
+ )
+
+
+class SpanCollector:
+ """A pass-through tee that queues eligible prose as it streams by.
+
+ Writes straight into the staging store rather than accumulating in memory:
+ the queue is the durable backlog, and it commits with the cursors that
+ said those bytes were read.
+ """
+
+ def __init__(
+ self,
+ store: SessionStagingStore,
+ repo_root: Path,
+ *,
+ now: float | None = None,
+ ) -> None:
+ self._store = store
+ self._repo_root = repo_root
+ self._repo_prefix = str(repo_root).lower().rstrip("\\/")
+ self._now = now
+ self._per_session: dict[str, int] = {}
+ self._nearby: dict[str, deque[str]] = {}
+ self.queued = 0
+
+ def observe(self, events: Iterable[Event]) -> Iterator[Event]:
+ for event in events:
+ self._maybe_queue(event)
+ yield event
+
+ def _maybe_queue(self, event: Event) -> None:
+ session_id = event.session_id
+ if not session_id:
+ return
+ # Same repository scoping as the deterministic gates: one checkout can
+ # host nested repositories, and a span from one must not be evidence
+ # for another.
+ cwd = (event.cwd or "").lower().rstrip("\\/")
+ if cwd and not cwd.startswith(self._repo_prefix):
+ return
+ nearby = self._nearby.setdefault(session_id, deque(maxlen=_NEARBY_FILES))
+ for path in relative_files(event_files(event), self._repo_root):
+ if path in nearby:
+ nearby.remove(path)
+ nearby.append(path)
+
+ if event.kind == "user":
+ if not is_prose_user_text(event):
+ return
+ elif event.kind == "assistant":
+ if event.sidechain or event.is_meta or event.is_compact_summary:
+ return
+ else:
+ return
+ text = _clip(event.text)
+ if len(text) < _MIN_SPAN_CHARS:
+ return
+ seen = self._per_session.get(session_id, 0)
+ if seen >= _MAX_SPANS_PER_SESSION:
+ return
+ self._per_session[session_id] = seen + 1
+ if self._store.add_discovery_span(
+ span_id=span_id_for(session_id, event.ts, text),
+ session_id=session_id,
+ role=event.kind,
+ text=text,
+ files=list(nearby),
+ ts=event.ts,
+ now=self._now,
+ ):
+ self.queued += 1
diff --git a/packages/core/src/repowise/core/analysis/decisions/policy.py b/packages/core/src/repowise/core/analysis/decisions/policy.py
index cf94a7753..44bf841d0 100644
--- a/packages/core/src/repowise/core/analysis/decisions/policy.py
+++ b/packages/core/src/repowise/core/analysis/decisions/policy.py
@@ -20,11 +20,13 @@ from repowise.core.analysis.decisions.provenance import RETIRED_SOURCES
__all__ = [
"CAPTURE_SOURCE_KEYS",
+ "DISCOVERY_BOUNDS",
"INDEX_SOURCE_KEYS",
"PRESETS",
"PRESET_NAMES",
"SOURCE_SPECS",
"DecisionPolicy",
+ "DiscoveryBudget",
"PolicyResolution",
"SourceRuntime",
"SourceSetting",
@@ -123,6 +125,15 @@ SOURCE_SPECS: tuple[SourceSpec, ...] = (
authority="machine",
default_enabled=True,
),
+ SourceSpec(
+ key="session_discovery",
+ label="Session discovery",
+ description="One broad model pass over new transcript prose each update.",
+ deterministic=False,
+ llm=True,
+ authority="machine",
+ default_enabled=False,
+ ),
SourceSpec(
key="cli",
label="Manual entry",
@@ -154,6 +165,33 @@ INDEX_SOURCE_KEYS: tuple[str, ...] = (
)
+#: Inclusive ``(min, max, default)`` for each broad-discovery budget knob.
+#: The upper bounds are what the probe actually measured at: roughly 8-12
+#: session deltas and about 30,000 input tokens for one call. Bounds are
+#: enforced on resolution so a typo'd config costs a warning, not a bill.
+DISCOVERY_BOUNDS: dict[str, tuple[int, int, int]] = {
+ "max_sessions": (1, 24, 12),
+ "max_input_tokens": (2_000, 60_000, 30_000),
+}
+
+
+@dataclass(frozen=True, slots=True)
+class DiscoveryBudget:
+ """Per-update ceiling on the one broad session-discovery call."""
+
+ max_sessions: int = DISCOVERY_BOUNDS["max_sessions"][2]
+ max_input_tokens: int = DISCOVERY_BOUNDS["max_input_tokens"][2]
+
+ def to_dict(self) -> dict[str, int]:
+ return {
+ "max_sessions": self.max_sessions,
+ "max_input_tokens": self.max_input_tokens,
+ }
+
+
+_DEFAULT_DISCOVERY = DiscoveryBudget()
+
+
@dataclass(frozen=True, slots=True)
class SourceSetting:
"""Per-source configuration, already merged with defaults."""
@@ -178,6 +216,11 @@ _OFF = SourceSetting(enabled=False, llm=False)
#: Named conveniences over the same policy. A preset is only a way to write
#: several settings at once; nothing downstream branches on the preset name.
PRESETS: dict[str, dict[str, Any]] = {
+ "default": {
+ "enabled": True,
+ "llm": True,
+ "sources": _preset(),
+ },
"off": {
"enabled": False,
"llm": True,
@@ -198,7 +241,7 @@ PRESETS: dict[str, dict[str, Any]] = {
"balanced": {
"enabled": True,
"llm": True,
- "sources": _preset(comment=_OFF),
+ "sources": _preset(comment=_OFF, session_discovery=_ON),
},
"full": {
"enabled": True,
@@ -209,12 +252,14 @@ PRESETS: dict[str, dict[str, Any]] = {
PRESET_NAMES: tuple[str, ...] = tuple(PRESETS)
-#: What an absent ``decisions:`` block resolves to. Deliberately every source
-#: on with the model enabled, because that is what a repo indexed before this
-#: module existed already did, and a config-less repo must not change behavior
-#: on upgrade. New repos pick a preset explicitly instead of inheriting a
-#: different hidden default.
-_LEGACY_DEFAULT = PRESETS["full"]
+#: What an absent ``decisions:`` block resolves to: every source whose spec
+#: says it shipped on, with the model enabled, because that is what a repo
+#: indexed before this module existed already did and a config-less repo must
+#: not change behavior on upgrade. Deliberately *not* ``full``: ``full`` means
+#: every source there is, so a source added later joins it, and reusing it here
+#: would switch that source on for every repository that never asked for it.
+#: New repos pick a preset explicitly instead of inheriting a hidden default.
+_LEGACY_DEFAULT = PRESETS["default"]
@dataclass(frozen=True, slots=True)
@@ -256,6 +301,7 @@ class DecisionPolicy:
enabled: bool
llm: bool
sources: dict[str, SourceSetting]
+ discovery: DiscoveryBudget = _DEFAULT_DISCOVERY
# -- queries ---------------------------------------------------------
@@ -312,6 +358,7 @@ class DecisionPolicy:
self.enabled == spec["enabled"]
and self.llm == spec["llm"]
and self.sources == spec["sources"]
+ and self.discovery == _DEFAULT_DISCOVERY
):
return name
return "custom"
@@ -386,7 +433,14 @@ class DecisionPolicy:
sources[spec.key] = setting.enabled
else:
sources[spec.key] = {"enabled": setting.enabled, "llm": setting.llm}
- return {"enabled": self.enabled, "llm": self.llm, "sources": sources}
+ block: dict[str, Any] = {
+ "enabled": self.enabled,
+ "llm": self.llm,
+ "sources": sources,
+ }
+ if self.discovery != _DEFAULT_DISCOVERY:
+ block["discovery"] = self.discovery.to_dict()
+ return block
def to_dict(self, *, provider_available: bool = True) -> dict[str, Any]:
"""The JSON payload shared by ``decision config show`` and the API."""
@@ -394,6 +448,7 @@ class DecisionPolicy:
"enabled": self.enabled,
"llm": self.llm,
"preset": self.preset_name(),
+ "discovery": self.discovery.to_dict(),
"sources": [rt.to_dict() for rt in self.runtime(provider_available=provider_available)],
}
@@ -414,6 +469,14 @@ class DecisionPolicy:
sources[key] = merged
return replace(self, sources=sources)
+ def with_discovery(self, **fields: int) -> DecisionPolicy:
+ """A copy with the named discovery budget fields replaced."""
+ for name, value in fields.items():
+ low, high, _ = DISCOVERY_BOUNDS[name]
+ if not low <= value <= high:
+ raise ValueError(f"decisions.discovery.{name} must be between {low} and {high}")
+ return replace(self, discovery=replace(self.discovery, **fields))
+
def with_llm(self, value: bool) -> DecisionPolicy:
return replace(self, llm=value)
@@ -433,6 +496,30 @@ class PolicyResolution:
legacy_keys: tuple[str, ...] = ()
+def _resolve_discovery(raw: Any, warnings: list[str]) -> DiscoveryBudget:
+ """Bounds-checked discovery budget from the ``decisions.discovery`` block."""
+ if raw is None:
+ return _DEFAULT_DISCOVERY
+ if not isinstance(raw, dict):
+ warnings.append("`decisions.discovery:` is not a mapping; ignoring it.")
+ return _DEFAULT_DISCOVERY
+ fields: dict[str, int] = {}
+ for name, (low, high, default) in DISCOVERY_BOUNDS.items():
+ value = raw.get(name, default)
+ if isinstance(value, bool) or not isinstance(value, int):
+ warnings.append(f"`decisions.discovery.{name}` must be an integer; using {default}.")
+ value = default
+ elif not low <= value <= high:
+ warnings.append(
+ f"`decisions.discovery.{name}` must be between {low} and {high}; using {default}."
+ )
+ value = default
+ fields[name] = value
+ for field in set(raw) - set(DISCOVERY_BOUNDS):
+ warnings.append(f"Unknown key `decisions.discovery.{field}`; ignoring it.")
+ return DiscoveryBudget(**fields)
+
+
def preset_policy(name: str) -> DecisionPolicy:
"""The policy a named preset resolves to."""
spec = PRESETS.get(name)
@@ -487,12 +574,25 @@ def resolve_policy(repo_config: dict[str, Any] | None) -> PolicyResolution:
sources: dict[str, SourceSetting] = dict(base["sources"])
raw_sources = raw.get("sources")
+ enumerated = isinstance(raw_sources, dict)
if raw_sources is None:
raw_sources = {}
- elif not isinstance(raw_sources, dict):
+ elif not enumerated:
warnings.append("`decisions.sources:` is not a mapping; ignoring it.")
raw_sources = {}
+ # A `sources:` block written next to a preset is the authoritative list of
+ # the sources that preset covered when it was written, because every write
+ # through this layer enumerates all of them. So a source missing from a
+ # present enumeration is one that did not exist yet, and it stays off: a
+ # stored `preset: balanced` must not silently acquire a model call the day
+ # a new source joins that preset. A bare `preset:` with no enumeration is a
+ # live declaration and does get the preset's current membership.
+ if preset_name and enumerated:
+ for spec in SOURCE_SPECS:
+ if spec.togglable and not spec.default_enabled and spec.key not in raw_sources:
+ sources[spec.key] = SourceSetting(enabled=False, llm=spec.llm)
+
for key, value in raw_sources.items():
spec = _SPECS_BY_KEY.get(str(key))
if spec is None or not spec.togglable:
@@ -539,11 +639,16 @@ def resolve_policy(repo_config: dict[str, Any] | None) -> PolicyResolution:
else:
warnings.append("`decisions.session_mining` is not a boolean; ignoring it.")
- for field in set(raw) - {"preset", "enabled", "llm", "sources", "session_mining"}:
+ discovery = _resolve_discovery(raw.get("discovery"), warnings)
+
+ known = {"preset", "enabled", "llm", "sources", "session_mining", "discovery"}
+ for field in set(raw) - known:
warnings.append(f"Unknown key `decisions.{field}`; ignoring it.")
return PolicyResolution(
- policy=DecisionPolicy(enabled=enabled, llm=llm, sources=sources),
+ policy=DecisionPolicy(
+ enabled=enabled, llm=llm, sources=sources, discovery=discovery
+ ),
warnings=tuple(warnings),
legacy_keys=tuple(legacy),
)
diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.py
index 6d44288e6..8cb53d9eb 100644
--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py
@@ -7,11 +7,18 @@ orchestrator.py) imports these phase functions. No CLI/click/rich imports.
from __future__ import annotations
import asyncio
+from dataclasses import replace
from pathlib import Path
from typing import Any
import structlog
+from repowise.core.analysis.decisions.discovery import (
+ DISCOVERY_SOURCE,
+ DiscoveryOutcome,
+ DiscoveryReport,
+ run_update_discovery,
+)
from repowise.core.pipeline.progress import ProgressCallback
from ._common import _phase_done
@@ -32,6 +39,7 @@ _DECISION_SOURCE_LABELS: tuple[tuple[str, str], ...] = (
("git_archaeology", "from git history"),
("comment", "from comments"),
("session", "from agent sessions"),
+ ("session_discovery", "from session discovery"),
)
@@ -293,6 +301,36 @@ async def _run_health_analysis(
return None
+async def _run_session_discovery(
+ repo_path: Path,
+ *,
+ llm_client: Any | None,
+ policy: Any,
+ report: Any,
+) -> DiscoveryOutcome:
+ """The one broad session-discovery call, folded into the decision report.
+
+ Never raises: a discovery outage must degrade this phase's reporting, not
+ lose the decisions every other source already found.
+ """
+ try:
+ outcome = await asyncio.wait_for(
+ run_update_discovery(
+ repo_path,
+ provider=llm_client,
+ policy=policy,
+ ),
+ timeout=DECISION_EXTRACTION_TIMEOUT_SECS,
+ )
+ except Exception as exc:
+ outcome = DiscoveryOutcome(report=DiscoveryReport(status="failed", reason=str(exc)))
+ if outcome.decisions:
+ report.decisions.extend(outcome.decisions)
+ report.by_source[DISCOVERY_SOURCE] = len(outcome.decisions)
+ report.total_found = len(report.decisions)
+ return outcome
+
+
async def _run_decision_extraction(
repo_path: Path,
*,
@@ -354,7 +392,11 @@ async def _run_decision_extraction(
if policy.source_enabled("session"):
session_provider = llm_client if policy.llm_allowed("session") else None
session_decisions = await asyncio.wait_for(
- mine_session_decisions(repo_path, provider=session_provider),
+ mine_session_decisions(
+ repo_path,
+ provider=session_provider,
+ collect_discovery_spans=policy.llm_allowed("session_discovery"),
+ ),
timeout=DECISION_EXTRACTION_TIMEOUT_SECS,
)
if session_decisions:
@@ -365,6 +407,13 @@ async def _run_decision_extraction(
if progress:
progress.on_message("warning", f"Session decision mining skipped: {exc}")
+ # The broad lane, after the miner because the miner's single read is
+ # what filled its span queue. At most one call, and it reports its own
+ # zero so a switched-off source never reads as an empty repository.
+ discovery = await _run_session_discovery(
+ repo_path, llm_client=llm_client, policy=policy, report=report
+ )
+
if progress:
# Only the sources that actually found something. On a typical
# first index most of these are zero, and the line read as
@@ -403,7 +452,9 @@ async def _run_decision_extraction(
# nobody could read. Same shape the update path already uses for
# its ``degraded`` list, so both runs report an outage the same
# way instead of one of them printing a reassuring zero.
- failures = getattr(report, "failures", {}) or {}
+ failures = dict(getattr(report, "failures", {}) or {})
+ if discovery.report.status == "failed":
+ failures["session_discovery"] = discovery.report.reason
# Sources that never ran, and why. Built first because a source
# listed here must not also appear as an honest zero below: with no
# API key the three model-only sources return [] immediately, and
@@ -418,14 +469,35 @@ async def _run_decision_extraction(
for key, rt in runtime.items()
if rt.togglable and rt.status in ("disabled", "skipped_no_provider")
}
+ # Broad discovery is not one of the extractor's sources, so it
+ # would fall out of all three lists on ``source in enabled`` alone.
+ # It is always considered, so it lands in exactly one of them. Its
+ # own reason overrides the policy's, being the more specific of the
+ # two ("no new prose since the last update" is not "switched off").
+ considered = set(enabled) | {DISCOVERY_SOURCE}
+ if discovery.report.status in ("not_run", "skipped_no_provider"):
+ not_run.add(DISCOVERY_SOURCE)
+ if discovery.report.reason:
+ runtime[DISCOVERY_SOURCE] = replace(
+ runtime[DISCOVERY_SOURCE], reason=discovery.report.reason
+ )
+ # A grounded candidate is a finding even though promotion waits for
+ # a second sighting, so discovery is not empty on the run that
+ # first finds something.
+ staged = discovery.report.candidates_grounded
empty = [
label.removeprefix("from ")
for source, label in _DECISION_SOURCE_LABELS
- if source in enabled
+ if source in considered
and source not in not_run
and not bs.get(source)
and source not in failures
+ and not (source == DISCOVERY_SOURCE and staged)
]
+ if staged:
+ progress.on_message(
+ "info", f"→ {staged} session-discovery candidate(s) staged for review"
+ )
if empty:
progress.on_message("info", f"→ Nothing found in: {', '.join(empty)}")
for source, label in _DECISION_SOURCE_LABELS:
diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.py
index eefbaf863..2f7c8849e 100644
--- a/packages/core/src/repowise/core/sessions/miners/decisions.py
+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py
@@ -55,6 +55,7 @@ from typing import Any
import structlog
+from repowise.core.analysis.decisions.discovery.spans import SpanCollector
from repowise.core.analysis.decisions.extractor import ExtractedDecision
from repowise.core.analysis.decisions.policy import resolve_policy
from repowise.core.analysis.decisions.provenance import (
@@ -77,7 +78,7 @@ from repowise.core.sessions.events import (
is_prose_user_text,
relative_files,
)
-from repowise.core.sessions.staging import SessionStagingStore
+from repowise.core.sessions.staging import DISCOVERY_KIND, SessionStagingStore
logger = structlog.get_logger(__name__)
@@ -86,6 +87,7 @@ __all__ = [
"apply_injection_feedback",
"mine_events",
"mine_session_decisions",
+ "promotion_decisions",
"session_mining_enabled",
]
@@ -599,7 +601,7 @@ def _gate_structured(item: dict[str, Any], raw: dict[str, Any]) -> dict[str, Any
_MAX_EVIDENCE_SESSIONS = 5
-def _promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[ExtractedDecision]:
+def promotion_decisions(row: dict[str, Any], repo_root: Path) -> list[ExtractedDecision]:
"""decision_records-ready members for one promotable staging row.
One member per observing session (capped) so each session becomes its own
@@ -789,6 +791,7 @@ async def mine_session_decisions(
provider: Any | None,
projects_root: Path | None = None,
max_structured: int = MAX_STRUCTURED_PER_UPDATE,
+ collect_discovery_spans: bool = False,
now: float | None = None,
) -> list[ExtractedDecision]:
"""Read this repo's new transcript lines once, and serve both consumers.
@@ -809,6 +812,11 @@ async def mine_session_decisions(
*provider* may be ``None``. Discovery, folding and staging are keyless and
run regardless; only the structuring pass needs a model, so a user with no
API key gets transcript episodes and a staged backlog rather than nothing.
+
+ With *collect_discovery_spans*, the same read also queues the user and
+ assistant prose that the broad discovery lane consumes. It rides this pass
+ for the same reason the episode recorder does: the cursor advances as the
+ bytes are read, so a second reader would find an empty file.
"""
repo_root = Path(repo_path).resolve()
repo_prefix = str(repo_root).lower().rstrip("\\/")
@@ -819,6 +827,7 @@ async def mine_session_decisions(
recorder = TranscriptEpisodeRecorder(repo_root)
store = SessionStagingStore.open_default(repo_root)
+ collector = SpanCollector(store, repo_root, now=now) if collect_discovery_spans else None
try:
# Stage new gate hits from transcript lines appended since last run.
staged = 0
@@ -842,7 +851,10 @@ async def mine_session_decisions(
break
try:
events = iter_new_events(adapter, path, store.cursors, prefilter=prefilter)
- for candidate in mine_events(recorder.observe(path, events), repo_prefix):
+ stream = recorder.observe(path, events)
+ if collector is not None:
+ stream = collector.observe(stream)
+ for candidate in mine_events(stream, repo_prefix):
if store.add_raw(
hash_=candidate.hash,
kind=candidate.kind,
@@ -909,7 +921,9 @@ async def mine_session_decisions(
# Promotion: observation-qualified decisions, ready for upsert.
decisions: list[ExtractedDecision] = []
for row in store.promotable():
- decisions.extend(_promotion_decisions(row, repo_root))
+ if row["kind"] == DISCOVERY_KIND:
+ continue # the broad lane runs its own promotion, under its own rules
+ decisions.extend(promotion_decisions(row, repo_root))
store.mark_emitted(row["key"], observations=row["observations"], now=now)
store.commit()
@@ -918,6 +932,7 @@ async def mine_session_decisions(
staged=staged,
structured=structured_count,
pending_backlog=max(0, len(pending) - processed),
+ discovery_spans=collector.queued if collector else 0,
promoted=len(decisions),
episodes=episodes,
transcripts_deferred=deferred,
diff --git a/packages/core/src/repowise/core/sessions/staging.py b/packages/core/src/repowise/core/sessions/staging.py
index 92df1885c..2cb27e8dc 100644
--- a/packages/core/src/repowise/core/sessions/staging.py
+++ b/packages/core/src/repowise/core/sessions/staging.py
@@ -47,6 +47,16 @@ RAW_TTL_DAYS = 90.0
#: database with raw sqlite3 and must not learn about a new one.
_VERDICT_REPAIR_VERSION = 1
+#: ``raw_candidates.kind`` for a broad-discovery candidate. Discovery writes
+#: its raw row only as the anchor ``upsert_structured`` needs, never as work
+#: for the deterministic structuring pass.
+DISCOVERY_KIND = "session_discovery"
+
+#: Retries a discovery span gets across updates before it is retired. Bounded
+#: so one span the provider keeps choking on cannot wedge the queue head
+#: forever; a validation rejection is not a retry, since the span was read.
+MAX_SPAN_ATTEMPTS = 3
+
#: Cap on the distinct session ids tracked per structured decision. Two is
#: enough to promote; beyond a handful the extra ids only pad evidence.
_MAX_SESSIONS_TRACKED = 20
@@ -103,8 +113,21 @@ CREATE TABLE IF NOT EXISTS injections (
build TEXT NOT NULL DEFAULT '',
PRIMARY KEY (session_id, decision_id)
);
+CREATE TABLE IF NOT EXISTS discovery_spans (
+ span_id TEXT PRIMARY KEY,
+ session_id TEXT NOT NULL,
+ role TEXT NOT NULL,
+ text TEXT NOT NULL,
+ files TEXT NOT NULL,
+ ts REAL,
+ created_at REAL NOT NULL,
+ consumed_at REAL,
+ attempts INTEGER NOT NULL DEFAULT 0
+);
CREATE INDEX IF NOT EXISTS idx_raw_pending ON raw_candidates(structured_key)
WHERE structured_key IS NULL;
+CREATE INDEX IF NOT EXISTS idx_discovery_pending ON discovery_spans(created_at)
+ WHERE consumed_at IS NULL;
"""
#: Columns added to ``injections`` after PR4 shipped the table (the ledger now
@@ -150,9 +173,17 @@ def normalize_title(title: str) -> str:
return _WS_RE.sub(" ", t)
-def title_key(title: str) -> str:
- """Stable 16-hex staging key for a decision title."""
- return hashlib.sha256(normalize_title(title).encode("utf-8")).hexdigest()[:16]
+def title_key(title: str, lane: str = "") -> str:
+ """Stable 16-hex staging key for a decision title within one *lane*.
+
+ Lanes get separate key namespaces because folding is destructive: the merge
+ path overwrites ``structured`` and keeps a ``user_correction`` kind sticky.
+ A broad-discovery candidate whose title happened to normalize onto a gate
+ hit's would replace that row's text while inheriting its one-observation
+ promotion path, which is neither lane's rule.
+ """
+ payload = f"{lane}|{normalize_title(title)}" if lane else normalize_title(title)
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16]
def default_store_path(repo_path: Path) -> Path:
@@ -245,13 +276,17 @@ class SessionStagingStore:
User corrections first (they carry the one-observation fast path),
then dead ends, then choices; oldest first within a kind, so a
cold-start backlog drains its highest-value candidates first.
+
+ Broad-discovery rows are excluded: they arrive already structured and
+ grounded against their own spans, and this query feeds a prompt that
+ would re-derive them from the wrong evidence.
"""
rows = self._conn.execute(
"SELECT hash, kind, quotes, files, session_id FROM raw_candidates "
- "WHERE structured_key IS NULL "
+ "WHERE structured_key IS NULL AND kind <> ? "
"ORDER BY CASE kind WHEN 'user_correction' THEN 0 WHEN 'dead_end' THEN 1 ELSE 2 END, "
"created_at ASC LIMIT ?",
- (limit,),
+ (DISCOVERY_KIND, limit),
).fetchall()
return [
{
@@ -268,6 +303,98 @@ class SessionStagingStore:
"""The LLM (or the substring gate) ruled this raw out; never retry it."""
self._conn.execute("UPDATE raw_candidates SET structured_key = '' WHERE hash = ?", (hash_,))
+ # -- discovery spans -----------------------------------------------------
+ # The durable input queue for the one broad update-level discovery call.
+ # Spans are written during the same transcript read that stages gate hits,
+ # so they commit with the cursors; whatever does not fit one update's
+ # budget stays pending and is served oldest-first by the next.
+
+ def add_discovery_span(
+ self,
+ *,
+ span_id: str,
+ session_id: str,
+ role: str,
+ text: str,
+ files: list[str],
+ ts: float | None,
+ now: float | None = None,
+ ) -> bool:
+ """Queue one prose span; idempotent per span id. True when new."""
+ cur = self._conn.execute(
+ "INSERT OR IGNORE INTO discovery_spans "
+ "(span_id, session_id, role, text, files, ts, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
+ (
+ span_id,
+ session_id,
+ role,
+ text,
+ json.dumps(files),
+ ts,
+ now if now is not None else time.time(),
+ ),
+ )
+ return cur.rowcount > 0
+
+ def pending_discovery_spans(self, limit: int) -> list[dict[str, Any]]:
+ """Unconsumed spans, oldest first, then in transcript order.
+
+ Ordered by ``created_at`` before ``ts`` so a backlog drains in the
+ order it accumulated rather than by whichever session happens to hold
+ the oldest wall-clock turn.
+ """
+ rows = self._conn.execute(
+ "SELECT span_id, session_id, role, text, files, ts "
+ "FROM discovery_spans WHERE consumed_at IS NULL "
+ "ORDER BY created_at ASC, ts ASC, span_id ASC LIMIT ?",
+ (limit,),
+ ).fetchall()
+ return [
+ {
+ "span_id": r[0],
+ "session_id": r[1],
+ "role": r[2],
+ "text": r[3],
+ "files": json.loads(r[4]),
+ "ts": r[5],
+ }
+ for r in rows
+ ]
+
+ def pending_discovery_count(self) -> int:
+ row = self._conn.execute(
+ "SELECT COUNT(*) FROM discovery_spans WHERE consumed_at IS NULL"
+ ).fetchone()
+ return int(row[0]) if row else 0
+
+ def mark_discovery_consumed(self, span_ids: list[str], *, now: float | None = None) -> None:
+ """Retire spans that were actually put in front of the model."""
+ ts = now if now is not None else time.time()
+ self._conn.executemany(
+ "UPDATE discovery_spans SET consumed_at = ? WHERE span_id = ?",
+ [(ts, span_id) for span_id in span_ids],
+ )
+
+ def bump_discovery_attempts(self, span_ids: list[str], *, now: float | None = None) -> int:
+ """Record a transient failure over *span_ids*; retire the exhausted.
+
+ Returns how many spans hit :data:`MAX_SPAN_ATTEMPTS` and were retired,
+ so the caller can report a permanent drop rather than a silent one.
+ """
+ ts = now if now is not None else time.time()
+ self._conn.executemany(
+ "UPDATE discovery_spans SET attempts = attempts + 1 WHERE span_id = ?",
+ [(span_id,) for span_id in span_ids],
+ )
+ marks = ",".join("?" * len(span_ids))
+ cur = self._conn.execute(
+ f"UPDATE discovery_spans SET consumed_at = ? "
+ f"WHERE consumed_at IS NULL AND attempts >= ? AND span_id IN ({marks})",
+ (ts, MAX_SPAN_ATTEMPTS, *span_ids),
+ )
+ return cur.rowcount
+
# -- structured decisions --------------------------------------------------
def upsert_structured(
@@ -280,6 +407,7 @@ class SessionStagingStore:
quotes: list[str],
files: list[str],
session_id: str | None,
+ lane: str = "",
now: float | None = None,
) -> str:
"""Fold one structured candidate into its normalized-title row.
@@ -291,7 +419,7 @@ class SessionStagingStore:
Returns the decision key.
"""
ts = now if now is not None else time.time()
- key = title_key(title)
+ key = title_key(title, lane)
row = self._conn.execute(
"SELECT kind, sessions, quotes, files FROM decisions WHERE key = ?", (key,)
).fetchone()
@@ -340,6 +468,13 @@ class SessionStagingStore:
# -- promotion ---------------------------------------------------------
+ def structured_exists(self, title: str, lane: str = "") -> bool:
+ """Whether *title* already folds into an existing row in *lane*."""
+ row = self._conn.execute(
+ "SELECT 1 FROM decisions WHERE key = ?", (title_key(title, lane),)
+ ).fetchone()
+ return row is not None
+
def promotable(self) -> list[dict[str, Any]]:
"""Decisions that qualify for (re-)emission into decision_records.
@@ -706,12 +841,23 @@ class SessionStagingStore:
# -- lifecycle -----------------------------------------------------------
def prune(self, *, now: float | None = None) -> None:
- """Drop never-structured raws past the TTL (see :data:`RAW_TTL_DAYS`)."""
+ """Drop spent rows past the TTL (see :data:`RAW_TTL_DAYS`).
+
+ Discovery spans are dropped only once *consumed*: the candidate they
+ produced keeps its own copy of the quote, so the raw prose is only the
+ input queue. A span still waiting for a call is never pruned, however
+ old, because ageing out unread input is exactly the silent backlog loss
+ the queue exists to prevent.
+ """
cutoff = (now if now is not None else time.time()) - RAW_TTL_DAYS * 86400.0
self._conn.execute(
"DELETE FROM raw_candidates WHERE structured_key IS NULL AND created_at < ?",
(cutoff,),
)
+ self._conn.execute(
+ "DELETE FROM discovery_spans WHERE consumed_at IS NOT NULL AND consumed_at < ?",
+ (cutoff,),
+ )
def commit(self) -> None:
self._conn.commit()
diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.py
index a5bebdab4..5a0b3dddb 100644
--- a/packages/server/src/repowise/server/routers/decisions.py
+++ b/packages/server/src/repowise/server/routers/decisions.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from dataclasses import replace
from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException, Query
@@ -15,6 +16,7 @@ from repowise.server.schemas import (
DecisionCodeEdge,
DecisionCountsResponse,
DecisionCreate,
+ DecisionDiscoveryBudget,
DecisionEvidenceListResponse,
DecisionEvidenceResponse,
DecisionGraphEdge,
@@ -250,6 +252,7 @@ def _settings_payload(repo_path: Path, resolution) -> DecisionSettings:
enabled=policy.enabled,
llm=policy.llm,
preset=policy.preset_name(),
+ discovery=DecisionDiscoveryBudget(**policy.discovery.to_dict()),
sources=[
DecisionSourceState(**rt.to_dict())
for rt in policy.runtime(provider_available=available)
@@ -319,7 +322,9 @@ async def update_decision_settings(
if body.preset is not None:
try:
- policy = preset_policy(body.preset)
+ # A preset names source membership, not a budget; the budget the
+ # caller did not send is theirs and survives.
+ policy = replace(preset_policy(body.preset), discovery=policy.discovery)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if body.enabled is not None:
@@ -331,6 +336,12 @@ async def update_decision_settings(
policy = policy.with_source(key, enabled=patch.enabled, llm=patch.llm)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+ patch = body.discovery.model_dump(exclude_none=True) if body.discovery else {}
+ if patch:
+ try:
+ policy = policy.with_discovery(**patch)
+ except ValueError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
try:
resolution = write_policy(repo_path, policy, expected_etag=body.etag)
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index ca39c71c4..e716f4ab0 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -78,6 +78,8 @@ from .decisions import (
DecisionCodeEdge,
DecisionCountsResponse,
DecisionCreate,
+ DecisionDiscoveryBudget,
+ DecisionDiscoveryPatch,
DecisionEvidenceListResponse,
DecisionEvidenceResponse,
DecisionGraphEdge,
@@ -343,6 +345,8 @@ __all__ = [
"DecisionCodeEdge",
"DecisionCountsResponse",
"DecisionCreate",
+ "DecisionDiscoveryBudget",
+ "DecisionDiscoveryPatch",
"DecisionEvidenceListResponse",
"DecisionEvidenceResponse",
"DecisionGraphEdge",
diff --git a/packages/server/src/repowise/server/schemas/decisions.py b/packages/server/src/repowise/server/schemas/decisions.py
index 343abfcfd..32eba9f90 100644
--- a/packages/server/src/repowise/server/schemas/decisions.py
+++ b/packages/server/src/repowise/server/schemas/decisions.py
@@ -5,8 +5,9 @@ from __future__ import annotations
import json
from datetime import datetime
-from pydantic import BaseModel, ConfigDict
+from pydantic import BaseModel, ConfigDict, Field
+from repowise.core.analysis.decisions.policy import DISCOVERY_BOUNDS
from repowise.core.analysis.decisions.scope import derive_decision_scope
@@ -254,6 +255,12 @@ class DecisionLineageResponse(BaseModel):
# ---------------------------------------------------------------------------
+#: Sourced from the policy registry so the wire bounds cannot drift from the
+#: ones the resolver enforces.
+_DISCOVERY_DEFAULTS = {key: bounds[2] for key, bounds in DISCOVERY_BOUNDS.items()}
+_DISCOVERY_RANGE = {key: {"ge": bounds[0], "le": bounds[1]} for key, bounds in DISCOVERY_BOUNDS.items()}
+
+
class DecisionSourceState(BaseModel):
"""One capture source's capabilities and resolved state."""
@@ -273,13 +280,37 @@ class DecisionSourceState(BaseModel):
reason: str
+class DecisionDiscoveryBudget(BaseModel):
+ """Per-update ceiling on the one broad session-discovery call."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ max_sessions: int = _DISCOVERY_DEFAULTS["max_sessions"]
+ max_input_tokens: int = _DISCOVERY_DEFAULTS["max_input_tokens"]
+
+
+class DecisionDiscoveryPatch(BaseModel):
+ """A change to the discovery budget. Omitted fields keep their value.
+
+ Separate from :class:`DecisionDiscoveryBudget` because a response states
+ both numbers while a write may set one, and a shared model would fill the
+ other from its default and quietly reset it.
+ """
+
+ model_config = ConfigDict(extra="forbid")
+
+ max_sessions: int | None = Field(default=None, **_DISCOVERY_RANGE["max_sessions"])
+ max_input_tokens: int | None = Field(default=None, **_DISCOVERY_RANGE["max_input_tokens"])
+
+
class DecisionSettings(BaseModel):
"""The resolved decision capture policy for one repository."""
enabled: bool = True
llm: bool = True
- #: off | local_only | balanced | full | custom
- preset: str = "full"
+ #: default | off | local_only | balanced | full | custom
+ preset: str = "default"
+ discovery: DecisionDiscoveryBudget = DecisionDiscoveryBudget()
sources: list[DecisionSourceState] = []
provider_available: bool = True
#: Recoverable config problems, e.g. an unknown source key.
@@ -316,4 +347,6 @@ class DecisionSettingsUpdate(BaseModel):
#: Applied first, so a preset plus per-source overrides works in one call.
preset: str | None = None
sources: dict[str, DecisionSourcePatch] | None = None
+ #: Budget for broad session discovery. Omitted fields keep their value.
+ discovery: DecisionDiscoveryPatch | None = None
etag: str | None = None
diff --git a/packages/types/src/decisions.ts b/packages/types/src/decisions.ts
index ed3bf1a4e..9e24a4f26 100644
--- a/packages/types/src/decisions.ts
+++ b/packages/types/src/decisions.ts
@@ -216,13 +216,29 @@ export interface DecisionSourceState {
reason: string;
}
-export type DecisionPreset = "off" | "local_only" | "balanced" | "full" | "custom";
+export type DecisionPreset =
+ | "default"
+ | "off"
+ | "local_only"
+ | "balanced"
+ | "full"
+ | "custom";
+
+/** Per-update ceiling on the one broad session-discovery call. */
+export interface DecisionDiscoveryBudget {
+ max_sessions: number;
+ max_input_tokens: number;
+}
+
+/** A change to the discovery budget. Omitted fields keep their value. */
+export type DecisionDiscoveryPatch = Partial<DecisionDiscoveryBudget>;
/** The resolved decision capture policy for one repository. */
export interface DecisionSettings {
enabled: boolean;
llm: boolean;
preset: DecisionPreset;
+ discovery: DecisionDiscoveryBudget;
sources: DecisionSourceState[];
provider_available: boolean;
warnings: string[];
@@ -244,5 +260,6 @@ export interface DecisionSettingsUpdate {
llm?: boolean;
preset?: Exclude<DecisionPreset, "custom">;
sources?: Record<string, DecisionSourcePatch>;
+ discovery?: DecisionDiscoveryPatch;
etag?: string;
}
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index a7865d28b..7bd0392b5 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -730,6 +730,24 @@ export interface DecisionCreate {
tags?: string[];
}
+/** Per-update ceiling on the one broad session-discovery call. */
+export interface DecisionDiscoveryBudget {
+ max_sessions?: number;
+ max_input_tokens?: number;
+}
+
+/**
+ * A change to the discovery budget. Omitted fields keep their value.
+ *
+ * Separate from :class:`DecisionDiscoveryBudget` because a response states
+ * both numbers while a write may set one, and a shared model would fill the
+ * other from its default and quietly reset it.
+ */
+export interface DecisionDiscoveryPatch {
+ max_sessions?: number | null;
+ max_input_tokens?: number | null;
+}
+
export interface DecisionEvidenceListResponse {
evidence?: DecisionEvidenceResponse[];
}
@@ -831,6 +849,7 @@ export interface DecisionSettings {
enabled?: boolean;
llm?: boolean;
preset?: string;
+ discovery?: DecisionDiscoveryBudget;
sources?: DecisionSourceState[];
provider_available?: boolean;
warnings?: string[];
@@ -844,6 +863,7 @@ export interface DecisionSettingsUpdate {
llm?: boolean | null;
preset?: string | null;
sources?: Record<string, DecisionSourcePatch> | null;
+ discovery?: DecisionDiscoveryPatch | null;
etag?: string | null;
}
diff --git a/tests/unit/analysis/test_decision_authority_containment.py b/tests/unit/analysis/test_decision_authority_containment.py
index 1bcc4fa5d..b9acd961b 100644
--- a/tests/unit/analysis/test_decision_authority_containment.py
+++ b/tests/unit/analysis/test_decision_authority_containment.py
@@ -9,7 +9,7 @@ from __future__ import annotations
from pathlib import Path
-from repowise.core.sessions.miners.decisions import _promotion_decisions
+from repowise.core.sessions.miners.decisions import promotion_decisions
from repowise.server.mcp_server._helpers import _compute_alignment
@@ -35,19 +35,19 @@ def _row(**overrides):
class TestRecurrenceIsNotAcceptance:
def test_first_promotion_lands_proposed(self):
"""Recurrence across sessions is evidence, not an acceptance event."""
- out = _promotion_decisions(_row(first_promotion=True), Path("."))
+ out = promotion_decisions(_row(first_promotion=True), Path("."))
assert out
assert {d.status for d in out} == {"proposed"}
def test_re_emission_also_lands_proposed(self):
- out = _promotion_decisions(_row(first_promotion=False), Path("."))
+ out = promotion_decisions(_row(first_promotion=False), Path("."))
assert {d.status for d in out} == {"proposed"}
def test_no_observation_count_produces_an_active_record(self):
for observations in (1, 2, 5, 50):
- out = _promotion_decisions(_row(observations=observations), Path("."))
+ out = promotion_decisions(_row(observations=observations), Path("."))
assert all(d.status != "active" for d in out)
diff --git a/tests/unit/analysis/test_decision_discovery.py b/tests/unit/analysis/test_decision_discovery.py
new file mode 100644
index 000000000..0eb9ad503
--- /dev/null
+++ b/tests/unit/analysis/test_decision_discovery.py
@@ -0,0 +1,574 @@
+"""Broad session discovery: packet bounds, grounding, and the one-call rule."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.decisions.discovery import (
+ ProseSpan,
+ build_packet,
+ ground_candidates,
+ parse_response,
+ run_update_discovery,
+)
+from repowise.core.analysis.decisions.discovery.runner import candidate_hash
+from repowise.core.analysis.decisions.policy import preset_policy, resolve_policy
+from repowise.core.sessions.staging import DISCOVERY_KIND, MAX_SPAN_ATTEMPTS, SessionStagingStore
+
+QUOTE = "Never run ruff format on this repository; CI diffs the formatting."
+PROSE = (
+ "Do not run ruff format here. " + QUOTE + " We settled that after the "
+ "repo-wide reformat blew up every open branch."
+)
+
+
+def _span(index: int, session: str = "s1", text: str = PROSE, files=("packages/core/a.py",)):
+ return ProseSpan(
+ span_id=f"span{index:02d}",
+ session_id=session,
+ role="user",
+ text=text,
+ files=tuple(files),
+ ts=float(index),
+ )
+
+
+def _candidate(**overrides):
+ item = {
+ "title": "Never run ruff format",
+ "decision": "Never run ruff format on this repository because CI diffs the formatting.",
+ "rationale": "CI diffs the formatting.",
+ "kind": "constraint",
+ "durability": "durable",
+ "acceptance_basis": "user_explicit",
+ "evidence_quote": QUOTE,
+ "span_ids": ["span01"],
+ "paths": ["packages/core/a.py"],
+ }
+ item.update(overrides)
+ return item
+
+
+def _payload(*items):
+ return {
+ "candidates": list(items),
+ "rejected_task_local": 0,
+ "rejected_assistant_only": 0,
+ }
+
+
+class _Response:
+ def __init__(self, content: str) -> None:
+ self.content = content
+ self.input_tokens = 1234
+ self.output_tokens = 56
+
+
+class FakeProvider:
+ """Counts calls, so the one-call invariant is an assertion not a promise."""
+
+ def __init__(self, content: str = "", *, error: Exception | None = None) -> None:
+ self.content = content
+ self.error = error
+ self.calls = 0
+
+ async def generate(self, system, prompt, **kwargs):
+ self.calls += 1
+ self.prompt = prompt
+ if self.error is not None:
+ raise self.error
+ return _Response(self.content)
+
+
+class ExplodingProvider:
+ """Any call at all is the failure."""
+
+ async def generate(self, *args, **kwargs): # pragma: no cover - must not run
+ raise AssertionError("a model call was made on a no-call path")
+
+
+# ---------------------------------------------------------------------------
+# Packet
+# ---------------------------------------------------------------------------
+
+
+def test_packet_admits_sessions_whole_and_in_queue_order():
+ spans = [_span(1, "s1"), _span(2, "s1"), _span(3, "s2")]
+ packet = build_packet(spans, max_sessions=2, max_input_tokens=30_000)
+ assert packet.sessions == ("s1", "s2")
+ assert [s.span_id for s in packet.spans] == ["span01", "span02", "span03"]
+
+
+def test_packet_stops_at_the_session_bound_and_leaves_the_rest_queued():
+ spans = [_span(1, "s1"), _span(2, "s2"), _span(3, "s3")]
+ packet = build_packet(spans, max_sessions=1, max_input_tokens=30_000)
+ assert packet.sessions == ("s1",)
+ assert len(packet.spans) == 1
+
+
+def test_packet_stops_at_the_token_bound():
+ # Two sessions of ~1,300 tokens each against a budget that fits one.
+ big = "word " * 800
+ spans = [_span(1, "s1", text=big), _span(2, "s2", text=big)]
+ packet = build_packet(spans, max_sessions=12, max_input_tokens=3_000)
+ assert packet.sessions == ("s1",)
+
+
+def test_one_oversized_session_never_wedges_the_queue():
+ """Trimming stops at one span: refusing to send it would drain nothing."""
+ huge = "word " * 20_000
+ spans = [_span(1, "s1", text=huge), _span(2, "s1", text=huge)]
+ packet = build_packet(spans, max_sessions=12, max_input_tokens=4_000)
+ assert packet.sessions == ("s1",)
+ assert len(packet.spans) == 1
+
+
+def test_packet_offers_only_the_files_its_spans_touched():
+ packet = build_packet([_span(1)], max_sessions=12, max_input_tokens=30_000)
+ assert packet.known_paths == ("packages/core/a.py",)
+ assert "packages/core/a.py" in packet.prompt
+ assert "span01" in packet.prompt
+
+
+def test_empty_queue_builds_no_packet():
+ assert not build_packet([], max_sessions=12, max_input_tokens=30_000)
+
+
+# ---------------------------------------------------------------------------
+# Grounding
+# ---------------------------------------------------------------------------
+
+
+def test_a_grounded_candidate_survives():
+ result = ground_candidates(_payload(_candidate()), (_span(1),))
+ assert len(result.grounded) == 1
+ candidate = result.grounded[0]
+ assert candidate.verification == "exact"
+ assert candidate.affected_files == ("packages/core/a.py",)
+ assert candidate.to_structured()["discovery"] is True
+
+
+ ("overrides", "reason"),
+ [
+ ({"title": ""}, "empty_claim"),
+ ({"decision": "add tests"}, "generic_claim"),
+ ({"durability": "task_local"}, "task_local"),
+ ({"span_ids": ["nope"]}, "unknown_span"),
+ ({"span_ids": ["span01", "nope"]}, "unknown_span"),
+ ({"span_ids": []}, "unknown_span"),
+ ({"evidence_quote": "We agreed to migrate everything to Bazel."}, "unverified_quote"),
+ (
+ {"decision": "Delete the entire persistence layer and rewrite it in Rust today."},
+ "ungrounded_claim",
+ ),
+ ],
+)
+def test_ungrounded_candidates_are_rejected_with_a_reason(overrides, reason):
+ result = ground_candidates(_payload(_candidate(**overrides)), (_span(1),))
+ assert result.grounded == []
+ assert result.rejected == {reason: 1}
+
+
+def test_an_invented_path_never_becomes_scope():
+ """Unresolved beats guessed: a repository-wide claim is not pinned anywhere."""
+ result = ground_candidates(
+ _payload(_candidate(paths=["packages/web/src/invented.tsx"])), (_span(1),)
+ )
+ assert result.grounded[0].affected_files == ()
+
+
+def test_a_selected_path_from_the_known_set_becomes_scope():
+ result = ground_candidates(_payload(_candidate()), (_span(1),))
+ assert result.grounded[0].affected_files == ("packages/core/a.py",)
+
+
+def test_the_packet_never_exceeds_the_token_ceiling():
+ spans = [_span(i, f"s{i}", text="word " * 900) for i in range(1, 30)]
+ packet = build_packet(spans, max_sessions=24, max_input_tokens=8_000)
+ assert 0 < packet.estimated_tokens <= 8_000
+
+
+def test_an_invented_rationale_is_dropped_without_killing_the_candidate():
+ result = ground_candidates(
+ _payload(_candidate(rationale="Because the board mandated a Kubernetes migration.")),
+ (_span(1),),
+ )
+ assert result.grounded[0].rationale == ""
+
+
+def test_a_combined_claim_is_flagged_never_split():
+ result = ground_candidates(
+ _payload(
+ _candidate(
+ decision=(
+ "Never run ruff format on this repository; "
+ "CI diffs the formatting on every branch."
+ )
+ )
+ ),
+ (_span(1),),
+ )
+ assert len(result.grounded) == 1
+ assert result.grounded[0].needs_split is True
+
+
[email protected]("content", ["", "not json at all", '{"candidates": "nope"}', "[]"])
+def test_malformed_output_grounds_nothing(content):
+ result = ground_candidates(parse_response(content), (_span(1),))
+ assert result.grounded == []
+ assert result.rejected.get("malformed") == 1
+
+
+def test_fenced_json_still_parses():
+ body = "```json\n" + json.dumps(_payload(_candidate())) + "\n```"
+ assert ground_candidates(parse_response(body), (_span(1),)).grounded
+
+
+def test_identity_covers_claim_and_evidence():
+ one = ground_candidates(_payload(_candidate()), (_span(1),)).grounded[0]
+ same = ground_candidates(_payload(_candidate()), (_span(1),)).grounded[0]
+ assert candidate_hash(one) == candidate_hash(same)
+
+
+# ---------------------------------------------------------------------------
+# Runner: the one-call invariant and the backlog
+# ---------------------------------------------------------------------------
+
+
+def _queue(repo: Path, spans: list[ProseSpan], now: float = 100.0) -> None:
+ with SessionStagingStore.open_default(repo) as store:
+ for span in spans:
+ store.add_discovery_span(
+ span_id=span.span_id,
+ session_id=span.session_id,
+ role=span.role,
+ text=span.text,
+ files=list(span.files),
+ ts=span.ts,
+ now=now,
+ )
+ store.commit()
+
+
+ ("policy", "reason"),
+ [
+ (resolve_policy(None).policy, "switched off"),
+ (preset_policy("off"), "capture is off"),
+ (preset_policy("full").with_llm(False), "LLM extraction is off"),
+ ],
+)
+async def test_disabled_paths_make_no_model_call(tmp_path, policy, reason):
+ """Each guard names the switch that stopped it, not a generic zero."""
+ _queue(tmp_path, [_span(1)])
+ outcome = await run_update_discovery(
+ tmp_path, provider=ExplodingProvider(), policy=policy, now=200.0
+ )
+ assert outcome.report.status == "not_run"
+ assert outcome.report.calls == 0
+ assert reason in outcome.report.reason
+
+
+async def test_no_provider_makes_no_call_and_says_so(tmp_path):
+ _queue(tmp_path, [_span(1)])
+ outcome = await run_update_discovery(
+ tmp_path, provider=None, policy=preset_policy("balanced"), now=200.0
+ )
+ assert outcome.report.status == "skipped_no_provider"
+ assert outcome.report.calls == 0
+
+
+async def test_empty_input_makes_no_call(tmp_path):
+ outcome = await run_update_discovery(
+ tmp_path, provider=ExplodingProvider(), policy=preset_policy("balanced"), now=200.0
+ )
+ assert outcome.report.status == "empty"
+ assert outcome.report.calls == 0
+
+
+async def test_a_large_backlog_still_costs_exactly_one_call(tmp_path):
+ _queue(tmp_path, [_span(i, f"s{i}") for i in range(1, 40)])
+ provider = FakeProvider(json.dumps(_payload()))
+ outcome = await run_update_discovery(
+ tmp_path, provider=provider, policy=preset_policy("balanced"), now=200.0
+ )
+ assert provider.calls == 1
+ assert outcome.report.calls == 1
+ assert outcome.report.sessions_considered == 12
+ assert outcome.report.spans_deferred == 39 - 12
+
+
+async def test_overflow_is_queued_oldest_first_not_dropped(tmp_path):
+ _queue(tmp_path, [_span(i, f"s{i}") for i in range(1, 16)])
+ policy = preset_policy("balanced").with_discovery(max_sessions=2)
+ provider = FakeProvider(json.dumps(_payload()))
+ await run_update_discovery(tmp_path, provider=provider, policy=policy, now=200.0)
+ assert "span01" in provider.prompt and "span02" in provider.prompt
+ assert "span03" not in provider.prompt
+
+ await run_update_discovery(tmp_path, provider=provider, policy=policy, now=300.0)
+ assert "span03" in provider.prompt and "span04" in provider.prompt
+ assert "span01" not in provider.prompt
+
+
+async def test_a_provider_failure_retries_the_same_spans_then_retires_them(tmp_path):
+ _queue(tmp_path, [_span(1)])
+ provider = FakeProvider(error=RuntimeError("rate limited"))
+ for attempt in range(1, MAX_SPAN_ATTEMPTS + 1):
+ outcome = await run_update_discovery(
+ tmp_path, provider=provider, policy=preset_policy("balanced"), now=200.0 + attempt
+ )
+ assert outcome.report.status == "failed"
+ assert outcome.report.calls == 0
+ assert outcome.report.spans_retired == 1
+ with SessionStagingStore.open_default(tmp_path) as store:
+ assert store.pending_discovery_count() == 0
+
+
+async def test_grounded_candidates_persist_and_rerunning_is_idempotent(tmp_path):
+ _queue(tmp_path, [_span(1)])
+ provider = FakeProvider(json.dumps(_payload(_candidate())))
+ first = await run_update_discovery(
+ tmp_path, provider=provider, policy=preset_policy("balanced"), now=200.0
+ )
+ assert first.report.candidates_grounded == 1
+ assert first.report.candidates_new == 1
+ # Spans are spent once read, so a second update has nothing left to send.
+ second = await run_update_discovery(
+ tmp_path, provider=provider, policy=preset_policy("balanced"), now=300.0
+ )
+ assert second.report.status == "empty"
+ assert provider.calls == 1
+
+ with SessionStagingStore.open_default(tmp_path) as store:
+ assert store.pending_raws(10) == [] # never fed to the deterministic lane
+ rows = store.promotable()
+ assert rows == [] # one observation is not enough to propose anything
+
+
+async def test_a_second_session_promotes_the_candidate_as_proposed(tmp_path):
+ provider = FakeProvider(json.dumps(_payload(_candidate())))
+ _queue(tmp_path, [_span(1, "s1")], now=100.0)
+ await run_update_discovery(
+ tmp_path, provider=provider, policy=preset_policy("balanced"), now=200.0
+ )
+ _queue(tmp_path, [_span(2, "s2")], now=300.0)
+ provider.content = json.dumps(_payload(_candidate(span_ids=["span02"])))
+ outcome = await run_update_discovery(
+ tmp_path, provider=provider, policy=preset_policy("balanced"), now=400.0
+ )
+ assert outcome.decisions
+ assert {d.status for d in outcome.decisions} == {"proposed"}
+ assert {d.source for d in outcome.decisions} == {"session"}
+
+
+async def test_discovery_never_promotes_the_deterministic_lanes_backlog(tmp_path):
+ with SessionStagingStore.open_default(tmp_path) as store:
+ store.add_raw(
+ hash_="det1",
+ kind="user_correction",
+ quotes=[QUOTE],
+ files=["packages/core/a.py"],
+ session_id="s9",
+ now=100.0,
+ )
+ store.upsert_structured(
+ "det1",
+ kind="user_correction",
+ title="A deterministic gate hit",
+ structured={"decision": "Do the thing", "verification": "exact"},
+ quotes=[QUOTE],
+ files=["packages/core/a.py"],
+ session_id="s9",
+ now=100.0,
+ )
+ store.commit()
+ assert len(store.promotable()) == 1
+
+ _queue(tmp_path, [_span(1)])
+ outcome = await run_update_discovery(
+ tmp_path,
+ provider=FakeProvider(json.dumps(_payload())),
+ policy=preset_policy("balanced"),
+ now=200.0,
+ )
+ assert outcome.decisions == []
+ with SessionStagingStore.open_default(tmp_path) as store:
+ assert [row["kind"] for row in store.promotable()] == ["user_correction"]
+
+
+async def test_a_candidate_citing_an_invented_span_is_dropped_not_stored(tmp_path):
+ _queue(tmp_path, [_span(1)])
+ outcome = await run_update_discovery(
+ tmp_path,
+ provider=FakeProvider(json.dumps(_payload(_candidate(span_ids=["ghost"])))),
+ policy=preset_policy("balanced"),
+ now=200.0,
+ )
+ assert outcome.report.candidates_returned == 1
+ assert outcome.report.candidates_grounded == 0
+ assert outcome.report.rejected == {"unknown_span": 1}
+ with SessionStagingStore.open_default(tmp_path) as store:
+ assert store.promotable() == []
+
+
+def test_discovery_rows_are_hidden_from_the_deterministic_structuring_queue(tmp_path):
+ with SessionStagingStore.open_default(tmp_path) as store:
+ store.add_raw(
+ hash_="d1",
+ kind=DISCOVERY_KIND,
+ quotes=[QUOTE],
+ files=[],
+ session_id="s1",
+ now=100.0,
+ )
+ store.add_raw(
+ hash_="c1",
+ kind="explicit_choice",
+ quotes=[QUOTE],
+ files=[],
+ session_id="s1",
+ now=100.0,
+ )
+ store.commit()
+ assert [row["hash"] for row in store.pending_raws(10)] == ["c1"]
+
+
+def test_a_paraphrased_quote_is_not_evidence_in_this_lane():
+ """A loose overlap across a whole transcript is not a verbatim sentence."""
+ result = ground_candidates(
+ _payload(
+ _candidate(
+ evidence_quote=(
+ "the team agreed formatting tools stay disabled across every "
+ "continuous integration pipeline"
+ )
+ )
+ ),
+ (_span(1),),
+ )
+ assert result.grounded == []
+ assert result.rejected == {"unverified_quote": 1}
+
+
+def test_a_verbatim_quote_that_only_lost_an_article_still_counts():
+ """Exact-substring alone rejected 4 of 7 measured candidates over reflow."""
+ result = ground_candidates(
+ _payload(_candidate(evidence_quote="Never run ruff format on repository; CI diffs the formatting.")),
+ (_span(1),),
+ )
+ assert len(result.grounded) == 1
+ assert result.grounded[0].verification == "fuzzy"
+
+
+def test_a_claim_carried_only_by_function_words_is_rejected():
+ result = ground_candidates(
+ _payload(
+ _candidate(decision="Always deploy the production bundle to the Fridays release train.")
+ ),
+ (_span(1),),
+ )
+ assert result.grounded == []
+ assert result.rejected == {"ungrounded_claim": 1}
+
+
+def test_the_selectable_path_set_is_the_packets_resolved_one():
+ packet = build_packet([_span(1)], max_sessions=12, max_input_tokens=30_000)
+ result = ground_candidates(_payload(_candidate()), packet.spans, packet.known_paths)
+ assert result.grounded[0].affected_files == ("packages/core/a.py",)
+
+
+def test_discovery_and_deterministic_titles_never_share_a_staging_row(tmp_path):
+ """A colliding title must not overwrite the other lane's row or its kind."""
+ with SessionStagingStore.open_default(tmp_path) as store:
+ store.add_raw(
+ hash_="det1", kind="user_correction", quotes=[QUOTE], files=[],
+ session_id="s9", now=100.0,
+ )
+ det_key = store.upsert_structured(
+ "det1",
+ kind="user_correction",
+ title="Never run ruff format",
+ structured={"decision": "the deterministic text", "verification": "exact"},
+ quotes=[QUOTE],
+ files=[],
+ session_id="s9",
+ now=100.0,
+ )
+ store.add_raw(
+ hash_="dis1", kind=DISCOVERY_KIND, quotes=[QUOTE], files=[],
+ session_id="s8", now=100.0,
+ )
+ dis_key = store.upsert_structured(
+ "dis1",
+ kind=DISCOVERY_KIND,
+ title="Never run ruff format",
+ structured={"decision": "the discovery text", "verification": "exact"},
+ quotes=[QUOTE],
+ files=[],
+ session_id="s8",
+ lane=DISCOVERY_KIND,
+ now=100.0,
+ )
+ store.commit()
+ assert det_key != dis_key
+ rows = {row["key"]: row for row in store.promotable()}
+ assert rows[det_key]["kind"] == "user_correction"
+ assert rows[det_key]["structured"]["decision"] == "the deterministic text"
+ assert dis_key not in rows # one discovery observation does not promote
+
+
+def test_pending_spans_are_never_pruned_before_they_are_read(tmp_path):
+ _queue(tmp_path, [_span(1), _span(2)], now=100.0)
+ with SessionStagingStore.open_default(tmp_path) as store:
+ store.mark_discovery_consumed(["span01"], now=100.0)
+ store.commit()
+ store.prune(now=100.0 + 200 * 86400)
+ store.commit()
+ assert store.pending_discovery_count() == 1
+
+
+async def test_a_second_sighting_of_a_claim_accretes_rather_than_duplicating(tmp_path):
+ provider = FakeProvider(json.dumps(_payload(_candidate())))
+ _queue(tmp_path, [_span(1, "s1")], now=100.0)
+ first = await run_update_discovery(
+ tmp_path, provider=provider, policy=preset_policy("balanced"), now=200.0
+ )
+ _queue(tmp_path, [_span(2, "s2")], now=300.0)
+ provider.content = json.dumps(_payload(_candidate(span_ids=["span02"])))
+ second = await run_update_discovery(
+ tmp_path, provider=provider, policy=preset_policy("balanced"), now=400.0
+ )
+ assert (first.report.candidates_new, first.report.candidates_accreted) == (1, 0)
+ assert (second.report.candidates_new, second.report.candidates_accreted) == (0, 1)
+
+
+async def test_an_exhausted_span_does_not_retire_an_unrelated_one(tmp_path):
+ _queue(tmp_path, [_span(1, "s1")], now=100.0)
+ provider = FakeProvider(error=RuntimeError("boom"))
+ policy = preset_policy("balanced").with_discovery(max_sessions=1)
+ for attempt in range(MAX_SPAN_ATTEMPTS):
+ _queue(tmp_path, [_span(90 + attempt, "s2")], now=200.0 + attempt)
+ await run_update_discovery(
+ tmp_path, provider=provider, policy=policy, now=300.0 + attempt
+ )
+ with SessionStagingStore.open_default(tmp_path) as store:
+ remaining = {row["span_id"] for row in store.pending_discovery_spans(10)}
+ assert "span01" not in remaining # exhausted its retries
+ assert remaining # the untried session behind it is untouched
diff --git a/tests/unit/analysis/test_decision_policy.py b/tests/unit/analysis/test_decision_policy.py
index f3d9edd7e..579503da1 100644
--- a/tests/unit/analysis/test_decision_policy.py
+++ b/tests/unit/analysis/test_decision_policy.py
@@ -11,6 +11,7 @@ from repowise.core.analysis.decisions.policy import (
CAPTURE_SOURCE_KEYS,
PRESET_NAMES,
SOURCE_SPECS,
+ DiscoveryBudget,
preset_policy,
resolve_policy,
)
@@ -42,9 +43,13 @@ def test_absent_config_resolves_to_prior_behaviour(config):
assert policy.enabled is True
assert policy.llm is True
- assert all(policy.source_enabled(key) for key in CAPTURE_SOURCE_KEYS)
- assert all(policy.llm_allowed(key) for key in CAPTURE_SOURCE_KEYS)
- assert policy.preset_name() == "full"
+ legacy = [key for key in CAPTURE_SOURCE_KEYS if key != "session_discovery"]
+ assert all(policy.source_enabled(key) for key in legacy)
+ assert all(policy.llm_allowed(key) for key in legacy)
+ # A source added after this config shape existed is off until asked for:
+ # an upgrade must not start a model call nobody enabled.
+ assert policy.source_enabled("session_discovery") is False
+ assert policy.preset_name() == "default"
def test_legacy_session_mining_false_disables_the_session_source():
@@ -93,7 +98,11 @@ def test_retired_source_keys_say_retired_not_unknown(retired):
assert any(retired in w and "retired" in w for w in resolution.warnings)
assert not any("Unknown decision source" in w for w in resolution.warnings)
- assert all(resolution.policy.source_enabled(key) for key in CAPTURE_SOURCE_KEYS)
+ assert all(
+ resolution.policy.source_enabled(key)
+ for key in CAPTURE_SOURCE_KEYS
+ if key != "session_discovery"
+ )
@pytest.mark.parametrize(
@@ -343,3 +352,123 @@ def test_a_broken_config_file_raises_rather_than_resolving_to_defaults(tmp_path)
with pytest.raises(RepoConfigError):
load_policy(tmp_path)
+
+
+# ---------------------------------------------------------------------------
+# Broad session discovery: opt-in, and its budget
+# ---------------------------------------------------------------------------
+
+
+def test_discovery_is_off_by_default_and_on_in_the_discovery_presets():
+ assert preset_policy("default").source_enabled("session_discovery") is False
+ assert preset_policy("off").source_enabled("session_discovery") is False
+ assert preset_policy("local_only").llm_allowed("session_discovery") is False
+ assert preset_policy("balanced").llm_allowed("session_discovery") is True
+ assert preset_policy("full").llm_allowed("session_discovery") is True
+
+
+def test_the_legacy_default_is_not_the_full_preset():
+ """Reusing ``full`` here is how a new source switches itself on everywhere."""
+ assert resolve_policy(None).policy != preset_policy("full")
+
+
+def test_discovery_has_no_deterministic_stage_so_llm_off_disables_it():
+ policy = preset_policy("balanced").with_llm(False)
+ runtime = {rt.key: rt for rt in policy.runtime(provider_available=True)}
+
+ assert runtime["session_discovery"].status == "disabled"
+ assert policy.llm_allowed("session_discovery") is False
+
+
+def test_discovery_without_a_provider_is_skipped_not_failed():
+ runtime = {
+ rt.key: rt for rt in preset_policy("balanced").runtime(provider_available=False)
+ }
+ assert runtime["session_discovery"].status == "skipped_no_provider"
+
+
+def test_discovery_budget_round_trips_through_the_config_block():
+ policy = preset_policy("balanced").with_discovery(max_sessions=4, max_input_tokens=9000)
+ block = policy.to_config_block()
+
+ assert block["discovery"] == {"max_sessions": 4, "max_input_tokens": 9000}
+ assert resolve_policy({"decisions": block}).policy == policy
+ assert policy.preset_name() == "custom"
+
+
+def test_a_default_budget_is_not_written_back():
+ assert "discovery" not in preset_policy("balanced").to_config_block()
+
+
+ "raw",
+ [
+ {"max_sessions": 0},
+ {"max_sessions": 999},
+ {"max_input_tokens": 10},
+ {"max_input_tokens": 10_000_000},
+ {"max_sessions": "twelve"},
+ {"max_sessions": True},
+ ],
+)
+def test_out_of_range_budgets_warn_and_fall_back(raw):
+ resolution = resolve_policy({"decisions": {"discovery": raw}})
+
+ assert resolution.warnings
+ assert resolution.policy.discovery == DiscoveryBudget()
+
+
+def test_a_non_mapping_discovery_block_warns():
+ resolution = resolve_policy({"decisions": {"discovery": "big"}})
+
+ assert any("discovery" in w for w in resolution.warnings)
+ assert resolution.policy.discovery == DiscoveryBudget()
+
+
+def test_with_discovery_rejects_an_out_of_range_value():
+ with pytest.raises(ValueError, match="max_sessions"):
+ preset_policy("balanced").with_discovery(max_sessions=0)
+
+
+def test_a_stored_preset_does_not_adopt_a_source_added_after_it_was_written():
+ """The upgrade path that `_LEGACY_DEFAULT` alone does not cover.
+
+ `write_policy` stamps `preset:` into every config it writes, alongside a
+ `sources:` block enumerating every source that existed then. Resolving the
+ preset's *current* membership over that block is how a stored `balanced`
+ would silently acquire a model call on upgrade.
+ """
+ stored = {
+ "decisions": {
+ "preset": "balanced",
+ "enabled": True,
+ "llm": True,
+ "sources": {
+ "inline_marker": True,
+ "git_archaeology": True,
+ "adr": True,
+ "pr": True,
+ "comment": False,
+ "session": True,
+ },
+ }
+ }
+ policy = resolve_policy(stored).policy
+
+ assert policy.source_enabled("session_discovery") is False
+ assert policy.llm_allowed("session_discovery") is False
+ assert policy.source_enabled("session") is True
+
+
+def test_a_bare_preset_declaration_still_gets_its_current_membership():
+ """No enumeration means no claim about which sources it covered."""
+ policy = resolve_policy({"decisions": {"preset": "balanced"}}).policy
+
+ assert policy.llm_allowed("session_discovery") is True
+
+
+def test_a_preset_written_today_round_trips_with_discovery_on():
+ policy = preset_policy("balanced")
+ stored = {"decisions": {**policy.to_config_block(), "preset": "balanced"}}
+
+ assert resolve_policy(stored).policy == policy
diff --git a/tests/unit/cli/test_decision_config_cmd.py b/tests/unit/cli/test_decision_config_cmd.py
index 86f508c88..611c844dc 100644
--- a/tests/unit/cli/test_decision_config_cmd.py
+++ b/tests/unit/cli/test_decision_config_cmd.py
@@ -53,9 +53,10 @@ def test_show_json_lists_every_source(repo: Path):
"pr",
"comment",
"session",
+ "session_discovery",
"cli",
]
- assert payload["policy"]["preset"] == "full"
+ assert payload["policy"]["preset"] == "default"
def test_show_table_renders_without_a_config(repo: Path):
@@ -241,3 +242,84 @@ def test_a_broken_config_is_a_clean_error_not_a_traceback(repo: Path):
assert result.exit_code != 0
assert "Could not parse" in result.output
assert "Traceback" not in result.output
+
+
+# ---------------------------------------------------------------------------
+# config discovery
+# ---------------------------------------------------------------------------
+
+
+def test_discovery_budget_writes_and_reports(repo: Path):
+ result = _run(
+ "decision", "config", "discovery", str(repo),
+ "--max-sessions", "4", "--max-input-tokens", "9000",
+ "--format", "json",
+ )
+
+ assert result.exit_code == 0, result.output
+ assert json.loads(result.output)["policy"]["discovery"] == {
+ "max_sessions": 4,
+ "max_input_tokens": 9000,
+ }
+ assert _config(repo)["decisions"]["discovery"] == {
+ "max_sessions": 4,
+ "max_input_tokens": 9000,
+ }
+
+
+def test_discovery_budget_setting_one_field_keeps_the_other(repo: Path):
+ _run("decision", "config", "discovery", str(repo), "--max-input-tokens", "9000")
+ _run("decision", "config", "discovery", str(repo), "--max-sessions", "4")
+
+ assert _config(repo)["decisions"]["discovery"] == {
+ "max_sessions": 4,
+ "max_input_tokens": 9000,
+ }
+
+
+def test_discovery_budget_with_no_flags_only_reports(repo: Path):
+ result = _run("decision", "config", "discovery", str(repo), "--format", "json")
+
+ assert result.exit_code == 0, result.output
+ assert not (repo / ".repowise" / "config.yaml").exists()
+
+
+def test_discovery_budget_rejects_an_out_of_range_value(repo: Path):
+ result = _run("decision", "config", "discovery", str(repo), "--max-sessions", "0")
+
+ assert result.exit_code != 0
+ assert "between 1 and 24" in result.output
+
+
+def test_discovery_budget_dry_run_writes_nothing(repo: Path):
+ result = _run(
+ "decision", "config", "discovery", str(repo), "--max-sessions", "4", "--dry-run"
+ )
+
+ assert result.exit_code == 0, result.output
+ assert "discovery.max_sessions" in result.output
+ assert not (repo / ".repowise" / "config.yaml").exists()
+
+
+def test_discovery_budget_resolves_its_target_like_every_sibling(repo: Path, monkeypatch):
+ """It must not bypass workspace/primary-repo redirection with its own resolve()."""
+ seen: list[object] = []
+
+ def _spy(path=None, **kw):
+ seen.append(path)
+ from repowise.cli.helpers import resolve_command_target
+
+ return resolve_command_target(path=path, **kw)
+
+ monkeypatch.setattr("repowise.cli.commands.decision_cmd.resolve_command_target", _spy)
+ result = _run("decision", "config", "discovery", str(repo), "--max-sessions", "4")
+
+ assert result.exit_code == 0, result.output
+ assert seen == [str(repo)]
+
+
+def test_switching_discovery_on_is_an_ordinary_source_toggle(repo: Path):
+ result = _run("decision", "source", "set", "session_discovery", str(repo), "--on")
+
+ assert result.exit_code == 0, result.output
+ assert _config(repo)["decisions"]["sources"]["session_discovery"] is True
diff --git a/tests/unit/pipeline/test_decision_source_reporting.py b/tests/unit/pipeline/test_decision_source_reporting.py
index 044f0bf49..5ee0917fb 100644
--- a/tests/unit/pipeline/test_decision_source_reporting.py
+++ b/tests/unit/pipeline/test_decision_source_reporting.py
@@ -155,3 +155,93 @@ async def test_a_disabled_source_is_reported_as_switched_off(tmp_path, monkeypat
assert "comments" in not_run
assert "agent sessions" in not_run
assert "switched off" in not_run
+
+
+async def test_discovery_off_is_reported_as_not_run_and_makes_no_call(_patched):
+ """The default policy: the source exists, is off, and reaches no provider."""
+
+ class _Exploding:
+ async def generate(self, *_a, **_k):
+ raise AssertionError("a model call was made with discovery off")
+
+ progress = _RecordingProgress()
+
+ await _run_decision_extraction(
+ _patched,
+ llm_client=_Exploding(),
+ graph_builder=SimpleNamespace(graph=lambda: None),
+ git_meta_map={},
+ parsed_files=[],
+ progress=progress,
+ )
+
+ # A swallowed call would surface as a failed source, not as "not run".
+ assert "discovery" not in progress.text_at("warning").lower()
+ not_run = next(t for lvl, t in progress.messages if lvl == "info" and "Not run" in t)
+ assert "session discovery" in not_run
+ assert "switched off" in not_run
+ for level, text in progress.messages:
+ if level == "info" and "Nothing found" in text:
+ assert "session discovery" not in text
+
+
+async def test_discovery_enabled_with_no_prose_is_an_honest_zero(tmp_path, monkeypatch):
+ """Ran and found nothing is not the same state as never ran."""
+ import repowise.core.analysis.decision_extractor as de
+
+ monkeypatch.setattr(de, "DecisionExtractor", _StubExtractor)
+ _write_policy(tmp_path, session=False, session_discovery=True)
+ progress = _RecordingProgress()
+
+ await _run_decision_extraction(
+ tmp_path,
+ llm_client=SimpleNamespace(),
+ graph_builder=SimpleNamespace(graph=lambda: None),
+ git_meta_map={},
+ parsed_files=[],
+ progress=progress,
+ )
+
+ nothing = next(t for lvl, t in progress.messages if lvl == "info" and "Nothing found" in t)
+ assert "session discovery" in nothing
+ not_run = [t for lvl, t in progress.messages if lvl == "info" and "Not run" in t]
+ for line in not_run:
+ assert "session discovery" not in line
+
+
+async def test_discovery_candidates_are_reported_even_when_nothing_promotes(
+ tmp_path, monkeypatch
+):
+ """The first sighting is the normal case, and it must not vanish.
+
+ A grounded candidate needs a second session before it is proposed, so a
+ successful first run has zero promotions. Reporting that as an honest zero
+ would hide the whole lane on exactly the run that found something.
+ """
+ import repowise.core.analysis.decision_extractor as de
+ import repowise.core.pipeline.phases.analysis as phase
+ from repowise.core.analysis.decisions.discovery import DiscoveryOutcome, DiscoveryReport
+
+ monkeypatch.setattr(de, "DecisionExtractor", _StubExtractor)
+ _write_policy(tmp_path, session=False, session_discovery=True)
+
+ async def _fake(*_a, **_k):
+ return DiscoveryOutcome(report=DiscoveryReport(status="ran", candidates_grounded=3))
+
+ monkeypatch.setattr(phase, "run_update_discovery", _fake)
+ progress = _RecordingProgress()
+
+ await _run_decision_extraction(
+ tmp_path,
+ llm_client=SimpleNamespace(),
+ graph_builder=SimpleNamespace(graph=lambda: None),
+ git_meta_map={},
+ parsed_files=[],
+ progress=progress,
+ )
+
+ info = progress.text_at("info")
+ assert "3 session-discovery candidate(s) staged for review" in info
+ for level, text in progress.messages:
+ if level == "info" and ("Nothing found" in text or "Not run" in text):
+ assert "session discovery" not in text
diff --git a/tests/unit/server/test_decision_settings_api.py b/tests/unit/server/test_decision_settings_api.py
index 718425a2e..4e73c700e 100644
--- a/tests/unit/server/test_decision_settings_api.py
+++ b/tests/unit/server/test_decision_settings_api.py
@@ -44,9 +44,10 @@ async def test_get_returns_the_full_source_registry(client: AsyncClient):
"pr",
"comment",
"session",
+ "session_discovery",
"cli",
]
- assert body["preset"] == "full"
+ assert body["preset"] == "default"
assert body["enabled"] is True
assert body["etag"]
@@ -234,3 +235,47 @@ async def test_a_repo_with_no_checkout_on_this_server_is_a_404(client: AsyncClie
assert resp.status_code == 404
assert "not accessible" in resp.json()["detail"]
+
+
+async def test_put_discovery_merges_rather_than_replacing(client: AsyncClient):
+ """A UI sending one budget field must not reset the other to its default."""
+ repo = await create_test_repo(client)
+ await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings",
+ json={"discovery": {"max_sessions": 4, "max_input_tokens": 50000}},
+ )
+
+ resp = await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings",
+ json={"discovery": {"max_sessions": 6}},
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["discovery"] == {"max_sessions": 6, "max_input_tokens": 50000}
+
+
+async def test_put_preset_keeps_a_custom_discovery_budget(client: AsyncClient):
+ """A preset names source membership; the budget is not part of it."""
+ repo = await create_test_repo(client)
+ await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings",
+ json={"discovery": {"max_sessions": 4}},
+ )
+
+ resp = await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings", json={"preset": "balanced"}
+ )
+
+ assert resp.status_code == 200
+ assert resp.json()["discovery"]["max_sessions"] == 4
+
+
+async def test_put_rejects_an_out_of_range_budget(client: AsyncClient):
+ repo = await create_test_repo(client)
+
+ resp = await client.put(
+ f"/api/repos/{repo['id']}/decisions/settings",
+ json={"discovery": {"max_sessions": 999}},
+ )
+
+ assert resp.status_code == 422
diff --git a/tests/unit/sessions/test_session_decisions_e2e.py b/tests/unit/sessions/test_session_decisions_e2e.py
index dc1164fd9..3c4a8bafe 100644
--- a/tests/unit/sessions/test_session_decisions_e2e.py
+++ b/tests/unit/sessions/test_session_decisions_e2e.py
@@ -302,3 +302,79 @@ async def test_a_repo_with_no_transcripts_derives_nothing_and_deletes_nothing(tm
)
assert decisions == []
assert not episode_store_path(repo_root).exists()
+
+
+# ---------------------------------------------------------------------------
+# Broad discovery rides the same read (one cursor, one pass over the bytes)
+# ---------------------------------------------------------------------------
+
+
+async def test_discovery_spans_are_collected_only_when_asked(tmp_path):
+ repo_root = tmp_path / "repo"
+ repo_root.mkdir()
+ projects_root = tmp_path / "projects"
+ _write_transcript(repo_root, projects_root, "one.jsonl", "sess-1", CORRECTION)
+
+ await mine_session_decisions(
+ repo_root, provider=None, projects_root=projects_root, now=100.0
+ )
+ with SessionStagingStore(default_store_path(repo_root)) as store:
+ assert store.pending_discovery_count() == 0
+
+
+async def test_discovery_spans_ride_the_miners_single_transcript_read(tmp_path):
+ repo_root = tmp_path / "repo"
+ repo_root.mkdir()
+ projects_root = tmp_path / "projects"
+ _write_transcript(repo_root, projects_root, "one.jsonl", "sess-1", CORRECTION)
+
+ await mine_session_decisions(
+ repo_root,
+ provider=None,
+ projects_root=projects_root,
+ collect_discovery_spans=True,
+ now=100.0,
+ )
+ with SessionStagingStore(default_store_path(repo_root)) as store:
+ spans = store.pending_discovery_spans(10)
+ assert [span["session_id"] for span in spans] == ["sess-1"]
+ assert CORRECTION in spans[0]["text"]
+
+ # The cursor already consumed those bytes, so a second pass adds nothing.
+ await mine_session_decisions(
+ repo_root,
+ provider=None,
+ projects_root=projects_root,
+ collect_discovery_spans=True,
+ now=200.0,
+ )
+ with SessionStagingStore(default_store_path(repo_root)) as store:
+ assert store.pending_discovery_count() == 1
+
+
+async def test_a_span_from_another_checkout_is_not_collected(tmp_path):
+ repo_root = tmp_path / "repo"
+ repo_root.mkdir()
+ other = tmp_path / "other"
+ other.mkdir()
+ projects_root = tmp_path / "projects"
+ directory = transcript_dir_for(repo_root, projects_root)
+ directory.mkdir(parents=True, exist_ok=True)
+ entry = {
+ "type": "user",
+ "cwd": str(other),
+ "timestamp": "2026-07-11T10:00:00.000Z",
+ "sessionId": "sess-elsewhere",
+ "message": {"role": "user", "content": [{"type": "text", "text": CORRECTION}]},
+ }
+ (directory / "one.jsonl").write_text(json.dumps(entry) + "\n", encoding="utf-8")
+
+ await mine_session_decisions(
+ repo_root,
+ provider=None,
+ projects_root=projects_root,
+ collect_discovery_spans=True,
+ now=100.0,
+ )
+ with SessionStagingStore(default_store_path(repo_root)) as store:
+ assert store.pending_discovery_count() == 0