dsh-vibe-math 2.3.12 → 2.3.14

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 (49) hide show
  1. package/README.md +17 -13
  2. package/cordis.patch.yml +1 -1
  3. package/{AUDIT-CHECKLIST.md → docs/AUDIT-CHECKLIST.md} +323 -304
  4. package/docs/COMPAT-AUDIT-ROUND2.md +325 -0
  5. package/docs/generate_framework_diagram_v2.py +114 -0
  6. package/docs/generate_framework_diagram_v3.py +127 -0
  7. package/{RELEASE-NOTES-2.1.0.md → docs/release-notes/RELEASE-NOTES-2.1.0.md} +143 -143
  8. package/{RELEASE-NOTES-2.2.0.md → docs/release-notes/RELEASE-NOTES-2.2.0.md} +266 -266
  9. package/{RELEASE-NOTES-2.2.1.md → docs/release-notes/RELEASE-NOTES-2.2.1.md} +43 -43
  10. package/{RELEASE-NOTES-2.2.2.md → docs/release-notes/RELEASE-NOTES-2.2.2.md} +88 -88
  11. package/{RELEASE-NOTES-2.3.0.md → docs/release-notes/RELEASE-NOTES-2.3.0.md} +207 -207
  12. package/{RELEASE-NOTES-2.3.1.md → docs/release-notes/RELEASE-NOTES-2.3.1.md} +134 -134
  13. package/{RELEASE-NOTES-2.3.10.md → docs/release-notes/RELEASE-NOTES-2.3.10.md} +105 -105
  14. package/{RELEASE-NOTES-2.3.11.md → docs/release-notes/RELEASE-NOTES-2.3.11.md} +57 -57
  15. package/{RELEASE-NOTES-2.3.12.md → docs/release-notes/RELEASE-NOTES-2.3.12.md} +80 -80
  16. package/docs/release-notes/RELEASE-NOTES-2.3.13.md +137 -0
  17. package/docs/release-notes/RELEASE-NOTES-2.3.14.md +83 -0
  18. package/{RELEASE-NOTES-2.3.2.md → docs/release-notes/RELEASE-NOTES-2.3.2.md} +145 -145
  19. package/{RELEASE-NOTES-2.3.3.md → docs/release-notes/RELEASE-NOTES-2.3.3.md} +115 -115
  20. package/{RELEASE-NOTES-2.3.4.md → docs/release-notes/RELEASE-NOTES-2.3.4.md} +69 -69
  21. package/{RELEASE-NOTES-2.3.5.md → docs/release-notes/RELEASE-NOTES-2.3.5.md} +63 -63
  22. package/{RELEASE-NOTES-2.3.6.md → docs/release-notes/RELEASE-NOTES-2.3.6.md} +66 -66
  23. package/{RELEASE-NOTES-2.3.7.md → docs/release-notes/RELEASE-NOTES-2.3.7.md} +59 -59
  24. package/{RELEASE-NOTES-2.3.8.md → docs/release-notes/RELEASE-NOTES-2.3.8.md} +45 -45
  25. package/{RELEASE-NOTES-2.3.9.md → docs/release-notes/RELEASE-NOTES-2.3.9.md} +70 -70
  26. package/docs/test-timing.md +19 -18
  27. package/installer.js +115 -41
  28. package/package.json +43 -37
  29. package/{audit-formal-sensitivity.mjs → tests/audit-formal-sensitivity.mjs} +342 -342
  30. package/{audit-installer-compat.test.mjs → tests/audit-installer-compat.test.mjs} +136 -136
  31. package/tests/audit-installer-policy.test.mjs +261 -0
  32. package/{audit-persona-sensitivity.mjs → tests/audit-persona-sensitivity.mjs} +249 -249
  33. package/{audit-persona-surface.test.mjs → tests/audit-persona-surface.test.mjs} +349 -349
  34. package/{audit-prompt-invariants.mjs → tests/audit-prompt-invariants.mjs} +508 -508
  35. package/{audit-spec-traceability.mjs → tests/audit-spec-traceability.mjs} +193 -193
  36. package/{audit-v5-integrity.mjs → tests/audit-v5-integrity.mjs} +448 -448
  37. package/{audit-v5-sensitivity.mjs → tests/audit-v5-sensitivity.mjs} +384 -384
  38. package/{e2e-v5-round2.test.mjs → tests/e2e-v5-round2.test.mjs} +521 -521
  39. package/{formal-verify-v2.test.mjs → tests/formal-verify-v2.test.mjs} +1315 -1315
  40. package/{formal-verify-v3.test.mjs → tests/formal-verify-v3.test.mjs} +1257 -1257
  41. package/{formal-verify-v4.test.mjs → tests/formal-verify-v4.test.mjs} +1082 -1082
  42. package/{formal-verify-v5.test.mjs → tests/formal-verify-v5.test.mjs} +708 -708
  43. package/{prompt-v5-integrity.test.mjs → tests/prompt-v5-integrity.test.mjs} +3 -3
  44. package/{run-tests.mjs → tests/run-tests.mjs} +121 -118
  45. package/{selfdrive-v5.mjs → tests/selfdrive-v5.mjs} +470 -470
  46. package/vibe-math-v4//345/256/236/347/216/260/346/226/271/346/241/210.md +1 -1
  47. package/vibe-math-v5//345/256/236/347/216/260/346/226/271/346/241/210.md +1 -1
  48. package/vibe-math-v5//346/236/266/346/236/204/345/233/276.md +1 -1
  49. /package/{RELEASE-NOTES-2.0.22.md → docs/release-notes/RELEASE-NOTES-2.0.22.md} +0 -0
