Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
refactor(agents): define each agent once, and stop savings enumerating them (#2394)
Raghav Chamadiyaca227c53fda4
diff --git a/docs/architecture/savings-accounting.md b/docs/architecture/savings-accounting.mdindex add0b745d..2391ab89d 100644--- a/docs/architecture/savings-accounting.md+++ b/docs/architecture/savings-accounting.md@@ -1,7 +1,7 @@# Savings accounting contract-Status: Phase 0 decision record for the costs-and-savings overhaul. This document-locks the v1 accounting truth before schema, capture, reporting, or UI work begins.+How Repowise decides what it saved an agent, and what it refuses to claim.+Binding on every capture surface, the report, and anything that renders a total.## Reporting vocabulary@@ -51,11 +51,9 @@ meaning is versioned with the estimator.- `omission_refs`: zero or more content-recovery references. An empty list meansno recovery artifact was linked, not zero savings.-`null` means unavailable or not observed. Applicability comes from surface,-evidence kind, and result state; consumers must not infer zero from `null`.-Enum attribution uses the literal `unknown` instead of null. Optional correlation,-model, and pricing fields use null when unavailable. Canonical serialized fields-are present even when null, so field omission never acquires a second meaning.+`null` means unavailable or not observed, and a consumer must never read it as+zero. Attribution uses the literal `unknown` rather than null. Canonical fields+are serialized even when null, so an absent key never acquires a second meaning.## Decision table@@ -99,14 +97,21 @@ counterfactual estimation, dead-end handling, and the final writer.FastMCP exposes a request ID across stdio, SSE, and streamable HTTP. On normalstateful sessions it also exposes initialize-time `clientInfo`, which isclient-declared rather than authenticated. Mapping version `mcp_client_info_v1`-lowercases the name and removes non-alphanumerics, then accepts only:-`claude`/`claudecode` -> `claude_code`, `codex` -> `codex`, `opencode` ->-`opencode`, `hermes` -> `hermes`, `cursor` -> `cursor`, and `vscode` ->-`vscode`. Every other value, including a generic MCP client, maps to `unknown`.-Never infer agent or-model from headers, capabilities, environment variables, executable parents, or-transport. Session/request/tool-call IDs and model remain null until an adapter-explicitly supplies trustworthy evidence.+lowercases the name and removes non-alphanumerics, then looks the result up in+the agent registry (`repowise.core.agents.identity`), where every agent answers+to its own slug and its own display name, plus any extra name its host is known+to announce. Every other value, including a generic MCP client, maps to+`unknown`.++Resolving an announced name is the only step that produces `unknown`. Nowhere+else does savings enumerate agents: a stored id is checked syntactically against+`^[a-z0-9_]{1,32}$` by the writer, the reader, and the sidecar's own `CHECK`+constraints alike. So a new agent is a valid attribution the day its descriptor+lands, and an event from an agent since retired still reads back as that agent.++Never infer agent or model from headers, capabilities, environment variables,+executable parents, or transport. Session, request and tool-call IDs and model+stay null until an adapter supplies trustworthy evidence.The v1 metadata allow-list is `client_info_normalized` and`identity_mapping_version`. Values are bounded strings; no raw prompts,@@ -121,9 +126,9 @@ measured after the VS Code host's final cap.## Legacy omission fields-The legacy `omissions` table is a recovery store, not an accounting event log.-Its content hash `ref` identifies content, so byte-identical omissions from two-calls collapse to one row. Its row count cannot represent logical interactions.+The legacy `omissions` table is a recovery store, not an event log. Its `ref` is+a content hash, so byte-identical omissions from two calls collapse into one row+and the row count cannot stand for a number of interactions.- MCP budgeting persists the dropped recovery document or inline chunk.`original_tokens` is the estimated size of that persisted dropped artifact,@@ -133,82 +138,55 @@ calls collapse to one row. Its row count cannot represent logical interactions.artifact's estimated size and `kept_tokens` is the retained filtered bodybefore the recoverability marker. Actual delivered input includes the marker.-Therefore the columns have producer-specific meanings. Preserve them and-`evidence_references` for expand/recovery, but do not use either column or the-omission row count in canonical savings arithmetic. New events link omission-references without duplicating their content.+So both columns mean different things depending on who wrote them. Preserve them+and `evidence_references` for recovery, but keep them and the row count out of+savings arithmetic. Events link omission references without copying content.## Pricing-Price each event only from the model, source/version, currency, and input/output-rates captured with that event. Savings reports expose priced and unpriced tokens-separately. They never reprice history from the newest session. Input and output-rates apply only to their matching dimensions. The old fixed 60-output-token-credit is removed; nullable output fields remain so explicit evidence can be-supported without invention.+Price each event only from the model, source, version, currency and rates+captured with that event, and apply each rate only to its matching dimension.+Reports expose priced and unpriced tokens separately and never reprice history+from the newest session. There is no fixed output-token credit; output fields+stay nullable so explicit evidence can be recorded without inventing any.-Repowise's own `llm_costs` provider-token spend is a separate metered-spend-section. It is not subtracted from or merged into achieved agent-token savings.+Repowise's own `llm_costs` spend is a separate metered-spend section, never+merged into or subtracted from achieved agent savings.## Hosted and shared-presentation boundary-The verified hosted backend defines `total_cents` as the lifetime absolute value-of negative `credit_transactions.amount_cents`, scoped to authenticated user and-repository. `by_type` partitions those debits into indexing, chat, reindex, and-other, so its money buckets sum to `total_cents`; positive/zero rows do not add-spend. The current `transaction_count` is the number of fetched ledger rows and-can include non-debits. Anonymous public-snapshot callers receive zero billing-spend. Hosted engine `llm_costs` telemetry is a separate field.--Accordingly, hosted credit spend remains a named host-only billing section. It is-not equivalent to OSS `wiki.db.llm_costs` and is not mapped into canonical-repository model spend or savings.--`frontend/docs/DESIGN_LANGUAGE.md` remains binding for hosted and OSS. The shared-`@repowise-dev/ui` savings surface receives a pure, already-derived presentation-model plus link/action capabilities. It performs no fetching, authentication,-routing, pricing, correlation, or accounting and contains no `isHosted` branch.-Hosts adapt their real wire contracts and retain hosted-only billing as a sibling-capability. Visual hierarchy, evidence labels, and interaction semantics stay-shared.+Hosted `total_cents` is the lifetime absolute value of negative+`credit_transactions.amount_cents` for one user and repository, partitioned by+`by_type` into indexing, chat, reindex and other. `transaction_count` counts+fetched ledger rows and can include non-debits, so it is not a count of charges.+Anonymous snapshot callers see zero billing spend.++Hosted credit spend therefore stays a named host-only billing section. It is not+equivalent to OSS `wiki.db.llm_costs` and is never folded into repository model+spend or savings.++The shared savings surface receives an already-derived presentation model: it+performs no pricing, correlation, or accounting of its own. Arithmetic lives+here, not in a renderer.## Savings reset disclosure-The clean telemetry reset is a user-visible methodology change, not silent data-loss. On the first costs-page visit after the reset, show a calm inline-informational notice beside the savings lede:--> **Savings accounting has been upgraded**-> Savings now use interaction-level evidence for more accurate, auditable totals.-> Previous savings estimates were not compatible with the new methodology, so-> savings history restarted on **[reset date]**. Omission history and other-> repository data were not deleted.--The notice has a normal `See what changed` link and a dismiss control. It is not a-modal, warning, error, toast, or global promotional banner: it must not steal-focus or interrupt work. After dismissal, the reset date and methodology link-remain quietly visible near the total.--Presentation is a reusable controlled `DismissibleNotice` primitive in-`@repowise-dev/ui`. It accepts content, neutral/info tone, optional action/link,-and `onDismiss`; it owns no storage, fetching, routes, or host detection. Each host-decides whether it is visible and persists a versioned dismissal key scoped to-repository plus accounting-method version. This keeps localStorage, user-preferences, and future server persistence interchangeable without turning a rare-announcement into a general modal framework. Existing feature-specific banners-may migrate only when doing so is independently useful, not as required scope for-this overhaul.--## Frozen diagnostic baseline--On 2026-09-13 a SQLite online backup of the worktree-local omission database at-commit `a3e49b7692be` was frozen, queried, and deleted. Its SHA-256 was-`23E44B9E4C16A29087D5A9C2FB4F5EACF366C16E126281D44CA9B135941A5298`.-It contained 953 MCP ledger rows and 36 MCP omission artifacts. The legacy-tool-wide algorithm reported 7,495,645 MCP tokens; blindly adding both signal-sets produced 7,959,262. The clamped non-MCP ledger reduction was 1,276,569.--These values are diagnostic reproduction evidence only. No canonical historical-MCP total can be reconstructed because there is no interaction ID and identical-omitted content is hash-deduplicated. Product expectations come exclusively from-the deterministic fixture in `tests/fixtures/savings/mixed_agents_v1.json`.+Restarting savings history is a user-visible methodology change, not silent data+loss, so it is disclosed rather than absorbed. Incompatible estimates were+restarted on a stated date; omission history and other repository data were not+deleted, and saying so is part of the disclosure.++Disclosure is calm and inline beside the total: not a modal, warning, toast, or+promotional banner, and it never steals focus. It is dismissible once per+repository and accounting-method version, so a later methodology change can+announce itself again. After dismissal the reset date and a link to this document+stay quietly visible next to the number they qualify.++## Historical totals++No canonical pre-v1 savings total can be reconstructed. The legacy ledger has no+interaction ID and hash-deduplicates identical omitted content, so its rows+cannot be resolved back into logical interactions at any accuracy worth+publishing. Figures from the legacy algorithm are not a baseline to preserve or+to reproduce. Expected totals come from the deterministic fixture in+`tests/fixtures/savings/mixed_agents_v1.json`.diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.pyindex ea02ae5b9..923d0bb27 100644--- a/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py+++ b/packages/cli/src/repowise/cli/agent_targets/targets/claude_code.py@@ -29,6 +29,8 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+from repowise.core.agents import identity+from ..types import (Capability,DoctorReport,@@ -41,8 +43,9 @@ from ..types import (WriteResult,)-ID = "claude-code"-DISPLAY_NAME = "Claude Code"+IDENTITY = identity.CLAUDE_CODE+ID = IDENTITY.cli_target_id+DISPLAY_NAME = IDENTITY.display_nameDOCS_URL = "https://docs.claude.com/en/docs/claude-code"#: Name the plugin registers itself under in the host's plugin manifest.@@ -341,8 +344,8 @@ class ClaudeCodeTarget:id = IDdisplay_name = DISPLAY_NAMEdocs_url = DOCS_URL- hook_adapter = "claude-code"- session_adapter = "claude_code"+ hook_adapter = IDENTITY.hook_adapter+ session_adapter = IDENTITY.session_adaptermethods = METHODSproject_file_id = PROJECT_FILE_IDdiff --git a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py b/packages/cli/src/repowise/cli/agent_targets/targets/codex.pyindex 6f8e5a8ba..07c22c273 100644--- a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py@@ -37,6 +37,7 @@ import tomllibfrom pathlib import Pathfrom repowise.cli.errors import reasoned_error+from repowise.core.agents import identityfrom ..types import (Capability,@@ -50,8 +51,9 @@ from ..types import (WriteResult,)-ID = "codex"-DISPLAY_NAME = "Codex CLI"+IDENTITY = identity.CODEX+ID = IDENTITY.cli_target_id+DISPLAY_NAME = IDENTITY.display_nameDOCS_URL = "https://developers.openai.com/codex/cli"#: Config key for this agent's managed instruction file (``AGENTS.md``).@@ -978,8 +980,8 @@ class CodexTarget:id = IDdisplay_name = DISPLAY_NAMEdocs_url = DOCS_URL- hook_adapter = "codex"- session_adapter = "codex"+ hook_adapter = IDENTITY.hook_adapter+ session_adapter = IDENTITY.session_adaptermethods = METHODSproject_file_id = PROJECT_FILE_IDdiff --git a/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.pyindex 2bfa38d7a..678b48751 100644--- a/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py+++ b/packages/cli/src/repowise/cli/agent_targets/targets/cursor.py@@ -47,6 +47,8 @@ import contextlibimport jsonfrom pathlib import Path+from repowise.core.agents import identity+from ..types import (Capability,DoctorReport,@@ -59,8 +61,9 @@ from ..types import (WriteResult,)-ID = "cursor"-DISPLAY_NAME = "Cursor"+IDENTITY = identity.CURSOR+ID = IDENTITY.cli_target_id+DISPLAY_NAME = IDENTITY.display_nameDOCS_URL = "https://cursor.com/docs/context/mcp"#: Config key gating this agent's managed rules file.@@ -360,8 +363,8 @@ class CursorTarget:id = IDdisplay_name = DISPLAY_NAMEdocs_url = DOCS_URL- hook_adapter = None- session_adapter = None+ hook_adapter = IDENTITY.hook_adapter+ session_adapter = IDENTITY.session_adaptermethods = METHODSproject_file_id = PROJECT_FILE_IDdiff --git a/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py b/packages/cli/src/repowise/cli/agent_targets/targets/hermes.pyindex 5770456a7..7b534bceb 100644--- a/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py+++ b/packages/cli/src/repowise/cli/agent_targets/targets/hermes.py@@ -55,6 +55,8 @@ import osimport sysfrom pathlib import Path+from repowise.core.agents import identity+from ..formats.server_entry import RemoteServerEntryErrorfrom ..types import (Capability,@@ -68,8 +70,9 @@ from ..types import (WriteResult,)-ID = "hermes"-DISPLAY_NAME = "Hermes"+IDENTITY = identity.HERMES+ID = IDENTITY.cli_target_id+DISPLAY_NAME = IDENTITY.display_nameDOCS_URL = "https://hermes-agent.nousresearch.com/docs/user-guide/features/mcp"#: Config key gating this agent's managed instruction file. Deliberately the@@ -801,8 +804,8 @@ class HermesTarget:id = IDdisplay_name = DISPLAY_NAMEdocs_url = DOCS_URL- hook_adapter = None- session_adapter = None+ hook_adapter = IDENTITY.hook_adapter+ session_adapter = IDENTITY.session_adaptermethods = METHODSproject_file_id = PROJECT_FILE_IDdiff --git a/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py b/packages/cli/src/repowise/cli/agent_targets/targets/opencode.pyindex dee7b995c..5a2309c64 100644--- a/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py+++ b/packages/cli/src/repowise/cli/agent_targets/targets/opencode.py@@ -62,6 +62,8 @@ import jsonimport osfrom pathlib import Path+from repowise.core.agents import identity+from ..formats.server_entry import RemoteServerEntryErrorfrom ..types import (Capability,@@ -75,8 +77,9 @@ from ..types import (WriteResult,)-ID = "opencode"-DISPLAY_NAME = "OpenCode"+IDENTITY = identity.OPENCODE+ID = IDENTITY.cli_target_id+DISPLAY_NAME = IDENTITY.display_nameDOCS_URL = "https://opencode.ai/docs/mcp-servers/"#: Config key gating this agent's managed instruction file. Deliberately the@@ -586,8 +589,8 @@ class OpenCodeTarget:id = IDdisplay_name = DISPLAY_NAMEdocs_url = DOCS_URL- hook_adapter = None- session_adapter = None+ hook_adapter = IDENTITY.hook_adapter+ session_adapter = IDENTITY.session_adaptermethods = METHODSproject_file_id = PROJECT_FILE_IDdiff --git a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.pyindex fde8061cb..81a4228ec 100644--- a/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py+++ b/packages/cli/src/repowise/cli/agent_targets/targets/vscode.py@@ -23,6 +23,8 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+from repowise.core.agents import identity+from ..formats.server_entry import RemoteServerEntryErrorfrom ..types import (Capability,@@ -36,8 +38,9 @@ from ..types import (WriteResult,)-ID = "vscode"-DISPLAY_NAME = "VS Code"+IDENTITY = identity.VSCODE+ID = IDENTITY.cli_target_id+DISPLAY_NAME = IDENTITY.display_nameDOCS_URL = "https://code.visualstudio.com/docs/copilot/chat/mcp-servers"EXTENSION_ID = "repowise-dev.repowise"@@ -266,8 +269,8 @@ class VSCodeTarget:id = IDdisplay_name = DISPLAY_NAMEdocs_url = DOCS_URL- hook_adapter = None- session_adapter = None+ hook_adapter = IDENTITY.hook_adapter+ session_adapter = IDENTITY.session_adaptermethods = METHODSproject_file_id = PROJECT_FILE_IDdiff --git a/packages/core/src/repowise/core/agents/__init__.py b/packages/core/src/repowise/core/agents/__init__.pynew file mode 100644index 000000000..84b525c16--- /dev/null+++ b/packages/core/src/repowise/core/agents/__init__.py@@ -0,0 +1,44 @@+"""The vocabulary for the agents repowise integrates with.++Core declares who an agent *is*; the other packages bind behaviour to it.+:mod:`repowise.cli.agent_targets` wires an agent up, ``cli.agent_adapters``+and :mod:`repowise.core.sessions.adapters` implement its hook and transcript+surfaces, and :mod:`repowise.core.savings` attributes accounting to it. Core is+the leaf package, so every one of those can read this and none of them could+have read a copy owned by one of the others.++Deliberately not the same thing as :mod:`repowise.core.registry`, which is a+set of plugin extension seams. This is a vocabulary.+"""++from __future__ import annotations++from repowise.core.agents.identity import (+ CLIENT_IDENTITY_MAPPING_VERSION,+ UNKNOWN_AGENT,+ AgentIdentity,+ all_identities,+ display_name_for,+ get_identity,+ identity_for_target_id,+ is_agent_slug,+ normalize_client_name,+ register_identity,+ resolve_client_identity,+ unregister_identity,+)++__all__ = [+ "CLIENT_IDENTITY_MAPPING_VERSION",+ "UNKNOWN_AGENT",+ "AgentIdentity",+ "all_identities",+ "display_name_for",+ "get_identity",+ "identity_for_target_id",+ "is_agent_slug",+ "normalize_client_name",+ "register_identity",+ "resolve_client_identity",+ "unregister_identity",+]diff --git a/packages/core/src/repowise/core/agents/identity.py b/packages/core/src/repowise/core/agents/identity.pynew file mode 100644index 000000000..a5046ea4f--- /dev/null+++ b/packages/core/src/repowise/core/agents/identity.py@@ -0,0 +1,258 @@+"""One record per agent, and the only place an announced name becomes a slug.++The same agent used to be spelled four ways in four namespaces — ``claude-code``+as a ``--target`` id, ``claude-code`` as a hook adapter, ``claude_code`` as a+transcript adapter, and again in whatever the savings ledger happened to+enumerate. Each spelling was hand-maintained beside the others, which is the+defect even while they agree: agreement by hand is invisible when it breaks.++So one :class:`AgentIdentity` holds all of them and every namespace derives its+spelling from it.++Three shapes here are load-bearing:++**The canonical slug is the underscore form.** ``claude_code`` is already what+:mod:`repowise.core.sessions.adapters` uses and what the shipped+``pricing_agent`` wire field carries, it is a valid identifier, and it is a+clean column value. The hyphenated ``--target=`` id is *derived* from it rather+than declared, following :func:`~repowise.cli.agent_targets.types.derive_tier`:+a field a descriptor can set independently is a field that can disagree with the+thing it describes. The ceiling is an agent whose published target id is not the+hyphenated slug; the upgrade path is an explicit override field on this record,+added the day a second spelling is real rather than in anticipation of it.++**Aliases are mostly derived too.** What a host announces in MCP ``clientInfo``+is almost always its slug or its display name, so :attr:`AgentIdentity.aliases`+computes both and :attr:`announced_as` carries only the names neither spelling+reaches. A seventh agent therefore resolves correctly without anyone remembering+to write an alias down.++**Nothing downstream enumerates agents.** :func:`is_agent_slug` is the bounded+syntactic rule that storage applies — writer and reader alike — so an agent is+valid the day its descriptor lands and an event written by an agent since+retired still reads back. Membership in this registry decides only two things:+what an *announced* name resolves to, and what an agent is called on screen.+``unknown`` is what an unrecognised announcement becomes; it is never what a+stored slug is coerced to.+"""++from __future__ import annotations++import re+import threading+from dataclasses import dataclass, field++#: The attribution used when evidence is absent or unrecognised. Reserved: no+#: identity may claim it, because "we could not tell" and "this agent" have to+#: stay distinguishable.+UNKNOWN_AGENT = "unknown"++#: Version of the announced-name mapping, recorded on events that used it so a+#: later change to the alias rules is legible in stored data.+CLIENT_IDENTITY_MAPPING_VERSION = "mcp_client_info_v1"++#: Storage rule for an agent slug. Syntactic on purpose — see the module+#: docstring. Bounded so a column value cannot be a payload.+_SLUG_RE = re.compile(r"[a-z0-9_]{1,32}\Z")++#: Announced client names are compared with punctuation and case removed, so+#: ``Claude-Code``, ``claude code`` and ``ClaudeCode`` are one name. Bounded+#: before it reaches a lookup or a metadata field.+_ALIAS_LIMIT = 64+++def is_agent_slug(value: object) -> bool:+ """Whether *value* is a well-formed agent slug.++ The whole of the validation an agent id gets in storage. Deliberately not a+ membership test: see the module docstring.+ """+ return isinstance(value, str) and _SLUG_RE.fullmatch(value) is not None+++def normalize_client_name(value: object | None) -> str:+ """Reduce a self-declared client name to its comparable form.++ Empty for anything that carries no letters or digits, which the resolver+ treats as "not announced" rather than as a name it failed to recognise.+ """+ return re.sub(r"[^a-z0-9]", "", str(value or "").lower())[:_ALIAS_LIMIT]+++@dataclass(frozen=True, slots=True)+class AgentIdentity:+ """Who one agent is, in every namespace that needs to name it."""++ #: Canonical, underscore form. The value stored in the savings ledger and+ #: carried on the wire.+ slug: str+ #: What a human sees. The source an agent's label should come from; the+ #: report payload carries it so no consumer needs a label map of its own.+ #: (A few pre-existing UI maps still spell labels by hand and are folded in+ #: when their surfaces are rebuilt, not before.)+ display_name: str+ #: Names a host announces in MCP ``clientInfo`` that neither the slug nor+ #: the display name normalizes to. Usually empty.+ announced_as: frozenset[str] = field(default_factory=frozenset)+ #: Entry in ``repowise.cli.agent_adapters`` / ``core.sessions.adapters``.+ #: ``None`` means this agent has no such surface, which is what keeps it out+ #: of the Full tier. Declared rather than derived: the presence of these is+ #: an independent fact about what is implemented, which is exactly why+ #: ``derive_tier`` reads them.+ hook_adapter: str | None = None+ session_adapter: str | None = None++ def __post_init__(self) -> None:+ if not is_agent_slug(self.slug):+ raise ValueError(f"agent slug must match {_SLUG_RE.pattern}: {self.slug!r}")+ if self.slug == UNKNOWN_AGENT:+ raise ValueError(f"{UNKNOWN_AGENT!r} is reserved for unrecognised attribution")+ if not self.display_name:+ raise ValueError(f"{self.slug} needs a display name")+ if isinstance(self.announced_as, str):+ # A bare string is iterable, so this would otherwise register one+ # alias per character and answer to "e".+ raise ValueError(f"{self.slug} announced_as must be a set of names, not a string")+ for announced in self.announced_as:+ if announced != normalize_client_name(announced) or not announced:+ raise ValueError(f"{self.slug} alias {announced!r} is not in normalized form")+ if UNKNOWN_AGENT in self.aliases:+ raise ValueError(f"{self.slug} may not answer to {UNKNOWN_AGENT!r}")++ @property+ def cli_target_id(self) -> str:+ """The spelling ``--target=`` publishes, and the registry keys on."""+ return self.slug.replace("_", "-")++ @property+ def aliases(self) -> frozenset[str]:+ """Every announced name that resolves to this agent."""+ return frozenset(+ {normalize_client_name(self.slug), normalize_client_name(self.display_name)}+ | set(self.announced_as)+ )+++CLAUDE_CODE = AgentIdentity(+ slug="claude_code",+ display_name="Claude Code",+ #: The host announces the product, not the CLI, in some versions.+ announced_as=frozenset({"claude"}),+ hook_adapter="claude-code",+ session_adapter="claude_code",+)+CODEX = AgentIdentity(+ slug="codex",+ display_name="Codex CLI",+ hook_adapter="codex",+ session_adapter="codex",+)+VSCODE = AgentIdentity(slug="vscode", display_name="VS Code")+CURSOR = AgentIdentity(slug="cursor", display_name="Cursor")+OPENCODE = AgentIdentity(slug="opencode", display_name="OpenCode")+HERMES = AgentIdentity(slug="hermes", display_name="Hermes")++#: Registered identities, by slug. Order is not load-bearing here — the order+#: agents are *presented* in belongs to the target registry, which is where a+#: reader already looks for it.+_REGISTERED: dict[str, AgentIdentity] = {}++#: Announced name to slug, rebuilt on every registration and rebound as a whole.+#:+#: A prebuilt dict rather than a memoized lookup, because the registry is+#: mutable and the readers are concurrent. A ``functools.lru_cache`` computes+#: outside its own lock, so a thread that missed before a registration can store+#: its stale ``unknown`` after the invalidation and answer wrongly forever; and+#: a reader iterating the registry while another thread registers raises+#: ``dictionary changed size during iteration`` inside a request. Rebinding one+#: immutable snapshot has neither failure mode, and a dict lookup is cheaper+#: than a cache hit anyway.+_ALIAS_INDEX: dict[str, str] = {}++#: Held only by the two mutators, which run at import and in tests.+_REGISTRY_LOCK = threading.Lock()+++def _rebuild_alias_index() -> None:+ """Rebuild and atomically rebind the index. Caller holds the lock."""+ global _ALIAS_INDEX+ _ALIAS_INDEX = {+ alias: identity.slug for identity in _REGISTERED.values() for alias in identity.aliases+ }+++def register_identity(identity: AgentIdentity) -> AgentIdentity:+ """Register *identity*, replacing any prior record for the same slug.++ The seam a third-party agent package registers through, and the one tests+ use to prove a seventh agent needs no edit anywhere downstream. Returns the+ identity so it can decorate a declaration.+ """+ with _REGISTRY_LOCK:+ conflicts = {+ alias: existing.slug+ for existing in _REGISTERED.values()+ if existing.slug != identity.slug+ for alias in identity.aliases & existing.aliases+ }+ if conflicts:+ raise ValueError(f"{identity.slug} claims aliases already owned: {sorted(conflicts)}")+ _REGISTERED[identity.slug] = identity+ _rebuild_alias_index()+ return identity+++def unregister_identity(slug: str) -> None:+ """Drop a registered identity. For tests that register a fake agent."""+ with _REGISTRY_LOCK:+ _REGISTERED.pop(slug, None)+ _rebuild_alias_index()+++def all_identities() -> tuple[AgentIdentity, ...]:+ """Every registered identity, in registration order."""+ return tuple(_REGISTERED.values())+++def get_identity(slug: str) -> AgentIdentity | None:+ """The identity for *slug*, or ``None`` when no agent claims it."""+ return _REGISTERED.get(slug)+++def identity_for_target_id(target_id: str) -> AgentIdentity | None:+ """The identity behind a ``--target=`` id."""+ return get_identity(target_id.replace("-", "_"))+++def display_name_for(slug: str) -> str:+ """What to call *slug* on screen.++ An unregistered slug — a retired agent whose events are still in the ledger+ — is returned verbatim. Guessing a prettier label for an agent we no longer+ describe would be inventing evidence.+ """+ identity = _REGISTERED.get(slug)+ return identity.display_name if identity else slug+++def resolve_client_identity(client_name: str | None) -> str:+ """Resolve an announced MCP ``clientInfo`` name to a slug.++ The only place anything maps to :data:`UNKNOWN_AGENT`. Absent, empty and+ unrecognised names all resolve there — never to whichever agent happens to+ be the CLI's auto-detection fallback, which would attribute one host's+ traffic to another.++ Two operations, no allocation beyond the normalized name, so a caller on the+ MCP hot path pays almost nothing. It should still resolve once per session+ rather than once per event, because the announced name cannot change within+ one session.+ """+ return _ALIAS_INDEX.get(normalize_client_name(client_name), UNKNOWN_AGENT)+++#: The agents shipped with repowise, registered through the same seam a+#: third-party package would use, so the alias-disjointness check covers them too.+for _shipped in (CLAUDE_CODE, CODEX, VSCODE, CURSOR, OPENCODE, HERMES):+ register_identity(_shipped)+del _shippeddiff --git a/packages/core/src/repowise/core/savings/contracts.py b/packages/core/src/repowise/core/savings/contracts.pyindex d01c2d652..08f8ece3b 100644--- a/packages/core/src/repowise/core/savings/contracts.py+++ b/packages/core/src/repowise/core/savings/contracts.py@@ -11,6 +11,7 @@ from datetime import UTC, datetimefrom typing import Anyfrom uuid import UUID+from repowise.core.agents.identity import UNKNOWN_AGENT, is_agent_slugfrom repowise.core.savings.correlation import hash_correlation_evidence, new_event_idfrom repowise.core.savings.formulas import TokenAccounting, calculate_token_accountingfrom repowise.core.savings.normalization import normalize_metadata@@ -19,12 +20,30 @@ SCHEMA_VERSION = 1SURFACES = frozenset({"distill", "hook", "mcp", "vscode_lm"})EVIDENCE_KINDS = frozenset({"measured", "inferred"})RESULT_STATES = frozenset({"success", "dead_end", "error", "partial", "unknown"})-IDENTITIES = frozenset(- {"claude_code", "codex", "opencode", "hermes", "cursor", "vscode", "unknown"}-)_HASH_RE = re.compile(r"sha256:[0-9a-f]{64}\Z")+def _agent_slug(value: object | None, name: str) -> str:+ """Validate a stored agent id syntactically, never by membership.++ Deliberately not a closed set. A closed set here would be a second copy of+ the agent registry: it would go stale the day a seventh agent landed and+ bucket that agent's traffic as unattributed forever, and an event written by+ an agent since retired would stop reading back at all. Whether an announced+ name is *recognised* is a question for+ :mod:`repowise.core.agents.identity`, asked once when a client announces+ itself — not again on every read of a value we ourselves wrote.++ Applied identically on the way in and on the way out, which is the point:+ the two used to disagree, raising on an unrecognised id while the report+ silently coerced one to ``unknown``.+ """+ slug = str(value if value is not None else UNKNOWN_AGENT)+ if not is_agent_slug(slug):+ raise ValueError(f"{name} must be a bounded lowercase agent slug: {slug!r}")+ return slug++def utc_text(value: str | datetime) -> str:"""Normalize an aware timestamp to a lexically sortable UTC string."""parsed = (@@ -87,16 +106,14 @@ def _semantics(value: Mapping[str, Any]) -> _Semantics:surface = str(value["surface"])evidence_kind = str(value["evidence_kind"])result_state = str(value["result_state"])- integration = str(value.get("integration", "unknown"))- agent = str(value.get("agent", "unknown"))+ integration = _agent_slug(value.get("integration"), "integration")+ agent = _agent_slug(value.get("agent"), "agent")if surface not in SURFACES:raise ValueError(f"unsupported surface: {surface}")if evidence_kind not in EVIDENCE_KINDS:raise ValueError(f"unsupported evidence kind: {evidence_kind}")if result_state not in RESULT_STATES:raise ValueError(f"unsupported result state: {result_state}")- if integration not in IDENTITIES or agent not in IDENTITIES:- raise ValueError("integration and agent must use the v1 identity vocabulary")is_usable = value.get("is_usable")if not isinstance(is_usable, bool):raise ValueError("is_usable must be explicit")@@ -277,9 +294,7 @@ class OpportunityObservation:def from_mapping(cls, value: Mapping[str, Any], *, repository_id: str | None = None) -> OpportunityObservation:- integration = str(value.get("integration", "unknown"))- if integration not in IDENTITIES:- integration = "unknown"+ integration = _agent_slug(value.get("integration"), "integration")tokens = value.get("estimated_potential_input_tokens", 0)if isinstance(tokens, bool) or not isinstance(tokens, int):raise TypeError("estimated opportunity tokens must be an integer")diff --git a/packages/core/src/repowise/core/savings/normalization.py b/packages/core/src/repowise/core/savings/normalization.pyindex 2e9378ca4..187f80fc6 100644--- a/packages/core/src/repowise/core/savings/normalization.py+++ b/packages/core/src/repowise/core/savings/normalization.py@@ -2,30 +2,34 @@from __future__ import annotations-import refrom collections.abc import Mapping-IDENTITY_MAPPING_VERSION = "mcp_client_info_v1"-_IDENTITIES = {- "claude": "claude_code",- "claudecode": "claude_code",- "codex": "codex",- "opencode": "opencode",- "hermes": "hermes",- "cursor": "cursor",- "vscode": "vscode",-}+from repowise.core.agents.identity import (+ CLIENT_IDENTITY_MAPPING_VERSION,+ normalize_client_name,+ resolve_client_identity,+)++#: Re-exported so an event keeps recording which rules produced its attribution.+#: The rules themselves belong to the identity registry; this module only shapes+#: their result into event metadata.+IDENTITY_MAPPING_VERSION = CLIENT_IDENTITY_MAPPING_VERSIONMETADATA_ALLOWLIST = frozenset({"client_info_normalized", "identity_mapping_version"})def normalize_mcp_identity(client_name: object | None) -> tuple[str, dict[str, str]]:- """Map self-declared MCP clientInfo through the versioned allow-list."""- normalized = re.sub(r"[^a-z0-9]", "", str(client_name or "").lower())[:64]- identity = _IDENTITIES.get(normalized, "unknown")+ """Attribute a self-declared MCP clientInfo name, and record how.++ Resolution lives in :mod:`repowise.core.agents.identity` — savings does not+ enumerate agents. What *is* savings' concern is the audit trail: the+ normalized form that was looked up and the version of the rules that looked+ it up, so an attribution can be re-derived from the stored row later.+ """+ normalized = normalize_client_name(client_name)metadata = {"identity_mapping_version": IDENTITY_MAPPING_VERSION}if normalized:metadata["client_info_normalized"] = normalized- return identity, metadata+ return resolve_client_identity(normalized), metadatadef normalize_metadata(metadata: Mapping[str, object] | None) -> dict[str, str]:diff --git a/packages/core/src/repowise/core/savings/schema.py b/packages/core/src/repowise/core/savings/schema.pyindex 8f6e01276..52b600505 100644--- a/packages/core/src/repowise/core/savings/schema.py+++ b/packages/core/src/repowise/core/savings/schema.py@@ -4,7 +4,10 @@ from __future__ import annotationsimport sqlite3-SAVINGS_SCHEMA_VERSION = 1+#: Version of the *store*, recorded in ``PRAGMA user_version``. Distinct from+#: the per-event ``schema_version`` column, which versions an event payload and+#: is still 1: v2 changed only how the store validates an agent id.+SAVINGS_SCHEMA_VERSION = 2_PRESERVED_TABLES = ("""@@ -41,7 +44,7 @@ CREATE TABLE savings ()"""-_V1_TABLES = (+_SCHEMA_TABLES = ("""CREATE TABLE savings_events (event_id TEXT PRIMARY KEY,@@ -81,6 +84,14 @@ _V1_TABLES = (UNIQUE(repository_id, idempotency_key),CHECK(schema_version = 1),CHECK(surface IN ('distill','hook','mcp','vscode_lm')),+ -- Agent ids are checked syntactically, never against a list. A list+ -- here would be a copy of the agent registry that only the database+ -- can see, and it would reject a newly added agent's events outright.+ CHECK(length(integration) BETWEEN 1 AND 32+ AND integration NOT GLOB '*[^a-z0-9_]*'+ AND length(CAST(integration AS BLOB)) = length(integration)),+ CHECK(length(agent) BETWEEN 1 AND 32 AND agent NOT GLOB '*[^a-z0-9_]*'+ AND length(CAST(agent AS BLOB)) = length(agent)),CHECK(evidence_kind IN ('measured','inferred')),CHECK(result_state IN ('success','dead_end','error','partial','unknown')),CHECK(is_usable IN (0,1)),@@ -123,14 +134,15 @@ _V1_TABLES = (integration TEXT NOT NULL,kind TEXT NOT NULL,estimated_potential_input_tokens INTEGER NOT NULL,- CHECK(integration IN- ('claude_code','codex','opencode','hermes','cursor','vscode','unknown')),+ CHECK(length(integration) BETWEEN 1 AND 32+ AND integration NOT GLOB '*[^a-z0-9_]*'+ AND length(CAST(integration AS BLOB)) = length(integration)),CHECK(estimated_potential_input_tokens >= 0))""",)-_V1_INDEXES = (+_SCHEMA_INDEXES = ("CREATE INDEX idx_savings_events_repo_time ON savings_events(repository_id, occurred_at)","CREATE INDEX idx_savings_events_surface_time ON savings_events(surface, occurred_at)","CREATE INDEX idx_savings_events_operation_time ON savings_events(operation, occurred_at)",@@ -141,7 +153,7 @@ _V1_INDEXES = ("CREATE INDEX idx_savings_created ON savings(created_at)",)-_V1_REQUIRED_TABLES = frozenset(+_REQUIRED_TABLES = frozenset({"omissions","evidence_references",@@ -154,13 +166,19 @@ _V1_REQUIRED_TABLES = frozenset()-def _has_v1_schema(conn: sqlite3.Connection) -> bool:+def _has_current_schema(conn: sqlite3.Connection) -> bool:tables = {row[0] for row in conn.execute("SELECT name FROM sqlite_master WHERE type = 'table'")}- return tables >= _V1_REQUIRED_TABLES+ return tables >= _REQUIRED_TABLES-def _apply_v1(conn: sqlite3.Connection) -> None:- """Reset obsolete telemetry and install v1; caller owns the transaction."""+def _apply_schema(conn: sqlite3.Connection) -> None:+ """Reset obsolete telemetry and install the current schema.++ Caller owns the transaction. There is no row translation here by design:+ the savings tables carry no data worth migrating, because no producer has+ ever written one outside a test. The clean-reset policy is the plan's, not+ an oversight -- see docs/architecture/savings-accounting.md.+ """for statement in _PRESERVED_TABLES:conn.execute(statement)for table in (@@ -172,9 +190,9 @@ def _apply_v1(conn: sqlite3.Connection) -> None:):conn.execute(f"DROP TABLE IF EXISTS {table}")conn.execute(_LEGACY_SAVINGS_TABLE)- for statement in _V1_TABLES:+ for statement in _SCHEMA_TABLES:conn.execute(statement)- for statement in _V1_INDEXES:+ for statement in _SCHEMA_INDEXES:conn.execute(statement)@@ -187,7 +205,7 @@ def initialize_savings_schema(conn: sqlite3.Connection) -> None:f"savings sidecar schema {version} is newer than supported "f"version {SAVINGS_SCHEMA_VERSION}")- if version == SAVINGS_SCHEMA_VERSION and _has_v1_schema(conn):+ if version == SAVINGS_SCHEMA_VERSION and _has_current_schema(conn):returnconn.execute("BEGIN IMMEDIATE")try:@@ -197,8 +215,8 @@ def initialize_savings_schema(conn: sqlite3.Connection) -> None:f"savings sidecar schema {version} is newer than supported "f"version {SAVINGS_SCHEMA_VERSION}")- if version < SAVINGS_SCHEMA_VERSION or not _has_v1_schema(conn):- _apply_v1(conn)+ if version < SAVINGS_SCHEMA_VERSION or not _has_current_schema(conn):+ _apply_schema(conn)conn.execute(f"PRAGMA user_version={SAVINGS_SCHEMA_VERSION}")conn.commit()except BaseException:diff --git a/tests/unit/agents/__init__.py b/tests/unit/agents/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/tests/unit/agents/test_identity.py b/tests/unit/agents/test_identity.pynew file mode 100644index 000000000..3cb4a230e--- /dev/null+++ b/tests/unit/agents/test_identity.py@@ -0,0 +1,253 @@+"""Contract tests for the one place an agent is defined.++The properties here are the ones every downstream namespace assumes without+re-checking: that a slug is syntactically bounded, that the hyphenated target id+is derivable rather than declared, that no two agents answer to the same+announced name, and that an unrecognised announcement becomes ``unknown``+rather than somebody's traffic.+"""++from __future__ import annotations++from collections.abc import Iterator++import pytest++from repowise.core.agents import identity+from repowise.core.agents.identity import (+ UNKNOWN_AGENT,+ AgentIdentity,+ all_identities,+ display_name_for,+ get_identity,+ identity_for_target_id,+ is_agent_slug,+ normalize_client_name,+ register_identity,+ resolve_client_identity,+ unregister_identity,+)++SHIPPED = all_identities()+++def seventh_agent() -> Iterator[AgentIdentity]:+ """A registered agent that ships with nothing, removed again afterwards."""+ fake = AgentIdentity(slug="zed", display_name="Zed")+ register_identity(fake)+ try:+ yield fake+ finally:+ unregister_identity(fake.slug)+++# ---------------------------------------------------------------------------+# The slug rule+# ---------------------------------------------------------------------------++[email protected]("value", ["claude_code", "codex", "unknown", "a", "a" * 32, "x9_0"])+def test_well_formed_slugs_are_accepted(value: str) -> None:+ assert is_agent_slug(value)+++ "value",+ ["", "a" * 33, "Claude", "claude-code", "claude code", "claude.code", "claude/code", None, 7],+)+def test_malformed_slugs_are_rejected(value: object) -> None:+ assert not is_agent_slug(value)+++def test_the_rule_is_syntactic_not_membership() -> None:+ """The property the savings ledger depends on.++ An agent nobody has described — one added tomorrow, or one retired years+ ago whose events are still stored — is still a *valid* id. Only resolution+ of an announced name cares whether we recognise it.+ """+ assert get_identity("agent_from_the_future") is None+ assert is_agent_slug("agent_from_the_future")+++# ---------------------------------------------------------------------------+# The record+# ---------------------------------------------------------------------------++[email protected]("value", ["Claude-Code", "claude code", "", "a" * 33])+def test_a_record_refuses_a_malformed_slug(value: str) -> None:+ with pytest.raises(ValueError, match="agent slug"):+ AgentIdentity(slug=value, display_name="Whatever")+++def test_no_agent_may_claim_the_unknown_slug() -> None:+ """Otherwise "we could not tell" and "this agent" stop being distinguishable."""+ with pytest.raises(ValueError, match="reserved"):+ AgentIdentity(slug=UNKNOWN_AGENT, display_name="Unknown")+++def test_a_record_needs_a_display_name() -> None:+ with pytest.raises(ValueError, match="display name"):+ AgentIdentity(slug="nameless", display_name="")+++def test_announced_as_refuses_a_bare_string() -> None:+ """A string is iterable, so this would register one alias per character.++ ``announced_as="claude"`` would silently make the agent answer to "e".+ """+ with pytest.raises(ValueError, match="not a string"):+ AgentIdentity(slug="acme", display_name="Acme", announced_as="claude") # type: ignore[arg-type]+++def test_no_agent_may_answer_to_the_unknown_name() -> None:+ """Reserving the slug is not enough; an alias reaches the same confusion.++ A client announcing itself as "Unknown" must stay unattributed rather than+ being filed under whichever agent happened to be called that.+ """+ with pytest.raises(ValueError, match="may not answer to"):+ AgentIdentity(slug="mystery", display_name="Unknown")+ with pytest.raises(ValueError, match="may not answer to"):+ AgentIdentity(slug="mystery", display_name="Mystery", announced_as=frozenset({"unknown"}))+++def test_aliases_must_already_be_normalized() -> None:+ """A denormalized alias would sit in the index where nothing can match it."""+ with pytest.raises(ValueError, match="normalized form"):+ AgentIdentity(slug="x", display_name="X", announced_as=frozenset({"Claude Code"}))+++def test_the_published_target_ids_are_exactly_what_users_already_type() -> None:+ """Spelled out rather than re-derived.++ ``--target=`` ids are in the README, in INTEGRATIONS.md and in people's+ shell history. Deriving them from the slug is an implementation choice; that+ the derivation still produces these six strings is the constraint, and+ restating the formula here would assert nothing.+ """+ assert [agent.cli_target_id for agent in SHIPPED] == [+ "claude-code",+ "codex",+ "vscode",+ "cursor",+ "opencode",+ "hermes",+ ]++[email protected]("agent", SHIPPED, ids=lambda a: a.slug)+def test_a_target_id_round_trips_to_its_identity(agent: AgentIdentity) -> None:+ assert identity_for_target_id(agent.cli_target_id) is agent++[email protected]("agent", SHIPPED, ids=lambda a: a.slug)+def test_an_agent_answers_to_its_own_slug_and_display_name(agent: AgentIdentity) -> None:+ """Derived, so a seventh agent resolves without anyone writing an alias down.++ Asserted through the resolver rather than against ``aliases``, so it fails+ if the index, the normalizer or the derivation breaks -- not only if the+ property body is edited.+ """+ assert resolve_client_identity(agent.slug) == agent.slug+ assert resolve_client_identity(agent.display_name) == agent.slug+++def test_shipped_alias_sets_are_disjoint() -> None:+ seen: dict[str, str] = {}+ for agent in SHIPPED:+ for alias in agent.aliases:+ assert alias not in seen, f"{alias!r} claimed by {seen.get(alias)} and {agent.slug}"+ seen[alias] = agent.slug+++def test_registering_a_colliding_alias_is_refused() -> None:+ """Two agents answering to one name is silent misattribution, not a merge."""+ with pytest.raises(ValueError, match="aliases already owned"):+ register_identity(AgentIdentity(slug="impostor", display_name="Claude Code"))+ assert get_identity("impostor") is None+++# ---------------------------------------------------------------------------+# Resolution+# ---------------------------------------------------------------------------+++ ("announced", "expected"),+ [+ ("Claude Code", "claude_code"),+ ("claude-code", "claude_code"),+ ("ClaudeCode", "claude_code"),+ ("claude", "claude_code"),+ ("Codex CLI", "codex"),+ ("codex", "codex"),+ ("VS Code", "vscode"),+ ("Cursor", "cursor"),+ ("OpenCode", "opencode"),+ ("Hermes", "hermes"),+ ],+)+def test_announced_names_resolve_through_punctuation_and_case(+ announced: str, expected: str+) -> None:+ assert resolve_client_identity(announced) == expected+++ "announced", [None, "", " ", "!!!", "Windsurf", "Untrusted Client!" * 20]+)+def test_absent_or_unrecognised_names_resolve_to_unknown(announced: str | None) -> None:+ assert resolve_client_identity(announced) == UNKNOWN_AGENT+++def test_an_unannounced_client_is_never_attributed_to_the_cli_fallback() -> None:+ """The bug this resolver exists to make impossible.++ ``claude-code`` is what ``--target=auto`` falls back to when it detects+ nothing. Reusing that fallback here would file every anonymous MCP client's+ traffic under Claude Code, which is inventing evidence rather than missing it.+ """+ assert resolve_client_identity(None) != "claude_code"+ assert resolve_client_identity(None) == UNKNOWN_AGENT+++def test_normalization_bounds_a_hostile_announced_name() -> None:+ assert len(normalize_client_name("Untrusted Client!" * 200)) == 64+++def test_registration_rebuilds_the_alias_index(seventh_agent: AgentIdentity) -> None:+ """The index is an optimization; it must never outlive the truth."""+ assert resolve_client_identity("Zed") == "zed"+ unregister_identity("zed")+ assert resolve_client_identity("Zed") == UNKNOWN_AGENT+++# ---------------------------------------------------------------------------+# Labels+# ---------------------------------------------------------------------------++[email protected]("agent", SHIPPED, ids=lambda a: a.slug)+def test_the_registry_is_where_a_label_comes_from(agent: AgentIdentity) -> None:+ assert display_name_for(agent.slug) == agent.display_name+++def test_an_unregistered_slug_is_labelled_verbatim() -> None:+ """A retired agent still in the ledger gets its id back, not an invented name."""+ assert display_name_for("retired_agent") == "retired_agent"+ assert display_name_for(UNKNOWN_AGENT) == UNKNOWN_AGENT+++def test_the_shipped_registry_is_the_six_integrated_agents() -> None:+ """Frozen, so a seventh is a deliberate edit rather than a side effect."""+ assert [agent.slug for agent in identity.all_identities()] == [+ "claude_code",+ "codex",+ "vscode",+ "cursor",+ "opencode",+ "hermes",+ ]diff --git a/tests/unit/cli/test_agent_identity.py b/tests/unit/cli/test_agent_identity.pynew file mode 100644index 000000000..3a4afa7c7--- /dev/null+++ b/tests/unit/cli/test_agent_identity.py@@ -0,0 +1,359 @@+"""The descriptor/identity seam, and the promise that a seventh agent is cheap.++Parameterized across ``_TARGET_MODULES`` rather than written per agent, for the+same reason ``test_agent_targets.py`` is: the property under test is that the+seam holds for *every* registered target, and a per-agent test file would+quietly not have that property for the next one added.++``INTEGRATIONS.md`` promises adding an agent costs one descriptor file and one+registry line. The tests at the bottom are what stops savings attribution from+silently not being included in that promise.+"""++from __future__ import annotations++from collections.abc import Iterator+from datetime import UTC, datetime+from pathlib import Path++import pytest++from repowise.cli.agent_targets.registry import _TARGET_MODULES, get_target+from repowise.core.agents.identity import (+ UNKNOWN_AGENT,+ AgentIdentity,+ display_name_for,+ identity_for_target_id,+ is_agent_slug,+ register_identity,+ resolve_client_identity,+ unregister_identity,+)+from repowise.core.distill.store import OmissionStore+from repowise.core.savings.contracts import OpportunityObservation, SavingsEvent+from repowise.core.savings.correlation import scoped_idempotency_key+from repowise.core.savings.normalization import normalize_mcp_identity+from repowise.core.savings.repository import SavingsRepository++ALL_IDS = list(_TARGET_MODULES)++#: The agent this file pretends repowise integrated with. Nothing under+#: ``core/savings/`` mentions it, which is the whole point.+SEVENTH = AgentIdentity(+ slug="windsurf",+ display_name="Windsurf",+ hook_adapter="windsurf",+ session_adapter="windsurf",+)+++# ---------------------------------------------------------------------------+# Every registered target resolves an identity+# ---------------------------------------------------------------------------++[email protected]("target_id", ALL_IDS)+def test_every_target_is_backed_by_an_identity(target_id: str) -> None:+ assert identity_for_target_id(target_id) is not None++[email protected]("target_id", ALL_IDS)+def test_a_descriptor_does_not_restate_what_its_identity_says(target_id: str) -> None:+ """The duplication this seam exists to remove.++ ``id``, ``display_name`` and the two adapter names used to be typed into the+ descriptor beside the identical values elsewhere. They are now one value+ each, read from one record, so they cannot drift apart by hand.+ """+ target = get_target(target_id)+ agent = identity_for_target_id(target_id)+ assert target is not None and agent is not None+ assert target.id == agent.cli_target_id+ assert target.display_name == agent.display_name+ assert target.hook_adapter == agent.hook_adapter+ assert target.session_adapter == agent.session_adapter++[email protected]("target_id", ALL_IDS)+def test_the_published_target_id_is_the_registry_key(target_id: str) -> None:+ """``--target=`` ids are documented and typed by users; they may not move."""+ agent = identity_for_target_id(target_id)+ assert agent is not None+ assert agent.cli_target_id == target_id+ assert is_agent_slug(agent.slug)++[email protected]("target_id", ALL_IDS)+def test_every_alias_resolves_back_to_its_own_agent(target_id: str) -> None:+ agent = identity_for_target_id(target_id)+ assert agent is not None+ for alias in agent.aliases:+ assert resolve_client_identity(alias) == agent.slug+++def test_no_two_targets_answer_to_the_same_announced_name() -> None:+ claimed: dict[str, str] = {}+ for target_id in ALL_IDS:+ agent = identity_for_target_id(target_id)+ assert agent is not None+ for alias in agent.aliases:+ assert alias not in claimed, (+ f"{alias!r} claimed by {claimed.get(alias)} and {agent.slug}"+ )+ claimed[alias] = agent.slug+++# ---------------------------------------------------------------------------+# A seventh agent, end to end+# ---------------------------------------------------------------------------+++class _WindsurfTarget:+ """A descriptor for an agent repowise does not actually integrate with.++ Only the identity-derived attributes are real; nothing here touches the+ filesystem, because the chain under test is attribution, not installation.+ """++ id = SEVENTH.cli_target_id+ display_name = SEVENTH.display_name+ docs_url = None+ hook_adapter = SEVENTH.hook_adapter+ session_adapter = SEVENTH.session_adapter+ methods = ()+ project_file_id = "windsurf_rules"+++TARGET = _WindsurfTarget()+++def seventh_agent(monkeypatch: pytest.MonkeyPatch) -> Iterator[AgentIdentity]:+ """Add the agent exactly as shipping one would: an identity and a registry line."""+ register_identity(SEVENTH)+ monkeypatch.setitem(_TARGET_MODULES, SEVENTH.cli_target_id, f"{__name__}:TARGET")+ try:+ yield SEVENTH+ finally:+ unregister_identity(SEVENTH.slug)+++def test_a_seventh_agent_costs_a_descriptor_and_a_registry_line(+ seventh_agent: AgentIdentity,+) -> None:+ target = get_target("windsurf")+ assert target is not None+ assert target.id == "windsurf"+ assert target.display_name == "Windsurf"+ assert identity_for_target_id("windsurf") is seventh_agent+++def test_a_seventh_agent_is_attributed_rather_than_bucketed_as_unknown(+ seventh_agent: AgentIdentity,+) -> None:+ """The regression this phase exists to prevent.++ Before the vocabulary was unified, a newly added agent announced a name the+ savings domain had never heard of, so every one of its events landed in+ ``unknown`` permanently — while an adapter that passed the new id directly+ raised instead, on a write path behind live MCP calls.+ """+ assert resolve_client_identity("Windsurf") == seventh_agent.slug+ assert resolve_client_identity("Windsurf") != UNKNOWN_AGENT+++def test_a_seventh_agents_events_record_and_report_with_no_savings_edit(+ tmp_path: Path, seventh_agent: AgentIdentity+) -> None:+ """The exit criterion, proved rather than inspected.++ Nothing under ``core/savings/`` names this agent, and nothing needed to: the+ event validates, stores, survives the database's own CHECK constraints, and+ comes back out of the report attributed to it.+ """+ with OmissionStore(tmp_path / "omissions.db") as store:+ repository = SavingsRepository(store._conn)+ event = SavingsEvent.from_mapping(+ {+ "idempotency_key": scoped_idempotency_key("repo", "mcp", 1),+ "occurred_at": "2026-09-18T00:00:01Z",+ "repository_id": "repo",+ "surface": "mcp",+ "integration": seventh_agent.slug,+ "agent": seventh_agent.slug,+ "operation": "get_risk",+ "evidence_kind": "measured",+ "estimator": "seventh_agent_test",+ "token_unit": "estimated_tokens",+ "result_state": "success",+ "is_usable": True,+ "baseline_input_tokens": 100,+ "pre_budget_input_tokens": 100,+ "delivered_input_tokens": 40,+ }+ )+ assert event.agent == event.integration == seventh_agent.slug+ assert repository.record_event(event) is True+ assert (+ repository.record_opportunity(+ OpportunityObservation.from_mapping(+ {+ "observation_id": "obs-1",+ "occurred_at": "2026-09-18T00:00:02Z",+ "repository_id": "repo",+ "integration": seventh_agent.slug,+ "kind": "bypassed_distillation",+ "estimated_potential_input_tokens": 500,+ }+ )+ )+ is True+ )++ report = repository.report("repo", as_of=datetime(2026, 9, 19, tzinfo=UTC))+ assert report.saved_input_tokens == 60+ assert report.opportunity_count == 1+ assert report.opportunity_tokens_excluded == 500+ stored = store._conn.execute("SELECT agent, integration FROM savings_events").fetchone()+ assert tuple(stored) == (seventh_agent.slug, seventh_agent.slug)++ assert display_name_for(seventh_agent.slug) == "Windsurf"+++def test_a_retired_agents_events_still_read_back(tmp_path: Path) -> None:+ """The other half of a syntactic rule: nothing is enumerated on the way out.++ ``deprecated_agent`` has no identity record at all. A membership check would+ reject the write, or coerce the read to ``unknown`` and lose the attribution+ that was recorded when the agent did exist.+ """+ with OmissionStore(tmp_path / "omissions.db") as store:+ repository = SavingsRepository(store._conn)+ event = SavingsEvent.from_mapping(+ {+ "idempotency_key": scoped_idempotency_key("repo", "mcp", 2),+ "occurred_at": "2026-09-18T00:00:03Z",+ "repository_id": "repo",+ "surface": "mcp",+ "integration": "deprecated_agent",+ "agent": "deprecated_agent",+ "operation": "get_risk",+ "evidence_kind": "measured",+ "estimator": "seventh_agent_test",+ "token_unit": "estimated_tokens",+ "result_state": "success",+ "is_usable": True,+ "baseline_input_tokens": 10,+ "pre_budget_input_tokens": 10,+ "delivered_input_tokens": 4,+ }+ )+ assert repository.record_event(event) is True+ stored = store._conn.execute("SELECT agent FROM savings_events").fetchone()[0]+ assert stored == "deprecated_agent"+ assert display_name_for("deprecated_agent") == "deprecated_agent"++[email protected]("field", ["integration", "agent"])+def test_writer_and_reader_reject_a_malformed_id_the_same_way(field: str) -> None:+ """These two used to disagree: one raised, the other coerced to ``unknown``."""+ payload = {+ "idempotency_key": scoped_idempotency_key("repo", "mcp", 3),+ "occurred_at": "2026-09-18T00:00:04Z",+ "repository_id": "repo",+ "surface": "mcp",+ "integration": "codex",+ "agent": "codex",+ "operation": "get_risk",+ "evidence_kind": "measured",+ "estimator": "seventh_agent_test",+ "token_unit": "estimated_tokens",+ "result_state": "success",+ "is_usable": True,+ "baseline_input_tokens": 10,+ "pre_budget_input_tokens": 10,+ "delivered_input_tokens": 4,+ }+ with pytest.raises(ValueError, match=f"{field} must be a bounded"):+ SavingsEvent.from_mapping({**payload, field: "Windsurf!"})+ with pytest.raises(ValueError, match="integration must be a bounded"):+ OpportunityObservation.from_mapping(+ {+ "observation_id": "obs-2",+ "occurred_at": "2026-09-18T00:00:05Z",+ "repository_id": "repo",+ "integration": "Windsurf!",+ "kind": "bypassed_distillation",+ "estimated_potential_input_tokens": 1,+ }+ )++[email protected]("target_id", ALL_IDS)+def test_the_adapter_names_an_identity_declares_actually_exist(target_id: str) -> None:+ """The last hand-agreement this change did not already remove.++ ``hook_adapter`` and ``session_adapter`` are strings pointing into two+ registries the identity record does not own, and ``derive_tier`` reads both+ to decide the Full tier the README badges repeat. A typo in either would+ otherwise claim a depth that does not exist, silently, until something tried+ to load the adapter.+ """+ from repowise.cli.agent_adapters import _REGISTRY+ from repowise.core.sessions.adapters import registered_adapters++ agent = identity_for_target_id(target_id)+ assert agent is not None+ if agent.hook_adapter is not None:+ assert agent.hook_adapter in _REGISTRY+ if agent.session_adapter is not None:+ assert agent.session_adapter in registered_adapters()+++def test_an_announced_name_reaches_the_stored_attribution(+ tmp_path: Path, seventh_agent: AgentIdentity+) -> None:+ """The chain the commit claims, driven end to end rather than in halves.++ A host announces a display name over MCP; that name is resolved once; the+ resolved slug is what lands in the ``agent`` column and comes back out of+ the report. Nothing between those two ends enumerates agents.+ """+ resolved, metadata = normalize_mcp_identity("Windsurf")+ assert resolved == seventh_agent.slug+ assert metadata["client_info_normalized"] == "windsurf"++ with OmissionStore(tmp_path / "omissions.db") as store:+ repository = SavingsRepository(store._conn)+ repository.record_event(+ SavingsEvent.from_mapping(+ {+ "idempotency_key": scoped_idempotency_key("repo", "mcp", 9),+ "occurred_at": "2026-09-18T00:00:09Z",+ "repository_id": "repo",+ "surface": "mcp",+ "integration": resolved,+ "agent": resolved,+ "operation": "get_risk",+ "evidence_kind": "measured",+ "estimator": "seventh_agent_test",+ "token_unit": "estimated_tokens",+ "result_state": "success",+ "is_usable": True,+ "metadata": metadata,+ "baseline_input_tokens": 100,+ "pre_budget_input_tokens": 100,+ "delivered_input_tokens": 40,+ }+ )+ )+ stored = store._conn.execute("SELECT agent FROM savings_events").fetchone()[0]+ assert stored == "windsurf"+ assert display_name_for(stored) == "Windsurf"+++def test_an_unannounced_client_is_stored_as_unknown_not_as_the_fallback() -> None:+ """Absent evidence stays absent all the way into the row."""+ resolved, _ = normalize_mcp_identity(None)+ assert resolved == UNKNOWN_AGENT+ assert resolved != identity_for_target_id("claude-code").slug # type: ignore[union-attr]diff --git a/tests/unit/savings/test_repository.py b/tests/unit/savings/test_repository.pyindex 9b7862bfc..249f92a55 100644--- a/tests/unit/savings/test_repository.py+++ b/tests/unit/savings/test_repository.py@@ -82,7 +82,10 @@ def _seed_legacy(db_path: Path) -> None:def test_clean_install_has_versioned_event_link_and_query_indexes(tmp_path: Path) -> None:store = OmissionStore(tmp_path / "omissions.db")try:- assert store._conn.execute("PRAGMA user_version").fetchone()[0] == 1+ assert (+ store._conn.execute("PRAGMA user_version").fetchone()[0]+ == schema.SAVINGS_SCHEMA_VERSION+ )tables = {row[0]for row in store._conn.execute("SELECT name FROM sqlite_master WHERE type = 'table'")@@ -131,7 +134,7 @@ def test_claimed_current_but_incomplete_sidecar_is_repaired(tmp_path: Path) -> Ndb_path = tmp_path / "omissions.db"_seed_legacy(db_path)with sqlite3.connect(db_path) as conn:- conn.execute("PRAGMA user_version=1")+ conn.execute(f"PRAGMA user_version={schema.SAVINGS_SCHEMA_VERSION}")with OmissionStore(db_path) as store:assert store._conn.execute("SELECT COUNT(*) FROM savings").fetchone()[0] == 0assert store._conn.execute("SELECT COUNT(*) FROM savings_events").fetchone()[0] == 0@@ -143,13 +146,13 @@ def test_failed_upgrade_rolls_back_tables_rows_and_version(tmp_path: Path, monke_seed_legacy(db_path)conn = sqlite3.connect(db_path, isolation_level=None)apply_sqlite_pragmas(conn, 5000)- original = schema._apply_v1+ original = schema._apply_schemadef fail_after_changes(connection: sqlite3.Connection) -> None:original(connection)raise RuntimeError("simulated upgrade failure")- monkeypatch.setattr(schema, "_apply_v1", fail_after_changes)+ monkeypatch.setattr(schema, "_apply_schema", fail_after_changes)with pytest.raises(RuntimeError, match="simulated upgrade failure"):schema.initialize_savings_schema(conn)assert conn.execute("PRAGMA user_version").fetchone()[0] == 0@@ -174,7 +177,8 @@ def test_two_concurrent_openers_upgrade_once(tmp_path: Path) -> None:return store._conn.execute("PRAGMA user_version").fetchone()[0]with ThreadPoolExecutor(max_workers=2) as executor:- assert list(executor.map(open_and_read_version, range(2))) == [1, 1]+ expected = schema.SAVINGS_SCHEMA_VERSION+ assert list(executor.map(open_and_read_version, range(2))) == [expected, expected]with sqlite3.connect(db_path) as conn:assert conn.execute("SELECT COUNT(*) FROM savings_events").fetchone()[0] == 0@@ -258,3 +262,59 @@ def test_report_queries_are_read_only_and_breakdowns_are_bounded(tmp_path: Path)assert len(report.per_operation) == 3assert len(statements) == 3assert all(statement.lstrip().upper().startswith("SELECT") for statement in statements)++[email protected]("column", ["integration", "agent"])+ "value",+ ["", "A", "Windsurf", "a-b", "a b", "a\nb", "a" * 33, "a\x00WINDSURF!!!!", "café"],+)+def test_the_sidecar_refuses_a_malformed_agent_id_in_sql(+ tmp_path: Path, column: str, value: str+) -> None:+ """The backstop, tested where it actually lives.++ Every write in the domain goes through ``SavingsEvent.from_mapping``, which+ rejects these in Python long before SQLite sees them -- so a test that only+ writes through the contract passes whether the CHECK is right, inverted or+ absent. These go in by raw SQL, which is the only way to find out.++ The NUL case is why the constraint is not just ``GLOB``: SQLite's+ ``length()`` and pattern matching both stop at the first NUL, so+ ``'a\x00WINDSURF!!!!'`` looks one character long and clean to both.+ """+ with OmissionStore(tmp_path / "omissions.db") as store:+ columns = "event_id,schema_version,idempotency_key,occurred_at,repository_id,surface,"+ columns += "integration,agent,operation,evidence_kind,estimator,token_unit,result_state,"+ columns += "is_usable,saved_input_tokens,metadata_json"+ row = {"integration": "codex", "agent": "codex"}+ row[column] = value+ with pytest.raises(sqlite3.IntegrityError, match="CHECK constraint failed"):+ store._conn.execute(+ f"INSERT INTO savings_events ({columns}) "+ "VALUES ('e1',1,'k','2026-09-18T00:00:00Z','repo','mcp',?,?,"+ "'get_risk','measured','t','estimated_tokens','success',1,0,'{}')",+ (row["integration"], row["agent"]),+ )+++def test_the_sidecar_accepts_an_agent_it_has_never_heard_of(tmp_path: Path) -> None:+ """The constraint's actual purpose: bound the shape, never the membership.++ A SQL vocabulary list would reject this row outright, which is what made the+ seventh agent expensive.+ """+ with OmissionStore(tmp_path / "omissions.db") as store:+ writer = SavingsRepository(store._conn)+ assert writer.record_event(+ SavingsEvent.from_mapping(+ {**asdict(_event(0)), "integration": "windsurf", "agent": "windsurf"}+ )+ ) is True+ store._conn.execute(+ "INSERT INTO savings_opportunities VALUES ('o1','2026-09-18T00:00:00Z','repo',"+ "'never_heard_of_it','bypassed_distillation',5)"+ )+ assert store._conn.execute(+ "SELECT agent FROM savings_events"+ ).fetchone()[0] == "windsurf"