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.

fix(sessions): scope Codex transcripts to the repo that owns them (#2387)

Raghav Chamadiyaca933adbca87
diff --git a/docs/layers/DECISIONS.md b/docs/layers/DECISIONS.md
index 5fa582c81..1eb4dcf15 100644
--- a/docs/layers/DECISIONS.md
+++ b/docs/layers/DECISIONS.md
@@ -485,6 +485,21 @@ stated reason, and failed approaches replaced by working ones. Claude Code
transcripts come from `~/.claude/projects/`, read incrementally from a cursor so
each line is processed once.
+Claude Code is the only harness read unless you name another:
+
+```yaml
+decisions:
+ harnesses: [claude_code, codex]
+```
+
+Adding one is a real widening rather than a preference. Codex files its
+sessions by date rather than by project, so its store holds every session on
+the machine and the repository a line belongs to is decided by the working
+directory recorded in it, not by where the file sits. Sessions bulk-imported
+into that store from another harness are skipped, because the harness that
+recorded them already reads them and counting them here would count one
+conversation twice.
+
Three stages, in order:
1. **Deterministic gates.** A user correction needs a pushback lead ("no,",
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.md
index 8d54ee9cc..71a1696a8 100644
--- a/docs/reference/CONFIG.md
+++ b/docs/reference/CONFIG.md
@@ -409,6 +409,8 @@ decisions:
discovery: # budget for that one pass, per update
max_sessions: 12 # 1-24
max_input_tokens: 30000 # 2000-60000
+ harnesses: # whose transcripts the session lane reads
+ - claude_code # the default; add codex to read that store too
```
Every key is optional. **A config with no `decisions:` block behaves exactly as
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 832b3e0c7..f7f6f405c 100644
--- a/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/decision_config_cmd.py
@@ -107,6 +107,9 @@ def _emit(repo_path: Path, resolution, fmt: str) -> None:
f" [dim]Discovery budget: up to {budget.max_sessions} session(s), "
f"{budget.max_input_tokens:,} input tokens per update.[/dim]"
)
+ # Named even at the default: this is the one setting that widens whose
+ # transcripts are read, and a reader cannot check a line that is absent.
+ console.print(f" [dim]Harnesses read: {', '.join(policy.harnesses)}.[/dim]")
console.print("")
for warning in resolution.warnings:
@@ -175,6 +178,14 @@ def _diff(before: DecisionPolicy, after: DecisionPolicy) -> list[dict[str, str]]
changes.append(
{"key": f"discovery.{key}", "from": str(old_value), "to": str(new_value)}
)
+ if before.harnesses != after.harnesses:
+ changes.append(
+ {
+ "key": "harnesses",
+ "from": ", ".join(before.harnesses),
+ "to": ", ".join(after.harnesses),
+ }
+ )
return changes
@@ -206,11 +217,16 @@ def config_show(path: str | None, fmt: str) -> None:
@format_option()
def config_preset(name: str, path: str | None, dry_run: bool, fmt: str) -> None:
"""Apply a named preset: default, off, local_only, balanced, full."""
+ from dataclasses import replace
+
from repowise.cli.commands.decision_cmd import _resolve_decision_repo
from repowise.core.analysis.decisions.policy import preset_policy
repo_path = _resolve_decision_repo(path, fmt)
- _apply(repo_path, preset_policy(name), fmt, dry_run)
+ # A preset names source membership, not which harnesses are read, so the
+ # harness list the caller did not touch survives applying one.
+ current = _load(repo_path).policy
+ _apply(repo_path, replace(preset_policy(name), harnesses=current.harnesses), fmt, dry_run)
# ---------------------------------------------------------------------------
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 03e7fd5b1..4dd0c97b7 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -1861,6 +1861,7 @@ def run_update(
mine_session_decisions(
repo_path,
provider=session_provider,
+ harnesses=decision_policy.harnesses,
collect_discovery_spans=decision_policy.llm_allowed("session_discovery"),
)
)
diff --git a/packages/core/src/repowise/core/analysis/decisions/policy.py b/packages/core/src/repowise/core/analysis/decisions/policy.py
index d4a4924f4..599b9d629 100644
--- a/packages/core/src/repowise/core/analysis/decisions/policy.py
+++ b/packages/core/src/repowise/core/analysis/decisions/policy.py
@@ -219,6 +219,12 @@ class DiscoveryBudget:
_DEFAULT_DISCOVERY = DiscoveryBudget()
+#: Harnesses whose transcripts the session lane reads. One name per registered
+#: transcript adapter. Only Claude Code by default: a harness added to the
+#: registry is a reader this repository has not asked for, and switching one on
+#: makes a machine's whole history for that agent eligible on the next update.
+DEFAULT_HARNESSES: tuple[str, ...] = ("claude_code",)
+
@dataclass(frozen=True, slots=True)
class SourceSetting:
@@ -337,6 +343,7 @@ class DecisionPolicy:
llm: bool
sources: dict[str, SourceSetting]
discovery: DiscoveryBudget = _DEFAULT_DISCOVERY
+ harnesses: tuple[str, ...] = DEFAULT_HARNESSES
# -- queries ---------------------------------------------------------
@@ -394,6 +401,7 @@ class DecisionPolicy:
and self.llm == spec["llm"]
and self.sources == spec["sources"]
and self.discovery == _DEFAULT_DISCOVERY
+ and self.harnesses == DEFAULT_HARNESSES
):
return name
return "custom"
@@ -475,6 +483,8 @@ class DecisionPolicy:
}
if self.discovery != _DEFAULT_DISCOVERY:
block["discovery"] = self.discovery.to_dict()
+ if self.harnesses != DEFAULT_HARNESSES:
+ block["harnesses"] = list(self.harnesses)
return block
def to_dict(self, *, provider_available: bool = True) -> dict[str, Any]:
@@ -484,6 +494,7 @@ class DecisionPolicy:
"llm": self.llm,
"preset": self.preset_name(),
"discovery": self.discovery.to_dict(),
+ "harnesses": list(self.harnesses),
"sources": [rt.to_dict() for rt in self.runtime(provider_available=provider_available)],
}
@@ -555,6 +566,35 @@ def _resolve_discovery(raw: Any, warnings: list[str]) -> DiscoveryBudget:
return DiscoveryBudget(**fields)
+def _resolve_harnesses(raw: Any, warnings: list[str]) -> tuple[str, ...]:
+ """Transcript adapters named by ``decisions.harnesses``, validated.
+
+ Validated against the registry rather than a list here, so adding an
+ adapter stays one registration. An unknown name is dropped with a warning
+ instead of failing the run: a config written against a newer repowise must
+ not stop this one from indexing.
+ """
+ if raw is None:
+ return DEFAULT_HARNESSES
+ if not isinstance(raw, list):
+ warnings.append("`decisions.harnesses:` is not a list; ignoring it.")
+ return DEFAULT_HARNESSES
+ from repowise.core.sessions.adapters.registry import registered_adapters
+
+ known = set(registered_adapters())
+ names: list[str] = []
+ for value in raw:
+ if not isinstance(value, str) or value not in known:
+ warnings.append(f"Unknown harness `{value}` in `decisions.harnesses`; ignoring it.")
+ continue
+ if value not in names:
+ names.append(value)
+ if not names:
+ warnings.append("`decisions.harnesses` named no known harness; using the default.")
+ return DEFAULT_HARNESSES
+ return tuple(names)
+
+
def preset_policy(name: str) -> DecisionPolicy:
"""The policy a named preset resolves to."""
spec = PRESETS.get(name)
@@ -698,14 +738,15 @@ def resolve_policy(repo_config: dict[str, Any] | None) -> PolicyResolution:
warnings.append("`decisions.session_mining` is not a boolean; ignoring it.")
discovery = _resolve_discovery(raw.get("discovery"), warnings)
+ harnesses = _resolve_harnesses(raw.get("harnesses"), warnings)
- known = {"preset", "enabled", "llm", "sources", "session_mining", "discovery"}
+ known = {"preset", "enabled", "llm", "sources", "session_mining", "discovery", "harnesses"}
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, discovery=discovery
+ enabled=enabled, llm=llm, sources=sources, discovery=discovery, harnesses=harnesses
),
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 4011f24b6..f8d7b59c0 100644
--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py
@@ -451,6 +451,7 @@ async def _run_decision_extraction(
mine_session_decisions(
repo_path,
provider=session_provider,
+ harnesses=policy.harnesses,
collect_discovery_spans=policy.llm_allowed("session_discovery"),
),
timeout=DECISION_EXTRACTION_TIMEOUT_SECS,
diff --git a/packages/core/src/repowise/core/sessions/README.md b/packages/core/src/repowise/core/sessions/README.md
index 250c0b86b..1eb6cb598 100644
--- a/packages/core/src/repowise/core/sessions/README.md
+++ b/packages/core/src/repowise/core/sessions/README.md
@@ -12,27 +12,47 @@ own machine and never leave it.
| File | What it holds |
|------|---------------|
| `events.py` | The `Event` / `ToolUse` / `ToolResult` model, the `INTERRUPT_MARKER` constant, and `iter_deduped_usage` |
-| `adapters/base.py` | The `HarnessAdapter` contract: `discover()` + `normalize()`, with shared `iter_events()` built on top |
-| `adapters/claude_code.py` | First adapter: `~/.claude/projects/<munged-cwd>/*.jsonl` |
+| `adapters/base.py` | The `HarnessAdapter` contract, with shared `iter_events()` built on top |
+| `adapters/claude_code.py` | `~/.claude/projects/<munged-cwd>/*.jsonl`, one cwd per line |
+| `adapters/codex.py` | `~/.codex/sessions/YYYY/MM/DD/*.jsonl`, one cwd per file |
+| `adapters/registry.py` | Which adapter a consumer gets by name, and the default |
| `cursor.py` | `CursorStore` (byte offset + mtime per file) and `iter_new_events` for incremental scans |
| `staging.py` | `SessionStagingStore`: the `.repowise/sessions/sessions.db` sidecar (WAL) holding mined candidates, observation counts, and DB-backed cursors |
| `miners/decisions.py` | Session-sourced decisions: deterministic gates over Events, one batched LLM structuring pass per update, observation-counted promotion |
## The contract
-An adapter implements exactly two things:
+An adapter must implement two things:
- `discover(repo_root, projects_root=None)`: transcript files for sessions
rooted at a repo. Absent directory means empty list, never an error.
+ `projects_root` is a sandbox, so an adapter given one never reads outside
+ it.
- `normalize(raw_line)`: one raw transcript line to an `Event`, or `None`
when the line is unparseable. Never raises on content.
+and may implement three more:
+
+- `prefilter(intent)`: a gate on the raw string for a named intent.
+- `begin_file(path)` / `end_file()`: scope per-transcript state.
+
Iteration, prefiltering, and cursoring are shared code. Consumers that only
care about a slice of the stream pass a `prefilter` callable that gates on
the raw string before any JSON parsing happens; transcript lines routinely
run to hundreds of kilobytes, so this is the difference between skimming and
parsing whole sessions.
+**A prefilter must admit whatever line carries the scoping `cwd`.** For a
+harness that states it once per file rather than once per line, a gate that
+drops that line leaves every event unscoped, and an empty `cwd` reads as "no
+opinion" to the miners rather than as a miss, so one repository's sessions
+land in another's records.
+
+**Per-file state is reset, not replayed.** A cursored read resumes mid-file
+and `begin_file` runs on the tail, so anything an adapter learned from the
+top of the file is gone. An adapter that threads state forward rebuilds it
+from the head itself; see `CodexAdapter._seed_from_head`.
+
## Claude Code schema gotchas (encoded in the adapter and fixtures)
- One API message spans several JSONL lines (one per content block) and each
diff --git a/packages/core/src/repowise/core/sessions/__init__.py b/packages/core/src/repowise/core/sessions/__init__.py
index d163ed2dc..9462f54cc 100644
--- a/packages/core/src/repowise/core/sessions/__init__.py
+++ b/packages/core/src/repowise/core/sessions/__init__.py
@@ -2,12 +2,13 @@
One normalized :class:`Event` stream over coding-agent transcripts, behind a
:class:`HarnessAdapter` interface so consumers never parse harness-specific
-JSONL themselves. Claude Code is the first adapter; Codex and others slot in
-behind the same interface later.
+JSONL themselves. Claude Code and Codex today, behind the same interface;
+which of them a repository actually reads is a config question, not a
+registry one.
-Consumers today are the distill transcript miners (missed savings, wasteful
-re-reads, correction mining). Session decision mining rides the same stream
-next.
+Consumers are the distill transcript miners (missed savings, wasteful
+re-reads, correction mining) and session decision mining, which rides the
+same stream.
Everything here is read-only and local: transcripts are read from the user's
own machine and never leave it.
diff --git a/packages/core/src/repowise/core/sessions/adapters/base.py b/packages/core/src/repowise/core/sessions/adapters/base.py
index b5093747c..41a8aa172 100644
--- a/packages/core/src/repowise/core/sessions/adapters/base.py
+++ b/packages/core/src/repowise/core/sessions/adapters/base.py
@@ -4,7 +4,9 @@ An adapter knows two things about its agent: where transcripts for a given
repo live (:meth:`HarnessAdapter.discover`) and how one raw transcript line
becomes a normalized :class:`~repowise.core.sessions.events.Event`
(:meth:`HarnessAdapter.normalize`). Iteration, cursoring, and mining are
-shared code built on those two primitives.
+shared code built on those two primitives. Three optional hooks scope the
+rest: :meth:`HarnessAdapter.prefilter` and the per-file
+:meth:`HarnessAdapter.begin_file` / :meth:`HarnessAdapter.end_file`.
Best-effort contract, matching the distill miners this layer was extracted
from: ``normalize`` returns None for anything it cannot parse rather than
@@ -70,6 +72,12 @@ class HarnessAdapter(ABC):
None means "no cheap gate for this intent", so every line is parsed.
Correct but slow, which is the right default for an intent an
adapter has not thought about.
+
+ Not purely a speed knob for a harness that states its ``cwd`` once
+ per file rather than once per line: dropping that line leaves every
+ event unscoped, and the miners read a blank ``cwd`` as "no opinion"
+ rather than as a miss. A gate for such a harness admits the line
+ carrying it, however narrow the rest of the gate is.
"""
return None
diff --git a/packages/core/src/repowise/core/sessions/adapters/codex.py b/packages/core/src/repowise/core/sessions/adapters/codex.py
index 9959ce6e8..c8b1dbeab 100644
--- a/packages/core/src/repowise/core/sessions/adapters/codex.py
+++ b/packages/core/src/repowise/core/sessions/adapters/codex.py
@@ -32,6 +32,18 @@ _SHELL_COMMAND_RE = re.compile(r'"command"\s*:\s*"([^"]*)"')
_RG_MATCH_RE = re.compile(r"^(?P<path>[^:]+(?::[^:\\/]*[\\/][^:]*)?):\d+:")
#: Lines the exec wrapper prints around a command's real output.
_EXEC_NOISE = ("Script ", "Exit code:", "Wall time", "Output:")
+#: Codex writes ``cwd`` once, on this line, and every later event inherits it
+#: from adapter state. A gate that drops it leaves every event unscoped, so
+#: every intent admits it however narrow the rest of the gate is.
+_SESSION_META = '"type":"session_meta"'
+#: Turn id on sessions bulk-imported from another harness into the Codex
+#: store. Those turns are that harness's, and its own adapter already reads
+#: them, so mining them here counts one session twice.
+_IMPORTED_TURN_PREFIX = "external-import-turn"
+#: Lines read from the top of a transcript to recover the facts a resume
+#: starts past. Both sit in the first two on every rollout measured; the
+#: margin is for a writer that adds a preamble, not for a search.
+_HEAD_LINES = 8
def _tool_calls_prefilter(raw: str) -> bool:
@@ -40,11 +52,13 @@ def _tool_calls_prefilter(raw: str) -> bool:
or '"type":"custom_tool_call_output"' in raw
or '"type":"function_call"' in raw
or '"type":"function_call_output"' in raw
+ # Last: it matches once per file, and every other line pays the scan.
+ or _SESSION_META in raw
)
def _turns_prefilter(raw: str) -> bool:
- return '"type":"event_msg"' in raw or '"type":"response_item"' in raw
+ return '"type":"event_msg"' in raw or '"type":"response_item"' in raw or _SESSION_META in raw
@register_adapter
@@ -57,6 +71,7 @@ class CodexAdapter(HarnessAdapter):
self._tool_calls: dict[str, ToolUse] = {}
self._current_session: str | None = None
self._current_cwd: str | None = None
+ self._imported = False
def discover(self, repo_root: Path, *, projects_root: Path | None = None) -> list[Path]:
"""Every Codex rollout, not just this repo's.
@@ -80,6 +95,15 @@ class CodexAdapter(HarnessAdapter):
return None
payload = entry.get("payload") if isinstance(entry.get("payload"), dict) else {}
+ # Only an import's turns carry the marker; the messages it replays
+ # look native. The latch is armed from the head in begin_file, so it
+ # holds for a gate that admits no turn lines and for a resumed read,
+ # and this is the belt for a marker that arrives later than the head.
+ turn_id = payload.get("turn_id")
+ if isinstance(turn_id, str) and turn_id.startswith(_IMPORTED_TURN_PREFIX):
+ self._imported = True
+ if self._imported:
+ return None
entry_kind = (
entry.get("type") if isinstance(entry.get("type"), str) and entry.get("type") else None
)
@@ -153,11 +177,42 @@ class CodexAdapter(HarnessAdapter):
self._tool_calls.clear()
self._current_session = None
self._current_cwd = None
+ self._imported = False
+ if path is not None:
+ self._seed_from_head(path)
+
+ def _seed_from_head(self, path: Path) -> None:
+ """Read the scoping facts off the top of the file, every pass.
+
+ Codex states ``cwd`` once and marks an import once, both within the
+ first few lines, and a cursored resume starts past them. Rebuilding
+ from the head rather than from the stream is what makes those facts
+ hold on an incremental run: without it the second pass onward carries
+ no cwd, and a blank cwd reads as "no opinion" to the miners, so one
+ repo's sessions land in another's records.
+
+ Normalizing those lines rather than re-reading their fields is the
+ point: the state they set is exactly what this needs, so there is one
+ parser to keep right. The events themselves are discarded, and the
+ correlation map with them, because the calls they pair with are
+ either behind the cursor already or still ahead of it.
+ """
+ try:
+ with path.open(encoding="utf-8", errors="replace") as fh:
+ for _ in range(_HEAD_LINES):
+ raw = fh.readline()
+ if not raw or self._imported:
+ break
+ self.normalize(raw)
+ except OSError:
+ pass
+ self._tool_calls.clear()
def end_file(self) -> None:
self._tool_calls.clear()
self._current_session = None
self._current_cwd = None
+ self._imported = False
def _fill_response_item(self, event: Event, payload: dict[str, Any]) -> None:
"""Handles response_item entries in Codex transcripts, and converts them to either text, tool uses or tool results
diff --git a/packages/core/src/repowise/core/sessions/miners/decisions.py b/packages/core/src/repowise/core/sessions/miners/decisions.py
index ba60c5d5d..5b8081fb1 100644
--- a/packages/core/src/repowise/core/sessions/miners/decisions.py
+++ b/packages/core/src/repowise/core/sessions/miners/decisions.py
@@ -49,7 +49,7 @@ import json
import re
import time
from collections import deque
-from collections.abc import Iterable
+from collections.abc import Iterable, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
@@ -58,7 +58,7 @@ 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.policy import DEFAULT_HARNESSES, resolve_policy
from repowise.core.analysis.decisions.provenance import (
completeness,
compute_confidence,
@@ -73,6 +73,7 @@ from repowise.core.precedent.transcript_episodes import (
record_transcript_episodes,
)
from repowise.core.sessions import INTENT_TURNS, Event, get_adapter
+from repowise.core.sessions.adapters.registry import DEFAULT_ADAPTER, registered_adapters
from repowise.core.sessions.cursor import iter_new_events
from repowise.core.sessions.events import (
FILE_INPUT_KEYS,
@@ -510,6 +511,110 @@ def session_mining_enabled(repo_config: dict[str, Any] | None) -> bool:
return resolve_policy(repo_config).policy.source_enabled("session")
+def harnesses_for(repo_path: Path) -> tuple[str, ...]:
+ """Harnesses this repo reads transcripts from, from its own config.
+
+ The fallback for a caller that holds no resolved policy. Both pipelines
+ do hold one and pass it, so this is not the usual path: two readings of
+ the same setting that can disagree is the drift worth avoiding.
+ """
+ from repowise.core.repo_config import load_repo_config
+
+ try:
+ policy = resolve_policy(load_repo_config(repo_path)).policy
+ except Exception:
+ return DEFAULT_HARNESSES
+ return registered_harnesses(policy.harnesses)
+
+
+def registered_harnesses(names: Sequence[str]) -> tuple[str, ...]:
+ """*names* that name a registered adapter, never empty.
+
+ An unregistered name is dropped rather than raised on: a config written
+ against a newer repowise must not stop this one from indexing. Falling
+ back is deliberate too, because an empty reader list and a repository
+ with no sessions produce the same silence.
+ """
+ known = set(registered_adapters())
+ return tuple(name for name in names if name in known) or DEFAULT_HARNESSES
+
+
+def _sweep_harness(
+ harness: str,
+ *,
+ repo_root: Path,
+ repo_prefix: str,
+ projects_root: Path | None,
+ store: SessionStagingStore,
+ recorder: TranscriptEpisodeRecorder,
+ collector: SpanCollector | None,
+ budget: float,
+ now: float | None,
+) -> dict[str, int]:
+ """Read one harness's new transcript lines, and report what it did.
+
+ The counts are the harness's own, and they are separate on purpose:
+ *read* is transcripts opened, so a reader that has stopped reading shows
+ a zero there next to a non-zero *discovered*, which one total cannot say.
+ """
+ adapter = get_adapter(harness)
+ # This miner needs user prose, assistant prose, tool uses and results:
+ # everything the conversation carries, minus the fat non-dialog lines.
+ prefilter = adapter.prefilter(INTENT_TURNS)
+ deadline = time.monotonic() + budget
+ discovered = adapter.discover(repo_root, projects_root=_root_for(harness, projects_root))
+ counts = {"discovered": len(discovered), "read": 0, "found": 0, "staged": 0, "deferred": 0}
+ # Every discovered transcript is present whether or not this run gets to
+ # read it; the episode writer notes absence on the row it can no longer
+ # point at, and keeps the episode.
+ recorder.note_present(discovered)
+ for index, path in enumerate(discovered):
+ if time.monotonic() > deadline:
+ # A first index on a machine with a long agent history reads the
+ # whole corpus from byte 0, and that corpus is bounded by how much
+ # the user has worked, not by the size of the repo. Stopping is
+ # safe and self-healing rather than lossy, because the cursor is
+ # per file and saved by the caller, so the next run resumes
+ # exactly where this one stopped. Steady state never reaches it.
+ counts["deferred"] = len(discovered) - index
+ break
+ try:
+ events = iter_new_events(adapter, path, store.cursors, prefilter=prefilter)
+ stream = recorder.observe(path, events)
+ if collector is not None:
+ stream = collector.observe(stream)
+ for candidate in mine_events(stream, repo_prefix):
+ counts["found"] += 1
+ if store.add_raw(
+ hash_=candidate.hash,
+ kind=candidate.kind,
+ quotes=candidate.quotes,
+ files=candidate.files,
+ session_id=candidate.session_id,
+ harness=harness,
+ now=now,
+ ):
+ counts["staged"] += 1
+ counts["read"] += 1
+ except OSError:
+ continue
+ return counts
+
+
+def _root_for(harness: str, projects_root: Path | None) -> Path | None:
+ """The transcript-root override, per harness.
+
+ The override is a sandbox, so nothing may read outside it: a caller that
+ passes one and gets a harness reading the real home directory has been
+ given the machine's whole history for that agent without asking. The
+ default harness keeps the root itself, so existing callers are unchanged,
+ and every other harness gets a subdirectory that is simply absent unless
+ the caller made one.
+ """
+ if projects_root is None:
+ return None
+ return projects_root if harness == DEFAULT_ADAPTER else projects_root / harness
+
def _candidates_block(raws: list[dict[str, Any]]) -> str:
parts: list[str] = []
@@ -803,6 +908,7 @@ async def mine_session_decisions(
*,
provider: Any | None,
projects_root: Path | None = None,
+ harnesses: Sequence[str] | None = None,
max_structured: int = MAX_STRUCTURED_PER_UPDATE,
collect_discovery_spans: bool = False,
now: float | None = None,
@@ -833,10 +939,13 @@ async def mine_session_decisions(
"""
repo_root = Path(repo_path).resolve()
repo_prefix = str(repo_root).lower().rstrip("\\/")
- adapter = get_adapter()
- # This miner needs user prose, assistant prose, tool uses and results:
- # everything the conversation carries, minus the fat non-dialog lines.
- prefilter = adapter.prefilter(INTENT_TURNS)
+ # The caller's resolved policy wins; reading config again here would be a
+ # second answer to a question it has already asked.
+ names = registered_harnesses(harnesses) if harnesses is not None else harnesses_for(repo_path)
+ # One recorder across every harness, and one write at the end. The episode
+ # writer resolves absence by negation over the tier, so a second write
+ # carrying only the second harness's subjects would mark the first's as
+ # sources that had gone away.
recorder = TranscriptEpisodeRecorder(repo_root)
store = SessionStagingStore.open_default(repo_root)
@@ -844,41 +953,34 @@ async def mine_session_decisions(
try:
# Stage new gate hits from transcript lines appended since last run.
staged = 0
- deadline = time.monotonic() + SWEEP_BUDGET_S
deferred = 0
- discovered = adapter.discover(repo_root, projects_root=projects_root)
- # Every discovered transcript is present whether or not this run gets
- # to read it; the episode writer notes absence on the row it can no
- # longer point at, and keeps the episode.
- recorder.note_present(discovered)
- for index, path in enumerate(discovered):
- if time.monotonic() > deadline:
- # A first index on a machine with a long agent history reads
- # the whole corpus from byte 0, and that corpus is bounded by
- # how much the user has worked, not by the size of the repo:
- # 857 MB across 426 sessions here. Stopping is safe and
- # self-healing rather than lossy, because the cursor is per
- # file and saved below, so the next run resumes exactly where
- # this one stopped. Steady state never reaches the budget.
- deferred = len(discovered) - index
- break
+ yields: dict[str, dict[str, int]] = {}
+ # Split the sweep rather than sharing it. Under one deadline the
+ # harness iterated first spends the whole budget on a cold corpus and
+ # the next is deferred on its first file every run, which is
+ # indistinguishable from a harness with nothing to read.
+ budget = SWEEP_BUDGET_S / len(names)
+ for name in names:
try:
- events = iter_new_events(adapter, path, store.cursors, prefilter=prefilter)
- 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,
- quotes=candidate.quotes,
- files=candidate.files,
- session_id=candidate.session_id,
- now=now,
- ):
- staged += 1
- except OSError:
+ yields[name] = _sweep_harness(
+ name,
+ repo_root=repo_root,
+ repo_prefix=repo_prefix,
+ projects_root=projects_root,
+ store=store,
+ recorder=recorder,
+ collector=collector,
+ budget=budget,
+ now=now,
+ )
+ except Exception as exc:
+ # One harness must not cost another's committed progress: the
+ # cursor save below is shared, so an escape here would discard
+ # every harness's advances and re-read them next run.
+ logger.warning("session_mining.harness_failed", harness=name, error=str(exc))
continue
+ staged += yields[name]["staged"]
+ deferred += yields[name]["deferred"]
store.prune(now=now)
store.cursors.save() # commits the staged raws atomically with the cursors
@@ -946,6 +1048,11 @@ async def mine_session_decisions(
structured=structured_count,
pending_backlog=max(0, len(pending) - processed),
discovery_spans=collector.queued if collector else 0,
+ # Per harness, so a reader that stops reading is visible. A
+ # harness that did not run, or failed, has no key at all; one that
+ # ran reports what it discovered, read and found separately, so an
+ # empty corpus and an unread one do not share a number.
+ yields=yields,
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 f147aaabf..5b249c644 100644
--- a/packages/core/src/repowise/core/sessions/staging.py
+++ b/packages/core/src/repowise/core/sessions/staging.py
@@ -74,7 +74,8 @@ CREATE TABLE IF NOT EXISTS raw_candidates (
files TEXT NOT NULL,
session_id TEXT,
created_at REAL NOT NULL,
- structured_key TEXT
+ structured_key TEXT,
+ harness TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS decisions (
key TEXT PRIMARY KEY,
@@ -159,12 +160,28 @@ INJECTIONS_LEDGER_COLUMNS = (
)
-def _migrate_injections_columns(conn: sqlite3.Connection) -> None:
- """Best-effort ALTER for sidecars created before the ledger columns."""
- existing = {row[1] for row in conn.execute("PRAGMA table_info(injections)")}
- for name, decl in INJECTIONS_LEDGER_COLUMNS:
+#: Columns added to ``raw_candidates`` once the session lane could read more
+#: than one harness. Same shape as the injections migration beside it.
+RAW_CANDIDATE_COLUMNS = (
+ # Which harness's transcript this observation came off. Empty on rows
+ # written before the column existed, and on any adapter that cannot name
+ # itself: an unattributable count is better left unclaimed than guessed.
+ ("harness", "TEXT NOT NULL DEFAULT ''"),
+)
+
+
+def _add_missing_columns(
+ conn: sqlite3.Connection, table: str, columns: tuple[tuple[str, str], ...]
+) -> None:
+ """ALTER *table* up to *columns*, skipping the ones it already has.
+
+ A sidecar can be created by either opener, so both apply the identical
+ migration and each must tolerate the other having gone first.
+ """
+ existing = {row[1] for row in conn.execute(f"PRAGMA table_info({table})")}
+ for name, decl in columns:
if name not in existing:
- conn.execute(f"ALTER TABLE injections ADD COLUMN {name} {decl}")
+ conn.execute(f"ALTER TABLE {table} ADD COLUMN {name} {decl}")
_NON_ALNUM_RE = re.compile(r"[^a-z0-9\s]")
@@ -238,7 +255,8 @@ class SessionStagingStore:
self._conn = sqlite3.connect(db_path)
apply_sqlite_pragmas(self._conn, _BUSY_TIMEOUT_MS)
self._conn.executescript(_SCHEMA)
- _migrate_injections_columns(self._conn)
+ _add_missing_columns(self._conn, "injections", INJECTIONS_LEDGER_COLUMNS)
+ _add_missing_columns(self._conn, "raw_candidates", RAW_CANDIDATE_COLUMNS)
self._conn.commit()
self.cursors = _DbCursors(self._conn)
@@ -256,12 +274,19 @@ class SessionStagingStore:
quotes: list[str],
files: list[str],
session_id: str | None,
+ harness: str = "",
now: float | None = None,
) -> bool:
- """Stage one gate hit; idempotent per content hash. True when new."""
+ """Stage one gate hit; idempotent per content hash. True when new.
+
+ The hash is content-only, so the same sentence said under two
+ harnesses stages once and keeps the first one's attribution. That is
+ the existing ceiling on ``session_id``, and *harness* inherits it.
+ """
cur = self._conn.execute(
"INSERT OR IGNORE INTO raw_candidates "
- "(hash, kind, quotes, files, session_id, created_at) VALUES (?, ?, ?, ?, ?, ?)",
+ "(hash, kind, quotes, files, session_id, created_at, harness) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?)",
(
hash_,
kind,
@@ -269,6 +294,7 @@ class SessionStagingStore:
json.dumps(files),
session_id,
now if now is not None else time.time(),
+ harness,
),
)
return cur.rowcount > 0
diff --git a/packages/server/src/repowise/server/routers/decisions.py b/packages/server/src/repowise/server/routers/decisions.py
index 4022dcdc1..09713cbe7 100644
--- a/packages/server/src/repowise/server/routers/decisions.py
+++ b/packages/server/src/repowise/server/routers/decisions.py
@@ -407,9 +407,14 @@ async def update_decision_settings(
if body.preset is not None:
try:
- # 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)
+ # A preset names source membership, not a budget and not which
+ # harnesses are read; what the caller did not send is theirs and
+ # survives.
+ policy = replace(
+ preset_policy(body.preset),
+ discovery=policy.discovery,
+ harnesses=policy.harnesses,
+ )
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
if body.enabled is not None:
diff --git a/tests/unit/sessions/data/codex_imported_session.jsonl b/tests/unit/sessions/data/codex_imported_session.jsonl
new file mode 100644
index 000000000..119350301
--- /dev/null
+++ b/tests/unit/sessions/data/codex_imported_session.jsonl
@@ -0,0 +1,5 @@
+{"timestamp":"2026-08-28T04:22:41.201Z","type":"session_meta","payload":{"session_id":"01a0469b-0a8d-7491-bca5-19fa04e7c94e","id":"01a0469b-0a8d-7491-bca5-19fa04e7c94e","timestamp":"2026-08-28T04:22:41.100Z","cwd":"C:\\Users\\dev\\Projects\\demo","originator":"Codex Desktop","cli_version":"0.144.5","source":"vscode","model_provider":"openai","git":{"branch":"main"}}}
+{"timestamp":"2026-08-28T04:22:41.289Z","ordinal":2,"type":"event_msg","payload":{"type":"item_completed","thread_id":"01a0469b-0a8d-7491-bca5-19fa04e7c94e","turn_id":"external-import-turn-1","item":{"type":"UserMessage","id":"item-1","content":[{"type":"text","text":"We switched to Postgres because SQLite locked under concurrent writes."}]},"completed_at_ms":1787890961289}}
+{"timestamp":"2026-08-28T04:22:42.010Z","type":"response_item","payload":{"type":"message","id":"msg_imported_01","role":"assistant","content":[{"type":"output_text","text":"We chose Postgres because SQLite locked under concurrent writes, so the connection pool is the durable fix."}]}}
+{"timestamp":"2026-08-28T04:22:43.115Z","type":"response_item","payload":{"type":"custom_tool_call","call_id":"ctc_imported_01","id":"ctc_imported_01","name":"exec","status":"completed","input":"const r = await tools.shell_command({\"command\":\"Get-Content -LiteralPath 'db/pool.py'\",\"workdir\":\"C:\\\\Users\\\\dev\\\\Projects\\\\demo\",\"timeout_ms\":10000}); text(typeof r === 'string' ? r : JSON.stringify(r));"}}
+{"timestamp":"2026-08-28T04:22:44.220Z","type":"event_msg","payload":{"type":"task_complete","turn_id":"external-import-turn-2"}}
diff --git a/tests/unit/sessions/test_codex_adapter.py b/tests/unit/sessions/test_codex_adapter.py
index b5d0280b2..d22294613 100644
--- a/tests/unit/sessions/test_codex_adapter.py
+++ b/tests/unit/sessions/test_codex_adapter.py
@@ -6,6 +6,11 @@ from pathlib import Path
import pytest
from repowise.core.sessions import CodexAdapter, Event
+from repowise.core.sessions.adapters.base import (
+ INTENT_SHELL_CALLS,
+ INTENT_TOOL_CALLS,
+ INTENT_TURNS,
+)
from repowise.core.sessions.adapters.codex import _normalize_tool_name
from repowise.core.sessions.miners.decisions import mine_events
@@ -256,3 +261,59 @@ def test_a_string_search_output_survives_rewriting(adapter: CodexAdapter) -> Non
assert event is not None
assert event.tool_results[0].content == "Output:\nsrc/app.py\n"
+
+
+#: A session bulk-imported from another harness into the Codex store.
+IMPORTED_FIXTURE = Path(__file__).parent / "data" / "codex_imported_session.jsonl"
+
+
[email protected]("intent", [INTENT_TURNS, INTENT_SHELL_CALLS, INTENT_TOOL_CALLS])
+def test_cwd_threads_under_the_gate_production_runs(adapter: CodexAdapter, intent: str) -> None:
+ """The scoping guard has to hold on the gated path, not just the bare one.
+
+ Every consumer passes a prefilter. A gate that drops ``session_meta``
+ leaves ``cwd`` unset on every event, and the miners' scoping test reads a
+ blank cwd as "no opinion" rather than as a miss, so one machine's every
+ session lands in whichever repo is being indexed.
+ """
+ events = list(adapter.iter_events(FIXTURE, prefilter=adapter.prefilter(intent)))
+
+ assert events
+ assert all(e.cwd for e in events)
+
+
+def test_another_repos_session_is_scoped_out_under_the_gate(adapter: CodexAdapter) -> None:
+ prefilter = adapter.prefilter(INTENT_TURNS)
+ events = list(adapter.iter_events(FIXTURE, prefilter=prefilter))
+
+ assert mine_events(events, r"d:\some\other\repo") == []
+
+
+def test_bulk_imported_session_yields_nothing_minable(adapter: CodexAdapter) -> None:
+ """An import is the other harness's session, and its adapter already read it.
+
+ Mining it here would count one session twice: once under the harness that
+ recorded it and once under the store it was copied into.
+ """
+ prefilter = adapter.prefilter(INTENT_TURNS)
+ events = list(adapter.iter_events(IMPORTED_FIXTURE, prefilter=prefilter))
+
+ assert all(not e.text for e in events)
+ assert mine_events(events, r"c:\users\dev\projects\demo") == []
+
+
+def test_the_import_gate_does_not_catch_a_native_session(adapter: CodexAdapter) -> None:
+ """The fixture's own originator is ``Codex Desktop``, so that is not the signal."""
+ prefilter = adapter.prefilter(INTENT_TURNS)
+ events = list(adapter.iter_events(FIXTURE, prefilter=prefilter))
+
+ assert mine_events(events, REPO_PREFIX)
+
+
+def test_import_state_does_not_leak_between_files(adapter: CodexAdapter) -> None:
+ """One adapter drives many transcripts; the latch is per file."""
+ prefilter = adapter.prefilter(INTENT_TURNS)
+ list(adapter.iter_events(IMPORTED_FIXTURE, prefilter=prefilter))
+ events = list(adapter.iter_events(FIXTURE, prefilter=prefilter))
+
+ assert mine_events(events, REPO_PREFIX)
diff --git a/tests/unit/sessions/test_harness_selection.py b/tests/unit/sessions/test_harness_selection.py
new file mode 100644
index 000000000..a0e67ea19
--- /dev/null
+++ b/tests/unit/sessions/test_harness_selection.py
@@ -0,0 +1,370 @@
+"""Which harnesses the session lane reads, and what changes when it reads two.
+
+Only Claude Code is read by default. A harness added to the registry is a
+reader this repository has not asked for, and switching one on makes a
+machine's whole history for that agent eligible on the next update.
+"""
+
+from __future__ import annotations
+
+import json
+
+import yaml
+
+from repowise.core.analysis.decisions.policy import DEFAULT_HARNESSES, resolve_policy
+from repowise.core.sessions.miners.decisions import harnesses_for
+
+
+def _repo(tmp_path, block=None):
+ repo = tmp_path / "repo"
+ (repo / ".repowise").mkdir(parents=True)
+ if block is not None:
+ (repo / ".repowise" / "config.yaml").write_text(
+ yaml.safe_dump({"decisions": block}), encoding="utf-8"
+ )
+ return repo
+
+
+def test_only_claude_code_is_read_by_default(tmp_path):
+ assert harnesses_for(_repo(tmp_path)) == ("claude_code",)
+ assert DEFAULT_HARNESSES == ("claude_code",)
+
+
+def test_a_named_harness_is_read(tmp_path):
+ repo = _repo(tmp_path, {"harnesses": ["claude_code", "codex"]})
+
+ assert harnesses_for(repo) == ("claude_code", "codex")
+
+
+def test_an_unknown_harness_is_dropped_with_a_warning():
+ resolution = resolve_policy({"decisions": {"harnesses": ["claude_code", "emacs"]}})
+
+ assert resolution.policy.harnesses == ("claude_code",)
+ assert any("emacs" in w for w in resolution.warnings)
+
+
+def test_naming_no_known_harness_falls_back_rather_than_reading_nothing():
+ """An empty reader list is indistinguishable from a repo with no sessions."""
+ resolution = resolve_policy({"decisions": {"harnesses": ["emacs"]}})
+
+ assert resolution.policy.harnesses == DEFAULT_HARNESSES
+ assert any("no known harness" in w for w in resolution.warnings)
+
+
+def test_harnesses_is_a_known_key():
+ resolution = resolve_policy({"decisions": {"harnesses": ["codex"]}})
+
+ assert not any("Unknown key" in w for w in resolution.warnings)
+
+
+def test_a_non_list_is_refused_rather_than_coerced():
+ resolution = resolve_policy({"decisions": {"harnesses": "codex"}})
+
+ assert resolution.policy.harnesses == DEFAULT_HARNESSES
+ assert any("not a list" in w for w in resolution.warnings)
+
+
+def test_duplicates_collapse_so_a_transcript_is_not_read_twice(tmp_path):
+ repo = _repo(tmp_path, {"harnesses": ["codex", "codex", "claude_code"]})
+
+ assert harnesses_for(repo) == ("codex", "claude_code")
+
+
+def test_the_policy_payload_names_the_harnesses():
+ """``decision config show`` and the API read this dict."""
+ policy = resolve_policy({"decisions": {"harnesses": ["codex"]}}).policy
+
+ assert policy.to_dict(provider_available=False)["harnesses"] == ["codex"]
+
+
+def test_a_staged_observation_records_which_harness_it_came_off(tmp_path):
+ from repowise.core.sessions.staging import SessionStagingStore
+
+ store = SessionStagingStore(tmp_path / "sessions.db")
+ store.add_raw(
+ hash_="h1", kind="explicit_choice", quotes=["q"], files=[], session_id="s1",
+ harness="codex", now=1.0,
+ )
+ row = store._conn.execute("SELECT harness FROM raw_candidates WHERE hash = 'h1'").fetchone()
+
+ assert row[0] == "codex"
+
+
+def test_a_store_written_before_the_column_still_opens(tmp_path):
+ """The ALTER runs on open; a pre-existing sidecar must not be a crash."""
+ import sqlite3
+
+ from repowise.core.sessions.staging import SessionStagingStore
+
+ db = tmp_path / "sessions.db"
+ conn = sqlite3.connect(db)
+ conn.executescript(
+ "CREATE TABLE raw_candidates (hash TEXT PRIMARY KEY, kind TEXT NOT NULL, "
+ "quotes TEXT NOT NULL, files TEXT NOT NULL, session_id TEXT, "
+ "created_at REAL NOT NULL, structured_key TEXT);"
+ )
+ conn.execute(
+ "INSERT INTO raw_candidates VALUES ('old', 'explicit_choice', '[]', '[]', 's0', 1.0, NULL)"
+ )
+ conn.commit()
+ conn.close()
+
+ store = SessionStagingStore(db)
+ rows = dict(store._conn.execute("SELECT hash, harness FROM raw_candidates").fetchall())
+
+ # Empty rather than backfilled: those rows' attribution cannot be recovered.
+ assert rows == {"old": ""}
+
+
+# --- the drive loop -------------------------------------------------------
+
+
+def _claude_transcript(repo_root, projects_root, name, session_id, text):
+ from repowise.core.sessions.adapters.claude_code import transcript_dir_for
+
+ directory = transcript_dir_for(repo_root, projects_root)
+ directory.mkdir(parents=True, exist_ok=True)
+ (directory / name).write_text(
+ json.dumps(
+ {
+ "type": "user",
+ "cwd": str(repo_root),
+ "timestamp": "2026-07-11T10:00:00.000Z",
+ "sessionId": session_id,
+ "message": {"role": "user", "content": [{"type": "text", "text": text}]},
+ }
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+
+
+async def test_the_default_config_never_reads_the_codex_root(tmp_path, monkeypatch):
+ """The safety property of shipping this off: nothing new is read.
+
+ Codex discovery is not repo-scoped, so a harness switched on by accident
+ makes every session on the machine eligible. Default means untouched.
+ """
+ from repowise.core.sessions.miners.decisions import mine_session_decisions
+ from repowise.core.sessions.staging import SessionStagingStore, default_store_path
+
+ repo = _repo(tmp_path)
+ projects_root = tmp_path / "projects"
+ _claude_transcript(repo, projects_root, "a.jsonl", "s1", "No, use the venv python because bare python is stale")
+
+ seen: list[str] = []
+ from repowise.core.sessions.adapters import codex as codex_mod
+
+ original = codex_mod.CodexAdapter.discover
+
+ def spy(self, repo_root, *, projects_root=None):
+ seen.append("codex")
+ return original(self, repo_root, projects_root=projects_root)
+
+ monkeypatch.setattr(codex_mod.CodexAdapter, "discover", spy)
+
+ await mine_session_decisions(repo, provider=None, projects_root=projects_root, now=100.0)
+
+ assert seen == []
+ # Anchored to a run that did something, or the negative proves nothing.
+ store = SessionStagingStore(default_store_path(repo))
+ assert store._conn.execute("SELECT COUNT(*) FROM raw_candidates").fetchone()[0] == 1
+
+
+def _codex_rollout(projects_root, repo, name, *, turn_id=None, subdir="codex"):
+ """A native Codex rollout, inside the sandbox the caller was given."""
+ root = projects_root / subdir / "2026" / "07" / "11" if subdir else projects_root / "2026" / "07" / "11"
+ root.mkdir(parents=True, exist_ok=True)
+ meta = {
+ "timestamp": "2026-07-11T10:00:00.000Z",
+ "type": "session_meta",
+ "payload": {"session_id": "cx-1", "cwd": str(repo), "originator": "codex-tui"},
+ }
+ payload = {
+ "type": "user_message",
+ "message": "No, use the venv python because bare python is a stale install",
+ }
+ if turn_id is not None:
+ payload["turn_id"] = turn_id
+ turn = {"timestamp": "2026-07-11T10:00:01.000Z", "type": "event_msg", "payload": payload}
+ # Compact, like a real rollout: the raw-string gates match `"type":"x"`
+ # with no space after the colon, which is what Codex writes.
+ compact = (",", ":")
+ (root / name).write_text(
+ json.dumps(meta, separators=compact) + "\n" + json.dumps(turn, separators=compact) + "\n",
+ encoding="utf-8",
+ )
+
+
+def _staged_by_harness(repo):
+ from repowise.core.sessions.staging import SessionStagingStore, default_store_path
+
+ store = SessionStagingStore(default_store_path(repo))
+ return dict(
+ store._conn.execute(
+ "SELECT harness, COUNT(*) FROM raw_candidates GROUP BY harness"
+ ).fetchall()
+ )
+
+
+async def test_both_harnesses_are_read_when_both_are_named(tmp_path):
+ from repowise.core.sessions.miners.decisions import mine_session_decisions
+
+ repo = _repo(tmp_path, {"harnesses": ["claude_code", "codex"]})
+ projects_root = tmp_path / "projects"
+ _claude_transcript(repo, projects_root, "a.jsonl", "s1", "No, use the venv python because bare python is stale")
+ _codex_rollout(projects_root, repo, "rollout-x.jsonl")
+
+ await mine_session_decisions(repo, provider=None, projects_root=projects_root, now=100.0)
+ staged = _staged_by_harness(repo)
+
+ assert staged.get("claude_code"), staged
+ assert staged.get("codex"), staged
+
+
+async def test_a_sandboxed_run_never_escapes_to_the_real_home(tmp_path, monkeypatch):
+ """``projects_root`` is a sandbox, and a second harness must stay inside it.
+
+ A harness that falls back to the real home reads the machine's whole
+ history for that agent into a temporary store, which is slow, undeterministic
+ and a privacy surprise on a developer box.
+ """
+ from repowise.core.sessions.miners.decisions import mine_session_decisions
+
+ repo = _repo(tmp_path, {"harnesses": ["claude_code", "codex"]})
+ projects_root = tmp_path / "projects"
+ _claude_transcript(repo, projects_root, "a.jsonl", "s1", "No, use the venv python because bare python is stale")
+
+ # A rollout at the real home location, which the run must not reach.
+ home = tmp_path / "home"
+ _codex_rollout(home / ".codex" / "sessions", repo, "escaped.jsonl", subdir=None)
+ monkeypatch.setattr("pathlib.Path.home", lambda: home)
+
+ await mine_session_decisions(repo, provider=None, projects_root=projects_root, now=100.0)
+ staged = _staged_by_harness(repo)
+
+ assert staged.get("claude_code"), staged
+ assert "codex" not in staged, staged
+
+
+async def test_an_imported_session_is_not_staged_by_the_drive_loop(tmp_path):
+ """End to end: the latch holds through discovery, cursoring and mining."""
+ from repowise.core.sessions.miners.decisions import mine_session_decisions
+
+ repo = _repo(tmp_path, {"harnesses": ["codex"]})
+ projects_root = tmp_path / "projects"
+ _codex_rollout(projects_root, repo, "imported.jsonl", turn_id="external-import-turn-1")
+
+ await mine_session_decisions(repo, provider=None, projects_root=projects_root, now=100.0)
+
+ assert _staged_by_harness(repo) == {}
+
+
+async def test_a_resumed_read_still_scopes_to_this_repo(tmp_path):
+ """The cwd fix has to survive the cursor, which is the common path.
+
+ Codex states cwd once, at the top of the file, and a resumed read starts
+ past it. If the adapter does not recover it, every appended line from
+ every session on the machine reads as belonging to whichever repo is
+ being indexed.
+ """
+ from repowise.core.sessions.miners.decisions import mine_session_decisions
+
+ repo = _repo(tmp_path, {"harnesses": ["codex"]})
+ other = tmp_path / "elsewhere"
+ other.mkdir()
+ projects_root = tmp_path / "projects"
+ # The rollout belongs to another repo entirely.
+ _codex_rollout(projects_root, other, "rollout-y.jsonl")
+
+ await mine_session_decisions(repo, provider=None, projects_root=projects_root, now=100.0)
+
+ rollout = projects_root / "codex" / "2026" / "07" / "11" / "rollout-y.jsonl"
+ appended = {
+ "timestamp": "2026-07-11T10:00:02.000Z",
+ "type": "event_msg",
+ "payload": {
+ "type": "user_message",
+ "message": "No, always use ruff check because the format sweep buries the diff",
+ },
+ }
+ with rollout.open("a", encoding="utf-8") as fh:
+ fh.write(json.dumps(appended, separators=(",", ":")) + "\n")
+
+ await mine_session_decisions(repo, provider=None, projects_root=projects_root, now=200.0)
+
+ assert _staged_by_harness(repo) == {}
+
+
+def test_a_non_default_harness_list_round_trips_through_a_policy_write(tmp_path):
+ """Every config mutation validates by round-tripping the written block.
+
+ A field on the policy that the block does not carry fails that check on
+ every write, so the setting bricks the commands that configure it.
+ """
+ from repowise.core.analysis.decisions.policy_store import load_policy, write_policy
+
+ repo = _repo(tmp_path, {"harnesses": ["claude_code", "codex"]})
+ policy = load_policy(repo).policy
+
+ write_policy(repo, policy.with_llm(False))
+
+ assert load_policy(repo).policy.harnesses == ("claude_code", "codex")
+
+
+def test_applying_a_preset_keeps_the_harness_list(tmp_path):
+ """A preset names source membership, not which harnesses are read."""
+ from dataclasses import replace
+
+ from repowise.core.analysis.decisions.policy import preset_policy
+ from repowise.core.analysis.decisions.policy_store import load_policy, write_policy
+
+ repo = _repo(tmp_path, {"harnesses": ["claude_code", "codex"]})
+ current = load_policy(repo).policy
+
+ write_policy(repo, replace(preset_policy("local_only"), harnesses=current.harnesses))
+
+ assert load_policy(repo).policy.harnesses == ("claude_code", "codex")
+
+
+def test_a_non_default_harness_list_is_not_a_named_preset():
+ """Otherwise the one setting that widens what is read reads as `default`."""
+ policy = resolve_policy({"decisions": {"harnesses": ["claude_code", "codex"]}}).policy
+
+ assert policy.preset_name() == "custom"
+
+
+async def test_the_callers_policy_wins_over_a_second_config_read(tmp_path):
+ """One resolved answer, not two that can disagree.
+
+ Both pipelines resolve the policy before calling the miner. Re-reading
+ config here would be a second answer to a question already asked, and the
+ two can drift.
+ """
+ from repowise.core.sessions.miners.decisions import mine_session_decisions
+
+ # Config names codex; the caller passes claude_code only. The caller wins.
+ repo = _repo(tmp_path, {"harnesses": ["claude_code", "codex"]})
+ projects_root = tmp_path / "projects"
+ _claude_transcript(repo, projects_root, "a.jsonl", "s1", "No, use the venv python because bare python is stale")
+ _codex_rollout(projects_root, repo, "rollout-x.jsonl")
+
+ await mine_session_decisions(
+ repo,
+ provider=None,
+ projects_root=projects_root,
+ harnesses=("claude_code",),
+ now=100.0,
+ )
+ staged = _staged_by_harness(repo)
+
+ assert staged.get("claude_code"), staged
+ assert "codex" not in staged, staged
+
+
+def test_an_unregistered_harness_from_a_caller_is_dropped_not_raised():
+ """A config written against a newer repowise must not stop this one."""
+ from repowise.core.sessions.miners.decisions import registered_harnesses
+
+ assert registered_harnesses(["codex", "emacs"]) == ("codex",)
+ assert registered_harnesses(["emacs"]) == DEFAULT_HARNESSES