dsh-vibe-math 2.2.2 → 2.3.1

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 (43) hide show
  1. package/AUDIT-CHECKLIST.md +61 -3
  2. package/README.md +119 -1
  3. package/RELEASE-NOTES-2.3.0.md +207 -0
  4. package/RELEASE-NOTES-2.3.1.md +134 -0
  5. package/audit-formal-sensitivity.mjs +333 -0
  6. package/audit-persona-sensitivity.mjs +249 -0
  7. package/audit-persona-surface.test.mjs +349 -0
  8. package/audit-v5-integrity.mjs +43 -2
  9. package/audit-v5-sensitivity.mjs +77 -6
  10. package/docs/formal-verification.md +401 -0
  11. package/docs/generate_framework_diagram_v5.mjs +22 -16
  12. package/docs/test-timing.md +79 -0
  13. package/formal-verify-v2.test.mjs +951 -0
  14. package/formal-verify-v3.test.mjs +1031 -0
  15. package/formal-verify-v4.test.mjs +882 -0
  16. package/formal-verify-v5.test.mjs +598 -0
  17. package/package.json +22 -2
  18. package/prompt-corpus-persona/persona-corpus.json +32 -0
  19. package/prompt-corpus-persona/persona-corpus.md +674 -0
  20. package/prompt-corpus-v2/formal-verify-v2.json +394 -0
  21. package/prompt-corpus-v2/formal-verify-v2.md +4250 -0
  22. package/prompt-corpus-v3/formal-verify-v3.json +382 -0
  23. package/prompt-corpus-v3/formal-verify-v3.md +3843 -0
  24. package/prompt-corpus-v4/formal-verify-v4.json +84 -0
  25. package/prompt-corpus-v4/formal-verify-v4.md +255 -0
  26. package/prompt-corpus-v5/prompt-corpus-v5.json +109 -5
  27. package/prompt-corpus-v5/prompt-corpus-v5.md +653 -109
  28. package/prompt-v5-integrity.test.mjs +1158 -984
  29. package/run-tests.mjs +99 -0
  30. package/vibe-math-v2/agent.cordis.yml +40 -2
  31. package/vibe-math-v2/vibe-math-v2.js +811 -21
  32. package/vibe-math-v2//345/256/236/347/216/260/346/226/271/346/241/210.md +218 -1
  33. package/vibe-math-v3/agent.cordis.yml +46 -2
  34. package/vibe-math-v3/vibe-math-v3.js +810 -21
  35. package/vibe-math-v3//345/256/236/347/216/260/346/226/271/346/241/210.md +104 -2
  36. package/vibe-math-v4/agent.cordis.yml +46 -4
  37. package/vibe-math-v4/vibe-math-v4.js +744 -15
  38. package/vibe-math-v4//345/256/236/347/216/260/346/226/271/346/241/210.md +255 -0
  39. package/vibe-math-v5/agent.cordis.yml +41 -5
  40. package/vibe-math-v5/vibe-math-v5.js +621 -9
  41. package/vibe-math-v5//345/256/236/347/216/260/346/226/271/346/241/210.md +131 -4
  42. package/vibe-math-v5//346/236/266/346/236/204/345/233/276.md +57 -0
  43. package//347/244/272/344/276/213/345/233/276//346/241/206/346/236/266/345/233/276-v5.svg +51 -46
