deepmodebot 0.10.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/plugins/marketplace.json +1 -1
- package/.claude-plugin/marketplace.json +2 -2
- package/.omp-plugin/marketplace.json +2 -2
- package/README.md +15 -6
- package/bin/deepmodebot.mjs +104 -10
- package/native/dmb-gate/Cargo.toml +1 -1
- package/native/dmb-gate/src/agents.rs +58 -25
- package/native/dmb-gate/src/ci.rs +530 -14
- package/native/dmb-gate/src/main.rs +215 -7
- package/native/dmb-gate/src/reward.rs +1895 -242
- package/native/dmb-gate/src/sim.rs +969 -0
- package/native/dmb-gate/src/slop.rs +1061 -295
- package/package.json +1 -1
- package/plugins/deepmodebot/.antigravity-plugin/plugin.json +1 -1
- package/plugins/deepmodebot/.antigravity-plugin/skills/deep/SKILL.md +1 -1
- package/plugins/deepmodebot/.claude-plugin/plugin.json +1 -1
- package/plugins/deepmodebot/.codex-plugin/plugin.json +2 -2
- package/plugins/deepmodebot/agents/comment-sicko.md +29 -0
- package/plugins/deepmodebot/agents/researcher.md +29 -0
- package/plugins/deepmodebot/agents/reviewer.md +29 -0
- package/plugins/deepmodebot/agents/scout.md +28 -0
- package/plugins/deepmodebot/agents/security-reviewer.md +27 -0
- package/plugins/deepmodebot/commands/deep.md +3 -2
- package/plugins/deepmodebot/commands/tournament.md +1 -1
- package/plugins/deepmodebot/hooks/hooks.json +12 -2
- package/plugins/deepmodebot/hooks.json +1 -1
- package/plugins/deepmodebot/scripts/antigravity-guard.mjs +740 -37
- package/plugins/deepmodebot/skills/agent-harnesses/references/antigravity.md +2 -2
- package/plugins/deepmodebot/skills/deepmodebot/SKILL.md +19 -11
- package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/agents_md.py +51 -20
- package/plugins/deepmodebot/skills/deepmodebot/assets/autoroute/autoroute.py +54 -49
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude-guard.sh +4 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude_guard.py +658 -21
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/holdout_guard_cases.json +272 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain.ts +774 -23
- package/plugins/deepmodebot/skills/deepmodebot/assets/f2p-gate/f2p_gate.py +547 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/gap-audit/gap_audit.py +5 -11
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard-patterns.txt +4 -4
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.sh +53 -6
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.ts +48 -2
- package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/local_ci.py +262 -6
- package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/slop_gate.py +529 -122
- package/plugins/deepmodebot/skills/deepmodebot/assets/loop/loop.py +747 -46
- package/plugins/deepmodebot/skills/deepmodebot/assets/memory/project_memory.py +404 -5
- package/plugins/deepmodebot/skills/deepmodebot/assets/mutation/mutation_gate.py +798 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/reward-guard/reward_guard.py +2050 -200
- package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule-paths.json +44 -1
- package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule_ledger.py +278 -252
- package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rules_watch.py +436 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/self-grill/self_grill.py +594 -18
- package/plugins/deepmodebot/skills/deepmodebot/assets/setup/project_setup.py +41 -5
- package/plugins/deepmodebot/skills/deepmodebot/assets/sim/sim.py +856 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/worker-gate/worker_gate.py +237 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/catalog.md +3 -2
- package/plugins/deepmodebot/skills/deepmodebot/references/delegation.md +6 -2
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/authoring-a-skill.md +1 -1
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/hillclimb.md +1 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/self-authoring.md +1 -1
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/no-reward-hacking.md +6 -6
- package/plugins/deepmodebot/skills/deepmodebot/references/rule-approval.md +36 -16
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/autoroute.md +9 -8
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/correct.md +1 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/inner-loop.md +6 -2
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/mutation-testing.md +31 -9
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/no-comments.md +1 -1
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/panel.md +4 -4
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sim.md +41 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tdd.md +12 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tournament.md +24 -13
- package/plugins/deepmodebot/skills/deepmodebot/worker.md +28 -16
- package/plugins/deepmodebot/agents/comment-sicko/agent.md +0 -35
- package/plugins/deepmodebot/agents/researcher/agent.md +0 -33
- package/plugins/deepmodebot/agents/reviewer/agent.md +0 -35
- package/plugins/deepmodebot/agents/scout/agent.md +0 -33
- package/plugins/deepmodebot/agents/security-reviewer/agent.md +0 -31
|
@@ -0,0 +1,856 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Self-Improvement Memory (SIM) for the harness optimizer, with Continual Recursive Self-Improvement (CRSI).
|
|
3
|
+
|
|
4
|
+
Paper: https://arxiv.org/abs/2611.18856. SIM groups accepted harness edits by the recurring problem they address and
|
|
5
|
+
keeps each attempt's rationale, predicted and observed outcomes, and evaluation context (domain, benchmark, policy,
|
|
6
|
+
round). The store is `.deepmodebot/sim.json`; it is append-only and committed with the harness it explains.
|
|
7
|
+
|
|
8
|
+
python -B sim.py init [--root <repo>] [--force] [--json]
|
|
9
|
+
python -B sim.py read [--root <repo>] [--role proposer|selector] [--format prompt|json|markdown]
|
|
10
|
+
python -B sim.py propose --root <repo> (--problem <Pid> | --root-cause <text>) --what <edit and why>
|
|
11
|
+
--files <f1,f2> [--predicted <t1,t2>] --domain <d> [--benchmark <b>]
|
|
12
|
+
--policy <model> [--round N] [--sample sN] [--split evolve] [--json]
|
|
13
|
+
python -B sim.py record --root <repo> [--proposal <id>] [--accepted | --no-accepted]
|
|
14
|
+
[--fixed t1,t2] [--missed t3] [--passed N --total M | --check-cmd <cmd>] [--json]
|
|
15
|
+
python -B sim.py transfer --from <source sim.json> [--root <repo> | --to <sim.json>] --into <arm>
|
|
16
|
+
--domain <d> [--benchmark <b>] [--policy <m>] [--source-arm <arm>]
|
|
17
|
+
[--mode full|problem-only|none] [--json]
|
|
18
|
+
python -B sim.py status [--root <repo>] [--json]
|
|
19
|
+
python -B sim.py check [--root <repo>] [--base <ref>] [--staged] [--files a,b] [--advisory] [--json]
|
|
20
|
+
|
|
21
|
+
Enforcement (`check`): when `.deepmodebot/sim.json` exists, existed at the base ref, or `.deepmodebot/policy.xml` has
|
|
22
|
+
`<sim required="true"/>`, the store must be valid. Once the store exists at the base ref, every changed harness file
|
|
23
|
+
must be covered by a new accepted attempt and committed attempts are immutable (the diff that introduces the store is
|
|
24
|
+
bootstrap). Only evolve-split feedback may enter the store, and each attempt's pre-evaluation digest must match.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import argparse
|
|
30
|
+
import fnmatch
|
|
31
|
+
import hashlib
|
|
32
|
+
import json
|
|
33
|
+
import os
|
|
34
|
+
import re
|
|
35
|
+
import subprocess
|
|
36
|
+
import sys
|
|
37
|
+
import time
|
|
38
|
+
import xml.etree.ElementTree as ET
|
|
39
|
+
from pathlib import Path
|
|
40
|
+
|
|
41
|
+
sys.dont_write_bytecode = True
|
|
42
|
+
|
|
43
|
+
SCHEMA_VERSION = 1
|
|
44
|
+
PAPER_URL = "https://arxiv.org/abs/2611.18856"
|
|
45
|
+
SIM_REL = ".deepmodebot/sim.json"
|
|
46
|
+
NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
47
|
+
PROBLEM_ID_RE = re.compile(r"^P([1-9][0-9]*)$")
|
|
48
|
+
PROPOSAL_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$")
|
|
49
|
+
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
|
|
50
|
+
TRANSFER_MODES = ("full", "problem-only", "none")
|
|
51
|
+
SKIP_SEGMENTS = frozenset({".git", ".scratch", ".worktrees", "node_modules", "__pycache__"})
|
|
52
|
+
TEST_PATH_RE = re.compile(
|
|
53
|
+
r"(?:^|/)(?:tests?/|spec/|__tests__/)|(?:^|/)(?:test_[^/]+|[^/]+(?:_test|\.test|\.spec))\.[^/]+$", re.I)
|
|
54
|
+
HARNESS_NAMES = frozenset({
|
|
55
|
+
"agents.md", "agents.override.md", "agents.local.md", "agent.md", "claude.md", "claude.local.md", "gemini.md",
|
|
56
|
+
".cursorrules", ".windsurfrules", ".clinerules", ".roorules", ".rules",
|
|
57
|
+
})
|
|
58
|
+
HARNESS_FILES = frozenset({".github/copilot-instructions.md", ".deepmodebot/policy.xml", ".deepmodebot/ci.yml"})
|
|
59
|
+
HARNESS_DIRS = (
|
|
60
|
+
".omp/", ".claude/", ".agents/", ".agent/", ".codex/", ".gemini/", ".cursor/rules/", ".windsurf/rules/",
|
|
61
|
+
".devin/", ".roo/rules/", ".kiro/steering/", ".continue/rules/", ".amazonq/rules/", ".github/instructions/",
|
|
62
|
+
)
|
|
63
|
+
CRSI_DIRECTIVES = (
|
|
64
|
+
"1. Treat entries as prior experience, with flexibility to choose a different edit.",
|
|
65
|
+
"2. Check the domain, benchmark, and model behind each entry.",
|
|
66
|
+
"3. Start with an existing diagnosis when it explains the current failure.",
|
|
67
|
+
"4. Reuse the rationale and reassess the edit after a benchmark or model change.",
|
|
68
|
+
"5. Revise, replace, or override a harness modification when new evidence warrants it.",
|
|
69
|
+
"6. Revisit a tested direction only when new evidence justifies it.",
|
|
70
|
+
"7. Create a new problem entry when existing diagnoses do not explain the failure.",
|
|
71
|
+
"8. Give task-specific evidence more weight in similar settings and less when both benchmark and model change.",
|
|
72
|
+
)
|
|
73
|
+
_UNSET = object()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def norm_rel(raw) -> str:
|
|
77
|
+
cleaned = str(raw or "").strip().replace("\\", "/")
|
|
78
|
+
while cleaned.startswith("./"):
|
|
79
|
+
cleaned = cleaned[2:]
|
|
80
|
+
return cleaned.lstrip("/")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def normalize_ws(text) -> str:
|
|
84
|
+
return " ".join(str(text or "").split())
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def normalize_cause(text) -> str:
|
|
88
|
+
return normalize_ws(text).lower()
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def split_csv(items) -> list[str]:
|
|
92
|
+
out: list[str] = []
|
|
93
|
+
for raw in items or ():
|
|
94
|
+
for part in str(raw).split(","):
|
|
95
|
+
val = part.strip()
|
|
96
|
+
if val and val not in out:
|
|
97
|
+
out.append(val)
|
|
98
|
+
return out
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def finding(severity: str, rule: str, file: str, message: str, fix: str) -> dict:
|
|
102
|
+
return {"severity": severity, "rule": rule, "file": file, "line": 1, "message": message, "fix": fix}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def proposal_digest(*, cause_key, round_num, sample, domain, benchmark, policy, what, files, predicted) -> str:
|
|
106
|
+
"""Pre-evaluation commitment: binds the rationale, files and predictions before outcomes are known."""
|
|
107
|
+
payload = "\n".join([
|
|
108
|
+
"dmb-sim-proposal-v1",
|
|
109
|
+
normalize_cause(cause_key),
|
|
110
|
+
f"round={int(round_num)}",
|
|
111
|
+
f"sample={str(sample).strip()}",
|
|
112
|
+
f"domain={str(domain).strip()}",
|
|
113
|
+
f"benchmark={str(benchmark or '').strip()}",
|
|
114
|
+
f"policy={str(policy).strip()}",
|
|
115
|
+
f"what={normalize_ws(what)}",
|
|
116
|
+
"files=" + ",".join(sorted({norm_rel(f) for f in files if norm_rel(f)})),
|
|
117
|
+
"predicted=" + ",".join(sorted({str(p).strip() for p in predicted if str(p).strip()})),
|
|
118
|
+
])
|
|
119
|
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def attempt_digest(att: dict) -> str:
|
|
123
|
+
return proposal_digest(
|
|
124
|
+
cause_key=att.get("cause_key", ""), round_num=att.get("round", 0), sample=att.get("sample", ""),
|
|
125
|
+
domain=att.get("domain", ""), benchmark=att.get("benchmark", ""), policy=att.get("policy", ""),
|
|
126
|
+
what=att.get("what", ""), files=att.get("files") or [], predicted=att.get("predicted") or [],
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _git(root: Path, *args: str) -> subprocess.CompletedProcess:
|
|
131
|
+
proc = subprocess.run(["git", "-C", str(root), *args], capture_output=True, timeout=30, creationflags=NO_WINDOW)
|
|
132
|
+
return subprocess.CompletedProcess(proc.args, proc.returncode, proc.stdout.decode("utf-8", errors="replace"),
|
|
133
|
+
proc.stderr.decode("utf-8", errors="replace"))
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def resolve_main_root(start: Path) -> Path:
|
|
137
|
+
resolved = start.expanduser().resolve()
|
|
138
|
+
try:
|
|
139
|
+
proc = _git(resolved, "rev-parse", "--path-format=absolute", "--git-common-dir")
|
|
140
|
+
except OSError:
|
|
141
|
+
return resolved
|
|
142
|
+
common = Path(proc.stdout.strip()) if proc.returncode == 0 and proc.stdout.strip() else None
|
|
143
|
+
if common is not None and common.name == ".git" and ".scratch" not in resolved.parts:
|
|
144
|
+
return common.parent
|
|
145
|
+
return resolved
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def sim_store_path(root: Path) -> Path:
|
|
149
|
+
return Path(root).resolve() / SIM_REL
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def scratch_dir(root: Path) -> Path:
|
|
153
|
+
scratch = resolve_main_root(Path(root)) / ".scratch"
|
|
154
|
+
if scratch.is_symlink():
|
|
155
|
+
raise ValueError(f"refusing symlinked scratch directory: {scratch}")
|
|
156
|
+
scratch.mkdir(parents=True, exist_ok=True)
|
|
157
|
+
ignore = scratch / ".gitignore"
|
|
158
|
+
if not ignore.exists():
|
|
159
|
+
ignore.write_text("*\n", encoding="utf-8")
|
|
160
|
+
sim_dir = scratch / "sim"
|
|
161
|
+
if sim_dir.is_symlink():
|
|
162
|
+
raise ValueError(f"refusing symlinked SIM scratch directory: {sim_dir}")
|
|
163
|
+
(sim_dir / "proposals").mkdir(parents=True, exist_ok=True)
|
|
164
|
+
return sim_dir
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def write_json_atomic(path: Path, data: dict) -> str:
|
|
168
|
+
if path.is_symlink():
|
|
169
|
+
raise ValueError(f"refusing symlinked SIM file: {path}")
|
|
170
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
171
|
+
encoded = json.dumps(data, indent=2, ensure_ascii=False) + "\n"
|
|
172
|
+
tmp = path.parent / f".{path.name}.{os.getpid()}.tmp"
|
|
173
|
+
tmp.write_text(encoded, encoding="utf-8", newline="\n")
|
|
174
|
+
os.replace(tmp, path)
|
|
175
|
+
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def empty_store(carried_from: dict | None = None) -> dict:
|
|
179
|
+
return {"schema_version": SCHEMA_VERSION, "paper": PAPER_URL, "next_id": 1, "carried_from": carried_from,
|
|
180
|
+
"aliases": {}, "problems": []}
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def load_store(path: Path) -> tuple[dict, str]:
|
|
184
|
+
if path.is_symlink():
|
|
185
|
+
raise ValueError(f"refusing symlinked SIM store: {path}")
|
|
186
|
+
raw = path.read_bytes()
|
|
187
|
+
data = json.loads(raw.decode("utf-8"))
|
|
188
|
+
if not isinstance(data, dict):
|
|
189
|
+
raise ValueError("SIM store root must be a JSON object")
|
|
190
|
+
return data, hashlib.sha256(raw).hexdigest()
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def load_or_empty(root: Path) -> tuple[dict, str]:
|
|
194
|
+
store = sim_store_path(root)
|
|
195
|
+
return load_store(store) if store.is_file() else (empty_store(), "empty")
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def policy_config(root: Path) -> dict:
|
|
199
|
+
cfg = {"required": False, "include": [], "exclude": []}
|
|
200
|
+
policy = Path(root) / ".deepmodebot" / "policy.xml"
|
|
201
|
+
if not policy.is_file() or policy.is_symlink():
|
|
202
|
+
return cfg
|
|
203
|
+
try:
|
|
204
|
+
el = ET.fromstring(policy.read_text(encoding="utf-8")).find(".//sim")
|
|
205
|
+
except (OSError, ET.ParseError):
|
|
206
|
+
return cfg
|
|
207
|
+
if el is None:
|
|
208
|
+
return cfg
|
|
209
|
+
cfg["required"] = (el.attrib.get("required") or "").strip().lower() in ("true", "1", "yes")
|
|
210
|
+
cfg["include"] = [norm_rel(p) for p in (el.attrib.get("paths") or "").split(",") if norm_rel(p)]
|
|
211
|
+
cfg["exclude"] = [norm_rel(p) for p in (el.attrib.get("exclude") or "").split(",") if norm_rel(p)]
|
|
212
|
+
return cfg
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def sim_enforced(root: Path) -> bool:
|
|
216
|
+
store = sim_store_path(root)
|
|
217
|
+
return store.exists() or store.is_symlink() or policy_config(root)["required"]
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def is_harness_file(rel_raw, include=(), exclude=()) -> bool:
|
|
221
|
+
"""Agent instructions, skills, hooks, agent settings and the repo's declared harness code (policy `paths`)."""
|
|
222
|
+
rel = norm_rel(rel_raw)
|
|
223
|
+
if not rel or rel == SIM_REL or SKIP_SEGMENTS & set(rel.split("/")) or TEST_PATH_RE.search(rel):
|
|
224
|
+
return False
|
|
225
|
+
low = rel.lower()
|
|
226
|
+
if any(fnmatch.fnmatch(low, pat.lower()) for pat in exclude):
|
|
227
|
+
return False
|
|
228
|
+
if any(fnmatch.fnmatch(low, pat.lower()) for pat in include):
|
|
229
|
+
return True
|
|
230
|
+
if low.rsplit("/", 1)[-1] in HARNESS_NAMES or low in HARNESS_FILES:
|
|
231
|
+
return True
|
|
232
|
+
return any(low.startswith(d) or f"/{d}" in f"/{low}" for d in HARNESS_DIRS)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def stamp_read_receipt(root: Path, sim_sha: str, role: str) -> None:
|
|
236
|
+
write_json_atomic(scratch_dir(root) / "read-receipt.json", {
|
|
237
|
+
"sim_sha256": sim_sha, "role": role, "read_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
238
|
+
})
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def read_receipt_fresh(root: Path, sim_sha: str) -> bool:
|
|
242
|
+
receipt = scratch_dir(root) / "read-receipt.json"
|
|
243
|
+
try:
|
|
244
|
+
return json.loads(receipt.read_text(encoding="utf-8")).get("sim_sha256") == sim_sha
|
|
245
|
+
except (OSError, ValueError):
|
|
246
|
+
return False
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def init_store(root: Path, force: bool = False) -> dict:
|
|
250
|
+
store = sim_store_path(root)
|
|
251
|
+
if store.exists() and not force:
|
|
252
|
+
data, sha = load_store(store)
|
|
253
|
+
return {"ok": True, "created": False, "path": str(store), "sha256": sha, "problems": len(data.get("problems") or [])}
|
|
254
|
+
sha = write_json_atomic(store, empty_store())
|
|
255
|
+
return {"ok": True, "created": True, "path": str(store), "sha256": sha, "problems": 0}
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def resolve_alias(aliases: dict, pid: str) -> str:
|
|
259
|
+
cur, seen = str(pid).strip(), set()
|
|
260
|
+
while cur in aliases and cur not in seen:
|
|
261
|
+
seen.add(cur)
|
|
262
|
+
cur = str(aliases[cur]).strip()
|
|
263
|
+
return cur
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def render_prompt(data: dict, role: str = "proposer") -> str:
|
|
267
|
+
"""The complete record, untruncated, as the paper gives it to the proposer and selector."""
|
|
268
|
+
lines = [f'<self-improvement-memory role="{role}" paper="{PAPER_URL}">',
|
|
269
|
+
"Use this record of earlier harness edits before proposing or selecting another (CRSI):", *CRSI_DIRECTIVES]
|
|
270
|
+
if data.get("carried_from"):
|
|
271
|
+
lines.append("Carried from: " + json.dumps(data["carried_from"], ensure_ascii=False, sort_keys=True))
|
|
272
|
+
if data.get("aliases"):
|
|
273
|
+
lines.append("Merged problem aliases: " + json.dumps(data["aliases"], ensure_ascii=False, sort_keys=True))
|
|
274
|
+
problems = data.get("problems") or []
|
|
275
|
+
if problems:
|
|
276
|
+
lines.append(f"Problems ({len(problems)}), every attempt kept, misses included:")
|
|
277
|
+
lines.append(json.dumps(problems, indent=2, ensure_ascii=False))
|
|
278
|
+
else:
|
|
279
|
+
lines.append("Problems: none recorded yet; the first accepted harness edit opens P1.")
|
|
280
|
+
lines.append("</self-improvement-memory>")
|
|
281
|
+
return "\n".join(lines)
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def render_markdown(data: dict) -> str:
|
|
285
|
+
problems = data.get("problems") or []
|
|
286
|
+
lines = [f"# Self-Improvement Memory: {len(problems)} problem(s)", ""]
|
|
287
|
+
for prob in problems:
|
|
288
|
+
lines.append(f"## {prob.get('id')}: {prob.get('name')} (opened round {prob.get('opened_round')})")
|
|
289
|
+
for att in prob.get("attempts") or []:
|
|
290
|
+
lines.append(f"- round {att.get('round')} {att.get('sample')} [{att.get('domain')} / {att.get('benchmark')} / "
|
|
291
|
+
f"{att.get('policy')}] {att.get('passed')}/{att.get('total')}: {att.get('what')}")
|
|
292
|
+
lines.append(f" files {att.get('files')}; predicted {att.get('predicted')}; fixed {att.get('fixed')}; "
|
|
293
|
+
f"missed {att.get('missed')}")
|
|
294
|
+
lines.append("")
|
|
295
|
+
return "\n".join(lines).rstrip() + "\n"
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def check_split(split) -> str:
|
|
299
|
+
if str(split or "evolve").strip().lower() != "evolve":
|
|
300
|
+
raise ValueError(f"split {split!r} rejected: only evolve-set feedback may enter SIM; held-out data stays outside the loop")
|
|
301
|
+
return "evolve"
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def clean_files(files) -> list[str]:
|
|
305
|
+
out: list[str] = []
|
|
306
|
+
for raw in files:
|
|
307
|
+
rel = norm_rel(raw)
|
|
308
|
+
if not rel:
|
|
309
|
+
continue
|
|
310
|
+
if os.path.isabs(str(raw)) or ".." in rel.split("/") or ":" in rel.split("/")[0]:
|
|
311
|
+
raise ValueError(f"SIM file entry must be a repo-relative path: {raw!r}")
|
|
312
|
+
if rel not in out:
|
|
313
|
+
out.append(rel)
|
|
314
|
+
return out
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _target_problem(data: dict, problem_id: str | None, root_cause: str | None) -> tuple[str | None, str]:
|
|
318
|
+
problems = [p for p in data.get("problems") or [] if isinstance(p, dict)]
|
|
319
|
+
if problem_id:
|
|
320
|
+
target = resolve_alias(data.get("aliases") or {}, problem_id)
|
|
321
|
+
for prob in problems:
|
|
322
|
+
if prob.get("id") == target:
|
|
323
|
+
return target, normalize_ws(prob.get("name"))
|
|
324
|
+
raise ValueError(f"cited problem {problem_id!r} does not exist in SIM")
|
|
325
|
+
if len(normalize_ws(root_cause)) < 8:
|
|
326
|
+
raise ValueError("cite --problem <Pid> or name a specific --root-cause (8+ characters)")
|
|
327
|
+
for prob in problems:
|
|
328
|
+
if normalize_cause(prob.get("name")) == normalize_cause(root_cause):
|
|
329
|
+
return str(prob["id"]), normalize_ws(prob.get("name"))
|
|
330
|
+
return None, normalize_ws(root_cause)
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def stage_proposal(root: Path, *, what: str, files, domain: str, policy: str, problem_id: str | None = None,
|
|
334
|
+
root_cause: str | None = None, predicted=(), benchmark: str = "", round_num: int = 1,
|
|
335
|
+
sample: str = "s1", split: str = "evolve", proposal_id: str | None = None) -> dict:
|
|
336
|
+
"""Record the edit, its rationale and its predicted fixes before evaluation (paper section 3.2)."""
|
|
337
|
+
root = Path(root).resolve()
|
|
338
|
+
checked_split = check_split(split)
|
|
339
|
+
data, sim_sha = load_or_empty(root)
|
|
340
|
+
if (data.get("problems") or []) and not read_receipt_fresh(root, sim_sha):
|
|
341
|
+
raise ValueError("read the current SIM first (`sim.py read`); the proposer must see every earlier attempt")
|
|
342
|
+
norm_files = clean_files(files)
|
|
343
|
+
if not norm_files:
|
|
344
|
+
raise ValueError("propose needs at least one repo-relative harness file in --files")
|
|
345
|
+
if len(normalize_ws(what)) < 15:
|
|
346
|
+
raise ValueError("--what must state the modification and its rationale (15+ characters)")
|
|
347
|
+
if not str(domain).strip() or not str(policy).strip():
|
|
348
|
+
raise ValueError("propose needs --domain and --policy provenance")
|
|
349
|
+
pid, cause = _target_problem(data, problem_id, root_cause)
|
|
350
|
+
cause_key = pid or cause
|
|
351
|
+
preds = [str(p).strip() for p in predicted if str(p).strip()]
|
|
352
|
+
digest = proposal_digest(cause_key=cause_key, round_num=round_num, sample=sample, domain=domain,
|
|
353
|
+
benchmark=benchmark, policy=policy, what=what, files=norm_files, predicted=preds)
|
|
354
|
+
slug = proposal_id or f"r{int(round_num)}-{sample}-{digest[:10]}"
|
|
355
|
+
if not PROPOSAL_ID_RE.fullmatch(slug):
|
|
356
|
+
raise ValueError(f"invalid proposal id {slug!r}")
|
|
357
|
+
record = {
|
|
358
|
+
"proposal_id": slug, "problem_id": pid, "root_cause": cause, "cause_key": cause_key,
|
|
359
|
+
"round": int(round_num), "sample": str(sample).strip(), "what": normalize_ws(what), "files": norm_files,
|
|
360
|
+
"predicted": preds, "domain": str(domain).strip(), "benchmark": str(benchmark or "").strip(),
|
|
361
|
+
"policy": str(policy).strip(), "split": checked_split, "sim_sha256": sim_sha, "proposal_sha256": digest,
|
|
362
|
+
"created_epoch": round(time.time(), 3), "status": "staged",
|
|
363
|
+
}
|
|
364
|
+
write_json_atomic(scratch_dir(root) / "proposals" / f"{slug}.json", record)
|
|
365
|
+
return record
|
|
366
|
+
|
|
367
|
+
|
|
368
|
+
def staged_proposals(root: Path, since_epoch: float = 0.0) -> list[Path]:
|
|
369
|
+
rows = []
|
|
370
|
+
for path in (scratch_dir(root) / "proposals").glob("*.json"):
|
|
371
|
+
try:
|
|
372
|
+
obj = json.loads(path.read_text(encoding="utf-8"))
|
|
373
|
+
except (OSError, ValueError):
|
|
374
|
+
continue
|
|
375
|
+
if obj.get("status") == "staged" and float(obj.get("created_epoch") or 0.0) >= since_epoch:
|
|
376
|
+
rows.append((float(obj.get("created_epoch") or 0.0), path))
|
|
377
|
+
return [path for _, path in sorted(rows)]
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _open_problem(data: dict, problem_id: str | None, cause: str, round_num: int) -> dict:
|
|
381
|
+
problems = data.setdefault("problems", [])
|
|
382
|
+
if problem_id:
|
|
383
|
+
target = resolve_alias(data.setdefault("aliases", {}), problem_id)
|
|
384
|
+
for prob in problems:
|
|
385
|
+
if prob.get("id") == target:
|
|
386
|
+
return prob
|
|
387
|
+
for prob in problems:
|
|
388
|
+
if normalize_cause(prob.get("name")) == normalize_cause(cause):
|
|
389
|
+
return prob
|
|
390
|
+
nums = [int(m.group(1)) for p in problems if (m := PROBLEM_ID_RE.match(str(p.get("id", ""))))]
|
|
391
|
+
next_id = max([int(data.get("next_id") or 1), *(n + 1 for n in nums)])
|
|
392
|
+
prob = {"id": f"P{next_id}", "name": normalize_ws(cause), "opened_round": int(round_num), "attempts": []}
|
|
393
|
+
problems.append(prob)
|
|
394
|
+
data["next_id"] = next_id + 1
|
|
395
|
+
return prob
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def record_outcome(root: Path, *, proposal_id: str | None = None, accepted: bool = True, fixed=None, missed=None,
|
|
399
|
+
passed: int | None = None, total: int | None = None, check_cmd: str | None = None,
|
|
400
|
+
timeout_sec: int = 300) -> dict:
|
|
401
|
+
"""Append the selected candidate's measured outcome, misses included (paper section 3.2)."""
|
|
402
|
+
root = Path(root).resolve()
|
|
403
|
+
if proposal_id:
|
|
404
|
+
prop_file = scratch_dir(root) / "proposals" / f"{proposal_id}.json"
|
|
405
|
+
if not prop_file.is_file():
|
|
406
|
+
raise ValueError(f"staged proposal {proposal_id!r} not found")
|
|
407
|
+
else:
|
|
408
|
+
staged = staged_proposals(root)
|
|
409
|
+
if not staged:
|
|
410
|
+
raise ValueError("no staged proposal; run `sim.py propose` before evaluating the edit")
|
|
411
|
+
prop_file = staged[-1]
|
|
412
|
+
prop = json.loads(prop_file.read_text(encoding="utf-8"))
|
|
413
|
+
if prop.get("status") != "staged":
|
|
414
|
+
raise ValueError(f"proposal {prop.get('proposal_id')!r} is already {prop.get('status')}")
|
|
415
|
+
check_split(prop.get("split"))
|
|
416
|
+
predicted = list(prop.get("predicted") or [])
|
|
417
|
+
if check_cmd:
|
|
418
|
+
proc = subprocess.run(check_cmd, shell=True, cwd=str(root), capture_output=True, text=True, encoding="utf-8",
|
|
419
|
+
errors="replace", timeout=max(1, int(timeout_sec)), creationflags=NO_WINDOW)
|
|
420
|
+
if passed is None and total is None:
|
|
421
|
+
passed, total = (1 if proc.returncode == 0 else 0), 1
|
|
422
|
+
if fixed is None and missed is None:
|
|
423
|
+
fixed, missed = (predicted, []) if proc.returncode == 0 else ([], predicted)
|
|
424
|
+
if not accepted:
|
|
425
|
+
prop["status"] = "rejected"
|
|
426
|
+
write_json_atomic(prop_file, prop)
|
|
427
|
+
return {"ok": True, "accepted": False, "updated_sim": False, "proposal_id": prop["proposal_id"]}
|
|
428
|
+
if passed is None or total is None or not 0 <= int(passed) <= int(total) or int(total) <= 0:
|
|
429
|
+
raise ValueError("an accepted attempt needs evolve-set trials: 0 <= --passed <= --total, --total > 0")
|
|
430
|
+
fixed_list = [str(x).strip() for x in fixed or [] if str(x).strip()]
|
|
431
|
+
missed_list = ([str(x).strip() for x in missed if str(x).strip()] if missed is not None
|
|
432
|
+
else [p for p in predicted if p not in fixed_list])
|
|
433
|
+
if set(fixed_list) & set(missed_list):
|
|
434
|
+
raise ValueError(f"fixed and missed overlap: {sorted(set(fixed_list) & set(missed_list))}")
|
|
435
|
+
unresolved = [p for p in predicted if p not in fixed_list and p not in missed_list]
|
|
436
|
+
if unresolved:
|
|
437
|
+
raise ValueError(f"every predicted item must land in fixed or missed; unresolved: {unresolved}")
|
|
438
|
+
store = sim_store_path(root)
|
|
439
|
+
data = load_store(store)[0] if store.is_file() else empty_store()
|
|
440
|
+
prob = _open_problem(data, prop.get("problem_id"), prop["root_cause"], int(prop["round"]))
|
|
441
|
+
attempt = {
|
|
442
|
+
"round": int(prop["round"]), "sample": prop["sample"], "accepted": True, "backfilled": False,
|
|
443
|
+
"what": prop["what"], "files": list(prop["files"]), "predicted": predicted, "fixed": fixed_list,
|
|
444
|
+
"missed": missed_list, "passed": int(passed), "total": int(total), "domain": prop["domain"],
|
|
445
|
+
"benchmark": prop.get("benchmark", ""), "policy": prop["policy"], "split": "evolve",
|
|
446
|
+
"cause_key": prop["cause_key"], "proposal_sha256": prop["proposal_sha256"],
|
|
447
|
+
}
|
|
448
|
+
if attempt_digest(attempt) != prop["proposal_sha256"]:
|
|
449
|
+
raise ValueError("staged proposal was edited after staging; stage it again")
|
|
450
|
+
prob["attempts"].append(attempt)
|
|
451
|
+
sim_sha = write_json_atomic(store, data)
|
|
452
|
+
stamp_read_receipt(root, sim_sha, "recorder")
|
|
453
|
+
prop.update(status="recorded", recorded_problem_id=prob["id"])
|
|
454
|
+
write_json_atomic(prop_file, prop)
|
|
455
|
+
return {"ok": True, "accepted": True, "updated_sim": True, "problem_id": prob["id"],
|
|
456
|
+
"proposal_id": prop["proposal_id"], "sim_sha256": sim_sha}
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def transfer(source: Path, dest: Path, *, into: str, domain: str, benchmark: str = "", policy: str = "",
|
|
460
|
+
source_arm: str = "", mode: str = "full") -> dict:
|
|
461
|
+
"""Carry SIM into a new benchmark or policy model (paper section 3.3 transfer conditions)."""
|
|
462
|
+
if mode not in TRANSFER_MODES:
|
|
463
|
+
raise ValueError(f"mode must be one of {TRANSFER_MODES}")
|
|
464
|
+
src, src_sha = load_store(Path(source))
|
|
465
|
+
carried = {"arm": source_arm or "source", "into": into, "domain": domain, "benchmark": benchmark,
|
|
466
|
+
"policy": policy, "mode": mode, "source_sha256": src_sha}
|
|
467
|
+
problems = [p for p in src.get("problems") or [] if isinstance(p, dict)]
|
|
468
|
+
if mode == "none":
|
|
469
|
+
out = empty_store(carried)
|
|
470
|
+
elif mode == "problem-only":
|
|
471
|
+
out = {**empty_store(carried), "next_id": int(src.get("next_id") or 1), "aliases": dict(src.get("aliases") or {}),
|
|
472
|
+
"problems": [{"id": p["id"], "name": p["name"], "opened_round": p.get("opened_round", 0), "attempts": []}
|
|
473
|
+
for p in problems]}
|
|
474
|
+
else:
|
|
475
|
+
out = {**json.loads(json.dumps(src)), "schema_version": SCHEMA_VERSION, "paper": PAPER_URL, "carried_from": carried}
|
|
476
|
+
sha = write_json_atomic(Path(dest), out)
|
|
477
|
+
return {"ok": True, "mode": mode, "dest": str(dest), "sha256": sha, "problems": len(out["problems"])}
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
def changed_files(root: Path, *, staged: bool = False, base_ref: str | None = None) -> list[str]:
|
|
481
|
+
found: set[str] = set()
|
|
482
|
+
if staged:
|
|
483
|
+
r = _git(root, "diff", "--cached", "--name-only", "--diff-filter=ACMRD")
|
|
484
|
+
return sorted({norm_rel(x) for x in r.stdout.splitlines() if norm_rel(x)}) if r.returncode == 0 else []
|
|
485
|
+
ref = base_ref or "HEAD"
|
|
486
|
+
if _git(root, "rev-parse", "--verify", ref).returncode == 0:
|
|
487
|
+
r = _git(root, "diff", ref, "--name-only", "--diff-filter=ACMRD")
|
|
488
|
+
else:
|
|
489
|
+
r = _git(root, "diff", "--cached", "--name-only", "--diff-filter=ACMRD")
|
|
490
|
+
if r.returncode == 0:
|
|
491
|
+
found.update(norm_rel(x) for x in r.stdout.splitlines() if norm_rel(x))
|
|
492
|
+
u = _git(root, "ls-files", "--others", "--exclude-standard")
|
|
493
|
+
if u.returncode == 0:
|
|
494
|
+
found.update(norm_rel(x) for x in u.stdout.splitlines() if norm_rel(x))
|
|
495
|
+
return sorted(found)
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def _int_field(value) -> bool:
|
|
499
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
def _validate_attempt(pid: str, idx: int, att, carried_mode: str) -> list[dict]:
|
|
503
|
+
where = f"{pid} attempt[{idx}]"
|
|
504
|
+
if not isinstance(att, dict):
|
|
505
|
+
return [finding("P0", "sim-schema-invalid", SIM_REL, f"{where} must be an object.", "Record attempts with `sim.py record`.")]
|
|
506
|
+
out: list[dict] = []
|
|
507
|
+
if str(att.get("split") or "evolve").strip().lower() != "evolve":
|
|
508
|
+
out.append(finding("P0", "sim-holdout-leakage", SIM_REL, f"{where} uses split={att.get('split')!r}.",
|
|
509
|
+
"SIM takes evolve-set feedback only; keep held-out evaluation outside the loop."))
|
|
510
|
+
if att.get("accepted") is not True:
|
|
511
|
+
out.append(finding("P1", "sim-schema-invalid", SIM_REL, f"{where} is not an accepted edit.",
|
|
512
|
+
"SIM stores the selected candidate only; record rejected ones with `--no-accepted`."))
|
|
513
|
+
if len(normalize_ws(att.get("what"))) < 15:
|
|
514
|
+
out.append(finding("P1", "sim-schema-invalid", SIM_REL, f"{where} lacks the modification and rationale (`what`).",
|
|
515
|
+
"State what changed and why."))
|
|
516
|
+
files = att.get("files")
|
|
517
|
+
if not isinstance(files, list) or not files or not all(isinstance(f, str) and norm_rel(f) for f in files):
|
|
518
|
+
out.append(finding("P1", "sim-schema-invalid", SIM_REL, f"{where} needs a non-empty `files` list.",
|
|
519
|
+
"List the harness files the edit changed."))
|
|
520
|
+
passed, total = att.get("passed"), att.get("total")
|
|
521
|
+
if not (_int_field(passed) and _int_field(total) and 0 <= passed <= total and total > 0):
|
|
522
|
+
out.append(finding("P1", "sim-schema-invalid", SIM_REL, f"{where} has invalid passed/total ({passed}/{total}).",
|
|
523
|
+
"Record evolve-set trials with 0 <= passed <= total and total > 0."))
|
|
524
|
+
if not normalize_ws(att.get("domain")) or not normalize_ws(att.get("policy")):
|
|
525
|
+
out.append(finding("P1", "sim-schema-invalid", SIM_REL, f"{where} lacks `domain` or `policy` provenance.",
|
|
526
|
+
"Record the benchmark domain and the policy model that executed the tasks."))
|
|
527
|
+
lists = [att.get(k) for k in ("predicted", "fixed", "missed")]
|
|
528
|
+
if not all(isinstance(v, list) for v in lists):
|
|
529
|
+
out.append(finding("P1", "sim-schema-invalid", SIM_REL, f"{where} needs `predicted`, `fixed`, `missed` lists.",
|
|
530
|
+
"Record predictions before evaluation and both outcome lists after it."))
|
|
531
|
+
return out
|
|
532
|
+
pred, fixed, missed = lists
|
|
533
|
+
if set(fixed) & set(missed) or [p for p in pred if p not in fixed and p not in missed]:
|
|
534
|
+
out.append(finding("P1", "sim-prediction-mismatch", SIM_REL, f"{where} drops or double-counts a prediction.",
|
|
535
|
+
"Keep each predicted task in exactly one of `fixed` or `missed`, unresolved ones included."))
|
|
536
|
+
if not att.get("backfilled"):
|
|
537
|
+
sha = str(att.get("proposal_sha256") or "")
|
|
538
|
+
if not SHA256_RE.fullmatch(sha) or sha != attempt_digest(att):
|
|
539
|
+
out.append(finding("P1", "sim-proposal-digest-invalid", SIM_REL,
|
|
540
|
+
f"{where} does not match its pre-evaluation proposal digest.",
|
|
541
|
+
"Stage with `sim.py propose` before evaluating, then `sim.py record`; never hand-edit attempts."))
|
|
542
|
+
return out
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def validate_store(data: dict) -> list[dict]:
|
|
546
|
+
out: list[dict] = []
|
|
547
|
+
if not _int_field(data.get("next_id")) or data["next_id"] < 1:
|
|
548
|
+
out.append(finding("P0", "sim-schema-invalid", SIM_REL, "`next_id` must be a positive integer.", "Run `sim.py init`."))
|
|
549
|
+
if not isinstance(data.get("aliases"), dict):
|
|
550
|
+
out.append(finding("P0", "sim-schema-invalid", SIM_REL, "`aliases` must be an object.", "Set `aliases` to `{}`."))
|
|
551
|
+
problems = data.get("problems")
|
|
552
|
+
if not isinstance(problems, list):
|
|
553
|
+
return out + [finding("P0", "sim-schema-invalid", SIM_REL, "`problems` must be a list.", "Restore the SIM store.")]
|
|
554
|
+
carried_mode = str((data.get("carried_from") or {}).get("mode") or "")
|
|
555
|
+
seen_ids, seen_causes, max_num = set(), {}, 0
|
|
556
|
+
for idx, prob in enumerate(problems):
|
|
557
|
+
pid = str(prob.get("id") or "") if isinstance(prob, dict) else ""
|
|
558
|
+
m = PROBLEM_ID_RE.match(pid)
|
|
559
|
+
if not m or pid in seen_ids:
|
|
560
|
+
out.append(finding("P0", "sim-schema-invalid", SIM_REL, f"problems[{idx}] has an invalid or duplicate id {pid!r}.",
|
|
561
|
+
"Use unique ids P1, P2, ..."))
|
|
562
|
+
continue
|
|
563
|
+
seen_ids.add(pid)
|
|
564
|
+
max_num = max(max_num, int(m.group(1)))
|
|
565
|
+
cause = normalize_cause(prob.get("name"))
|
|
566
|
+
if len(cause) < 8:
|
|
567
|
+
out.append(finding("P1", "sim-schema-invalid", SIM_REL, f"{pid} needs a specific root-cause `name`.",
|
|
568
|
+
"Name the recurring harness problem (8+ characters)."))
|
|
569
|
+
elif cause in seen_causes:
|
|
570
|
+
out.append(finding("P1", "sim-unmerged-duplicate-cause", SIM_REL, f"{pid} repeats the root cause of {seen_causes[cause]}.",
|
|
571
|
+
"Merge entries with identical root-cause text and keep the id in `aliases`."))
|
|
572
|
+
else:
|
|
573
|
+
seen_causes[cause] = pid
|
|
574
|
+
attempts = prob.get("attempts")
|
|
575
|
+
if not isinstance(attempts, list) or (not attempts and carried_mode != "problem-only"):
|
|
576
|
+
out.append(finding("P1", "sim-schema-invalid", SIM_REL, f"{pid} has no recorded attempts.",
|
|
577
|
+
"Open a problem only by recording an accepted attempt."))
|
|
578
|
+
continue
|
|
579
|
+
for a_idx, att in enumerate(attempts):
|
|
580
|
+
out.extend(_validate_attempt(pid, a_idx, att, carried_mode))
|
|
581
|
+
if _int_field(data.get("next_id")) and max_num >= data["next_id"]:
|
|
582
|
+
out.append(finding("P1", "sim-schema-invalid", SIM_REL, f"`next_id` must exceed P{max_num}.", f"Set it to {max_num + 1}."))
|
|
583
|
+
return out
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _attempt_key(att: dict) -> str:
|
|
587
|
+
return json.dumps(att, sort_keys=True, ensure_ascii=False)
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def compare_with_base(base: dict, cur: dict) -> tuple[list[dict], list[dict]]:
|
|
591
|
+
"""Committed attempts are immutable; new attempts are whatever the current store adds on top of them."""
|
|
592
|
+
out: list[dict] = []
|
|
593
|
+
if _int_field(base.get("next_id")) and _int_field(cur.get("next_id")) and cur["next_id"] < base["next_id"]:
|
|
594
|
+
out.append(finding("P0", "sim-history-tamper", SIM_REL, "`next_id` went backwards.", "Keep `next_id` monotonic."))
|
|
595
|
+
aliases = cur.get("aliases") if isinstance(cur.get("aliases"), dict) else {}
|
|
596
|
+
cur_by_id = {str(p.get("id")): p for p in cur.get("problems") or [] if isinstance(p, dict)}
|
|
597
|
+
expected: dict[str, list[str]] = {}
|
|
598
|
+
for bprob in base.get("problems") or []:
|
|
599
|
+
if not isinstance(bprob, dict):
|
|
600
|
+
continue
|
|
601
|
+
target = resolve_alias(aliases, str(bprob.get("id")))
|
|
602
|
+
if target not in cur_by_id:
|
|
603
|
+
out.append(finding("P0", "sim-history-tamper", SIM_REL, f"Committed problem {bprob.get('id')} was removed.",
|
|
604
|
+
"SIM is append-only; merge duplicates through `aliases` instead of deleting."))
|
|
605
|
+
continue
|
|
606
|
+
expected.setdefault(target, []).extend(_attempt_key(a) for a in bprob.get("attempts") or [] if isinstance(a, dict))
|
|
607
|
+
new_attempts: list[dict] = []
|
|
608
|
+
for pid, prob in cur_by_id.items():
|
|
609
|
+
pending = list(expected.get(pid, []))
|
|
610
|
+
for att in prob.get("attempts") or []:
|
|
611
|
+
if not isinstance(att, dict):
|
|
612
|
+
continue
|
|
613
|
+
key = _attempt_key(att)
|
|
614
|
+
if key in pending:
|
|
615
|
+
pending.remove(key)
|
|
616
|
+
else:
|
|
617
|
+
new_attempts.append(att)
|
|
618
|
+
if pending:
|
|
619
|
+
out.append(finding("P0", "sim-history-tamper", SIM_REL, f"Committed attempts under {pid} were deleted or rewritten.",
|
|
620
|
+
"Restore them; record a new attempt to revise, replace, or remove an edit."))
|
|
621
|
+
return out, new_attempts
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def _base_store(root: Path, base_ref: str | None) -> dict | None:
|
|
625
|
+
ref = base_ref or "HEAD"
|
|
626
|
+
if _git(root, "rev-parse", "--verify", ref).returncode != 0:
|
|
627
|
+
return None
|
|
628
|
+
blob = _git(root, "show", f"{ref}:{SIM_REL}")
|
|
629
|
+
if blob.returncode != 0:
|
|
630
|
+
return None
|
|
631
|
+
try:
|
|
632
|
+
parsed = json.loads(blob.stdout)
|
|
633
|
+
except ValueError:
|
|
634
|
+
return None
|
|
635
|
+
return parsed if isinstance(parsed, dict) else None
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _current_text(root: Path, staged: bool) -> str | None:
|
|
639
|
+
if staged:
|
|
640
|
+
idx = _git(root, "show", f":{SIM_REL}")
|
|
641
|
+
return idx.stdout if idx.returncode == 0 else None
|
|
642
|
+
store = root / SIM_REL
|
|
643
|
+
return store.read_text(encoding="utf-8") if store.is_file() and not store.is_symlink() else None
|
|
644
|
+
|
|
645
|
+
|
|
646
|
+
def pack(harness: list[str], findings: list[dict], enforced: bool = True) -> dict:
|
|
647
|
+
counts = {"P0": 0, "P1": 0, "P2": 0}
|
|
648
|
+
for item in findings:
|
|
649
|
+
counts[item["severity"]] += 1
|
|
650
|
+
return {"ok": counts["P0"] == 0 and counts["P1"] == 0, "enforced": enforced, "sim_file": SIM_REL,
|
|
651
|
+
"harness_files_changed": harness, "counts": counts, "findings": findings}
|
|
652
|
+
|
|
653
|
+
|
|
654
|
+
def check_repo(root: Path, *, changed: list[str] | None = None, staged: bool = False, base_ref: str | None = None,
|
|
655
|
+
base_data=_UNSET) -> dict:
|
|
656
|
+
root = Path(root).resolve()
|
|
657
|
+
cfg = policy_config(root)
|
|
658
|
+
base = _base_store(root, base_ref) if base_data is _UNSET else base_data
|
|
659
|
+
if not (sim_enforced(root) or base is not None):
|
|
660
|
+
return pack([], [], enforced=False)
|
|
661
|
+
if (root / SIM_REL).is_symlink():
|
|
662
|
+
return pack([], [finding("P0", "sim-schema-invalid", SIM_REL, "SIM store must not be a symlink.", "Use a regular file.")])
|
|
663
|
+
text = _current_text(root, staged)
|
|
664
|
+
if text is None:
|
|
665
|
+
rule, sev = ("sim-history-tamper", "P0") if base is not None else ("sim-missing-store", "P1")
|
|
666
|
+
return pack([], [finding(sev, rule, SIM_REL, f"`{SIM_REL}` is missing.", "Run `sim.py init` and record harness edits.")])
|
|
667
|
+
try:
|
|
668
|
+
cur = json.loads(text)
|
|
669
|
+
if not isinstance(cur, dict):
|
|
670
|
+
raise ValueError("root must be an object")
|
|
671
|
+
except ValueError as exc:
|
|
672
|
+
return pack([], [finding("P0", "sim-schema-invalid", SIM_REL, f"Invalid JSON: {exc}", "Restore the store from git.")])
|
|
673
|
+
findings = validate_store(cur)
|
|
674
|
+
if base is not None:
|
|
675
|
+
history, new_attempts = compare_with_base(base, cur)
|
|
676
|
+
findings.extend(history)
|
|
677
|
+
else:
|
|
678
|
+
new_attempts = [a for p in cur.get("problems") or [] if isinstance(p, dict)
|
|
679
|
+
for a in p.get("attempts") or [] if isinstance(a, dict)]
|
|
680
|
+
files = changed if changed is not None else changed_files(root, staged=staged, base_ref=base_ref)
|
|
681
|
+
harness = [f for f in (norm_rel(x) for x in files) if is_harness_file(f, cfg["include"], cfg["exclude"])]
|
|
682
|
+
covered = {f for f in harness for att in new_attempts
|
|
683
|
+
if any(f == norm_rel(p) or fnmatch.fnmatch(f, norm_rel(p)) for p in att.get("files") or [])}
|
|
684
|
+
uncovered = [f for f in harness if f not in covered] if base is not None else []
|
|
685
|
+
if uncovered:
|
|
686
|
+
findings.append(finding(
|
|
687
|
+
"P1", "sim-missing-update", uncovered[0],
|
|
688
|
+
f"Harness edit not recorded in SIM ({len(uncovered)} file(s): {', '.join(uncovered[:5])}).",
|
|
689
|
+
"Run `sim.py read`, `sim.py propose` before evaluating, then `sim.py record` with the evolve-set outcome."))
|
|
690
|
+
if not staged:
|
|
691
|
+
for pf in (scratch_dir(root) / "proposals").glob("*.json"):
|
|
692
|
+
try:
|
|
693
|
+
split = str(json.loads(pf.read_text(encoding="utf-8")).get("split") or "evolve").strip().lower()
|
|
694
|
+
except (OSError, ValueError):
|
|
695
|
+
continue
|
|
696
|
+
if split != "evolve":
|
|
697
|
+
findings.append(finding("P0", "sim-holdout-leakage", f".scratch/sim/proposals/{pf.name}",
|
|
698
|
+
f"Staged proposal uses split {split!r}.", "Delete it and stage from evolve-set feedback."))
|
|
699
|
+
return pack(harness, findings)
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def loop_gate(root: Path, *, base_data, ignore: set[str], since_epoch: float, check_passed: bool, accepted: bool) -> tuple[bool, str]:
|
|
703
|
+
"""loop.py hook: record proposals staged this iteration, then require SIM coverage for this run's harness edits."""
|
|
704
|
+
root = Path(root).resolve()
|
|
705
|
+
notes: list[str] = []
|
|
706
|
+
for path in staged_proposals(root, since_epoch):
|
|
707
|
+
try:
|
|
708
|
+
prop = json.loads(path.read_text(encoding="utf-8"))
|
|
709
|
+
res = record_outcome(root, proposal_id=prop["proposal_id"], accepted=accepted, passed=1 if check_passed else 0,
|
|
710
|
+
total=1, fixed=prop["predicted"] if check_passed else [],
|
|
711
|
+
missed=[] if check_passed else prop["predicted"])
|
|
712
|
+
except (OSError, ValueError, KeyError) as exc:
|
|
713
|
+
notes.append(f"[sim_guard] could not record {path.name}: {exc}")
|
|
714
|
+
continue
|
|
715
|
+
notes.append(f"[sim] recorded {res['proposal_id']} into {res['problem_id']}" if res["accepted"]
|
|
716
|
+
else f"[sim] {res['proposal_id']} rejected (failed iteration reverted)")
|
|
717
|
+
changed = [f for f in changed_files(root) if f not in ignore]
|
|
718
|
+
res = check_repo(root, changed=changed, base_data=base_data)
|
|
719
|
+
for item in res["findings"]:
|
|
720
|
+
notes.append(f"[sim_guard failed] {item['file']} [{item['severity']}:{item['rule']}] {item['message']} -> {item['fix']}")
|
|
721
|
+
return res["ok"], "\n".join(notes)
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def status(root: Path) -> dict:
|
|
725
|
+
store = sim_store_path(root)
|
|
726
|
+
if not store.is_file():
|
|
727
|
+
return {"exists": False, "path": str(store), "problems": 0, "attempts": 0, "enforced": sim_enforced(root)}
|
|
728
|
+
data, sha = load_store(store)
|
|
729
|
+
problems = [p for p in data.get("problems") or [] if isinstance(p, dict)]
|
|
730
|
+
return {"exists": True, "path": str(store), "sha256": sha, "enforced": True, "next_id": data.get("next_id"),
|
|
731
|
+
"problems": len(problems), "attempts": sum(len(p.get("attempts") or []) for p in problems),
|
|
732
|
+
"carried_from": data.get("carried_from"), "read_receipt_fresh": read_receipt_fresh(root, sha)}
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
736
|
+
p = argparse.ArgumentParser(description="Self-Improvement Memory (SIM) for harness optimization (arXiv:2611.18856).")
|
|
737
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
738
|
+
s = sub.add_parser("init")
|
|
739
|
+
s.add_argument("--root", default=".")
|
|
740
|
+
s.add_argument("--force", action="store_true")
|
|
741
|
+
s.add_argument("--json", action="store_true")
|
|
742
|
+
s = sub.add_parser("read")
|
|
743
|
+
s.add_argument("--root", default=".")
|
|
744
|
+
s.add_argument("--role", choices=("proposer", "selector"), default="proposer")
|
|
745
|
+
s.add_argument("--format", choices=("prompt", "json", "markdown"), default="prompt")
|
|
746
|
+
s = sub.add_parser("propose")
|
|
747
|
+
s.add_argument("--root", default=".")
|
|
748
|
+
s.add_argument("--problem")
|
|
749
|
+
s.add_argument("--root-cause")
|
|
750
|
+
s.add_argument("--what", required=True)
|
|
751
|
+
s.add_argument("--files", nargs="+", required=True)
|
|
752
|
+
s.add_argument("--predicted", nargs="*", default=[])
|
|
753
|
+
s.add_argument("--domain", required=True)
|
|
754
|
+
s.add_argument("--benchmark", default="")
|
|
755
|
+
s.add_argument("--policy", required=True)
|
|
756
|
+
s.add_argument("--round", dest="round_num", type=int, default=1)
|
|
757
|
+
s.add_argument("--sample", default="s1")
|
|
758
|
+
s.add_argument("--split", default="evolve")
|
|
759
|
+
s.add_argument("--proposal-id")
|
|
760
|
+
s.add_argument("--json", action="store_true")
|
|
761
|
+
s = sub.add_parser("record")
|
|
762
|
+
s.add_argument("--root", default=".")
|
|
763
|
+
s.add_argument("--proposal")
|
|
764
|
+
group = s.add_mutually_exclusive_group()
|
|
765
|
+
group.add_argument("--accepted", dest="accepted", action="store_true", default=True)
|
|
766
|
+
group.add_argument("--no-accepted", dest="accepted", action="store_false")
|
|
767
|
+
s.add_argument("--fixed", nargs="*")
|
|
768
|
+
s.add_argument("--missed", nargs="*")
|
|
769
|
+
s.add_argument("--passed", type=int)
|
|
770
|
+
s.add_argument("--total", type=int)
|
|
771
|
+
s.add_argument("--check-cmd")
|
|
772
|
+
s.add_argument("--timeout", type=int, default=300)
|
|
773
|
+
s.add_argument("--json", action="store_true")
|
|
774
|
+
s = sub.add_parser("transfer")
|
|
775
|
+
s.add_argument("--from", dest="source", required=True)
|
|
776
|
+
s.add_argument("--root", default=".")
|
|
777
|
+
s.add_argument("--to", dest="dest")
|
|
778
|
+
s.add_argument("--into", required=True)
|
|
779
|
+
s.add_argument("--source-arm", default="")
|
|
780
|
+
s.add_argument("--domain", required=True)
|
|
781
|
+
s.add_argument("--benchmark", default="")
|
|
782
|
+
s.add_argument("--policy", default="")
|
|
783
|
+
s.add_argument("--mode", choices=TRANSFER_MODES, default="full")
|
|
784
|
+
s.add_argument("--json", action="store_true")
|
|
785
|
+
s = sub.add_parser("status")
|
|
786
|
+
s.add_argument("--root", default=".")
|
|
787
|
+
s.add_argument("--json", action="store_true")
|
|
788
|
+
s = sub.add_parser("check")
|
|
789
|
+
s.add_argument("--root", default=".")
|
|
790
|
+
s.add_argument("--base")
|
|
791
|
+
s.add_argument("--staged", action="store_true")
|
|
792
|
+
s.add_argument("--files", nargs="*")
|
|
793
|
+
s.add_argument("--advisory", action="store_true")
|
|
794
|
+
s.add_argument("--json", action="store_true")
|
|
795
|
+
return p
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def _print(obj: dict, as_json: bool, text: str) -> None:
|
|
799
|
+
print(json.dumps(obj, indent=2, ensure_ascii=False) if as_json else text)
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def main(argv: list[str] | None = None) -> int:
|
|
803
|
+
raw = list(sys.argv[1:] if argv is None else argv)
|
|
804
|
+
if not raw or raw[0].startswith("--") and raw[0] != "--help":
|
|
805
|
+
raw = ["check", *raw]
|
|
806
|
+
args = build_parser().parse_args(raw)
|
|
807
|
+
try:
|
|
808
|
+
if args.cmd == "init":
|
|
809
|
+
res = init_store(Path(args.root), force=args.force)
|
|
810
|
+
_print(res, args.json, f"sim init: {res['path']} ({'created' if res['created'] else 'exists'})")
|
|
811
|
+
elif args.cmd == "read":
|
|
812
|
+
root = Path(args.root).resolve()
|
|
813
|
+
data, sha = load_or_empty(root)
|
|
814
|
+
stamp_read_receipt(root, sha, args.role)
|
|
815
|
+
print(json.dumps(data, indent=2, ensure_ascii=False) if args.format == "json"
|
|
816
|
+
else render_markdown(data) if args.format == "markdown" else render_prompt(data, args.role))
|
|
817
|
+
elif args.cmd == "propose":
|
|
818
|
+
rec = stage_proposal(Path(args.root), problem_id=args.problem, root_cause=args.root_cause, what=args.what,
|
|
819
|
+
files=split_csv(args.files), predicted=split_csv(args.predicted), domain=args.domain,
|
|
820
|
+
benchmark=args.benchmark, policy=args.policy, round_num=args.round_num,
|
|
821
|
+
sample=args.sample, split=args.split, proposal_id=args.proposal_id)
|
|
822
|
+
_print(rec, args.json, f"sim propose: {rec['proposal_id']} ({rec['problem_id'] or 'new problem'}, "
|
|
823
|
+
f"{len(rec['predicted'])} predicted)")
|
|
824
|
+
elif args.cmd == "record":
|
|
825
|
+
res = record_outcome(Path(args.root), proposal_id=args.proposal, accepted=args.accepted,
|
|
826
|
+
fixed=split_csv(args.fixed) if args.fixed is not None else None,
|
|
827
|
+
missed=split_csv(args.missed) if args.missed is not None else None,
|
|
828
|
+
passed=args.passed, total=args.total, check_cmd=args.check_cmd, timeout_sec=args.timeout)
|
|
829
|
+
_print(res, args.json, f"sim record: {res['proposal_id']} " +
|
|
830
|
+
(f"-> {res['problem_id']}" if res["accepted"] else "rejected; SIM unchanged"))
|
|
831
|
+
elif args.cmd == "transfer":
|
|
832
|
+
dest = Path(args.dest) if args.dest else sim_store_path(Path(args.root))
|
|
833
|
+
res = transfer(Path(args.source), dest, into=args.into, domain=args.domain, benchmark=args.benchmark,
|
|
834
|
+
policy=args.policy, source_arm=args.source_arm, mode=args.mode)
|
|
835
|
+
_print(res, args.json, f"sim transfer ({res['mode']}): {res['dest']} ({res['problems']} problems)")
|
|
836
|
+
elif args.cmd == "status":
|
|
837
|
+
st = status(Path(args.root))
|
|
838
|
+
_print(st, args.json, f"sim status: exists={st['exists']} enforced={st['enforced']} "
|
|
839
|
+
f"problems={st['problems']} attempts={st['attempts']}")
|
|
840
|
+
else:
|
|
841
|
+
res = check_repo(Path(args.root), changed=split_csv(args.files) if args.files is not None else None,
|
|
842
|
+
staged=args.staged, base_ref=args.base)
|
|
843
|
+
c = res["counts"]
|
|
844
|
+
lines = [f"sim-gate [{'OK' if res['ok'] else 'BLOCKED'}]: enforced={res['enforced']} "
|
|
845
|
+
f"harness_files={len(res['harness_files_changed'])} P0:{c['P0']} P1:{c['P1']} P2:{c['P2']}"]
|
|
846
|
+
lines += [f" {f['file']}:{f['line']} [{f['severity']}:{f['rule']}] {f['message']} -> {f['fix']}" for f in res["findings"]]
|
|
847
|
+
_print(res, args.json, "\n".join(lines))
|
|
848
|
+
return 0 if res["ok"] or args.advisory else 1
|
|
849
|
+
except (ValueError, OSError) as exc:
|
|
850
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
851
|
+
return 2
|
|
852
|
+
return 0
|
|
853
|
+
|
|
854
|
+
|
|
855
|
+
if __name__ == "__main__":
|
|
856
|
+
raise SystemExit(main())
|