@@ -1,1257 +1,1257 @@
1
- // ============================================================
2
- // V3 LEAN FORMAL VERIFICATION SUITE (docs/formal-verification.md)
3
- //
4
- // Asserts the whole contract of the `formalVerify` knob on the v3 preset:
5
- // · 'off' is a TRUE no-op (no Lean text in ANY prompt, no Formal record, no gate)
6
- // · 'encourage' injects the Lean section into the work prompts AND into both verification
7
- // prompts, and — the actual point of the feature — turns the voting prompt into
8
- // a FIDELITY review once a Lean run has passed
9
- // · 'require' withholds a true/false verdict as 未定论 until the object is Lean-passed or
10
- // carries an explicit, reasoned blocker record; then allows it, and the Verified
11
- // card records how strong the result really is
12
- // · the three tools (run / archive / lib) write the right things to the right paths
13
- //
14
- // The Lean toolchain is mocked through the subprocess SERVICE, so the tests exercise the real
15
- // code path (resolveExecutable → spawn → collected stdout → exit code) without requiring Lean.
16
- //
17
- // V3_PLUGIN overrides the plugin under test: a sensitivity probe MUST point this suite at a
18
- // mutated copy, otherwise every probe would exercise the unmutated plugin and stay green.
19
- //
20
- // Run: node formal-verify-v3.test.mjs
21
- // ============================================================
22
- import { mkdtempSync, rmSync, existsSync, readFileSync, readdirSync, mkdirSync, writeFileSync } from 'node:fs'
23
- import { tmpdir } from 'node:os'
24
- import { join, dirname, isAbsolute, resolve as pathResolve } from 'node:path'
25
- import { fileURLToPath } from 'node:url'
26
-
27
- const PLUGIN = process.env.V3_PLUGIN
28
- ? new URL('file:///' + String(process.env.V3_PLUGIN).replace(/\\/g, '/'))
29
- : new URL('./vibe-math-v3/vibe-math-v3.js', import.meta.url)
30
- const HERE = dirname(fileURLToPath(import.meta.url))
31
- // AUDIT-CHECKLIST §2.4: the suite must also keep the INTERACTION TEXT it drove, so a human can
32
- // re-read the prompts the framework really emitted. V3_CORPUS_DIR overrides the destination.
33
- const CORPUS_DIR = process.env.V3_CORPUS_DIR ? pathResolve(process.env.V3_CORPUS_DIR) : join(HERE, 'prompt-corpus-v3')
34
- const WS = mkdtempSync(join(tmpdir(), 'vibe-v3-lean-'))
35
- const VIBE = join(WS, 'VibeMath')
36
- const projRoot = (slug) => join(VIBE, 'Projects', slug)
37
- const readIf = (p) => (existsSync(p) ? readFileSync(p, 'utf8') : '')
38
- const reEsc = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
39
- const verifyRe = (target) => new RegExp('^verifier:r-' + reEsc(target) + '(?:-\\w+)?:\\d+$')
40
-
41
- let passed = 0, failed = 0
42
- const failures = []
43
- const assert = (c, m) => { if (c) { passed++; console.log(' ok - ' + m) } else { failed++; failures.push(m); console.error(' FAIL - ' + m) } }
44
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
45
- const section = (t) => console.log('\n[' + t + ']')
46
-
47
- // ---------------------------------------------------------------
48
- // mock host
49
- // ---------------------------------------------------------------
50
- const listeners = {}
51
- const toolRegs = []
52
- const cmdRegs = []
53
- const spawns = [] // { label, childId, rootId, prompt }
54
- const wakes = [] // { childId, rootId, prompt }
55
- const interrupts = []
56
- const leanRuns = [] // { argv, file, cwd, graceMs }
57
- const terminated = []
58
- const roots = []
59
- let rootSeq = 0
60
- let subprocessAvailable = true
61
- let toolchainAvailable = true
62
- let spawnThrows = false
63
- // Interaction corpus (AUDIT-CHECKLIST §2.4): every prompt the framework actually sent, with the
64
- // workspace path normalised so the dump is deterministic and diffable.
65
- const corpus = []
66
- // Normalise BOTH slash forms. The VibeMath ROOT must be replaced BEFORE the workspace root,
67
- // otherwise `<WS>/VibeMath` would survive as a half-substituted path: the corpus would still leak
68
- // the machine layout and would not be diffable against another checkout.
69
- //
70
- // The PLANNER prompt embeds the raw state brief, whose volatile RUN METADATA would otherwise change
71
- // on every run and make the corpus undiffable (contract §10 item 10 demands byte determinism; the
72
- // same class of bug is recorded in AUDIT-CHECKLIST §2.4 as a real accident): the random plan id in
73
- // the label, epoch-millisecond `at` timestamps, child ids, and the free-slot count. They are run
74
- // metadata, not the text under review, so they are normalised to placeholders.
75
- const scrub = (s) => String(s == null ? '' : s)
76
- .split(VIBE).join('<VIBEMATH>')
77
- .split(VIBE.replace(/\\/g, '/')).join('<VIBEMATH>')
78
- .split(WS).join('<WS>')
79
- .split(WS.replace(/\\/g, '/')).join('<WS>')
80
- .replace(/plan-[0-9a-f]{8}/g, 'plan-<ID>')
81
- .replace(/("at"\s*:\s*)\d{10,16}/g, '$1"<TIME>"')
82
- .replace(/("childId"\s*:\s*")c\d+(")/g, '$1<CHILD>$2')
83
- .replace(/("free_slots"\s*:\s*)\d+/g, '$1<SLOTS>')
84
-
85
- // A fake Lean: a file PASSES unless it still contains `sorry` or the marker `-- FAIL`.
86
- // `-- HANG` simulates a toolchain that never returns (the timeout path).
87
- const subprocess = {
88
- async resolveExecutable(cmd) {
89
- if (!toolchainAvailable) throw new Error('spawn ' + cmd + ' ENOENT')
90
- if (String(cmd) !== 'lean' && String(cmd) !== 'lake') throw new Error('unknown executable ' + cmd)
91
- return String(cmd)
92
- },
93
- spawn(spec) {
94
- const argv = spec.argv || []
95
- const last = String(argv[argv.length - 1] || '')
96
- const isShell = /powershell|cmd\.exe|\/bin\/sh|(^|\/)sh$/i.test(String(argv[0] || '')) || /New-Item|Remove-Item|Move-Item|^mkdir -p/.test(last)
97
- if (isShell) {
98
- // directory shim (v3's runShell: powershell New-Item / POSIX mkdir -p)
99
- if (/New-Item/.test(last)) {
100
- const m = last.match(/-Path\s+(?:'((?:[^']|'')*)'|"((?:[^"]|"")*)")/)
101
- const raw = (m && (m[1] || m[2])) || ''
102
- for (const p of raw.split(',').map((x) => x.replace(/''/g, "'"))) if (p) mkdirSync(p, { recursive: true })
103
- }
104
- if (/^mkdir -p/.test(last)) {
105
- const re = /'((?:[^']|'\\'')*)'/g
106
- let m
107
- while ((m = re.exec(last)) !== null) mkdirSync(m[1].replace(/'\\''/g, "'"), { recursive: true })
108
- }
109
- if (/Remove-Item/.test(last)) {
110
- const m = last.match(/-LiteralPath\s+'((?:[^']|'')*)'/)
111
- if (m) rmSync(m[1].replace(/''/g, "'"), { force: true, recursive: true })
112
- }
113
- return { done: Promise.resolve({ exitCode: 0 }), collected: {} }
114
- }
115
- const file = last
116
- const text = existsSync(file) ? readFileSync(file, 'utf8') : ''
117
- leanRuns.push({ argv: argv.slice(0, -1), file, cwd: spec.cwd, graceMs: spec.graceMs })
118
- if (spawnThrows) throw new Error('spawn ' + String(argv[0]) + ' EPERM')
119
- if (/-- REJECT/.test(text)) {
120
- return {
121
- done: Promise.reject(new Error('child process died before reporting')),
122
- collected: { stdout: { readFrom: () => ({ text: '', nextOffset: 0, lossy: false }) }, stderr: { readFrom: () => ({ text: '', nextOffset: 0, lossy: false }) } },
123
- terminate() {},
124
- }
125
- }
126
- if (/-- HANG/.test(text)) {
127
- return {
128
- done: new Promise(() => {}),
129
- collected: { stdout: { readFrom: () => ({ text: '', nextOffset: 0, lossy: false }) }, stderr: { readFrom: () => ({ text: '', nextOffset: 0, lossy: false }) } },
130
- terminate() { terminated.push(file) },
131
- }
132
- }
133
- const bad = /sorry|-- FAIL/.test(text)
134
- const stdout = bad ? '' : 'ok\n'
135
- const stderr = bad ? 'error: declaration uses sorry\n' : ''
136
- return {
137
- done: Promise.resolve({ exitCode: bad ? 1 : 0, signal: null }),
138
- collected: {
139
- stdout: { readFrom: () => ({ text: stdout, nextOffset: stdout.length, lossy: false }) },
140
- stderr: { readFrom: () => ({ text: stderr, nextOffset: stderr.length, lossy: false }) },
141
- },
142
- terminate() {},
143
- }
144
- },
145
- }
146
-
147
- const ctx = {
148
- get(name) {
149
- if (name === 'subprocess') return subprocessAvailable ? subprocess : undefined
150
- if (name === 'sandboxPolicy') return { resolve() { return { workspaceRoot: WS } } }
151
- return undefined
152
- },
153
- on(e, fn) { (listeners[e] = listeners[e] || []).push(fn) },
154
- effect(fn) { const d = fn(); return () => { if (typeof d === 'function') d() } },
155
- logger: { info() {}, warn() {}, error() {} },
156
- tools: { register(spec) { toolRegs.push(spec); return () => {} } },
157
- commands: { register(spec) { cmdRegs.push(spec); return () => {} } },
158
- subagents: {
159
- list() { return ['spawn'] },
160
- async startContinuable({ label, request }) {
161
- const childId = 'c' + (spawns.length + 1)
162
- const rootId = (request && request.parent && request.parent.id) || ''
163
- const prompt = (request && request.prompt && request.prompt[0] && request.prompt[0].text) || ''
164
- spawns.push({ label, childId, rootId, prompt })
165
- corpus.push({ kind: 'spawn', label: scrub(label), root: rootId, prompt: scrub(prompt) })
166
- return { childId, messageId: 'm' + spawns.length }
167
- },
168
- async sendMessage(parent, childId, blocks) {
169
- const rootId = (parent && parent.id) || ''
170
- const prompt = (blocks && blocks[0] && blocks[0].text) || ''
171
- wakes.push({ childId, rootId, prompt })
172
- const sp = spawns.find((s) => s.childId === childId)
173
- corpus.push({ kind: 'wake', label: scrub(sp ? sp.label : childId), root: rootId, prompt: scrub(prompt) })
174
- return 'w' + wakes.length
175
- },
176
- async followup(parent, childId, blocks) { return await this.sendMessage(parent, childId, blocks) },
177
- interrupt(childId) { interrupts.push(childId) },
178
- },
179
- agents: { roots() { return roots.slice() }, get() { return undefined } },
180
- // DSH 0.1.1 fs API: resolve → { targetKey, displayPath }
181
- fs: {
182
- async resolve(rel, opts) {
183
- const base = (opts && opts.cwd) || WS
184
- const p = (typeof rel === 'string' && isAbsolute(rel)) ? rel.replace(/\//g, '\\') : join(base, ...String(rel).split('/'))
185
- return { targetKey: p, displayPath: p }
186
- },
187
- async stat(t) { return existsSync(t.targetKey) ? { version: 'v1', type: 'file', size: 1 } : undefined },
188
- async readText(t) { return readFileSync(t.targetKey, 'utf8') },
189
- async writeText(t, content) { mkdirSync(dirname(t.targetKey), { recursive: true }); writeFileSync(t.targetKey, content, 'utf8') },
190
- async listDir(t) { if (!existsSync(t.targetKey)) return []; return readdirSync(t.targetKey, { withFileTypes: true }).map((e) => ({ name: e.name, type: e.isDirectory() ? 'directory' : 'file' })) },
191
- },
192
- }
193
-
194
- const mod = await import(PLUGIN.href + '?t=' + Date.now())
195
- ;(mod.default || mod).apply(ctx)
196
-
197
- // ---------------------------------------------------------------
198
- // driving helpers
199
- // ---------------------------------------------------------------
200
- function makeRoot() {
201
- const id = 'sess-' + String.fromCharCode(65 + rootSeq++)
202
- const root = { id, options: { provider: 'mock', model: 'mock-model' }, session: { id, header: { cwd: WS, parentSession: undefined } }, followup() {}, ctx: undefined }
203
- roots.push(root)
204
- return root
205
- }
206
- async function callTool(name, args, agent) {
207
- const spec = toolRegs.find((s) => s.name === name)
208
- if (!spec) throw new Error('no tool ' + name)
209
- return JSON.parse(await spec.execute(args || {}, { agent }))
210
- }
211
- function fireEnd(childId, reply) {
212
- const blocks = reply === undefined ? [] : [{ type: 'text', text: '```json\n' + JSON.stringify(reply) + '\n```' }]
213
- for (const h of (listeners['subagent/end'] || [])) h({ id: childId, runId: 'r', provider: 'spawn', local: true, stopReason: 'completed', lastAssistantMessage: blocks })
214
- }
215
- const firedChildren = new Set()
216
- // Spawns created before a restart belong to a task the restart discarded; they are never a valid
217
- // target for a later round (their onChildEnd has no agentRegistry entry any more). The floor keeps
218
- // `unfiredVerifiers` from selecting them.
219
- const spawnFloor = {}
220
- const markFloor = (root) => { spawnFloor[root.id] = spawns.length }
221
- const spawnOf = (root, prefix) => spawns.filter((s) => s.rootId === root.id && s.label.startsWith(prefix))
222
- const lastSpawn = (root, prefix) => spawnOf(root, prefix).slice(-1)[0]
223
- const unfiredVerifiers = (root, re) => spawns.filter((s, i) => s.rootId === root.id && (spawnFloor[root.id] || 0) <= i && re.test(s.label) && !firedChildren.has(s.childId))
224
- const promptText = (root) => spawns.filter((s) => s.rootId === root.id).map((s) => s.prompt).join('\n') + '\n' + wakes.filter((w) => w.rootId === root.id).map((w) => w.prompt).join('\n')
225
-
226
- /** Parameters every verification scenario uses. A high concurrency cap keeps the fallback
227
- * scheduler from starving a later object behind a pile of unfired mock verifiers. */
228
- const VPARAMS = { plannerEnabled: false, verifierCount: 2, debateMaxRounds: 1, maxParallelThreshold: 64, tickIntervalMs: 200 }
229
-
230
- /** Fire the one in-flight forced planner with an empty plan (an empty plan schedules a tick). */
231
- async function pump(root) {
232
- const pending = spawns.filter((s) => s.rootId === root.id && s.label.startsWith('planner:') && !firedChildren.has(s.childId)).slice(-1)[0]
233
- if (pending) { firedChildren.add(pending.childId); fireEnd(pending.childId, { summary: 'noop', plan: [] }); return }
234
- try { await callTool('vibe_math_plan', { force: true }, root) } catch (e) { /* not running / gated */ }
235
- }
236
- /** Poll `pred`, nudging the scheduler along with an empty forced plan (the 1s tick timer is the fallback). */
237
- async function drive(root, pred, label, timeoutMs) {
238
- const deadline = Date.now() + (timeoutMs || 15000)
239
- while (Date.now() < deadline) {
240
- if (pred()) return true
241
- await pump(root)
242
- await sleep(80)
243
- }
244
- if (pred()) return true
245
- console.error(' .. drive timed out: ' + label)
246
- return false
247
- }
248
- /** Fire the next `results.length` verifiers of one object (any of its candidate rIds). */
249
- async function runVerifyRound(root, target, results, timeoutMs) {
250
- const re = verifyRe(target)
251
- const ok = await drive(root, () => unfiredVerifiers(root, re).length >= results.length, 'verifiers for r-' + target, timeoutMs)
252
- if (!ok) return null
253
- const un = unfiredVerifiers(root, re).slice(0, results.length)
254
- for (let i = 0; i < un.length; i++) { firedChildren.add(un[i].childId); fireEnd(un[i].childId, { Result: results[i], Reason: 'mock 裁决 ' + results[i] }) }
255
- await sleep(220)
256
- return un
257
- }
258
- /** Abort + restart: gives the next verification a FRESH task, so a prompt is guaranteed to be
259
- * constructed after whatever changed in between (mode switch, archived proof, …). */
260
- async function restart(root) {
261
- await callTool('vibe_math_abort', {}, root)
262
- await callTool('vibe_math_start', {}, root)
263
- markFloor(root)
264
- }
265
-
266
- console.log('-- V3 Lean formal verification --')
267
- console.log('plugin under test: ' + PLUGIN.href)
268
-
269
- // ===============================================================
270
- // 1. 'off' is a true no-op
271
- // ===============================================================
272
- section("1 'off' (default) is a true no-op")
273
- const RA = makeRoot()
274
- await callTool('vibe_math_new_project', { name: 'lean-off' }, RA)
275
- await callTool('vibe_math_set_params', Object.assign({}, VPARAMS), RA)
276
- await callTool('vibe_math_add_proposition', { id: 'p-off', 概述: '关模式下的普通命题', 概率: 0.6, 分类: '数论' }, RA)
277
- await callTool('vibe_math_start', {}, RA)
278
- const offRound = await runVerifyRound(RA, 'p-off', [1, 1])
279
- assert(offRound !== null && offRound.length === 2, 'off: two independent verifiers were asked (投票流程照常)')
280
- const offProj = projRoot('lean-off')
281
- assert(await drive(RA, () => existsSync(join(offProj, 'Verified', '命题', 'p-off.md')), 'off Verified card'), "'off' still finalizes on a unanimous boolean vote with NO Lean artifact")
282
- {
283
- const st = await callTool('vibe_math_status', {}, RA)
284
- assert(st.params.formalVerify === 'off', "the default is 'off' (got " + st.params.formalVerify + ')')
285
- const all = promptText(RA)
286
- assert(!/Lean/.test(all), 'no prompt mentions Lean in off mode')
287
- assert(!/形式化/.test(all), 'no prompt mentions 形式化 in off mode')
288
- assert(!/\[形式化\]/.test(all), 'the [形式化] announcement line is absent in off mode')
289
- }
290
- assert(!/形式化/.test(readIf(join(offProj, 'Verified', '命题', 'p-off.md'))), 'the Verified card carries no formal line in off mode')
291
- assert(!existsSync(join(offProj, 'Formal', 'Index.md')), 'no Formal/Index.md is produced in off mode (no formal record)')
292
- assert(!existsSync(join(offProj, 'State', 'formal.json')), 'no State/formal.json is produced in off mode')
293
- {
294
- const st = await callTool('vibe_math_status', {}, RA)
295
- assert(st.formal.mode === 'off' && st.formal.objects.length === 0, 'status reports mode=off with zero formal objects')
296
- }
297
- // the tools still EXIST in off mode (static registration), they are just never advertised
298
- assert(!!toolRegs.find((t) => t.name === 'vibe_math_lean_run') && !!toolRegs.find((t) => t.name === 'vibe_math_lean_archive') && !!toolRegs.find((t) => t.name === 'vibe_math_lean_lib'),
299
- 'the three Lean tools are registered in every mode (registration is static)')
300
-
301
- // ★ The mode switch must be REACHABLE THROUGH THE TOOL SCHEMA (2.3.2 defect D1) ──────────────
302
- // Every tool schema here is closed (`additionalProperties:false`), so a key the schema does not
303
- // advertise is REJECTED by any schema-validating provider. v3 shipped 2.3.0/2.3.1 with all four Lean
304
- // parameters missing from the set-params schema while every assertion in this file stayed green —
305
- // because the suite calls the handler DIRECTLY and never inspects the registered schema. The feature
306
- // could not be switched on at all through the tool interface.
307
- {
308
- const setSpec = toolRegs.find((t) => t.name === 'vibe_math_set_params')
309
- assert(!!setSpec, "vibe_math_set_params is registered")
310
- assert(setSpec.parameters && setSpec.parameters.type === 'object' && setSpec.parameters.additionalProperties === false,
311
- '★ vibe_math_set_params publishes a CLOSED object schema (an unlisted key is rejected, so the schema IS the contract)')
312
- for (const k of ['formalVerify', 'leanCommand', 'leanArgs', 'leanTimeoutMs']) {
313
- assert(Object.prototype.hasOwnProperty.call(setSpec.parameters.properties, k),
314
- '★ the registered schema advertises ' + k + ' (every other surface documents it; a schema that omits it makes the switch unreachable)')
315
- }
316
- assert(JSON.stringify(setSpec.parameters.properties.formalVerify.enum) === JSON.stringify(['off', 'encourage', 'require']),
317
- 'the schema narrows formalVerify to the three real modes (a typo must not be a fourth)')
318
- }
319
-
320
- // A stray `formal` reply in OFF mode must be INERT (finding #1): the absorber is mode-gated, and the
321
- // reply contract does not offer the field in off mode. The TOOLS stay usable on purpose.
322
- {
323
- const RB0 = makeRoot()
324
- await callTool('vibe_math_new_project', { name: 'lean-off-reply' }, RB0)
325
- await callTool('vibe_math_set_params', Object.assign({}, VPARAMS), RB0)
326
- await callTool('vibe_math_add_proposition', { id: 'p-offr', 概述: '关模式下的回执注入测试', 概率: 0.6, 分类: '数论' }, RB0)
327
- await callTool('vibe_math_start', {}, RB0)
328
- const re0 = verifyRe('p-offr')
329
- const ok0 = await drive(RB0, () => unfiredVerifiers(RB0, re0).length >= 1, 'off-reply verifier')
330
- assert(ok0, 'off mode: a verifier wake exists to carry the stray formal reply')
331
- const un0 = unfiredVerifiers(RB0, re0).slice(0, 1)
332
- if (un0.length) {
333
- firedChildren.add(un0[0].childId)
334
- fireEnd(un0[0].childId, { Result: 0.5, Reason: '普通评审', formal: { target: 'p-offr', decision: 'defect', note: '不应被记录' } })
335
- }
336
- await sleep(220)
337
- const pj0 = projRoot('lean-off-reply')
338
- assert(!existsSync(join(pj0, 'State', 'formal.json')), '★ a stray `formal` reply in off mode writes NO State/formal.json')
339
- const st0 = await callTool('vibe_math_status', {}, RB0)
340
- assert(st0.formal.objects.length === 0, '★ and records no formal object')
341
- }
342
-
343
- // ===============================================================
344
- // 2. parameter validation + runtime switching
345
- // ===============================================================
346
- section('2 parameter validation and runtime switching')
347
- const RB = makeRoot()
348
- await callTool('vibe_math_new_project', { name: 'lean-params' }, RB)
349
- const bad = await callTool('vibe_math_set_params', { formalVerify: 'banana' }, RB)
350
- assert(bad.params.formalVerify === 'off', "an unknown mode degrades to 'off', never to a stronger mode (got " + bad.params.formalVerify + ')')
351
- const bad2 = await callTool('vibe_math_set_params', { formalVerify: 'REQUIRE' }, RB)
352
- assert(bad2.params.formalVerify === 'off', 'the mode is matched exactly (a case typo cannot force formalization)')
353
- const enc = await callTool('vibe_math_set_params', { formalVerify: 'encourage' }, RB)
354
- assert(enc.params.formalVerify === 'encourage', "'encourage' is accepted")
355
- const req = await callTool('vibe_math_set_params', { formalVerify: 'require', leanTimeoutMs: -5, leanCommand: ' ' }, RB)
356
- assert(req.params.formalVerify === 'require', "'require' is accepted")
357
- assert(req.params.leanTimeoutMs === 120000, 'a non-positive leanTimeoutMs falls back to the default (' + req.params.leanTimeoutMs + ')')
358
- assert((await callTool('vibe_math_set_params', { leanTimeoutMs: 0 }, RB)).params.leanTimeoutMs === 120000, 'leanTimeoutMs=0 also falls back to the default')
359
- assert(req.params.leanCommand === 'lean', 'a blank leanCommand falls back to "lean"')
360
- const t5 = await callTool('vibe_math_set_params', { leanTimeoutMs: 5000 }, RB)
361
- assert(t5.params.leanTimeoutMs === 5000, 'a positive leanTimeoutMs is accepted (got ' + t5.params.leanTimeoutMs + ')')
362
- const arrBad = await callTool('vibe_math_set_params', { leanArgs: 'not-an-array' }, RB)
363
- assert(Array.isArray(arrBad.params.leanArgs) && arrBad.params.leanArgs.length === 0, 'a non-array leanArgs falls back to []')
364
- await callTool('vibe_math_set_params', { leanCommand: 'lake', leanArgs: ['env', 'lean'] }, RB)
365
- const stL = await callTool('vibe_math_status', {}, RB)
366
- assert(stL.params.leanCommand === 'lake' && stL.params.leanArgs.join(' ') === 'env lean', 'leanCommand/leanArgs are settable (lake env lean)')
367
- {
368
- const setup = await callTool('vibe_math_setup', {}, RB)
369
- const names = setup.parameters.map((p) => p.name)
370
- assert(names.indexOf('formalVerify') !== -1 && names.indexOf('leanCommand') !== -1 && names.indexOf('leanArgs') !== -1 && names.indexOf('leanTimeoutMs') !== -1,
371
- 'the settings schema surfaces all four Lean parameters')
372
- const f = setup.parameters.find((p) => p.name === 'formalVerify')
373
- assert(f.default === 'off' && f.current === 'require', 'the schema carries the default (off) and the current value (require)')
374
- const tmpl = await callTool('vibe_math_template', { where: 'project' }, RB)
375
- const tj = readIf(join(projRoot('lean-params'), 'vibe_math_setting.json'))
376
- assert(tmpl.ok === true && /"formalVerify": "off"/.test(tj) && /"leanArgs": \[\]/.test(tj), 'the generated settings template documents the Lean parameters with their defaults')
377
- assert(/formalVerify — /.test(tj), 'the template carries the human-readable parameter description as a comment')
378
- }
379
-
380
- // ===============================================================
381
- // 3. 'encourage' injection into the WORK prompts
382
- // ===============================================================
383
- section("3 'encourage' injects 顺手形式化 into solver / explorer / method-keeper prompts")
384
- const RC = makeRoot()
385
- await callTool('vibe_math_new_project', { name: 'lean-work' }, RC)
386
- await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'encourage', methodKeepEvery: 1 }), RC)
387
- await callTool('vibe_math_add_problem', { id: 'qE', description: '证明 log 2 是无理数', priority: 0 }, RC)
388
- await callTool('vibe_math_start', {}, RC)
389
- assert(await drive(RC, () => !!lastSpawn(RC, 'explorer:qE'), 'explorer:qE'), 'fallback scheduler spawned explorer:qE')
390
- {
391
- const p = lastSpawn(RC, 'explorer:qE').prompt
392
- assert(/【顺手形式化(鼓励)】/.test(p), 'the explorer work prompt carries the 顺手形式化 line')
393
- assert(/vibe_math_lean_archive kind='def'/.test(p), 'the work prompt points at the archive tool for reusable definitions')
394
- assert(/vibe_math_lean_lib 查重/.test(p), 'the work prompt tells agents to check the reuse library first')
395
- assert(/形式化回执/.test(p) && /"decision":"used\|blocked\|defect"/.test(p), '★ the work-round reply contract also advertises the formal field, defect included (契约 §6.3)')
396
- }
397
- fireEnd(lastSpawn(RC, 'explorer:qE').childId, { meta: { kind: 'directions', qid: 'qE', formal: { target: 'qE', decision: 'blocked', note: '需要先形式化连分数收敛定理' }, directions: [{ id: 'd1', title: '连分数法', method: 'e 的连分数', core_assumption: '', feasibility: 0.7 }] } })
398
- // Answer EVERY explorer the fallback scheduler dispatches (it re-derives when a direction looks
399
- // unattended) until the solver for d1 appears — otherwise the retry cap can stall the project.
400
- for (let guard = 0; guard < 40 && !lastSpawn(RC, 'solver:qE:d1'); guard++) {
401
- const ex = spawns.filter((s) => s.rootId === RC.id && s.label.startsWith('explorer:qE') && !firedChildren.has(s.childId)).slice(-1)[0]
402
- if (ex) {
403
- firedChildren.add(ex.childId)
404
- fireEnd(ex.childId, { meta: { kind: 'directions', qid: 'qE', directions: [{ id: 'd1', title: '连分数法', method: 'e 的连分数', core_assumption: '', feasibility: 0.7 }] } })
405
- }
406
- await pump(RC)
407
- await sleep(80)
408
- }
409
- assert(!!lastSpawn(RC, 'solver:qE:d1'), 'solver spawned for direction d1')
410
- assert(/【顺手形式化(鼓励)】/.test(lastSpawn(RC, 'solver:qE:d1').prompt), 'the solver work prompt carries the 顺手形式化 line')
411
- {
412
- // the explorer's `meta.formal` judgement is recorded even though it never called a Lean tool
413
- const st = await callTool('vibe_math_status', {}, RC)
414
- assert(st.formal.blocked.indexOf('qE') !== -1, '★ an explorer `meta.formal` judgement is recorded (no Lean tool call needed)')
415
- assert(/- 形式化: 阻塞(/.test(readIf(join(projRoot('lean-work'), 'Problems', 'qE.md'))), 'and it lands on the problem card anchor')
416
- }
417
- fireEnd(lastSpawn(RC, 'solver:qE:d1').childId, { status: 'continue', survival_probability: 0.6, formal: { target: 'd1-lemma', decision: 'used', file: 'Formal/d1-lemma.lean' }, new_inventions: [{ 类型: '工具', 标题: '连分数估值工具', 内容描述: '控制收敛速度', 是否已入库: false }] })
418
- await sleep(250)
419
- {
420
- const st = await callTool('vibe_math_status', {}, RC)
421
- assert(st.formal.objects.some((o) => o.target === 'd1-lemma' && o.status === 'attempted'), 'a solver top-level `formal.decision=used` reply records the object as attempted')
422
- }
423
- assert(await drive(RC, () => !!lastSpawn(RC, 'method-keeper'), 'method-keeper'), 'method keeper spawned for the pending invention')
424
- {
425
- const p = lastSpawn(RC, 'method-keeper').prompt
426
- assert(/【顺手形式化(鼓励)】/.test(p), 'the method-keeper prompt carries the 顺手形式化 line')
427
- assert(/【方法沉淀 × Lean 形式化】/.test(p), '★ the method keeper is told to ALSO sediment reusable Lean definitions/lemmas')
428
- assert(/kind='lemma'/.test(p) && /Proved/.test(p), 'and where the proved lemmas go')
429
- }
430
- await callTool('vibe_math_abort', {}, RC)
431
- assert((await callTool('vibe_math_status', {}, RC)).running === false, 'work-prompt scenario aborted (keeps later scenarios deterministic)')
432
-
433
- // ===============================================================
434
- // 4. 'encourage' injection into BOTH verification prompts + the fidelity switch
435
- // ===============================================================
436
- section("4 'encourage' reaches the review prompt and the debate prompt")
437
- const RD = makeRoot()
438
- await callTool('vibe_math_new_project', { name: 'lean-verify' }, RD)
439
- await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'encourage', debateMaxRounds: 2 }), RD)
440
- await callTool('vibe_math_add_proposition', { id: 'p-enc', 概述: '鼓励模式下的忠实性审查', 概率: 0.6, 分类: '数论' }, RD)
441
- await callTool('vibe_math_start', {}, RD)
442
- const encBatch = await runVerifyRound(RD, 'p-enc', [0.9, 0.95])
443
- assert(encBatch !== null, 'encourage: the first review round was asked')
444
- if (encBatch) {
445
- const vp = encBatch.map((s) => s.prompt).join('\n')
446
- assert(/【Lean 形式化验证(鼓励模式)】/.test(vp), 'the review prompt explains the Lean mode')
447
- assert(/一旦 Lean 通过,你唯一需要确认的就是忠实性/.test(vp), 'the review prompt states that a passing Lean run shrinks the question to fidelity')
448
- assert(/实现难度/.test(vp), 'the review prompt asks for the implementation-difficulty judgement')
449
- assert(/可以不做,但请在回执的 formal 字段写明难度判断/.test(vp), "'encourage' explicitly allows skipping (with a recorded judgement)")
450
- assert(/"formal":/.test(vp) && /"decision":"used\|blocked\|defect"/.test(vp), 'the reply contract documents the formal field (defect included)')
451
- assert(/vibe_math_lean_run/.test(vp) && /vibe_math_lean_archive/.test(vp) && /vibe_math_lean_lib/.test(vp), 'the prompt names the three v3 Lean tools')
452
- assert(/Formal\/(相对项目根)/.test(vp) && /VibeMath\/Formal\/Lib/.test(vp), 'the prompt states the path layout')
453
- }
454
- // a non-consensus round moves to the public debate, whose prompt must carry the same injection
455
- assert(await drive(RD, () => wakes.some((w) => w.rootId === RD.id && /交流群/.test(w.prompt)), 'debate prompt'), 'a non-consensus round moved to the debate')
456
- {
457
- const dp = wakes.filter((w) => w.rootId === RD.id).map((w) => w.prompt).join('\n')
458
- assert(/【Lean 形式化验证(鼓励模式)】/.test(dp), 'the debate prompt names the mode')
459
- assert(/一旦 Lean 通过,你唯一需要确认的就是忠实性|你不需要重新检查推导/.test(dp), 'the debate prompt carries the Lean block too')
460
- assert(/"formal":/.test(dp), 'the debate reply contract carries the formal field')
461
- }
462
- // finish the debate: a unanimous round concludes
463
- if (encBatch) for (const b of encBatch) fireEnd(b.childId, { Result: 1, Reason: 'mock 第二轮一致' })
464
- assert(await drive(RD, () => existsSync(join(projRoot('lean-verify'), 'Verified', '命题', 'p-enc.md')), 'p-enc verified'), 'the debate finished and the object was verified')
465
-
466
- // ===============================================================
467
- // 5. lean_run executes through the subprocess service and reports honestly
468
- // ===============================================================
469
- section('5 lean_run executes through the subprocess service and reports honestly')
470
- const RE = makeRoot()
471
- await callTool('vibe_math_new_project', { name: 'lean-tools' }, RE)
472
- await callTool('vibe_math_set_params', { formalVerify: 'encourage' }, RE)
473
- await callTool('vibe_math_add_proposition', { id: 'p-tool', 概述: '工具实验命题', 概率: 0.6, 分类: '数论' }, RE)
474
- const toolProj = projRoot('lean-tools')
475
- mkdirSync(join(toolProj, 'Formal'), { recursive: true })
476
- writeFileSync(join(toolProj, 'Formal', 'good.lean'), 'theorem t : 1 = 1 := rfl\n', 'utf8')
477
- writeFileSync(join(toolProj, 'Formal', 'bad.lean'), 'theorem t : 1 = 2 := by sorry\n', 'utf8')
478
- writeFileSync(join(toolProj, 'Formal', 'hang.lean'), '-- HANG\ntheorem t : 1 = 1 := rfl\n', 'utf8')
479
- {
480
- const runGood = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean', target: 'p-tool' }, RE)
481
- assert(runGood.ok === true && runGood.exitCode === 0, 'a file with no sorry runs green (' + JSON.stringify({ ok: runGood.ok, exitCode: runGood.exitCode }) + ')')
482
- assert(/ok/.test(runGood.stdout), 'the compiler stdout is returned')
483
- const last = leanRuns[leanRuns.length - 1]
484
- assert(last.cwd.replace(/\\/g, '/') === toolProj.replace(/\\/g, '/'), 'the toolchain runs with the PROJECT root as cwd')
485
- assert(last.argv.join(' ') === 'lean', 'by default the argv is just the executable (got ' + last.argv.join(' ') + ')')
486
- assert(last.graceMs === 120000, 'the default leanTimeoutMs is passed down as graceMs (' + last.graceMs + ')')
487
- }
488
- {
489
- const st = await callTool('vibe_math_status', {}, RE)
490
- const o = st.formal.objects.find((x) => x.target === 'p-tool')
491
- assert(!!o && o.status === 'attempted', 'lean_run with target records the object as attempted (not passed)')
492
- assert(!!o.run && o.run.ok === true, 'the run result is recorded on the object')
493
- const card = readIf(join(toolProj, 'Propos', '数论', 'p-tool.md'))
494
- assert(/- 形式化: 已尝试未通过/.test(card), '★ the object card anchor block gains `- 形式化: <状态>` alongside 状态/概率')
495
- assert(/\n- ID: p-tool\n/.test(card) && /\n- 状态: 未定论\n/.test(card) && /\n- 概率: 0.6\n/.test(card), 'the pre-existing anchors are untouched (the scheduler parser keeps working)')
496
- }
497
- {
498
- const runBad = await callTool('vibe_math_lean_run', { file: 'Formal/bad.lean' }, RE)
499
- assert(runBad.ok === false && runBad.exitCode === 1, 'a file that still uses sorry reports a red run')
500
- assert(/sorry/.test(runBad.stderr), 'the compiler output is returned verbatim (' + JSON.stringify(runBad.stderr).slice(0, 60) + ')')
501
- assert(/修复后重跑/.test(runBad.hint || ''), 'a genuine compile failure still points at the compiler output (the hint is failure-code aware, not blanket)')
502
- }
503
- {
504
- const runMissing = await callTool('vibe_math_lean_run', { file: 'Formal/nope.lean' }, RE)
505
- assert(runMissing.ok === false && runMissing.code === 'V3_NOT_FOUND', 'a missing file is refused with a typed code')
506
- }
507
- {
508
- // The guard's boundary is the VibeMath ROOT, not the project: the global reuse library
509
- // deliberately lives at <VibeMath>/Formal/{Lib,Proved}, so climbing out of the project but
510
- // staying inside VibeMath must remain legal (it just fails as a missing file).
511
- const inside = await callTool('vibe_math_lean_run', { file: '../../Formal/Lib/x.lean' }, RE)
512
- assert(inside.code === 'V3_NOT_FOUND', 'climbing out of the project but staying inside VibeMath is allowed (the global library lives there)')
513
- const esc1 = await callTool('vibe_math_lean_run', { file: '../../../evil.lean' }, RE)
514
- assert(esc1.ok === false && esc1.code === 'V3_INVALID_ARGUMENT', '★ a traversal that climbs ABOVE the VibeMath root is refused')
515
- const esc2 = await callTool('vibe_math_lean_run', { file: 'Formal/../../../../../../evil.lean' }, RE)
516
- assert(esc2.ok === false && esc2.code === 'V3_INVALID_ARGUMENT', 'a deeper traversal is refused too')
517
- const esc3 = await callTool('vibe_math_lean_run', { file: '/etc/evil.lean' }, RE)
518
- assert(esc3.ok === false && esc3.code === 'V3_INVALID_ARGUMENT', 'an unrelated absolute path is refused')
519
- const notLean = await callTool('vibe_math_lean_run', { file: 'Formal/good.txt' }, RE)
520
- assert(notLean.ok === false && notLean.code === 'V3_INVALID_ARGUMENT', 'only .lean files can be executed')
521
- const noFile = await callTool('vibe_math_lean_run', {}, RE)
522
- assert(noFile.ok === false && noFile.code === 'V3_INVALID_ARGUMENT', 'a missing file argument is refused')
523
- }
524
- {
525
- toolchainAvailable = false
526
- const runNoTc = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean' }, RE)
527
- assert(runNoTc.ok === false && runNoTc.code === 'LEAN_NOT_FOUND', 'a missing toolchain returns LEAN_NOT_FOUND instead of crashing')
528
- assert(/仍可把形式化代码写下来归档/.test(runNoTc.message), 'the failure explains the graceful degradation')
529
- assert(/本宿主无法执行 Lean(LEAN_NOT_FOUND)/.test(runNoTc.hint || '') && !/编译器输出修复后重跑/.test(runNoTc.hint || ''),
530
- '★ the failure hint never tells the agent to fix compiler output that does not exist — it points at the archive + explicit-blocker way out (§6 hard requirement 4)')
531
- toolchainAvailable = true
532
- }
533
- {
534
- subprocessAvailable = false
535
- const runNoSub = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean' }, RE)
536
- assert(runNoSub.ok === false && runNoSub.code === 'NO_SUBPROCESS', 'a host without the subprocess service returns NO_SUBPROCESS')
537
- assert(/本宿主无法执行 Lean(NO_SUBPROCESS)/.test(runNoSub.hint || '') && /vibe_math_lean_archive/.test(runNoSub.hint || ''),
538
- '★ the NO_SUBPROCESS hint names the way out with the FULL tool name (no retry loop on an impossible run)')
539
- subprocessAvailable = true
540
- }
541
- {
542
- const runHang = await callTool('vibe_math_lean_run', { file: 'Formal/hang.lean', timeout_ms: 1000 }, RE)
543
- assert(runHang.ok === false && runHang.code === 'LEAN_TIMEOUT' && runHang.timedOut === true, '★ a hanging toolchain returns LEAN_TIMEOUT instead of wedging the scheduler')
544
- assert(terminated.some((f) => /hang\.lean$/.test(f)), '★ the timeout path calls handle.terminate()')
545
- }
546
- {
547
- spawnThrows = true
548
- const runSpawn = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean' }, RE)
549
- assert(runSpawn.ok === false && runSpawn.code === 'LEAN_SPAWN_FAILED', 'a spawn failure is reported as LEAN_SPAWN_FAILED instead of throwing')
550
- spawnThrows = false
551
- writeFileSync(join(toolProj, 'Formal', 'reject.lean'), '-- REJECT\ntheorem t : 1 = 1 := rfl\n', 'utf8')
552
- const runReject = await callTool('vibe_math_lean_run', { file: 'Formal/reject.lean' }, RE)
553
- assert(runReject.ok === false && runReject.code === 'LEAN_RUN_FAILED', 'a rejecting handle.done is reported as LEAN_RUN_FAILED instead of throwing into the loop')
554
- }
555
- {
556
- await callTool('vibe_math_set_params', { leanCommand: 'lake', leanArgs: ['env', 'lean'] }, RE)
557
- const runLake = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean' }, RE)
558
- assert(runLake.ok === true, 'lake env lean works through leanCommand/leanArgs')
559
- assert(leanRuns[leanRuns.length - 1].argv.join(' ') === 'lake env lean', 'the argv is [exe, ...leanArgs, file] (got ' + leanRuns[leanRuns.length - 1].argv.join(' ') + ')')
560
- await callTool('vibe_math_set_params', { leanCommand: 'lean', leanArgs: [] }, RE)
561
- }
562
-
563
- // ===============================================================
564
- // 6. lean_archive: def / lemma / proof / blocked → the right paths + indexes
565
- // ===============================================================
566
- section('6 lean_archive writes the contract paths and rebuilds the indexes')
567
- const libPath = join(VIBE, 'Formal', 'Lib')
568
- const provedPath = join(VIBE, 'Formal', 'Proved')
569
- {
570
- const defRes = await callTool('vibe_math_lean_archive', { kind: 'def', name: 'ZMod5', content: 'def ZMod5 := Fin 5\n' }, RE)
571
- assert(defRes.ok === true && defRes.file === 'Formal/Lib/ZMod5.lean', 'a reusable definition is archived to the global lib (' + defRes.file + ')')
572
- assert(existsSync(join(libPath, 'ZMod5.lean')), '★ the definition exists under VibeMath/Formal/Lib/ (cross-project, NOT inside the project)')
573
- assert(!existsSync(join(toolProj, 'Formal', 'Lib', 'ZMod5.lean')), 'it is NOT duplicated inside the project tree')
574
- assert(defRes.run && defRes.run.ok === true, 'the reusable definition is executed on archive (run defaults to true)')
575
- const libIdx = readIf(join(libPath, 'Index.md'))
576
- assert(/\| 名称 \| 文件 \| 类别 \| 摘要 \| 最近运行 \|/.test(libIdx), 'Lib/Index.md uses the contract columns')
577
- assert(/ZMod5/.test(libIdx) && /Lib\/ZMod5\.lean/.test(libIdx) && /\| ok \|/.test(libIdx), 'Lib/Index.md lists the new definition with its run result')
578
- assert(!/ZMod5/.test(readIf(join(toolProj, 'Formal', 'Index.md'))), 'the global definition does not pollute the project formal index')
579
- }
580
- {
581
- const lemRes = await callTool('vibe_math_lean_archive', { kind: 'lemma', name: 'sq_odd', content: 'import Mathlib\n\ntheorem sq_odd (n : Nat) : Odd (n*n) → Odd n := by omega\n' }, RE)
582
- assert(lemRes.ok === true && lemRes.file === 'Formal/Proved/sq_odd.lean', 'a lemma is archived to Proved/')
583
- assert(existsSync(join(provedPath, 'sq_odd.lean')), 'the lemma exists under VibeMath/Formal/Proved/')
584
- const provedIdx = readIf(join(provedPath, 'Index.md'))
585
- assert(/\| 名称 \| 文件 \| 陈述 \| 依赖 \| 最近运行 \|/.test(provedIdx), 'Proved/Index.md uses the contract columns')
586
- assert(/sq_odd/.test(provedIdx) && /Mathlib/.test(provedIdx), 'Proved/Index.md lists the lemma and its imports as 依赖')
587
- }
588
- {
589
- const noRun = await callTool('vibe_math_lean_archive', { kind: 'def', name: 'NoRun', content: 'def NoRun := 1\n', run: false }, RE)
590
- assert(noRun.ok === true && noRun.run === undefined, 'run=false archives WITHOUT executing (no toolchain needed)')
591
- }
592
- {
593
- const noName = await callTool('vibe_math_lean_archive', { kind: 'def', content: 'def x := 1\n' }, RE)
594
- assert(noName.ok === false && noName.code === 'V3_INVALID_ARGUMENT', 'archiving a definition without a name is refused')
595
- const badKind = await callTool('vibe_math_lean_archive', { kind: 'nonsense' }, RE)
596
- assert(badKind.ok === false && badKind.code === 'V3_INVALID_ARGUMENT', 'an unknown archive kind is refused')
597
- const noTarget = await callTool('vibe_math_lean_archive', { kind: 'proof', content: 'theorem x : 1 = 1 := rfl\n' }, RE)
598
- assert(noTarget.ok === false && noTarget.code === 'V3_INVALID_ARGUMENT', 'kind=proof without a target is refused')
599
- const noBody = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-x' }, RE)
600
- assert(noBody.ok === false && noBody.code === 'V3_INVALID_ARGUMENT', 'kind=proof without content/from is refused')
601
- const badFrom = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-x', from: '../../../evil.lean' }, RE)
602
- assert(badFrom.ok === false && badFrom.code === 'V3_INVALID_ARGUMENT', 'kind=proof with an out-of-tree from is refused')
603
- }
604
- {
605
- // a green proof → passed + Verified/Lean (the archived proof lives next to the conclusion)
606
- const arc = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-proof', content: 'theorem p_proof : 3 * 1 ^ 2 - 2 = (1:Nat) ^ 2 := by decide\n' }, RE)
607
- assert(arc.ok === true && arc.passed === true, 'the proof is archived and passes (' + JSON.stringify({ ok: arc.ok, passed: arc.passed }) + ')')
608
- assert(arc.file === 'Formal/p-proof.lean', 'the working file is Formal/<target>.lean')
609
- assert(arc.proof === 'Verified/Lean/p-proof.lean', 'the archived proof path is Verified/Lean/<target>.lean')
610
- assert(existsSync(join(toolProj, 'Formal', 'p-proof.lean')), 'the working file exists on disk')
611
- assert(existsSync(join(toolProj, 'Verified', 'Lean', 'p-proof.lean')), '★ the proof is archived under Verified/Lean/ as the proof of that object')
612
- const st = await callTool('vibe_math_status', {}, RE)
613
- assert(st.formal.passed.indexOf('p-proof') !== -1, 'status reports the object as Lean-passed')
614
- const idx = readIf(join(toolProj, 'Formal', 'Index.md'))
615
- assert(/# Lean 形式化索引/.test(idx) && /p-proof/.test(idx) && /passed/.test(idx) && /Verified\/Lean\/p-proof\.lean/.test(idx), 'Formal/Index.md indexes the object, its status and its archived proof')
616
- assert(/ok(exit 0,/.test(idx), 'the index shows the run result in the contract format')
617
- // a RED proof must NOT become passed
618
- const red = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-red', content: 'theorem p_red : 1 = 2 := by sorry\n' }, RE)
619
- assert(red.ok === true && red.passed === false && red.status === 'attempted', 'a red proof is archived as attempted, not passed')
620
- assert(!existsSync(join(toolProj, 'Verified', 'Lean', 'p-red.lean')), '★ no archived proof is written for a red run')
621
- }
622
- {
623
- const blkNoNote = await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-blk' }, RE)
624
- assert(blkNoNote.ok === false && blkNoNote.code === 'V3_INVALID_ARGUMENT', 'blocked without a note is refused')
625
- const blk = await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-blk', note: '需要外层解析数论框架,本轮工作量不可接受' }, RE)
626
- assert(blk.ok === true && blk.status === 'blocked', 'a reasoned blocker is recorded')
627
- const stBlk = await callTool('vibe_math_status', {}, RE)
628
- assert(stBlk.formal.blocked.indexOf('p-blk') !== -1, 'status lists the blocked object')
629
- assert(/需要外层解析数论框架/.test(readIf(join(toolProj, 'Formal', 'Index.md'))), 'the blocker reason is written into the index')
630
- }
631
- {
632
- const libList = await callTool('vibe_math_lean_lib', {}, RE)
633
- assert(libList.ok === true && libList.counts.lib >= 2 && libList.counts.proved >= 1, 'lean_lib reports the reuse library sizes (' + JSON.stringify(libList.counts) + ')')
634
- assert(libList.objects.some((o) => o.target === 'p-proof' && o.status === 'passed'), 'lean_lib lists per-object formal status')
635
- assert(/复用优先/.test(libList.hint || ''), 'lean_lib tells agents to reuse before redefining')
636
- assert(libList.paths && /VibeMath\/Formal\/Lib/.test(libList.paths.lib), 'lean_lib reports the cross-project path layout')
637
- const ro = await callTool('vibe_math_lean_lib', { refresh: false }, RE)
638
- assert(ro.rebuilt === false && ro.counts.lib === null, 'refresh:false only reads (does not rebuild the indexes)')
639
- }
640
- {
641
- const ann = readIf(join(toolProj, 'Logs', '形式化.md'))
642
- assert(/# 形式化公告/.test(ann) && /ZMod5/.test(ann) && /p-proof/.test(ann), 'the announcement log records what was formalized')
643
- }
644
-
645
- // ===============================================================
646
- // 7. the 'require' gate
647
- // ===============================================================
648
- section("7 'require' withholds a verdict until the formal record exists")
649
- const RF = makeRoot()
650
- await callTool('vibe_math_new_project', { name: 'lean-gate' }, RF)
651
- await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RF)
652
- await callTool('vibe_math_add_proposition', { id: 'p-gate', 概述: '必须形式化的命题', 概率: 0.6, 分类: '数论' }, RF)
653
- const gateProj = projRoot('lean-gate')
654
- await callTool('vibe_math_start', {}, RF)
655
- {
656
- const batch = await runVerifyRound(RF, 'p-gate', [1, 1])
657
- assert(batch !== null, 'require: the review round was asked')
658
- if (batch) {
659
- const vp = batch.map((s) => s.prompt).join('\n')
660
- assert(/【Lean 形式化验证(强制模式)】/.test(vp), 'the review prompt says 强制模式')
661
- assert(/必须产出 Lean 形式化/.test(vp), "'require' states the formalization is mandatory")
662
- assert(/本次裁定不会生效/.test(vp), 'the prompt warns that the verdict will not take effect without it')
663
- assert(/formal-required/.test(vp), 'the prompt names the machine-readable reason')
664
- assert(/归档可复用定义\/引理前先跑通(vibe_math_lean_archive run=true 或先 vibe_math_lean_run);跑不通不要入库。/.test(vp),
665
- '★ the verification prompt requires a GREEN run before archiving into the reuse library (§6 hard requirement 3)')
666
- assert(/宿主没有 Lean 工具链(LEAN_NOT_FOUND)或宿主不提供 subprocess 服务(NO_SUBPROCESS)时:把代码写下来归档,并在回执的 note 里写明"宿主无 Lean 工具链"/.test(vp),
667
- '★ and spells out the way out when the host has no Lean toolchain, naming BOTH failure codes (LEAN_NOT_FOUND / NO_SUBPROCESS, §6 hard requirement 4)')
668
- assert(/Result/.test(vp) && !/verdict/.test(vp) && !/(^|[^a-z_])lean_(run|archive|lib)/.test(vp),
669
- '★ the voting prompt uses FULL tool names and names Result, never verdict (§6 hard requirements 1-2)')
670
- }
671
- }
672
- assert(await drive(RF, () => /p-gate/.test(readIf(join(gateProj, 'Formal', 'TODO.md'))), 'p-gate in Formal/TODO.md'), '★ a unanimous TRUE verdict was withheld: the object is on the formalization TODO')
673
- assert(!existsSync(join(gateProj, 'Verified', '命题', 'p-gate.md')), 'no Verified card was written')
674
- {
675
- const card = readIf(join(gateProj, 'Propos', '数论', 'p-gate.md'))
676
- assert(/- 概率: 0.6/.test(card), '★ the object keeps its existing probability (no silent promotion to 1)')
677
- assert(/- 状态: 未定论/.test(card), 'and its 状态 stays 未定论')
678
- const todo = readIf(join(gateProj, 'Formal', 'TODO.md'))
679
- assert(/# 形式化待办/.test(todo) && /p-gate/.test(todo) && /formal-required/.test(todo), '★ the TODO records the object with the machine-readable reason')
680
- const idx = readIf(join(gateProj, 'Formal', 'Index.md'))
681
- assert(/## 形式化待办/.test(idx) && /p-gate/.test(idx), 'Formal/Index.md mirrors the formalization TODO')
682
- const ann = readIf(join(gateProj, 'Logs', '形式化.md'))
683
- assert(/require 模式/.test(ann) && /不定论/.test(ann), '★ the withholding is announced')
684
- const st = await callTool('vibe_math_status', {}, RF)
685
- assert(st.formal.todo.some((t) => t.id === 'p-gate'), 'status lists the deferred object')
686
- assert(/formal-required/.test(st.recentActivity.map((e) => e.detail).join('\n')), 'the activity feed shows the formal-required deferral')
687
- const voteLog = readdirSync(join(gateProj, 'Logs', 'Verification')).filter((f) => /^r-p-gate_/.test(f))
688
- assert(voteLog.length >= 1, 'the votes themselves are still recorded in Logs/Verification (nothing is lost)')
689
- }
690
- // runtime switch: the mode is read when the prompt is CONSTRUCTED, so a fresh round reflects it
691
- await callTool('vibe_math_add_proposition', { id: 'p-mode', 概述: '模式切换观察对象', 概率: 0.6, 分类: '数论' }, RF)
692
- await restart(RF)
693
- assert(await drive(RF, () => unfiredVerifiers(RF, verifyRe('p-mode')).length >= 2, 'fresh verifiers in require mode'), 'a fresh object is still verified in require mode')
694
- {
695
- const fresh = unfiredVerifiers(RF, verifyRe('p-mode'))[0]
696
- assert(!!fresh && /【Lean 形式化验证(强制模式)】/.test(fresh.prompt) && /本次裁定不会生效/.test(fresh.prompt), 'a fresh round reflects the current mode (强制模式)')
697
- }
698
- // ★ anti-idle: a deferred object must NOT be re-voted while it sits on the TODO (each round would
699
- // just be withheld again, burning verifiers on the same rId every tick). The assertion is only
700
- // meaningful because the previous block proved the scheduler IS allocating verify tasks here.
701
- assert(unfiredVerifiers(RF, verifyRe('p-gate')).length === 0, '★ a deferred object is NOT re-voted while it sits on the formalization TODO (no verification livelock)')
702
- await callTool('vibe_math_set_params', { formalVerify: 'encourage' }, RF)
703
- await restart(RF)
704
- assert(await drive(RF, () => unfiredVerifiers(RF, verifyRe('p-mode')).length >= 2, 'fresh verifiers after the mode switch'), 'the unresolved object is verified again after the mode switch')
705
- {
706
- const fresh = unfiredVerifiers(RF, verifyRe('p-mode'))[0]
707
- assert(!!fresh && /【Lean 形式化验证(鼓励模式)】/.test(fresh.prompt), '★ switching the mode at runtime immediately changes the prompt (now 鼓励模式)')
708
- assert(!!fresh && !/本次裁定不会生效/.test(fresh.prompt), 'and the mandatory wording is gone in encourage mode')
709
- }
710
- await callTool('vibe_math_set_params', { formalVerify: 'require' }, RF)
711
- // formalize it, restart (so the next prompt is built AFTER the proof exists), then re-verify
712
- {
713
- const proofNow = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-gate', content: 'theorem p_gate : 2 + 2 = 4 := by decide\n' }, RF)
714
- assert(proofNow.ok === true && proofNow.passed === true, 'the object is now Lean-passed')
715
- const st = await callTool('vibe_math_status', {}, RF)
716
- assert(st.formal.passed.indexOf('p-gate') !== -1, 'status reports p-gate as passed')
717
- assert(!st.formal.todo.some((t) => t.id === 'p-gate'), '★ satisfying the gate removes the object from the formalization TODO (no stale TODO)')
718
- assert(!/p-gate/.test(readIf(join(gateProj, 'Formal', 'TODO.md'))), 'Formal/TODO.md no longer lists it')
719
- assert(/- 形式化: Lean 通过/.test(readIf(join(gateProj, 'Propos', '数论', 'p-gate.md'))), 'the object card anchor now records Lean 通过')
720
- }
721
- await restart(RF)
722
- assert(await drive(RF, () => unfiredVerifiers(RF, verifyRe('p-gate')).length >= 2, 'p-gate re-eligible after passing'), '★ once the formal record satisfies the gate, the object becomes eligible for verification again')
723
- {
724
- const batch = await runVerifyRound(RF, 'p-gate', [1, 1])
725
- assert(batch !== null, 'the re-verification round was asked')
726
- if (batch) {
727
- const vp = batch.map((s) => s.prompt).join('\n')
728
- assert(/该对象已有\*\*通过的 Lean 形式化证明\*\*/.test(vp), 'the voting prompt announces the passing proof')
729
- assert(/你不需要重新检查推导/.test(vp), '★ it tells voters NOT to re-derive')
730
- assert(/忠实性审查/.test(vp), '★ it tells voters the review subject is now fidelity')
731
- assert(/定义 \/ 对象 \/ 条件 \/ 假设 \/ 结论是否与命题原文\*\*完全一致\*\*/.test(vp), 'it enumerates exactly what fidelity means')
732
- assert(!/必须产出 Lean 形式化/.test(vp), 'and the "must formalize" wording is replaced (the object already has one)')
733
- }
734
- }
735
- assert(await drive(RF, () => existsSync(join(gateProj, 'Verified', '命题', 'p-gate.md')), 'p-gate Verified card'), '★ with a passing Lean artifact the same vote DOES promote it')
736
- {
737
- const card = readIf(join(gateProj, 'Verified', '命题', 'p-gate.md'))
738
- assert(/- 形式化: Lean 通过/.test(card), '★ the Verified card records how strong the result is (Lean 通过)')
739
- assert(/Verified\/Lean\/p-gate\.lean/.test(card), 'the card points at the archived proof')
740
- assert(/- 结论: 真/.test(card), 'the card states the conclusion')
741
- }
742
- // the blocker escape hatch must also open the gate
743
- await callTool('vibe_math_add_proposition', { id: 'p-blocked-ok', 概述: '记录阻塞后可定论', 概率: 0.6, 分类: '数论' }, RF)
744
- await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-blocked-ok', note: '命题涉及未形式化的分析学,本轮不做' }, RF)
745
- await restart(RF)
746
- assert(await runVerifyRound(RF, 'p-blocked-ok', [1, 1]) !== null, 'the blocked object is put to a vote')
747
- assert(await drive(RF, () => existsSync(join(gateProj, 'Verified', '命题', 'p-blocked-ok.md')), 'p-blocked-ok Verified card'), '★ an explicit reasoned blocker also lets the verdict through (decide by difficulty, but decide out loud)')
748
- {
749
- const card = readIf(join(gateProj, 'Verified', '命题', 'p-blocked-ok.md'))
750
- assert(/- 形式化: 阻塞(/.test(card), 'the Verified card records the blocker')
751
- assert(/未形式化的分析学/.test(card), 'and quotes the reason')
752
- }
753
-
754
- // ===============================================================
755
- // 8. the reply-channel judgement (formal field in the verifier reply)
756
- // ===============================================================
757
- section('8 the per-round `formal` reply channel records the difficulty judgement')
758
- const RG = makeRoot()
759
- await callTool('vibe_math_new_project', { name: 'lean-reply' }, RG)
760
- await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RG)
761
- const replyProj = projRoot('lean-reply')
762
-
763
- // (a) blocked WITH a note → recorded, reason reaches the index + the card anchor
764
- await callTool('vibe_math_add_proposition', { id: 'p-reply', 概述: '用回执记录阻塞', 概率: 0.6, 分类: '数论' }, RG)
765
- await callTool('vibe_math_start', {}, RG)
766
- {
767
- const re = verifyRe('p-reply')
768
- assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-reply'), 'p-reply was put to a vote')
769
- const vs = unfiredVerifiers(RG, re).slice(0, 2)
770
- if (vs.length === 2) {
771
- for (const v of vs) firedChildren.add(v.childId)
772
- // A verifier that never calls a Lean tool still has to state its difficulty judgement: the
773
- // JSON reply channel is the path that actually fires in practice.
774
- fireEnd(vs[0].childId, { Result: 0.5, Reason: '我判断形式化不划算', formal: { target: 'p-reply', decision: 'blocked', note: '需要大量未形式化的实分析前置知识' } })
775
- await sleep(150)
776
- const st1 = await callTool('vibe_math_status', {}, RG)
777
- assert(st1.formal.blocked.indexOf('p-reply') !== -1, 'a `formal.decision=blocked` reply is recorded as a blocker')
778
- assert(/实分析前置知识/.test(readIf(join(replyProj, 'Formal', 'Index.md'))), 'and its reason reaches the index')
779
- assert(/- 形式化: 阻塞(/.test(readIf(join(replyProj, 'Propos', '数论', 'p-reply.md'))), 'the reply-recorded blocker also lands on the object card anchor')
780
- fireEnd(vs[1].childId, { Result: 0.5, Reason: '同上' })
781
- await sleep(200)
782
- }
783
- }
784
- // (b) `used` records attempted — which does NOT open the require gate
785
- await restart(RG)
786
- await callTool('vibe_math_add_proposition', { id: 'p-used', 概述: '写了草稿但没跑通', 概率: 0.6, 分类: '数论' }, RG)
787
- {
788
- const re = verifyRe('p-used')
789
- assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-used'), 'p-used was put to a vote')
790
- const vs = unfiredVerifiers(RG, re).slice(0, 2)
791
- if (vs.length === 2) {
792
- for (const v of vs) firedChildren.add(v.childId)
793
- fireEnd(vs[0].childId, { Result: 1, Reason: '看起来对', formal: { target: 'p-used', decision: 'used', file: 'Formal/p-used.lean' } })
794
- await sleep(150)
795
- const st = await callTool('vibe_math_status', {}, RG)
796
- const o = st.formal.objects.find((x) => x.target === 'p-used')
797
- assert(!!o && o.status === 'attempted' && o.file === 'Formal/p-used.lean', 'a `formal.decision=used` reply records the object as attempted with its file')
798
- fireEnd(vs[1].childId, { Result: 1, Reason: '同样看起来对' })
799
- await sleep(250)
800
- assert(!existsSync(join(replyProj, 'Verified', '命题', 'p-used.md')), '★ attempted is NOT passed: the require gate still withholds the verdict')
801
- assert(/p-used/.test(readIf(join(replyProj, 'Formal', 'TODO.md'))), 'and the object is on the formalization TODO')
802
- }
803
- }
804
- // (c) a blocker with no note is refused (an explicit decision is required, never a silent skip)
805
- await restart(RG)
806
- await callTool('vibe_math_add_proposition', { id: 'p-nonote', 概述: '没有理由的阻塞', 概率: 0.6, 分类: '数论' }, RG)
807
- {
808
- const re = verifyRe('p-nonote')
809
- assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-nonote'), 'p-nonote was put to a vote')
810
- const vs = unfiredVerifiers(RG, re).slice(0, 2)
811
- if (vs.length === 2) {
812
- for (const v of vs) firedChildren.add(v.childId)
813
- fireEnd(vs[0].childId, { Result: 0.5, Reason: '不想做', formal: { target: 'p-nonote', decision: 'blocked' } })
814
- await sleep(180)
815
- assert(/未写明 note/.test(readIf(join(replyProj, 'Logs', '形式化.md'))), 'a blocked judgement without a note is refused with an explicit announcement')
816
- const st = await callTool('vibe_math_status', {}, RG)
817
- assert(st.formal.objects.every((o) => o.target !== 'p-nonote'), 'and no blocker record is created for the refused judgement')
818
- // a formal reply without a target must not invent an object (idSafe('') would fall back to 'id')
819
- fireEnd(vs[1].childId, { Result: 0.5, Reason: '同上', formal: { decision: 'blocked', note: '没有写 target' } })
820
- await sleep(180)
821
- const st2 = await callTool('vibe_math_status', {}, RG)
822
- assert(st2.formal.objects.every((o) => o.target !== 'id' && o.target !== ''), 'a `formal` reply with no target cannot invent an object record')
823
- }
824
- }
825
- await callTool('vibe_math_abort', {}, RG)
826
-
827
- // ===============================================================
828
- // 8b. the §4.1 `defect` channel (contract §4.1 / §6 / §10 items 8-9)
829
- //
830
- // A fidelity defect is NOT "the proposition is false". These are BEHAVIOURAL assertions: a real
831
- // agent reply carrying `formal:{decision:'defect', note}` is fed through the real reply path
832
- // (subagent/end → handleVerifier → absorbFormalReply) and the record, the archived file and the
833
- // formalization TODO are inspected on disk.
834
- // ===============================================================
835
- section('8b a formal.decision=defect reply withdraws the passed proof and withholds the verdict')
836
- const RH = makeRoot()
837
- await callTool('vibe_math_new_project', { name: 'lean-defect' }, RH)
838
- await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RH)
839
- const defectProj = projRoot('lean-defect')
840
- await callTool('vibe_math_add_proposition', { id: 'p-defect', 概述: '形式化写窄了的命题', 概率: 0.6, 分类: '数论' }, RH)
841
- {
842
- const pass = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-defect', content: 'theorem p_defect : 2 + 2 = 4 := by decide\n' }, RH)
843
- assert(pass.ok === true && pass.passed === true, 'defect: the object starts out Lean-passed')
844
- assert(existsSync(join(defectProj, 'Verified', 'Lean', 'p-defect.lean')), 'defect: the archived proof is on disk before the fidelity review')
845
- }
846
- await callTool('vibe_math_start', {}, RH)
847
- {
848
- const re = verifyRe('p-defect')
849
- assert(await drive(RH, () => unfiredVerifiers(RH, re).length >= 2, 'verifiers for r-p-defect'), 'defect: the Lean-passed object is put to a fidelity review')
850
- const vs = unfiredVerifiers(RH, re).slice(0, 2)
851
- if (vs.length === 2) {
852
- for (const v of vs) firedChildren.add(v.childId)
853
- assert(/该对象已有\*\*通过的 Lean 形式化证明\*\*/.test(vs[0].prompt) && /不要投 0/.test(vs[0].prompt) && /formal:\{decision:'defect'/.test(vs[0].prompt),
854
- 'defect: the fidelity prompt asks for the defect reply and forbids recording the deviation as 0')
855
- assert(/本次裁定\*\*不定论\*\*/.test(vs[0].prompt),
856
- "★ `require` DOES keep the hold clause (the clause is mode-dependent, not deleted)")
857
- // The defect reply carries an EXTREME Result on purpose: the gate (not the vote value) has to
858
- // be what withholds the verdict — a defect must never be harvested as "the proposition is false".
859
- fireEnd(vs[0].childId, { Result: 1, Reason: '逐条核对后认定形式化不忠实', formal: { target: 'p-defect', decision: 'defect', note: 'Lean 代码多加了 h>0 假设,命题原文未要求' } })
860
- await sleep(240)
861
- const st = await callTool('vibe_math_status', {}, RH)
862
- const rec = st.formal.objects.find((o) => o.target === 'p-defect')
863
- assert(!!rec && rec.status === 'attempted', '★ defect downgrades the formal record to attempted (observed ' + (rec && rec.status) + ')')
864
- assert(st.formal.passed.indexOf('p-defect') === -1, '★ and the object is no longer reported as Lean-passed')
865
- assert(!!rec && rec.proof === '', '★ defect clears the `proof` field')
866
- assert(!existsSync(join(defectProj, 'Verified', 'Lean', 'p-defect.lean')), '★ defect deletes the archived proof Verified/Lean/p-defect.lean')
867
- assert(existsSync(join(defectProj, 'Formal', 'p-defect.lean')), 'the WORK file Formal/p-defect.lean survives (the code itself is not lost)')
868
- const persisted = JSON.parse(readIf(join(defectProj, 'State', 'formal.json')))
869
- assert(persisted.records['p-defect'].decision === 'defect' && /多加了 h>0 假设/.test(persisted.records['p-defect'].note),
870
- '★ the note (the concrete deviation) is recorded in the persisted formal record')
871
- assert(/- 形式化: 已尝试未通过/.test(readIf(join(defectProj, 'Propos', '数论', 'p-defect.md'))), 'and the object card anchor is refreshed')
872
- fireEnd(vs[1].childId, { Result: 1, Reason: '同意:形式化不忠实' })
873
- await sleep(300)
874
- }
875
- }
876
- {
877
- const todo = readIf(join(defectProj, 'Formal', 'TODO.md'))
878
- assert(/p-defect/.test(todo) && /多加了 h>0 假设/.test(todo), '★ the deviation is written into Formal/TODO.md')
879
- const idx = readIf(join(defectProj, 'Formal', 'Index.md'))
880
- assert(/p-defect/.test(idx) && /attempted/.test(idx) && !/Verified\/Lean\/p-defect\.lean/.test(idx), 'Formal/Index.md now shows attempted with no archived proof')
881
- assert(!existsSync(join(defectProj, 'Verified', '命题', 'p-defect.md')), '★ require after a defect: NO Verified card is written (the verdict is withheld, not turned into "false")')
882
- const card = readIf(join(defectProj, 'Propos', '数论', 'p-defect.md'))
883
- assert(/- 状态: 未定论/.test(card), '★ and the object stays 未定论')
884
- assert(/- 概率: 0.6/.test(card), 'the object keeps its existing probability: a defect must NOT be harvested as a refutation')
885
- const ann = readIf(join(defectProj, 'Logs', '形式化.md'))
886
- assert(/忠实性缺陷/.test(ann) && /多加了 h>0 假设/.test(ann), '★ the defect is announced with its concrete deviation')
887
- assert(ann.indexOf('不是"命题为假"') !== -1, 'the announcement spells out that a fidelity defect is NOT "the proposition is false"')
888
- const st = await callTool('vibe_math_status', {}, RH)
889
- assert(st.formal.todo.some((t) => t.id === 'p-defect'), '★ the object is on the formalization TODO (undecided until the formalization is fixed and re-run)')
890
- }
891
- await callTool('vibe_math_abort', {}, RH)
892
-
893
- section('8b-2 a defect without a note is refused (the deviation must be auditable)')
894
- const RI = makeRoot()
895
- await callTool('vibe_math_new_project', { name: 'lean-defect-nonote' }, RI)
896
- await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RI)
897
- const nonoteProj = projRoot('lean-defect-nonote')
898
- await callTool('vibe_math_add_proposition', { id: 'p-nonote-defect', 概述: '没有偏差说明的缺陷回执', 概率: 0.6, 分类: '数论' }, RI)
899
- await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-nonote-defect', content: 'theorem p_nn_defect : 2 + 2 = 4 := by decide\n' }, RI)
900
- await callTool('vibe_math_start', {}, RI)
901
- {
902
- const re = verifyRe('p-nonote-defect')
903
- assert(await drive(RI, () => unfiredVerifiers(RI, re).length >= 2, 'verifiers for r-p-nonote-defect'), 'defect: the passed object is put to a fidelity review')
904
- const vs = unfiredVerifiers(RI, re).slice(0, 2)
905
- if (vs.length === 2) {
906
- for (const v of vs) firedChildren.add(v.childId)
907
- fireEnd(vs[0].childId, { Result: 1, Reason: '觉得不忠实但没写清楚', formal: { target: 'p-nonote-defect', decision: 'defect' } })
908
- await sleep(240)
909
- const st = await callTool('vibe_math_status', {}, RI)
910
- const rec = st.formal.objects.find((o) => o.target === 'p-nonote-defect')
911
- assert(!!rec && rec.status === 'passed', '★ a defect WITHOUT a note is refused: the object stays Lean-passed (no silent downgrade)')
912
- assert(existsSync(join(nonoteProj, 'Verified', 'Lean', 'p-nonote-defect.lean')), '★ and the archived proof is NOT deleted')
913
- assert(st.formal.todo.every((t) => t.id !== 'p-nonote-defect') && !/p-nonote-defect/.test(readIf(join(nonoteProj, 'Formal', 'TODO.md'))),
914
- 'and no bogus formalization-TODO entry is created')
915
- assert(/未写明 note/.test(readIf(join(nonoteProj, 'Logs', '形式化.md'))), '★ the refusal is announced explicitly')
916
- fireEnd(vs[1].childId, { Result: 1, Reason: '核对后认为一致' })
917
- await sleep(300)
918
- }
919
- }
920
- assert(await drive(RI, () => existsSync(join(nonoteProj, 'Verified', '命题', 'p-nonote-defect.md')), 'Verified card'), 'a refused defect leaves the gate open: the same vote still promotes the object')
921
- // §4.1: the downgrade is unconditional — a `blocked` record loses to a defect too (it needs REDOING,
922
- // not a free pass through the gate, which `blocked` would otherwise grant).
923
- await callTool('vibe_math_add_proposition', { id: 'p-blocked-defect', 概述: '阻塞后仍被认定不忠实', 概率: 0.6, 分类: '数论' }, RI)
924
- await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-blocked-defect', note: '先按难度记为阻塞' }, RI)
925
- await restart(RI)
926
- {
927
- const re = verifyRe('p-blocked-defect')
928
- assert(await drive(RI, () => unfiredVerifiers(RI, re).length >= 2, 'verifiers for r-p-blocked-defect'), 'a blocked object is put to a vote (the gate is open for blocked)')
929
- const vs = unfiredVerifiers(RI, re).slice(0, 2)
930
- if (vs.length === 2) {
931
- for (const v of vs) firedChildren.add(v.childId)
932
- fireEnd(vs[0].childId, { Result: 1, Reason: '形式化与命题不对应', formal: { target: 'p-blocked-defect', decision: 'defect', note: '阻塞所依据的形式化本身写错了对象' } })
933
- await sleep(240)
934
- const st = await callTool('vibe_math_status', {}, RI)
935
- const rec = st.formal.objects.find((o) => o.target === 'p-blocked-defect')
936
- assert(!!rec && rec.status === 'attempted', '★★ a defect ALWAYS downgrades, even from `blocked` (observed ' + (rec && rec.status) + ')')
937
- assert(st.formal.blocked.indexOf('p-blocked-defect') === -1 && /阻塞所依据的形式化本身写错了对象/.test(rec.note || ''), 'and the blocked record is replaced by the concrete deviation')
938
- fireEnd(vs[1].childId, { Result: 1, Reason: '同意,形式化写错了对象' })
939
- await sleep(280)
940
- }
941
- }
942
- assert(!existsSync(join(nonoteProj, 'Verified', '命题', 'p-blocked-defect.md')), 'require after a blocked→defect downgrade: still no Verified card (undecided, not "false")')
943
- await callTool('vibe_math_abort', {}, RI)
944
-
945
- // ===============================================================
946
- // 8b-3. the withdrawal is not a best-effort delete (contract §4.1)
947
- //
948
- // `Verified/Lean/<id>.lean` is exactly where everyone looks for "the proof of this object", so a
949
- // downgraded record with the old code still sitting there is worse than no record at all. The fs
950
- // service exposes no unlink and `subprocess` is optional, so on a host that cannot delete, the
951
- // withdrawal must fall back to overwriting the file with an explicit notice. This runs in
952
- // `encourage` mode on purpose: the same scenario also proves the injected text and the
953
- // framework's own announcement do NOT promise a hold that only `require` can enforce (§4.1 item 3).
954
- // ===============================================================
955
- section('8b-3 a defect withdraws the archived proof even on a host that cannot delete files')
956
- const RL = makeRoot()
957
- await callTool('vibe_math_new_project', { name: 'lean-defect-nodelete' }, RL)
958
- await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'encourage' }), RL)
959
- const nodeleteProj = projRoot('lean-defect-nodelete')
960
- await callTool('vibe_math_add_proposition', { id: 'p-nodelete', 概述: '宿主无法删除文件时的撤回', 概率: 0.6, 分类: '数论' }, RL)
961
- const proofFile = join(nodeleteProj, 'Verified', 'Lean', 'p-nodelete.lean')
962
- {
963
- const pass = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-nodelete', content: 'theorem p_nodelete : 2 + 2 = 4 := by decide\n' }, RL)
964
- assert(pass.ok === true && pass.passed === true && /theorem p_nodelete/.test(readIf(proofFile)),
965
- 'no-delete: the object starts out Lean-passed with its archived proof on disk')
966
- }
967
- await callTool('vibe_math_start', {}, RL)
968
- {
969
- const re = verifyRe('p-nodelete')
970
- assert(await drive(RL, () => unfiredVerifiers(RL, re).length >= 2, 'verifiers for r-p-nodelete'), 'no-delete: the Lean-passed object is put to a fidelity review')
971
- const vs = unfiredVerifiers(RL, re).slice(0, 2)
972
- if (vs.length === 2) {
973
- for (const v of vs) firedChildren.add(v.childId)
974
- assert(/发现任何偏差,不要投 0/.test(vs[0].prompt) && /本档没有门禁/.test(vs[0].prompt) && !/不定论/.test(vs[0].prompt),
975
- '★ encourage: the fidelity text does NOT claim the framework will withhold the verdict (only require gates; §4.1 item 3)')
976
- // A host whose shell cannot delete anything: no subprocess service at all. The withdrawal must
977
- // therefore be observable as an OVERWRITE, not as a missing file.
978
- subprocessAvailable = false
979
- fireEnd(vs[0].childId, { Result: 0.5, Reason: '逐条核对后认定形式化不忠实', formal: { target: 'p-nodelete', decision: 'defect', note: 'Lean 里把自然数写成了整数' } })
980
- await sleep(320)
981
- subprocessAvailable = true
982
- const after = readIf(proofFile)
983
- assert(existsSync(proofFile) && !/theorem p_nodelete/.test(after),
984
- '★ without a working delete the archived proof text is gone (overwritten, not left readable as a proof)')
985
- assert(/已撤回(/.test(after) && /Formal\/p-nodelete\.lean/.test(after),
986
- '★ and it carries the withdrawal notice pointing at the kept working file Formal/p-nodelete.lean')
987
- const st = await callTool('vibe_math_status', {}, RL)
988
- const rec = st.formal.objects.find((o) => o.target === 'p-nodelete')
989
- assert(!!rec && rec.status === 'attempted' && rec.proof === '' && /自然数写成了整数/.test(rec.note || ''),
990
- '★ the record is still downgraded to attempted with an emptied proof pointer')
991
- const ann = readIf(join(nodeleteProj, 'Logs', '形式化.md'))
992
- assert(/忠实性缺陷/.test(ann) && /就地覆盖/.test(ann),
993
- '★ the announcement says the proof was OVERWRITTEN (not deleted), so the reader knows which withdrawal happened')
994
- assert(ann.indexOf('不定论') === -1, '★ and `encourage` never claims the framework withheld the verdict')
995
- const todo = readIf(join(nodeleteProj, 'Formal', 'TODO.md'))
996
- assert(/# 形式化待办/.test(todo) && /p-nodelete/.test(todo) && !/定论被搁置/.test(todo) && /没有定论门禁/.test(todo),
997
- '★ Formal/TODO.md states what this mode really does (it does not claim 定论被搁置)')
998
- const idx = readIf(join(nodeleteProj, 'Formal', 'Index.md'))
999
- assert(/## 形式化待办/.test(idx) && !/定论被搁置/.test(idx), '★ and Formal/Index.md mirrors that framing')
1000
- fireEnd(vs[1].childId, { Result: 0.5, Reason: '同意,形式化不忠实' })
1001
- await sleep(280)
1002
- }
1003
- }
1004
- await callTool('vibe_math_abort', {}, RL)
1005
-
1006
- // ===============================================================
1007
- // 8b-4. a defect on an ALREADY-verified object must not leave a stale card anchor
1008
- //
1009
- // `defect` withdraws the formalization (record → attempted, proof pointer cleared, archived file
1010
- // deleted/overwritten). A Verified card written earlier still says 「形式化: Lean 通过(Verified/
1011
- // Lean/<id>.lean)」 — a pointer to a proof that no longer exists. The gate must not prevent that
1012
- // refresh: the gate decides whether a NEW conclusion may be declared, not whether the framework may
1013
- // tell the truth about one it already declared.
1014
- // ===============================================================
1015
- section('8b-4 a later defect refreshes an existing Verified card instead of leaving a stale anchor')
1016
- const RM = makeRoot()
1017
- await callTool('vibe_math_new_project', { name: 'lean-stale-card' }, RM)
1018
- await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RM)
1019
- const staleProj = projRoot('lean-stale-card')
1020
- await callTool('vibe_math_add_proposition', { id: 'p-stale', 概述: '定论后才被认定形式化不忠实', 概率: 0.6, 分类: '数论' }, RM)
1021
- await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-stale', content: 'theorem p_stale : 2 + 2 = 4 := by decide\n' }, RM)
1022
- await callTool('vibe_math_start', {}, RM)
1023
- assert(await runVerifyRound(RM, 'p-stale', [1, 1]) !== null, 'stale-card: the Lean-passed proposition was put to a vote')
1024
- assert(await drive(RM, () => existsSync(join(staleProj, 'Verified', '命题', 'p-stale.md')), 'p-stale Verified card'), 'stale-card: the gate was satisfied, so it reaches a Verified card')
1025
- {
1026
- const card = readIf(join(staleProj, 'Verified', '命题', 'p-stale.md'))
1027
- assert(/- 形式化: Lean 通过/.test(card) && /Verified\/Lean\/p-stale\.lean/.test(card), 'stale-card: the card records the machine-checked strength and its proof path')
1028
- }
1029
- // A LATER work-round reply (e.g. a solver that reuses the object and finds the Lean statement too
1030
- // wide) reports the fidelity defect — long after the card was written.
1031
- await callTool('vibe_math_add_problem', { id: 'q-w', description: '让 explorer 起来以便回执一条 defect', priority: 0 }, RM)
1032
- await restart(RM)
1033
- assert(await drive(RM, () => !!lastSpawn(RM, 'explorer:q-w'), 'explorer:q-w'), 'stale-card: an explorer exists to carry the work-round reply')
1034
- fireEnd(lastSpawn(RM, 'explorer:q-w').childId, {
1035
- meta: { kind: 'directions', qid: 'q-w', formal: { target: 'p-stale', decision: 'defect', note: '这份形式化把结论写宽了' },
1036
- directions: [{ id: 'd1', title: '直接法', method: '', core_assumption: '', feasibility: 0.6 }] },
1037
- })
1038
- assert(await drive(RM, () => !/Lean 通过/.test(readIf(join(staleProj, 'Verified', '命题', 'p-stale.md'))), 'p-stale card refreshed'),
1039
- '★ a defect on an already-verified object refreshes the existing Verified card (no stale 「Lean 通过」 anchor pointing at a withdrawn proof)')
1040
- {
1041
- const card = readIf(join(staleProj, 'Verified', '命题', 'p-stale.md'))
1042
- assert(/- 形式化: 已尝试未通过/.test(card), '★ the refreshed card states the honest formal status (已尝试未通过)')
1043
- assert(!/Verified\/Lean\/p-stale\.lean/.test(card), '★ and no longer points at the withdrawn proof')
1044
- assert(/- 结论: 真/.test(card), 'the conclusion itself is untouched — a fidelity defect is not a refutation')
1045
- assert(!existsSync(join(staleProj, 'Verified', 'Lean', 'p-stale.lean')), 'and the archived proof really is gone')
1046
- assert(await drive(RM, () => /p-stale/.test(readIf(join(staleProj, 'Formal', 'TODO.md'))), 'p-stale formalization TODO'), 'the object is on the formalization TODO for redoing')
1047
- }
1048
- await callTool('vibe_math_abort', {}, RM)
1049
-
1050
- // ===============================================================
1051
- // 8c. the injected text obeys the five hard requirements of contract §6
1052
- // ===============================================================
1053
- section('8c the injected text uses full tool names, Result (not verdict) and the run-before-archive rule')
1054
- const RJ = makeRoot()
1055
- await callTool('vibe_math_new_project', { name: 'lean-workline' }, RJ)
1056
- await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RJ)
1057
- await callTool('vibe_math_add_problem', { id: 'q-defect', description: '顺手形式化的对象', priority: 0 }, RJ)
1058
- const workProj = projRoot('lean-workline')
1059
- // a `meta.formal` defect on the WORK-round path (absorbFormalFromReply) must downgrade too
1060
- await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'q-defect', content: 'theorem q_defect : 2 + 2 = 4 := by decide\n' }, RJ)
1061
- await callTool('vibe_math_start', {}, RJ)
1062
- assert(await drive(RJ, () => !!lastSpawn(RJ, 'explorer:q-defect'), 'explorer:q-defect'), 'the explorer for q-defect was spawned')
1063
- {
1064
- const p = lastSpawn(RJ, 'explorer:q-defect').prompt
1065
- assert(/归档前先跑通(vibe_math_lean_run 或 run=true);跑不通的定义不要进可复用库。/.test(p),
1066
- '★ the work-round prompt requires a GREEN run before archiving a reusable definition (§6 hard requirement 3)')
1067
- assert(/"decision":"used\|blocked\|defect"/.test(p), 'the work-round reply contract advertises the defect decision too')
1068
- assert(!/verdict/.test(p) && !/(^|[^a-z_])lean_(run|archive|lib)/.test(p),
1069
- '★ the work-round prompt uses FULL tool names only and never the v4/v5 field name `verdict`')
1070
- fireEnd(lastSpawn(RJ, 'explorer:q-defect').childId, {
1071
- meta: { kind: 'directions', qid: 'q-defect', formal: { target: 'q-defect', decision: 'defect', note: '陈述里的自然数范围被写成了整数' },
1072
- directions: [{ id: 'd1', title: '直接形式化', method: 'Lean', core_assumption: '', feasibility: 0.6 }] },
1073
- })
1074
- await sleep(260)
1075
- const st = await callTool('vibe_math_status', {}, RJ)
1076
- const rec = st.formal.objects.find((o) => o.target === 'q-defect')
1077
- assert(!!rec && rec.status === 'attempted' && /自然数范围被写成了整数/.test(rec.note || ''),
1078
- '★ a `meta.formal` defect from a WORK reply downgrades the record too (absorbFormalFromReply, not just the verifier path)')
1079
- assert(!existsSync(join(workProj, 'Verified', 'Lean', 'q-defect.lean')), '★ and its archived proof is deleted')
1080
- }
1081
- await callTool('vibe_math_abort', {}, RJ)
1082
-
1083
- section('8c-2 the fidelity branch reaches BOTH the review and the debate prompt, and names Result')
1084
- const RK = makeRoot()
1085
- await callTool('vibe_math_new_project', { name: 'lean-fidelity' }, RK)
1086
- await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'encourage', debateMaxRounds: 2 }), RK)
1087
- await callTool('vibe_math_add_proposition', { id: 'p-fid', 概述: '忠实性审查措辞观察对象', 概率: 0.6, 分类: '数论' }, RK)
1088
- await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-fid', content: 'theorem p_fid : 2 + 2 = 4 := by decide\n' }, RK)
1089
- await callTool('vibe_math_start', {}, RK)
1090
- const fidBatch = await runVerifyRound(RK, 'p-fid', [0.9, 0.95])
1091
- assert(fidBatch !== null, 'fidelity: the review round was asked')
1092
- if (fidBatch) {
1093
- const vp = fidBatch.map((s) => s.prompt).join('\n')
1094
- assert(/一致 → Result = 1/.test(vp), "★ the review prompt states the faithful case as `Result = 1` (v3's REAL reply field, not v4/v5's verdict)")
1095
- assert(/发现任何偏差,不要投 0/.test(vp) && /形式化不合格/.test(vp), '★ and forbids expressing a fidelity defect as 0')
1096
- assert(/formal:\{decision:'defect', note:'<具体偏差>'\}/.test(vp), 'and points at the defect reply field to record it')
1097
- assert(/独立于这份 Lean 代码/.test(vp), 'only an INDEPENDENT refutation may be voted 0')
1098
- assert(/Result/.test(vp) && !/verdict/.test(vp), '★ the voting prompt names Result, never verdict (§6 hard requirement 2)')
1099
- assert(vp.indexOf('偏离 → 0') === -1, '★ no "偏离 → 0" instruction anywhere in the fidelity branch (contract §10 item 9)')
1100
- }
1101
- assert(await drive(RK, () => wakes.some((w) => w.rootId === RK.id && /交流群/.test(w.prompt)), 'debate prompt'), 'a non-consensus fidelity round moved to the debate')
1102
- {
1103
- const dp = wakes.filter((w) => w.rootId === RK.id).map((w) => w.prompt).join('\n')
1104
- assert(/一致 → Result = 1/.test(dp) && /不要投 0/.test(dp), '★ the DEBATE prompt carries the same fidelity wording')
1105
- assert(/Result/.test(dp) && !/verdict/.test(dp), 'the debate prompt names Result, never verdict')
1106
- assert(dp.indexOf('偏离 → 0') === -1, 'the debate prompt also refuses "a deviation is a 0"')
1107
- }
1108
- await callTool('vibe_math_abort', {}, RK)
1109
-
1110
- // ===============================================================
1111
- // 9. reporting + persistence
1112
- // ===============================================================
1113
- // (d) a plain `used` judgement must NOT withdraw an ESTABLISHED proof (contract §4). Only a
1114
- // fidelity defect retracts a proof; `used` just reports "this round touched the formalization".
1115
- // v2 shipped the unconditional downgrade here and silently re-closed the require gate.
1116
- section('8d a \`used\` reply must NOT downgrade an already-passed object')
1117
- await restart(RG)
1118
- await callTool('vibe_math_add_proposition', { id: 'p-usedkeep', 概述: '已有通过证明后再写一次 used 回执', 概率: 0.6, 分类: '数论' }, RG)
1119
- {
1120
- const pass = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-usedkeep', content: 'theorem p_usedkeep : 2 + 2 = 4 := by decide\n' }, RG)
1121
- assert(pass.ok === true && pass.passed === true, 'used-keep: the object starts out Lean-passed')
1122
- const re = verifyRe('p-usedkeep')
1123
- assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-usedkeep'), 'used-keep: the Lean-passed object is put to a fidelity review')
1124
- const vs = unfiredVerifiers(RG, re).slice(0, 2)
1125
- if (vs.length === 2) {
1126
- for (const v of vs) firedChildren.add(v.childId)
1127
- fireEnd(vs[0].childId, { Result: 0.5, Reason: '这一轮只是又写了一遍草稿', formal: { target: 'p-usedkeep', decision: 'used', file: 'Formal/p-usedkeep.lean' } })
1128
- await sleep(150)
1129
- const st = await callTool('vibe_math_status', {}, RG)
1130
- const o = st.formal.objects.find((x) => x.target === 'p-usedkeep')
1131
- assert(!!o && o.status === 'passed', '★ a `used` reply does NOT downgrade an already-passed object (got ' + JSON.stringify(o) + ')')
1132
- assert(st.formal.passed.indexOf('p-usedkeep') !== -1, '★ and status still reports it as Lean-passed (the fidelity branch stays the reviewers\' subject)')
1133
- assert(existsSync(join(replyProj, 'Verified', 'Lean', 'p-usedkeep.lean')), '★ and the archived proof is still on disk by that name')
1134
- fireEnd(vs[1].childId, { Result: 0.5, Reason: '同样只是又写了一遍草稿' })
1135
- await sleep(250)
1136
- assert(!/p-usedkeep/.test(readIf(join(replyProj, 'Formal', 'TODO.md')) || ''), '★ no formal-required TODO was created: the surviving passed still opens the require gate')
1137
- // The same rule covers the RUN path (contract §4): a run attributed to the object may not downgrade it.
1138
- const rerun = await callTool('vibe_math_lean_run', { file: 'Formal/p-usedkeep.lean', target: 'p-usedkeep' }, RG)
1139
- assert(rerun.ok === true, 'used-keep: the object work file runs green (the record assertion below is the point)')
1140
- const o2 = (await callTool('vibe_math_status', {}, RG)).formal.objects.find((x) => x.target === 'p-usedkeep')
1141
- assert(!!o2 && o2.status === 'passed', '★ and the record is still passed')
1142
- }
1143
- }
1144
-
1145
- // (e) the same rule for `blocked`: a blocker is a gate-opening record, so a later `used` reply
1146
- // must not push the object back to `attempted` and silently re-close the gate (v3 used to preserve
1147
- // only `passed` here — v2/v4/v5 preserve both).
1148
- await restart(RG)
1149
- await callTool('vibe_math_add_proposition', { id: 'p-usedblocked', 概述: '已记录阻塞后再写一次 used 回执', 概率: 0.6, 分类: '数论' }, RG)
1150
- {
1151
- const blk = await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-usedblocked', note: '需要大量未形式化的实分析前置知识' }, RG)
1152
- assert(blk.ok === true && blk.status === 'blocked', 'used-blocked: the object starts with an explicit blocker (the gate is open)')
1153
- const re = verifyRe('p-usedblocked')
1154
- assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-usedblocked'), 'used-blocked: the object is put to a vote')
1155
- const vs = unfiredVerifiers(RG, re).slice(0, 2)
1156
- if (vs.length === 2) {
1157
- for (const v of vs) firedChildren.add(v.childId)
1158
- fireEnd(vs[0].childId, { Result: 0.5, Reason: '这一轮只是又写了一遍草稿', formal: { target: 'p-usedblocked', decision: 'used', file: 'Formal/p-usedblocked.lean' } })
1159
- await sleep(150)
1160
- const o = (await callTool('vibe_math_status', {}, RG)).formal.objects.find((x) => x.target === 'p-usedblocked')
1161
- assert(!!o && o.status === 'blocked', '★ a `used` reply does not re-close a gate an explicit blocker opened (got ' + JSON.stringify(o) + ')')
1162
- fireEnd(vs[1].childId, { Result: 0.5, Reason: '同上' })
1163
- await sleep(200)
1164
- }
1165
- }
1166
-
1167
- section('9 the office can audit formal strength')
1168
- {
1169
- const rep = await callTool('vibe_math_report', {}, RF)
1170
- assert(rep.formal && rep.formal.mode === 'require', 'the JSON report carries the formal mode')
1171
- assert(rep.formal.passed.indexOf('p-gate') !== -1 && rep.formal.blocked.indexOf('p-blocked-ok') !== -1, 'the JSON report lists both passed and blocked objects')
1172
- assert(rep.params.formalVerify === 'require' && rep.params.leanCommand === 'lean', 'the readable parameter table carries the Lean parameters')
1173
- const md = readIf(join(gateProj, 'Logs', '报告.md'))
1174
- assert(/## Lean 形式化/.test(md), 'the human-readable report has a Lean formal-verification section')
1175
- assert(/已通过:.*p-gate/.test(md), 'it lists Lean-passed objects')
1176
- assert(/已记录阻塞:.*p-blocked-ok/.test(md), 'it lists blocked objects')
1177
- assert(/可复用库:VibeMath\/Formal\/\{Lib,Proved\}\//.test(md), 'it documents the path layout')
1178
- await callTool('vibe_math_report', {}, RA)
1179
- assert(/未启用(`formalVerify` = off/.test(readIf(join(offProj, 'Logs', '报告.md'))), 'in off mode the report says the feature is not enabled')
1180
- const offRep = await callTool('vibe_math_report', {}, RA)
1181
- assert(offRep.formal.mode === 'off' && /off/.test(offRep.formal.note || ''), 'and the JSON report says the same')
1182
- }
1183
- {
1184
- const before = JSON.parse(readIf(join(gateProj, 'State', 'formal.json')))
1185
- assert(!!before && !!before.records && before.records['p-gate'] && before.records['p-gate'].status === 'passed', 'the formal record is persisted in State/formal.json, keyed by object id')
1186
- assert(Array.isArray(before.todo), 'the formalization TODO is persisted alongside it')
1187
- assert(before.records['p-blocked-ok'].status === 'blocked' && /分析学/.test(before.records['p-blocked-ok'].note), 'a blocker record keeps its reason across sessions')
1188
- assert(existsSync(join(VIBE, 'Formal', 'Proved', 'Index.md')) && existsSync(join(libPath, 'Index.md')), 'both global indexes are framework-maintained')
1189
- }
1190
-
1191
- // ===============================================================
1192
- // 10. interaction corpus (AUDIT-CHECKLIST §2.4) — a HUMAN must be able to re-read
1193
- // every prompt the framework emitted, not just the assertions about them.
1194
- // ===============================================================
1195
- section('10 the captured prompt corpus is written for human review')
1196
- {
1197
- mkdirSync(CORPUS_DIR, { recursive: true })
1198
- writeFileSync(join(CORPUS_DIR, 'formal-verify-v3.json'), JSON.stringify({ entries: corpus }, null, 2), 'utf8')
1199
- const md = ['# V3 形式化验证交互语料(prompt corpus)', '',
1200
- '> 由 `formal-verify-v3.test.mjs` 落盘:框架**真正发出**的每一条提示词原文。路径归一化:工作区 → `<WS>`,',
1201
- '> VibeMath 根 → `<VIBEMATH>`(两者都按正/反斜杠两种写法替换,因此语料是确定性的、可 diff 的、不泄露本机路径)。',
1202
- '> 覆盖:explorer / solver / method-keeper 的日常工作提示词(含「顺手形式化」与"归档前先跑通"),',
1203
- '> `off`(零 Lean 文本)、`encourage`、**`require`** 三档下的表决初评与辩论提示词,`passed` 之后的忠实性审查分支',
1204
- '> (含 `defect` 出口),以及规划提示词。', '']
1205
- for (let i = 0; i < corpus.length; i++) {
1206
- const c = corpus[i]
1207
- md.push('## [' + i + '] ' + c.kind + ' · ' + c.label)
1208
- md.push('')
1209
- md.push('```text')
1210
- md.push(c.prompt)
1211
- md.push('```')
1212
- md.push('')
1213
- }
1214
- writeFileSync(join(CORPUS_DIR, 'formal-verify-v3.md'), md.join('\n'), 'utf8')
1215
- assert(existsSync(join(CORPUS_DIR, 'formal-verify-v3.json')) && existsSync(join(CORPUS_DIR, 'formal-verify-v3.md')), 'the prompt corpus was written (JSON + Markdown)')
1216
- assert(corpus.length >= 25, 'the corpus covers the whole run (' + corpus.length + ' prompts)')
1217
- assert(corpus.some((c) => c.label.startsWith('explorer:')) && corpus.some((c) => c.label.startsWith('solver:')) && corpus.some((c) => c.label.startsWith('method-keeper')) && corpus.some((c) => c.label.startsWith('verifier:')), 'the corpus covers every interaction type this suite drives')
1218
- assert(corpus.some((c) => c.kind === 'wake'), 'the corpus also keeps the continuation prompts (debate rounds)')
1219
- // generic sweep over EVERY captured prompt, not spot checks (AUDIT §2.1)
1220
- const dirty = corpus.filter((c) => /\[object Object\]|\bNaN\b|:\s*undefined|["']undefined["']|undefined\s*[,}\]]/.test(c.prompt))
1221
- assert(dirty.length === 0, 'no captured prompt contains placeholder garbage (' + dirty.map((d) => d.label).join(',') + ')')
1222
- const joined = corpus.map((c) => c.prompt).join('\n')
1223
- assert(joined.indexOf(WS) === -1 && joined.indexOf(WS.replace(/\\/g, '/')) === -1, 'every captured prompt normalises the workspace path to <WS> (the corpus stays diffable)')
1224
- assert(joined.indexOf(VIBE) === -1 && joined.indexOf(VIBE.replace(/\\/g, '/')) === -1 && joined.indexOf('<VIBEMATH>') !== -1,
1225
- '★ every captured prompt normalises the VibeMath root to <VIBEMATH> (no machine path leaks into the shipped corpus, contract §10 item 10)')
1226
- assert(!corpus.some((c) => c.root === RA.id && /Lean|形式化/.test(c.prompt)),
1227
- '★ the off-mode prompts captured in the corpus contain ZERO Lean text (off stays a true no-op)')
1228
- // contract §10 item 10: the corpus must cover require AND the work round (not just encourage + fidelity)
1229
- assert(corpus.some((c) => /【Lean 形式化验证(鼓励模式)】/.test(c.prompt)), '★ the corpus covers the encourage-mode verification prompt')
1230
- assert(corpus.some((c) => /【Lean 形式化验证(强制模式)】/.test(c.prompt)), '★ the corpus covers the REQUIRE-mode verification prompt')
1231
- assert(corpus.some((c) => /【顺手形式化(鼓励)】/.test(c.prompt)) && corpus.some((c) => /【顺手形式化(强制)】/.test(c.prompt)), '★ the corpus covers the work-round 顺手形式化 prompt in both modes')
1232
- assert(corpus.some((c) => /一致 → Result = 1/.test(c.prompt)), '★ the corpus keeps the passed/fidelity branch verbatim for human review')
1233
- // contract §6 hard requirements 1-2 + §10 item 9, swept over EVERY captured prompt
1234
- const verifier = corpus.filter((c) => c.label.startsWith('verifier:'))
1235
- assert(verifier.length >= 5 && verifier.every((c) => /Result/.test(c.prompt) && !/verdict/.test(c.prompt)),
1236
- '★ every captured voting prompt names Result and never verdict (§6 hard requirement 2)')
1237
- const bareTools = corpus.filter((c) => /(^|[^a-z_])lean_(run|archive|lib)/.test(c.prompt))
1238
- assert(bareTools.length === 0, '★ no captured prompt abbreviates a Lean tool name (§6 hard requirement 1): ' + bareTools.map((b) => b.label).join(','))
1239
- const zeroDeviation = corpus.filter((c) => c.prompt.indexOf('偏离 → 0') !== -1)
1240
- assert(zeroDeviation.length === 0, '★ no captured prompt turns a fidelity defect into a 0 vote (§6 hard requirement 5 / §10 item 9): ' + zeroDeviation.map((b) => b.label).join(','))
1241
- // Contract §10 item 10 + AUDIT-CHECKLIST §2.4: the shipped corpus must be BYTE-deterministic, so
1242
- // the volatile run metadata the planner brief carries (random plan id, epoch timestamps, child
1243
- // ids, free-slot count) must be normalised out — otherwise every run diffs and the corpus loses
1244
- // its only purpose (human review of what agents actually read).
1245
- const volatile = corpus.filter((c) => /plan-[0-9a-f]{8}/.test(c.label) || /plan-[0-9a-f]{8}|"at": \d{10,}|"childId": "c\d+"|"free_slots": \d+/.test(c.prompt))
1246
- assert(volatile.length === 0, '★ no captured prompt/label keeps volatile run metadata (random plan id / epoch timestamps / child ids / slot count) — the corpus is byte-deterministic: ' + volatile.map((b) => b.label).join(','))
1247
- assert(corpus.some((c) => /"free_slots": <SLOTS>/.test(c.prompt)) && corpus.some((c) => /plan-<ID>/.test(c.label)),
1248
- '★ and the normalisation actually fired (a planner brief and its plan id were captured)')
1249
- }
1250
-
1251
- console.log('')
1252
- console.log('passed=' + passed + ' failed=' + failed)
1253
- if (failed) { console.error('FAILURES:'); for (const f of failures) console.error(' - ' + f) }
1254
- rmSync(WS, { recursive: true, force: true })
1255
- if (failed) process.exit(1)
1256
- console.log('ALL GREEN')
1257
- process.exit(0)
1
+ // ============================================================
2
+ // V3 LEAN FORMAL VERIFICATION SUITE (docs/formal-verification.md)
3
+ //
4
+ // Asserts the whole contract of the `formalVerify` knob on the v3 preset:
5
+ // · 'off' is a TRUE no-op (no Lean text in ANY prompt, no Formal record, no gate)
6
+ // · 'encourage' injects the Lean section into the work prompts AND into both verification
7
+ // prompts, and — the actual point of the feature — turns the voting prompt into
8
+ // a FIDELITY review once a Lean run has passed
9
+ // · 'require' withholds a true/false verdict as 未定论 until the object is Lean-passed or
10
+ // carries an explicit, reasoned blocker record; then allows it, and the Verified
11
+ // card records how strong the result really is
12
+ // · the three tools (run / archive / lib) write the right things to the right paths
13
+ //
14
+ // The Lean toolchain is mocked through the subprocess SERVICE, so the tests exercise the real
15
+ // code path (resolveExecutable → spawn → collected stdout → exit code) without requiring Lean.
16
+ //
17
+ // V3_PLUGIN overrides the plugin under test: a sensitivity probe MUST point this suite at a
18
+ // mutated copy, otherwise every probe would exercise the unmutated plugin and stay green.
19
+ //
20
+ // Run: node tests/formal-verify-v3.test.mjs
21
+ // ============================================================
22
+ import { mkdtempSync, rmSync, existsSync, readFileSync, readdirSync, mkdirSync, writeFileSync } from 'node:fs'
23
+ import { tmpdir } from 'node:os'
24
+ import { join, dirname, isAbsolute, resolve as pathResolve } from 'node:path'
25
+ import { fileURLToPath } from 'node:url'
26
+
27
+ const PLUGIN = process.env.V3_PLUGIN
28
+ ? new URL('file:///' + String(process.env.V3_PLUGIN).replace(/\\/g, '/'))
29
+ : new URL('../vibe-math-v3/vibe-math-v3.js', import.meta.url)
30
+ const HERE = dirname(fileURLToPath(import.meta.url))
31
+ // AUDIT-CHECKLIST §2.4: the suite must also keep the INTERACTION TEXT it drove, so a human can
32
+ // re-read the prompts the framework really emitted. V3_CORPUS_DIR overrides the destination.
33
+ const CORPUS_DIR = process.env.V3_CORPUS_DIR ? pathResolve(process.env.V3_CORPUS_DIR) : join(HERE, '..', 'prompt-corpus-v3')
34
+ const WS = mkdtempSync(join(tmpdir(), 'vibe-v3-lean-'))
35
+ const VIBE = join(WS, 'VibeMath')
36
+ const projRoot = (slug) => join(VIBE, 'Projects', slug)
37
+ const readIf = (p) => (existsSync(p) ? readFileSync(p, 'utf8') : '')
38
+ const reEsc = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
39
+ const verifyRe = (target) => new RegExp('^verifier:r-' + reEsc(target) + '(?:-\\w+)?:\\d+$')
40
+
41
+ let passed = 0, failed = 0
42
+ const failures = []
43
+ const assert = (c, m) => { if (c) { passed++; console.log(' ok - ' + m) } else { failed++; failures.push(m); console.error(' FAIL - ' + m) } }
44
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
45
+ const section = (t) => console.log('\n[' + t + ']')
46
+
47
+ // ---------------------------------------------------------------
48
+ // mock host
49
+ // ---------------------------------------------------------------
50
+ const listeners = {}
51
+ const toolRegs = []
52
+ const cmdRegs = []
53
+ const spawns = [] // { label, childId, rootId, prompt }
54
+ const wakes = [] // { childId, rootId, prompt }
55
+ const interrupts = []
56
+ const leanRuns = [] // { argv, file, cwd, graceMs }
57
+ const terminated = []
58
+ const roots = []
59
+ let rootSeq = 0
60
+ let subprocessAvailable = true
61
+ let toolchainAvailable = true
62
+ let spawnThrows = false
63
+ // Interaction corpus (AUDIT-CHECKLIST §2.4): every prompt the framework actually sent, with the
64
+ // workspace path normalised so the dump is deterministic and diffable.
65
+ const corpus = []
66
+ // Normalise BOTH slash forms. The VibeMath ROOT must be replaced BEFORE the workspace root,
67
+ // otherwise `<WS>/VibeMath` would survive as a half-substituted path: the corpus would still leak
68
+ // the machine layout and would not be diffable against another checkout.
69
+ //
70
+ // The PLANNER prompt embeds the raw state brief, whose volatile RUN METADATA would otherwise change
71
+ // on every run and make the corpus undiffable (contract §10 item 10 demands byte determinism; the
72
+ // same class of bug is recorded in AUDIT-CHECKLIST §2.4 as a real accident): the random plan id in
73
+ // the label, epoch-millisecond `at` timestamps, child ids, and the free-slot count. They are run
74
+ // metadata, not the text under review, so they are normalised to placeholders.
75
+ const scrub = (s) => String(s == null ? '' : s)
76
+ .split(VIBE).join('<VIBEMATH>')
77
+ .split(VIBE.replace(/\\/g, '/')).join('<VIBEMATH>')
78
+ .split(WS).join('<WS>')
79
+ .split(WS.replace(/\\/g, '/')).join('<WS>')
80
+ .replace(/plan-[0-9a-f]{8}/g, 'plan-<ID>')
81
+ .replace(/("at"\s*:\s*)\d{10,16}/g, '$1"<TIME>"')
82
+ .replace(/("childId"\s*:\s*")c\d+(")/g, '$1<CHILD>$2')
83
+ .replace(/("free_slots"\s*:\s*)\d+/g, '$1<SLOTS>')
84
+
85
+ // A fake Lean: a file PASSES unless it still contains `sorry` or the marker `-- FAIL`.
86
+ // `-- HANG` simulates a toolchain that never returns (the timeout path).
87
+ const subprocess = {
88
+ async resolveExecutable(cmd) {
89
+ if (!toolchainAvailable) throw new Error('spawn ' + cmd + ' ENOENT')
90
+ if (String(cmd) !== 'lean' && String(cmd) !== 'lake') throw new Error('unknown executable ' + cmd)
91
+ return String(cmd)
92
+ },
93
+ spawn(spec) {
94
+ const argv = spec.argv || []
95
+ const last = String(argv[argv.length - 1] || '')
96
+ const isShell = /powershell|cmd\.exe|\/bin\/sh|(^|\/)sh$/i.test(String(argv[0] || '')) || /New-Item|Remove-Item|Move-Item|^mkdir -p/.test(last)
97
+ if (isShell) {
98
+ // directory shim (v3's runShell: powershell New-Item / POSIX mkdir -p)
99
+ if (/New-Item/.test(last)) {
100
+ const m = last.match(/-Path\s+(?:'((?:[^']|'')*)'|"((?:[^"]|"")*)")/)
101
+ const raw = (m && (m[1] || m[2])) || ''
102
+ for (const p of raw.split(',').map((x) => x.replace(/''/g, "'"))) if (p) mkdirSync(p, { recursive: true })
103
+ }
104
+ if (/^mkdir -p/.test(last)) {
105
+ const re = /'((?:[^']|'\\'')*)'/g
106
+ let m
107
+ while ((m = re.exec(last)) !== null) mkdirSync(m[1].replace(/'\\''/g, "'"), { recursive: true })
108
+ }
109
+ if (/Remove-Item/.test(last)) {
110
+ const m = last.match(/-LiteralPath\s+'((?:[^']|'')*)'/)
111
+ if (m) rmSync(m[1].replace(/''/g, "'"), { force: true, recursive: true })
112
+ }
113
+ return { done: Promise.resolve({ exitCode: 0 }), collected: {} }
114
+ }
115
+ const file = last
116
+ const text = existsSync(file) ? readFileSync(file, 'utf8') : ''
117
+ leanRuns.push({ argv: argv.slice(0, -1), file, cwd: spec.cwd, graceMs: spec.graceMs })
118
+ if (spawnThrows) throw new Error('spawn ' + String(argv[0]) + ' EPERM')
119
+ if (/-- REJECT/.test(text)) {
120
+ return {
121
+ done: Promise.reject(new Error('child process died before reporting')),
122
+ collected: { stdout: { readFrom: () => ({ text: '', nextOffset: 0, lossy: false }) }, stderr: { readFrom: () => ({ text: '', nextOffset: 0, lossy: false }) } },
123
+ terminate() {},
124
+ }
125
+ }
126
+ if (/-- HANG/.test(text)) {
127
+ return {
128
+ done: new Promise(() => {}),
129
+ collected: { stdout: { readFrom: () => ({ text: '', nextOffset: 0, lossy: false }) }, stderr: { readFrom: () => ({ text: '', nextOffset: 0, lossy: false }) } },
130
+ terminate() { terminated.push(file) },
131
+ }
132
+ }
133
+ const bad = /sorry|-- FAIL/.test(text)
134
+ const stdout = bad ? '' : 'ok\n'
135
+ const stderr = bad ? 'error: declaration uses sorry\n' : ''
136
+ return {
137
+ done: Promise.resolve({ exitCode: bad ? 1 : 0, signal: null }),
138
+ collected: {
139
+ stdout: { readFrom: () => ({ text: stdout, nextOffset: stdout.length, lossy: false }) },
140
+ stderr: { readFrom: () => ({ text: stderr, nextOffset: stderr.length, lossy: false }) },
141
+ },
142
+ terminate() {},
143
+ }
144
+ },
145
+ }
146
+
147
+ const ctx = {
148
+ get(name) {
149
+ if (name === 'subprocess') return subprocessAvailable ? subprocess : undefined
150
+ if (name === 'sandboxPolicy') return { resolve() { return { workspaceRoot: WS } } }
151
+ return undefined
152
+ },
153
+ on(e, fn) { (listeners[e] = listeners[e] || []).push(fn) },
154
+ effect(fn) { const d = fn(); return () => { if (typeof d === 'function') d() } },
155
+ logger: { info() {}, warn() {}, error() {} },
156
+ tools: { register(spec) { toolRegs.push(spec); return () => {} } },
157
+ commands: { register(spec) { cmdRegs.push(spec); return () => {} } },
158
+ subagents: {
159
+ list() { return ['spawn'] },
160
+ async startContinuable({ label, request }) {
161
+ const childId = 'c' + (spawns.length + 1)
162
+ const rootId = (request && request.parent && request.parent.id) || ''
163
+ const prompt = (request && request.prompt && request.prompt[0] && request.prompt[0].text) || ''
164
+ spawns.push({ label, childId, rootId, prompt })
165
+ corpus.push({ kind: 'spawn', label: scrub(label), root: rootId, prompt: scrub(prompt) })
166
+ return { childId, messageId: 'm' + spawns.length }
167
+ },
168
+ async sendMessage(parent, childId, blocks) {
169
+ const rootId = (parent && parent.id) || ''
170
+ const prompt = (blocks && blocks[0] && blocks[0].text) || ''
171
+ wakes.push({ childId, rootId, prompt })
172
+ const sp = spawns.find((s) => s.childId === childId)
173
+ corpus.push({ kind: 'wake', label: scrub(sp ? sp.label : childId), root: rootId, prompt: scrub(prompt) })
174
+ return 'w' + wakes.length
175
+ },
176
+ async followup(parent, childId, blocks) { return await this.sendMessage(parent, childId, blocks) },
177
+ interrupt(childId) { interrupts.push(childId) },
178
+ },
179
+ agents: { roots() { return roots.slice() }, get() { return undefined } },
180
+ // DSH 0.1.1 fs API: resolve → { targetKey, displayPath }
181
+ fs: {
182
+ async resolve(rel, opts) {
183
+ const base = (opts && opts.cwd) || WS
184
+ const p = (typeof rel === 'string' && isAbsolute(rel)) ? rel.replace(/\//g, '\\') : join(base, ...String(rel).split('/'))
185
+ return { targetKey: p, displayPath: p }
186
+ },
187
+ async stat(t) { return existsSync(t.targetKey) ? { version: 'v1', type: 'file', size: 1 } : undefined },
188
+ async readText(t) { return readFileSync(t.targetKey, 'utf8') },
189
+ async writeText(t, content) { mkdirSync(dirname(t.targetKey), { recursive: true }); writeFileSync(t.targetKey, content, 'utf8') },
190
+ async listDir(t) { if (!existsSync(t.targetKey)) return []; return readdirSync(t.targetKey, { withFileTypes: true }).map((e) => ({ name: e.name, type: e.isDirectory() ? 'directory' : 'file' })) },
191
+ },
192
+ }
193
+
194
+ const mod = await import(PLUGIN.href + '?t=' + Date.now())
195
+ ;(mod.default || mod).apply(ctx)
196
+
197
+ // ---------------------------------------------------------------
198
+ // driving helpers
199
+ // ---------------------------------------------------------------
200
+ function makeRoot() {
201
+ const id = 'sess-' + String.fromCharCode(65 + rootSeq++)
202
+ const root = { id, options: { provider: 'mock', model: 'mock-model' }, session: { id, header: { cwd: WS, parentSession: undefined } }, followup() {}, ctx: undefined }
203
+ roots.push(root)
204
+ return root
205
+ }
206
+ async function callTool(name, args, agent) {
207
+ const spec = toolRegs.find((s) => s.name === name)
208
+ if (!spec) throw new Error('no tool ' + name)
209
+ return JSON.parse(await spec.execute(args || {}, { agent }))
210
+ }
211
+ function fireEnd(childId, reply) {
212
+ const blocks = reply === undefined ? [] : [{ type: 'text', text: '```json\n' + JSON.stringify(reply) + '\n```' }]
213
+ for (const h of (listeners['subagent/end'] || [])) h({ id: childId, runId: 'r', provider: 'spawn', local: true, stopReason: 'completed', lastAssistantMessage: blocks })
214
+ }
215
+ const firedChildren = new Set()
216
+ // Spawns created before a restart belong to a task the restart discarded; they are never a valid
217
+ // target for a later round (their onChildEnd has no agentRegistry entry any more). The floor keeps
218
+ // `unfiredVerifiers` from selecting them.
219
+ const spawnFloor = {}
220
+ const markFloor = (root) => { spawnFloor[root.id] = spawns.length }
221
+ const spawnOf = (root, prefix) => spawns.filter((s) => s.rootId === root.id && s.label.startsWith(prefix))
222
+ const lastSpawn = (root, prefix) => spawnOf(root, prefix).slice(-1)[0]
223
+ const unfiredVerifiers = (root, re) => spawns.filter((s, i) => s.rootId === root.id && (spawnFloor[root.id] || 0) <= i && re.test(s.label) && !firedChildren.has(s.childId))
224
+ const promptText = (root) => spawns.filter((s) => s.rootId === root.id).map((s) => s.prompt).join('\n') + '\n' + wakes.filter((w) => w.rootId === root.id).map((w) => w.prompt).join('\n')
225
+
226
+ /** Parameters every verification scenario uses. A high concurrency cap keeps the fallback
227
+ * scheduler from starving a later object behind a pile of unfired mock verifiers. */
228
+ const VPARAMS = { plannerEnabled: false, verifierCount: 2, debateMaxRounds: 1, maxParallelThreshold: 64, tickIntervalMs: 200 }
229
+
230
+ /** Fire the one in-flight forced planner with an empty plan (an empty plan schedules a tick). */
231
+ async function pump(root) {
232
+ const pending = spawns.filter((s) => s.rootId === root.id && s.label.startsWith('planner:') && !firedChildren.has(s.childId)).slice(-1)[0]
233
+ if (pending) { firedChildren.add(pending.childId); fireEnd(pending.childId, { summary: 'noop', plan: [] }); return }
234
+ try { await callTool('vibe_math_plan', { force: true }, root) } catch (e) { /* not running / gated */ }
235
+ }
236
+ /** Poll `pred`, nudging the scheduler along with an empty forced plan (the 1s tick timer is the fallback). */
237
+ async function drive(root, pred, label, timeoutMs) {
238
+ const deadline = Date.now() + (timeoutMs || 15000)
239
+ while (Date.now() < deadline) {
240
+ if (pred()) return true
241
+ await pump(root)
242
+ await sleep(80)
243
+ }
244
+ if (pred()) return true
245
+ console.error(' .. drive timed out: ' + label)
246
+ return false
247
+ }
248
+ /** Fire the next `results.length` verifiers of one object (any of its candidate rIds). */
249
+ async function runVerifyRound(root, target, results, timeoutMs) {
250
+ const re = verifyRe(target)
251
+ const ok = await drive(root, () => unfiredVerifiers(root, re).length >= results.length, 'verifiers for r-' + target, timeoutMs)
252
+ if (!ok) return null
253
+ const un = unfiredVerifiers(root, re).slice(0, results.length)
254
+ for (let i = 0; i < un.length; i++) { firedChildren.add(un[i].childId); fireEnd(un[i].childId, { Result: results[i], Reason: 'mock 裁决 ' + results[i] }) }
255
+ await sleep(220)
256
+ return un
257
+ }
258
+ /** Abort + restart: gives the next verification a FRESH task, so a prompt is guaranteed to be
259
+ * constructed after whatever changed in between (mode switch, archived proof, …). */
260
+ async function restart(root) {
261
+ await callTool('vibe_math_abort', {}, root)
262
+ await callTool('vibe_math_start', {}, root)
263
+ markFloor(root)
264
+ }
265
+
266
+ console.log('-- V3 Lean formal verification --')
267
+ console.log('plugin under test: ' + PLUGIN.href)
268
+
269
+ // ===============================================================
270
+ // 1. 'off' is a true no-op
271
+ // ===============================================================
272
+ section("1 'off' (default) is a true no-op")
273
+ const RA = makeRoot()
274
+ await callTool('vibe_math_new_project', { name: 'lean-off' }, RA)
275
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS), RA)
276
+ await callTool('vibe_math_add_proposition', { id: 'p-off', 概述: '关模式下的普通命题', 概率: 0.6, 分类: '数论' }, RA)
277
+ await callTool('vibe_math_start', {}, RA)
278
+ const offRound = await runVerifyRound(RA, 'p-off', [1, 1])
279
+ assert(offRound !== null && offRound.length === 2, 'off: two independent verifiers were asked (投票流程照常)')
280
+ const offProj = projRoot('lean-off')
281
+ assert(await drive(RA, () => existsSync(join(offProj, 'Verified', '命题', 'p-off.md')), 'off Verified card'), "'off' still finalizes on a unanimous boolean vote with NO Lean artifact")
282
+ {
283
+ const st = await callTool('vibe_math_status', {}, RA)
284
+ assert(st.params.formalVerify === 'off', "the default is 'off' (got " + st.params.formalVerify + ')')
285
+ const all = promptText(RA)
286
+ assert(!/Lean/.test(all), 'no prompt mentions Lean in off mode')
287
+ assert(!/形式化/.test(all), 'no prompt mentions 形式化 in off mode')
288
+ assert(!/\[形式化\]/.test(all), 'the [形式化] announcement line is absent in off mode')
289
+ }
290
+ assert(!/形式化/.test(readIf(join(offProj, 'Verified', '命题', 'p-off.md'))), 'the Verified card carries no formal line in off mode')
291
+ assert(!existsSync(join(offProj, 'Formal', 'Index.md')), 'no Formal/Index.md is produced in off mode (no formal record)')
292
+ assert(!existsSync(join(offProj, 'State', 'formal.json')), 'no State/formal.json is produced in off mode')
293
+ {
294
+ const st = await callTool('vibe_math_status', {}, RA)
295
+ assert(st.formal.mode === 'off' && st.formal.objects.length === 0, 'status reports mode=off with zero formal objects')
296
+ }
297
+ // the tools still EXIST in off mode (static registration), they are just never advertised
298
+ assert(!!toolRegs.find((t) => t.name === 'vibe_math_lean_run') && !!toolRegs.find((t) => t.name === 'vibe_math_lean_archive') && !!toolRegs.find((t) => t.name === 'vibe_math_lean_lib'),
299
+ 'the three Lean tools are registered in every mode (registration is static)')
300
+
301
+ // ★ The mode switch must be REACHABLE THROUGH THE TOOL SCHEMA (2.3.2 defect D1) ──────────────
302
+ // Every tool schema here is closed (`additionalProperties:false`), so a key the schema does not
303
+ // advertise is REJECTED by any schema-validating provider. v3 shipped 2.3.0/2.3.1 with all four Lean
304
+ // parameters missing from the set-params schema while every assertion in this file stayed green —
305
+ // because the suite calls the handler DIRECTLY and never inspects the registered schema. The feature
306
+ // could not be switched on at all through the tool interface.
307
+ {
308
+ const setSpec = toolRegs.find((t) => t.name === 'vibe_math_set_params')
309
+ assert(!!setSpec, "vibe_math_set_params is registered")
310
+ assert(setSpec.parameters && setSpec.parameters.type === 'object' && setSpec.parameters.additionalProperties === false,
311
+ '★ vibe_math_set_params publishes a CLOSED object schema (an unlisted key is rejected, so the schema IS the contract)')
312
+ for (const k of ['formalVerify', 'leanCommand', 'leanArgs', 'leanTimeoutMs']) {
313
+ assert(Object.prototype.hasOwnProperty.call(setSpec.parameters.properties, k),
314
+ '★ the registered schema advertises ' + k + ' (every other surface documents it; a schema that omits it makes the switch unreachable)')
315
+ }
316
+ assert(JSON.stringify(setSpec.parameters.properties.formalVerify.enum) === JSON.stringify(['off', 'encourage', 'require']),
317
+ 'the schema narrows formalVerify to the three real modes (a typo must not be a fourth)')
318
+ }
319
+
320
+ // A stray `formal` reply in OFF mode must be INERT (finding #1): the absorber is mode-gated, and the
321
+ // reply contract does not offer the field in off mode. The TOOLS stay usable on purpose.
322
+ {
323
+ const RB0 = makeRoot()
324
+ await callTool('vibe_math_new_project', { name: 'lean-off-reply' }, RB0)
325
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS), RB0)
326
+ await callTool('vibe_math_add_proposition', { id: 'p-offr', 概述: '关模式下的回执注入测试', 概率: 0.6, 分类: '数论' }, RB0)
327
+ await callTool('vibe_math_start', {}, RB0)
328
+ const re0 = verifyRe('p-offr')
329
+ const ok0 = await drive(RB0, () => unfiredVerifiers(RB0, re0).length >= 1, 'off-reply verifier')
330
+ assert(ok0, 'off mode: a verifier wake exists to carry the stray formal reply')
331
+ const un0 = unfiredVerifiers(RB0, re0).slice(0, 1)
332
+ if (un0.length) {
333
+ firedChildren.add(un0[0].childId)
334
+ fireEnd(un0[0].childId, { Result: 0.5, Reason: '普通评审', formal: { target: 'p-offr', decision: 'defect', note: '不应被记录' } })
335
+ }
336
+ await sleep(220)
337
+ const pj0 = projRoot('lean-off-reply')
338
+ assert(!existsSync(join(pj0, 'State', 'formal.json')), '★ a stray `formal` reply in off mode writes NO State/formal.json')
339
+ const st0 = await callTool('vibe_math_status', {}, RB0)
340
+ assert(st0.formal.objects.length === 0, '★ and records no formal object')
341
+ }
342
+
343
+ // ===============================================================
344
+ // 2. parameter validation + runtime switching
345
+ // ===============================================================
346
+ section('2 parameter validation and runtime switching')
347
+ const RB = makeRoot()
348
+ await callTool('vibe_math_new_project', { name: 'lean-params' }, RB)
349
+ const bad = await callTool('vibe_math_set_params', { formalVerify: 'banana' }, RB)
350
+ assert(bad.params.formalVerify === 'off', "an unknown mode degrades to 'off', never to a stronger mode (got " + bad.params.formalVerify + ')')
351
+ const bad2 = await callTool('vibe_math_set_params', { formalVerify: 'REQUIRE' }, RB)
352
+ assert(bad2.params.formalVerify === 'off', 'the mode is matched exactly (a case typo cannot force formalization)')
353
+ const enc = await callTool('vibe_math_set_params', { formalVerify: 'encourage' }, RB)
354
+ assert(enc.params.formalVerify === 'encourage', "'encourage' is accepted")
355
+ const req = await callTool('vibe_math_set_params', { formalVerify: 'require', leanTimeoutMs: -5, leanCommand: ' ' }, RB)
356
+ assert(req.params.formalVerify === 'require', "'require' is accepted")
357
+ assert(req.params.leanTimeoutMs === 120000, 'a non-positive leanTimeoutMs falls back to the default (' + req.params.leanTimeoutMs + ')')
358
+ assert((await callTool('vibe_math_set_params', { leanTimeoutMs: 0 }, RB)).params.leanTimeoutMs === 120000, 'leanTimeoutMs=0 also falls back to the default')
359
+ assert(req.params.leanCommand === 'lean', 'a blank leanCommand falls back to "lean"')
360
+ const t5 = await callTool('vibe_math_set_params', { leanTimeoutMs: 5000 }, RB)
361
+ assert(t5.params.leanTimeoutMs === 5000, 'a positive leanTimeoutMs is accepted (got ' + t5.params.leanTimeoutMs + ')')
362
+ const arrBad = await callTool('vibe_math_set_params', { leanArgs: 'not-an-array' }, RB)
363
+ assert(Array.isArray(arrBad.params.leanArgs) && arrBad.params.leanArgs.length === 0, 'a non-array leanArgs falls back to []')
364
+ await callTool('vibe_math_set_params', { leanCommand: 'lake', leanArgs: ['env', 'lean'] }, RB)
365
+ const stL = await callTool('vibe_math_status', {}, RB)
366
+ assert(stL.params.leanCommand === 'lake' && stL.params.leanArgs.join(' ') === 'env lean', 'leanCommand/leanArgs are settable (lake env lean)')
367
+ {
368
+ const setup = await callTool('vibe_math_setup', {}, RB)
369
+ const names = setup.parameters.map((p) => p.name)
370
+ assert(names.indexOf('formalVerify') !== -1 && names.indexOf('leanCommand') !== -1 && names.indexOf('leanArgs') !== -1 && names.indexOf('leanTimeoutMs') !== -1,
371
+ 'the settings schema surfaces all four Lean parameters')
372
+ const f = setup.parameters.find((p) => p.name === 'formalVerify')
373
+ assert(f.default === 'off' && f.current === 'require', 'the schema carries the default (off) and the current value (require)')
374
+ const tmpl = await callTool('vibe_math_template', { where: 'project' }, RB)
375
+ const tj = readIf(join(projRoot('lean-params'), 'vibe_math_setting.json'))
376
+ assert(tmpl.ok === true && /"formalVerify": "off"/.test(tj) && /"leanArgs": \[\]/.test(tj), 'the generated settings template documents the Lean parameters with their defaults')
377
+ assert(/formalVerify — /.test(tj), 'the template carries the human-readable parameter description as a comment')
378
+ }
379
+
380
+ // ===============================================================
381
+ // 3. 'encourage' injection into the WORK prompts
382
+ // ===============================================================
383
+ section("3 'encourage' injects 顺手形式化 into solver / explorer / method-keeper prompts")
384
+ const RC = makeRoot()
385
+ await callTool('vibe_math_new_project', { name: 'lean-work' }, RC)
386
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'encourage', methodKeepEvery: 1 }), RC)
387
+ await callTool('vibe_math_add_problem', { id: 'qE', description: '证明 log 2 是无理数', priority: 0 }, RC)
388
+ await callTool('vibe_math_start', {}, RC)
389
+ assert(await drive(RC, () => !!lastSpawn(RC, 'explorer:qE'), 'explorer:qE'), 'fallback scheduler spawned explorer:qE')
390
+ {
391
+ const p = lastSpawn(RC, 'explorer:qE').prompt
392
+ assert(/【顺手形式化(鼓励)】/.test(p), 'the explorer work prompt carries the 顺手形式化 line')
393
+ assert(/vibe_math_lean_archive kind='def'/.test(p), 'the work prompt points at the archive tool for reusable definitions')
394
+ assert(/vibe_math_lean_lib 查重/.test(p), 'the work prompt tells agents to check the reuse library first')
395
+ assert(/形式化回执/.test(p) && /"decision":"used\|blocked\|defect"/.test(p), '★ the work-round reply contract also advertises the formal field, defect included (契约 §6.3)')
396
+ }
397
+ fireEnd(lastSpawn(RC, 'explorer:qE').childId, { meta: { kind: 'directions', qid: 'qE', formal: { target: 'qE', decision: 'blocked', note: '需要先形式化连分数收敛定理' }, directions: [{ id: 'd1', title: '连分数法', method: 'e 的连分数', core_assumption: '', feasibility: 0.7 }] } })
398
+ // Answer EVERY explorer the fallback scheduler dispatches (it re-derives when a direction looks
399
+ // unattended) until the solver for d1 appears — otherwise the retry cap can stall the project.
400
+ for (let guard = 0; guard < 40 && !lastSpawn(RC, 'solver:qE:d1'); guard++) {
401
+ const ex = spawns.filter((s) => s.rootId === RC.id && s.label.startsWith('explorer:qE') && !firedChildren.has(s.childId)).slice(-1)[0]
402
+ if (ex) {
403
+ firedChildren.add(ex.childId)
404
+ fireEnd(ex.childId, { meta: { kind: 'directions', qid: 'qE', directions: [{ id: 'd1', title: '连分数法', method: 'e 的连分数', core_assumption: '', feasibility: 0.7 }] } })
405
+ }
406
+ await pump(RC)
407
+ await sleep(80)
408
+ }
409
+ assert(!!lastSpawn(RC, 'solver:qE:d1'), 'solver spawned for direction d1')
410
+ assert(/【顺手形式化(鼓励)】/.test(lastSpawn(RC, 'solver:qE:d1').prompt), 'the solver work prompt carries the 顺手形式化 line')
411
+ {
412
+ // the explorer's `meta.formal` judgement is recorded even though it never called a Lean tool
413
+ const st = await callTool('vibe_math_status', {}, RC)
414
+ assert(st.formal.blocked.indexOf('qE') !== -1, '★ an explorer `meta.formal` judgement is recorded (no Lean tool call needed)')
415
+ assert(/- 形式化: 阻塞(/.test(readIf(join(projRoot('lean-work'), 'Problems', 'qE.md'))), 'and it lands on the problem card anchor')
416
+ }
417
+ fireEnd(lastSpawn(RC, 'solver:qE:d1').childId, { status: 'continue', survival_probability: 0.6, formal: { target: 'd1-lemma', decision: 'used', file: 'Formal/d1-lemma.lean' }, new_inventions: [{ 类型: '工具', 标题: '连分数估值工具', 内容描述: '控制收敛速度', 是否已入库: false }] })
418
+ await sleep(250)
419
+ {
420
+ const st = await callTool('vibe_math_status', {}, RC)
421
+ assert(st.formal.objects.some((o) => o.target === 'd1-lemma' && o.status === 'attempted'), 'a solver top-level `formal.decision=used` reply records the object as attempted')
422
+ }
423
+ assert(await drive(RC, () => !!lastSpawn(RC, 'method-keeper'), 'method-keeper'), 'method keeper spawned for the pending invention')
424
+ {
425
+ const p = lastSpawn(RC, 'method-keeper').prompt
426
+ assert(/【顺手形式化(鼓励)】/.test(p), 'the method-keeper prompt carries the 顺手形式化 line')
427
+ assert(/【方法沉淀 × Lean 形式化】/.test(p), '★ the method keeper is told to ALSO sediment reusable Lean definitions/lemmas')
428
+ assert(/kind='lemma'/.test(p) && /Proved/.test(p), 'and where the proved lemmas go')
429
+ }
430
+ await callTool('vibe_math_abort', {}, RC)
431
+ assert((await callTool('vibe_math_status', {}, RC)).running === false, 'work-prompt scenario aborted (keeps later scenarios deterministic)')
432
+
433
+ // ===============================================================
434
+ // 4. 'encourage' injection into BOTH verification prompts + the fidelity switch
435
+ // ===============================================================
436
+ section("4 'encourage' reaches the review prompt and the debate prompt")
437
+ const RD = makeRoot()
438
+ await callTool('vibe_math_new_project', { name: 'lean-verify' }, RD)
439
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'encourage', debateMaxRounds: 2 }), RD)
440
+ await callTool('vibe_math_add_proposition', { id: 'p-enc', 概述: '鼓励模式下的忠实性审查', 概率: 0.6, 分类: '数论' }, RD)
441
+ await callTool('vibe_math_start', {}, RD)
442
+ const encBatch = await runVerifyRound(RD, 'p-enc', [0.9, 0.95])
443
+ assert(encBatch !== null, 'encourage: the first review round was asked')
444
+ if (encBatch) {
445
+ const vp = encBatch.map((s) => s.prompt).join('\n')
446
+ assert(/【Lean 形式化验证(鼓励模式)】/.test(vp), 'the review prompt explains the Lean mode')
447
+ assert(/一旦 Lean 通过,你唯一需要确认的就是忠实性/.test(vp), 'the review prompt states that a passing Lean run shrinks the question to fidelity')
448
+ assert(/实现难度/.test(vp), 'the review prompt asks for the implementation-difficulty judgement')
449
+ assert(/可以不做,但请在回执的 formal 字段写明难度判断/.test(vp), "'encourage' explicitly allows skipping (with a recorded judgement)")
450
+ assert(/"formal":/.test(vp) && /"decision":"used\|blocked\|defect"/.test(vp), 'the reply contract documents the formal field (defect included)')
451
+ assert(/vibe_math_lean_run/.test(vp) && /vibe_math_lean_archive/.test(vp) && /vibe_math_lean_lib/.test(vp), 'the prompt names the three v3 Lean tools')
452
+ assert(/Formal\/(相对项目根)/.test(vp) && /VibeMath\/Formal\/Lib/.test(vp), 'the prompt states the path layout')
453
+ }
454
+ // a non-consensus round moves to the public debate, whose prompt must carry the same injection
455
+ assert(await drive(RD, () => wakes.some((w) => w.rootId === RD.id && /交流群/.test(w.prompt)), 'debate prompt'), 'a non-consensus round moved to the debate')
456
+ {
457
+ const dp = wakes.filter((w) => w.rootId === RD.id).map((w) => w.prompt).join('\n')
458
+ assert(/【Lean 形式化验证(鼓励模式)】/.test(dp), 'the debate prompt names the mode')
459
+ assert(/一旦 Lean 通过,你唯一需要确认的就是忠实性|你不需要重新检查推导/.test(dp), 'the debate prompt carries the Lean block too')
460
+ assert(/"formal":/.test(dp), 'the debate reply contract carries the formal field')
461
+ }
462
+ // finish the debate: a unanimous round concludes
463
+ if (encBatch) for (const b of encBatch) fireEnd(b.childId, { Result: 1, Reason: 'mock 第二轮一致' })
464
+ assert(await drive(RD, () => existsSync(join(projRoot('lean-verify'), 'Verified', '命题', 'p-enc.md')), 'p-enc verified'), 'the debate finished and the object was verified')
465
+
466
+ // ===============================================================
467
+ // 5. lean_run executes through the subprocess service and reports honestly
468
+ // ===============================================================
469
+ section('5 lean_run executes through the subprocess service and reports honestly')
470
+ const RE = makeRoot()
471
+ await callTool('vibe_math_new_project', { name: 'lean-tools' }, RE)
472
+ await callTool('vibe_math_set_params', { formalVerify: 'encourage' }, RE)
473
+ await callTool('vibe_math_add_proposition', { id: 'p-tool', 概述: '工具实验命题', 概率: 0.6, 分类: '数论' }, RE)
474
+ const toolProj = projRoot('lean-tools')
475
+ mkdirSync(join(toolProj, 'Formal'), { recursive: true })
476
+ writeFileSync(join(toolProj, 'Formal', 'good.lean'), 'theorem t : 1 = 1 := rfl\n', 'utf8')
477
+ writeFileSync(join(toolProj, 'Formal', 'bad.lean'), 'theorem t : 1 = 2 := by sorry\n', 'utf8')
478
+ writeFileSync(join(toolProj, 'Formal', 'hang.lean'), '-- HANG\ntheorem t : 1 = 1 := rfl\n', 'utf8')
479
+ {
480
+ const runGood = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean', target: 'p-tool' }, RE)
481
+ assert(runGood.ok === true && runGood.exitCode === 0, 'a file with no sorry runs green (' + JSON.stringify({ ok: runGood.ok, exitCode: runGood.exitCode }) + ')')
482
+ assert(/ok/.test(runGood.stdout), 'the compiler stdout is returned')
483
+ const last = leanRuns[leanRuns.length - 1]
484
+ assert(last.cwd.replace(/\\/g, '/') === toolProj.replace(/\\/g, '/'), 'the toolchain runs with the PROJECT root as cwd')
485
+ assert(last.argv.join(' ') === 'lean', 'by default the argv is just the executable (got ' + last.argv.join(' ') + ')')
486
+ assert(last.graceMs === 120000, 'the default leanTimeoutMs is passed down as graceMs (' + last.graceMs + ')')
487
+ }
488
+ {
489
+ const st = await callTool('vibe_math_status', {}, RE)
490
+ const o = st.formal.objects.find((x) => x.target === 'p-tool')
491
+ assert(!!o && o.status === 'attempted', 'lean_run with target records the object as attempted (not passed)')
492
+ assert(!!o.run && o.run.ok === true, 'the run result is recorded on the object')
493
+ const card = readIf(join(toolProj, 'Propos', '数论', 'p-tool.md'))
494
+ assert(/- 形式化: 已尝试未通过/.test(card), '★ the object card anchor block gains `- 形式化: <状态>` alongside 状态/概率')
495
+ assert(/\n- ID: p-tool\n/.test(card) && /\n- 状态: 未定论\n/.test(card) && /\n- 概率: 0.6\n/.test(card), 'the pre-existing anchors are untouched (the scheduler parser keeps working)')
496
+ }
497
+ {
498
+ const runBad = await callTool('vibe_math_lean_run', { file: 'Formal/bad.lean' }, RE)
499
+ assert(runBad.ok === false && runBad.exitCode === 1, 'a file that still uses sorry reports a red run')
500
+ assert(/sorry/.test(runBad.stderr), 'the compiler output is returned verbatim (' + JSON.stringify(runBad.stderr).slice(0, 60) + ')')
501
+ assert(/修复后重跑/.test(runBad.hint || ''), 'a genuine compile failure still points at the compiler output (the hint is failure-code aware, not blanket)')
502
+ }
503
+ {
504
+ const runMissing = await callTool('vibe_math_lean_run', { file: 'Formal/nope.lean' }, RE)
505
+ assert(runMissing.ok === false && runMissing.code === 'V3_NOT_FOUND', 'a missing file is refused with a typed code')
506
+ }
507
+ {
508
+ // The guard's boundary is the VibeMath ROOT, not the project: the global reuse library
509
+ // deliberately lives at <VibeMath>/Formal/{Lib,Proved}, so climbing out of the project but
510
+ // staying inside VibeMath must remain legal (it just fails as a missing file).
511
+ const inside = await callTool('vibe_math_lean_run', { file: '../../Formal/Lib/x.lean' }, RE)
512
+ assert(inside.code === 'V3_NOT_FOUND', 'climbing out of the project but staying inside VibeMath is allowed (the global library lives there)')
513
+ const esc1 = await callTool('vibe_math_lean_run', { file: '../../../evil.lean' }, RE)
514
+ assert(esc1.ok === false && esc1.code === 'V3_INVALID_ARGUMENT', '★ a traversal that climbs ABOVE the VibeMath root is refused')
515
+ const esc2 = await callTool('vibe_math_lean_run', { file: 'Formal/../../../../../../evil.lean' }, RE)
516
+ assert(esc2.ok === false && esc2.code === 'V3_INVALID_ARGUMENT', 'a deeper traversal is refused too')
517
+ const esc3 = await callTool('vibe_math_lean_run', { file: '/etc/evil.lean' }, RE)
518
+ assert(esc3.ok === false && esc3.code === 'V3_INVALID_ARGUMENT', 'an unrelated absolute path is refused')
519
+ const notLean = await callTool('vibe_math_lean_run', { file: 'Formal/good.txt' }, RE)
520
+ assert(notLean.ok === false && notLean.code === 'V3_INVALID_ARGUMENT', 'only .lean files can be executed')
521
+ const noFile = await callTool('vibe_math_lean_run', {}, RE)
522
+ assert(noFile.ok === false && noFile.code === 'V3_INVALID_ARGUMENT', 'a missing file argument is refused')
523
+ }
524
+ {
525
+ toolchainAvailable = false
526
+ const runNoTc = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean' }, RE)
527
+ assert(runNoTc.ok === false && runNoTc.code === 'LEAN_NOT_FOUND', 'a missing toolchain returns LEAN_NOT_FOUND instead of crashing')
528
+ assert(/仍可把形式化代码写下来归档/.test(runNoTc.message), 'the failure explains the graceful degradation')
529
+ assert(/本宿主无法执行 Lean(LEAN_NOT_FOUND)/.test(runNoTc.hint || '') && !/编译器输出修复后重跑/.test(runNoTc.hint || ''),
530
+ '★ the failure hint never tells the agent to fix compiler output that does not exist — it points at the archive + explicit-blocker way out (§6 hard requirement 4)')
531
+ toolchainAvailable = true
532
+ }
533
+ {
534
+ subprocessAvailable = false
535
+ const runNoSub = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean' }, RE)
536
+ assert(runNoSub.ok === false && runNoSub.code === 'NO_SUBPROCESS', 'a host without the subprocess service returns NO_SUBPROCESS')
537
+ assert(/本宿主无法执行 Lean(NO_SUBPROCESS)/.test(runNoSub.hint || '') && /vibe_math_lean_archive/.test(runNoSub.hint || ''),
538
+ '★ the NO_SUBPROCESS hint names the way out with the FULL tool name (no retry loop on an impossible run)')
539
+ subprocessAvailable = true
540
+ }
541
+ {
542
+ const runHang = await callTool('vibe_math_lean_run', { file: 'Formal/hang.lean', timeout_ms: 1000 }, RE)
543
+ assert(runHang.ok === false && runHang.code === 'LEAN_TIMEOUT' && runHang.timedOut === true, '★ a hanging toolchain returns LEAN_TIMEOUT instead of wedging the scheduler')
544
+ assert(terminated.some((f) => /hang\.lean$/.test(f)), '★ the timeout path calls handle.terminate()')
545
+ }
546
+ {
547
+ spawnThrows = true
548
+ const runSpawn = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean' }, RE)
549
+ assert(runSpawn.ok === false && runSpawn.code === 'LEAN_SPAWN_FAILED', 'a spawn failure is reported as LEAN_SPAWN_FAILED instead of throwing')
550
+ spawnThrows = false
551
+ writeFileSync(join(toolProj, 'Formal', 'reject.lean'), '-- REJECT\ntheorem t : 1 = 1 := rfl\n', 'utf8')
552
+ const runReject = await callTool('vibe_math_lean_run', { file: 'Formal/reject.lean' }, RE)
553
+ assert(runReject.ok === false && runReject.code === 'LEAN_RUN_FAILED', 'a rejecting handle.done is reported as LEAN_RUN_FAILED instead of throwing into the loop')
554
+ }
555
+ {
556
+ await callTool('vibe_math_set_params', { leanCommand: 'lake', leanArgs: ['env', 'lean'] }, RE)
557
+ const runLake = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean' }, RE)
558
+ assert(runLake.ok === true, 'lake env lean works through leanCommand/leanArgs')
559
+ assert(leanRuns[leanRuns.length - 1].argv.join(' ') === 'lake env lean', 'the argv is [exe, ...leanArgs, file] (got ' + leanRuns[leanRuns.length - 1].argv.join(' ') + ')')
560
+ await callTool('vibe_math_set_params', { leanCommand: 'lean', leanArgs: [] }, RE)
561
+ }
562
+
563
+ // ===============================================================
564
+ // 6. lean_archive: def / lemma / proof / blocked → the right paths + indexes
565
+ // ===============================================================
566
+ section('6 lean_archive writes the contract paths and rebuilds the indexes')
567
+ const libPath = join(VIBE, 'Formal', 'Lib')
568
+ const provedPath = join(VIBE, 'Formal', 'Proved')
569
+ {
570
+ const defRes = await callTool('vibe_math_lean_archive', { kind: 'def', name: 'ZMod5', content: 'def ZMod5 := Fin 5\n' }, RE)
571
+ assert(defRes.ok === true && defRes.file === 'Formal/Lib/ZMod5.lean', 'a reusable definition is archived to the global lib (' + defRes.file + ')')
572
+ assert(existsSync(join(libPath, 'ZMod5.lean')), '★ the definition exists under VibeMath/Formal/Lib/ (cross-project, NOT inside the project)')
573
+ assert(!existsSync(join(toolProj, 'Formal', 'Lib', 'ZMod5.lean')), 'it is NOT duplicated inside the project tree')
574
+ assert(defRes.run && defRes.run.ok === true, 'the reusable definition is executed on archive (run defaults to true)')
575
+ const libIdx = readIf(join(libPath, 'Index.md'))
576
+ assert(/\| 名称 \| 文件 \| 类别 \| 摘要 \| 最近运行 \|/.test(libIdx), 'Lib/Index.md uses the contract columns')
577
+ assert(/ZMod5/.test(libIdx) && /Lib\/ZMod5\.lean/.test(libIdx) && /\| ok \|/.test(libIdx), 'Lib/Index.md lists the new definition with its run result')
578
+ assert(!/ZMod5/.test(readIf(join(toolProj, 'Formal', 'Index.md'))), 'the global definition does not pollute the project formal index')
579
+ }
580
+ {
581
+ const lemRes = await callTool('vibe_math_lean_archive', { kind: 'lemma', name: 'sq_odd', content: 'import Mathlib\n\ntheorem sq_odd (n : Nat) : Odd (n*n) → Odd n := by omega\n' }, RE)
582
+ assert(lemRes.ok === true && lemRes.file === 'Formal/Proved/sq_odd.lean', 'a lemma is archived to Proved/')
583
+ assert(existsSync(join(provedPath, 'sq_odd.lean')), 'the lemma exists under VibeMath/Formal/Proved/')
584
+ const provedIdx = readIf(join(provedPath, 'Index.md'))
585
+ assert(/\| 名称 \| 文件 \| 陈述 \| 依赖 \| 最近运行 \|/.test(provedIdx), 'Proved/Index.md uses the contract columns')
586
+ assert(/sq_odd/.test(provedIdx) && /Mathlib/.test(provedIdx), 'Proved/Index.md lists the lemma and its imports as 依赖')
587
+ }
588
+ {
589
+ const noRun = await callTool('vibe_math_lean_archive', { kind: 'def', name: 'NoRun', content: 'def NoRun := 1\n', run: false }, RE)
590
+ assert(noRun.ok === true && noRun.run === undefined, 'run=false archives WITHOUT executing (no toolchain needed)')
591
+ }
592
+ {
593
+ const noName = await callTool('vibe_math_lean_archive', { kind: 'def', content: 'def x := 1\n' }, RE)
594
+ assert(noName.ok === false && noName.code === 'V3_INVALID_ARGUMENT', 'archiving a definition without a name is refused')
595
+ const badKind = await callTool('vibe_math_lean_archive', { kind: 'nonsense' }, RE)
596
+ assert(badKind.ok === false && badKind.code === 'V3_INVALID_ARGUMENT', 'an unknown archive kind is refused')
597
+ const noTarget = await callTool('vibe_math_lean_archive', { kind: 'proof', content: 'theorem x : 1 = 1 := rfl\n' }, RE)
598
+ assert(noTarget.ok === false && noTarget.code === 'V3_INVALID_ARGUMENT', 'kind=proof without a target is refused')
599
+ const noBody = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-x' }, RE)
600
+ assert(noBody.ok === false && noBody.code === 'V3_INVALID_ARGUMENT', 'kind=proof without content/from is refused')
601
+ const badFrom = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-x', from: '../../../evil.lean' }, RE)
602
+ assert(badFrom.ok === false && badFrom.code === 'V3_INVALID_ARGUMENT', 'kind=proof with an out-of-tree from is refused')
603
+ }
604
+ {
605
+ // a green proof → passed + Verified/Lean (the archived proof lives next to the conclusion)
606
+ const arc = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-proof', content: 'theorem p_proof : 3 * 1 ^ 2 - 2 = (1:Nat) ^ 2 := by decide\n' }, RE)
607
+ assert(arc.ok === true && arc.passed === true, 'the proof is archived and passes (' + JSON.stringify({ ok: arc.ok, passed: arc.passed }) + ')')
608
+ assert(arc.file === 'Formal/p-proof.lean', 'the working file is Formal/<target>.lean')
609
+ assert(arc.proof === 'Verified/Lean/p-proof.lean', 'the archived proof path is Verified/Lean/<target>.lean')
610
+ assert(existsSync(join(toolProj, 'Formal', 'p-proof.lean')), 'the working file exists on disk')
611
+ assert(existsSync(join(toolProj, 'Verified', 'Lean', 'p-proof.lean')), '★ the proof is archived under Verified/Lean/ as the proof of that object')
612
+ const st = await callTool('vibe_math_status', {}, RE)
613
+ assert(st.formal.passed.indexOf('p-proof') !== -1, 'status reports the object as Lean-passed')
614
+ const idx = readIf(join(toolProj, 'Formal', 'Index.md'))
615
+ assert(/# Lean 形式化索引/.test(idx) && /p-proof/.test(idx) && /passed/.test(idx) && /Verified\/Lean\/p-proof\.lean/.test(idx), 'Formal/Index.md indexes the object, its status and its archived proof')
616
+ assert(/ok(exit 0,/.test(idx), 'the index shows the run result in the contract format')
617
+ // a RED proof must NOT become passed
618
+ const red = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-red', content: 'theorem p_red : 1 = 2 := by sorry\n' }, RE)
619
+ assert(red.ok === true && red.passed === false && red.status === 'attempted', 'a red proof is archived as attempted, not passed')
620
+ assert(!existsSync(join(toolProj, 'Verified', 'Lean', 'p-red.lean')), '★ no archived proof is written for a red run')
621
+ }
622
+ {
623
+ const blkNoNote = await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-blk' }, RE)
624
+ assert(blkNoNote.ok === false && blkNoNote.code === 'V3_INVALID_ARGUMENT', 'blocked without a note is refused')
625
+ const blk = await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-blk', note: '需要外层解析数论框架,本轮工作量不可接受' }, RE)
626
+ assert(blk.ok === true && blk.status === 'blocked', 'a reasoned blocker is recorded')
627
+ const stBlk = await callTool('vibe_math_status', {}, RE)
628
+ assert(stBlk.formal.blocked.indexOf('p-blk') !== -1, 'status lists the blocked object')
629
+ assert(/需要外层解析数论框架/.test(readIf(join(toolProj, 'Formal', 'Index.md'))), 'the blocker reason is written into the index')
630
+ }
631
+ {
632
+ const libList = await callTool('vibe_math_lean_lib', {}, RE)
633
+ assert(libList.ok === true && libList.counts.lib >= 2 && libList.counts.proved >= 1, 'lean_lib reports the reuse library sizes (' + JSON.stringify(libList.counts) + ')')
634
+ assert(libList.objects.some((o) => o.target === 'p-proof' && o.status === 'passed'), 'lean_lib lists per-object formal status')
635
+ assert(/复用优先/.test(libList.hint || ''), 'lean_lib tells agents to reuse before redefining')
636
+ assert(libList.paths && /VibeMath\/Formal\/Lib/.test(libList.paths.lib), 'lean_lib reports the cross-project path layout')
637
+ const ro = await callTool('vibe_math_lean_lib', { refresh: false }, RE)
638
+ assert(ro.rebuilt === false && ro.counts.lib === null, 'refresh:false only reads (does not rebuild the indexes)')
639
+ }
640
+ {
641
+ const ann = readIf(join(toolProj, 'Logs', '形式化.md'))
642
+ assert(/# 形式化公告/.test(ann) && /ZMod5/.test(ann) && /p-proof/.test(ann), 'the announcement log records what was formalized')
643
+ }
644
+
645
+ // ===============================================================
646
+ // 7. the 'require' gate
647
+ // ===============================================================
648
+ section("7 'require' withholds a verdict until the formal record exists")
649
+ const RF = makeRoot()
650
+ await callTool('vibe_math_new_project', { name: 'lean-gate' }, RF)
651
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RF)
652
+ await callTool('vibe_math_add_proposition', { id: 'p-gate', 概述: '必须形式化的命题', 概率: 0.6, 分类: '数论' }, RF)
653
+ const gateProj = projRoot('lean-gate')
654
+ await callTool('vibe_math_start', {}, RF)
655
+ {
656
+ const batch = await runVerifyRound(RF, 'p-gate', [1, 1])
657
+ assert(batch !== null, 'require: the review round was asked')
658
+ if (batch) {
659
+ const vp = batch.map((s) => s.prompt).join('\n')
660
+ assert(/【Lean 形式化验证(强制模式)】/.test(vp), 'the review prompt says 强制模式')
661
+ assert(/必须产出 Lean 形式化/.test(vp), "'require' states the formalization is mandatory")
662
+ assert(/本次裁定不会生效/.test(vp), 'the prompt warns that the verdict will not take effect without it')
663
+ assert(/formal-required/.test(vp), 'the prompt names the machine-readable reason')
664
+ assert(/归档可复用定义\/引理前先跑通(vibe_math_lean_archive run=true 或先 vibe_math_lean_run);跑不通不要入库。/.test(vp),
665
+ '★ the verification prompt requires a GREEN run before archiving into the reuse library (§6 hard requirement 3)')
666
+ assert(/宿主没有 Lean 工具链(LEAN_NOT_FOUND)或宿主不提供 subprocess 服务(NO_SUBPROCESS)时:把代码写下来归档,并在回执的 note 里写明"宿主无 Lean 工具链"/.test(vp),
667
+ '★ and spells out the way out when the host has no Lean toolchain, naming BOTH failure codes (LEAN_NOT_FOUND / NO_SUBPROCESS, §6 hard requirement 4)')
668
+ assert(/Result/.test(vp) && !/verdict/.test(vp) && !/(^|[^a-z_])lean_(run|archive|lib)/.test(vp),
669
+ '★ the voting prompt uses FULL tool names and names Result, never verdict (§6 hard requirements 1-2)')
670
+ }
671
+ }
672
+ assert(await drive(RF, () => /p-gate/.test(readIf(join(gateProj, 'Formal', 'TODO.md'))), 'p-gate in Formal/TODO.md'), '★ a unanimous TRUE verdict was withheld: the object is on the formalization TODO')
673
+ assert(!existsSync(join(gateProj, 'Verified', '命题', 'p-gate.md')), 'no Verified card was written')
674
+ {
675
+ const card = readIf(join(gateProj, 'Propos', '数论', 'p-gate.md'))
676
+ assert(/- 概率: 0.6/.test(card), '★ the object keeps its existing probability (no silent promotion to 1)')
677
+ assert(/- 状态: 未定论/.test(card), 'and its 状态 stays 未定论')
678
+ const todo = readIf(join(gateProj, 'Formal', 'TODO.md'))
679
+ assert(/# 形式化待办/.test(todo) && /p-gate/.test(todo) && /formal-required/.test(todo), '★ the TODO records the object with the machine-readable reason')
680
+ const idx = readIf(join(gateProj, 'Formal', 'Index.md'))
681
+ assert(/## 形式化待办/.test(idx) && /p-gate/.test(idx), 'Formal/Index.md mirrors the formalization TODO')
682
+ const ann = readIf(join(gateProj, 'Logs', '形式化.md'))
683
+ assert(/require 模式/.test(ann) && /不定论/.test(ann), '★ the withholding is announced')
684
+ const st = await callTool('vibe_math_status', {}, RF)
685
+ assert(st.formal.todo.some((t) => t.id === 'p-gate'), 'status lists the deferred object')
686
+ assert(/formal-required/.test(st.recentActivity.map((e) => e.detail).join('\n')), 'the activity feed shows the formal-required deferral')
687
+ const voteLog = readdirSync(join(gateProj, 'Logs', 'Verification')).filter((f) => /^r-p-gate_/.test(f))
688
+ assert(voteLog.length >= 1, 'the votes themselves are still recorded in Logs/Verification (nothing is lost)')
689
+ }
690
+ // runtime switch: the mode is read when the prompt is CONSTRUCTED, so a fresh round reflects it
691
+ await callTool('vibe_math_add_proposition', { id: 'p-mode', 概述: '模式切换观察对象', 概率: 0.6, 分类: '数论' }, RF)
692
+ await restart(RF)
693
+ assert(await drive(RF, () => unfiredVerifiers(RF, verifyRe('p-mode')).length >= 2, 'fresh verifiers in require mode'), 'a fresh object is still verified in require mode')
694
+ {
695
+ const fresh = unfiredVerifiers(RF, verifyRe('p-mode'))[0]
696
+ assert(!!fresh && /【Lean 形式化验证(强制模式)】/.test(fresh.prompt) && /本次裁定不会生效/.test(fresh.prompt), 'a fresh round reflects the current mode (强制模式)')
697
+ }
698
+ // ★ anti-idle: a deferred object must NOT be re-voted while it sits on the TODO (each round would
699
+ // just be withheld again, burning verifiers on the same rId every tick). The assertion is only
700
+ // meaningful because the previous block proved the scheduler IS allocating verify tasks here.
701
+ assert(unfiredVerifiers(RF, verifyRe('p-gate')).length === 0, '★ a deferred object is NOT re-voted while it sits on the formalization TODO (no verification livelock)')
702
+ await callTool('vibe_math_set_params', { formalVerify: 'encourage' }, RF)
703
+ await restart(RF)
704
+ assert(await drive(RF, () => unfiredVerifiers(RF, verifyRe('p-mode')).length >= 2, 'fresh verifiers after the mode switch'), 'the unresolved object is verified again after the mode switch')
705
+ {
706
+ const fresh = unfiredVerifiers(RF, verifyRe('p-mode'))[0]
707
+ assert(!!fresh && /【Lean 形式化验证(鼓励模式)】/.test(fresh.prompt), '★ switching the mode at runtime immediately changes the prompt (now 鼓励模式)')
708
+ assert(!!fresh && !/本次裁定不会生效/.test(fresh.prompt), 'and the mandatory wording is gone in encourage mode')
709
+ }
710
+ await callTool('vibe_math_set_params', { formalVerify: 'require' }, RF)
711
+ // formalize it, restart (so the next prompt is built AFTER the proof exists), then re-verify
712
+ {
713
+ const proofNow = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-gate', content: 'theorem p_gate : 2 + 2 = 4 := by decide\n' }, RF)
714
+ assert(proofNow.ok === true && proofNow.passed === true, 'the object is now Lean-passed')
715
+ const st = await callTool('vibe_math_status', {}, RF)
716
+ assert(st.formal.passed.indexOf('p-gate') !== -1, 'status reports p-gate as passed')
717
+ assert(!st.formal.todo.some((t) => t.id === 'p-gate'), '★ satisfying the gate removes the object from the formalization TODO (no stale TODO)')
718
+ assert(!/p-gate/.test(readIf(join(gateProj, 'Formal', 'TODO.md'))), 'Formal/TODO.md no longer lists it')
719
+ assert(/- 形式化: Lean 通过/.test(readIf(join(gateProj, 'Propos', '数论', 'p-gate.md'))), 'the object card anchor now records Lean 通过')
720
+ }
721
+ await restart(RF)
722
+ assert(await drive(RF, () => unfiredVerifiers(RF, verifyRe('p-gate')).length >= 2, 'p-gate re-eligible after passing'), '★ once the formal record satisfies the gate, the object becomes eligible for verification again')
723
+ {
724
+ const batch = await runVerifyRound(RF, 'p-gate', [1, 1])
725
+ assert(batch !== null, 'the re-verification round was asked')
726
+ if (batch) {
727
+ const vp = batch.map((s) => s.prompt).join('\n')
728
+ assert(/该对象已有\*\*通过的 Lean 形式化证明\*\*/.test(vp), 'the voting prompt announces the passing proof')
729
+ assert(/你不需要重新检查推导/.test(vp), '★ it tells voters NOT to re-derive')
730
+ assert(/忠实性审查/.test(vp), '★ it tells voters the review subject is now fidelity')
731
+ assert(/定义 \/ 对象 \/ 条件 \/ 假设 \/ 结论是否与命题原文\*\*完全一致\*\*/.test(vp), 'it enumerates exactly what fidelity means')
732
+ assert(!/必须产出 Lean 形式化/.test(vp), 'and the "must formalize" wording is replaced (the object already has one)')
733
+ }
734
+ }
735
+ assert(await drive(RF, () => existsSync(join(gateProj, 'Verified', '命题', 'p-gate.md')), 'p-gate Verified card'), '★ with a passing Lean artifact the same vote DOES promote it')
736
+ {
737
+ const card = readIf(join(gateProj, 'Verified', '命题', 'p-gate.md'))
738
+ assert(/- 形式化: Lean 通过/.test(card), '★ the Verified card records how strong the result is (Lean 通过)')
739
+ assert(/Verified\/Lean\/p-gate\.lean/.test(card), 'the card points at the archived proof')
740
+ assert(/- 结论: 真/.test(card), 'the card states the conclusion')
741
+ }
742
+ // the blocker escape hatch must also open the gate
743
+ await callTool('vibe_math_add_proposition', { id: 'p-blocked-ok', 概述: '记录阻塞后可定论', 概率: 0.6, 分类: '数论' }, RF)
744
+ await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-blocked-ok', note: '命题涉及未形式化的分析学,本轮不做' }, RF)
745
+ await restart(RF)
746
+ assert(await runVerifyRound(RF, 'p-blocked-ok', [1, 1]) !== null, 'the blocked object is put to a vote')
747
+ assert(await drive(RF, () => existsSync(join(gateProj, 'Verified', '命题', 'p-blocked-ok.md')), 'p-blocked-ok Verified card'), '★ an explicit reasoned blocker also lets the verdict through (decide by difficulty, but decide out loud)')
748
+ {
749
+ const card = readIf(join(gateProj, 'Verified', '命题', 'p-blocked-ok.md'))
750
+ assert(/- 形式化: 阻塞(/.test(card), 'the Verified card records the blocker')
751
+ assert(/未形式化的分析学/.test(card), 'and quotes the reason')
752
+ }
753
+
754
+ // ===============================================================
755
+ // 8. the reply-channel judgement (formal field in the verifier reply)
756
+ // ===============================================================
757
+ section('8 the per-round `formal` reply channel records the difficulty judgement')
758
+ const RG = makeRoot()
759
+ await callTool('vibe_math_new_project', { name: 'lean-reply' }, RG)
760
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RG)
761
+ const replyProj = projRoot('lean-reply')
762
+
763
+ // (a) blocked WITH a note → recorded, reason reaches the index + the card anchor
764
+ await callTool('vibe_math_add_proposition', { id: 'p-reply', 概述: '用回执记录阻塞', 概率: 0.6, 分类: '数论' }, RG)
765
+ await callTool('vibe_math_start', {}, RG)
766
+ {
767
+ const re = verifyRe('p-reply')
768
+ assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-reply'), 'p-reply was put to a vote')
769
+ const vs = unfiredVerifiers(RG, re).slice(0, 2)
770
+ if (vs.length === 2) {
771
+ for (const v of vs) firedChildren.add(v.childId)
772
+ // A verifier that never calls a Lean tool still has to state its difficulty judgement: the
773
+ // JSON reply channel is the path that actually fires in practice.
774
+ fireEnd(vs[0].childId, { Result: 0.5, Reason: '我判断形式化不划算', formal: { target: 'p-reply', decision: 'blocked', note: '需要大量未形式化的实分析前置知识' } })
775
+ await sleep(150)
776
+ const st1 = await callTool('vibe_math_status', {}, RG)
777
+ assert(st1.formal.blocked.indexOf('p-reply') !== -1, 'a `formal.decision=blocked` reply is recorded as a blocker')
778
+ assert(/实分析前置知识/.test(readIf(join(replyProj, 'Formal', 'Index.md'))), 'and its reason reaches the index')
779
+ assert(/- 形式化: 阻塞(/.test(readIf(join(replyProj, 'Propos', '数论', 'p-reply.md'))), 'the reply-recorded blocker also lands on the object card anchor')
780
+ fireEnd(vs[1].childId, { Result: 0.5, Reason: '同上' })
781
+ await sleep(200)
782
+ }
783
+ }
784
+ // (b) `used` records attempted — which does NOT open the require gate
785
+ await restart(RG)
786
+ await callTool('vibe_math_add_proposition', { id: 'p-used', 概述: '写了草稿但没跑通', 概率: 0.6, 分类: '数论' }, RG)
787
+ {
788
+ const re = verifyRe('p-used')
789
+ assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-used'), 'p-used was put to a vote')
790
+ const vs = unfiredVerifiers(RG, re).slice(0, 2)
791
+ if (vs.length === 2) {
792
+ for (const v of vs) firedChildren.add(v.childId)
793
+ fireEnd(vs[0].childId, { Result: 1, Reason: '看起来对', formal: { target: 'p-used', decision: 'used', file: 'Formal/p-used.lean' } })
794
+ await sleep(150)
795
+ const st = await callTool('vibe_math_status', {}, RG)
796
+ const o = st.formal.objects.find((x) => x.target === 'p-used')
797
+ assert(!!o && o.status === 'attempted' && o.file === 'Formal/p-used.lean', 'a `formal.decision=used` reply records the object as attempted with its file')
798
+ fireEnd(vs[1].childId, { Result: 1, Reason: '同样看起来对' })
799
+ await sleep(250)
800
+ assert(!existsSync(join(replyProj, 'Verified', '命题', 'p-used.md')), '★ attempted is NOT passed: the require gate still withholds the verdict')
801
+ assert(/p-used/.test(readIf(join(replyProj, 'Formal', 'TODO.md'))), 'and the object is on the formalization TODO')
802
+ }
803
+ }
804
+ // (c) a blocker with no note is refused (an explicit decision is required, never a silent skip)
805
+ await restart(RG)
806
+ await callTool('vibe_math_add_proposition', { id: 'p-nonote', 概述: '没有理由的阻塞', 概率: 0.6, 分类: '数论' }, RG)
807
+ {
808
+ const re = verifyRe('p-nonote')
809
+ assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-nonote'), 'p-nonote was put to a vote')
810
+ const vs = unfiredVerifiers(RG, re).slice(0, 2)
811
+ if (vs.length === 2) {
812
+ for (const v of vs) firedChildren.add(v.childId)
813
+ fireEnd(vs[0].childId, { Result: 0.5, Reason: '不想做', formal: { target: 'p-nonote', decision: 'blocked' } })
814
+ await sleep(180)
815
+ assert(/未写明 note/.test(readIf(join(replyProj, 'Logs', '形式化.md'))), 'a blocked judgement without a note is refused with an explicit announcement')
816
+ const st = await callTool('vibe_math_status', {}, RG)
817
+ assert(st.formal.objects.every((o) => o.target !== 'p-nonote'), 'and no blocker record is created for the refused judgement')
818
+ // a formal reply without a target must not invent an object (idSafe('') would fall back to 'id')
819
+ fireEnd(vs[1].childId, { Result: 0.5, Reason: '同上', formal: { decision: 'blocked', note: '没有写 target' } })
820
+ await sleep(180)
821
+ const st2 = await callTool('vibe_math_status', {}, RG)
822
+ assert(st2.formal.objects.every((o) => o.target !== 'id' && o.target !== ''), 'a `formal` reply with no target cannot invent an object record')
823
+ }
824
+ }
825
+ await callTool('vibe_math_abort', {}, RG)
826
+
827
+ // ===============================================================
828
+ // 8b. the §4.1 `defect` channel (contract §4.1 / §6 / §10 items 8-9)
829
+ //
830
+ // A fidelity defect is NOT "the proposition is false". These are BEHAVIOURAL assertions: a real
831
+ // agent reply carrying `formal:{decision:'defect', note}` is fed through the real reply path
832
+ // (subagent/end → handleVerifier → absorbFormalReply) and the record, the archived file and the
833
+ // formalization TODO are inspected on disk.
834
+ // ===============================================================
835
+ section('8b a formal.decision=defect reply withdraws the passed proof and withholds the verdict')
836
+ const RH = makeRoot()
837
+ await callTool('vibe_math_new_project', { name: 'lean-defect' }, RH)
838
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RH)
839
+ const defectProj = projRoot('lean-defect')
840
+ await callTool('vibe_math_add_proposition', { id: 'p-defect', 概述: '形式化写窄了的命题', 概率: 0.6, 分类: '数论' }, RH)
841
+ {
842
+ const pass = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-defect', content: 'theorem p_defect : 2 + 2 = 4 := by decide\n' }, RH)
843
+ assert(pass.ok === true && pass.passed === true, 'defect: the object starts out Lean-passed')
844
+ assert(existsSync(join(defectProj, 'Verified', 'Lean', 'p-defect.lean')), 'defect: the archived proof is on disk before the fidelity review')
845
+ }
846
+ await callTool('vibe_math_start', {}, RH)
847
+ {
848
+ const re = verifyRe('p-defect')
849
+ assert(await drive(RH, () => unfiredVerifiers(RH, re).length >= 2, 'verifiers for r-p-defect'), 'defect: the Lean-passed object is put to a fidelity review')
850
+ const vs = unfiredVerifiers(RH, re).slice(0, 2)
851
+ if (vs.length === 2) {
852
+ for (const v of vs) firedChildren.add(v.childId)
853
+ assert(/该对象已有\*\*通过的 Lean 形式化证明\*\*/.test(vs[0].prompt) && /不要投 0/.test(vs[0].prompt) && /formal:\{decision:'defect'/.test(vs[0].prompt),
854
+ 'defect: the fidelity prompt asks for the defect reply and forbids recording the deviation as 0')
855
+ assert(/本次裁定\*\*不定论\*\*/.test(vs[0].prompt),
856
+ "★ `require` DOES keep the hold clause (the clause is mode-dependent, not deleted)")
857
+ // The defect reply carries an EXTREME Result on purpose: the gate (not the vote value) has to
858
+ // be what withholds the verdict — a defect must never be harvested as "the proposition is false".
859
+ fireEnd(vs[0].childId, { Result: 1, Reason: '逐条核对后认定形式化不忠实', formal: { target: 'p-defect', decision: 'defect', note: 'Lean 代码多加了 h>0 假设,命题原文未要求' } })
860
+ await sleep(240)
861
+ const st = await callTool('vibe_math_status', {}, RH)
862
+ const rec = st.formal.objects.find((o) => o.target === 'p-defect')
863
+ assert(!!rec && rec.status === 'attempted', '★ defect downgrades the formal record to attempted (observed ' + (rec && rec.status) + ')')
864
+ assert(st.formal.passed.indexOf('p-defect') === -1, '★ and the object is no longer reported as Lean-passed')
865
+ assert(!!rec && rec.proof === '', '★ defect clears the `proof` field')
866
+ assert(!existsSync(join(defectProj, 'Verified', 'Lean', 'p-defect.lean')), '★ defect deletes the archived proof Verified/Lean/p-defect.lean')
867
+ assert(existsSync(join(defectProj, 'Formal', 'p-defect.lean')), 'the WORK file Formal/p-defect.lean survives (the code itself is not lost)')
868
+ const persisted = JSON.parse(readIf(join(defectProj, 'State', 'formal.json')))
869
+ assert(persisted.records['p-defect'].decision === 'defect' && /多加了 h>0 假设/.test(persisted.records['p-defect'].note),
870
+ '★ the note (the concrete deviation) is recorded in the persisted formal record')
871
+ assert(/- 形式化: 已尝试未通过/.test(readIf(join(defectProj, 'Propos', '数论', 'p-defect.md'))), 'and the object card anchor is refreshed')
872
+ fireEnd(vs[1].childId, { Result: 1, Reason: '同意:形式化不忠实' })
873
+ await sleep(300)
874
+ }
875
+ }
876
+ {
877
+ const todo = readIf(join(defectProj, 'Formal', 'TODO.md'))
878
+ assert(/p-defect/.test(todo) && /多加了 h>0 假设/.test(todo), '★ the deviation is written into Formal/TODO.md')
879
+ const idx = readIf(join(defectProj, 'Formal', 'Index.md'))
880
+ assert(/p-defect/.test(idx) && /attempted/.test(idx) && !/Verified\/Lean\/p-defect\.lean/.test(idx), 'Formal/Index.md now shows attempted with no archived proof')
881
+ assert(!existsSync(join(defectProj, 'Verified', '命题', 'p-defect.md')), '★ require after a defect: NO Verified card is written (the verdict is withheld, not turned into "false")')
882
+ const card = readIf(join(defectProj, 'Propos', '数论', 'p-defect.md'))
883
+ assert(/- 状态: 未定论/.test(card), '★ and the object stays 未定论')
884
+ assert(/- 概率: 0.6/.test(card), 'the object keeps its existing probability: a defect must NOT be harvested as a refutation')
885
+ const ann = readIf(join(defectProj, 'Logs', '形式化.md'))
886
+ assert(/忠实性缺陷/.test(ann) && /多加了 h>0 假设/.test(ann), '★ the defect is announced with its concrete deviation')
887
+ assert(ann.indexOf('不是"命题为假"') !== -1, 'the announcement spells out that a fidelity defect is NOT "the proposition is false"')
888
+ const st = await callTool('vibe_math_status', {}, RH)
889
+ assert(st.formal.todo.some((t) => t.id === 'p-defect'), '★ the object is on the formalization TODO (undecided until the formalization is fixed and re-run)')
890
+ }
891
+ await callTool('vibe_math_abort', {}, RH)
892
+
893
+ section('8b-2 a defect without a note is refused (the deviation must be auditable)')
894
+ const RI = makeRoot()
895
+ await callTool('vibe_math_new_project', { name: 'lean-defect-nonote' }, RI)
896
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RI)
897
+ const nonoteProj = projRoot('lean-defect-nonote')
898
+ await callTool('vibe_math_add_proposition', { id: 'p-nonote-defect', 概述: '没有偏差说明的缺陷回执', 概率: 0.6, 分类: '数论' }, RI)
899
+ await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-nonote-defect', content: 'theorem p_nn_defect : 2 + 2 = 4 := by decide\n' }, RI)
900
+ await callTool('vibe_math_start', {}, RI)
901
+ {
902
+ const re = verifyRe('p-nonote-defect')
903
+ assert(await drive(RI, () => unfiredVerifiers(RI, re).length >= 2, 'verifiers for r-p-nonote-defect'), 'defect: the passed object is put to a fidelity review')
904
+ const vs = unfiredVerifiers(RI, re).slice(0, 2)
905
+ if (vs.length === 2) {
906
+ for (const v of vs) firedChildren.add(v.childId)
907
+ fireEnd(vs[0].childId, { Result: 1, Reason: '觉得不忠实但没写清楚', formal: { target: 'p-nonote-defect', decision: 'defect' } })
908
+ await sleep(240)
909
+ const st = await callTool('vibe_math_status', {}, RI)
910
+ const rec = st.formal.objects.find((o) => o.target === 'p-nonote-defect')
911
+ assert(!!rec && rec.status === 'passed', '★ a defect WITHOUT a note is refused: the object stays Lean-passed (no silent downgrade)')
912
+ assert(existsSync(join(nonoteProj, 'Verified', 'Lean', 'p-nonote-defect.lean')), '★ and the archived proof is NOT deleted')
913
+ assert(st.formal.todo.every((t) => t.id !== 'p-nonote-defect') && !/p-nonote-defect/.test(readIf(join(nonoteProj, 'Formal', 'TODO.md'))),
914
+ 'and no bogus formalization-TODO entry is created')
915
+ assert(/未写明 note/.test(readIf(join(nonoteProj, 'Logs', '形式化.md'))), '★ the refusal is announced explicitly')
916
+ fireEnd(vs[1].childId, { Result: 1, Reason: '核对后认为一致' })
917
+ await sleep(300)
918
+ }
919
+ }
920
+ assert(await drive(RI, () => existsSync(join(nonoteProj, 'Verified', '命题', 'p-nonote-defect.md')), 'Verified card'), 'a refused defect leaves the gate open: the same vote still promotes the object')
921
+ // §4.1: the downgrade is unconditional — a `blocked` record loses to a defect too (it needs REDOING,
922
+ // not a free pass through the gate, which `blocked` would otherwise grant).
923
+ await callTool('vibe_math_add_proposition', { id: 'p-blocked-defect', 概述: '阻塞后仍被认定不忠实', 概率: 0.6, 分类: '数论' }, RI)
924
+ await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-blocked-defect', note: '先按难度记为阻塞' }, RI)
925
+ await restart(RI)
926
+ {
927
+ const re = verifyRe('p-blocked-defect')
928
+ assert(await drive(RI, () => unfiredVerifiers(RI, re).length >= 2, 'verifiers for r-p-blocked-defect'), 'a blocked object is put to a vote (the gate is open for blocked)')
929
+ const vs = unfiredVerifiers(RI, re).slice(0, 2)
930
+ if (vs.length === 2) {
931
+ for (const v of vs) firedChildren.add(v.childId)
932
+ fireEnd(vs[0].childId, { Result: 1, Reason: '形式化与命题不对应', formal: { target: 'p-blocked-defect', decision: 'defect', note: '阻塞所依据的形式化本身写错了对象' } })
933
+ await sleep(240)
934
+ const st = await callTool('vibe_math_status', {}, RI)
935
+ const rec = st.formal.objects.find((o) => o.target === 'p-blocked-defect')
936
+ assert(!!rec && rec.status === 'attempted', '★★ a defect ALWAYS downgrades, even from `blocked` (observed ' + (rec && rec.status) + ')')
937
+ assert(st.formal.blocked.indexOf('p-blocked-defect') === -1 && /阻塞所依据的形式化本身写错了对象/.test(rec.note || ''), 'and the blocked record is replaced by the concrete deviation')
938
+ fireEnd(vs[1].childId, { Result: 1, Reason: '同意,形式化写错了对象' })
939
+ await sleep(280)
940
+ }
941
+ }
942
+ assert(!existsSync(join(nonoteProj, 'Verified', '命题', 'p-blocked-defect.md')), 'require after a blocked→defect downgrade: still no Verified card (undecided, not "false")')
943
+ await callTool('vibe_math_abort', {}, RI)
944
+
945
+ // ===============================================================
946
+ // 8b-3. the withdrawal is not a best-effort delete (contract §4.1)
947
+ //
948
+ // `Verified/Lean/<id>.lean` is exactly where everyone looks for "the proof of this object", so a
949
+ // downgraded record with the old code still sitting there is worse than no record at all. The fs
950
+ // service exposes no unlink and `subprocess` is optional, so on a host that cannot delete, the
951
+ // withdrawal must fall back to overwriting the file with an explicit notice. This runs in
952
+ // `encourage` mode on purpose: the same scenario also proves the injected text and the
953
+ // framework's own announcement do NOT promise a hold that only `require` can enforce (§4.1 item 3).
954
+ // ===============================================================
955
+ section('8b-3 a defect withdraws the archived proof even on a host that cannot delete files')
956
+ const RL = makeRoot()
957
+ await callTool('vibe_math_new_project', { name: 'lean-defect-nodelete' }, RL)
958
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'encourage' }), RL)
959
+ const nodeleteProj = projRoot('lean-defect-nodelete')
960
+ await callTool('vibe_math_add_proposition', { id: 'p-nodelete', 概述: '宿主无法删除文件时的撤回', 概率: 0.6, 分类: '数论' }, RL)
961
+ const proofFile = join(nodeleteProj, 'Verified', 'Lean', 'p-nodelete.lean')
962
+ {
963
+ const pass = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-nodelete', content: 'theorem p_nodelete : 2 + 2 = 4 := by decide\n' }, RL)
964
+ assert(pass.ok === true && pass.passed === true && /theorem p_nodelete/.test(readIf(proofFile)),
965
+ 'no-delete: the object starts out Lean-passed with its archived proof on disk')
966
+ }
967
+ await callTool('vibe_math_start', {}, RL)
968
+ {
969
+ const re = verifyRe('p-nodelete')
970
+ assert(await drive(RL, () => unfiredVerifiers(RL, re).length >= 2, 'verifiers for r-p-nodelete'), 'no-delete: the Lean-passed object is put to a fidelity review')
971
+ const vs = unfiredVerifiers(RL, re).slice(0, 2)
972
+ if (vs.length === 2) {
973
+ for (const v of vs) firedChildren.add(v.childId)
974
+ assert(/发现任何偏差,不要投 0/.test(vs[0].prompt) && /本档没有门禁/.test(vs[0].prompt) && !/不定论/.test(vs[0].prompt),
975
+ '★ encourage: the fidelity text does NOT claim the framework will withhold the verdict (only require gates; §4.1 item 3)')
976
+ // A host whose shell cannot delete anything: no subprocess service at all. The withdrawal must
977
+ // therefore be observable as an OVERWRITE, not as a missing file.
978
+ subprocessAvailable = false
979
+ fireEnd(vs[0].childId, { Result: 0.5, Reason: '逐条核对后认定形式化不忠实', formal: { target: 'p-nodelete', decision: 'defect', note: 'Lean 里把自然数写成了整数' } })
980
+ await sleep(320)
981
+ subprocessAvailable = true
982
+ const after = readIf(proofFile)
983
+ assert(existsSync(proofFile) && !/theorem p_nodelete/.test(after),
984
+ '★ without a working delete the archived proof text is gone (overwritten, not left readable as a proof)')
985
+ assert(/已撤回(/.test(after) && /Formal\/p-nodelete\.lean/.test(after),
986
+ '★ and it carries the withdrawal notice pointing at the kept working file Formal/p-nodelete.lean')
987
+ const st = await callTool('vibe_math_status', {}, RL)
988
+ const rec = st.formal.objects.find((o) => o.target === 'p-nodelete')
989
+ assert(!!rec && rec.status === 'attempted' && rec.proof === '' && /自然数写成了整数/.test(rec.note || ''),
990
+ '★ the record is still downgraded to attempted with an emptied proof pointer')
991
+ const ann = readIf(join(nodeleteProj, 'Logs', '形式化.md'))
992
+ assert(/忠实性缺陷/.test(ann) && /就地覆盖/.test(ann),
993
+ '★ the announcement says the proof was OVERWRITTEN (not deleted), so the reader knows which withdrawal happened')
994
+ assert(ann.indexOf('不定论') === -1, '★ and `encourage` never claims the framework withheld the verdict')
995
+ const todo = readIf(join(nodeleteProj, 'Formal', 'TODO.md'))
996
+ assert(/# 形式化待办/.test(todo) && /p-nodelete/.test(todo) && !/定论被搁置/.test(todo) && /没有定论门禁/.test(todo),
997
+ '★ Formal/TODO.md states what this mode really does (it does not claim 定论被搁置)')
998
+ const idx = readIf(join(nodeleteProj, 'Formal', 'Index.md'))
999
+ assert(/## 形式化待办/.test(idx) && !/定论被搁置/.test(idx), '★ and Formal/Index.md mirrors that framing')
1000
+ fireEnd(vs[1].childId, { Result: 0.5, Reason: '同意,形式化不忠实' })
1001
+ await sleep(280)
1002
+ }
1003
+ }
1004
+ await callTool('vibe_math_abort', {}, RL)
1005
+
1006
+ // ===============================================================
1007
+ // 8b-4. a defect on an ALREADY-verified object must not leave a stale card anchor
1008
+ //
1009
+ // `defect` withdraws the formalization (record → attempted, proof pointer cleared, archived file
1010
+ // deleted/overwritten). A Verified card written earlier still says 「形式化: Lean 通过(Verified/
1011
+ // Lean/<id>.lean)」 — a pointer to a proof that no longer exists. The gate must not prevent that
1012
+ // refresh: the gate decides whether a NEW conclusion may be declared, not whether the framework may
1013
+ // tell the truth about one it already declared.
1014
+ // ===============================================================
1015
+ section('8b-4 a later defect refreshes an existing Verified card instead of leaving a stale anchor')
1016
+ const RM = makeRoot()
1017
+ await callTool('vibe_math_new_project', { name: 'lean-stale-card' }, RM)
1018
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RM)
1019
+ const staleProj = projRoot('lean-stale-card')
1020
+ await callTool('vibe_math_add_proposition', { id: 'p-stale', 概述: '定论后才被认定形式化不忠实', 概率: 0.6, 分类: '数论' }, RM)
1021
+ await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-stale', content: 'theorem p_stale : 2 + 2 = 4 := by decide\n' }, RM)
1022
+ await callTool('vibe_math_start', {}, RM)
1023
+ assert(await runVerifyRound(RM, 'p-stale', [1, 1]) !== null, 'stale-card: the Lean-passed proposition was put to a vote')
1024
+ assert(await drive(RM, () => existsSync(join(staleProj, 'Verified', '命题', 'p-stale.md')), 'p-stale Verified card'), 'stale-card: the gate was satisfied, so it reaches a Verified card')
1025
+ {
1026
+ const card = readIf(join(staleProj, 'Verified', '命题', 'p-stale.md'))
1027
+ assert(/- 形式化: Lean 通过/.test(card) && /Verified\/Lean\/p-stale\.lean/.test(card), 'stale-card: the card records the machine-checked strength and its proof path')
1028
+ }
1029
+ // A LATER work-round reply (e.g. a solver that reuses the object and finds the Lean statement too
1030
+ // wide) reports the fidelity defect — long after the card was written.
1031
+ await callTool('vibe_math_add_problem', { id: 'q-w', description: '让 explorer 起来以便回执一条 defect', priority: 0 }, RM)
1032
+ await restart(RM)
1033
+ assert(await drive(RM, () => !!lastSpawn(RM, 'explorer:q-w'), 'explorer:q-w'), 'stale-card: an explorer exists to carry the work-round reply')
1034
+ fireEnd(lastSpawn(RM, 'explorer:q-w').childId, {
1035
+ meta: { kind: 'directions', qid: 'q-w', formal: { target: 'p-stale', decision: 'defect', note: '这份形式化把结论写宽了' },
1036
+ directions: [{ id: 'd1', title: '直接法', method: '', core_assumption: '', feasibility: 0.6 }] },
1037
+ })
1038
+ assert(await drive(RM, () => !/Lean 通过/.test(readIf(join(staleProj, 'Verified', '命题', 'p-stale.md'))), 'p-stale card refreshed'),
1039
+ '★ a defect on an already-verified object refreshes the existing Verified card (no stale 「Lean 通过」 anchor pointing at a withdrawn proof)')
1040
+ {
1041
+ const card = readIf(join(staleProj, 'Verified', '命题', 'p-stale.md'))
1042
+ assert(/- 形式化: 已尝试未通过/.test(card), '★ the refreshed card states the honest formal status (已尝试未通过)')
1043
+ assert(!/Verified\/Lean\/p-stale\.lean/.test(card), '★ and no longer points at the withdrawn proof')
1044
+ assert(/- 结论: 真/.test(card), 'the conclusion itself is untouched — a fidelity defect is not a refutation')
1045
+ assert(!existsSync(join(staleProj, 'Verified', 'Lean', 'p-stale.lean')), 'and the archived proof really is gone')
1046
+ assert(await drive(RM, () => /p-stale/.test(readIf(join(staleProj, 'Formal', 'TODO.md'))), 'p-stale formalization TODO'), 'the object is on the formalization TODO for redoing')
1047
+ }
1048
+ await callTool('vibe_math_abort', {}, RM)
1049
+
1050
+ // ===============================================================
1051
+ // 8c. the injected text obeys the five hard requirements of contract §6
1052
+ // ===============================================================
1053
+ section('8c the injected text uses full tool names, Result (not verdict) and the run-before-archive rule')
1054
+ const RJ = makeRoot()
1055
+ await callTool('vibe_math_new_project', { name: 'lean-workline' }, RJ)
1056
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RJ)
1057
+ await callTool('vibe_math_add_problem', { id: 'q-defect', description: '顺手形式化的对象', priority: 0 }, RJ)
1058
+ const workProj = projRoot('lean-workline')
1059
+ // a `meta.formal` defect on the WORK-round path (absorbFormalFromReply) must downgrade too
1060
+ await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'q-defect', content: 'theorem q_defect : 2 + 2 = 4 := by decide\n' }, RJ)
1061
+ await callTool('vibe_math_start', {}, RJ)
1062
+ assert(await drive(RJ, () => !!lastSpawn(RJ, 'explorer:q-defect'), 'explorer:q-defect'), 'the explorer for q-defect was spawned')
1063
+ {
1064
+ const p = lastSpawn(RJ, 'explorer:q-defect').prompt
1065
+ assert(/归档前先跑通(vibe_math_lean_run 或 run=true);跑不通的定义不要进可复用库。/.test(p),
1066
+ '★ the work-round prompt requires a GREEN run before archiving a reusable definition (§6 hard requirement 3)')
1067
+ assert(/"decision":"used\|blocked\|defect"/.test(p), 'the work-round reply contract advertises the defect decision too')
1068
+ assert(!/verdict/.test(p) && !/(^|[^a-z_])lean_(run|archive|lib)/.test(p),
1069
+ '★ the work-round prompt uses FULL tool names only and never the v4/v5 field name `verdict`')
1070
+ fireEnd(lastSpawn(RJ, 'explorer:q-defect').childId, {
1071
+ meta: { kind: 'directions', qid: 'q-defect', formal: { target: 'q-defect', decision: 'defect', note: '陈述里的自然数范围被写成了整数' },
1072
+ directions: [{ id: 'd1', title: '直接形式化', method: 'Lean', core_assumption: '', feasibility: 0.6 }] },
1073
+ })
1074
+ await sleep(260)
1075
+ const st = await callTool('vibe_math_status', {}, RJ)
1076
+ const rec = st.formal.objects.find((o) => o.target === 'q-defect')
1077
+ assert(!!rec && rec.status === 'attempted' && /自然数范围被写成了整数/.test(rec.note || ''),
1078
+ '★ a `meta.formal` defect from a WORK reply downgrades the record too (absorbFormalFromReply, not just the verifier path)')
1079
+ assert(!existsSync(join(workProj, 'Verified', 'Lean', 'q-defect.lean')), '★ and its archived proof is deleted')
1080
+ }
1081
+ await callTool('vibe_math_abort', {}, RJ)
1082
+
1083
+ section('8c-2 the fidelity branch reaches BOTH the review and the debate prompt, and names Result')
1084
+ const RK = makeRoot()
1085
+ await callTool('vibe_math_new_project', { name: 'lean-fidelity' }, RK)
1086
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'encourage', debateMaxRounds: 2 }), RK)
1087
+ await callTool('vibe_math_add_proposition', { id: 'p-fid', 概述: '忠实性审查措辞观察对象', 概率: 0.6, 分类: '数论' }, RK)
1088
+ await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-fid', content: 'theorem p_fid : 2 + 2 = 4 := by decide\n' }, RK)
1089
+ await callTool('vibe_math_start', {}, RK)
1090
+ const fidBatch = await runVerifyRound(RK, 'p-fid', [0.9, 0.95])
1091
+ assert(fidBatch !== null, 'fidelity: the review round was asked')
1092
+ if (fidBatch) {
1093
+ const vp = fidBatch.map((s) => s.prompt).join('\n')
1094
+ assert(/一致 → Result = 1/.test(vp), "★ the review prompt states the faithful case as `Result = 1` (v3's REAL reply field, not v4/v5's verdict)")
1095
+ assert(/发现任何偏差,不要投 0/.test(vp) && /形式化不合格/.test(vp), '★ and forbids expressing a fidelity defect as 0')
1096
+ assert(/formal:\{decision:'defect', note:'<具体偏差>'\}/.test(vp), 'and points at the defect reply field to record it')
1097
+ assert(/独立于这份 Lean 代码/.test(vp), 'only an INDEPENDENT refutation may be voted 0')
1098
+ assert(/Result/.test(vp) && !/verdict/.test(vp), '★ the voting prompt names Result, never verdict (§6 hard requirement 2)')
1099
+ assert(vp.indexOf('偏离 → 0') === -1, '★ no "偏离 → 0" instruction anywhere in the fidelity branch (contract §10 item 9)')
1100
+ }
1101
+ assert(await drive(RK, () => wakes.some((w) => w.rootId === RK.id && /交流群/.test(w.prompt)), 'debate prompt'), 'a non-consensus fidelity round moved to the debate')
1102
+ {
1103
+ const dp = wakes.filter((w) => w.rootId === RK.id).map((w) => w.prompt).join('\n')
1104
+ assert(/一致 → Result = 1/.test(dp) && /不要投 0/.test(dp), '★ the DEBATE prompt carries the same fidelity wording')
1105
+ assert(/Result/.test(dp) && !/verdict/.test(dp), 'the debate prompt names Result, never verdict')
1106
+ assert(dp.indexOf('偏离 → 0') === -1, 'the debate prompt also refuses "a deviation is a 0"')
1107
+ }
1108
+ await callTool('vibe_math_abort', {}, RK)
1109
+
1110
+ // ===============================================================
1111
+ // 9. reporting + persistence
1112
+ // ===============================================================
1113
+ // (d) a plain `used` judgement must NOT withdraw an ESTABLISHED proof (contract §4). Only a
1114
+ // fidelity defect retracts a proof; `used` just reports "this round touched the formalization".
1115
+ // v2 shipped the unconditional downgrade here and silently re-closed the require gate.
1116
+ section('8d a \`used\` reply must NOT downgrade an already-passed object')
1117
+ await restart(RG)
1118
+ await callTool('vibe_math_add_proposition', { id: 'p-usedkeep', 概述: '已有通过证明后再写一次 used 回执', 概率: 0.6, 分类: '数论' }, RG)
1119
+ {
1120
+ const pass = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-usedkeep', content: 'theorem p_usedkeep : 2 + 2 = 4 := by decide\n' }, RG)
1121
+ assert(pass.ok === true && pass.passed === true, 'used-keep: the object starts out Lean-passed')
1122
+ const re = verifyRe('p-usedkeep')
1123
+ assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-usedkeep'), 'used-keep: the Lean-passed object is put to a fidelity review')
1124
+ const vs = unfiredVerifiers(RG, re).slice(0, 2)
1125
+ if (vs.length === 2) {
1126
+ for (const v of vs) firedChildren.add(v.childId)
1127
+ fireEnd(vs[0].childId, { Result: 0.5, Reason: '这一轮只是又写了一遍草稿', formal: { target: 'p-usedkeep', decision: 'used', file: 'Formal/p-usedkeep.lean' } })
1128
+ await sleep(150)
1129
+ const st = await callTool('vibe_math_status', {}, RG)
1130
+ const o = st.formal.objects.find((x) => x.target === 'p-usedkeep')
1131
+ assert(!!o && o.status === 'passed', '★ a `used` reply does NOT downgrade an already-passed object (got ' + JSON.stringify(o) + ')')
1132
+ assert(st.formal.passed.indexOf('p-usedkeep') !== -1, '★ and status still reports it as Lean-passed (the fidelity branch stays the reviewers\' subject)')
1133
+ assert(existsSync(join(replyProj, 'Verified', 'Lean', 'p-usedkeep.lean')), '★ and the archived proof is still on disk by that name')
1134
+ fireEnd(vs[1].childId, { Result: 0.5, Reason: '同样只是又写了一遍草稿' })
1135
+ await sleep(250)
1136
+ assert(!/p-usedkeep/.test(readIf(join(replyProj, 'Formal', 'TODO.md')) || ''), '★ no formal-required TODO was created: the surviving passed still opens the require gate')
1137
+ // The same rule covers the RUN path (contract §4): a run attributed to the object may not downgrade it.
1138
+ const rerun = await callTool('vibe_math_lean_run', { file: 'Formal/p-usedkeep.lean', target: 'p-usedkeep' }, RG)
1139
+ assert(rerun.ok === true, 'used-keep: the object work file runs green (the record assertion below is the point)')
1140
+ const o2 = (await callTool('vibe_math_status', {}, RG)).formal.objects.find((x) => x.target === 'p-usedkeep')
1141
+ assert(!!o2 && o2.status === 'passed', '★ and the record is still passed')
1142
+ }
1143
+ }
1144
+
1145
+ // (e) the same rule for `blocked`: a blocker is a gate-opening record, so a later `used` reply
1146
+ // must not push the object back to `attempted` and silently re-close the gate (v3 used to preserve
1147
+ // only `passed` here — v2/v4/v5 preserve both).
1148
+ await restart(RG)
1149
+ await callTool('vibe_math_add_proposition', { id: 'p-usedblocked', 概述: '已记录阻塞后再写一次 used 回执', 概率: 0.6, 分类: '数论' }, RG)
1150
+ {
1151
+ const blk = await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-usedblocked', note: '需要大量未形式化的实分析前置知识' }, RG)
1152
+ assert(blk.ok === true && blk.status === 'blocked', 'used-blocked: the object starts with an explicit blocker (the gate is open)')
1153
+ const re = verifyRe('p-usedblocked')
1154
+ assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-usedblocked'), 'used-blocked: the object is put to a vote')
1155
+ const vs = unfiredVerifiers(RG, re).slice(0, 2)
1156
+ if (vs.length === 2) {
1157
+ for (const v of vs) firedChildren.add(v.childId)
1158
+ fireEnd(vs[0].childId, { Result: 0.5, Reason: '这一轮只是又写了一遍草稿', formal: { target: 'p-usedblocked', decision: 'used', file: 'Formal/p-usedblocked.lean' } })
1159
+ await sleep(150)
1160
+ const o = (await callTool('vibe_math_status', {}, RG)).formal.objects.find((x) => x.target === 'p-usedblocked')
1161
+ assert(!!o && o.status === 'blocked', '★ a `used` reply does not re-close a gate an explicit blocker opened (got ' + JSON.stringify(o) + ')')
1162
+ fireEnd(vs[1].childId, { Result: 0.5, Reason: '同上' })
1163
+ await sleep(200)
1164
+ }
1165
+ }
1166
+
1167
+ section('9 the office can audit formal strength')
1168
+ {
1169
+ const rep = await callTool('vibe_math_report', {}, RF)
1170
+ assert(rep.formal && rep.formal.mode === 'require', 'the JSON report carries the formal mode')
1171
+ assert(rep.formal.passed.indexOf('p-gate') !== -1 && rep.formal.blocked.indexOf('p-blocked-ok') !== -1, 'the JSON report lists both passed and blocked objects')
1172
+ assert(rep.params.formalVerify === 'require' && rep.params.leanCommand === 'lean', 'the readable parameter table carries the Lean parameters')
1173
+ const md = readIf(join(gateProj, 'Logs', '报告.md'))
1174
+ assert(/## Lean 形式化/.test(md), 'the human-readable report has a Lean formal-verification section')
1175
+ assert(/已通过:.*p-gate/.test(md), 'it lists Lean-passed objects')
1176
+ assert(/已记录阻塞:.*p-blocked-ok/.test(md), 'it lists blocked objects')
1177
+ assert(/可复用库:VibeMath\/Formal\/\{Lib,Proved\}\//.test(md), 'it documents the path layout')
1178
+ await callTool('vibe_math_report', {}, RA)
1179
+ assert(/未启用(`formalVerify` = off/.test(readIf(join(offProj, 'Logs', '报告.md'))), 'in off mode the report says the feature is not enabled')
1180
+ const offRep = await callTool('vibe_math_report', {}, RA)
1181
+ assert(offRep.formal.mode === 'off' && /off/.test(offRep.formal.note || ''), 'and the JSON report says the same')
1182
+ }
1183
+ {
1184
+ const before = JSON.parse(readIf(join(gateProj, 'State', 'formal.json')))
1185
+ assert(!!before && !!before.records && before.records['p-gate'] && before.records['p-gate'].status === 'passed', 'the formal record is persisted in State/formal.json, keyed by object id')
1186
+ assert(Array.isArray(before.todo), 'the formalization TODO is persisted alongside it')
1187
+ assert(before.records['p-blocked-ok'].status === 'blocked' && /分析学/.test(before.records['p-blocked-ok'].note), 'a blocker record keeps its reason across sessions')
1188
+ assert(existsSync(join(VIBE, 'Formal', 'Proved', 'Index.md')) && existsSync(join(libPath, 'Index.md')), 'both global indexes are framework-maintained')
1189
+ }
1190
+
1191
+ // ===============================================================
1192
+ // 10. interaction corpus (AUDIT-CHECKLIST §2.4) — a HUMAN must be able to re-read
1193
+ // every prompt the framework emitted, not just the assertions about them.
1194
+ // ===============================================================
1195
+ section('10 the captured prompt corpus is written for human review')
1196
+ {
1197
+ mkdirSync(CORPUS_DIR, { recursive: true })
1198
+ writeFileSync(join(CORPUS_DIR, 'formal-verify-v3.json'), JSON.stringify({ entries: corpus }, null, 2), 'utf8')
1199
+ const md = ['# V3 形式化验证交互语料(prompt corpus)', '',
1200
+ '> 由 `formal-verify-v3.test.mjs` 落盘:框架**真正发出**的每一条提示词原文。路径归一化:工作区 → `<WS>`,',
1201
+ '> VibeMath 根 → `<VIBEMATH>`(两者都按正/反斜杠两种写法替换,因此语料是确定性的、可 diff 的、不泄露本机路径)。',
1202
+ '> 覆盖:explorer / solver / method-keeper 的日常工作提示词(含「顺手形式化」与"归档前先跑通"),',
1203
+ '> `off`(零 Lean 文本)、`encourage`、**`require`** 三档下的表决初评与辩论提示词,`passed` 之后的忠实性审查分支',
1204
+ '> (含 `defect` 出口),以及规划提示词。', '']
1205
+ for (let i = 0; i < corpus.length; i++) {
1206
+ const c = corpus[i]
1207
+ md.push('## [' + i + '] ' + c.kind + ' · ' + c.label)
1208
+ md.push('')
1209
+ md.push('```text')
1210
+ md.push(c.prompt)
1211
+ md.push('```')
1212
+ md.push('')
1213
+ }
1214
+ writeFileSync(join(CORPUS_DIR, 'formal-verify-v3.md'), md.join('\n'), 'utf8')
1215
+ assert(existsSync(join(CORPUS_DIR, 'formal-verify-v3.json')) && existsSync(join(CORPUS_DIR, 'formal-verify-v3.md')), 'the prompt corpus was written (JSON + Markdown)')
1216
+ assert(corpus.length >= 25, 'the corpus covers the whole run (' + corpus.length + ' prompts)')
1217
+ assert(corpus.some((c) => c.label.startsWith('explorer:')) && corpus.some((c) => c.label.startsWith('solver:')) && corpus.some((c) => c.label.startsWith('method-keeper')) && corpus.some((c) => c.label.startsWith('verifier:')), 'the corpus covers every interaction type this suite drives')
1218
+ assert(corpus.some((c) => c.kind === 'wake'), 'the corpus also keeps the continuation prompts (debate rounds)')
1219
+ // generic sweep over EVERY captured prompt, not spot checks (AUDIT §2.1)
1220
+ const dirty = corpus.filter((c) => /\[object Object\]|\bNaN\b|:\s*undefined|["']undefined["']|undefined\s*[,}\]]/.test(c.prompt))
1221
+ assert(dirty.length === 0, 'no captured prompt contains placeholder garbage (' + dirty.map((d) => d.label).join(',') + ')')
1222
+ const joined = corpus.map((c) => c.prompt).join('\n')
1223
+ assert(joined.indexOf(WS) === -1 && joined.indexOf(WS.replace(/\\/g, '/')) === -1, 'every captured prompt normalises the workspace path to <WS> (the corpus stays diffable)')
1224
+ assert(joined.indexOf(VIBE) === -1 && joined.indexOf(VIBE.replace(/\\/g, '/')) === -1 && joined.indexOf('<VIBEMATH>') !== -1,
1225
+ '★ every captured prompt normalises the VibeMath root to <VIBEMATH> (no machine path leaks into the shipped corpus, contract §10 item 10)')
1226
+ assert(!corpus.some((c) => c.root === RA.id && /Lean|形式化/.test(c.prompt)),
1227
+ '★ the off-mode prompts captured in the corpus contain ZERO Lean text (off stays a true no-op)')
1228
+ // contract §10 item 10: the corpus must cover require AND the work round (not just encourage + fidelity)
1229
+ assert(corpus.some((c) => /【Lean 形式化验证(鼓励模式)】/.test(c.prompt)), '★ the corpus covers the encourage-mode verification prompt')
1230
+ assert(corpus.some((c) => /【Lean 形式化验证(强制模式)】/.test(c.prompt)), '★ the corpus covers the REQUIRE-mode verification prompt')
1231
+ assert(corpus.some((c) => /【顺手形式化(鼓励)】/.test(c.prompt)) && corpus.some((c) => /【顺手形式化(强制)】/.test(c.prompt)), '★ the corpus covers the work-round 顺手形式化 prompt in both modes')
1232
+ assert(corpus.some((c) => /一致 → Result = 1/.test(c.prompt)), '★ the corpus keeps the passed/fidelity branch verbatim for human review')
1233
+ // contract §6 hard requirements 1-2 + §10 item 9, swept over EVERY captured prompt
1234
+ const verifier = corpus.filter((c) => c.label.startsWith('verifier:'))
1235
+ assert(verifier.length >= 5 && verifier.every((c) => /Result/.test(c.prompt) && !/verdict/.test(c.prompt)),
1236
+ '★ every captured voting prompt names Result and never verdict (§6 hard requirement 2)')
1237
+ const bareTools = corpus.filter((c) => /(^|[^a-z_])lean_(run|archive|lib)/.test(c.prompt))
1238
+ assert(bareTools.length === 0, '★ no captured prompt abbreviates a Lean tool name (§6 hard requirement 1): ' + bareTools.map((b) => b.label).join(','))
1239
+ const zeroDeviation = corpus.filter((c) => c.prompt.indexOf('偏离 → 0') !== -1)
1240
+ assert(zeroDeviation.length === 0, '★ no captured prompt turns a fidelity defect into a 0 vote (§6 hard requirement 5 / §10 item 9): ' + zeroDeviation.map((b) => b.label).join(','))
1241
+ // Contract §10 item 10 + AUDIT-CHECKLIST §2.4: the shipped corpus must be BYTE-deterministic, so
1242
+ // the volatile run metadata the planner brief carries (random plan id, epoch timestamps, child
1243
+ // ids, free-slot count) must be normalised out — otherwise every run diffs and the corpus loses
1244
+ // its only purpose (human review of what agents actually read).
1245
+ const volatile = corpus.filter((c) => /plan-[0-9a-f]{8}/.test(c.label) || /plan-[0-9a-f]{8}|"at": \d{10,}|"childId": "c\d+"|"free_slots": \d+/.test(c.prompt))
1246
+ assert(volatile.length === 0, '★ no captured prompt/label keeps volatile run metadata (random plan id / epoch timestamps / child ids / slot count) — the corpus is byte-deterministic: ' + volatile.map((b) => b.label).join(','))
1247
+ assert(corpus.some((c) => /"free_slots": <SLOTS>/.test(c.prompt)) && corpus.some((c) => /plan-<ID>/.test(c.label)),
1248
+ '★ and the normalisation actually fired (a planner brief and its plan id were captured)')
1249
+ }
1250
+
1251
+ console.log('')
1252
+ console.log('passed=' + passed + ' failed=' + failed)
1253
+ if (failed) { console.error('FAILURES:'); for (const f of failures) console.error(' - ' + f) }
1254
+ rmSync(WS, { recursive: true, force: true })
1255
+ if (failed) process.exit(1)
1256
+ console.log('ALL GREEN')
1257
+ process.exit(0)