@@ -0,0 +1,1031 @@
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
+ const scrub = (s) => String(s == null ? '' : s)
70
+ .split(VIBE).join('<VIBEMATH>')
71
+ .split(VIBE.replace(/\\/g, '/')).join('<VIBEMATH>')
72
+ .split(WS).join('<WS>')
73
+ .split(WS.replace(/\\/g, '/')).join('<WS>')
74
+
75
+ // A fake Lean: a file PASSES unless it still contains `sorry` or the marker `-- FAIL`.
76
+ // `-- HANG` simulates a toolchain that never returns (the timeout path).
77
+ const subprocess = {
78
+ async resolveExecutable(cmd) {
79
+ if (!toolchainAvailable) throw new Error('spawn ' + cmd + ' ENOENT')
80
+ if (String(cmd) !== 'lean' && String(cmd) !== 'lake') throw new Error('unknown executable ' + cmd)
81
+ return String(cmd)
82
+ },
83
+ spawn(spec) {
84
+ const argv = spec.argv || []
85
+ const last = String(argv[argv.length - 1] || '')
86
+ const isShell = /powershell|cmd\.exe|\/bin\/sh|(^|\/)sh$/i.test(String(argv[0] || '')) || /New-Item|Remove-Item|Move-Item|^mkdir -p/.test(last)
87
+ if (isShell) {
88
+ // directory shim (v3's runShell: powershell New-Item / POSIX mkdir -p)
89
+ if (/New-Item/.test(last)) {
90
+ const m = last.match(/-Path\s+(?:'((?:[^']|'')*)'|"((?:[^"]|"")*)")/)
91
+ const raw = (m && (m[1] || m[2])) || ''
92
+ for (const p of raw.split(',').map((x) => x.replace(/''/g, "'"))) if (p) mkdirSync(p, { recursive: true })
93
+ }
94
+ if (/^mkdir -p/.test(last)) {
95
+ const re = /'((?:[^']|'\\'')*)'/g
96
+ let m
97
+ while ((m = re.exec(last)) !== null) mkdirSync(m[1].replace(/'\\''/g, "'"), { recursive: true })
98
+ }
99
+ if (/Remove-Item/.test(last)) {
100
+ const m = last.match(/-LiteralPath\s+'((?:[^']|'')*)'/)
101
+ if (m) rmSync(m[1].replace(/''/g, "'"), { force: true, recursive: true })
102
+ }
103
+ return { done: Promise.resolve({ exitCode: 0 }), collected: {} }
104
+ }
105
+ const file = last
106
+ const text = existsSync(file) ? readFileSync(file, 'utf8') : ''
107
+ leanRuns.push({ argv: argv.slice(0, -1), file, cwd: spec.cwd, graceMs: spec.graceMs })
108
+ if (spawnThrows) throw new Error('spawn ' + String(argv[0]) + ' EPERM')
109
+ if (/-- REJECT/.test(text)) {
110
+ return {
111
+ done: Promise.reject(new Error('child process died before reporting')),
112
+ collected: { stdout: { readFrom: () => ({ text: '', nextOffset: 0, lossy: false }) }, stderr: { readFrom: () => ({ text: '', nextOffset: 0, lossy: false }) } },
113
+ terminate() {},
114
+ }
115
+ }
116
+ if (/-- HANG/.test(text)) {
117
+ return {
118
+ done: new Promise(() => {}),
119
+ collected: { stdout: { readFrom: () => ({ text: '', nextOffset: 0, lossy: false }) }, stderr: { readFrom: () => ({ text: '', nextOffset: 0, lossy: false }) } },
120
+ terminate() { terminated.push(file) },
121
+ }
122
+ }
123
+ const bad = /sorry|-- FAIL/.test(text)
124
+ const stdout = bad ? '' : 'ok\n'
125
+ const stderr = bad ? 'error: declaration uses sorry\n' : ''
126
+ return {
127
+ done: Promise.resolve({ exitCode: bad ? 1 : 0, signal: null }),
128
+ collected: {
129
+ stdout: { readFrom: () => ({ text: stdout, nextOffset: stdout.length, lossy: false }) },
130
+ stderr: { readFrom: () => ({ text: stderr, nextOffset: stderr.length, lossy: false }) },
131
+ },
132
+ terminate() {},
133
+ }
134
+ },
135
+ }
136
+
137
+ const ctx = {
138
+ get(name) {
139
+ if (name === 'subprocess') return subprocessAvailable ? subprocess : undefined
140
+ if (name === 'sandboxPolicy') return { resolve() { return { workspaceRoot: WS } } }
141
+ return undefined
142
+ },
143
+ on(e, fn) { (listeners[e] = listeners[e] || []).push(fn) },
144
+ effect(fn) { const d = fn(); return () => { if (typeof d === 'function') d() } },
145
+ logger: { info() {}, warn() {}, error() {} },
146
+ tools: { register(spec) { toolRegs.push(spec); return () => {} } },
147
+ commands: { register(spec) { cmdRegs.push(spec); return () => {} } },
148
+ subagents: {
149
+ list() { return ['spawn'] },
150
+ async startContinuable({ label, request }) {
151
+ const childId = 'c' + (spawns.length + 1)
152
+ const rootId = (request && request.parent && request.parent.id) || ''
153
+ const prompt = (request && request.prompt && request.prompt[0] && request.prompt[0].text) || ''
154
+ spawns.push({ label, childId, rootId, prompt })
155
+ corpus.push({ kind: 'spawn', label, root: rootId, prompt: scrub(prompt) })
156
+ return { childId, messageId: 'm' + spawns.length }
157
+ },
158
+ async sendMessage(parent, childId, blocks) {
159
+ const rootId = (parent && parent.id) || ''
160
+ const prompt = (blocks && blocks[0] && blocks[0].text) || ''
161
+ wakes.push({ childId, rootId, prompt })
162
+ const sp = spawns.find((s) => s.childId === childId)
163
+ corpus.push({ kind: 'wake', label: sp ? sp.label : childId, root: rootId, prompt: scrub(prompt) })
164
+ return 'w' + wakes.length
165
+ },
166
+ async followup(parent, childId, blocks) { return await this.sendMessage(parent, childId, blocks) },
167
+ interrupt(childId) { interrupts.push(childId) },
168
+ },
169
+ agents: { roots() { return roots.slice() }, get() { return undefined } },
170
+ // DSH 0.1.1 fs API: resolve → { targetKey, displayPath }
171
+ fs: {
172
+ async resolve(rel, opts) {
173
+ const base = (opts && opts.cwd) || WS
174
+ const p = (typeof rel === 'string' && isAbsolute(rel)) ? rel.replace(/\//g, '\\') : join(base, ...String(rel).split('/'))
175
+ return { targetKey: p, displayPath: p }
176
+ },
177
+ async stat(t) { return existsSync(t.targetKey) ? { version: 'v1', type: 'file', size: 1 } : undefined },
178
+ async readText(t) { return readFileSync(t.targetKey, 'utf8') },
179
+ async writeText(t, content) { mkdirSync(dirname(t.targetKey), { recursive: true }); writeFileSync(t.targetKey, content, 'utf8') },
180
+ async listDir(t) { if (!existsSync(t.targetKey)) return []; return readdirSync(t.targetKey, { withFileTypes: true }).map((e) => ({ name: e.name, type: e.isDirectory() ? 'directory' : 'file' })) },
181
+ },
182
+ }
183
+
184
+ const mod = await import(PLUGIN.href + '?t=' + Date.now())
185
+ ;(mod.default || mod).apply(ctx)
186
+
187
+ // ---------------------------------------------------------------
188
+ // driving helpers
189
+ // ---------------------------------------------------------------
190
+ function makeRoot() {
191
+ const id = 'sess-' + String.fromCharCode(65 + rootSeq++)
192
+ const root = { id, options: { provider: 'mock', model: 'mock-model' }, session: { id, header: { cwd: WS, parentSession: undefined } }, followup() {}, ctx: undefined }
193
+ roots.push(root)
194
+ return root
195
+ }
196
+ async function callTool(name, args, agent) {
197
+ const spec = toolRegs.find((s) => s.name === name)
198
+ if (!spec) throw new Error('no tool ' + name)
199
+ return JSON.parse(await spec.execute(args || {}, { agent }))
200
+ }
201
+ function fireEnd(childId, reply) {
202
+ const blocks = reply === undefined ? [] : [{ type: 'text', text: '```json\n' + JSON.stringify(reply) + '\n```' }]
203
+ for (const h of (listeners['subagent/end'] || [])) h({ id: childId, runId: 'r', provider: 'spawn', local: true, stopReason: 'completed', lastAssistantMessage: blocks })
204
+ }
205
+ const firedChildren = new Set()
206
+ // Spawns created before a restart belong to a task the restart discarded; they are never a valid
207
+ // target for a later round (their onChildEnd has no agentRegistry entry any more). The floor keeps
208
+ // `unfiredVerifiers` from selecting them.
209
+ const spawnFloor = {}
210
+ const markFloor = (root) => { spawnFloor[root.id] = spawns.length }
211
+ const spawnOf = (root, prefix) => spawns.filter((s) => s.rootId === root.id && s.label.startsWith(prefix))
212
+ const lastSpawn = (root, prefix) => spawnOf(root, prefix).slice(-1)[0]
213
+ 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))
214
+ 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')
215
+
216
+ /** Parameters every verification scenario uses. A high concurrency cap keeps the fallback
217
+ * scheduler from starving a later object behind a pile of unfired mock verifiers. */
218
+ const VPARAMS = { plannerEnabled: false, verifierCount: 2, debateMaxRounds: 1, maxParallelThreshold: 64, tickIntervalMs: 200 }
219
+
220
+ /** Fire the one in-flight forced planner with an empty plan (an empty plan schedules a tick). */
221
+ async function pump(root) {
222
+ const pending = spawns.filter((s) => s.rootId === root.id && s.label.startsWith('planner:') && !firedChildren.has(s.childId)).slice(-1)[0]
223
+ if (pending) { firedChildren.add(pending.childId); fireEnd(pending.childId, { summary: 'noop', plan: [] }); return }
224
+ try { await callTool('vibe_math_plan', { force: true }, root) } catch (e) { /* not running / gated */ }
225
+ }
226
+ /** Poll `pred`, nudging the scheduler along with an empty forced plan (the 1s tick timer is the fallback). */
227
+ async function drive(root, pred, label, timeoutMs) {
228
+ const deadline = Date.now() + (timeoutMs || 15000)
229
+ while (Date.now() < deadline) {
230
+ if (pred()) return true
231
+ await pump(root)
232
+ await sleep(80)
233
+ }
234
+ if (pred()) return true
235
+ console.error(' .. drive timed out: ' + label)
236
+ return false
237
+ }
238
+ /** Fire the next `results.length` verifiers of one object (any of its candidate rIds). */
239
+ async function runVerifyRound(root, target, results, timeoutMs) {
240
+ const re = verifyRe(target)
241
+ const ok = await drive(root, () => unfiredVerifiers(root, re).length >= results.length, 'verifiers for r-' + target, timeoutMs)
242
+ if (!ok) return null
243
+ const un = unfiredVerifiers(root, re).slice(0, results.length)
244
+ for (let i = 0; i < un.length; i++) { firedChildren.add(un[i].childId); fireEnd(un[i].childId, { Result: results[i], Reason: 'mock 裁决 ' + results[i] }) }
245
+ await sleep(220)
246
+ return un
247
+ }
248
+ /** Abort + restart: gives the next verification a FRESH task, so a prompt is guaranteed to be
249
+ * constructed after whatever changed in between (mode switch, archived proof, …). */
250
+ async function restart(root) {
251
+ await callTool('vibe_math_abort', {}, root)
252
+ await callTool('vibe_math_start', {}, root)
253
+ markFloor(root)
254
+ }
255
+
256
+ console.log('-- V3 Lean formal verification --')
257
+ console.log('plugin under test: ' + PLUGIN.href)
258
+
259
+ // ===============================================================
260
+ // 1. 'off' is a true no-op
261
+ // ===============================================================
262
+ section("1 'off' (default) is a true no-op")
263
+ const RA = makeRoot()
264
+ await callTool('vibe_math_new_project', { name: 'lean-off' }, RA)
265
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS), RA)
266
+ await callTool('vibe_math_add_proposition', { id: 'p-off', 概述: '关模式下的普通命题', 概率: 0.6, 分类: '数论' }, RA)
267
+ await callTool('vibe_math_start', {}, RA)
268
+ const offRound = await runVerifyRound(RA, 'p-off', [1, 1])
269
+ assert(offRound !== null && offRound.length === 2, 'off: two independent verifiers were asked (投票流程照常)')
270
+ const offProj = projRoot('lean-off')
271
+ 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")
272
+ {
273
+ const st = await callTool('vibe_math_status', {}, RA)
274
+ assert(st.params.formalVerify === 'off', "the default is 'off' (got " + st.params.formalVerify + ')')
275
+ const all = promptText(RA)
276
+ assert(!/Lean/.test(all), 'no prompt mentions Lean in off mode')
277
+ assert(!/形式化/.test(all), 'no prompt mentions 形式化 in off mode')
278
+ assert(!/\[形式化\]/.test(all), 'the [形式化] announcement line is absent in off mode')
279
+ }
280
+ assert(!/形式化/.test(readIf(join(offProj, 'Verified', '命题', 'p-off.md'))), 'the Verified card carries no formal line in off mode')
281
+ assert(!existsSync(join(offProj, 'Formal', 'Index.md')), 'no Formal/Index.md is produced in off mode (no formal record)')
282
+ assert(!existsSync(join(offProj, 'State', 'formal.json')), 'no State/formal.json is produced in off mode')
283
+ {
284
+ const st = await callTool('vibe_math_status', {}, RA)
285
+ assert(st.formal.mode === 'off' && st.formal.objects.length === 0, 'status reports mode=off with zero formal objects')
286
+ }
287
+ // the tools still EXIST in off mode (static registration), they are just never advertised
288
+ 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'),
289
+ 'the three Lean tools are registered in every mode (registration is static)')
290
+
291
+ // ===============================================================
292
+ // 2. parameter validation + runtime switching
293
+ // ===============================================================
294
+ section('2 parameter validation and runtime switching')
295
+ const RB = makeRoot()
296
+ await callTool('vibe_math_new_project', { name: 'lean-params' }, RB)
297
+ const bad = await callTool('vibe_math_set_params', { formalVerify: 'banana' }, RB)
298
+ assert(bad.params.formalVerify === 'off', "an unknown mode degrades to 'off', never to a stronger mode (got " + bad.params.formalVerify + ')')
299
+ const bad2 = await callTool('vibe_math_set_params', { formalVerify: 'REQUIRE' }, RB)
300
+ assert(bad2.params.formalVerify === 'off', 'the mode is matched exactly (a case typo cannot force formalization)')
301
+ const enc = await callTool('vibe_math_set_params', { formalVerify: 'encourage' }, RB)
302
+ assert(enc.params.formalVerify === 'encourage', "'encourage' is accepted")
303
+ const req = await callTool('vibe_math_set_params', { formalVerify: 'require', leanTimeoutMs: -5, leanCommand: ' ' }, RB)
304
+ assert(req.params.formalVerify === 'require', "'require' is accepted")
305
+ assert(req.params.leanTimeoutMs === 120000, 'a non-positive leanTimeoutMs falls back to the default (' + req.params.leanTimeoutMs + ')')
306
+ assert((await callTool('vibe_math_set_params', { leanTimeoutMs: 0 }, RB)).params.leanTimeoutMs === 120000, 'leanTimeoutMs=0 also falls back to the default')
307
+ assert(req.params.leanCommand === 'lean', 'a blank leanCommand falls back to "lean"')
308
+ const t5 = await callTool('vibe_math_set_params', { leanTimeoutMs: 5000 }, RB)
309
+ assert(t5.params.leanTimeoutMs === 5000, 'a positive leanTimeoutMs is accepted (got ' + t5.params.leanTimeoutMs + ')')
310
+ const arrBad = await callTool('vibe_math_set_params', { leanArgs: 'not-an-array' }, RB)
311
+ assert(Array.isArray(arrBad.params.leanArgs) && arrBad.params.leanArgs.length === 0, 'a non-array leanArgs falls back to []')
312
+ await callTool('vibe_math_set_params', { leanCommand: 'lake', leanArgs: ['env', 'lean'] }, RB)
313
+ const stL = await callTool('vibe_math_status', {}, RB)
314
+ assert(stL.params.leanCommand === 'lake' && stL.params.leanArgs.join(' ') === 'env lean', 'leanCommand/leanArgs are settable (lake env lean)')
315
+ {
316
+ const setup = await callTool('vibe_math_setup', {}, RB)
317
+ const names = setup.parameters.map((p) => p.name)
318
+ assert(names.indexOf('formalVerify') !== -1 && names.indexOf('leanCommand') !== -1 && names.indexOf('leanArgs') !== -1 && names.indexOf('leanTimeoutMs') !== -1,
319
+ 'the settings schema surfaces all four Lean parameters')
320
+ const f = setup.parameters.find((p) => p.name === 'formalVerify')
321
+ assert(f.default === 'off' && f.current === 'require', 'the schema carries the default (off) and the current value (require)')
322
+ const tmpl = await callTool('vibe_math_template', { where: 'project' }, RB)
323
+ const tj = readIf(join(projRoot('lean-params'), 'vibe_math_setting.json'))
324
+ assert(tmpl.ok === true && /"formalVerify": "off"/.test(tj) && /"leanArgs": \[\]/.test(tj), 'the generated settings template documents the Lean parameters with their defaults')
325
+ assert(/formalVerify — /.test(tj), 'the template carries the human-readable parameter description as a comment')
326
+ }
327
+
328
+ // ===============================================================
329
+ // 3. 'encourage' injection into the WORK prompts
330
+ // ===============================================================
331
+ section("3 'encourage' injects 顺手形式化 into solver / explorer / method-keeper prompts")
332
+ const RC = makeRoot()
333
+ await callTool('vibe_math_new_project', { name: 'lean-work' }, RC)
334
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'encourage', methodKeepEvery: 1 }), RC)
335
+ await callTool('vibe_math_add_problem', { id: 'qE', description: '证明 log 2 是无理数', priority: 0 }, RC)
336
+ await callTool('vibe_math_start', {}, RC)
337
+ assert(await drive(RC, () => !!lastSpawn(RC, 'explorer:qE'), 'explorer:qE'), 'fallback scheduler spawned explorer:qE')
338
+ {
339
+ const p = lastSpawn(RC, 'explorer:qE').prompt
340
+ assert(/【顺手形式化(鼓励)】/.test(p), 'the explorer work prompt carries the 顺手形式化 line')
341
+ assert(/vibe_math_lean_archive kind='def'/.test(p), 'the work prompt points at the archive tool for reusable definitions')
342
+ assert(/vibe_math_lean_lib 查重/.test(p), 'the work prompt tells agents to check the reuse library first')
343
+ assert(/形式化回执/.test(p) && /"decision":"used\|blocked\|defect"/.test(p), '★ the work-round reply contract also advertises the formal field, defect included (契约 §6.3)')
344
+ }
345
+ 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 }] } })
346
+ // Answer EVERY explorer the fallback scheduler dispatches (it re-derives when a direction looks
347
+ // unattended) until the solver for d1 appears — otherwise the retry cap can stall the project.
348
+ for (let guard = 0; guard < 40 && !lastSpawn(RC, 'solver:qE:d1'); guard++) {
349
+ const ex = spawns.filter((s) => s.rootId === RC.id && s.label.startsWith('explorer:qE') && !firedChildren.has(s.childId)).slice(-1)[0]
350
+ if (ex) {
351
+ firedChildren.add(ex.childId)
352
+ fireEnd(ex.childId, { meta: { kind: 'directions', qid: 'qE', directions: [{ id: 'd1', title: '连分数法', method: 'e 的连分数', core_assumption: '', feasibility: 0.7 }] } })
353
+ }
354
+ await pump(RC)
355
+ await sleep(80)
356
+ }
357
+ assert(!!lastSpawn(RC, 'solver:qE:d1'), 'solver spawned for direction d1')
358
+ assert(/【顺手形式化(鼓励)】/.test(lastSpawn(RC, 'solver:qE:d1').prompt), 'the solver work prompt carries the 顺手形式化 line')
359
+ {
360
+ // the explorer's `meta.formal` judgement is recorded even though it never called a Lean tool
361
+ const st = await callTool('vibe_math_status', {}, RC)
362
+ assert(st.formal.blocked.indexOf('qE') !== -1, '★ an explorer `meta.formal` judgement is recorded (no Lean tool call needed)')
363
+ assert(/- 形式化: 阻塞(/.test(readIf(join(projRoot('lean-work'), 'Problems', 'qE.md'))), 'and it lands on the problem card anchor')
364
+ }
365
+ 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 }] })
366
+ await sleep(250)
367
+ {
368
+ const st = await callTool('vibe_math_status', {}, RC)
369
+ 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')
370
+ }
371
+ assert(await drive(RC, () => !!lastSpawn(RC, 'method-keeper'), 'method-keeper'), 'method keeper spawned for the pending invention')
372
+ {
373
+ const p = lastSpawn(RC, 'method-keeper').prompt
374
+ assert(/【顺手形式化(鼓励)】/.test(p), 'the method-keeper prompt carries the 顺手形式化 line')
375
+ assert(/【方法沉淀 × Lean 形式化】/.test(p), '★ the method keeper is told to ALSO sediment reusable Lean definitions/lemmas')
376
+ assert(/kind='lemma'/.test(p) && /Proved/.test(p), 'and where the proved lemmas go')
377
+ }
378
+ await callTool('vibe_math_abort', {}, RC)
379
+ assert((await callTool('vibe_math_status', {}, RC)).running === false, 'work-prompt scenario aborted (keeps later scenarios deterministic)')
380
+
381
+ // ===============================================================
382
+ // 4. 'encourage' injection into BOTH verification prompts + the fidelity switch
383
+ // ===============================================================
384
+ section("4 'encourage' reaches the review prompt and the debate prompt")
385
+ const RD = makeRoot()
386
+ await callTool('vibe_math_new_project', { name: 'lean-verify' }, RD)
387
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'encourage', debateMaxRounds: 2 }), RD)
388
+ await callTool('vibe_math_add_proposition', { id: 'p-enc', 概述: '鼓励模式下的忠实性审查', 概率: 0.6, 分类: '数论' }, RD)
389
+ await callTool('vibe_math_start', {}, RD)
390
+ const encBatch = await runVerifyRound(RD, 'p-enc', [0.9, 0.95])
391
+ assert(encBatch !== null, 'encourage: the first review round was asked')
392
+ if (encBatch) {
393
+ const vp = encBatch.map((s) => s.prompt).join('\n')
394
+ assert(/【Lean 形式化验证(鼓励模式)】/.test(vp), 'the review prompt explains the Lean mode')
395
+ assert(/一旦 Lean 通过,你唯一需要确认的就是忠实性/.test(vp), 'the review prompt states that a passing Lean run shrinks the question to fidelity')
396
+ assert(/实现难度/.test(vp), 'the review prompt asks for the implementation-difficulty judgement')
397
+ assert(/可以不做,但请在回执的 formal 字段写明难度判断/.test(vp), "'encourage' explicitly allows skipping (with a recorded judgement)")
398
+ assert(/"formal":/.test(vp) && /"decision":"used\|blocked\|defect"/.test(vp), 'the reply contract documents the formal field (defect included)')
399
+ 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')
400
+ assert(/Formal\/(相对项目根)/.test(vp) && /VibeMath\/Formal\/Lib/.test(vp), 'the prompt states the path layout')
401
+ }
402
+ // a non-consensus round moves to the public debate, whose prompt must carry the same injection
403
+ assert(await drive(RD, () => wakes.some((w) => w.rootId === RD.id && /交流群/.test(w.prompt)), 'debate prompt'), 'a non-consensus round moved to the debate')
404
+ {
405
+ const dp = wakes.filter((w) => w.rootId === RD.id).map((w) => w.prompt).join('\n')
406
+ assert(/【Lean 形式化验证(鼓励模式)】/.test(dp), 'the debate prompt names the mode')
407
+ assert(/一旦 Lean 通过,你唯一需要确认的就是忠实性|你不需要重新检查推导/.test(dp), 'the debate prompt carries the Lean block too')
408
+ assert(/"formal":/.test(dp), 'the debate reply contract carries the formal field')
409
+ }
410
+ // finish the debate: a unanimous round concludes
411
+ if (encBatch) for (const b of encBatch) fireEnd(b.childId, { Result: 1, Reason: 'mock 第二轮一致' })
412
+ assert(await drive(RD, () => existsSync(join(projRoot('lean-verify'), 'Verified', '命题', 'p-enc.md')), 'p-enc verified'), 'the debate finished and the object was verified')
413
+
414
+ // ===============================================================
415
+ // 5. lean_run executes through the subprocess service and reports honestly
416
+ // ===============================================================
417
+ section('5 lean_run executes through the subprocess service and reports honestly')
418
+ const RE = makeRoot()
419
+ await callTool('vibe_math_new_project', { name: 'lean-tools' }, RE)
420
+ await callTool('vibe_math_set_params', { formalVerify: 'encourage' }, RE)
421
+ await callTool('vibe_math_add_proposition', { id: 'p-tool', 概述: '工具实验命题', 概率: 0.6, 分类: '数论' }, RE)
422
+ const toolProj = projRoot('lean-tools')
423
+ mkdirSync(join(toolProj, 'Formal'), { recursive: true })
424
+ writeFileSync(join(toolProj, 'Formal', 'good.lean'), 'theorem t : 1 = 1 := rfl\n', 'utf8')
425
+ writeFileSync(join(toolProj, 'Formal', 'bad.lean'), 'theorem t : 1 = 2 := by sorry\n', 'utf8')
426
+ writeFileSync(join(toolProj, 'Formal', 'hang.lean'), '-- HANG\ntheorem t : 1 = 1 := rfl\n', 'utf8')
427
+ {
428
+ const runGood = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean', target: 'p-tool' }, RE)
429
+ assert(runGood.ok === true && runGood.exitCode === 0, 'a file with no sorry runs green (' + JSON.stringify({ ok: runGood.ok, exitCode: runGood.exitCode }) + ')')
430
+ assert(/ok/.test(runGood.stdout), 'the compiler stdout is returned')
431
+ const last = leanRuns[leanRuns.length - 1]
432
+ assert(last.cwd.replace(/\\/g, '/') === toolProj.replace(/\\/g, '/'), 'the toolchain runs with the PROJECT root as cwd')
433
+ assert(last.argv.join(' ') === 'lean', 'by default the argv is just the executable (got ' + last.argv.join(' ') + ')')
434
+ assert(last.graceMs === 120000, 'the default leanTimeoutMs is passed down as graceMs (' + last.graceMs + ')')
435
+ }
436
+ {
437
+ const st = await callTool('vibe_math_status', {}, RE)
438
+ const o = st.formal.objects.find((x) => x.target === 'p-tool')
439
+ assert(!!o && o.status === 'attempted', 'lean_run with target records the object as attempted (not passed)')
440
+ assert(!!o.run && o.run.ok === true, 'the run result is recorded on the object')
441
+ const card = readIf(join(toolProj, 'Propos', '数论', 'p-tool.md'))
442
+ assert(/- 形式化: 已尝试未通过/.test(card), '★ the object card anchor block gains `- 形式化: <状态>` alongside 状态/概率')
443
+ 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)')
444
+ }
445
+ {
446
+ const runBad = await callTool('vibe_math_lean_run', { file: 'Formal/bad.lean' }, RE)
447
+ assert(runBad.ok === false && runBad.exitCode === 1, 'a file that still uses sorry reports a red run')
448
+ assert(/sorry/.test(runBad.stderr), 'the compiler output is returned verbatim (' + JSON.stringify(runBad.stderr).slice(0, 60) + ')')
449
+ }
450
+ {
451
+ const runMissing = await callTool('vibe_math_lean_run', { file: 'Formal/nope.lean' }, RE)
452
+ assert(runMissing.ok === false && runMissing.code === 'V3_NOT_FOUND', 'a missing file is refused with a typed code')
453
+ }
454
+ {
455
+ // The guard's boundary is the VibeMath ROOT, not the project: the global reuse library
456
+ // deliberately lives at <VibeMath>/Formal/{Lib,Proved}, so climbing out of the project but
457
+ // staying inside VibeMath must remain legal (it just fails as a missing file).
458
+ const inside = await callTool('vibe_math_lean_run', { file: '../../Formal/Lib/x.lean' }, RE)
459
+ assert(inside.code === 'V3_NOT_FOUND', 'climbing out of the project but staying inside VibeMath is allowed (the global library lives there)')
460
+ const esc1 = await callTool('vibe_math_lean_run', { file: '../../../evil.lean' }, RE)
461
+ assert(esc1.ok === false && esc1.code === 'V3_INVALID_ARGUMENT', '★ a traversal that climbs ABOVE the VibeMath root is refused')
462
+ const esc2 = await callTool('vibe_math_lean_run', { file: 'Formal/../../../../../../evil.lean' }, RE)
463
+ assert(esc2.ok === false && esc2.code === 'V3_INVALID_ARGUMENT', 'a deeper traversal is refused too')
464
+ const esc3 = await callTool('vibe_math_lean_run', { file: '/etc/evil.lean' }, RE)
465
+ assert(esc3.ok === false && esc3.code === 'V3_INVALID_ARGUMENT', 'an unrelated absolute path is refused')
466
+ const notLean = await callTool('vibe_math_lean_run', { file: 'Formal/good.txt' }, RE)
467
+ assert(notLean.ok === false && notLean.code === 'V3_INVALID_ARGUMENT', 'only .lean files can be executed')
468
+ const noFile = await callTool('vibe_math_lean_run', {}, RE)
469
+ assert(noFile.ok === false && noFile.code === 'V3_INVALID_ARGUMENT', 'a missing file argument is refused')
470
+ }
471
+ {
472
+ toolchainAvailable = false
473
+ const runNoTc = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean' }, RE)
474
+ assert(runNoTc.ok === false && runNoTc.code === 'LEAN_NOT_FOUND', 'a missing toolchain returns LEAN_NOT_FOUND instead of crashing')
475
+ assert(/仍可把形式化代码写下来归档/.test(runNoTc.message), 'the failure explains the graceful degradation')
476
+ toolchainAvailable = true
477
+ }
478
+ {
479
+ subprocessAvailable = false
480
+ const runNoSub = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean' }, RE)
481
+ assert(runNoSub.ok === false && runNoSub.code === 'NO_SUBPROCESS', 'a host without the subprocess service returns NO_SUBPROCESS')
482
+ subprocessAvailable = true
483
+ }
484
+ {
485
+ const runHang = await callTool('vibe_math_lean_run', { file: 'Formal/hang.lean', timeout_ms: 1000 }, RE)
486
+ assert(runHang.ok === false && runHang.code === 'LEAN_TIMEOUT' && runHang.timedOut === true, '★ a hanging toolchain returns LEAN_TIMEOUT instead of wedging the scheduler')
487
+ assert(terminated.some((f) => /hang\.lean$/.test(f)), '★ the timeout path calls handle.terminate()')
488
+ }
489
+ {
490
+ spawnThrows = true
491
+ const runSpawn = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean' }, RE)
492
+ assert(runSpawn.ok === false && runSpawn.code === 'LEAN_SPAWN_FAILED', 'a spawn failure is reported as LEAN_SPAWN_FAILED instead of throwing')
493
+ spawnThrows = false
494
+ writeFileSync(join(toolProj, 'Formal', 'reject.lean'), '-- REJECT\ntheorem t : 1 = 1 := rfl\n', 'utf8')
495
+ const runReject = await callTool('vibe_math_lean_run', { file: 'Formal/reject.lean' }, RE)
496
+ 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')
497
+ }
498
+ {
499
+ await callTool('vibe_math_set_params', { leanCommand: 'lake', leanArgs: ['env', 'lean'] }, RE)
500
+ const runLake = await callTool('vibe_math_lean_run', { file: 'Formal/good.lean' }, RE)
501
+ assert(runLake.ok === true, 'lake env lean works through leanCommand/leanArgs')
502
+ assert(leanRuns[leanRuns.length - 1].argv.join(' ') === 'lake env lean', 'the argv is [exe, ...leanArgs, file] (got ' + leanRuns[leanRuns.length - 1].argv.join(' ') + ')')
503
+ await callTool('vibe_math_set_params', { leanCommand: 'lean', leanArgs: [] }, RE)
504
+ }
505
+
506
+ // ===============================================================
507
+ // 6. lean_archive: def / lemma / proof / blocked → the right paths + indexes
508
+ // ===============================================================
509
+ section('6 lean_archive writes the contract paths and rebuilds the indexes')
510
+ const libPath = join(VIBE, 'Formal', 'Lib')
511
+ const provedPath = join(VIBE, 'Formal', 'Proved')
512
+ {
513
+ const defRes = await callTool('vibe_math_lean_archive', { kind: 'def', name: 'ZMod5', content: 'def ZMod5 := Fin 5\n' }, RE)
514
+ assert(defRes.ok === true && defRes.file === 'Formal/Lib/ZMod5.lean', 'a reusable definition is archived to the global lib (' + defRes.file + ')')
515
+ assert(existsSync(join(libPath, 'ZMod5.lean')), '★ the definition exists under VibeMath/Formal/Lib/ (cross-project, NOT inside the project)')
516
+ assert(!existsSync(join(toolProj, 'Formal', 'Lib', 'ZMod5.lean')), 'it is NOT duplicated inside the project tree')
517
+ assert(defRes.run && defRes.run.ok === true, 'the reusable definition is executed on archive (run defaults to true)')
518
+ const libIdx = readIf(join(libPath, 'Index.md'))
519
+ assert(/\| 名称 \| 文件 \| 类别 \| 摘要 \| 最近运行 \|/.test(libIdx), 'Lib/Index.md uses the contract columns')
520
+ assert(/ZMod5/.test(libIdx) && /Lib\/ZMod5\.lean/.test(libIdx) && /\| ok \|/.test(libIdx), 'Lib/Index.md lists the new definition with its run result')
521
+ assert(!/ZMod5/.test(readIf(join(toolProj, 'Formal', 'Index.md'))), 'the global definition does not pollute the project formal index')
522
+ }
523
+ {
524
+ 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)
525
+ assert(lemRes.ok === true && lemRes.file === 'Formal/Proved/sq_odd.lean', 'a lemma is archived to Proved/')
526
+ assert(existsSync(join(provedPath, 'sq_odd.lean')), 'the lemma exists under VibeMath/Formal/Proved/')
527
+ const provedIdx = readIf(join(provedPath, 'Index.md'))
528
+ assert(/\| 名称 \| 文件 \| 陈述 \| 依赖 \| 最近运行 \|/.test(provedIdx), 'Proved/Index.md uses the contract columns')
529
+ assert(/sq_odd/.test(provedIdx) && /Mathlib/.test(provedIdx), 'Proved/Index.md lists the lemma and its imports as 依赖')
530
+ }
531
+ {
532
+ const noRun = await callTool('vibe_math_lean_archive', { kind: 'def', name: 'NoRun', content: 'def NoRun := 1\n', run: false }, RE)
533
+ assert(noRun.ok === true && noRun.run === undefined, 'run=false archives WITHOUT executing (no toolchain needed)')
534
+ }
535
+ {
536
+ const noName = await callTool('vibe_math_lean_archive', { kind: 'def', content: 'def x := 1\n' }, RE)
537
+ assert(noName.ok === false && noName.code === 'V3_INVALID_ARGUMENT', 'archiving a definition without a name is refused')
538
+ const badKind = await callTool('vibe_math_lean_archive', { kind: 'nonsense' }, RE)
539
+ assert(badKind.ok === false && badKind.code === 'V3_INVALID_ARGUMENT', 'an unknown archive kind is refused')
540
+ const noTarget = await callTool('vibe_math_lean_archive', { kind: 'proof', content: 'theorem x : 1 = 1 := rfl\n' }, RE)
541
+ assert(noTarget.ok === false && noTarget.code === 'V3_INVALID_ARGUMENT', 'kind=proof without a target is refused')
542
+ const noBody = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-x' }, RE)
543
+ assert(noBody.ok === false && noBody.code === 'V3_INVALID_ARGUMENT', 'kind=proof without content/from is refused')
544
+ const badFrom = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-x', from: '../../../evil.lean' }, RE)
545
+ assert(badFrom.ok === false && badFrom.code === 'V3_INVALID_ARGUMENT', 'kind=proof with an out-of-tree from is refused')
546
+ }
547
+ {
548
+ // a green proof → passed + Verified/Lean (the archived proof lives next to the conclusion)
549
+ 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)
550
+ assert(arc.ok === true && arc.passed === true, 'the proof is archived and passes (' + JSON.stringify({ ok: arc.ok, passed: arc.passed }) + ')')
551
+ assert(arc.file === 'Formal/p-proof.lean', 'the working file is Formal/<target>.lean')
552
+ assert(arc.proof === 'Verified/Lean/p-proof.lean', 'the archived proof path is Verified/Lean/<target>.lean')
553
+ assert(existsSync(join(toolProj, 'Formal', 'p-proof.lean')), 'the working file exists on disk')
554
+ assert(existsSync(join(toolProj, 'Verified', 'Lean', 'p-proof.lean')), '★ the proof is archived under Verified/Lean/ as the proof of that object')
555
+ const st = await callTool('vibe_math_status', {}, RE)
556
+ assert(st.formal.passed.indexOf('p-proof') !== -1, 'status reports the object as Lean-passed')
557
+ const idx = readIf(join(toolProj, 'Formal', 'Index.md'))
558
+ 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')
559
+ assert(/ok(exit 0,/.test(idx), 'the index shows the run result in the contract format')
560
+ // a RED proof must NOT become passed
561
+ const red = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-red', content: 'theorem p_red : 1 = 2 := by sorry\n' }, RE)
562
+ assert(red.ok === true && red.passed === false && red.status === 'attempted', 'a red proof is archived as attempted, not passed')
563
+ assert(!existsSync(join(toolProj, 'Verified', 'Lean', 'p-red.lean')), '★ no archived proof is written for a red run')
564
+ }
565
+ {
566
+ const blkNoNote = await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-blk' }, RE)
567
+ assert(blkNoNote.ok === false && blkNoNote.code === 'V3_INVALID_ARGUMENT', 'blocked without a note is refused')
568
+ const blk = await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-blk', note: '需要外层解析数论框架,本轮工作量不可接受' }, RE)
569
+ assert(blk.ok === true && blk.status === 'blocked', 'a reasoned blocker is recorded')
570
+ const stBlk = await callTool('vibe_math_status', {}, RE)
571
+ assert(stBlk.formal.blocked.indexOf('p-blk') !== -1, 'status lists the blocked object')
572
+ assert(/需要外层解析数论框架/.test(readIf(join(toolProj, 'Formal', 'Index.md'))), 'the blocker reason is written into the index')
573
+ }
574
+ {
575
+ const libList = await callTool('vibe_math_lean_lib', {}, RE)
576
+ assert(libList.ok === true && libList.counts.lib >= 2 && libList.counts.proved >= 1, 'lean_lib reports the reuse library sizes (' + JSON.stringify(libList.counts) + ')')
577
+ assert(libList.objects.some((o) => o.target === 'p-proof' && o.status === 'passed'), 'lean_lib lists per-object formal status')
578
+ assert(/复用优先/.test(libList.hint || ''), 'lean_lib tells agents to reuse before redefining')
579
+ assert(libList.paths && /VibeMath\/Formal\/Lib/.test(libList.paths.lib), 'lean_lib reports the cross-project path layout')
580
+ const ro = await callTool('vibe_math_lean_lib', { refresh: false }, RE)
581
+ assert(ro.rebuilt === false && ro.counts.lib === null, 'refresh:false only reads (does not rebuild the indexes)')
582
+ }
583
+ {
584
+ const ann = readIf(join(toolProj, 'Logs', '形式化.md'))
585
+ assert(/# 形式化公告/.test(ann) && /ZMod5/.test(ann) && /p-proof/.test(ann), 'the announcement log records what was formalized')
586
+ }
587
+
588
+ // ===============================================================
589
+ // 7. the 'require' gate
590
+ // ===============================================================
591
+ section("7 'require' withholds a verdict until the formal record exists")
592
+ const RF = makeRoot()
593
+ await callTool('vibe_math_new_project', { name: 'lean-gate' }, RF)
594
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RF)
595
+ await callTool('vibe_math_add_proposition', { id: 'p-gate', 概述: '必须形式化的命题', 概率: 0.6, 分类: '数论' }, RF)
596
+ const gateProj = projRoot('lean-gate')
597
+ await callTool('vibe_math_start', {}, RF)
598
+ {
599
+ const batch = await runVerifyRound(RF, 'p-gate', [1, 1])
600
+ assert(batch !== null, 'require: the review round was asked')
601
+ if (batch) {
602
+ const vp = batch.map((s) => s.prompt).join('\n')
603
+ assert(/【Lean 形式化验证(强制模式)】/.test(vp), 'the review prompt says 强制模式')
604
+ assert(/必须产出 Lean 形式化/.test(vp), "'require' states the formalization is mandatory")
605
+ assert(/本次裁定不会生效/.test(vp), 'the prompt warns that the verdict will not take effect without it')
606
+ assert(/formal-required/.test(vp), 'the prompt names the machine-readable reason')
607
+ assert(/归档可复用定义\/引理前先跑通(vibe_math_lean_archive run=true 或先 vibe_math_lean_run);跑不通不要入库。/.test(vp),
608
+ '★ the verification prompt requires a GREEN run before archiving into the reuse library (§6 hard requirement 3)')
609
+ assert(/宿主没有 Lean 工具链(LEAN_NOT_FOUND)时:把代码写下来归档,并在回执的 note 里写明"宿主无 Lean 工具链"/.test(vp),
610
+ '★ and spells out the way out when the host has no Lean toolchain (§6 hard requirement 4)')
611
+ assert(/Result/.test(vp) && !/verdict/.test(vp) && !/(^|[^a-z_])lean_(run|archive|lib)/.test(vp),
612
+ '★ the voting prompt uses FULL tool names and names Result, never verdict (§6 hard requirements 1-2)')
613
+ }
614
+ }
615
+ 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')
616
+ assert(!existsSync(join(gateProj, 'Verified', '命题', 'p-gate.md')), 'no Verified card was written')
617
+ {
618
+ const card = readIf(join(gateProj, 'Propos', '数论', 'p-gate.md'))
619
+ assert(/- 概率: 0.6/.test(card), '★ the object keeps its existing probability (no silent promotion to 1)')
620
+ assert(/- 状态: 未定论/.test(card), 'and its 状态 stays 未定论')
621
+ const todo = readIf(join(gateProj, 'Formal', 'TODO.md'))
622
+ assert(/# 形式化待办/.test(todo) && /p-gate/.test(todo) && /formal-required/.test(todo), '★ the TODO records the object with the machine-readable reason')
623
+ const idx = readIf(join(gateProj, 'Formal', 'Index.md'))
624
+ assert(/## 形式化待办/.test(idx) && /p-gate/.test(idx), 'Formal/Index.md mirrors the formalization TODO')
625
+ const ann = readIf(join(gateProj, 'Logs', '形式化.md'))
626
+ assert(/require 模式/.test(ann) && /不定论/.test(ann), '★ the withholding is announced')
627
+ const st = await callTool('vibe_math_status', {}, RF)
628
+ assert(st.formal.todo.some((t) => t.id === 'p-gate'), 'status lists the deferred object')
629
+ assert(/formal-required/.test(st.recentActivity.map((e) => e.detail).join('\n')), 'the activity feed shows the formal-required deferral')
630
+ const voteLog = readdirSync(join(gateProj, 'Logs', 'Verification')).filter((f) => /^r-p-gate_/.test(f))
631
+ assert(voteLog.length >= 1, 'the votes themselves are still recorded in Logs/Verification (nothing is lost)')
632
+ }
633
+ // runtime switch: the mode is read when the prompt is CONSTRUCTED, so a fresh round reflects it
634
+ await callTool('vibe_math_add_proposition', { id: 'p-mode', 概述: '模式切换观察对象', 概率: 0.6, 分类: '数论' }, RF)
635
+ await restart(RF)
636
+ 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')
637
+ {
638
+ const fresh = unfiredVerifiers(RF, verifyRe('p-mode'))[0]
639
+ assert(!!fresh && /【Lean 形式化验证(强制模式)】/.test(fresh.prompt) && /本次裁定不会生效/.test(fresh.prompt), 'a fresh round reflects the current mode (强制模式)')
640
+ }
641
+ // ★ anti-idle: a deferred object must NOT be re-voted while it sits on the TODO (each round would
642
+ // just be withheld again, burning verifiers on the same rId every tick). The assertion is only
643
+ // meaningful because the previous block proved the scheduler IS allocating verify tasks here.
644
+ 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)')
645
+ await callTool('vibe_math_set_params', { formalVerify: 'encourage' }, RF)
646
+ await restart(RF)
647
+ 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')
648
+ {
649
+ const fresh = unfiredVerifiers(RF, verifyRe('p-mode'))[0]
650
+ assert(!!fresh && /【Lean 形式化验证(鼓励模式)】/.test(fresh.prompt), '★ switching the mode at runtime immediately changes the prompt (now 鼓励模式)')
651
+ assert(!!fresh && !/本次裁定不会生效/.test(fresh.prompt), 'and the mandatory wording is gone in encourage mode')
652
+ }
653
+ await callTool('vibe_math_set_params', { formalVerify: 'require' }, RF)
654
+ // formalize it, restart (so the next prompt is built AFTER the proof exists), then re-verify
655
+ {
656
+ const proofNow = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-gate', content: 'theorem p_gate : 2 + 2 = 4 := by decide\n' }, RF)
657
+ assert(proofNow.ok === true && proofNow.passed === true, 'the object is now Lean-passed')
658
+ const st = await callTool('vibe_math_status', {}, RF)
659
+ assert(st.formal.passed.indexOf('p-gate') !== -1, 'status reports p-gate as passed')
660
+ assert(!st.formal.todo.some((t) => t.id === 'p-gate'), '★ satisfying the gate removes the object from the formalization TODO (no stale TODO)')
661
+ assert(!/p-gate/.test(readIf(join(gateProj, 'Formal', 'TODO.md'))), 'Formal/TODO.md no longer lists it')
662
+ assert(/- 形式化: Lean 通过/.test(readIf(join(gateProj, 'Propos', '数论', 'p-gate.md'))), 'the object card anchor now records Lean 通过')
663
+ }
664
+ await restart(RF)
665
+ 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')
666
+ {
667
+ const batch = await runVerifyRound(RF, 'p-gate', [1, 1])
668
+ assert(batch !== null, 'the re-verification round was asked')
669
+ if (batch) {
670
+ const vp = batch.map((s) => s.prompt).join('\n')
671
+ assert(/该对象已有\*\*通过的 Lean 形式化证明\*\*/.test(vp), 'the voting prompt announces the passing proof')
672
+ assert(/你不需要重新检查推导/.test(vp), '★ it tells voters NOT to re-derive')
673
+ assert(/忠实性审查/.test(vp), '★ it tells voters the review subject is now fidelity')
674
+ assert(/定义 \/ 对象 \/ 条件 \/ 假设 \/ 结论是否与命题原文\*\*完全一致\*\*/.test(vp), 'it enumerates exactly what fidelity means')
675
+ assert(!/必须产出 Lean 形式化/.test(vp), 'and the "must formalize" wording is replaced (the object already has one)')
676
+ }
677
+ }
678
+ 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')
679
+ {
680
+ const card = readIf(join(gateProj, 'Verified', '命题', 'p-gate.md'))
681
+ assert(/- 形式化: Lean 通过/.test(card), '★ the Verified card records how strong the result is (Lean 通过)')
682
+ assert(/Verified\/Lean\/p-gate\.lean/.test(card), 'the card points at the archived proof')
683
+ assert(/- 结论: 真/.test(card), 'the card states the conclusion')
684
+ }
685
+ // the blocker escape hatch must also open the gate
686
+ await callTool('vibe_math_add_proposition', { id: 'p-blocked-ok', 概述: '记录阻塞后可定论', 概率: 0.6, 分类: '数论' }, RF)
687
+ await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-blocked-ok', note: '命题涉及未形式化的分析学,本轮不做' }, RF)
688
+ await restart(RF)
689
+ assert(await runVerifyRound(RF, 'p-blocked-ok', [1, 1]) !== null, 'the blocked object is put to a vote')
690
+ 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)')
691
+ {
692
+ const card = readIf(join(gateProj, 'Verified', '命题', 'p-blocked-ok.md'))
693
+ assert(/- 形式化: 阻塞(/.test(card), 'the Verified card records the blocker')
694
+ assert(/未形式化的分析学/.test(card), 'and quotes the reason')
695
+ }
696
+
697
+ // ===============================================================
698
+ // 8. the reply-channel judgement (formal field in the verifier reply)
699
+ // ===============================================================
700
+ section('8 the per-round `formal` reply channel records the difficulty judgement')
701
+ const RG = makeRoot()
702
+ await callTool('vibe_math_new_project', { name: 'lean-reply' }, RG)
703
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RG)
704
+ const replyProj = projRoot('lean-reply')
705
+
706
+ // (a) blocked WITH a note → recorded, reason reaches the index + the card anchor
707
+ await callTool('vibe_math_add_proposition', { id: 'p-reply', 概述: '用回执记录阻塞', 概率: 0.6, 分类: '数论' }, RG)
708
+ await callTool('vibe_math_start', {}, RG)
709
+ {
710
+ const re = verifyRe('p-reply')
711
+ assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-reply'), 'p-reply was put to a vote')
712
+ const vs = unfiredVerifiers(RG, re).slice(0, 2)
713
+ if (vs.length === 2) {
714
+ for (const v of vs) firedChildren.add(v.childId)
715
+ // A verifier that never calls a Lean tool still has to state its difficulty judgement: the
716
+ // JSON reply channel is the path that actually fires in practice.
717
+ fireEnd(vs[0].childId, { Result: 0.5, Reason: '我判断形式化不划算', formal: { target: 'p-reply', decision: 'blocked', note: '需要大量未形式化的实分析前置知识' } })
718
+ await sleep(150)
719
+ const st1 = await callTool('vibe_math_status', {}, RG)
720
+ assert(st1.formal.blocked.indexOf('p-reply') !== -1, 'a `formal.decision=blocked` reply is recorded as a blocker')
721
+ assert(/实分析前置知识/.test(readIf(join(replyProj, 'Formal', 'Index.md'))), 'and its reason reaches the index')
722
+ assert(/- 形式化: 阻塞(/.test(readIf(join(replyProj, 'Propos', '数论', 'p-reply.md'))), 'the reply-recorded blocker also lands on the object card anchor')
723
+ fireEnd(vs[1].childId, { Result: 0.5, Reason: '同上' })
724
+ await sleep(200)
725
+ }
726
+ }
727
+ // (b) `used` records attempted — which does NOT open the require gate
728
+ await restart(RG)
729
+ await callTool('vibe_math_add_proposition', { id: 'p-used', 概述: '写了草稿但没跑通', 概率: 0.6, 分类: '数论' }, RG)
730
+ {
731
+ const re = verifyRe('p-used')
732
+ assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-used'), 'p-used was put to a vote')
733
+ const vs = unfiredVerifiers(RG, re).slice(0, 2)
734
+ if (vs.length === 2) {
735
+ for (const v of vs) firedChildren.add(v.childId)
736
+ fireEnd(vs[0].childId, { Result: 1, Reason: '看起来对', formal: { target: 'p-used', decision: 'used', file: 'Formal/p-used.lean' } })
737
+ await sleep(150)
738
+ const st = await callTool('vibe_math_status', {}, RG)
739
+ const o = st.formal.objects.find((x) => x.target === 'p-used')
740
+ assert(!!o && o.status === 'attempted' && o.file === 'Formal/p-used.lean', 'a `formal.decision=used` reply records the object as attempted with its file')
741
+ fireEnd(vs[1].childId, { Result: 1, Reason: '同样看起来对' })
742
+ await sleep(250)
743
+ assert(!existsSync(join(replyProj, 'Verified', '命题', 'p-used.md')), '★ attempted is NOT passed: the require gate still withholds the verdict')
744
+ assert(/p-used/.test(readIf(join(replyProj, 'Formal', 'TODO.md'))), 'and the object is on the formalization TODO')
745
+ }
746
+ }
747
+ // (c) a blocker with no note is refused (an explicit decision is required, never a silent skip)
748
+ await restart(RG)
749
+ await callTool('vibe_math_add_proposition', { id: 'p-nonote', 概述: '没有理由的阻塞', 概率: 0.6, 分类: '数论' }, RG)
750
+ {
751
+ const re = verifyRe('p-nonote')
752
+ assert(await drive(RG, () => unfiredVerifiers(RG, re).length >= 2, 'verifiers for r-p-nonote'), 'p-nonote was put to a vote')
753
+ const vs = unfiredVerifiers(RG, re).slice(0, 2)
754
+ if (vs.length === 2) {
755
+ for (const v of vs) firedChildren.add(v.childId)
756
+ fireEnd(vs[0].childId, { Result: 0.5, Reason: '不想做', formal: { target: 'p-nonote', decision: 'blocked' } })
757
+ await sleep(180)
758
+ assert(/未写明 note/.test(readIf(join(replyProj, 'Logs', '形式化.md'))), 'a blocked judgement without a note is refused with an explicit announcement')
759
+ const st = await callTool('vibe_math_status', {}, RG)
760
+ assert(st.formal.objects.every((o) => o.target !== 'p-nonote'), 'and no blocker record is created for the refused judgement')
761
+ // a formal reply without a target must not invent an object (idSafe('') would fall back to 'id')
762
+ fireEnd(vs[1].childId, { Result: 0.5, Reason: '同上', formal: { decision: 'blocked', note: '没有写 target' } })
763
+ await sleep(180)
764
+ const st2 = await callTool('vibe_math_status', {}, RG)
765
+ assert(st2.formal.objects.every((o) => o.target !== 'id' && o.target !== ''), 'a `formal` reply with no target cannot invent an object record')
766
+ }
767
+ }
768
+ await callTool('vibe_math_abort', {}, RG)
769
+
770
+ // ===============================================================
771
+ // 8b. the §4.1 `defect` channel (contract §4.1 / §6 / §10 items 8-9)
772
+ //
773
+ // A fidelity defect is NOT "the proposition is false". These are BEHAVIOURAL assertions: a real
774
+ // agent reply carrying `formal:{decision:'defect', note}` is fed through the real reply path
775
+ // (subagent/end → handleVerifier → absorbFormalReply) and the record, the archived file and the
776
+ // formalization TODO are inspected on disk.
777
+ // ===============================================================
778
+ section('8b a formal.decision=defect reply withdraws the passed proof and withholds the verdict')
779
+ const RH = makeRoot()
780
+ await callTool('vibe_math_new_project', { name: 'lean-defect' }, RH)
781
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RH)
782
+ const defectProj = projRoot('lean-defect')
783
+ await callTool('vibe_math_add_proposition', { id: 'p-defect', 概述: '形式化写窄了的命题', 概率: 0.6, 分类: '数论' }, RH)
784
+ {
785
+ const pass = await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-defect', content: 'theorem p_defect : 2 + 2 = 4 := by decide\n' }, RH)
786
+ assert(pass.ok === true && pass.passed === true, 'defect: the object starts out Lean-passed')
787
+ assert(existsSync(join(defectProj, 'Verified', 'Lean', 'p-defect.lean')), 'defect: the archived proof is on disk before the fidelity review')
788
+ }
789
+ await callTool('vibe_math_start', {}, RH)
790
+ {
791
+ const re = verifyRe('p-defect')
792
+ 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')
793
+ const vs = unfiredVerifiers(RH, re).slice(0, 2)
794
+ if (vs.length === 2) {
795
+ for (const v of vs) firedChildren.add(v.childId)
796
+ assert(/该对象已有\*\*通过的 Lean 形式化证明\*\*/.test(vs[0].prompt) && /不要投 0/.test(vs[0].prompt) && /formal:\{decision:'defect'/.test(vs[0].prompt),
797
+ 'defect: the fidelity prompt asks for the defect reply and forbids recording the deviation as 0')
798
+ // The defect reply carries an EXTREME Result on purpose: the gate (not the vote value) has to
799
+ // be what withholds the verdict — a defect must never be harvested as "the proposition is false".
800
+ fireEnd(vs[0].childId, { Result: 1, Reason: '逐条核对后认定形式化不忠实', formal: { target: 'p-defect', decision: 'defect', note: 'Lean 代码多加了 h>0 假设,命题原文未要求' } })
801
+ await sleep(240)
802
+ const st = await callTool('vibe_math_status', {}, RH)
803
+ const rec = st.formal.objects.find((o) => o.target === 'p-defect')
804
+ assert(!!rec && rec.status === 'attempted', '★ defect downgrades the formal record to attempted (observed ' + (rec && rec.status) + ')')
805
+ assert(st.formal.passed.indexOf('p-defect') === -1, '★ and the object is no longer reported as Lean-passed')
806
+ assert(!!rec && rec.proof === '', '★ defect clears the `proof` field')
807
+ assert(!existsSync(join(defectProj, 'Verified', 'Lean', 'p-defect.lean')), '★ defect deletes the archived proof Verified/Lean/p-defect.lean')
808
+ assert(existsSync(join(defectProj, 'Formal', 'p-defect.lean')), 'the WORK file Formal/p-defect.lean survives (the code itself is not lost)')
809
+ const persisted = JSON.parse(readIf(join(defectProj, 'State', 'formal.json')))
810
+ assert(persisted.records['p-defect'].decision === 'defect' && /多加了 h>0 假设/.test(persisted.records['p-defect'].note),
811
+ '★ the note (the concrete deviation) is recorded in the persisted formal record')
812
+ assert(/- 形式化: 已尝试未通过/.test(readIf(join(defectProj, 'Propos', '数论', 'p-defect.md'))), 'and the object card anchor is refreshed')
813
+ fireEnd(vs[1].childId, { Result: 1, Reason: '同意:形式化不忠实' })
814
+ await sleep(300)
815
+ }
816
+ }
817
+ {
818
+ const todo = readIf(join(defectProj, 'Formal', 'TODO.md'))
819
+ assert(/p-defect/.test(todo) && /多加了 h>0 假设/.test(todo), '★ the deviation is written into Formal/TODO.md')
820
+ const idx = readIf(join(defectProj, 'Formal', 'Index.md'))
821
+ 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')
822
+ 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")')
823
+ const card = readIf(join(defectProj, 'Propos', '数论', 'p-defect.md'))
824
+ assert(/- 状态: 未定论/.test(card), '★ and the object stays 未定论')
825
+ assert(/- 概率: 0.6/.test(card), 'the object keeps its existing probability: a defect must NOT be harvested as a refutation')
826
+ const ann = readIf(join(defectProj, 'Logs', '形式化.md'))
827
+ assert(/忠实性缺陷/.test(ann) && /多加了 h>0 假设/.test(ann), '★ the defect is announced with its concrete deviation')
828
+ assert(ann.indexOf('不是"命题为假"') !== -1, 'the announcement spells out that a fidelity defect is NOT "the proposition is false"')
829
+ const st = await callTool('vibe_math_status', {}, RH)
830
+ 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)')
831
+ }
832
+ await callTool('vibe_math_abort', {}, RH)
833
+
834
+ section('8b-2 a defect without a note is refused (the deviation must be auditable)')
835
+ const RI = makeRoot()
836
+ await callTool('vibe_math_new_project', { name: 'lean-defect-nonote' }, RI)
837
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RI)
838
+ const nonoteProj = projRoot('lean-defect-nonote')
839
+ await callTool('vibe_math_add_proposition', { id: 'p-nonote-defect', 概述: '没有偏差说明的缺陷回执', 概率: 0.6, 分类: '数论' }, RI)
840
+ await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-nonote-defect', content: 'theorem p_nn_defect : 2 + 2 = 4 := by decide\n' }, RI)
841
+ await callTool('vibe_math_start', {}, RI)
842
+ {
843
+ const re = verifyRe('p-nonote-defect')
844
+ 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')
845
+ const vs = unfiredVerifiers(RI, re).slice(0, 2)
846
+ if (vs.length === 2) {
847
+ for (const v of vs) firedChildren.add(v.childId)
848
+ fireEnd(vs[0].childId, { Result: 1, Reason: '觉得不忠实但没写清楚', formal: { target: 'p-nonote-defect', decision: 'defect' } })
849
+ await sleep(240)
850
+ const st = await callTool('vibe_math_status', {}, RI)
851
+ const rec = st.formal.objects.find((o) => o.target === 'p-nonote-defect')
852
+ assert(!!rec && rec.status === 'passed', '★ a defect WITHOUT a note is refused: the object stays Lean-passed (no silent downgrade)')
853
+ assert(existsSync(join(nonoteProj, 'Verified', 'Lean', 'p-nonote-defect.lean')), '★ and the archived proof is NOT deleted')
854
+ assert(st.formal.todo.every((t) => t.id !== 'p-nonote-defect') && !/p-nonote-defect/.test(readIf(join(nonoteProj, 'Formal', 'TODO.md'))),
855
+ 'and no bogus formalization-TODO entry is created')
856
+ assert(/未写明 note/.test(readIf(join(nonoteProj, 'Logs', '形式化.md'))), '★ the refusal is announced explicitly')
857
+ fireEnd(vs[1].childId, { Result: 1, Reason: '核对后认为一致' })
858
+ await sleep(300)
859
+ }
860
+ }
861
+ 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')
862
+ // §4.1: the downgrade is unconditional — a `blocked` record loses to a defect too (it needs REDOING,
863
+ // not a free pass through the gate, which `blocked` would otherwise grant).
864
+ await callTool('vibe_math_add_proposition', { id: 'p-blocked-defect', 概述: '阻塞后仍被认定不忠实', 概率: 0.6, 分类: '数论' }, RI)
865
+ await callTool('vibe_math_lean_archive', { kind: 'blocked', target: 'p-blocked-defect', note: '先按难度记为阻塞' }, RI)
866
+ await restart(RI)
867
+ {
868
+ const re = verifyRe('p-blocked-defect')
869
+ 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)')
870
+ const vs = unfiredVerifiers(RI, re).slice(0, 2)
871
+ if (vs.length === 2) {
872
+ for (const v of vs) firedChildren.add(v.childId)
873
+ fireEnd(vs[0].childId, { Result: 1, Reason: '形式化与命题不对应', formal: { target: 'p-blocked-defect', decision: 'defect', note: '阻塞所依据的形式化本身写错了对象' } })
874
+ await sleep(240)
875
+ const st = await callTool('vibe_math_status', {}, RI)
876
+ const rec = st.formal.objects.find((o) => o.target === 'p-blocked-defect')
877
+ assert(!!rec && rec.status === 'attempted', '★★ a defect ALWAYS downgrades, even from `blocked` (observed ' + (rec && rec.status) + ')')
878
+ assert(st.formal.blocked.indexOf('p-blocked-defect') === -1 && /阻塞所依据的形式化本身写错了对象/.test(rec.note || ''), 'and the blocked record is replaced by the concrete deviation')
879
+ fireEnd(vs[1].childId, { Result: 1, Reason: '同意,形式化写错了对象' })
880
+ await sleep(280)
881
+ }
882
+ }
883
+ assert(!existsSync(join(nonoteProj, 'Verified', '命题', 'p-blocked-defect.md')), 'require after a blocked→defect downgrade: still no Verified card (undecided, not "false")')
884
+ await callTool('vibe_math_abort', {}, RI)
885
+
886
+ // ===============================================================
887
+ // 8c. the injected text obeys the five hard requirements of contract §6
888
+ // ===============================================================
889
+ section('8c the injected text uses full tool names, Result (not verdict) and the run-before-archive rule')
890
+ const RJ = makeRoot()
891
+ await callTool('vibe_math_new_project', { name: 'lean-workline' }, RJ)
892
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'require' }), RJ)
893
+ await callTool('vibe_math_add_problem', { id: 'q-defect', description: '顺手形式化的对象', priority: 0 }, RJ)
894
+ const workProj = projRoot('lean-workline')
895
+ // a `meta.formal` defect on the WORK-round path (absorbFormalFromReply) must downgrade too
896
+ await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'q-defect', content: 'theorem q_defect : 2 + 2 = 4 := by decide\n' }, RJ)
897
+ await callTool('vibe_math_start', {}, RJ)
898
+ assert(await drive(RJ, () => !!lastSpawn(RJ, 'explorer:q-defect'), 'explorer:q-defect'), 'the explorer for q-defect was spawned')
899
+ {
900
+ const p = lastSpawn(RJ, 'explorer:q-defect').prompt
901
+ assert(/归档前先跑通(vibe_math_lean_run 或 run=true);跑不通的定义不要进可复用库。/.test(p),
902
+ '★ the work-round prompt requires a GREEN run before archiving a reusable definition (§6 hard requirement 3)')
903
+ assert(/"decision":"used\|blocked\|defect"/.test(p), 'the work-round reply contract advertises the defect decision too')
904
+ assert(!/verdict/.test(p) && !/(^|[^a-z_])lean_(run|archive|lib)/.test(p),
905
+ '★ the work-round prompt uses FULL tool names only and never the v4/v5 field name `verdict`')
906
+ fireEnd(lastSpawn(RJ, 'explorer:q-defect').childId, {
907
+ meta: { kind: 'directions', qid: 'q-defect', formal: { target: 'q-defect', decision: 'defect', note: '陈述里的自然数范围被写成了整数' },
908
+ directions: [{ id: 'd1', title: '直接形式化', method: 'Lean', core_assumption: '', feasibility: 0.6 }] },
909
+ })
910
+ await sleep(260)
911
+ const st = await callTool('vibe_math_status', {}, RJ)
912
+ const rec = st.formal.objects.find((o) => o.target === 'q-defect')
913
+ assert(!!rec && rec.status === 'attempted' && /自然数范围被写成了整数/.test(rec.note || ''),
914
+ '★ a `meta.formal` defect from a WORK reply downgrades the record too (absorbFormalFromReply, not just the verifier path)')
915
+ assert(!existsSync(join(workProj, 'Verified', 'Lean', 'q-defect.lean')), '★ and its archived proof is deleted')
916
+ }
917
+ await callTool('vibe_math_abort', {}, RJ)
918
+
919
+ section('8c-2 the fidelity branch reaches BOTH the review and the debate prompt, and names Result')
920
+ const RK = makeRoot()
921
+ await callTool('vibe_math_new_project', { name: 'lean-fidelity' }, RK)
922
+ await callTool('vibe_math_set_params', Object.assign({}, VPARAMS, { formalVerify: 'encourage', debateMaxRounds: 2 }), RK)
923
+ await callTool('vibe_math_add_proposition', { id: 'p-fid', 概述: '忠实性审查措辞观察对象', 概率: 0.6, 分类: '数论' }, RK)
924
+ await callTool('vibe_math_lean_archive', { kind: 'proof', target: 'p-fid', content: 'theorem p_fid : 2 + 2 = 4 := by decide\n' }, RK)
925
+ await callTool('vibe_math_start', {}, RK)
926
+ const fidBatch = await runVerifyRound(RK, 'p-fid', [0.9, 0.95])
927
+ assert(fidBatch !== null, 'fidelity: the review round was asked')
928
+ if (fidBatch) {
929
+ const vp = fidBatch.map((s) => s.prompt).join('\n')
930
+ 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)")
931
+ assert(/发现任何偏差,不要投 0/.test(vp) && /形式化不合格/.test(vp), '★ and forbids expressing a fidelity defect as 0')
932
+ assert(/formal:\{decision:'defect', note:'<具体偏差>'\}/.test(vp), 'and points at the defect reply field to record it')
933
+ assert(/独立于这份 Lean 代码/.test(vp), 'only an INDEPENDENT refutation may be voted 0')
934
+ assert(/Result/.test(vp) && !/verdict/.test(vp), '★ the voting prompt names Result, never verdict (§6 hard requirement 2)')
935
+ assert(vp.indexOf('偏离 → 0') === -1, '★ no "偏离 → 0" instruction anywhere in the fidelity branch (contract §10 item 9)')
936
+ }
937
+ 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')
938
+ {
939
+ const dp = wakes.filter((w) => w.rootId === RK.id).map((w) => w.prompt).join('\n')
940
+ assert(/一致 → Result = 1/.test(dp) && /不要投 0/.test(dp), '★ the DEBATE prompt carries the same fidelity wording')
941
+ assert(/Result/.test(dp) && !/verdict/.test(dp), 'the debate prompt names Result, never verdict')
942
+ assert(dp.indexOf('偏离 → 0') === -1, 'the debate prompt also refuses "a deviation is a 0"')
943
+ }
944
+ await callTool('vibe_math_abort', {}, RK)
945
+
946
+ // ===============================================================
947
+ // 9. reporting + persistence
948
+ // ===============================================================
949
+ section('9 the office can audit formal strength')
950
+ {
951
+ const rep = await callTool('vibe_math_report', {}, RF)
952
+ assert(rep.formal && rep.formal.mode === 'require', 'the JSON report carries the formal mode')
953
+ 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')
954
+ assert(rep.params.formalVerify === 'require' && rep.params.leanCommand === 'lean', 'the readable parameter table carries the Lean parameters')
955
+ const md = readIf(join(gateProj, 'Logs', '报告.md'))
956
+ assert(/## Lean 形式化/.test(md), 'the human-readable report has a Lean formal-verification section')
957
+ assert(/已通过:.*p-gate/.test(md), 'it lists Lean-passed objects')
958
+ assert(/已记录阻塞:.*p-blocked-ok/.test(md), 'it lists blocked objects')
959
+ assert(/可复用库:VibeMath\/Formal\/\{Lib,Proved\}\//.test(md), 'it documents the path layout')
960
+ await callTool('vibe_math_report', {}, RA)
961
+ assert(/未启用(`formalVerify` = off/.test(readIf(join(offProj, 'Logs', '报告.md'))), 'in off mode the report says the feature is not enabled')
962
+ const offRep = await callTool('vibe_math_report', {}, RA)
963
+ assert(offRep.formal.mode === 'off' && /off/.test(offRep.formal.note || ''), 'and the JSON report says the same')
964
+ }
965
+ {
966
+ const before = JSON.parse(readIf(join(gateProj, 'State', 'formal.json')))
967
+ 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')
968
+ assert(Array.isArray(before.todo), 'the formalization TODO is persisted alongside it')
969
+ assert(before.records['p-blocked-ok'].status === 'blocked' && /分析学/.test(before.records['p-blocked-ok'].note), 'a blocker record keeps its reason across sessions')
970
+ assert(existsSync(join(VIBE, 'Formal', 'Proved', 'Index.md')) && existsSync(join(libPath, 'Index.md')), 'both global indexes are framework-maintained')
971
+ }
972
+
973
+ // ===============================================================
974
+ // 10. interaction corpus (AUDIT-CHECKLIST §2.4) — a HUMAN must be able to re-read
975
+ // every prompt the framework emitted, not just the assertions about them.
976
+ // ===============================================================
977
+ section('10 the captured prompt corpus is written for human review')
978
+ {
979
+ mkdirSync(CORPUS_DIR, { recursive: true })
980
+ writeFileSync(join(CORPUS_DIR, 'formal-verify-v3.json'), JSON.stringify({ entries: corpus }, null, 2), 'utf8')
981
+ const md = ['# V3 形式化验证交互语料(prompt corpus)', '',
982
+ '> 由 `formal-verify-v3.test.mjs` 落盘:框架**真正发出**的每一条提示词原文。路径归一化:工作区 → `<WS>`,',
983
+ '> VibeMath 根 → `<VIBEMATH>`(两者都按正/反斜杠两种写法替换,因此语料是确定性的、可 diff 的、不泄露本机路径)。',
984
+ '> 覆盖:explorer / solver / method-keeper 的日常工作提示词(含「顺手形式化」与"归档前先跑通"),',
985
+ '> `off`(零 Lean 文本)、`encourage`、**`require`** 三档下的表决初评与辩论提示词,`passed` 之后的忠实性审查分支',
986
+ '> (含 `defect` 出口),以及规划提示词。', '']
987
+ for (let i = 0; i < corpus.length; i++) {
988
+ const c = corpus[i]
989
+ md.push('## [' + i + '] ' + c.kind + ' · ' + c.label)
990
+ md.push('')
991
+ md.push('```text')
992
+ md.push(c.prompt)
993
+ md.push('```')
994
+ md.push('')
995
+ }
996
+ writeFileSync(join(CORPUS_DIR, 'formal-verify-v3.md'), md.join('\n'), 'utf8')
997
+ assert(existsSync(join(CORPUS_DIR, 'formal-verify-v3.json')) && existsSync(join(CORPUS_DIR, 'formal-verify-v3.md')), 'the prompt corpus was written (JSON + Markdown)')
998
+ assert(corpus.length >= 25, 'the corpus covers the whole run (' + corpus.length + ' prompts)')
999
+ 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')
1000
+ assert(corpus.some((c) => c.kind === 'wake'), 'the corpus also keeps the continuation prompts (debate rounds)')
1001
+ // generic sweep over EVERY captured prompt, not spot checks (AUDIT §2.1)
1002
+ const dirty = corpus.filter((c) => /\[object Object\]|\bNaN\b|:\s*undefined|["']undefined["']|undefined\s*[,}\]]/.test(c.prompt))
1003
+ assert(dirty.length === 0, 'no captured prompt contains placeholder garbage (' + dirty.map((d) => d.label).join(',') + ')')
1004
+ const joined = corpus.map((c) => c.prompt).join('\n')
1005
+ assert(joined.indexOf(WS) === -1 && joined.indexOf(WS.replace(/\\/g, '/')) === -1, 'every captured prompt normalises the workspace path to <WS> (the corpus stays diffable)')
1006
+ assert(joined.indexOf(VIBE) === -1 && joined.indexOf(VIBE.replace(/\\/g, '/')) === -1 && joined.indexOf('<VIBEMATH>') !== -1,
1007
+ '★ every captured prompt normalises the VibeMath root to <VIBEMATH> (no machine path leaks into the shipped corpus, contract §10 item 10)')
1008
+ assert(!corpus.some((c) => c.root === RA.id && /Lean|形式化/.test(c.prompt)),
1009
+ '★ the off-mode prompts captured in the corpus contain ZERO Lean text (off stays a true no-op)')
1010
+ // contract §10 item 10: the corpus must cover require AND the work round (not just encourage + fidelity)
1011
+ assert(corpus.some((c) => /【Lean 形式化验证(鼓励模式)】/.test(c.prompt)), '★ the corpus covers the encourage-mode verification prompt')
1012
+ assert(corpus.some((c) => /【Lean 形式化验证(强制模式)】/.test(c.prompt)), '★ the corpus covers the REQUIRE-mode verification prompt')
1013
+ assert(corpus.some((c) => /【顺手形式化(鼓励)】/.test(c.prompt)) && corpus.some((c) => /【顺手形式化(强制)】/.test(c.prompt)), '★ the corpus covers the work-round 顺手形式化 prompt in both modes')
1014
+ assert(corpus.some((c) => /一致 → Result = 1/.test(c.prompt)), '★ the corpus keeps the passed/fidelity branch verbatim for human review')
1015
+ // contract §6 hard requirements 1-2 + §10 item 9, swept over EVERY captured prompt
1016
+ const verifier = corpus.filter((c) => c.label.startsWith('verifier:'))
1017
+ assert(verifier.length >= 5 && verifier.every((c) => /Result/.test(c.prompt) && !/verdict/.test(c.prompt)),
1018
+ '★ every captured voting prompt names Result and never verdict (§6 hard requirement 2)')
1019
+ const bareTools = corpus.filter((c) => /(^|[^a-z_])lean_(run|archive|lib)/.test(c.prompt))
1020
+ assert(bareTools.length === 0, '★ no captured prompt abbreviates a Lean tool name (§6 hard requirement 1): ' + bareTools.map((b) => b.label).join(','))
1021
+ const zeroDeviation = corpus.filter((c) => c.prompt.indexOf('偏离 → 0') !== -1)
1022
+ 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(','))
1023
+ }
1024
+
1025
+ console.log('')
1026
+ console.log('passed=' + passed + ' failed=' + failed)
1027
+ if (failed) { console.error('FAILURES:'); for (const f of failures) console.error(' - ' + f) }
1028
+ rmSync(WS, { recursive: true, force: true })
1029
+ if (failed) process.exit(1)
1030
+ console.log('ALL GREEN')
1031
+ process.exit(0)