From 45a4ef51b609819d18639a627e04617a84c9c61e Mon Sep 17 00:00:00 2001 From: Lan Zongwei Date: Fri, 27 Nov 2026 01:44:21 +0800 Subject: [PATCH] feat(rules): resolve accepted per-model rules for launchers `sim rules --harness H --model M --cwd D` prints the overlay SIM accepted for exactly this harness and model in the matching target, wrapped in a block, or nothing. Launchers that know the run's model (an orchestrator, a personal assistant) put it before the task prompt, the same place SIM evaluated it. Per-model overlays stay out of files every model reads: another model would get an unmeasured rule, and isolated worktrees do not carry untracked files. A run directory on another machine matches by repository name (match_repos, default the repo basename); --json adds provenance. Co-Authored-By: Claude Opus 5.5 --- README.md | 19 ++++++ README.zh-CN.md | 16 +++++ sim/cli.py | 30 ++++++++- sim/config.py | 4 ++ sim/rules.py | 156 ++++++++++++++++++++++++++++++++++++++++++++ tests/test_rules.py | 111 +++++++++++++++++++++++++++++++ 6 files changed, 335 insertions(+), 1 deletion(-) create mode 100644 sim/rules.py create mode 100644 tests/test_rules.py diff --git a/README.md b/README.md index 20e4947..71e4139 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,25 @@ pip install -e . ./bin/sim serve --port 8133 --token "" ``` +## Per-model rules in daily runs (`sim rules`) + +An overlay is validated on one model, so SIM never writes it into a file every model reads (`CLAUDE.md`, +`CLAUDE.local.md`): another model would get a rule nobody measured on it, and an isolated git worktree does not +carry untracked files anyway. Whatever starts the agent knows the model, so it asks SIM at start time and puts the +output before the task prompt, where SIM evaluated it: + +```sh +sim rules --harness claude --model small-model[1m] --cwd ~/repos/my-repo +# … (empty output: nothing to add) +``` + +- Only policies naming exactly this harness and model match; any other model gets nothing. +- `--cwd` may be a path on another machine: a target matches by its repository's name as a directory component + (`match_repos` in `target.json`, default the repo's basename). `--json` adds provenance (target, policy, + overlay, `rev`, ledger problems). +- Model-agnostic results (hooks, skills, scripts, `CLAUDE.md` edits) belong in the repository as commits, so every + launcher and worktree sees them. + ## Architecture ```text diff --git a/README.zh-CN.md b/README.zh-CN.md index ef532e3..3ff00cd 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -48,6 +48,22 @@ SIM 通过 6 条工程铁律打破这个循环: ./bin/sim serve --port 8133 --token "" ``` +## 日常运行里的按模型规则(`sim rules`) + +overlay 只在一个模型上验证过,所以 SIM 不把它写进所有模型都会读的文件(`CLAUDE.md`、`CLAUDE.local.md`): +别的模型会拿到没人测过的规则,而且隔离的 git worktree 本来就不带未跟踪文件。启动 Agent 的程序知道这次用哪个模型, +由它在启动时问 SIM,把输出放在任务提示前面,和 SIM 评测时的位置一致: + +```sh +sim rules --harness claude --model small-model[1m] --cwd ~/repos/my-repo +# … (无输出 = 没有要加的) +``` + +- 只有 harness 和模型都完全一致的 policy 才匹配;其他模型什么也拿不到。 +- `--cwd` 可以是另一台机器上的路径:按仓库名作为目录名来匹配(`target.json` 的 `match_repos`,默认是仓库目录名)。 + `--json` 附带溯源(靶标、policy、overlay、`rev`、账本里的问题编号)。 +- 与模型无关的产物(hook、skill、脚本、`CLAUDE.md` 改动)以提交的方式进仓库,所有启动方式和 worktree 都能拿到。 + ## Persona 扩展 见 [plugin/README.md](plugin/README.md)。扩展**只贡献 `nav_page` 和 `overview_card` 看板,刻意不注册 `memory_sources`**,确保 SIM 账本永远不会反向渗入日常对话上下文。 diff --git a/sim/cli.py b/sim/cli.py index 1185bc6..c2b7566 100644 --- a/sim/cli.py +++ b/sim/cli.py @@ -1,4 +1,4 @@ -"""Command-line interface for SIM (`sim init | preflight | eval | evolve | reaudit | harvest | status | gc | serve`).""" +"""Command-line interface for SIM (`sim init | preflight | eval | evolve | reaudit | rules | harvest | status | gc | serve`).""" from __future__ import annotations import argparse @@ -20,6 +20,7 @@ from .evolve import evolve_round, reaudit_for_model from .harvest import merge_harvest_inbox, scan_native_memories, set_harvest_status from .ledger import Ledger +from .rules import DEFAULT_MAX_BYTES, render as render_rules, resolve as resolve_rules from .sandbox import create_sandbox, gc_runs from .serve import build_board_status, make_server, save_last_eval @@ -377,6 +378,21 @@ def cmd_serve(args: argparse.Namespace) -> int: return 0 +def cmd_rules(args: argparse.Namespace) -> int: + """Print the rules SIM accepted for this run's repository, harness and model (nothing when there are none).""" + matches = resolve_rules(args.harness, args.model, args.cwd, repo_name=args.repo, + targets_dir=args.targets_dir, max_bytes=args.max_bytes) + text = render_rules(matches) + if getattr(args, "json", False): + _print_output({"rules": text, "matches": [m.to_dict() for m in matches]}, True) + elif text: + print(text) + for m in matches: + if m.skipped: + print(f"sim: rules for {m.target}/{m.policy} skipped: {m.skipped}", file=sys.stderr) + return 0 + + def build_parser() -> argparse.ArgumentParser: # Shared parent parser so BOTH `sim --json ` and `sim --json` work. common = argparse.ArgumentParser(add_help=False) @@ -429,6 +445,18 @@ def build_parser() -> argparse.ArgumentParser: p_re.add_argument("--policy", default=None, help="Target policy id") p_re.set_defaults(func=cmd_reaudit) + p_rules = sub.add_parser( + "rules", parents=[common], + help="Print the accepted per-model rules for a run (for launchers: put the output before the task prompt)", + ) + p_rules.add_argument("--harness", required=True, help="Harness of the run (claude, claude-code, codex, agy)") + p_rules.add_argument("--model", required=True, help="Model of the run (a [1m]-style suffix is ignored)") + p_rules.add_argument("--cwd", default="", help="Run directory (may be a path on another machine)") + p_rules.add_argument("--repo", default="", help="Repository name, when the caller knows it instead of a path") + p_rules.add_argument("--targets-dir", default="", help="Targets root (default: $SIM_TARGETS_DIR or ~/.sim/targets)") + p_rules.add_argument("--max-bytes", type=int, default=DEFAULT_MAX_BYTES, help="Skip an overlay larger than this") + p_rules.set_defaults(func=cmd_rules) + p_harv = sub.add_parser("harvest", parents=[common], help="Scan native harness memories for bloat, staleness, and SIM leads") p_harv.add_argument("--root", action="append", help="Explicit memory directory to scan (repeatable)") p_harv.add_argument("--harness", default="", help="Harness label when using --root") diff --git a/sim/config.py b/sim/config.py index 47e504e..d7cb7d0 100644 --- a/sim/config.py +++ b/sim/config.py @@ -217,6 +217,8 @@ class TargetConfig: env: EnvSpec = field(default_factory=EnvSpec) eval_suite: str = "v1" target_dir: str = "" + # Names a run directory on any machine may carry for this repository (default: the repo's basename). + match_repos: list[str] = field(default_factory=list) def __post_init__(self) -> None: if self.mode not in VALID_MODES: @@ -314,6 +316,7 @@ def load(cls, target_dir_or_file: str) -> "TargetConfig": env=EnvSpec.from_dict(data.get("env") or {}), eval_suite=str(data.get("eval_suite", "v1")), target_dir=target_dir, + match_repos=[str(x) for x in (data.get("match_repos") or []) if str(x).strip()], ) def to_dict(self) -> dict[str, Any]: @@ -333,6 +336,7 @@ def to_dict(self) -> dict[str, Any]: "policies": [asdict(p) for p in self.policies], "editable": asdict(self.editable), "env": asdict(self.env), + **({"match_repos": list(self.match_repos)} if self.match_repos else {}), } def save(self, path: str | None = None) -> None: diff --git a/sim/rules.py b/sim/rules.py new file mode 100644 index 0000000..a701ba4 --- /dev/null +++ b/sim/rules.py @@ -0,0 +1,156 @@ +"""Resolve the rules SIM accepted for one (repository, harness, model), for whoever starts an agent run. + +A per-model overlay is validated on one model only, so it must not live in a file every model reads +(`CLAUDE.md`, `CLAUDE.local.md`): another model would get a rule SIM never measured on it, and isolated +git worktrees do not carry untracked files anyway. The program that starts the run knows the model, so it +asks here at start time and puts the text where SIM evaluated it: before the task prompt. + +Read-only and model-free: it only reads `//target.json`, the policy's overlay and `sim.json`. +""" +from __future__ import annotations + +import hashlib +import os +from dataclasses import dataclass, field +from typing import Any + +from .adapters import load_overlay +from .config import TargetConfig, normalize_harness +from .ledger import Ledger + +DEFAULT_MAX_BYTES = 4096 + + +def default_targets_dir() -> str: + return os.path.expanduser(os.environ.get("SIM_TARGETS_DIR", "").strip() or "~/.sim/targets") + + +def canonical_model(model: str) -> str: + """`Gemini-4-Hydrogen[1m]` and `gemini-4-hydrogen` are one model: drop a context-window suffix and case.""" + m = (model or "").strip().lower() + if m.endswith("]") and "[" in m: + m = m[: m.rindex("[")] + return m + + +def _repo_names(cfg: TargetConfig) -> list[str]: + return [n for n in (cfg.match_repos or [os.path.basename(cfg.repo_path.rstrip(os.sep))]) if n] + + +def match_score(cfg: TargetConfig, cwd: str, repo_name: str = "") -> int: + """How well a run directory names this target's repository; -1 when it does not. + + A local path inside the repository wins. A path on another machine (or a checkout elsewhere) matches by a + directory component equal to the repository's name (`target.json` `match_repos`, default its basename); the + deepest such component wins, so `.../persona/tools/muster` is the muster repository, not persona.""" + names = _repo_names(cfg) + if repo_name: + return 1 if repo_name in names else -1 + if not cwd: + return -1 + expanded = os.path.expanduser(cwd) + repo = os.path.realpath(cfg.repo_path) + real = os.path.realpath(expanded) if os.path.exists(expanded) else os.path.normpath(expanded) + if real == repo or real.startswith(repo + os.sep): + return 100000 + len(repo) + parts = [p for p in os.path.normpath(expanded).split(os.sep) if p] + for idx in range(len(parts) - 1, -1, -1): + if parts[idx] in names: + return 1 + idx + return -1 + + +@dataclass +class RuleMatch: + target: str + policy: str + harness: str + model: str + overlay: str + text: str + rev: str + problems: list[str] = field(default_factory=list) + skipped: str = "" + + def to_dict(self) -> dict[str, Any]: + return { + "target": self.target, "policy": self.policy, "harness": self.harness, "model": self.model, + "overlay": self.overlay, "rev": self.rev, "bytes": len(self.text.encode("utf-8")), + "problems": self.problems, **({"skipped": self.skipped} if self.skipped else {}), + } + + +def _overlay_text(overlay: dict[str, Any]) -> str: + parts = [str(overlay.get(k) or "").strip() for k in ("append_system_prompt", "append_prompt")] + return "\n\n".join(p for p in parts if p) + + +def _accepted_problems(cfg: TargetConfig, overlay_rel: str) -> list[str]: + try: + ledger = Ledger.load(cfg.ledger_path()) + except (OSError, ValueError): + return [] + out = [] + for p in ledger.problems: + if p.status != "active": + continue + if any(a.accepted and overlay_rel in (a.files or []) for a in p.attempts): + out.append(p.id) + return out + + +def resolve(harness: str, model: str, cwd: str = "", *, repo_name: str = "", targets_dir: str = "", + max_bytes: int = DEFAULT_MAX_BYTES) -> list[RuleMatch]: + """The accepted overlays for this run: from the best-matching target, its policies on exactly this harness and + model. A model no policy names gets nothing: SIM has not measured any rule on it.""" + root = targets_dir or default_targets_dir() + want_h, want_m = normalize_harness(harness), canonical_model(model) + if not want_m or not os.path.isdir(root): + return [] + best: tuple[int, TargetConfig] | None = None + for name in sorted(os.listdir(root)): + path = os.path.join(root, name) + if not os.path.isfile(os.path.join(path, "target.json")): + continue + try: + cfg = TargetConfig.load(path) + except (OSError, ValueError, KeyError): + continue + score = match_score(cfg, cwd, repo_name) + if score >= 0 and (best is None or score > best[0]): + best = (score, cfg) + if best is None: + return [] + cfg = best[1] + out = [] + for pol in cfg.policies: + if normalize_harness(pol.harness) != want_h or canonical_model(pol.model) != want_m or not pol.overlay: + continue + overlay_path = os.path.join(cfg.target_dir, pol.overlay) + try: + overlay = load_overlay(overlay_path) + except (OSError, ValueError): + continue + bound = str(overlay.get("policy_model") or "") + if bound and canonical_model(bound) != want_m: + continue + text = _overlay_text(overlay) + if not text: + continue + rev = hashlib.sha256(text.encode("utf-8")).hexdigest()[:12] + m = RuleMatch(cfg.target, pol.id, want_h, pol.model, pol.overlay, text, rev, + _accepted_problems(cfg, pol.overlay)) + if len(text.encode("utf-8")) > max_bytes: + m.skipped = f"over {max_bytes} bytes" + out.append(m) + return out + + +def render(matches: list[RuleMatch]) -> str: + """The block a launcher puts before the task prompt; empty when there is nothing to add.""" + blocks = [] + for m in matches: + if m.skipped: + continue + blocks.append(f'\n{m.text}\n') + return "\n\n".join(blocks) diff --git a/tests/test_rules.py b/tests/test_rules.py new file mode 100644 index 0000000..9e31c36 --- /dev/null +++ b/tests/test_rules.py @@ -0,0 +1,111 @@ +import io +import json +import os +import tempfile +import unittest +from contextlib import redirect_stdout + +from sim.cli import main +from sim.rules import canonical_model, render, resolve + +RULE = "For README.md: never skip heading levels." + + +def _target(root, name, repo, policies, overlays, match_repos=None, ledger=None): + d = os.path.join(root, name) + os.makedirs(os.path.join(d, "overlays")) + cfg = {"target": name, "repo": repo, "mode": "unified", "policies": policies} + if match_repos: + cfg["match_repos"] = match_repos + with open(os.path.join(d, "target.json"), "w") as fh: + json.dump(cfg, fh) + for fname, body in overlays.items(): + with open(os.path.join(d, "overlays", fname), "w") as fh: + json.dump(body, fh) + with open(os.path.join(d, "sim.json"), "w") as fh: + json.dump(ledger or {"schema_version": 1, "target": name, "next_id": 1, "aliases": {}, "problems": []}, fh) + return d + + +class RulesTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.root = os.path.join(self.tmp.name, "targets") + self.repo = os.path.join(self.tmp.name, "repos", "muster") + os.makedirs(self.repo) + ledger = {"schema_version": 1, "target": "muster-harness", "next_id": 3, "aliases": {}, "problems": [ + {"id": "P1", "name": "doc headings", "opened_round": 1, "status": "active", "attempts": [ + {"round": 1, "op": "add", "artifact_type": "prompt", "what": "rule", + "files": ["overlays/small.json"], "accepted": True}]}, + {"id": "P2", "name": "hook", "opened_round": 2, "status": "active", "attempts": [ + {"round": 2, "op": "add", "artifact_type": "hook", "what": "hook", + "files": ["overlays/small.json"], "accepted": False}]}, + ]} + _target(self.root, "muster-harness", self.repo, [ + {"id": "claude-hub", "harness": "claude-code", "model": "small-model", "overlay": "overlays/small.json"}, + {"id": "codex-hub", "harness": "codex", "model": "codex-model", "overlay": "overlays/codex.json"}, + ], { + "small.json": {"policy_model": "small-model", "append_prompt": RULE}, + "codex.json": {"policy_model": "codex-model", "append_prompt": ""}, + "opus.json": {"policy_model": "claude-opus-5-5", "append_prompt": "never used: no policy names it"}, + }, ledger=ledger) + _target(self.root, "persona", os.path.join(self.tmp.name, "repos", "persona"), [ + {"id": "c", "harness": "claude-code", "model": "small-model", "overlay": "overlays/h.json"}, + ], {"h.json": {"policy_model": "small-model", "append_prompt": "persona rule"}}) + + def tearDown(self): + self.tmp.cleanup() + + def test_canonical_model_drops_context_suffix_and_case(self): + self.assertEqual(canonical_model("Small-Model[1m]"), "small-model") + self.assertEqual(canonical_model(" opus "), "opus") + + def test_only_the_validated_model_and_harness_get_the_rule(self): + got = resolve("claude", "small-model[1m]", self.repo, targets_dir=self.root) + self.assertEqual([m.policy for m in got], ["claude-hub"]) + self.assertEqual(got[0].problems, ["P1"]) # rejected attempts do not count + self.assertIn(RULE, render(got)) + self.assertIn('rev="', render(got)) + self.assertEqual(resolve("claude", "claude-opus-5-5", self.repo, targets_dir=self.root), []) + self.assertEqual(resolve("codex", "small-model", self.repo, targets_dir=self.root), []) + self.assertEqual(render(resolve("codex", "codex-model", self.repo, targets_dir=self.root)), "") + + def test_remote_paths_match_by_repo_name_and_deepest_component_wins(self): + got = resolve("claude-code", "small-model", "/home/other/repos/muster/sub", targets_dir=self.root) + self.assertEqual([m.target for m in got], ["muster-harness"]) + got = resolve("claude-code", "small-model", "/home/other/repos/persona/tools/muster", targets_dir=self.root) + self.assertEqual([m.target for m in got], ["muster-harness"]) + got = resolve("claude-code", "small-model", "/home/other/repos/persona", targets_dir=self.root) + self.assertEqual([m.target for m in got], ["persona"]) + self.assertEqual(resolve("claude-code", "small-model", "/home/other/.muster/wt/abc", targets_dir=self.root), []) + self.assertEqual(resolve("claude-code", "small-model", "", repo_name="muster", targets_dir=self.root)[0].target, + "muster-harness") + + def test_oversized_overlay_is_skipped(self): + got = resolve("claude", "small-model", self.repo, targets_dir=self.root, max_bytes=10) + self.assertEqual(got[0].skipped, "over 10 bytes") + self.assertEqual(render(got), "") + + def test_cli_prints_block_or_nothing(self): + out = io.StringIO() + with redirect_stdout(out): + rc = main(["rules", "--harness", "claude", "--model", "small-model", "--cwd", self.repo, + "--targets-dir", self.root]) + self.assertEqual(rc, 0) + self.assertTrue(out.getvalue().startswith('