dsh-vibe-math 2.3.1 → 2.3.2

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.
Files changed (38) hide show
  1. package/AUDIT-CHECKLIST.md +45 -0
  2. package/README.md +16 -6
  3. package/RELEASE-NOTES-2.3.2.md +145 -0
  4. package/audit-formal-sensitivity.mjs +11 -2
  5. package/audit-prompt-invariants.mjs +414 -0
  6. package/audit-spec-traceability.mjs +173 -0
  7. package/docs/formal-verification.md +33 -10
  8. package/docs/generate_framework_diagram_v5.mjs +2 -1
  9. package/docs/test-timing.md +32 -10
  10. package/formal-verify-v2.test.mjs +242 -2
  11. package/formal-verify-v3.test.mjs +176 -4
  12. package/formal-verify-v4.test.mjs +184 -5
  13. package/formal-verify-v5.test.mjs +91 -4
  14. package/installer.js +3 -1
  15. package/package.json +5 -2
  16. package/prompt-corpus-persona/persona-corpus.json +2 -2
  17. package/prompt-corpus-persona/persona-corpus.md +6 -2
  18. package/prompt-corpus-v2/formal-verify-v2.json +134 -44
  19. package/prompt-corpus-v2/formal-verify-v2.md +1033 -44
  20. package/prompt-corpus-v3/formal-verify-v3.json +200 -128
  21. package/prompt-corpus-v3/formal-verify-v3.md +948 -243
  22. package/prompt-corpus-v4/formal-verify-v4.json +8 -3
  23. package/prompt-corpus-v4/formal-verify-v4.md +38 -10
  24. package/prompt-corpus-v5/prompt-corpus-v5.json +175 -246
  25. package/prompt-corpus-v5/prompt-corpus-v5.md +341 -781
  26. package/prompt-v5-integrity.test.mjs +136 -22
  27. package/run-tests.mjs +30 -11
  28. package/vibe-math-v2/vibe-math-v2.js +149 -35
  29. package/vibe-math-v2//345/256/236/347/216/260/346/226/271/346/241/210.md +53 -5
  30. package/vibe-math-v3/vibe-math-v3.js +88 -23
  31. package/vibe-math-v3//345/256/236/347/216/260/346/226/271/346/241/210.md +7 -6
  32. package/vibe-math-v4/vibe-math-v4.js +103 -24
  33. package/vibe-math-v4//345/256/236/347/216/260/346/226/271/346/241/210.md +34 -11
  34. package/vibe-math-v5/agent.cordis.yml +6 -2
  35. package/vibe-math-v5/vibe-math-v5.js +56 -10
  36. package/vibe-math-v5//345/256/236/347/216/260/346/226/271/346/241/210.md +40 -13
  37. package/vibe-math-v5//346/236/266/346/236/204/345/233/276.md +16 -2
  38. package//347/244/272/344/276/213/345/233/276//346/241/206/346/236/266/345/233/276-v5.svg +6 -5
