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,969 @@
|
|
|
1
|
+
//! Self-Improvement Memory gate (arXiv:2611.18856), the native twin of `assets/sim/sim.py check`.
|
|
2
|
+
//! Same activation, rules, digests and findings as the Python gate; `test_sim.py` runs both on the same repos.
|
|
3
|
+
|
|
4
|
+
use crate::slop::Finding;
|
|
5
|
+
use crate::util::{json_escape, sha256_hex};
|
|
6
|
+
use std::collections::BTreeMap;
|
|
7
|
+
use std::fs;
|
|
8
|
+
use std::path::{Path, PathBuf};
|
|
9
|
+
use std::process::{Command, ExitCode};
|
|
10
|
+
|
|
11
|
+
pub const SIM_REL: &str = ".deepmodebot/sim.json";
|
|
12
|
+
|
|
13
|
+
const SKIP_SEGMENTS: &[&str] = &[".git", ".scratch", ".worktrees", "node_modules", "__pycache__"];
|
|
14
|
+
const HARNESS_NAMES: &[&str] = &[
|
|
15
|
+
"agents.md", "agents.override.md", "agents.local.md", "agent.md", "claude.md", "claude.local.md", "gemini.md",
|
|
16
|
+
".cursorrules", ".windsurfrules", ".clinerules", ".roorules", ".rules",
|
|
17
|
+
];
|
|
18
|
+
const HARNESS_FILES: &[&str] = &[".github/copilot-instructions.md", ".deepmodebot/policy.xml", ".deepmodebot/ci.yml"];
|
|
19
|
+
const HARNESS_DIRS: &[&str] = &[
|
|
20
|
+
".omp/", ".claude/", ".agents/", ".agent/", ".codex/", ".gemini/", ".cursor/rules/", ".windsurf/rules/",
|
|
21
|
+
".devin/", ".roo/rules/", ".kiro/steering/", ".continue/rules/", ".amazonq/rules/", ".github/instructions/",
|
|
22
|
+
];
|
|
23
|
+
const FIX_INIT: &str = "Run `sim.py init` and record harness edits.";
|
|
24
|
+
const FIX_RECORD: &str = "Run `sim.py read`, `sim.py propose` before evaluating, then `sim.py record` with the evolve-set outcome.";
|
|
25
|
+
|
|
26
|
+
#[derive(Clone, Debug, PartialEq)]
|
|
27
|
+
pub enum Json {
|
|
28
|
+
Null,
|
|
29
|
+
Bool(bool),
|
|
30
|
+
Int(i64),
|
|
31
|
+
Float(f64),
|
|
32
|
+
Str(String),
|
|
33
|
+
Arr(Vec<Json>),
|
|
34
|
+
Obj(BTreeMap<String, Json>),
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
impl Json {
|
|
38
|
+
fn get(&self, key: &str) -> Option<&Json> {
|
|
39
|
+
match self {
|
|
40
|
+
Json::Obj(map) => map.get(key),
|
|
41
|
+
_ => None,
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
fn as_arr(&self) -> Option<&Vec<Json>> {
|
|
45
|
+
match self {
|
|
46
|
+
Json::Arr(items) => Some(items),
|
|
47
|
+
_ => None,
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
fn as_int(&self) -> Option<i64> {
|
|
51
|
+
match self {
|
|
52
|
+
Json::Int(n) => Some(*n),
|
|
53
|
+
_ => None,
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
fn truthy(&self) -> bool {
|
|
57
|
+
match self {
|
|
58
|
+
Json::Null => false,
|
|
59
|
+
Json::Bool(b) => *b,
|
|
60
|
+
Json::Int(n) => *n != 0,
|
|
61
|
+
Json::Float(f) => *f != 0.0,
|
|
62
|
+
Json::Str(s) => !s.is_empty(),
|
|
63
|
+
Json::Arr(a) => !a.is_empty(),
|
|
64
|
+
Json::Obj(o) => !o.is_empty(),
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/// Python `str(value)` for the scalars SIM stores.
|
|
70
|
+
fn py_str(value: &Json) -> String {
|
|
71
|
+
match value {
|
|
72
|
+
Json::Null => "None".to_string(),
|
|
73
|
+
Json::Bool(true) => "True".to_string(),
|
|
74
|
+
Json::Bool(false) => "False".to_string(),
|
|
75
|
+
Json::Int(n) => n.to_string(),
|
|
76
|
+
Json::Float(f) => format!("{:?}", f),
|
|
77
|
+
Json::Str(s) => s.clone(),
|
|
78
|
+
other => serialize(other),
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/// Python `str(value or "")`.
|
|
83
|
+
fn py_text(value: Option<&Json>) -> String {
|
|
84
|
+
match value {
|
|
85
|
+
Some(v) if v.truthy() => py_str(v),
|
|
86
|
+
_ => String::new(),
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/// Python `str(att.get(key, default))`: a missing key gives the default, an explicit null gives "None".
|
|
91
|
+
fn py_get(obj: &Json, key: &str, default: &str) -> String {
|
|
92
|
+
obj.get(key).map(py_str).unwrap_or_else(|| default.to_string())
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
struct Parser {
|
|
96
|
+
chars: Vec<char>,
|
|
97
|
+
pos: usize,
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
pub fn parse_json(src: &str) -> Result<Json, String> {
|
|
101
|
+
let mut p = Parser { chars: src.chars().collect(), pos: 0 };
|
|
102
|
+
p.ws();
|
|
103
|
+
let value = p.value()?;
|
|
104
|
+
p.ws();
|
|
105
|
+
if p.pos != p.chars.len() {
|
|
106
|
+
return Err(format!("trailing data at char {}", p.pos));
|
|
107
|
+
}
|
|
108
|
+
Ok(value)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
impl Parser {
|
|
112
|
+
fn peek(&self) -> Option<char> {
|
|
113
|
+
self.chars.get(self.pos).copied()
|
|
114
|
+
}
|
|
115
|
+
fn ws(&mut self) {
|
|
116
|
+
while matches!(self.peek(), Some(' ' | '\t' | '\n' | '\r')) {
|
|
117
|
+
self.pos += 1;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
fn expect(&mut self, c: char) -> Result<(), String> {
|
|
121
|
+
if self.peek() == Some(c) {
|
|
122
|
+
self.pos += 1;
|
|
123
|
+
Ok(())
|
|
124
|
+
} else {
|
|
125
|
+
Err(format!("expected {:?} at char {}", c, self.pos))
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
fn literal(&mut self, word: &str, value: Json) -> Result<Json, String> {
|
|
129
|
+
for c in word.chars() {
|
|
130
|
+
self.expect(c)?;
|
|
131
|
+
}
|
|
132
|
+
Ok(value)
|
|
133
|
+
}
|
|
134
|
+
fn value(&mut self) -> Result<Json, String> {
|
|
135
|
+
match self.peek() {
|
|
136
|
+
Some('{') => self.object(),
|
|
137
|
+
Some('[') => self.array(),
|
|
138
|
+
Some('"') => self.string().map(Json::Str),
|
|
139
|
+
Some('t') => self.literal("true", Json::Bool(true)),
|
|
140
|
+
Some('f') => self.literal("false", Json::Bool(false)),
|
|
141
|
+
Some('n') => self.literal("null", Json::Null),
|
|
142
|
+
Some(c) if c == '-' || c.is_ascii_digit() => self.number(),
|
|
143
|
+
_ => Err(format!("unexpected input at char {}", self.pos)),
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
fn object(&mut self) -> Result<Json, String> {
|
|
147
|
+
self.expect('{')?;
|
|
148
|
+
let mut map = BTreeMap::new();
|
|
149
|
+
self.ws();
|
|
150
|
+
if self.peek() == Some('}') {
|
|
151
|
+
self.pos += 1;
|
|
152
|
+
return Ok(Json::Obj(map));
|
|
153
|
+
}
|
|
154
|
+
loop {
|
|
155
|
+
self.ws();
|
|
156
|
+
let key = self.string()?;
|
|
157
|
+
self.ws();
|
|
158
|
+
self.expect(':')?;
|
|
159
|
+
self.ws();
|
|
160
|
+
let value = self.value()?;
|
|
161
|
+
map.insert(key, value);
|
|
162
|
+
self.ws();
|
|
163
|
+
match self.peek() {
|
|
164
|
+
Some(',') => self.pos += 1,
|
|
165
|
+
Some('}') => {
|
|
166
|
+
self.pos += 1;
|
|
167
|
+
return Ok(Json::Obj(map));
|
|
168
|
+
}
|
|
169
|
+
_ => return Err(format!("expected ',' or '}}' at char {}", self.pos)),
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
fn array(&mut self) -> Result<Json, String> {
|
|
174
|
+
self.expect('[')?;
|
|
175
|
+
let mut items = Vec::new();
|
|
176
|
+
self.ws();
|
|
177
|
+
if self.peek() == Some(']') {
|
|
178
|
+
self.pos += 1;
|
|
179
|
+
return Ok(Json::Arr(items));
|
|
180
|
+
}
|
|
181
|
+
loop {
|
|
182
|
+
self.ws();
|
|
183
|
+
items.push(self.value()?);
|
|
184
|
+
self.ws();
|
|
185
|
+
match self.peek() {
|
|
186
|
+
Some(',') => self.pos += 1,
|
|
187
|
+
Some(']') => {
|
|
188
|
+
self.pos += 1;
|
|
189
|
+
return Ok(Json::Arr(items));
|
|
190
|
+
}
|
|
191
|
+
_ => return Err(format!("expected ',' or ']' at char {}", self.pos)),
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
fn hex4(&mut self) -> Result<u32, String> {
|
|
196
|
+
let mut n = 0u32;
|
|
197
|
+
for _ in 0..4 {
|
|
198
|
+
let c = self.peek().ok_or("truncated \\u escape")?;
|
|
199
|
+
n = n * 16 + c.to_digit(16).ok_or("bad \\u escape")?;
|
|
200
|
+
self.pos += 1;
|
|
201
|
+
}
|
|
202
|
+
Ok(n)
|
|
203
|
+
}
|
|
204
|
+
fn string(&mut self) -> Result<String, String> {
|
|
205
|
+
self.expect('"')?;
|
|
206
|
+
let mut out = String::new();
|
|
207
|
+
loop {
|
|
208
|
+
let c = self.peek().ok_or("unterminated string")?;
|
|
209
|
+
self.pos += 1;
|
|
210
|
+
match c {
|
|
211
|
+
'"' => return Ok(out),
|
|
212
|
+
'\\' => {
|
|
213
|
+
let e = self.peek().ok_or("unterminated escape")?;
|
|
214
|
+
self.pos += 1;
|
|
215
|
+
match e {
|
|
216
|
+
'"' => out.push('"'),
|
|
217
|
+
'\\' => out.push('\\'),
|
|
218
|
+
'/' => out.push('/'),
|
|
219
|
+
'b' => out.push('\u{8}'),
|
|
220
|
+
'f' => out.push('\u{c}'),
|
|
221
|
+
'n' => out.push('\n'),
|
|
222
|
+
'r' => out.push('\r'),
|
|
223
|
+
't' => out.push('\t'),
|
|
224
|
+
'u' => {
|
|
225
|
+
let hi = self.hex4()?;
|
|
226
|
+
let code = if (0xD800..0xDC00).contains(&hi)
|
|
227
|
+
&& self.peek() == Some('\\')
|
|
228
|
+
&& self.chars.get(self.pos + 1) == Some(&'u')
|
|
229
|
+
{
|
|
230
|
+
self.pos += 2;
|
|
231
|
+
let lo = self.hex4()?;
|
|
232
|
+
0x10000 + ((hi - 0xD800) << 10) + (lo.wrapping_sub(0xDC00) & 0x3FF)
|
|
233
|
+
} else {
|
|
234
|
+
hi
|
|
235
|
+
};
|
|
236
|
+
out.push(char::from_u32(code).unwrap_or('\u{FFFD}'));
|
|
237
|
+
}
|
|
238
|
+
_ => return Err(format!("bad escape at char {}", self.pos)),
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
c => out.push(c),
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
fn number(&mut self) -> Result<Json, String> {
|
|
246
|
+
let start = self.pos;
|
|
247
|
+
while matches!(self.peek(), Some(c) if c == '-' || c == '+' || c == '.' || c == 'e' || c == 'E' || c.is_ascii_digit()) {
|
|
248
|
+
self.pos += 1;
|
|
249
|
+
}
|
|
250
|
+
let text: String = self.chars[start..self.pos].iter().collect();
|
|
251
|
+
if !text.contains(['.', 'e', 'E']) {
|
|
252
|
+
if let Ok(n) = text.parse::<i64>() {
|
|
253
|
+
return Ok(Json::Int(n));
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
text.parse::<f64>().map(Json::Float).map_err(|_| format!("bad number {:?}", text))
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
fn serialize(value: &Json) -> String {
|
|
261
|
+
match value {
|
|
262
|
+
Json::Null => "null".to_string(),
|
|
263
|
+
Json::Bool(b) => b.to_string(),
|
|
264
|
+
Json::Int(n) => n.to_string(),
|
|
265
|
+
Json::Float(f) => format!("{:?}", f),
|
|
266
|
+
Json::Str(s) => json_escape(s),
|
|
267
|
+
Json::Arr(items) => format!("[{}]", items.iter().map(serialize).collect::<Vec<_>>().join(",")),
|
|
268
|
+
Json::Obj(map) => format!(
|
|
269
|
+
"{{{}}}",
|
|
270
|
+
map.iter().map(|(k, v)| format!("{}:{}", json_escape(k), serialize(v))).collect::<Vec<_>>().join(",")
|
|
271
|
+
),
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
pub fn norm_rel(raw: &str) -> String {
|
|
276
|
+
let mut s = raw.trim().replace('\\', "/");
|
|
277
|
+
while let Some(rest) = s.strip_prefix("./") {
|
|
278
|
+
s = rest.to_string();
|
|
279
|
+
}
|
|
280
|
+
s.trim_start_matches('/').to_string()
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
fn normalize_ws(text: &str) -> String {
|
|
284
|
+
text.split_whitespace().collect::<Vec<_>>().join(" ")
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
fn normalize_cause(text: &str) -> String {
|
|
288
|
+
normalize_ws(text).to_lowercase()
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/// Python `fnmatch.fnmatchcase`: `*` crosses `/`, `?` is one char, `[...]` and `[!...]` are char sets.
|
|
292
|
+
pub fn fnmatch(name: &str, pat: &str) -> bool {
|
|
293
|
+
fn set_match(pat: &[char], mut i: usize, c: char) -> Option<(bool, usize)> {
|
|
294
|
+
let negate = matches!(pat.get(i), Some('!'));
|
|
295
|
+
if negate {
|
|
296
|
+
i += 1;
|
|
297
|
+
}
|
|
298
|
+
let start = i;
|
|
299
|
+
let mut hit = false;
|
|
300
|
+
while i < pat.len() && (pat[i] != ']' || i == start) {
|
|
301
|
+
if i + 2 < pat.len() && pat[i + 1] == '-' && pat[i + 2] != ']' {
|
|
302
|
+
hit |= pat[i] <= c && c <= pat[i + 2];
|
|
303
|
+
i += 3;
|
|
304
|
+
} else {
|
|
305
|
+
hit |= pat[i] == c;
|
|
306
|
+
i += 1;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if i >= pat.len() {
|
|
310
|
+
return None;
|
|
311
|
+
}
|
|
312
|
+
Some((hit != negate, i + 1))
|
|
313
|
+
}
|
|
314
|
+
fn rec(n: &[char], p: &[char]) -> bool {
|
|
315
|
+
let (mut ni, mut pi) = (0, 0);
|
|
316
|
+
let (mut star_p, mut star_n) = (usize::MAX, 0);
|
|
317
|
+
while ni < n.len() {
|
|
318
|
+
let step = match p.get(pi) {
|
|
319
|
+
Some('*') => {
|
|
320
|
+
star_p = pi;
|
|
321
|
+
star_n = ni;
|
|
322
|
+
pi += 1;
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
Some('?') => Some(pi + 1),
|
|
326
|
+
Some('[') => match set_match(p, pi + 1, n[ni]) {
|
|
327
|
+
Some((true, next)) => Some(next),
|
|
328
|
+
Some((false, _)) => None,
|
|
329
|
+
None => (n[ni] == '[').then_some(pi + 1),
|
|
330
|
+
},
|
|
331
|
+
Some(&c) => (c == n[ni]).then_some(pi + 1),
|
|
332
|
+
None => None,
|
|
333
|
+
};
|
|
334
|
+
match step {
|
|
335
|
+
Some(next) => {
|
|
336
|
+
pi = next;
|
|
337
|
+
ni += 1;
|
|
338
|
+
}
|
|
339
|
+
None if star_p != usize::MAX => {
|
|
340
|
+
pi = star_p + 1;
|
|
341
|
+
star_n += 1;
|
|
342
|
+
ni = star_n;
|
|
343
|
+
}
|
|
344
|
+
None => return false,
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
p[pi..].iter().all(|&c| c == '*')
|
|
348
|
+
}
|
|
349
|
+
rec(&name.chars().collect::<Vec<_>>(), &pat.chars().collect::<Vec<_>>())
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/// `TEST_PATH_RE` in sim.py: a tests/spec folder segment, or a `test_*.ext`, `*_test.ext`, `*.test.ext`, `*.spec.ext` file.
|
|
353
|
+
fn is_test_path(rel: &str) -> bool {
|
|
354
|
+
let low = rel.to_lowercase();
|
|
355
|
+
let parts: Vec<&str> = low.split('/').collect();
|
|
356
|
+
let (base, dirs) = parts.split_last().unwrap_or((&"", &[]));
|
|
357
|
+
if dirs.iter().any(|d| matches!(*d, "test" | "tests" | "spec" | "__tests__")) {
|
|
358
|
+
return true;
|
|
359
|
+
}
|
|
360
|
+
if let Some(rest) = base.strip_prefix("test_") {
|
|
361
|
+
if rest.char_indices().any(|(i, c)| c == '.' && i > 0 && i + 1 < rest.len()) {
|
|
362
|
+
return true;
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
["_test.", ".test.", ".spec."].iter().any(|mark| {
|
|
366
|
+
base.match_indices(mark).any(|(i, m)| i > 0 && i + m.len() < base.len())
|
|
367
|
+
})
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
pub struct PolicyConfig {
|
|
371
|
+
pub required: bool,
|
|
372
|
+
pub include: Vec<String>,
|
|
373
|
+
pub exclude: Vec<String>,
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
fn xml_attr(tag: &str, key: &str) -> Option<String> {
|
|
377
|
+
let needle = format!("{}=\"", key);
|
|
378
|
+
let mut search = 0;
|
|
379
|
+
while let Some(found) = tag[search..].find(&needle) {
|
|
380
|
+
let at = search + found;
|
|
381
|
+
let boundary = at == 0 || tag[..at].ends_with(|c: char| c.is_whitespace());
|
|
382
|
+
let start = at + needle.len();
|
|
383
|
+
if boundary {
|
|
384
|
+
return tag[start..].find('"').map(|end| tag[start..start + end].to_string());
|
|
385
|
+
}
|
|
386
|
+
search = start;
|
|
387
|
+
}
|
|
388
|
+
None
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
pub fn policy_config(root: &Path) -> PolicyConfig {
|
|
392
|
+
let mut cfg = PolicyConfig { required: false, include: Vec::new(), exclude: Vec::new() };
|
|
393
|
+
let path = root.join(".deepmodebot/policy.xml");
|
|
394
|
+
if fs::symlink_metadata(&path).map(|m| m.file_type().is_symlink()).unwrap_or(true) {
|
|
395
|
+
return cfg;
|
|
396
|
+
}
|
|
397
|
+
let Ok(xml) = fs::read_to_string(&path) else { return cfg };
|
|
398
|
+
let mut from = 0;
|
|
399
|
+
while let Some(found) = xml[from..].find("<sim") {
|
|
400
|
+
let at = from + found;
|
|
401
|
+
let after = xml[at + 4..].chars().next();
|
|
402
|
+
if matches!(after, Some(c) if c.is_whitespace() || c == '/' || c == '>') {
|
|
403
|
+
let end = xml[at..].find('>').map(|e| at + e).unwrap_or(xml.len());
|
|
404
|
+
let tag = &xml[at..end];
|
|
405
|
+
let required = xml_attr(tag, "required").unwrap_or_default().trim().to_lowercase();
|
|
406
|
+
cfg.required = matches!(required.as_str(), "true" | "1" | "yes");
|
|
407
|
+
let split = |v: Option<String>| -> Vec<String> {
|
|
408
|
+
v.unwrap_or_default().split(',').map(norm_rel).filter(|s| !s.is_empty()).collect()
|
|
409
|
+
};
|
|
410
|
+
cfg.include = split(xml_attr(tag, "paths"));
|
|
411
|
+
cfg.exclude = split(xml_attr(tag, "exclude"));
|
|
412
|
+
break;
|
|
413
|
+
}
|
|
414
|
+
from = at + 4;
|
|
415
|
+
}
|
|
416
|
+
cfg
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
pub fn is_harness_file(rel_raw: &str, include: &[String], exclude: &[String]) -> bool {
|
|
420
|
+
let rel = norm_rel(rel_raw);
|
|
421
|
+
if rel.is_empty() || rel == SIM_REL || rel.split('/').any(|s| SKIP_SEGMENTS.contains(&s)) || is_test_path(&rel) {
|
|
422
|
+
return false;
|
|
423
|
+
}
|
|
424
|
+
let low = rel.to_lowercase();
|
|
425
|
+
if exclude.iter().any(|p| fnmatch(&low, &p.to_lowercase())) {
|
|
426
|
+
return false;
|
|
427
|
+
}
|
|
428
|
+
if include.iter().any(|p| fnmatch(&low, &p.to_lowercase())) {
|
|
429
|
+
return true;
|
|
430
|
+
}
|
|
431
|
+
let base = low.rsplit('/').next().unwrap_or("");
|
|
432
|
+
if HARNESS_NAMES.contains(&base) || HARNESS_FILES.contains(&low.as_str()) {
|
|
433
|
+
return true;
|
|
434
|
+
}
|
|
435
|
+
let slashed = format!("/{}", low);
|
|
436
|
+
HARNESS_DIRS.iter().any(|d| low.starts_with(d) || slashed.contains(&format!("/{}", d)))
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
fn proposal_digest(att: &Json) -> String {
|
|
440
|
+
let mut files: Vec<String> = att
|
|
441
|
+
.get("files")
|
|
442
|
+
.and_then(Json::as_arr)
|
|
443
|
+
.map(|fs| fs.iter().map(|f| norm_rel(&py_str(f))).filter(|f| !f.is_empty()).collect())
|
|
444
|
+
.unwrap_or_default();
|
|
445
|
+
files.sort();
|
|
446
|
+
files.dedup();
|
|
447
|
+
let mut predicted: Vec<String> = att
|
|
448
|
+
.get("predicted")
|
|
449
|
+
.and_then(Json::as_arr)
|
|
450
|
+
.map(|ps| ps.iter().map(|p| py_str(p).trim().to_string()).filter(|p| !p.is_empty()).collect())
|
|
451
|
+
.unwrap_or_default();
|
|
452
|
+
predicted.sort();
|
|
453
|
+
predicted.dedup();
|
|
454
|
+
let round = match att.get("round") {
|
|
455
|
+
Some(Json::Int(n)) => *n,
|
|
456
|
+
Some(Json::Float(f)) => *f as i64,
|
|
457
|
+
Some(Json::Bool(b)) => *b as i64,
|
|
458
|
+
Some(Json::Str(s)) => s.trim().parse().unwrap_or(0),
|
|
459
|
+
_ => 0,
|
|
460
|
+
};
|
|
461
|
+
let payload = [
|
|
462
|
+
"dmb-sim-proposal-v1".to_string(),
|
|
463
|
+
normalize_cause(&py_text(att.get("cause_key"))),
|
|
464
|
+
format!("round={}", round),
|
|
465
|
+
format!("sample={}", py_get(att, "sample", "").trim()),
|
|
466
|
+
format!("domain={}", py_get(att, "domain", "").trim()),
|
|
467
|
+
format!("benchmark={}", py_text(att.get("benchmark")).trim()),
|
|
468
|
+
format!("policy={}", py_get(att, "policy", "").trim()),
|
|
469
|
+
format!("what={}", normalize_ws(&py_text(att.get("what")))),
|
|
470
|
+
format!("files={}", files.join(",")),
|
|
471
|
+
format!("predicted={}", predicted.join(",")),
|
|
472
|
+
]
|
|
473
|
+
.join("\n");
|
|
474
|
+
sha256_hex(payload.as_bytes())
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
fn finding(severity: &'static str, rule: &'static str, file: &str, message: String, fix: &'static str) -> Finding {
|
|
478
|
+
Finding { severity, rule, file: file.to_string(), line: 1, message, fix }
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
fn is_problem_id(pid: &str) -> Option<u64> {
|
|
482
|
+
let digits = pid.strip_prefix('P')?;
|
|
483
|
+
if digits.is_empty() || digits.starts_with('0') || !digits.bytes().all(|b| b.is_ascii_digit()) {
|
|
484
|
+
return None;
|
|
485
|
+
}
|
|
486
|
+
digits.parse().ok()
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
fn validate_attempt(pid: &str, idx: usize, att: &Json, out: &mut Vec<Finding>) {
|
|
490
|
+
let at = format!("{} attempt[{}]", pid, idx);
|
|
491
|
+
if !matches!(att, Json::Obj(_)) {
|
|
492
|
+
out.push(finding("P0", "sim-schema-invalid", SIM_REL, format!("{} must be an object.", at), "Record attempts with `sim.py record`."));
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
let split = att.get("split").filter(|v| v.truthy()).map(py_str).unwrap_or_else(|| "evolve".to_string());
|
|
496
|
+
if split.trim().to_lowercase() != "evolve" {
|
|
497
|
+
out.push(finding("P0", "sim-holdout-leakage", SIM_REL, format!("{} uses split={:?}.", at, split),
|
|
498
|
+
"SIM takes evolve-set feedback only; keep held-out evaluation outside the loop."));
|
|
499
|
+
}
|
|
500
|
+
if att.get("accepted") != Some(&Json::Bool(true)) {
|
|
501
|
+
out.push(finding("P1", "sim-schema-invalid", SIM_REL, format!("{} is not an accepted edit.", at),
|
|
502
|
+
"SIM stores the selected candidate only; record rejected ones with `--no-accepted`."));
|
|
503
|
+
}
|
|
504
|
+
if normalize_ws(&py_text(att.get("what"))).chars().count() < 15 {
|
|
505
|
+
out.push(finding("P1", "sim-schema-invalid", SIM_REL, format!("{} lacks the modification and rationale (`what`).", at),
|
|
506
|
+
"State what changed and why."));
|
|
507
|
+
}
|
|
508
|
+
let files_ok = att.get("files").and_then(Json::as_arr).map(|fs| {
|
|
509
|
+
!fs.is_empty() && fs.iter().all(|f| matches!(f, Json::Str(s) if !norm_rel(s).is_empty()))
|
|
510
|
+
});
|
|
511
|
+
if files_ok != Some(true) {
|
|
512
|
+
out.push(finding("P1", "sim-schema-invalid", SIM_REL, format!("{} needs a non-empty `files` list.", at),
|
|
513
|
+
"List the harness files the edit changed."));
|
|
514
|
+
}
|
|
515
|
+
let (passed, total) = (att.get("passed").and_then(Json::as_int), att.get("total").and_then(Json::as_int));
|
|
516
|
+
let trials_ok = matches!((passed, total), (Some(p), Some(t)) if 0 <= p && p <= t && t > 0);
|
|
517
|
+
if !trials_ok {
|
|
518
|
+
let show = |v: Option<&Json>| v.map(py_str).unwrap_or_else(|| "None".to_string());
|
|
519
|
+
out.push(finding("P1", "sim-schema-invalid", SIM_REL,
|
|
520
|
+
format!("{} has invalid passed/total ({}/{}).", at, show(att.get("passed")), show(att.get("total"))),
|
|
521
|
+
"Record evolve-set trials with 0 <= passed <= total and total > 0."));
|
|
522
|
+
}
|
|
523
|
+
if normalize_ws(&py_text(att.get("domain"))).is_empty() || normalize_ws(&py_text(att.get("policy"))).is_empty() {
|
|
524
|
+
out.push(finding("P1", "sim-schema-invalid", SIM_REL, format!("{} lacks `domain` or `policy` provenance.", at),
|
|
525
|
+
"Record the benchmark domain and the policy model that executed the tasks."));
|
|
526
|
+
}
|
|
527
|
+
let lists: Vec<Option<&Vec<Json>>> = ["predicted", "fixed", "missed"].iter().map(|k| att.get(k).and_then(Json::as_arr)).collect();
|
|
528
|
+
let (Some(pred), Some(fixed), Some(missed)) = (lists[0], lists[1], lists[2]) else {
|
|
529
|
+
out.push(finding("P1", "sim-schema-invalid", SIM_REL, format!("{} needs `predicted`, `fixed`, `missed` lists.", at),
|
|
530
|
+
"Record predictions before evaluation and both outcome lists after it."));
|
|
531
|
+
return;
|
|
532
|
+
};
|
|
533
|
+
let overlap = fixed.iter().any(|f| missed.contains(f));
|
|
534
|
+
let dropped = pred.iter().any(|p| !fixed.contains(p) && !missed.contains(p));
|
|
535
|
+
if overlap || dropped {
|
|
536
|
+
out.push(finding("P1", "sim-prediction-mismatch", SIM_REL, format!("{} drops or double-counts a prediction.", at),
|
|
537
|
+
"Keep each predicted task in exactly one of `fixed` or `missed`, unresolved ones included."));
|
|
538
|
+
}
|
|
539
|
+
if !att.get("backfilled").map(Json::truthy).unwrap_or(false) {
|
|
540
|
+
let sha = py_text(att.get("proposal_sha256"));
|
|
541
|
+
let well_formed = sha.len() == 64 && sha.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b));
|
|
542
|
+
if !well_formed || sha != proposal_digest(att) {
|
|
543
|
+
out.push(finding("P1", "sim-proposal-digest-invalid", SIM_REL,
|
|
544
|
+
format!("{} does not match its pre-evaluation proposal digest.", at),
|
|
545
|
+
"Stage with `sim.py propose` before evaluating, then `sim.py record`; never hand-edit attempts."));
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
pub fn validate_store(data: &Json) -> Vec<Finding> {
|
|
551
|
+
let mut out = Vec::new();
|
|
552
|
+
let next_id = data.get("next_id").and_then(Json::as_int);
|
|
553
|
+
if !matches!(next_id, Some(n) if n >= 1) {
|
|
554
|
+
out.push(finding("P0", "sim-schema-invalid", SIM_REL, "`next_id` must be a positive integer.".into(), "Run `sim.py init`."));
|
|
555
|
+
}
|
|
556
|
+
if !matches!(data.get("aliases"), Some(Json::Obj(_))) {
|
|
557
|
+
out.push(finding("P0", "sim-schema-invalid", SIM_REL, "`aliases` must be an object.".into(), "Set `aliases` to `{}`."));
|
|
558
|
+
}
|
|
559
|
+
let Some(problems) = data.get("problems").and_then(Json::as_arr) else {
|
|
560
|
+
out.push(finding("P0", "sim-schema-invalid", SIM_REL, "`problems` must be a list.".into(), "Restore the SIM store."));
|
|
561
|
+
return out;
|
|
562
|
+
};
|
|
563
|
+
let carried_mode = data.get("carried_from").and_then(|c| c.get("mode")).map(|m| py_text(Some(m))).unwrap_or_default();
|
|
564
|
+
let mut seen_ids: Vec<String> = Vec::new();
|
|
565
|
+
let mut seen_causes: BTreeMap<String, String> = BTreeMap::new();
|
|
566
|
+
let mut max_num = 0u64;
|
|
567
|
+
for (idx, prob) in problems.iter().enumerate() {
|
|
568
|
+
let pid = if matches!(prob, Json::Obj(_)) { py_text(prob.get("id")) } else { String::new() };
|
|
569
|
+
let num = is_problem_id(&pid);
|
|
570
|
+
if num.is_none() || seen_ids.contains(&pid) {
|
|
571
|
+
out.push(finding("P0", "sim-schema-invalid", SIM_REL,
|
|
572
|
+
format!("problems[{}] has an invalid or duplicate id {:?}.", idx, pid), "Use unique ids P1, P2, ..."));
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
seen_ids.push(pid.clone());
|
|
576
|
+
max_num = max_num.max(num.unwrap_or(0));
|
|
577
|
+
let cause = normalize_cause(&py_text(prob.get("name")));
|
|
578
|
+
if cause.chars().count() < 8 {
|
|
579
|
+
out.push(finding("P1", "sim-schema-invalid", SIM_REL, format!("{} needs a specific root-cause `name`.", pid),
|
|
580
|
+
"Name the recurring harness problem (8+ characters)."));
|
|
581
|
+
} else if let Some(first) = seen_causes.get(&cause) {
|
|
582
|
+
out.push(finding("P1", "sim-unmerged-duplicate-cause", SIM_REL, format!("{} repeats the root cause of {}.", pid, first),
|
|
583
|
+
"Merge entries with identical root-cause text and keep the id in `aliases`."));
|
|
584
|
+
} else {
|
|
585
|
+
seen_causes.insert(cause, pid.clone());
|
|
586
|
+
}
|
|
587
|
+
match prob.get("attempts").and_then(Json::as_arr) {
|
|
588
|
+
Some(atts) if !atts.is_empty() || carried_mode == "problem-only" => {
|
|
589
|
+
for (a_idx, att) in atts.iter().enumerate() {
|
|
590
|
+
validate_attempt(&pid, a_idx, att, &mut out);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
_ => out.push(finding("P1", "sim-schema-invalid", SIM_REL, format!("{} has no recorded attempts.", pid),
|
|
594
|
+
"Open a problem only by recording an accepted attempt.")),
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
if let Some(n) = next_id {
|
|
598
|
+
if max_num as i64 >= n {
|
|
599
|
+
out.push(finding("P1", "sim-schema-invalid", SIM_REL, format!("`next_id` must exceed P{}.", max_num),
|
|
600
|
+
if max_num == 0 { "Set it to 1." } else { "Set it above the highest problem id." }));
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
out
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
fn resolve_alias(aliases: Option<&Json>, pid: &str) -> String {
|
|
607
|
+
let mut cur = pid.trim().to_string();
|
|
608
|
+
let mut seen: Vec<String> = Vec::new();
|
|
609
|
+
while let Some(next) = aliases.and_then(|a| a.get(&cur)) {
|
|
610
|
+
if seen.contains(&cur) {
|
|
611
|
+
break;
|
|
612
|
+
}
|
|
613
|
+
seen.push(cur.clone());
|
|
614
|
+
cur = py_str(next).trim().to_string();
|
|
615
|
+
}
|
|
616
|
+
cur
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
/// Committed attempts are immutable; returns history findings and the attempts the current store adds.
|
|
620
|
+
pub fn compare_with_base(base: &Json, cur: &Json) -> (Vec<Finding>, Vec<Json>) {
|
|
621
|
+
let mut out = Vec::new();
|
|
622
|
+
if let (Some(b), Some(c)) = (base.get("next_id").and_then(Json::as_int), cur.get("next_id").and_then(Json::as_int)) {
|
|
623
|
+
if c < b {
|
|
624
|
+
out.push(finding("P0", "sim-history-tamper", SIM_REL, "`next_id` went backwards.".into(), "Keep `next_id` monotonic."));
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
let aliases = cur.get("aliases").filter(|a| matches!(a, Json::Obj(_)));
|
|
628
|
+
let mut cur_by_id: Vec<(String, &Json)> = Vec::new();
|
|
629
|
+
for prob in cur.get("problems").and_then(Json::as_arr).into_iter().flatten() {
|
|
630
|
+
if matches!(prob, Json::Obj(_)) {
|
|
631
|
+
let id = py_get(prob, "id", "None");
|
|
632
|
+
match cur_by_id.iter_mut().find(|(k, _)| *k == id) {
|
|
633
|
+
Some(slot) => slot.1 = prob,
|
|
634
|
+
None => cur_by_id.push((id, prob)),
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
let mut expected: BTreeMap<String, Vec<&Json>> = BTreeMap::new();
|
|
639
|
+
for bprob in base.get("problems").and_then(Json::as_arr).into_iter().flatten() {
|
|
640
|
+
if !matches!(bprob, Json::Obj(_)) {
|
|
641
|
+
continue;
|
|
642
|
+
}
|
|
643
|
+
let bid = py_get(bprob, "id", "None");
|
|
644
|
+
let target = resolve_alias(aliases, &bid);
|
|
645
|
+
if !cur_by_id.iter().any(|(k, _)| *k == target) {
|
|
646
|
+
out.push(finding("P0", "sim-history-tamper", SIM_REL, format!("Committed problem {} was removed.", bid),
|
|
647
|
+
"SIM is append-only; merge duplicates through `aliases` instead of deleting."));
|
|
648
|
+
continue;
|
|
649
|
+
}
|
|
650
|
+
let atts = bprob.get("attempts").and_then(Json::as_arr).into_iter().flatten().filter(|a| matches!(a, Json::Obj(_)));
|
|
651
|
+
expected.entry(target).or_default().extend(atts);
|
|
652
|
+
}
|
|
653
|
+
let mut new_attempts = Vec::new();
|
|
654
|
+
for (pid, prob) in &cur_by_id {
|
|
655
|
+
let mut pending = expected.get(pid).cloned().unwrap_or_default();
|
|
656
|
+
for att in prob.get("attempts").and_then(Json::as_arr).into_iter().flatten() {
|
|
657
|
+
if !matches!(att, Json::Obj(_)) {
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
match pending.iter().position(|p| *p == att) {
|
|
661
|
+
Some(i) => {
|
|
662
|
+
pending.remove(i);
|
|
663
|
+
}
|
|
664
|
+
None => new_attempts.push(att.clone()),
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
if !pending.is_empty() {
|
|
668
|
+
out.push(finding("P0", "sim-history-tamper", SIM_REL, format!("Committed attempts under {} were deleted or rewritten.", pid),
|
|
669
|
+
"Restore them; record a new attempt to revise, replace, or remove an edit."));
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
(out, new_attempts)
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
fn git(root: &Path, args: &[&str]) -> Option<String> {
|
|
676
|
+
let out = Command::new("git").arg("-C").arg(root).args(args).output().ok()?;
|
|
677
|
+
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
fn lines_of(text: Option<String>) -> Vec<String> {
|
|
681
|
+
text.unwrap_or_default().lines().map(norm_rel).filter(|l| !l.is_empty()).collect()
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
pub fn changed_files(root: &Path, staged: bool, base_ref: Option<&str>) -> Vec<String> {
|
|
685
|
+
let mut found: Vec<String> = if staged {
|
|
686
|
+
lines_of(git(root, &["diff", "--cached", "--name-only", "--diff-filter=ACMRD"]))
|
|
687
|
+
} else {
|
|
688
|
+
let reference = base_ref.unwrap_or("HEAD");
|
|
689
|
+
let mut v = if git(root, &["rev-parse", "--verify", reference]).is_some() {
|
|
690
|
+
lines_of(git(root, &["diff", reference, "--name-only", "--diff-filter=ACMRD"]))
|
|
691
|
+
} else {
|
|
692
|
+
lines_of(git(root, &["diff", "--cached", "--name-only", "--diff-filter=ACMRD"]))
|
|
693
|
+
};
|
|
694
|
+
v.extend(lines_of(git(root, &["ls-files", "--others", "--exclude-standard"])));
|
|
695
|
+
v
|
|
696
|
+
};
|
|
697
|
+
found.sort();
|
|
698
|
+
found.dedup();
|
|
699
|
+
found
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
fn base_store(root: &Path, base_ref: Option<&str>) -> Option<Json> {
|
|
703
|
+
let reference = base_ref.unwrap_or("HEAD");
|
|
704
|
+
git(root, &["rev-parse", "--verify", reference])?;
|
|
705
|
+
let blob = git(root, &["show", &format!("{}:{}", reference, SIM_REL)])?;
|
|
706
|
+
parse_json(&blob).ok().filter(|v| matches!(v, Json::Obj(_)))
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
fn main_root(root: &Path) -> PathBuf {
|
|
710
|
+
let common = git(root, &["rev-parse", "--path-format=absolute", "--git-common-dir"]).map(|s| PathBuf::from(s.trim()));
|
|
711
|
+
match common {
|
|
712
|
+
Some(c) if c.file_name().map(|n| n == ".git").unwrap_or(false)
|
|
713
|
+
&& !root.components().any(|p| p.as_os_str() == ".scratch") => c.parent().map(Path::to_path_buf).unwrap_or_else(|| root.to_path_buf()),
|
|
714
|
+
_ => root.to_path_buf(),
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
pub struct SimReport {
|
|
719
|
+
pub enforced: bool,
|
|
720
|
+
pub harness_files_changed: Vec<String>,
|
|
721
|
+
pub findings: Vec<Finding>,
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
impl SimReport {
|
|
725
|
+
fn count(&self, sev: &str) -> usize {
|
|
726
|
+
self.findings.iter().filter(|f| f.severity == sev).count()
|
|
727
|
+
}
|
|
728
|
+
pub fn ok(&self) -> bool {
|
|
729
|
+
self.count("P0") == 0 && self.count("P1") == 0
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
fn report(enforced: bool, harness: Vec<String>, findings: Vec<Finding>) -> SimReport {
|
|
734
|
+
SimReport { enforced, harness_files_changed: harness, findings }
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
pub fn check(root: &Path, changed: Option<&[String]>, staged: bool, base_ref: Option<&str>) -> SimReport {
|
|
738
|
+
let cfg = policy_config(root);
|
|
739
|
+
let store = root.join(SIM_REL);
|
|
740
|
+
let store_meta = fs::symlink_metadata(&store).ok();
|
|
741
|
+
let base = base_store(root, base_ref);
|
|
742
|
+
let enforced = store_meta.is_some() || cfg.required;
|
|
743
|
+
if !(enforced || base.is_some()) {
|
|
744
|
+
return report(false, Vec::new(), Vec::new());
|
|
745
|
+
}
|
|
746
|
+
if store_meta.as_ref().map(|m| m.file_type().is_symlink()).unwrap_or(false) {
|
|
747
|
+
return report(true, Vec::new(), vec![finding("P0", "sim-schema-invalid", SIM_REL, "SIM store must not be a symlink.".into(), "Use a regular file.")]);
|
|
748
|
+
}
|
|
749
|
+
let text = if staged {
|
|
750
|
+
git(root, &["show", &format!(":{}", SIM_REL)])
|
|
751
|
+
} else {
|
|
752
|
+
fs::read_to_string(&store).ok()
|
|
753
|
+
};
|
|
754
|
+
let Some(text) = text else {
|
|
755
|
+
let (sev, rule) = if base.is_some() { ("P0", "sim-history-tamper") } else { ("P1", "sim-missing-store") };
|
|
756
|
+
return report(true, Vec::new(), vec![finding(sev, rule, SIM_REL, format!("`{}` is missing.", SIM_REL), FIX_INIT)]);
|
|
757
|
+
};
|
|
758
|
+
let cur = match parse_json(&text) {
|
|
759
|
+
Ok(v @ Json::Obj(_)) => v,
|
|
760
|
+
Ok(_) => return report(true, Vec::new(), vec![finding("P0", "sim-schema-invalid", SIM_REL, "Invalid JSON: root must be an object".into(), "Restore the store from git.")]),
|
|
761
|
+
Err(e) => return report(true, Vec::new(), vec![finding("P0", "sim-schema-invalid", SIM_REL, format!("Invalid JSON: {}", e), "Restore the store from git.")]),
|
|
762
|
+
};
|
|
763
|
+
let mut findings = validate_store(&cur);
|
|
764
|
+
let new_attempts = match &base {
|
|
765
|
+
Some(b) => {
|
|
766
|
+
let (history, added) = compare_with_base(b, &cur);
|
|
767
|
+
findings.extend(history);
|
|
768
|
+
added
|
|
769
|
+
}
|
|
770
|
+
None => cur.get("problems").and_then(Json::as_arr).into_iter().flatten()
|
|
771
|
+
.flat_map(|p| p.get("attempts").and_then(Json::as_arr).into_iter().flatten())
|
|
772
|
+
.filter(|a| matches!(a, Json::Obj(_))).cloned().collect(),
|
|
773
|
+
};
|
|
774
|
+
let files: Vec<String> = match changed {
|
|
775
|
+
Some(list) => list.iter().map(|f| norm_rel(f)).collect(),
|
|
776
|
+
None => changed_files(root, staged, base_ref),
|
|
777
|
+
};
|
|
778
|
+
let harness: Vec<String> = files.into_iter().filter(|f| is_harness_file(f, &cfg.include, &cfg.exclude)).collect();
|
|
779
|
+
if base.is_some() {
|
|
780
|
+
let uncovered: Vec<&String> = harness.iter().filter(|f| {
|
|
781
|
+
!new_attempts.iter().any(|att| {
|
|
782
|
+
att.get("files").and_then(Json::as_arr).into_iter().flatten().any(|p| {
|
|
783
|
+
let pat = norm_rel(&py_str(p));
|
|
784
|
+
**f == pat || fnmatch(f, &pat)
|
|
785
|
+
})
|
|
786
|
+
})
|
|
787
|
+
}).collect();
|
|
788
|
+
if let Some(first) = uncovered.first() {
|
|
789
|
+
let shown: Vec<&str> = uncovered.iter().take(5).map(|s| s.as_str()).collect();
|
|
790
|
+
findings.push(finding("P1", "sim-missing-update", first,
|
|
791
|
+
format!("Harness edit not recorded in SIM ({} file(s): {}).", uncovered.len(), shown.join(", ")), FIX_RECORD));
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
if !staged {
|
|
795
|
+
let dir = main_root(root).join(".scratch/sim/proposals");
|
|
796
|
+
let mut entries: Vec<PathBuf> = fs::read_dir(&dir).into_iter().flatten().flatten().map(|e| e.path())
|
|
797
|
+
.filter(|p| p.extension().map(|e| e == "json").unwrap_or(false)).collect();
|
|
798
|
+
entries.sort();
|
|
799
|
+
for path in entries {
|
|
800
|
+
let Some(prop) = fs::read_to_string(&path).ok().and_then(|t| parse_json(&t).ok()) else { continue };
|
|
801
|
+
let split = prop.get("split").filter(|v| v.truthy()).map(py_str).unwrap_or_else(|| "evolve".into()).trim().to_lowercase();
|
|
802
|
+
if split != "evolve" {
|
|
803
|
+
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
|
804
|
+
findings.push(finding("P0", "sim-holdout-leakage", &format!(".scratch/sim/proposals/{}", name),
|
|
805
|
+
format!("Staged proposal uses split {:?}.", split), "Delete it and stage from evolve-set feedback."));
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
report(true, harness, findings)
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
pub fn run(args: &[String]) -> ExitCode {
|
|
813
|
+
let mut root = PathBuf::from(".");
|
|
814
|
+
let (mut staged, mut advisory, mut as_json) = (false, false, false);
|
|
815
|
+
let mut base: Option<String> = None;
|
|
816
|
+
let mut files: Option<Vec<String>> = None;
|
|
817
|
+
let mut i = 0;
|
|
818
|
+
while i < args.len() {
|
|
819
|
+
match args[i].as_str() {
|
|
820
|
+
"check" => i += 1,
|
|
821
|
+
"--root" if i + 1 < args.len() => {
|
|
822
|
+
root = PathBuf::from(&args[i + 1]);
|
|
823
|
+
i += 2;
|
|
824
|
+
}
|
|
825
|
+
"--base" if i + 1 < args.len() => {
|
|
826
|
+
base = Some(args[i + 1].clone());
|
|
827
|
+
i += 2;
|
|
828
|
+
}
|
|
829
|
+
"--staged" => {
|
|
830
|
+
staged = true;
|
|
831
|
+
i += 1;
|
|
832
|
+
}
|
|
833
|
+
"--advisory" => {
|
|
834
|
+
advisory = true;
|
|
835
|
+
i += 1;
|
|
836
|
+
}
|
|
837
|
+
"--json" => {
|
|
838
|
+
as_json = true;
|
|
839
|
+
i += 1;
|
|
840
|
+
}
|
|
841
|
+
"--files" => {
|
|
842
|
+
i += 1;
|
|
843
|
+
let list = files.get_or_insert_with(Vec::new);
|
|
844
|
+
while i < args.len() && !args[i].starts_with("--") {
|
|
845
|
+
list.extend(args[i].split(',').map(str::trim).filter(|s| !s.is_empty()).map(String::from));
|
|
846
|
+
i += 1;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
other => {
|
|
850
|
+
eprintln!("dmb-gate sim: unknown argument {:?} (init/read/propose/record/transfer live in sim.py)", other);
|
|
851
|
+
return ExitCode::from(2);
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
let root = fs::canonicalize(&root).unwrap_or(root);
|
|
856
|
+
let res = check(&root, files.as_deref(), staged, base.as_deref());
|
|
857
|
+
let (p0, p1, p2) = (res.count("P0"), res.count("P1"), res.count("P2"));
|
|
858
|
+
if as_json {
|
|
859
|
+
let items: Vec<String> = res.findings.iter().map(|f| format!(
|
|
860
|
+
"{{\"severity\":{},\"rule\":{},\"file\":{},\"line\":{},\"message\":{},\"fix\":{}}}",
|
|
861
|
+
json_escape(f.severity), json_escape(f.rule), json_escape(&f.file), f.line, json_escape(&f.message), json_escape(f.fix)
|
|
862
|
+
)).collect();
|
|
863
|
+
let harness: Vec<String> = res.harness_files_changed.iter().map(|h| json_escape(h)).collect();
|
|
864
|
+
println!(
|
|
865
|
+
"{{\"ok\":{},\"engine\":\"rust-parallel\",\"enforced\":{},\"sim_file\":{},\"harness_files_changed\":[{}],\"counts\":{{\"P0\":{},\"P1\":{},\"P2\":{}}},\"findings\":[{}]}}",
|
|
866
|
+
res.ok(), res.enforced, json_escape(SIM_REL), harness.join(","), p0, p1, p2, items.join(",")
|
|
867
|
+
);
|
|
868
|
+
} else {
|
|
869
|
+
println!(
|
|
870
|
+
"dmb-gate sim [{}]: enforced={} harness_files={} P0:{} P1:{} P2:{}",
|
|
871
|
+
if res.ok() { "OK" } else { "BLOCKED" }, res.enforced, res.harness_files_changed.len(), p0, p1, p2
|
|
872
|
+
);
|
|
873
|
+
for f in &res.findings {
|
|
874
|
+
println!(" {}:{} [{}:{}] {} -> {}", f.file, f.line, f.severity, f.rule, f.message, f.fix);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
if res.ok() || advisory {
|
|
878
|
+
ExitCode::SUCCESS
|
|
879
|
+
} else {
|
|
880
|
+
ExitCode::from(1)
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
#[cfg(test)]
|
|
885
|
+
mod tests {
|
|
886
|
+
use super::*;
|
|
887
|
+
|
|
888
|
+
fn obj(src: &str) -> Json {
|
|
889
|
+
parse_json(src).expect("valid test JSON")
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
#[test]
|
|
893
|
+
fn proposal_digest_matches_python_sim_py() {
|
|
894
|
+
let att = obj(r#"{"cause_key":" Premature Completion ","round":3,"sample":" s2 ","domain":"coding","benchmark":"tb4",
|
|
895
|
+
"policy":"gemini","what":"Gate completion\n on evidence.","files":["./b.md","a\\x.py","b.md"],"predicted":["t2","t1","t1"]}"#);
|
|
896
|
+
assert_eq!(proposal_digest(&att), "a3dedd7a14c6858ada865b5d27bf812474af97d677dfe5f5cff2bd3f30c11d02");
|
|
897
|
+
let att2 = obj(r#"{"round":3,"sample":" s2 ","domain":"coding","benchmark":null,"policy":"gemini",
|
|
898
|
+
"what":"Gate completion\n on evidence.","files":["./b.md","a\\x.py","b.md"],"predicted":["t2","t1","t1"]}"#);
|
|
899
|
+
assert_eq!(proposal_digest(&att2), "2da420bda35514955d99baa80dca6edd4648b0be6f2670e69481b3c899447e52");
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
#[test]
|
|
903
|
+
fn json_parser_handles_escapes_numbers_and_rejects_garbage() {
|
|
904
|
+
let v = obj(r#"{"a":[1,-2.5e1,true,null],"s":"x\"\u00e9\ud83d\ude00\n"}"#);
|
|
905
|
+
assert_eq!(v.get("a"), Some(&Json::Arr(vec![Json::Int(1), Json::Float(-25.0), Json::Bool(true), Json::Null])));
|
|
906
|
+
assert_eq!(v.get("s"), Some(&Json::Str("x\"é😀\n".into())));
|
|
907
|
+
assert!(parse_json("{\"a\":1,}").is_err());
|
|
908
|
+
assert!(parse_json("[1] 2").is_err());
|
|
909
|
+
assert_ne!(obj("{\"n\":5}"), obj("{\"n\":5.0}"));
|
|
910
|
+
assert_eq!(obj("{\"a\":1,\"b\":2}"), obj("{\"b\":2,\"a\":1}"));
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
#[test]
|
|
914
|
+
fn harness_and_test_paths_match_sim_py() {
|
|
915
|
+
assert!(is_harness_file("AGENTS.md", &[], &[]));
|
|
916
|
+
assert!(is_harness_file("sub/.omp/skills/x/SKILL.md", &[], &[]));
|
|
917
|
+
assert!(is_harness_file(".deepmodebot/policy.xml", &[], &[]));
|
|
918
|
+
assert!(!is_harness_file(".deepmodebot/sim.json", &[], &[]));
|
|
919
|
+
assert!(!is_harness_file("app.py", &[], &[]));
|
|
920
|
+
let inc = vec!["plugins/*/skills/*".to_string()];
|
|
921
|
+
assert!(is_harness_file("plugins/p/skills/s/references/x.md", &inc, &[]));
|
|
922
|
+
assert!(!is_harness_file("plugins/p/skills/s/assets/test_x.py", &inc, &[]));
|
|
923
|
+
assert!(!is_harness_file("plugins/p/skills/s/tests/x.py", &inc, &[]));
|
|
924
|
+
assert!(!is_harness_file("AGENTS.md", &[], &["agents.md".to_string()]));
|
|
925
|
+
assert!(is_test_path("src/a.spec.ts") && is_test_path("test_a.py") && !is_test_path("test_") && !is_test_path("contest.py"));
|
|
926
|
+
assert!(fnmatch("gates/completion.py", "gates/*") && fnmatch("a/b/c", "a*c") && fnmatch("x1", "x[0-9]") && !fnmatch("x", "x?"));
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
#[test]
|
|
930
|
+
fn validation_and_history_catch_tampering() {
|
|
931
|
+
let att = r#"{"round":1,"sample":"s1","accepted":true,"backfilled":false,"what":"Gate completion on executed evidence.",
|
|
932
|
+
"files":["AGENTS.md"],"predicted":["t1"],"fixed":["t1"],"missed":[],"passed":1,"total":1,"domain":"coding",
|
|
933
|
+
"benchmark":"","policy":"m","split":"evolve","cause_key":"completion without evidence","proposal_sha256":"SHA"}"#;
|
|
934
|
+
let mut a = obj(att);
|
|
935
|
+
let sha = proposal_digest(&a);
|
|
936
|
+
if let Json::Obj(m) = &mut a {
|
|
937
|
+
m.insert("proposal_sha256".into(), Json::Str(sha));
|
|
938
|
+
}
|
|
939
|
+
let store = |atts: Vec<Json>| {
|
|
940
|
+
let mut root = BTreeMap::new();
|
|
941
|
+
let mut prob = BTreeMap::new();
|
|
942
|
+
prob.insert("id".into(), Json::Str("P1".into()));
|
|
943
|
+
prob.insert("name".into(), Json::Str("completion without evidence".into()));
|
|
944
|
+
prob.insert("opened_round".into(), Json::Int(1));
|
|
945
|
+
prob.insert("attempts".into(), Json::Arr(atts));
|
|
946
|
+
root.insert("next_id".into(), Json::Int(2));
|
|
947
|
+
root.insert("aliases".into(), Json::Obj(BTreeMap::new()));
|
|
948
|
+
root.insert("problems".into(), Json::Arr(vec![Json::Obj(prob)]));
|
|
949
|
+
Json::Obj(root)
|
|
950
|
+
};
|
|
951
|
+
let good = store(vec![a.clone()]);
|
|
952
|
+
assert!(validate_store(&good).is_empty(), "{:?}", validate_store(&good));
|
|
953
|
+
|
|
954
|
+
let mut forged = a.clone();
|
|
955
|
+
let mut leaked = a.clone();
|
|
956
|
+
if let (Json::Obj(f), Json::Obj(l)) = (&mut forged, &mut leaked) {
|
|
957
|
+
f.insert("predicted".into(), Json::Arr(vec![]));
|
|
958
|
+
l.insert("split".into(), Json::Str("held_out".into()));
|
|
959
|
+
}
|
|
960
|
+
let rules = |s: &Json| validate_store(s).iter().map(|f| f.rule).collect::<Vec<_>>();
|
|
961
|
+
assert!(rules(&store(vec![forged.clone()])).contains(&"sim-proposal-digest-invalid"));
|
|
962
|
+
assert!(rules(&store(vec![leaked])).contains(&"sim-holdout-leakage"));
|
|
963
|
+
|
|
964
|
+
let (hist, added) = compare_with_base(&good, &store(vec![a.clone(), forged.clone()]));
|
|
965
|
+
assert!(hist.is_empty() && added == vec![forged.clone()]);
|
|
966
|
+
let (hist, _) = compare_with_base(&good, &store(vec![forged]));
|
|
967
|
+
assert!(hist.iter().any(|f| f.rule == "sim-history-tamper"));
|
|
968
|
+
}
|
|
969
|
+
}
|