Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(grounding): a declared registry for grounding checks

Yufeng He74376747234d
diff --git a/agent/src/agent/grounding/identity_checks.py b/agent/src/agent/grounding/identity_checks.py
new file mode 100644
index 000000000..32a7a0046
--- /dev/null
+++ b/agent/src/agent/grounding/identity_checks.py
@@ -0,0 +1,56 @@
+"""Declared identity checks for the grounding gate (#1622).
+
+First checks migrated off the inline rule list in ``policies.py``; the
+predicates are byte-for-byte the logic that used to run inline, now declared
+with a stable name so run cards can say what fired.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+from src.agent.grounding.registry import grounding_check
+
+#: An answer that relabels a locked listed identity as private contradicts the
+#: resolver, which is an identity finding rather than a figure finding.
+_PRIVATE_ASSERTION_RE = re.compile(
+ r"(?:\b(?:is|remains|still)\s+(?:an?\s+)?(?:private company|privately held)\b|"
+ r"\bnot publicly traded\b|\bunlisted company\b|"
+ r"(?:是|仍是|属于)(?:一家)?(?:私人|私营|非上市)公司|未上市|没有上市)",
+ re.IGNORECASE,
+)
+
+
+@grounding_check(
+ name="listed-identity-relabelled-private",
+ code="listed_identity_relabelled_private",
+ description=(
+ "A locked listed identity (security or fund) was relabelled as "
+ "private or unlisted in the answer without a conflicting resolver result."
+ ),
+)
+def _listed_identity_relabelled_private(ledger: Any, content: str) -> list[dict[str, Any]]:
+ listed = [
+ record
+ for record in ledger._identities.values()
+ if record.status == "locked" and record.instrument_type in {"listed_security", "fund"}
+ ]
+ if not listed or not _PRIVATE_ASSERTION_RE.search(content):
+ return []
+ symbols = sorted(record.symbol for record in listed if record.symbol)
+ return [
+ {
+ "code": "listed_identity_relabelled_private",
+ "symbols": symbols,
+ "value": None,
+ "role": None,
+ "span": None,
+ "symbol": None,
+ "reason": "listed_relabelled_private",
+ "message": (
+ f"Locked listed identity {', '.join(symbols)} was relabelled as "
+ "private/unlisted without a conflicting resolver result."
+ ),
+ }
+ ]
diff --git a/agent/src/agent/grounding/policies.py b/agent/src/agent/grounding/policies.py
index 4768b60c6..d8b98cf78 100644
--- a/agent/src/agent/grounding/policies.py
+++ b/agent/src/agent/grounding/policies.py
@@ -20,6 +20,8 @@ from src.agent.grounding.identity import (
_normalize_symbol,
_scan_symbols,
)
+from src.agent.grounding import identity_checks # noqa: F401 (registers declared checks)
+from src.agent.grounding.registry import GROUNDING_CHECKS
from src.agent.grounding.evidence import (
EvidenceRecord,
_is_metadata_count_leaf,
@@ -41,15 +43,6 @@ from src.agent.grounding.figures import (
import re
-#: An answer that relabels a locked listed identity as private contradicts the
-#: resolver, which is an identity finding rather than a figure finding.
-_PRIVATE_ASSERTION_RE = re.compile(
- r"(?:\b(?:is|remains|still)\s+(?:an?\s+)?(?:private company|privately held)\b|"
- r"\bnot publicly traded\b|\bunlisted company\b|"
- r"(?:是|仍是|属于)(?:一家)?(?:私人|私营|非上市)公司|未上市|没有上市)",
- re.IGNORECASE,
-)
-
# Loader ids are ASCII but the answer follows the user's language, so a source
# is surfaced by any alias ("数据来源:腾讯财经" for ``tencent``).
_SOURCE_ALIASES = {
@@ -444,29 +437,7 @@ class _PolicyMixin:
),
}
)
- listed = [
- record
- for record in self._identities.values()
- if record.status == "locked"
- and record.instrument_type in {"listed_security", "fund"}
- ]
- if listed and _PRIVATE_ASSERTION_RE.search(content):
- symbols = sorted(record.symbol for record in listed if record.symbol)
- issues.append(
- {
- "code": "listed_identity_relabelled_private",
- "symbols": symbols,
- "value": None,
- "role": None,
- "span": None,
- "symbol": None,
- "reason": "listed_relabelled_private",
- "message": (
- f"Locked listed identity {', '.join(symbols)} was relabelled as "
- "private/unlisted without a conflicting resolver result."
- ),
- }
- )
+ issues.extend(GROUNDING_CHECKS.run("listed-identity-relabelled-private", self, content))
return issues
def _validate_figures(
diff --git a/agent/src/agent/grounding/registry.py b/agent/src/agent/grounding/registry.py
new file mode 100644
index 000000000..30e91898b
--- /dev/null
+++ b/agent/src/agent/grounding/registry.py
@@ -0,0 +1,88 @@
+"""Declared grounding checks: one registry entry per check (#1622).
+
+The grounding verifier used to grow by editing shared control flow in
+``policies.py``; every incident landed as another inline rule. This registry
+makes a check a declared row instead: a stable name, the issue code it emits
+(the release decision tables key on codes, so they stay the single decision
+owner), a description, and the predicate. Adding a check is adding a row plus
+a fixture pair, not touching call flow.
+
+Migration is golden-pass: existing suites must pass unchanged while checks
+move over one at a time. ``GROUNDING_CHECKS`` walks in registration order;
+the gate in ``ledger.py`` keeps built-ins first and walks the registry where
+each migrated check used to run inline, so issue order is preserved.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import TYPE_CHECKING, Any, Callable
+
+if TYPE_CHECKING:
+ from src.agent.grounding.ledger import GroundingLedger
+
+# A predicate gets the ledger (identity/figure state lives there) and the
+# candidate answer, and returns issue dicts in the existing shape.
+GroundingPredicate = Callable[["GroundingLedger", str], list[dict[str, Any]]]
+
+
+@dataclass(frozen=True)
+class GroundingCheck:
+ """One declared grounding check.
+
+ Attributes:
+ name: Stable identifier, shown when a run card lists fired checks.
+ code: The issue code the predicate emits. Release decisions key on
+ codes, so a registered check never invents a new one without a
+ matching decision entry.
+ description: What the check rejects, for the run card and docs.
+ predicate: The check itself.
+ """
+
+ name: str
+ code: str
+ description: str
+ predicate: GroundingPredicate
+
+
+class GroundingRegistry:
+ """Ordered registry of grounding checks. Duplicate names are rejected."""
+
+ def __init__(self) -> None:
+ self._checks: dict[str, GroundingCheck] = {}
+
+ def register(self, check: GroundingCheck) -> GroundingCheck:
+ if check.name in self._checks:
+ raise ValueError(f"duplicate grounding check: {check.name}")
+ self._checks[check.name] = check
+ return check
+
+ def get(self, name: str) -> GroundingCheck:
+ return self._checks[name]
+
+ def run(self, name: str, ledger: "GroundingLedger", content: str) -> list[dict[str, Any]]:
+ return self._checks[name].predicate(ledger, content)
+
+ def walk(self, ledger: "GroundingLedger", content: str) -> list[tuple[GroundingCheck, list[dict[str, Any]]]]:
+ """Every check with its issues, in registration order."""
+ return [(check, check.predicate(ledger, content)) for check in self._checks.values()]
+
+ def describe(self) -> list[dict[str, str]]:
+ """The check catalog for run cards and docs, in registration order."""
+ return [{"name": c.name, "code": c.code, "description": c.description} for c in self._checks.values()]
+
+ def __len__(self) -> int:
+ return len(self._checks)
+
+
+GROUNDING_CHECKS = GroundingRegistry()
+
+
+def grounding_check(*, name: str, code: str, description: str):
+ """Decorator: register a predicate as a declared grounding check."""
+
+ def wrap(predicate: GroundingPredicate) -> GroundingPredicate:
+ GROUNDING_CHECKS.register(GroundingCheck(name=name, code=code, description=description, predicate=predicate))
+ return predicate
+
+ return wrap
diff --git a/agent/tests/test_grounding_registry.py b/agent/tests/test_grounding_registry.py
new file mode 100644
index 000000000..51c5b69f6
--- /dev/null
+++ b/agent/tests/test_grounding_registry.py
@@ -0,0 +1,79 @@
+"""The declared grounding-check registry (#1622)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from src.agent.grounding.ledger import GroundingLedger
+from src.agent.grounding.registry import GROUNDING_CHECKS, GroundingCheck, GroundingRegistry
+
+
+def test_registry_rejects_duplicate_names() -> None:
+ registry = GroundingRegistry()
+ check = GroundingCheck(name="dup", code="some_code", description="d", predicate=lambda ledger, content: [])
+ registry.register(check)
+ with pytest.raises(ValueError, match="duplicate grounding check"):
+ registry.register(check)
+
+
+def test_registry_walk_order_and_describe_are_stable() -> None:
+ registry = GroundingRegistry()
+ for name in ("b-check", "a-check"):
+ registry.register(GroundingCheck(name=name, code=f"{name}_code", description="d", predicate=lambda l, c: []))
+ assert [c.name for c, _ in registry.walk(None, "")] == ["b-check", "a-check"]
+ assert [d["name"] for d in registry.describe()] == ["b-check", "a-check"]
+
+
+def _ledger_with_locked_listed_identity(tmp_path: Path) -> GroundingLedger:
+ ledger = GroundingLedger(run_dir=tmp_path, user_message="分析 GLD 并给出买入价")
+ ledger.ingest_tool_result(
+ tool_name="search_symbol",
+ arguments={"query": "GLD"},
+ result=json.dumps(
+ {
+ "ok": True,
+ "source": "symbol_search",
+ "data": {
+ "query": "GLD",
+ "count": 1,
+ "sources": {"yahoo": "ok"},
+ "candidates": [
+ {
+ "symbol": "GLD",
+ "market": "us",
+ "type": "listed_security",
+ "exchange": "ARCX",
+ "source": "yahoo",
+ }
+ ],
+ },
+ }
+ ),
+ call_id="resolve",
+ success=True,
+ )
+ assert ledger.identity_status == "locked"
+ return ledger
+
+
+def test_migrated_check_fires_identically_through_the_gate(tmp_path: Path) -> None:
+ """Golden pass for the first migrated check: same issue through both paths."""
+ ledger = _ledger_with_locked_listed_identity(tmp_path)
+
+ bad = ledger.validate_final_answer("GLD 仍是一家私人公司,建议观望。")
+ assert "listed_identity_relabelled_private" in [str(issue.get("code")) for issue in bad.issues]
+
+ direct = GROUNDING_CHECKS.run("listed-identity-relabelled-private", ledger, "GLD 仍是一家私人公司,建议观望。")
+ assert [issue["code"] for issue in direct] == ["listed_identity_relabelled_private"]
+
+ good = ledger.validate_final_answer("GLD 是上市 ETF,维持观察。")
+ assert "listed_identity_relabelled_private" not in [str(issue.get("code")) for issue in good.issues]
+ assert GROUNDING_CHECKS.run("listed-identity-relabelled-private", ledger, "GLD 是上市 ETF,维持观察。") == []
+
+
+def test_migrated_check_is_silent_with_nothing_locked(tmp_path: Path) -> None:
+ ledger = GroundingLedger(run_dir=tmp_path, user_message="随便聊聊")
+ assert GROUNDING_CHECKS.run("listed-identity-relabelled-private", ledger, "这是一家私人公司。") == []