@@ -0,0 +1,414 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * PROMPT/INTERACTION INVARIANTS — the specific defect CLASSES this project has actually shipped,
4
+ * encoded as static invariants over all four presets. This is the mechanical answer to
5
+ * "are the prompt defects really fixed, and can they come back silently?".
6
+ *
7
+ * Every check below exists because the class was found in a real audit round:
8
+ * I1 abbreviated tool names in agent-facing text (lean_archive is not a registered tool)
9
+ * I2 a fidelity defect expressed as a 0 vote ("偏离 → 0" records 命题为假)
10
+ * I3 the defect rule missing from the injected text (不要投 0 + decision:'defect')
11
+ * I4 `defect` advertised but not handled by code (the v2 dead-channel class)
12
+ * I5 the reply contract not offering `defect` (a defect would be unrecordable)
13
+ * I6 a defect accepted without a reason (silent, unauditable decisions)
14
+ * I7 the wrong reply field name in the fidelity text (`verdict` where the parser reads `Result`)
15
+ * I8 the `formal` reply channel live in `off` mode (off must be a TRUE no-op)
16
+ * I9 corpus non-determinism / machine-path leaks / missing mode coverage
17
+ * I10 the prompt-rule sensitivity probes going missing (a guard that is not proven to go red)
18
+ * I11 the "no Lean toolchain" guidance naming only one of the two failure codes
19
+ * I12 the fidelity branch promising a hold that `encourage` cannot enforce
20
+ * I13 the Lean switch unreachable THROUGH the closed tool schema (v3 2.3.1: all four params
21
+ * missing from vibe_math_set_params, invisible to every suite because suites call handlers)
22
+ * I14 a parameter the tool schema advertises but the parameter layer silently drops
23
+ *
24
+ * Run: node audit-prompt-invariants.mjs (add --json for a machine-readable report)
25
+ * node audit-prompt-invariants.mjs --self-probe
26
+ * prove the guard is a guard: re-run itself on mutated sources and require the matching
27
+ * invariant to go RED (control run must stay green)
28
+ */
29
+ import { readFileSync, existsSync } from 'node:fs'
30
+ import { spawnSync } from 'node:child_process'
31
+ import { fileURLToPath } from 'node:url'
32
+ import { join } from 'node:path'
33
+
34
+ const HERE = fileURLToPath(new URL('./', import.meta.url))
35
+ /**
36
+ * `PROMPT_INVARIANTS_MUTATE` carries a JSON `[rel, from, to]` triple: a single file is mutated IN
37
+ * MEMORY for one child run, so `--self-probe` can demonstrate that the invariant keyed to it really
38
+ * turns red. (Not a NUL-separated string: env values may not contain NUL bytes.)
39
+ */
40
+ function readRaw(rel) {
41
+ const p = join(HERE, rel)
42
+ if (!existsSync(p)) return null
43
+ let text = readFileSync(p, 'utf8')
44
+ const mut = process.env.PROMPT_INVARIANTS_MUTATE
45
+ if (mut) {
46
+ try {
47
+ const [rel2, from, to] = JSON.parse(mut)
48
+ if (rel2 === rel && from) text = text.replace(from, to)
49
+ } catch (e) { /* a malformed mutation is a harness error, not an invariant failure */ }
50
+ }
51
+ return text
52
+ }
53
+ const read = readRaw
54
+
55
+ /**
56
+ * Each mutation is a real defect shape from this project's history. `expect` is a substring that
57
+ * MUST appear in the failing run; `control: true` marks the unmutated run, which must stay green.
58
+ */
59
+ const SELF_PROBE_MUTATIONS = [
60
+ { name: 'control (no mutation)', rel: '', from: '', to: '', expect: '', control: true },
61
+ {
62
+ name: 'v3: one set_params registration loses the Lean params (I13 — the v2.3.1 shipped defect)',
63
+ rel: 'vibe-math-v3/vibe-math-v3.js',
64
+ from: 'formalVerify: { type: \'string\'',
65
+ to: 'formalVerifyDISABLED: { type: \'string\'',
66
+ expect: 'v3 I13: every vibe_math_set_params schema advertises',
67
+ },
68
+ {
69
+ name: 'v3: objParams stops closing the schema (I13 premise)',
70
+ rel: 'vibe-math-v3/vibe-math-v3.js',
71
+ from: "additionalProperties: false, required: required || [] }",
72
+ to: 'required: required || [] }',
73
+ expect: 'v3 I13: every objParams definition closes tool schemas',
74
+ },
75
+ {
76
+ name: 'v4: the schema advertises a knob the parameter layer drops (I14)',
77
+ rel: 'vibe-math-v4/vibe-math-v4.js',
78
+ from: "leanTimeoutMs:{type:'integer'}",
79
+ to: "leanTimeoutMs:{type:'integer'},bogusKnob:{type:'string'}",
80
+ expect: 'v4 I14: every key vibe_v4_set advertises is actually accepted',
81
+ },
82
+ {
83
+ name: 'v5: normalizeParams stops accepting an advertised key (I14)',
84
+ rel: 'vibe-math-v5/vibe-math-v5.js',
85
+ from: "'meetingKeepEvery', 'leanTimeoutMs']",
86
+ to: "'meetingKeepEvery']",
87
+ expect: 'advertised but dropped: [leanTimeoutMs]',
88
+ },
89
+ ]
90
+
91
+ if (process.argv.includes('--self-probe')) {
92
+ const bad = []
93
+ for (const mut of SELF_PROBE_MUTATIONS) {
94
+ const r = spawnSync(process.execPath, [fileURLToPath(import.meta.url), '--json'], {
95
+ cwd: HERE,
96
+ env: Object.assign({}, process.env, mut.control ? {} : { PROMPT_INVARIANTS_MUTATE: JSON.stringify([mut.rel, mut.from, mut.to]) }),
97
+ encoding: 'utf8',
98
+ })
99
+ let parsed = null
100
+ try { parsed = JSON.parse(r.stdout) } catch (e) { /* fall through to the diagnostic below */ }
101
+ const text = (r.stdout || '') + (r.stderr || '')
102
+ if (mut.control) {
103
+ const ok = r.status === 0 && parsed && parsed.failed === 0
104
+ console.log((ok ? 'PASS ' : 'FAIL ') + 'control: the unmutated run stays green (' + (parsed ? parsed.failed + ' failures' : 'unparsable output') + ')')
105
+ if (!ok) bad.push('control run was not green')
106
+ continue
107
+ }
108
+ const hit = text.includes(mut.expect)
109
+ const red = r.status === 1 && parsed && parsed.failed > 0
110
+ const ok = red && hit
111
+ console.log((ok ? 'PASS ' : 'FAIL ') + mut.name + (ok ? '' : ' → exit=' + r.status + ' hit=' + hit))
112
+ if (!ok) bad.push(mut.name + ' (exit ' + r.status + ', expected ' + JSON.stringify(mut.expect) + ')')
113
+ }
114
+ console.log('')
115
+ console.log('PROMPT INVARIANT SELF-PROBE: ' + (SELF_PROBE_MUTATIONS.length - bad.length) + '/' + SELF_PROBE_MUTATIONS.length + ' as required')
116
+ for (const b of bad) console.error(' FAIL ' + b)
117
+ process.exit(bad.length === 0 ? 0 : 1)
118
+ }
119
+
120
+ /**
121
+ * Blank out comments (line + block) while preserving string/template literals, so invariants about
122
+ * "text shown to an agent" do not fire on a COMMENT that quotes an anti-pattern. A naive regex
123
+ * would both miss block comments and mangle strings containing `//` (URLs), so this walks the
124
+ * source as a tiny scanner. Newlines are preserved to keep any line-based diagnostics aligned.
125
+ */
126
+ function stripComments(src) {
127
+ const out = []
128
+ let i = 0
129
+ let state = 'code' // code | line | block | sq | dq | tpl
130
+ while (i < src.length) {
131
+ const c = src[i]
132
+ const c2 = src[i + 1]
133
+ if (state === 'code') {
134
+ if (c === '/' && c2 === '/') { state = 'line'; out.push(' '); i += 2; continue }
135
+ if (c === '/' && c2 === '*') { state = 'block'; out.push(' '); i += 2; continue }
136
+ if (c === "'") state = 'sq'
137
+ else if (c === '"') state = 'dq'
138
+ else if (c === '`') state = 'tpl'
139
+ out.push(c); i++; continue
140
+ }
141
+ if (state === 'line') {
142
+ if (c === '\n') { state = 'code'; out.push(c) } else out.push(' ')
143
+ i++; continue
144
+ }
145
+ if (state === 'block') {
146
+ if (c === '*' && c2 === '/') { state = 'code'; out.push(' '); i += 2; continue }
147
+ out.push(c === '\n' ? c : ' '); i++; continue
148
+ }
149
+ // inside a string/template: copy verbatim, honouring escapes and the closing quote
150
+ if (c === '\\') { out.push(c, c2 === undefined ? '' : c2); i += 2; continue }
151
+ if ((state === 'sq' && c === "'") || (state === 'dq' && c === '"') || (state === 'tpl' && c === '`')) state = 'code'
152
+ out.push(c); i++
153
+ }
154
+ return out.join('')
155
+ }
156
+
157
+ /**
158
+ * Balanced-bracket slice starting at src[openIdx] (one of ( [ {), string/comment aware.
159
+ * Used by the TOOL-SURFACE invariants (I13/I14) to read a real parameter schema out of the source.
160
+ */
161
+ function balanced(src, openIdx) {
162
+ let depth = 0
163
+ let i = openIdx
164
+ let state = 'code'
165
+ while (i < src.length) {
166
+ const c = src[i]
167
+ const c2 = src[i + 1]
168
+ if (state === 'code') {
169
+ if (c === "'" || c === '"' || c === '`') { state = c; i++; continue }
170
+ if (c === '(' || c === '[' || c === '{') depth++
171
+ else if (c === ')' || c === ']' || c === '}') { depth--; if (depth === 0) return src.slice(openIdx, i + 1) }
172
+ i++; continue
173
+ }
174
+ if (c === '\\') { i += 2; continue }
175
+ if (c === state) state = 'code'
176
+ i++
177
+ }
178
+ return src.slice(openIdx)
179
+ }
180
+ /** Split an object-body on TOP-LEVEL commas only (brackets and strings respected). */
181
+ function splitTopLevel(body) {
182
+ const parts = []
183
+ let cur = ''
184
+ let depth = 0
185
+ let state = 'code'
186
+ for (let i = 0; i < body.length; i++) {
187
+ const c = body[i]
188
+ const c2 = body[i + 1]
189
+ if (state === 'code') {
190
+ if (c === "'" || c === '"' || c === '`') { state = c; cur += c; continue }
191
+ if (c === '{' || c === '[' || c === '(') depth++
192
+ else if (c === '}' || c === ']' || c === ')') depth--
193
+ if (c === ',' && depth === 0) { parts.push(cur); cur = ''; continue }
194
+ cur += c; continue
195
+ }
196
+ if (c === '\\') { cur += c + (c2 || ''); i++; continue }
197
+ if (c === state) state = 'code'
198
+ cur += c
199
+ }
200
+ parts.push(cur)
201
+ return parts.map((p) => p.trim()).filter(Boolean)
202
+ }
203
+ /** Property keys of the object literal at/after `at` (null when there is no object literal there). */
204
+ function objectKeys(src, at) {
205
+ const open = src.indexOf('{', at)
206
+ if (open < 0) return null
207
+ const region = balanced(src, open)
208
+ return splitTopLevel(region.slice(1, -1))
209
+ .map((p) => { const m = p.match(/^['"]?([A-Za-z_$][\w$]*)['"]?\s*:/); return m ? m[1] : null })
210
+ .filter(Boolean)
211
+ }
212
+
213
+ const PRESETS = [
214
+ { tag: 'v2', js: 'vibe-math-v2/vibe-math-v2.js', suite: 'formal-verify-v2.test.mjs', corpus: 'prompt-corpus-v2/formal-verify-v2.md', valueField: 'Result', prefix: 'vibe_math_', setTool: 'vibe_math_set_params' },
215
+ { tag: 'v3', js: 'vibe-math-v3/vibe-math-v3.js', suite: 'formal-verify-v3.test.mjs', corpus: 'prompt-corpus-v3/formal-verify-v3.md', valueField: 'Result', prefix: 'vibe_math_', setTool: 'vibe_math_set_params' },
216
+ { tag: 'v4', js: 'vibe-math-v4/vibe-math-v4.js', suite: 'formal-verify-v4.test.mjs', corpus: 'prompt-corpus-v4/formal-verify-v4.md', valueField: 'verdict', prefix: 'vibe_v4_', setTool: 'vibe_v4_set' },
217
+ { tag: 'v5', js: 'vibe-math-v5/vibe-math-v5.js', suite: 'formal-verify-v5.test.mjs', corpus: 'prompt-corpus-v5/prompt-corpus-v5.md', valueField: 'verdict', prefix: 'vibe_v5_', setTool: 'vibe_v5_set' },
218
+ ]
219
+ const LEAN_PARAMS = ['formalVerify', 'leanCommand', 'leanArgs', 'leanTimeoutMs']
220
+
221
+ let passed = 0
222
+ const failures = []
223
+ const notes = []
224
+ function check(cond, label, detail) {
225
+ if (cond) { passed++; return true }
226
+ failures.push(label + (detail ? ' — ' + detail : ''))
227
+ return false
228
+ }
229
+
230
+ for (const P of PRESETS) {
231
+ const js = read(P.js)
232
+ const suite = read(P.suite)
233
+ const corpus = read(P.corpus)
234
+ if (!check(js !== null, P.tag + ': plugin source readable', P.js)) continue
235
+ if (!check(suite !== null, P.tag + ': suite readable', P.suite)) continue
236
+ if (!check(corpus !== null, P.tag + ': prompt corpus shipped', P.corpus)) continue
237
+
238
+ // I1/I2 run on the source with comments blanked: a comment may legitimately quote an
239
+ // anti-pattern as documentation, but any STRING can reach an agent.
240
+ const code = stripComments(js)
241
+
242
+ // I1 — no abbreviated tool name in code/strings (code identifiers are leanArchive / leanRunTool,
243
+ // so a bare lean_* token is always a string that can be shown to an agent).
244
+ const bare = code.match(/(^|[^A-Za-z0-9_])lean_(run|archive|lib)\b/g) || []
245
+ check(bare.length === 0, P.tag + ' I1: no abbreviated Lean tool name in agent-facing text', 'found ' + JSON.stringify(bare.slice(0, 3)))
246
+
247
+ // I2 — never tell a voter to answer 0 for a faithfulness defect (comments excluded).
248
+ check(!/偏离\s*(?:→|->|=>)\s*0/.test(code), P.tag + ' I2: no "偏离 → 0" instruction')
249
+
250
+ // I3 — the defect rule is in the injected text.
251
+ check(js.includes('不要投 0'), P.tag + ' I3: injected text forbids a 0 vote on a defect')
252
+ check(/'defect'/.test(js) || /"defect"/.test(js), P.tag + ' I3: injected text names decision=\'defect\'')
253
+
254
+ // I4 — the defect decision is actually HANDLED (comparison + a downgrade to `attempted`).
255
+ const comparesDefect = /(?:===|==)\s*'defect'/.test(js) || /'defect'\s*(?:===|==)/.test(js)
256
+ check(comparesDefect, P.tag + ' I4: the code compares decision against \'defect\'')
257
+ const downgrades = /status:\s*'attempted'/.test(js) || /status='attempted'/.test(js) || /status:\s*"attempted"/.test(js)
258
+ check(downgrades, P.tag + " I4: a defect downgrades the record to 'attempted'")
259
+
260
+ // I5 — the reply contract offers the defect decision.
261
+ const contractCount = js.split('"decision":"used|blocked|defect"').length - 1
262
+ check(contractCount >= 1, P.tag + ' I5: the reply contract offers used|blocked|defect', 'occurrences=' + contractCount)
263
+
264
+ // I6 — a defect without a reason is refused.
265
+ check(/!note/.test(js), P.tag + ' I6: a defect/blocker without a note is rejected')
266
+
267
+ // I7 — the fidelity instruction names the field the parser really reads.
268
+ {
269
+ const lines = js.split(/\r?\n/)
270
+ const i = lines.findIndex((l) => l.includes('不要投 0'))
271
+ const window = i >= 0 ? lines.slice(Math.max(0, i - 3), i + 8).join('\n') : ''
272
+ check(i >= 0 && window.includes(P.valueField),
273
+ P.tag + ' I7: the fidelity instruction names ' + P.valueField + ' (the real reply field)',
274
+ i < 0 ? 'the 不要投 0 rule was not found' : 'window: ' + window.slice(0, 120).replace(/\n/g, ' | '))
275
+ if (P.tag === 'v2' || P.tag === 'v3') {
276
+ check(!/给出\s*verdict/.test(js), P.tag + ' I7b: no "给出 verdict" in a Result-based preset')
277
+ }
278
+ }
279
+
280
+ // I8 — the `formal` reply channel is inert in off mode (tools stay usable on purpose).
281
+ const offGuards = {
282
+ v2: /absorbFormal(?:From)?Reply[\s\S]{0,900}!formalOn\(\)/,
283
+ v3: /absorbFormal(?:From)?Reply[\s\S]{0,900}!formalOn\(\)/,
284
+ v4: /applyFormalReply[\s\S]{0,900}!formalOn\(\)/,
285
+ v5: /formalOn\(\)\s*&&\s*p\.formal/,
286
+ }
287
+ check(offGuards[P.tag].test(js), P.tag + ' I8: the reply channel is gated on formalOn() (off stays a no-op)')
288
+
289
+ // I9 — the corpus covers every mode and is deterministic / machine-path free.
290
+ check(corpus.includes('【Lean 形式化验证(鼓励模式)】'), P.tag + ' I9: corpus covers encourage mode')
291
+ check(corpus.includes('【Lean 形式化验证(强制模式)】'), P.tag + ' I9: corpus covers REQUIRE mode')
292
+ check(corpus.includes('不要投 0'), P.tag + ' I9: corpus contains the fidelity/defect rule')
293
+ check(/used\|blocked\|defect/.test(corpus), P.tag + ' I9: corpus contains the reply contract line')
294
+ check(/【顺手形式化/.test(corpus), P.tag + ' I9: corpus contains the work-round line')
295
+ check(!/[A-Za-z]:[\\/]/.test(corpus), P.tag + ' I9: corpus leaks no absolute path')
296
+ check(!/\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}/.test(corpus), P.tag + ' I9: corpus carries no timestamp (deterministic)')
297
+ check(!/vibe-v[0-9]-[a-z]+-[A-Za-z0-9]{4,}/.test(corpus), P.tag + ' I9: corpus leaks no temp-dir name')
298
+
299
+ // I10 — the prompt-rule probes exist for this preset (a guard nobody can prove is a guard nobody has).
300
+ const probeSrc = read('audit-formal-sensitivity.mjs') || ''
301
+ for (const kind of ['fidelity-defect-rule-removed', 'abbreviated-tool-name-injected', 'require-wording-removed', 'defect-decision-not-offered']) {
302
+ check(probeSrc.includes("tag + '-" + kind + "'") || probeSrc.includes("'" + P.tag + '-' + kind + "'"),
303
+ P.tag + ' I10: probe exists for ' + kind)
304
+ }
305
+
306
+ // I10b — the suite asserts the defect path (behaviourally, not just wording).
307
+ check(/\bdefect\b/.test(suite), P.tag + ' I10b: the suite exercises the defect path')
308
+
309
+ // I11 — the "no toolchain" guidance must name BOTH failure codes. An agent that only knows
310
+ // LEAN_NOT_FOUND treats NO_SUBPROCESS as an unknown failure and retries instead of recording the
311
+ // blocker (contract §6 hard rule 4).
312
+ {
313
+ const lines = js.split(/\r?\n/)
314
+ const gi = lines.findIndex((l) => l.includes('宿主无 Lean 工具链'))
315
+ const win = gi >= 0 ? lines.slice(Math.max(0, gi - 3), gi + 1).join('\n') : ''
316
+ check(gi >= 0 && /LEAN_NOT_FOUND/.test(win) && /NO_SUBPROCESS/.test(win),
317
+ P.tag + ' I11: the no-toolchain guidance names LEAN_NOT_FOUND AND NO_SUBPROCESS',
318
+ gi < 0 ? 'the guidance line was not found' : 'window: ' + win.slice(0, 140).replace(/\n/g, ' | '))
319
+ }
320
+
321
+ // I12 — the fidelity branch must qualify its promise BY MODE. Only `require` has a gate, so the
322
+ // text must say "本次裁定不定论" for require AND explicitly tell the voter, for encourage, that
323
+ // this mode has no gate and their abstention is what prevents a conclusion. Shipping the
324
+ // unconditional claim was a real defect that survived in three presets after v5 was fixed.
325
+ check(js.includes('本档没有门禁'), P.tag + ' I12: the fidelity text states the encourage branch has no gate')
326
+ check(js.includes('本次裁定**不定论**') || js.includes('本次裁定不定论'), P.tag + ' I12: the fidelity text states the require hold')
327
+
328
+ // I13 — the Lean switch must be REACHABLE THROUGH THE TOOL SCHEMA. Every tool schema here is
329
+ // built by `objParams`, which closes it with `additionalProperties:false`: a key the schema does
330
+ // not list is REJECTED by any schema-validating provider. v3 shipped 2.3.0/2.3.1 with all four
331
+ // Lean params missing from `vibe_math_set_params` and every suite stayed green, because the
332
+ // suites call the handler directly and never look at the schema — the feature could not be turned
333
+ // on at all. So: EVERY registration of the parameter tool (v2/v3 register it twice, for two agent
334
+ // scopes) must advertise all four, and the closed-schema premise must still hold.
335
+ {
336
+ // EVERY objParams definition must close its schema: one open definition (v2/v3 define it twice,
337
+ // for two agent scopes) would let tools registered through it accept arbitrary keys.
338
+ const defs = [...code.matchAll(/function objParams\(/g)].map((m) => m.index)
339
+ const closedDefs = defs.filter((i) => /additionalProperties:\s*false/.test(code.slice(i, i + 220)))
340
+ check(defs.length > 0 && closedDefs.length === defs.length,
341
+ P.tag + ' I13: every objParams definition closes tool schemas (additionalProperties:false)',
342
+ 'definitions=' + defs.length + ' closed=' + closedDefs.length +
343
+ (defs.length ? '; if this is gone the schema no longer rejects unlisted keys and I13 loses its premise' : ''))
344
+ const regRe = new RegExp("registerTool\\(\\s*['\"]" + P.setTool + "['\"]", 'g')
345
+ const schemas = []
346
+ let m
347
+ while ((m = regRe.exec(code))) {
348
+ const rest = code.slice(m.index)
349
+ const oi = rest.indexOf('objParams(')
350
+ schemas.push(oi < 0 ? null : objectKeys(rest, oi + 'objParams'.length))
351
+ }
352
+ check(schemas.length >= 1, P.tag + ' I13: the parameter tool ' + P.setTool + ' is registered',
353
+ 'no registerTool(\'' + P.setTool + '\') call found')
354
+ const bad = schemas.map((s, i) => (s === null ? 'reg#' + i + ': no objParams schema'
355
+ : LEAN_PARAMS.filter((k) => !s.includes(k)))).filter((x) => (Array.isArray(x) ? x.length : true))
356
+ check(schemas.length >= 1 && bad.length === 0,
357
+ P.tag + ' I13: every ' + P.setTool + ' schema advertises ' + LEAN_PARAMS.join('/'),
358
+ bad.length ? JSON.stringify(bad) : 'no registration found')
359
+
360
+ // I14 — a key the schema ACCEPTS must really be accepted by the parameter layer. Otherwise the
361
+ // tool advertises a knob that is silently dropped: the caller sees {ok:true} and nothing changes.
362
+ // The accept gate is DEFAULT_PARAMS for v2/v3/v4 (`if (k in params)`) and the typed lists inside
363
+ // normalizeParams for v5 (only those keys are copied through).
364
+ let accepts = null
365
+ if (P.tag === 'v5') {
366
+ const fn = code.indexOf('function normalizeParams')
367
+ const region = fn < 0 ? '' : balanced(code, code.indexOf('{', fn))
368
+ const names = []
369
+ for (const kind of ['ints', 'bools', 'strs', 'arrs']) {
370
+ const ai = region.indexOf('const ' + kind + ' = [')
371
+ if (ai < 0) continue
372
+ const arr = balanced(region, region.indexOf('[', ai))
373
+ for (const lit of arr.match(/'[A-Za-z_$][\w$]*'/g) || []) names.push(lit.slice(1, -1))
374
+ }
375
+ accepts = names.length ? [...new Set(names)] : null
376
+ } else {
377
+ const di = code.indexOf('DEFAULT_PARAMS =')
378
+ accepts = di < 0 ? null : objectKeys(code, di)
379
+ }
380
+ check(accepts !== null && accepts.length > 0, P.tag + ' I14: the parameter accept-set is readable',
381
+ 'extractor found no parameter set — the invariant cannot be checked')
382
+ const union = [...new Set(schemas.filter(Boolean).flat())]
383
+ const dropped = accepts ? union.filter((k) => !accepts.includes(k)) : []
384
+ check(accepts !== null && dropped.length === 0,
385
+ P.tag + ' I14: every key ' + P.setTool + ' advertises is actually accepted (no silently-dropped knob)',
386
+ 'advertised but dropped: [' + dropped.join(',') + ']')
387
+ check(union.length >= LEAN_PARAMS.length, P.tag + ' I14: the parameter schema was parsed (' + union.length + ' keys)',
388
+ 'schema extraction returned ' + union.length + ' keys')
389
+ }
390
+
391
+ notes.push(P.tag + ': plugin ' + js.length + 'B · suite ' + suite.length + 'B · corpus ' + corpus.length + 'B')
392
+ }
393
+
394
+ // Cross-preset: the probe script must refuse to report success on an empty selection (false green).
395
+ {
396
+ const probeSrc = read('audit-formal-sensitivity.mjs') || ''
397
+ check(/selected\.length === 0/.test(probeSrc), 'X1: the probe runner fails on an empty selection instead of reporting success')
398
+ const runner = read('run-tests.mjs') || ''
399
+ check(/no suites matched/.test(runner), 'X2: the suite runner fails when no suite matches')
400
+ check(/argv\[i \+ 1\]/.test(runner) && /argv\[\+\+i\]/.test(runner), 'X3: the suite runner accepts both --flag=x and --flag x')
401
+ }
402
+
403
+ const out = { passed, failed: failures.length, failures, notes }
404
+ if (process.argv.includes('--json')) {
405
+ console.log(JSON.stringify(out, null, 2))
406
+ } else {
407
+ console.log('-- prompt/interaction invariants (all four presets) --')
408
+ for (const n of notes) console.log(' note ' + n)
409
+ console.log('')
410
+ for (const f of failures) console.error(' FAIL ' + f)
411
+ console.log('')
412
+ console.log('PROMPT INVARIANTS: ' + passed + ' passed, ' + failures.length + ' failed')
413
+ }
414
+ process.exit(failures.length === 0 ? 0 : 1)
@@ -0,0 +1,173 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * SPEC/README ↔ CODE TRACEABILITY (all four presets).
4
+ *
5
+ * This class of drift has produced real bugs here twice: a `/v4` usage string that advertised a
6
+ * `message` subcommand no branch implemented, and personas that never named registered tools. The
7
+ * rule is asymmetric on purpose:
8
+ *
9
+ * · a tool the SPEC/README advertises that the code does NOT register → FAIL (a documented
10
+ * capability that does not exist is a lie the agent will act on);
11
+ * · a tool the code registers that the spec never names → NOTE (documenting
12
+ * every member-only tool in the spec is not always desirable, but the gap must be visible);
13
+ * · the four Lean parameters must be documented in the spec AND the README AND accepted by the
14
+ * code — a parameter nobody documents cannot be discovered, and one nobody accepts cannot be set.
15
+ *
16
+ * Run: node audit-spec-traceability.mjs [--json]
17
+ */
18
+ import { readFileSync, existsSync } from 'node:fs'
19
+ import { fileURLToPath } from 'node:url'
20
+ import { join } from 'node:path'
21
+
22
+ const HERE = fileURLToPath(new URL('./', import.meta.url))
23
+ const read = (rel) => (existsSync(join(HERE, rel)) ? readFileSync(join(HERE, rel), 'utf8') : null)
24
+
25
+ const PRESETS = [
26
+ { tag: 'v2', js: 'vibe-math-v2/vibe-math-v2.js', spec: 'vibe-math-v2/实现方案.md', prefix: 'vibe_math_' },
27
+ { tag: 'v3', js: 'vibe-math-v3/vibe-math-v3.js', spec: 'vibe-math-v3/实现方案.md', prefix: 'vibe_math_' },
28
+ { tag: 'v4', js: 'vibe-math-v4/vibe-math-v4.js', spec: 'vibe-math-v4/实现方案.md', prefix: 'vibe_v4_' },
29
+ { tag: 'v5', js: 'vibe-math-v5/vibe-math-v5.js', spec: 'vibe-math-v5/实现方案.md', prefix: 'vibe_v5_' },
30
+ ]
31
+ // Tokens that look like tool names but are FILE names / namespace prose, not tools.
32
+ const NOT_A_TOOL = new Set([
33
+ 'vibe_math_setting.json', 'vibe_math_installed.json', 'vibe_math_lean', 'vibe_math_lean_',
34
+ 'vibe_v4_setting.json', 'vibe_v5_state', 'vibe_v5_state.json', 'vibe_v5_lean', 'vibe_v5_lean_',
35
+ 'vibe_v4_lean', 'vibe_v4_lean_', 'vibe_math_state', 'vibe_math_state.json',
36
+ ])
37
+ const LEAN_PARAMS = ['formalVerify', 'leanCommand', 'leanArgs', 'leanTimeoutMs']
38
+
39
+ const README = read('README.md') || ''
40
+ const findings = []
41
+ const notes = []
42
+ let passed = 0
43
+ const ok = (cond, label, detail) => {
44
+ if (cond) { passed++; return true }
45
+ findings.push(label + (detail ? ' — ' + detail : ''))
46
+ return false
47
+ }
48
+ // The README documents ALL FOUR presets at once, and v2/v3 share the `vibe_math_` prefix, so a
49
+ // repo-wide token is legitimate if ANY preset registers it. The per-preset SPEC is checked strictly
50
+ // against that preset's own registry.
51
+ const ALL_TOOLS = new Set()
52
+ for (const P of PRESETS) {
53
+ const src = read(P.js)
54
+ if (!src) continue
55
+ for (const m of src.matchAll(/registerTool\(\s*'([A-Za-z0-9_]+)'/g)) ALL_TOOLS.add(m[1])
56
+ }
57
+ /** Collect `vibe_*` tokens that are used as TOOL names (not file names such as vibe_math_setting.json). */
58
+ function toolTokens(text) {
59
+ const out = new Set()
60
+ for (const m of text.matchAll(/\b(vibe_(?:math|v4|v5)_[A-Za-z0-9_]+)/g)) {
61
+ const after = text[m.index + m[0].length] || ''
62
+ if (after === '.') continue // a file name, e.g. vibe_math_setting.json
63
+ // A doc may name a tool precisely to say it does NOT exist ("v4 没有 vibe_v4_propose_verify 这个工具",
64
+ // "写了不存在的工具 …"). That is documentation of the fix, not a phantom capability — skip it, or
65
+ // the guard would forbid the very sentence that records the correction.
66
+ const lineStart = text.lastIndexOf('\n', m.index) + 1
67
+ const lineEnd = text.indexOf('\n', m.index)
68
+ const line = text.slice(lineStart, lineEnd === -1 ? text.length : lineEnd)
69
+ if (/没有|不存在|并非|不是工具|未注册|从未注册|无此|does not exist|no such|never registered|not a tool/i.test(line)) continue
70
+ out.add(m[1])
71
+ }
72
+ return out
73
+ }
74
+
75
+ for (const P of PRESETS) {
76
+ const js = read(P.js)
77
+ const spec = read(P.spec)
78
+ if (!js || !spec) { findings.push(P.tag + ': missing plugin or spec file'); continue }
79
+
80
+ const codeTools = new Set([...js.matchAll(/registerTool\(\s*'([A-Za-z0-9_]+)'/g)].map((m) => m[1]))
81
+ ok(codeTools.size > 0, P.tag + ': the plugin registers tools at all')
82
+
83
+ // direction 1 (FAIL): anything the spec names as a tool must exist in THIS preset; anything the
84
+ // README names must exist in at least one preset (the README covers all four).
85
+ for (const [label, text, own] of [['实现方案', spec, true], ['README', README, false]]) {
86
+ for (const t of toolTokens(text)) {
87
+ if (NOT_A_TOOL.has(t)) continue
88
+ if (t.endsWith('_')) continue // a `vibe_x_*` wildcard placeholder
89
+ if (!t.startsWith(P.prefix)) continue
90
+ const known = own ? codeTools.has(t) : ALL_TOOLS.has(t)
91
+ if (!known) {
92
+ findings.push(P.tag + ' [' + label + ']: documents tool ' + t
93
+ + (own ? ' but the plugin never registers it' : ' but NO preset registers it'))
94
+ }
95
+ }
96
+ }
97
+
98
+ // direction 2 (NOTE): registered but not documented anywhere
99
+ const md = spec + '\n' + README
100
+ const undocumented = [...codeTools].filter((t) => !md.includes(t)).sort()
101
+ if (undocumented.length) notes.push(P.tag + ': registered but not named in spec/README: ' + undocumented.join(', '))
102
+
103
+ // the four Lean parameters: documented in spec + README, and accepted by the code
104
+ for (const prm of LEAN_PARAMS) {
105
+ ok(spec.includes(prm), P.tag + ': 实现方案 documents ' + prm)
106
+ ok(README.includes(prm), P.tag + ': README documents ' + prm)
107
+ ok(js.includes(prm), P.tag + ': the plugin accepts ' + prm)
108
+ }
109
+
110
+ // the Lean tools must appear in the spec's tool table AND in the code
111
+ for (const t of [P.prefix + 'lean_run', P.prefix + 'lean_archive', P.prefix + 'lean_lib']) {
112
+ ok(codeTools.has(t), P.tag + ': registers ' + t)
113
+ ok(spec.includes(t), P.tag + ': 实现方案 names ' + t)
114
+ }
115
+
116
+ // the contract §7 requires an ACTIVE stop on timeout: `handle.terminate()`. Relying on the
117
+ // host's `graceMs` alone lets a runaway Lean process linger while the framework reports
118
+ // LEAN_TIMEOUT — three of four presets shipped that way, so this is now guarded statically.
119
+ ok(/terminate\s*\(/.test(js), P.tag + ': the Lean run path actively terminates on timeout (contract §7)')
120
+
121
+ // the contract §8 puts the `require` gate at the ONE choke point that writes a Verified card.
122
+ // A card writer reachable WITHOUT passing a gated function would be a gate bypass, i.e. the
123
+ // framework could conclude a verdict that `require` is supposed to withhold.
124
+ {
125
+ const cfg = {
126
+ v2: { writers: ['writeVerifiedCardIfNeeded', 'writeVerifiedProblemCardIfNeeded'], gate: /formalRequired\s*\(|formalGateOk\s*\(|formalVerdictDeferred\s*\(/ },
127
+ v3: { writers: ['writeVerifiedCardIfChanged', 'writeVerifiedPropositionCardIfNeeded', 'writeVerifiedProblemCardIfNeeded'], gate: /formalBlocksConclusion\s*\(/ },
128
+ v4: { writers: ['writeVerifiedCard'], gate: /formalGateOk\s*\(/ },
129
+ v5: { writers: ['writeVerifiedCard'], gate: /formalGateOk\s*\(/ },
130
+ }[P.tag]
131
+ const lines = js.split(/\r?\n/)
132
+ const fns = []
133
+ for (let i = 0; i < lines.length; i++) {
134
+ const m = /^(\s*)(?:async\s+)?function\s+([A-Za-z0-9_$]+)\s*\(/.exec(lines[i])
135
+ if (m) fns.push({ name: m[2], indent: m[1].length, start: i })
136
+ }
137
+ for (let k = 0; k < fns.length; k++) {
138
+ const f = fns[k]
139
+ let end = lines.length
140
+ for (const g of fns) if (g.start > f.start && g.indent <= f.indent) { end = g.start; break }
141
+ f.body = lines.slice(f.start, end).join('\n')
142
+ }
143
+ const byName = (n) => fns.find((f) => f.name === n)
144
+ for (const w of cfg.writers) {
145
+ const f = byName(w)
146
+ if (!f) { ok(false, P.tag + ' §8: the documented card writer ' + w + ' does not exist'); continue }
147
+ const selfGated = cfg.gate.test(f.body)
148
+ const callers = fns.filter((g) => g !== f && new RegExp('(^|[^A-Za-z0-9_$])' + w + '\\s*\\(').test(g.body))
149
+ const allCallersGatedOrRecursive = callers.length > 0 && callers.every((c) => cfg.gate.test(c.body) || fns.some((d) => cfg.gate.test(d.body) && new RegExp('(^|[^A-Za-z0-9_$])' + c.name + '\\s*\\(').test(d.body)))
150
+ ok(selfGated || allCallersGatedOrRecursive,
151
+ P.tag + ' §8: ' + w + ' is reachable only through a gated function (no gate bypass)',
152
+ 'callers: ' + callers.map((c) => c.name).join(', '))
153
+ }
154
+ }
155
+
156
+ notes.push(P.tag + ': ' + codeTools.size + ' tools registered; spec ' + spec.length + 'B')
157
+ }
158
+
159
+ // cross-preset: the shared contract must name the four parameters too
160
+ const contract = read('docs/formal-verification.md') || ''
161
+ for (const prm of LEAN_PARAMS) ok(contract.includes(prm), 'contract documents ' + prm)
162
+
163
+ const out = { passed, failed: findings.length, findings, notes }
164
+ if (process.argv.includes('--json')) console.log(JSON.stringify(out, null, 2))
165
+ else {
166
+ console.log('-- spec/README ↔ code traceability --')
167
+ for (const n of notes) console.log(' note ' + n)
168
+ console.log('')
169
+ for (const f of findings) console.error(' FAIL ' + f)
170
+ console.log('')
171
+ console.log('TRACEABILITY: ' + passed + ' passed, ' + findings.length + ' failed')
172
+ }
173
+ process.exit(findings.length === 0 ? 0 : 1)