dsh-vibe-math 2.5.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +175 -369
- package/README.md +175 -370
- package/cordis.patch.yml +78 -22
- package/docs/AUDIT-CHECKLIST.md +3 -3
- package/docs/final-paper.md +172 -0
- package/docs/formal-verification.md +184 -29
- package/docs/math-computation.md +121 -0
- package/docs/release-notes/RELEASE-NOTES-2.6.0.md +268 -0
- package/docs/release-notes/RELEASE-NOTES-2.7.0.en.md +151 -0
- package/docs/release-notes/RELEASE-NOTES-2.7.0.md +115 -0
- package/docs/test-timing.md +25 -9
- package/installer.js +7 -4
- package/package.json +21 -3
- package/prompt-corpus-persona/persona-corpus.json +16 -16
- package/prompt-corpus-persona/persona-corpus.md +164 -52
- package/prompt-corpus-v2/formal-verify-v2.json +128 -92
- package/prompt-corpus-v2/formal-verify-v2.md +1574 -108
- package/prompt-corpus-v3/formal-verify-v3.json +137 -53
- package/prompt-corpus-v3/formal-verify-v3.md +1406 -100
- package/prompt-corpus-v4/formal-verify-v4.json +14 -14
- package/prompt-corpus-v4/formal-verify-v4.md +247 -14
- package/prompt-corpus-v5/prompt-corpus-v5.json +62 -62
- package/prompt-corpus-v5/prompt-corpus-v5.md +570 -3
- package/tests/audit-math-computation-contract.mjs +191 -0
- package/tests/audit-math-computation-parity.mjs +169 -0
- package/tests/audit-math-computation-sensitivity.mjs +231 -0
- package/tests/audit-persona-sensitivity.mjs +64 -11
- package/tests/audit-persona-surface.test.mjs +53 -16
- package/tests/audit-v5-integrity.mjs +14 -0
- package/tests/e2e-v5-round2.test.mjs +923 -3
- package/tests/formal-verify-v2.test.mjs +295 -6
- package/tests/formal-verify-v3.test.mjs +275 -4
- package/tests/formal-verify-v4.test.mjs +295 -6
- package/tests/formal-verify-v5.test.mjs +9 -1
- package/tests/helpers/math-computation-fake-seam.mjs +135 -0
- package/tests/math-computation-shared.test.mjs +504 -0
- package/tests/prompt-v5-integrity.test.mjs +14 -8
- package/tests/selfdrive-v5.mjs +55 -4
- package/vibe-math-v2/agent.cordis.yml +36 -14
- package/vibe-math-v2/math-computation.js +936 -0
- package/vibe-math-v2/math-engines.js +156 -0
- package/vibe-math-v2/vibe-math-v2.js +1653 -48
- package/vibe-math-v2//345/256/236/347/216/260/346/226/271/346/241/210.md +6 -0
- package/vibe-math-v3/agent.cordis.yml +30 -12
- package/vibe-math-v3/math-computation.js +936 -0
- package/vibe-math-v3/math-engines.js +156 -0
- package/vibe-math-v3/vibe-math-v3.js +1623 -53
- package/vibe-math-v3//345/256/236/347/216/260/346/226/271/346/241/210.md +6 -0
- package/vibe-math-v4/agent.cordis.yml +44 -8
- package/vibe-math-v4/math-computation.js +936 -0
- package/vibe-math-v4/math-engines.js +156 -0
- package/vibe-math-v4/vibe-math-v4.js +1592 -37
- package/vibe-math-v4//345/256/236/347/216/260/346/226/271/346/241/210.md +6 -0
- package/vibe-math-v5/agent.cordis.yml +46 -10
- package/vibe-math-v5/math-computation.js +936 -0
- package/vibe-math-v5/math-engines.js +156 -0
- package/vibe-math-v5/vibe-math-v5.js +2233 -42
- package/vibe-math-v5//345/256/236/347/216/260/346/226/271/346/241/210.md +153 -4
- package/vibe-math-v5//346/236/266/346/236/204/345/233/276.md +251 -0
|
@@ -0,0 +1,936 @@
|
|
|
1
|
+
// math-computation.js — the `math_computation` tool for the Vibe Math presets (P1).
|
|
2
|
+
//
|
|
3
|
+
// CANONICAL COPY. Must stay BYTE-IDENTICAL in:
|
|
4
|
+
// vibe-math-v2/math-computation.js, vibe-math-v3/…, vibe-math-v4/…, vibe-math-v5/…
|
|
5
|
+
// Interface freeze: _oneoff/mc-P1-ready/INTERFACE-FREEZE.md
|
|
6
|
+
// Contract: _oneoff/math-computation-spec-v3.md (rev-3) + _oneoff/mc-P1-ready/{tool-schema.json,receipt.md,prompts.md,guards.md}
|
|
7
|
+
//
|
|
8
|
+
// Imports only node:crypto and its sibling ./math-engines.js (no repo imports), so the four
|
|
9
|
+
// byte-identical copies work from any preset directory and from an installed .agent-presets dir.
|
|
10
|
+
import { createHash } from 'node:crypto'
|
|
11
|
+
import { MATH_ENGINES, MATH_ENGINE_ORDER, mathEngineCandidates, mathEngineArgErrorHints } from './math-engines.js'
|
|
12
|
+
|
|
13
|
+
export const MATH_TOOL_NAME = 'math_computation'
|
|
14
|
+
|
|
15
|
+
export const MATH_PARAM_NAMES = Object.freeze([
|
|
16
|
+
'mathComputation', 'mathMode', 'mathEngines', 'mathTimeoutMs', 'mathPackages', 'mathInstallScope',
|
|
17
|
+
])
|
|
18
|
+
|
|
19
|
+
export const MATH_PARAM_DEFAULTS = Object.freeze({
|
|
20
|
+
mathComputation: 'auto',
|
|
21
|
+
mathMode: 'typed+shell',
|
|
22
|
+
mathEngines: MATH_ENGINE_ORDER.slice(),
|
|
23
|
+
mathTimeoutMs: 60000,
|
|
24
|
+
mathPackages: [],
|
|
25
|
+
mathInstallScope: 'user',
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
export const MATH_FAILURE_CODES = Object.freeze([
|
|
29
|
+
'MATH_NOT_AVAILABLE',
|
|
30
|
+
'MATH_ENGINE_NOT_FOUND',
|
|
31
|
+
'MATH_ENGINE_LICENSE_REQUIRED',
|
|
32
|
+
'MATH_ENGINE_UNUSABLE',
|
|
33
|
+
'MATH_MISSING_PACKAGES',
|
|
34
|
+
'MATH_TIMEOUT',
|
|
35
|
+
'MATH_NONZERO_EXIT',
|
|
36
|
+
'MATH_ENGINE_BAD_ARGV',
|
|
37
|
+
'MATH_REFUSED',
|
|
38
|
+
'MATH_INVALID_ARGUMENT',
|
|
39
|
+
'MATH_NO_SUBPROCESS',
|
|
40
|
+
])
|
|
41
|
+
|
|
42
|
+
export const MATH_CAPS = Object.freeze({ stdout: 64 * 1024, stderr: 64 * 1024, file: 4 * 1024 * 1024 })
|
|
43
|
+
|
|
44
|
+
// Archive retention (P2a item 5): a documented CAP that only ever WARNS - the tool never deletes.
|
|
45
|
+
// Per-run: the attempt number that may be created for one archive id (attempt 1 lives in
|
|
46
|
+
// Computation/<id>/, later attempts in Computation/<id>/attempts/<n>/). Per-project: only checked
|
|
47
|
+
// when the host exposes the optional listDir(); absent that, the per-run cap still applies.
|
|
48
|
+
export const MATH_ARCHIVE_MAX_ATTEMPTS_PER_RUN = 20
|
|
49
|
+
export const MATH_ARCHIVE_MAX_RUNS = 200
|
|
50
|
+
export const MATH_ARCHIVE_WARNING = 'ARCHIVE_RETENTION_EXCEEDED'
|
|
51
|
+
export const MATH_SCRIPT_CHANGED_WARNING = 'SCRIPT_CHANGED_SINCE_LAST_RECEIPT'
|
|
52
|
+
export const MATH_SCRIPT_CHANGED_DURING_RUN_WARNING = 'SCRIPT_CHANGED_DURING_RUN'
|
|
53
|
+
|
|
54
|
+
export const MATH_SHELL_FALLBACK_MARK = '未经工具归档'
|
|
55
|
+
export const MATH_SHELL_FALLBACK_MARK_EN = 'not tool-archived'
|
|
56
|
+
export const MATH_BAD_ARGV_HINT = 'mathEngineOverride'
|
|
57
|
+
|
|
58
|
+
// ── prompt text (verbatim source: _oneoff/mc-P1-ready/prompts.md) ───────────────────────────────
|
|
59
|
+
export const MATH_TOOL_DESCRIPTION = '数学计算:先用 op:\'probe\' 预检本机可用引擎与许可,再用 op:\'run\' 计算(mode=code|file|expr;'
|
|
60
|
+
+ 'P1 引擎=python|r|octave|julia + matlab|maple|wolfram(仅探测/许可,永不安装)+ cli(默认开启:用你指定的命令执行,'
|
|
61
|
+
+ '仍受本工具的超时/输出上限/cwd 约束并留回执;它与宿主 shell 的区别就是有回执与上限——要用宿主 shell 兜底由 mathMode 控制,'
|
|
62
|
+
+ '且结论必须标注未经工具归档))。每次执行都会归档成可复核回执(Computation/<id>/),回执里含 scriptPath/scriptHash 与**实际 argv**;'
|
|
63
|
+
+ '脚本原件就在那个归档目录里,你可以用普通文件工具打开/编辑它,编辑后用 mode:\'file\' 重跑会得到一份**新回执**——'
|
|
64
|
+
+ '**不得**拿旧回执当作修改后代码的证据。缺引擎/缺包只报告并给"用户自装指引"或"代理代装计划"(先计划、再确认);'
|
|
65
|
+
+ '商业引擎只给厂商指引;引擎选项报错时会回显 argv 并提示用 mathEngineOverride。计算结果是经验证据,不是证明。'
|
|
66
|
+
|
|
67
|
+
export const MATH_PERSONA_TOOL_LINE = '- math_computation {op: probe|run|receipt|install, engine, mode: code|file|expr, …} — '
|
|
68
|
+
+ '先 probe 预检引擎/包/许可,再调引擎计算并把脚本与输出归档成可复核回执;缺引擎/缺包只报告与给安装指引/计划;shell 兜底不算归档。'
|
|
69
|
+
|
|
70
|
+
// P2a: the archive -> edit -> re-run workflow. Injected into every preset's rule block (and appended
|
|
71
|
+
// to both persona blocks) so an agent cannot miss that (a) the script is archived, (b) it may edit
|
|
72
|
+
// it, and (c) re-running is what produces evidence for the edited code.
|
|
73
|
+
export const MATH_ARCHIVE_WORKFLOW_LINE = '- 归档→编辑→重跑:mode:\'code\' 的脚本原件在回执的 scriptPath(Computation/<id>/script.<ext>),你可以用普通文件工具打开并编辑它;'
|
|
74
|
+
+ '编辑后用 mode:\'file\' 指向它重跑,会写出一份**新回执/新 attempt**(含新的 scriptHash)。**旧回执对修改后的代码无效**——'
|
|
75
|
+
+ '报告里必须引用与当前代码哈希一致的那份回执;工具会在 scriptChanged / scriptChangedDuringRun 为 true 时显式告警。'
|
|
76
|
+
|
|
77
|
+
export const MATH_ARCHIVE_WORKFLOW_LINE_EN = '- Archive -> edit -> re-run: for mode:\'code\' the script original is at the receipt\'s scriptPath (Computation/<id>/script.<ext>) and you may open/edit it with your normal file tools; after editing, re-run it with mode:\'file\' to write a NEW receipt/attempt with a NEW scriptHash. **An old receipt is NOT evidence for edited code** - cite the receipt whose scriptHash matches the current code; the tool warns explicitly via scriptChanged / scriptChangedDuringRun.'
|
|
78
|
+
|
|
79
|
+
export const MATH_RULE_LINES = Object.freeze([
|
|
80
|
+
'- 需要精确数值、符号化简、反例搜索、统计或线性代数时调用 math_computation:先 probe,再 run。',
|
|
81
|
+
'- 复核他人的数值结论时用 op:\'receipt\'(或 op:\'run\', mode:\'file\' 指向同一脚本)重跑,并把回执路径写进报告。',
|
|
82
|
+
'- 归档即引用:报告里带 Computation/<id>/receipt.json;这是"支撑材料"的用法。',
|
|
83
|
+
'- 判断标准:① 有价值或可能复用;② 较为关键或必要;③ 你对该陈述有把握(置信度高)——没把握的先别入库。',
|
|
84
|
+
'- 不得把计算结果当成"已证明":对象是否已验证仍只由本预设既有的验证/共识路径给出。',
|
|
85
|
+
])
|
|
86
|
+
|
|
87
|
+
// The shell-fallback sentence is deliberately NOT part of MATH_RULE_LINES: it is only advertised
|
|
88
|
+
// when mathMode === 'typed+shell'. Owners either use mathAvailabilityLine(probe, lang, mathMode)
|
|
89
|
+
// (which appends it conditionally) or append MATH_SHELL_RULE_LINE themselves under the same
|
|
90
|
+
// condition. A 'typed' preset must contain no shell-fallback sentence at all.
|
|
91
|
+
export const MATH_SHELL_RULE_LINE = '- shell 兜底标注:工具不可用而改用宿主 shell 时,结论必须写"未经工具归档(shell 路径)",且不得与工具回执混同(shell 无回执、无超时/输出上限保证)。'
|
|
92
|
+
|
|
93
|
+
export const MATH_RULE_LINES_EN = Object.freeze([
|
|
94
|
+
'- Call math_computation for exact numerics, symbolic simplification, counter-example search, statistics or linear algebra: probe first, then run.',
|
|
95
|
+
'- To re-check someone else\'s numeric conclusion, re-run the same script (op:\'receipt\' or op:\'run\', mode:\'file\') and cite the receipt path.',
|
|
96
|
+
'- Archive means cite: put Computation/<id>/receipt.json in your report - that is what "supporting material" means.',
|
|
97
|
+
'- Criteria: (1) valuable or likely reusable; (2) important or necessary; (3) you are confident in it - do not archive what you are unsure about.',
|
|
98
|
+
'- Never treat a computation result as "proved": whether an object is verified is still decided only by this preset\'s existing verification/consensus path.',
|
|
99
|
+
])
|
|
100
|
+
|
|
101
|
+
export const MATH_SHELL_RULE_LINE_EN = '- Shell fallback: if the tool cannot run you may use the host shell, but mark the conclusion "not tool-archived (shell path)" - shell runs have no receipt and no timeout/output guarantees; only tool-routed computations count as reproducible supporting material.'
|
|
102
|
+
|
|
103
|
+
export const MATH_TOOL_SCHEMA = Object.freeze({
|
|
104
|
+
type: 'object',
|
|
105
|
+
properties: {
|
|
106
|
+
op: { type: 'string', enum: ['probe', 'run', 'receipt', 'install'] },
|
|
107
|
+
engine: { type: 'string' },
|
|
108
|
+
mode: { type: 'string', enum: ['code', 'file', 'expr'] },
|
|
109
|
+
code: { type: 'string' },
|
|
110
|
+
file: { type: 'string' },
|
|
111
|
+
expr: { type: 'string' },
|
|
112
|
+
packages: { type: 'array', items: { type: 'string' } },
|
|
113
|
+
timeoutMs: { type: 'integer' },
|
|
114
|
+
captureFiles: { type: 'array', items: { type: 'string' } },
|
|
115
|
+
record: { type: 'boolean' },
|
|
116
|
+
cli: {
|
|
117
|
+
type: 'object',
|
|
118
|
+
properties: { command: { type: 'string' }, argv: { type: 'array', items: { type: 'string' } }, stdin: { type: 'string' } },
|
|
119
|
+
required: ['command'],
|
|
120
|
+
additionalProperties: false,
|
|
121
|
+
},
|
|
122
|
+
scope: { type: 'string', enum: ['user', 'system'] },
|
|
123
|
+
dryRun: { type: 'boolean' },
|
|
124
|
+
confirm: { type: 'string' },
|
|
125
|
+
// AUDIT-B FIX (HIGH): the escape hatch the BAD_ARGV message advertises must be a real, accepted
|
|
126
|
+
// argument. Shape: { <engine>: { versionArgv?, scriptArgv?, evalArgv?, packageProbe? } }.
|
|
127
|
+
mathEngineOverride: { type: 'object' },
|
|
128
|
+
},
|
|
129
|
+
required: ['op'],
|
|
130
|
+
additionalProperties: false,
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
// ── small helpers ───────────────────────────────────────────────────────────────────────────────
|
|
134
|
+
function sha256(s) { return createHash('sha256').update(String(s)).digest('hex') }
|
|
135
|
+
function isObj(v) { return !!v && typeof v === 'object' && !Array.isArray(v) }
|
|
136
|
+
function canonical(s) { return String(s == null ? '' : s).replace(/\r\n/g, '\n').replace(/[ \t]+$/gm, '').replace(/\n+$/, '') + '\n' }
|
|
137
|
+
function slug(s) { return String(s == null ? '' : s).replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'default' }
|
|
138
|
+
function absJoin(root, rel) { return String(root).replace(/[\\/]+$/, '') + '/' + String(rel).replace(/^[\\/]+/, '') }
|
|
139
|
+
function projectRel(root, rel) {
|
|
140
|
+
const raw = String(rel == null ? '' : rel).trim()
|
|
141
|
+
if (!raw) return null
|
|
142
|
+
const norm = raw.replace(/\\/g, '/')
|
|
143
|
+
if (norm.startsWith('/') || /^[A-Za-z]:/.test(norm)) return null
|
|
144
|
+
const parts = []
|
|
145
|
+
for (const seg of norm.split('/')) {
|
|
146
|
+
if (!seg || seg === '.') continue
|
|
147
|
+
if (seg === '..') { if (!parts.length) return null; parts.pop(); continue }
|
|
148
|
+
parts.push(seg)
|
|
149
|
+
}
|
|
150
|
+
return parts.join('/')
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// ── params ──────────────────────────────────────────────────────────────────────────────────────
|
|
154
|
+
export function normalizeMathParams(raw) {
|
|
155
|
+
const r = isObj(raw) ? raw : {}
|
|
156
|
+
const out = {}
|
|
157
|
+
if ('mathComputation' in r) out.mathComputation = (r.mathComputation === 'off' || r.mathComputation === 'auto' || r.mathComputation === 'on') ? r.mathComputation : MATH_PARAM_DEFAULTS.mathComputation
|
|
158
|
+
if ('mathMode' in r) out.mathMode = (r.mathMode === 'typed' || r.mathMode === 'typed+shell') ? r.mathMode : MATH_PARAM_DEFAULTS.mathMode
|
|
159
|
+
if ('mathEngines' in r) {
|
|
160
|
+
const list = Array.isArray(r.mathEngines) ? r.mathEngines.filter((x) => typeof x === 'string' && !!MATH_ENGINES[x]) : []
|
|
161
|
+
const seen = []
|
|
162
|
+
for (const n of list) if (seen.indexOf(n) === -1) seen.push(n)
|
|
163
|
+
out.mathEngines = seen.length ? seen : MATH_PARAM_DEFAULTS.mathEngines.slice()
|
|
164
|
+
}
|
|
165
|
+
if ('mathTimeoutMs' in r) {
|
|
166
|
+
const n = Number(r.mathTimeoutMs)
|
|
167
|
+
out.mathTimeoutMs = Number.isFinite(n) && n > 0 ? Math.max(1000, Math.floor(n)) : MATH_PARAM_DEFAULTS.mathTimeoutMs
|
|
168
|
+
}
|
|
169
|
+
if ('mathPackages' in r) {
|
|
170
|
+
const list = Array.isArray(r.mathPackages) ? r.mathPackages.filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim()) : []
|
|
171
|
+
const seen = []
|
|
172
|
+
for (const n of list) if (seen.indexOf(n) === -1) seen.push(n)
|
|
173
|
+
out.mathPackages = seen
|
|
174
|
+
}
|
|
175
|
+
if ('mathInstallScope' in r) out.mathInstallScope = (r.mathInstallScope === 'user' || r.mathInstallScope === 'system') ? r.mathInstallScope : MATH_PARAM_DEFAULTS.mathInstallScope
|
|
176
|
+
return out
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
export function effectiveMathParams(raw) {
|
|
180
|
+
return Object.assign({}, MATH_PARAM_DEFAULTS, normalizeMathParams(raw))
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// ── closed-schema validation ────────────────────────────────────────────────────────────────────
|
|
184
|
+
const ALLOWED_ARGS = ['op', 'engine', 'mode', 'code', 'file', 'expr', 'packages', 'timeoutMs', 'captureFiles', 'record', 'cli', 'scope', 'dryRun', 'confirm', 'mathEngineOverride']
|
|
185
|
+
// AUDIT-B FIX (HIGH): validate the override shape in the same closed-argument spirit as everything
|
|
186
|
+
// else, so the escape hatch is usable but cannot smuggle arbitrary junk into argv assembly.
|
|
187
|
+
const OVERRIDE_ARGV_KEYS = ['versionArgv', 'scriptArgv', 'evalArgv']
|
|
188
|
+
function validateEngineOverride(ov) {
|
|
189
|
+
if (!isObj(ov)) return bad('mathEngineOverride must be an object keyed by engine name')
|
|
190
|
+
for (const name of Object.keys(ov)) {
|
|
191
|
+
if (!MATH_ENGINES[name]) return bad('mathEngineOverride: unknown engine ' + name + '(可用:' + MATH_ENGINE_ORDER.join(', ') + ')')
|
|
192
|
+
const o = ov[name]
|
|
193
|
+
if (!isObj(o)) return bad('mathEngineOverride.' + name + ' must be an object')
|
|
194
|
+
for (const k of Object.keys(o)) {
|
|
195
|
+
if (OVERRIDE_ARGV_KEYS.indexOf(k) === -1 && k !== 'packageProbe') return bad('mathEngineOverride.' + name + ': unknown key ' + k)
|
|
196
|
+
if (OVERRIDE_ARGV_KEYS.indexOf(k) !== -1 && (!Array.isArray(o[k]) || o[k].some((a) => typeof a !== 'string'))) return bad('mathEngineOverride.' + name + '.' + k + ' must be a string[]')
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return null
|
|
200
|
+
}
|
|
201
|
+
function bad(reason, code, nextHint) { const out = { ok: false, code: code || 'MATH_INVALID_ARGUMENT', reason: reason }; if (nextHint) out.next = nextHint; return out }
|
|
202
|
+
|
|
203
|
+
export function validateMathArgs(args, params) {
|
|
204
|
+
if (!isObj(args)) return bad('args must be an object')
|
|
205
|
+
for (const k of Object.keys(args)) if (ALLOWED_ARGS.indexOf(k) === -1) return bad('unknown argument: ' + k)
|
|
206
|
+
const op = args.op
|
|
207
|
+
if (op !== 'probe' && op !== 'run' && op !== 'receipt' && op !== 'install') return bad('op must be probe|run|receipt|install')
|
|
208
|
+
const p = effectiveMathParams(params)
|
|
209
|
+
if (args.engine !== undefined) {
|
|
210
|
+
if (typeof args.engine !== 'string') return bad('engine must be a string')
|
|
211
|
+
if (args.engine !== 'auto' && !MATH_ENGINES[args.engine]) return bad('unknown engine: ' + args.engine)
|
|
212
|
+
}
|
|
213
|
+
if (args.packages !== undefined && (!Array.isArray(args.packages) || args.packages.some((x) => typeof x !== 'string'))) return bad('packages must be a string[]')
|
|
214
|
+
if (args.captureFiles !== undefined && (!Array.isArray(args.captureFiles) || args.captureFiles.some((x) => typeof x !== 'string'))) return bad('captureFiles must be a string[]')
|
|
215
|
+
if (args.timeoutMs !== undefined) {
|
|
216
|
+
const n = Number(args.timeoutMs)
|
|
217
|
+
if (!Number.isFinite(n) || n < 1000) return bad('timeoutMs must be an integer >= 1000')
|
|
218
|
+
}
|
|
219
|
+
if (args.record !== undefined && typeof args.record !== 'boolean') return bad('record must be a boolean')
|
|
220
|
+
if (args.dryRun !== undefined && typeof args.dryRun !== 'boolean') return bad('dryRun must be a boolean')
|
|
221
|
+
if (args.confirm !== undefined && typeof args.confirm !== 'string') return bad('confirm must be a string')
|
|
222
|
+
if (args.mathEngineOverride !== undefined) {
|
|
223
|
+
const badOv = validateEngineOverride(args.mathEngineOverride)
|
|
224
|
+
if (badOv) return badOv
|
|
225
|
+
}
|
|
226
|
+
if (args.scope !== undefined && args.scope !== 'user' && args.scope !== 'system') return bad('scope must be user|system')
|
|
227
|
+
if (args.cli !== undefined) {
|
|
228
|
+
if (!isObj(args.cli)) return bad('cli must be an object')
|
|
229
|
+
for (const k of Object.keys(args.cli)) if (['command', 'argv', 'stdin'].indexOf(k) === -1) return bad('unknown cli key: ' + k)
|
|
230
|
+
if (typeof args.cli.command !== 'string' || !args.cli.command.trim()) return bad('cli.command is required')
|
|
231
|
+
if (args.cli.argv !== undefined && (!Array.isArray(args.cli.argv) || args.cli.argv.some((x) => typeof x !== 'string'))) return bad('cli.argv must be a string[]')
|
|
232
|
+
}
|
|
233
|
+
if (op === 'run') {
|
|
234
|
+
const mode = args.mode
|
|
235
|
+
if (mode !== 'code' && mode !== 'file' && mode !== 'expr') return bad('mode must be code|file|expr for op=run')
|
|
236
|
+
const engine = args.engine || 'auto'
|
|
237
|
+
if (engine === 'cli') {
|
|
238
|
+
if (p.mathMode !== 'typed+shell') return bad('engine=cli is disabled while mathMode=' + p.mathMode, 'MATH_REFUSED', next('reason', { reason: 'policy' }))
|
|
239
|
+
if (p.mathEngines.indexOf('cli') === -1) return bad('engine=cli is not in mathEngines', 'MATH_REFUSED', next('reason', { reason: 'engine-not-allowed' }))
|
|
240
|
+
if (!isObj(args.cli)) return bad('engine=cli requires cli:{command,argv}', 'MATH_REFUSED', next('reason', { reason: 'missing-cli-command' }))
|
|
241
|
+
if (mode === 'expr') return bad('cli does not support mode=expr', 'MATH_REFUSED', next('reason', { reason: 'expr-not-supported' }))
|
|
242
|
+
}
|
|
243
|
+
if (mode === 'code' && typeof args.code !== 'string') return bad('mode=code requires code')
|
|
244
|
+
if (mode === 'file') {
|
|
245
|
+
if (typeof args.file !== 'string') return bad('mode=file requires file')
|
|
246
|
+
if (projectRel('', args.file) === null) return bad('file must be a project-relative path inside the project', 'MATH_REFUSED', next('reason', { reason: 'path-outside-project' }))
|
|
247
|
+
}
|
|
248
|
+
if (mode === 'expr' && typeof args.expr !== 'string') return bad('mode=expr requires expr')
|
|
249
|
+
if (engine !== 'cli' && !MATH_ENGINES[engine] && engine !== 'auto') return bad('unknown engine: ' + engine)
|
|
250
|
+
}
|
|
251
|
+
if (op === 'receipt' && typeof args.file !== 'string') return bad('op=receipt requires file (a receipt id or script path)')
|
|
252
|
+
if (op === 'install') {
|
|
253
|
+
if (!Array.isArray(args.packages) || !args.packages.length) return bad('op=install requires packages[]')
|
|
254
|
+
}
|
|
255
|
+
return { ok: true, args: args, params: p }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// ── failure / return shells ─────────────────────────────────────────────────────────────────────
|
|
259
|
+
function next(kind, extra) { return Object.assign({ kind: kind }, extra || {}) }
|
|
260
|
+
function fail(code, engine, message, extra) {
|
|
261
|
+
const out = { ok: false, op: null, engine: engine || null, code: code, message: message }
|
|
262
|
+
if (extra && extra.next) out.next = extra.next
|
|
263
|
+
if (extra && extra.argv) out.argv = extra.argv
|
|
264
|
+
if (extra && extra.receipt) out.receipt = extra.receipt
|
|
265
|
+
if (extra && extra.missing) out.missing = extra.missing
|
|
266
|
+
if (extra && extra.engines) out.engines = extra.engines
|
|
267
|
+
if (extra && extra.available !== undefined) out.available = extra.available
|
|
268
|
+
if (extra && extra.packages) out.packages = extra.packages
|
|
269
|
+
return out
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function userInstallNext(engine) {
|
|
273
|
+
const d = MATH_ENGINES[engine] || {}
|
|
274
|
+
const per = d.userInstall || {}
|
|
275
|
+
const platform = process && process.platform === 'win32' ? 'windows' : (process && process.platform === 'darwin' ? 'macos' : 'linux')
|
|
276
|
+
return next('user-install', { engine: engine, perOs: per, command: per[platform] || '', platform: platform })
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// ── host adaptation ─────────────────────────────────────────────────────────────────────────────
|
|
280
|
+
function adaptHost(host) {
|
|
281
|
+
const h = host || {}
|
|
282
|
+
if (h.__mathAdapted) return h.__mathAdapted
|
|
283
|
+
const need = ['register', 'projectRoot', 'writeText', 'readText', 'exists', 'resolveExecutable', 'spawn']
|
|
284
|
+
for (const k of need) if (typeof h[k] !== 'function') throw new Error('math_computation: host.' + k + ' is required')
|
|
285
|
+
const adapted = {
|
|
286
|
+
register: h.register,
|
|
287
|
+
params: typeof h.params === 'function' ? h.params : function () { return h.params || {} },
|
|
288
|
+
projectRoot: h.projectRoot,
|
|
289
|
+
designator: typeof h.designator === 'string' && h.designator ? h.designator : 'vibe-math',
|
|
290
|
+
writeText: h.writeText,
|
|
291
|
+
readText: h.readText,
|
|
292
|
+
exists: h.exists,
|
|
293
|
+
resolveExecutable: h.resolveExecutable,
|
|
294
|
+
spawn: h.spawn,
|
|
295
|
+
hasSubprocess: typeof h.hasSubprocess === 'function' ? h.hasSubprocess : null,
|
|
296
|
+
listDir: typeof h.listDir === 'function' ? h.listDir : null,
|
|
297
|
+
log: typeof h.log === 'function' ? h.log : function () {},
|
|
298
|
+
}
|
|
299
|
+
adapted.__mathHost = true
|
|
300
|
+
try { h.__mathAdapted = adapted } catch (e) { /* frozen host object: the caller can still pass the adapted one */ }
|
|
301
|
+
return adapted
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
const PROBE_CACHE = new WeakMap()
|
|
305
|
+
|
|
306
|
+
export async function probeMathEngines(host, opts) {
|
|
307
|
+
const H = adaptHost(host)
|
|
308
|
+
const params = effectiveMathParams(typeof H.params === 'function' ? H.params() : H.params)
|
|
309
|
+
const refresh = !!(opts && opts.refresh)
|
|
310
|
+
const cached = PROBE_CACHE.get(H)
|
|
311
|
+
if (cached && !refresh) return cached
|
|
312
|
+
const engines = []
|
|
313
|
+
for (const name of params.mathEngines) {
|
|
314
|
+
const d = MATH_ENGINES[name]
|
|
315
|
+
if (!d) continue
|
|
316
|
+
if (name === 'cli') continue // cli needs a caller-supplied command, so it is not auto-detected
|
|
317
|
+
const hit = await resolveCandidate(H, d)
|
|
318
|
+
if (!hit) continue
|
|
319
|
+
const v = await probeVersion(H, d, hit)
|
|
320
|
+
if (!v.ok) {
|
|
321
|
+
if (d.license === 'commercial') continue // installed but not usable: reported by op=run as LICENSE_REQUIRED
|
|
322
|
+
continue
|
|
323
|
+
}
|
|
324
|
+
engines.push({ name: name, version: v.version, path: hit, license: d.license })
|
|
325
|
+
}
|
|
326
|
+
const result = { ok: true, engines: engines, available: engines.length > 0 }
|
|
327
|
+
PROBE_CACHE.set(H, result)
|
|
328
|
+
return result
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
async function resolveCandidate(H, d) {
|
|
332
|
+
const cands = mathEngineCandidates(d.name)
|
|
333
|
+
if (!cands) return null
|
|
334
|
+
for (const c of cands) {
|
|
335
|
+
try {
|
|
336
|
+
const p = await H.resolveExecutable(c)
|
|
337
|
+
if (typeof p === 'string' && p) return p
|
|
338
|
+
} catch (e) { /* not this one */ }
|
|
339
|
+
}
|
|
340
|
+
return null
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async function probeVersion(H, d, exe) {
|
|
344
|
+
const r = await H.spawn({ argv: [exe].concat(d.versionArgv || []), cwd: await H.projectRoot(), timeoutMs: 5000, stdoutCap: 8192, stderrCap: 8192 })
|
|
345
|
+
if (!r || r.timedOut) return { ok: false }
|
|
346
|
+
const m = new RegExp(d.versionRe).exec(String(r.stdout || '') + '\n' + String(r.stderr || ''))
|
|
347
|
+
return { ok: r.exit === 0 && !!m, version: m ? m[1] : 'unknown' }
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
async function checkLicence(H, d, exe) {
|
|
351
|
+
if (d.license !== 'commercial') return { ok: true }
|
|
352
|
+
if (!d.licenseProbe) return { ok: false }
|
|
353
|
+
const r = await H.spawn({ argv: [exe].concat(d.licenseProbe.argv), cwd: await H.projectRoot(), timeoutMs: 10000, stdoutCap: 8192, stderrCap: 8192 })
|
|
354
|
+
if (!r || r.timedOut || r.exit !== 0) return { ok: false }
|
|
355
|
+
if (d.licenseProbe.okWhen === 'trim-1') return { ok: String(r.stdout || '').trim() === '1' }
|
|
356
|
+
if (d.licenseProbe.okWhen === 'not-unlicensed') return { ok: !/Unlicensed/i.test(String(r.stdout || '')) }
|
|
357
|
+
return { ok: true }
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
async function resolveEngine(H, requested, params, args) {
|
|
361
|
+
const names = requested === 'auto' ? params.mathEngines.slice() : [requested]
|
|
362
|
+
for (const name of names) {
|
|
363
|
+
const d0 = MATH_ENGINES[name]
|
|
364
|
+
if (!d0) continue
|
|
365
|
+
// AUDIT-B FIX (HIGH): the override must also reach the VERSION probe and the licence probe, not
|
|
366
|
+
// just the script/eval argv - the BAD_ARGV hint advertises versionArgv explicitly.
|
|
367
|
+
const d = applyOverride({ name: name, desc: d0 }, params, args)
|
|
368
|
+
if (params.mathEngines.indexOf(name) === -1) return fail('MATH_REFUSED', name, '引擎 ' + name + ' 不在 mathEngines 允许列表内', { next: next('reason', { reason: 'engine-not-allowed' }) })
|
|
369
|
+
if (name === 'cli') {
|
|
370
|
+
if (params.mathMode !== 'typed+shell') return fail('MATH_REFUSED', name, 'cli 被策略禁用(mathMode=' + params.mathMode + ')', { next: next('reason', { reason: 'policy' }) })
|
|
371
|
+
let exe = null
|
|
372
|
+
try { exe = await H.resolveExecutable(args.cli.command) } catch (e) { exe = null }
|
|
373
|
+
if (!exe) return fail('MATH_ENGINE_NOT_FOUND', name, 'cli 命令无法解析:' + args.cli.command, { next: userInstallNext('cli') })
|
|
374
|
+
return { ok: true, name: name, desc: d, exe: exe, version: 'unknown' }
|
|
375
|
+
}
|
|
376
|
+
const hit = await resolveCandidate(H, d)
|
|
377
|
+
if (!hit) continue
|
|
378
|
+
const v = await probeVersion(H, d, hit)
|
|
379
|
+
if (!v.ok) {
|
|
380
|
+
if (d.license === 'commercial' || d.versionOptional) {
|
|
381
|
+
const lic = await checkLicence(H, d, hit)
|
|
382
|
+
if (!lic.ok) return fail('MATH_ENGINE_LICENSE_REQUIRED', name, name + ' 已安装但许可不可用(仅厂商可激活)', { next: next('vendor', { engine: name, url: d.vendor || '' }) })
|
|
383
|
+
return { ok: true, name: name, desc: d, exe: hit, version: 'unknown' }
|
|
384
|
+
}
|
|
385
|
+
return fail('MATH_ENGINE_UNUSABLE', name, name + ' 存在但不可用(版本探针失败)', { next: userInstallNext(name) })
|
|
386
|
+
}
|
|
387
|
+
const lic = await checkLicence(H, d, hit)
|
|
388
|
+
if (!lic.ok) return fail('MATH_ENGINE_LICENSE_REQUIRED', name, name + ' 已安装但许可不可用(仅厂商可激活)', { next: next('vendor', { engine: name, url: d.vendor || '' }) })
|
|
389
|
+
return { ok: true, name: name, desc: d, exe: hit, version: v.version }
|
|
390
|
+
}
|
|
391
|
+
const first = requested === 'auto' ? (params.mathEngines[0] || 'python') : requested
|
|
392
|
+
return fail('MATH_ENGINE_NOT_FOUND', first, '本机没有可用的计算引擎(试过:' + names.join(', ') + ')', { next: userInstallNext(first) })
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// ── package probe ───────────────────────────────────────────────────────────────────────────────
|
|
396
|
+
function buildProbeArgv(d, pkgs) {
|
|
397
|
+
const quoted = pkgs.map((p) => '"' + String(p).replace(/"/g, '') + '"').join(',')
|
|
398
|
+
const plain = pkgs.join(',')
|
|
399
|
+
const code = String(d.probeCode || '').replace(/__QPKGS__/g, quoted).replace(/__PKGS__/g, plain)
|
|
400
|
+
return (d.packageProbe.argv || []).map((a) => a === '<probeCode>' ? code : a === '<pkgs>' ? plain : a)
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
async function probePackages(H, det, pkgs) {
|
|
404
|
+
const found = {}
|
|
405
|
+
for (const p of pkgs) found[p] = null
|
|
406
|
+
if (!pkgs.length || !det.desc.packageProbe) return { requested: pkgs.slice(), found: found }
|
|
407
|
+
const r = await H.spawn({ argv: [det.exe].concat(buildProbeArgv(det.desc, pkgs)), cwd: await H.projectRoot(), timeoutMs: 15000, stdoutCap: 16384, stderrCap: 16384 })
|
|
408
|
+
if (r && !r.timedOut) {
|
|
409
|
+
if (det.desc.packageProbe.parse === 'lines') {
|
|
410
|
+
const text = String(r.stdout || '')
|
|
411
|
+
for (const p of pkgs) if (new RegExp('(^|\\s)' + p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(\\s|$)', 'm').test(text)) found[p] = 'present'
|
|
412
|
+
} else {
|
|
413
|
+
for (const tok of String(r.stdout || '').split('|')) {
|
|
414
|
+
const idx = tok.indexOf(':')
|
|
415
|
+
if (idx <= 0) continue
|
|
416
|
+
const name = tok.slice(0, idx).trim()
|
|
417
|
+
const state = tok.slice(idx + 1).trim()
|
|
418
|
+
if (Object.prototype.hasOwnProperty.call(found, name)) found[name] = (state === 'ok' || state === '1' || state === 'TRUE' || state === 'True') ? 'present' : null
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return { requested: pkgs.slice(), found: found }
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// ── argv assembly ───────────────────────────────────────────────────────────────────────────────
|
|
426
|
+
function assembleArgv(det, mode, payload) {
|
|
427
|
+
const d = det.desc
|
|
428
|
+
if (det.name === 'cli') {
|
|
429
|
+
const cliArgv = (payload.cli && Array.isArray(payload.cli.argv)) ? payload.cli.argv : []
|
|
430
|
+
return { argv: [det.exe].concat(cliArgv), cli: { command: payload.cli.command, argv: cliArgv } }
|
|
431
|
+
}
|
|
432
|
+
if (mode === 'code' || mode === 'file') {
|
|
433
|
+
return { argv: [det.exe].concat((d.scriptArgv || []).map((a) => a === '<script>' ? payload.scriptAbs : a)) }
|
|
434
|
+
}
|
|
435
|
+
if (mode === 'expr') {
|
|
436
|
+
if (!d.evalArgv) return { refused: 'engine does not support mode=expr' }
|
|
437
|
+
return { argv: [det.exe].concat(d.evalArgv.map((a) => a === '<expr>' ? payload.expr : a)) }
|
|
438
|
+
}
|
|
439
|
+
return { refused: 'unknown mode' }
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// AUDIT-B FIX (HIGH): `applyOverride` used to read only `params.mathEngineOverride`, which no preset
|
|
443
|
+
// can ever set (the six frozen params are copied verbatim by effectiveMathParams), while the tool
|
|
444
|
+
// description, MATH_BAD_ARGV_HINT and the BAD_ARGV message all advertised it. The per-call ARGUMENT
|
|
445
|
+
// now wins and is the documented route; the param route stays as a fallback for hosts that inject it.
|
|
446
|
+
function applyOverride(det, params, args) {
|
|
447
|
+
const d = det.desc
|
|
448
|
+
const fromArgs = args && isObj(args.mathEngineOverride) ? args.mathEngineOverride : null
|
|
449
|
+
const ov = fromArgs || (params && params.mathEngineOverride)
|
|
450
|
+
const o = ov && isObj(ov) ? ov[det.name] : null
|
|
451
|
+
if (!o) return d
|
|
452
|
+
return Object.assign({}, d, {
|
|
453
|
+
versionArgv: Array.isArray(o.versionArgv) ? o.versionArgv.slice() : d.versionArgv,
|
|
454
|
+
scriptArgv: Array.isArray(o.scriptArgv) ? o.scriptArgv.slice() : d.scriptArgv,
|
|
455
|
+
evalArgv: Array.isArray(o.evalArgv) ? o.evalArgv.slice() : d.evalArgv,
|
|
456
|
+
packageProbe: isObj(o.packageProbe) ? o.packageProbe : d.packageProbe,
|
|
457
|
+
})
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// ── receipt ────────────────────────────────────────────────────────────────────────────────────
|
|
461
|
+
function runIdOf(designator, projectSlug, engine, mode, scriptText, packages, fileRel) {
|
|
462
|
+
// P2a: mode:'file' is keyed by the SOURCE PATH, not by its content, so that editing the file and
|
|
463
|
+
// re-running lands in the same archive id - which is what makes the hash reconciliation below
|
|
464
|
+
// meaningful. mode:'code'/'expr' have no path, so their content stays the key.
|
|
465
|
+
const key = (mode === 'file' && fileRel) ? ('file:' + fileRel) : canonical(scriptText)
|
|
466
|
+
const input = sha256([engine, mode, key, packages.slice().sort().join(',')].join('\n'))
|
|
467
|
+
return { runId: designator + '-' + projectSlug + '-' + input.slice(0, 12), input: input }
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
// P2a item 3: append-only archives. Attempt 1 lives in Computation/<id>/ and is never rewritten;
|
|
471
|
+
// later runs of the same id go to Computation/<id>/attempts/<n>/ (first free n >= 2).
|
|
472
|
+
//
|
|
473
|
+
// AUDIT-C FIX (HIGH): `exists`-then-write is a read-modify-write race. Two concurrent runs of the
|
|
474
|
+
// SAME archive id both observed "no receipt.json yet", both took attempt 1, and the second silently
|
|
475
|
+
// overwrote the first receipt/script - so the append-only guarantee did not hold exactly when two
|
|
476
|
+
// members ran the same computation at once. Allocation (and the receipt write that claims the slot)
|
|
477
|
+
// now runs under a per-archive-id in-process mutex, so two calls through one plugin instance can
|
|
478
|
+
// never share an attempt dir. Cross-process concurrency still needs an exclusive-create primitive
|
|
479
|
+
// from the host (documented in docs/math-computation.md §6).
|
|
480
|
+
const mathArchiveChains = new Map()
|
|
481
|
+
function withArchiveLock(key, fn) {
|
|
482
|
+
const prev = mathArchiveChains.get(key) || Promise.resolve()
|
|
483
|
+
const run = prev.then(fn, fn)
|
|
484
|
+
const tail = run.then(() => {}, () => {})
|
|
485
|
+
mathArchiveChains.set(key, tail)
|
|
486
|
+
tail.then(() => { if (mathArchiveChains.get(key) === tail) mathArchiveChains.delete(key) })
|
|
487
|
+
return run
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
async function nextAttempt(H, baseDir) {
|
|
491
|
+
const hasFirst = await H.exists(baseDir + '/receipt.json')
|
|
492
|
+
if (!hasFirst) return { attempt: 1, dir: baseDir }
|
|
493
|
+
let n = 2
|
|
494
|
+
while (n < 10000) {
|
|
495
|
+
const d = baseDir + '/attempts/' + n
|
|
496
|
+
if (!(await H.exists(d + '/receipt.json'))) return { attempt: n, dir: d }
|
|
497
|
+
n++
|
|
498
|
+
}
|
|
499
|
+
return { attempt: n, dir: baseDir + '/attempts/' + n }
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
async function previousReceiptOf(H, baseDir, attempt) {
|
|
503
|
+
if (attempt > 2) {
|
|
504
|
+
const prev = await H.readText(baseDir + '/attempts/' + (attempt - 1) + '/receipt.json')
|
|
505
|
+
if (prev !== undefined) { try { return JSON.parse(prev) } catch (e) { /* fall through */ } }
|
|
506
|
+
}
|
|
507
|
+
const first = await H.readText(baseDir + '/receipt.json')
|
|
508
|
+
if (first !== undefined) { try { return JSON.parse(first) } catch (e) { /* ignore */ } }
|
|
509
|
+
return null
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function warning(code, message) { return { code: code, message: message } }
|
|
513
|
+
|
|
514
|
+
async function retentionWarnings(H, baseDir, attempt) {
|
|
515
|
+
const out = []
|
|
516
|
+
if (attempt > MATH_ARCHIVE_MAX_ATTEMPTS_PER_RUN) {
|
|
517
|
+
out.push(warning(MATH_ARCHIVE_WARNING, 'Computation/ 归档的 attempt 数已超过上限 ' + MATH_ARCHIVE_MAX_ATTEMPTS_PER_RUN + '(本次为第 ' + attempt + ' 次);工具只告警、绝不自动删除,请人工整理旧 attempt。'))
|
|
518
|
+
}
|
|
519
|
+
if (typeof H.listDir === 'function' && H.listDir) {
|
|
520
|
+
try {
|
|
521
|
+
const entries = await H.listDir('Computation')
|
|
522
|
+
const runs = (entries || []).filter((e) => e && e.type === 'directory').length
|
|
523
|
+
if (runs > MATH_ARCHIVE_MAX_RUNS) out.push(warning(MATH_ARCHIVE_WARNING, 'Computation/ 下的 run 目录数(' + runs + ')已超过上限 ' + MATH_ARCHIVE_MAX_RUNS + ';工具只告警、绝不自动删除。'))
|
|
524
|
+
} catch (e) { /* best effort */ }
|
|
525
|
+
}
|
|
526
|
+
return out
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function renderReceiptMd(r, fullOut, fullErr) {
|
|
530
|
+
const lines = []
|
|
531
|
+
lines.push('# 计算回执|' + r.preset + ' · ' + r.project + '|' + r.runId + (r.attempt && r.attempt > 1 ? '(attempt ' + r.attempt + ')' : ''))
|
|
532
|
+
lines.push('')
|
|
533
|
+
lines.push('- 引擎:' + r.engine.name + ' ' + r.engine.version + '(source=' + r.engine.source + ',path=' + r.engine.path + ')')
|
|
534
|
+
lines.push('- 模式:' + r.mode + '|cwd:' + r.cwd + '|attempt:' + (r.attempt || 1) + '(归档目录 ' + (r.attemptDir || '') + ',同 id 的首次归档 ' + (r.baseRunDir || '') + ')')
|
|
535
|
+
lines.push('- 命令(照抄可复跑):' + r.argv.join(' '))
|
|
536
|
+
lines.push('- 结果:exit=' + r.exit + '|耗时 ' + r.ms + 'ms|超时=' + r.timedOut + '|输出截断 ' + r.truncated.stdout + '/' + r.truncated.stderr)
|
|
537
|
+
lines.push('- 脚本:' + (r.scriptPath || r.script.path) + '|scriptHash=sha256:' + String(r.scriptHash || r.script.sha256) + '(' + r.script.bytes + ' bytes)')
|
|
538
|
+
if (r.sourceFile) {
|
|
539
|
+
lines.push('- 源文件:' + r.sourceFile + '(运行前 sha256:' + String(r.sourceHashBefore || '').slice(0, 16) + '…,运行后 sha256:' + String(r.sourceHashAfter || '').slice(0, 16) + '…)')
|
|
540
|
+
lines.push('- 哈希核对:scriptChanged=' + !!r.scriptChanged + '|scriptChangedDuringRun=' + !!r.scriptChangedDuringRun
|
|
541
|
+
+ (r.previousReceipt ? '(上一份回执 attempt ' + (r.previousReceipt.attempt || 1) + ' 记的 scriptHash 为 ' + String(r.previousReceipt.scriptHash || '').slice(0, 16) + '…)' : '(没有更早的回执)'))
|
|
542
|
+
if (r.scriptChanged) lines.push(' ▸ **旧回执不代表当前代码**:引用证据时必须用 scriptHash 与当前文件一致的那份回执。')
|
|
543
|
+
if (r.scriptChangedDuringRun) lines.push(' ▸ **本次运行期间文件被改动**:请重跑并引用重跑后的回执。')
|
|
544
|
+
}
|
|
545
|
+
const missing = Object.keys(r.packages.found).filter((k) => !r.packages.found[k])
|
|
546
|
+
lines.push('- 包:' + (Object.keys(r.packages.found).length ? Object.keys(r.packages.found).map((k) => k + '=' + (r.packages.found[k] || '未找到')).join('、') : '(未请求)') + (missing.length ? '|缺失:' + missing.join(',') : ''))
|
|
547
|
+
lines.push('- 网络:**未由插件强制**(subprocess.spawn 无 policy 槽)')
|
|
548
|
+
lines.push('- 复现:math_computation { op:\'run\', engine:\'' + r.engine.name + '\', mode:\'file\', file:\'' + (r.scriptPath || r.script.path) + '\' }')
|
|
549
|
+
for (const w of (r.warnings || [])) lines.push('- ⚠ [' + w.code + '] ' + w.message)
|
|
550
|
+
lines.push('')
|
|
551
|
+
lines.push('## 输出摘要(stdout,共 ' + String(fullOut || '').split('\n').length + ' 行)')
|
|
552
|
+
lines.push(String(fullOut || '').split('\n').slice(0, 20).join('\n'))
|
|
553
|
+
if (fullErr) { lines.push(''); lines.push('## stderr(前 10 行)'); lines.push(String(fullErr).split('\n').slice(0, 10).join('\n')) }
|
|
554
|
+
lines.push('')
|
|
555
|
+
lines.push('> 本回执是**经验证据**,不是数学证明;对象是否"已验证"仍由该预设既有的验证/共识路径给出。')
|
|
556
|
+
return lines.join('\n') + '\n'
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// ── op: probe ──────────────────────────────────────────────────────────────────────────────────
|
|
560
|
+
async function opProbe(H, args, params) {
|
|
561
|
+
const probe = await probeMathEngines(H, { refresh: !!(args.packages && args.packages.indexOf('refresh') !== -1) })
|
|
562
|
+
const pkgs = (args.packages || []).filter((p) => p !== 'refresh')
|
|
563
|
+
const want = pkgs.length ? pkgs : params.mathPackages
|
|
564
|
+
let packages = { requested: want.slice(), found: {} }
|
|
565
|
+
if (want.length && probe.engines.length) {
|
|
566
|
+
const det = await resolveEngine(H, args.engine && args.engine !== 'auto' ? args.engine : probe.engines[0].name, params, args)
|
|
567
|
+
if (det.ok) packages = await probePackages(H, det, want)
|
|
568
|
+
}
|
|
569
|
+
if (!probe.available) {
|
|
570
|
+
const first = params.mathEngines[0] || 'python'
|
|
571
|
+
const out = fail('MATH_ENGINE_NOT_FOUND', first, '本机没有可用的计算引擎', { next: userInstallNext(first), engines: [], available: false, packages: packages })
|
|
572
|
+
out.op = 'probe'
|
|
573
|
+
return out
|
|
574
|
+
}
|
|
575
|
+
return { ok: true, op: 'probe', engine: null, engines: probe.engines, available: true, packages: packages, message: '可用引擎:' + probe.engines.map((e) => e.name + ' ' + e.version).join('、') }
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// ── op: run ─────────────────────────────────────────────────────────────────────────────────────
|
|
579
|
+
async function opRun(H, args, params) {
|
|
580
|
+
const mode = args.mode
|
|
581
|
+
const det = await resolveEngine(H, args.engine || 'auto', params, args)
|
|
582
|
+
if (!det.ok) return det
|
|
583
|
+
const desc = applyOverride(det, params, args)
|
|
584
|
+
const det2 = { ok: true, name: det.name, desc: desc, exe: det.exe, version: det.version }
|
|
585
|
+
// The generic escape hatch is recorded as `cli:<command>` (spec §4.3 / guards §18): the model and
|
|
586
|
+
// the receipt must be able to tell WHICH command was run, not just that it was "cli".
|
|
587
|
+
const cliCommand = args.cli && typeof args.cli.command === 'string' ? args.cli.command : ''
|
|
588
|
+
const engineLabel = det.name === 'cli' ? ('cli:' + cliCommand) : det.name
|
|
589
|
+
|
|
590
|
+
const want = (args.packages && args.packages.length) ? args.packages : params.mathPackages
|
|
591
|
+
const pk = await probePackages(H, det2, want)
|
|
592
|
+
const missing = want.filter((p) => Object.prototype.hasOwnProperty.call(pk.found, p) && !pk.found[p])
|
|
593
|
+
if (missing.length) {
|
|
594
|
+
return fail('MATH_MISSING_PACKAGES', det.name, '需要的包未安装:' + missing.join(', '), {
|
|
595
|
+
missing: missing,
|
|
596
|
+
next: next('agent-install', { engine: det.name, packages: missing, dryRun: true }),
|
|
597
|
+
packages: pk,
|
|
598
|
+
})
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
const root = await H.projectRoot()
|
|
602
|
+
let scriptText = ''
|
|
603
|
+
let fileRel = null
|
|
604
|
+
let sourceHashBefore = null
|
|
605
|
+
if (mode === 'code') scriptText = args.code
|
|
606
|
+
else if (mode === 'file') {
|
|
607
|
+
fileRel = projectRel('', args.file)
|
|
608
|
+
if (fileRel === null) return fail('MATH_REFUSED', det.name, 'file 必须位于项目内:' + args.file, { next: next('reason', { reason: 'path-outside-project' }) })
|
|
609
|
+
const txt = await H.readText(fileRel)
|
|
610
|
+
if (txt === undefined) return fail('MATH_REFUSED', det.name, '找不到文件:' + args.file, { next: next('reason', { reason: 'file-not-found' }) })
|
|
611
|
+
scriptText = txt
|
|
612
|
+
sourceHashBefore = sha256(txt)
|
|
613
|
+
} else scriptText = (args.expr || '') + '\n'
|
|
614
|
+
|
|
615
|
+
const { runId, input } = runIdOf(H.designator, slug(root), det.name, mode, scriptText, want, fileRel)
|
|
616
|
+
const baseDir = 'Computation/' + runId
|
|
617
|
+
// P2a item 3 + AUDIT-C FIX (HIGH): the whole claim-and-archive section for one archive id is
|
|
618
|
+
// serialised. Allocation, the script/stdout/stderr writes and receipt.json (which claims the slot)
|
|
619
|
+
// must not interleave with another run of the same id, or both take attempt 1 and one is lost.
|
|
620
|
+
return await withArchiveLock(baseDir, async () => {
|
|
621
|
+
const slot = await nextAttempt(H, baseDir)
|
|
622
|
+
const dir = slot.dir
|
|
623
|
+
const attempt = slot.attempt
|
|
624
|
+
const prevReceipt = await previousReceiptOf(H, baseDir, attempt)
|
|
625
|
+
const scriptRel = dir + '/script' + (det.name === 'cli' ? '.txt' : desc.ext)
|
|
626
|
+
const scriptAbs = absJoin(root, scriptRel)
|
|
627
|
+
const scriptHash = sha256(scriptText)
|
|
628
|
+
// P2a item 2: reconciliation against the previous receipt for the same archive id (mode:'file' is
|
|
629
|
+
// path-keyed, so this is exactly "the file changed since that receipt").
|
|
630
|
+
const scriptChanged = !!(mode === 'file' && prevReceipt && prevReceipt.scriptHash && prevReceipt.scriptHash !== scriptHash)
|
|
631
|
+
const wrote = await H.writeText(scriptRel, scriptText)
|
|
632
|
+
if (wrote === false) return fail('MATH_INVALID_ARGUMENT', det.name, '无法写入 ' + scriptRel)
|
|
633
|
+
|
|
634
|
+
const assembled = assembleArgv(det2, mode, {
|
|
635
|
+
scriptAbs: scriptAbs,
|
|
636
|
+
expr: args.expr,
|
|
637
|
+
cli: args.cli,
|
|
638
|
+
})
|
|
639
|
+
if (assembled.refused) return fail('MATH_REFUSED', det.name, assembled.refused, { next: next('reason', { reason: 'mode-not-supported' }) })
|
|
640
|
+
|
|
641
|
+
const timeoutMs = args.timeoutMs || params.mathTimeoutMs
|
|
642
|
+
const r = await H.spawn({ argv: assembled.argv, cwd: root, timeoutMs: timeoutMs, stdoutCap: MATH_CAPS.file, stderrCap: MATH_CAPS.file })
|
|
643
|
+
// P2a item 2/4: hash the SOURCE again after the run. A member editing the file while this run was
|
|
644
|
+
// in flight shows up here (and never silently).
|
|
645
|
+
let sourceHashAfter = null
|
|
646
|
+
let scriptChangedDuringRun = false
|
|
647
|
+
if (mode === 'file' && fileRel) {
|
|
648
|
+
const after = await H.readText(fileRel)
|
|
649
|
+
sourceHashAfter = after === undefined ? null : sha256(after)
|
|
650
|
+
// AUDIT-A FIX: a null post-run hash means the source DISAPPEARED during the run - that is a
|
|
651
|
+
// change, not "no change". Comparing null-safe (null !== beforeHash) keeps it fail-closed.
|
|
652
|
+
scriptChangedDuringRun = sourceHashAfter !== sourceHashBefore
|
|
653
|
+
}
|
|
654
|
+
if (!r) return fail('MATH_NO_SUBPROCESS', det.name, '宿主不提供 subprocess 服务,无法执行计算', { next: next('note', { reason: 'no-subprocess' }) })
|
|
655
|
+
|
|
656
|
+
const fullOut = String(r.stdout || '')
|
|
657
|
+
const fullErr = String(r.stderr || '')
|
|
658
|
+
await H.writeText(dir + '/stdout.txt', fullOut)
|
|
659
|
+
await H.writeText(dir + '/stderr.txt', fullErr)
|
|
660
|
+
|
|
661
|
+
const captured = []
|
|
662
|
+
for (const cf of (args.captureFiles || [])) {
|
|
663
|
+
const rel = projectRel('', cf)
|
|
664
|
+
if (rel === null) continue
|
|
665
|
+
const txt = await H.readText(rel)
|
|
666
|
+
if (txt === undefined) continue
|
|
667
|
+
const dest = dir + '/captured/' + rel
|
|
668
|
+
if (await H.writeText(dest, txt) !== false) captured.push(rel)
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
const warnings = []
|
|
672
|
+
if (fullOut.length > MATH_CAPS.stdout) warnings.push(warning('OUTPUT_TRUNCATED', 'stdout 超过 64KB,完整版见 ' + dir + '/stdout.txt'))
|
|
673
|
+
if (scriptChanged) warnings.push(warning(MATH_SCRIPT_CHANGED_WARNING, 'scriptChanged:文件 ' + fileRel + ' 自上一次回执以来已改变(旧回执不再代表当前代码),本次已写出新 attempt ' + attempt + '。'))
|
|
674
|
+
if (scriptChangedDuringRun) warnings.push(warning(MATH_SCRIPT_CHANGED_DURING_RUN_WARNING, 'scriptChangedDuringRun:文件 ' + fileRel + ' 在本次运行期间被改动(可能有另一个成员在编辑);本次回执的 scriptHash 是运行前版本 ' + String(sourceHashBefore).slice(0, 12) + '…,请重跑后再引用。'))
|
|
675
|
+
for (const w of await retentionWarnings(H, baseDir, attempt)) warnings.push(w)
|
|
676
|
+
|
|
677
|
+
const receipt = {
|
|
678
|
+
schema: 'vibe-math/math-computation-receipt@1',
|
|
679
|
+
runId: runId, preset: H.designator, project: slug(root), op: 'run', mode: mode,
|
|
680
|
+
attempt: attempt, attemptDir: dir, baseRunDir: baseDir,
|
|
681
|
+
engine: { name: engineLabel, path: det.exe, version: det.version, source: det.name === 'cli' ? 'cli' : 'path' },
|
|
682
|
+
script: { path: scriptRel, sha256: scriptHash, bytes: Buffer.byteLength(scriptText, 'utf8') },
|
|
683
|
+
scriptPath: scriptRel, scriptHash: scriptHash,
|
|
684
|
+
sourceFile: fileRel || null,
|
|
685
|
+
sourceHashBefore: sourceHashBefore, sourceHashAfter: sourceHashAfter,
|
|
686
|
+
scriptChanged: scriptChanged, scriptChangedDuringRun: scriptChangedDuringRun,
|
|
687
|
+
previousReceipt: prevReceipt ? { runId: prevReceipt.runId, attempt: prevReceipt.attempt || 1, scriptHash: prevReceipt.scriptHash || (prevReceipt.script && prevReceipt.script.sha256) || null } : null,
|
|
688
|
+
argv: assembled.argv.slice(),
|
|
689
|
+
cwd: root,
|
|
690
|
+
packages: { requested: want.slice(), found: pk.found },
|
|
691
|
+
exit: r.timedOut ? null : (r.exit === undefined ? null : r.exit),
|
|
692
|
+
timedOut: !!r.timedOut,
|
|
693
|
+
ms: Number(r.ms || 0),
|
|
694
|
+
truncated: { stdout: fullOut.length > MATH_CAPS.stdout, stderr: fullErr.length > MATH_CAPS.stderr },
|
|
695
|
+
artifacts: [{ path: 'stdout.txt', sha256: sha256(fullOut), bytes: Buffer.byteLength(fullOut, 'utf8') }],
|
|
696
|
+
captured: captured,
|
|
697
|
+
network: 'not-enforced-by-plugin',
|
|
698
|
+
warnings: warnings,
|
|
699
|
+
determinism: { inputSha256: input, packagesSorted: true, noWallClockInId: true },
|
|
700
|
+
}
|
|
701
|
+
if (assembled.cli) receipt.cli = { command: assembled.cli.command, argv: assembled.cli.argv, stdinUsed: false }
|
|
702
|
+
const receiptJson = JSON.stringify(receipt, null, 2)
|
|
703
|
+
await H.writeText(dir + '/receipt.json', receiptJson)
|
|
704
|
+
await H.writeText(dir + '/receipt.md', renderReceiptMd(receipt, fullOut, fullErr))
|
|
705
|
+
const receiptRef = { dir: dir, json: dir + '/receipt.json', md: dir + '/receipt.md', sha256: sha256(receiptJson) }
|
|
706
|
+
H.log('math_computation', det.name + ' ' + (det.name === 'cli' ? 'cli' : mode) + ' attempt=' + attempt + ' exit=' + receipt.exit + ' argv=' + assembled.argv.join(' '))
|
|
707
|
+
|
|
708
|
+
const shell = {
|
|
709
|
+
ok: true, op: 'run', engine: engineLabel, mode: mode,
|
|
710
|
+
engineInfo: receipt.engine,
|
|
711
|
+
argv: assembled.argv.slice(),
|
|
712
|
+
scriptPath: scriptRel, scriptHash: scriptHash,
|
|
713
|
+
attempt: attempt, attemptDir: dir, baseRunDir: baseDir,
|
|
714
|
+
scriptChanged: scriptChanged, scriptChangedDuringRun: scriptChangedDuringRun,
|
|
715
|
+
sourceFile: fileRel || null,
|
|
716
|
+
previousReceipt: receipt.previousReceipt,
|
|
717
|
+
packages: pk.found,
|
|
718
|
+
exit: receipt.exit, timedOut: receipt.timedOut, ms: receipt.ms,
|
|
719
|
+
stdout: fullOut.slice(0, MATH_CAPS.stdout), stderr: fullErr.slice(0, MATH_CAPS.stderr),
|
|
720
|
+
truncated: receipt.truncated, artifacts: receipt.artifacts, receipt: receiptRef,
|
|
721
|
+
warnings: warnings,
|
|
722
|
+
}
|
|
723
|
+
if (receipt.timedOut) {
|
|
724
|
+
return Object.assign(fail('MATH_TIMEOUT', engineLabel, '执行超时(' + timeoutMs + 'ms)已被终止', { argv: assembled.argv.slice(), receipt: receiptRef }),
|
|
725
|
+
archiveFields(), { ms: receipt.ms, timedOut: true })
|
|
726
|
+
}
|
|
727
|
+
if (r.exit !== 0) {
|
|
728
|
+
const blob = fullErr + '\n' + fullOut
|
|
729
|
+
const hints = mathEngineArgErrorHints(det.name)
|
|
730
|
+
const looksLikeArgError = hints.some((h) => blob.toLowerCase().indexOf(String(h).toLowerCase()) !== -1)
|
|
731
|
+
if (looksLikeArgError) {
|
|
732
|
+
const out = fail('MATH_ENGINE_BAD_ARGV', engineLabel, engineLabel + ' 以选项/用法错误退出(argv=' + assembled.argv.join(' ') + ')。模板可能与本机版本不符:请用 mathEngineOverride 覆盖 versionArgv/scriptArgv/evalArgv。', {
|
|
733
|
+
argv: assembled.argv.slice(),
|
|
734
|
+
receipt: receiptRef,
|
|
735
|
+
next: next('engine-override', { engine: det.name, argv: assembled.argv.slice(), hint: MATH_BAD_ARGV_HINT }),
|
|
736
|
+
})
|
|
737
|
+
out.exit = r.exit
|
|
738
|
+
out.stderr = fullErr.slice(0, MATH_CAPS.stderr)
|
|
739
|
+
return Object.assign(out, archiveFields())
|
|
740
|
+
}
|
|
741
|
+
const out = fail('MATH_NONZERO_EXIT', engineLabel, '引擎以非零退出码结束:' + r.exit, { argv: assembled.argv.slice(), receipt: receiptRef })
|
|
742
|
+
out.exit = r.exit
|
|
743
|
+
out.stderr = fullErr.slice(0, MATH_CAPS.stderr)
|
|
744
|
+
return Object.assign(out, archiveFields())
|
|
745
|
+
}
|
|
746
|
+
return shell
|
|
747
|
+
|
|
748
|
+
function archiveFields() {
|
|
749
|
+
return {
|
|
750
|
+
scriptPath: scriptRel, scriptHash: scriptHash,
|
|
751
|
+
attempt: attempt, attemptDir: dir, baseRunDir: baseDir,
|
|
752
|
+
scriptChanged: scriptChanged, scriptChangedDuringRun: scriptChangedDuringRun,
|
|
753
|
+
sourceFile: fileRel || null, previousReceipt: receipt.previousReceipt, warnings: warnings,
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
}) // end withArchiveLock(baseDir) — see the AUDIT-C HIGH fix above
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
// ── op: receipt ────────────────────────────────────────────────────────────────────────────────
|
|
760
|
+
// P2a item 2: reconciliation. Read the receipt, re-hash the script it points at, and report
|
|
761
|
+
// scriptChanged. P2a item 3: receipt files are NEVER rewritten - only a MISSING receipt.md is
|
|
762
|
+
// filled in (that is the one documented exception, and it is not a rewrite of existing data).
|
|
763
|
+
async function opReceipt(H, args) {
|
|
764
|
+
const raw = String(args.file || '').replace(/\\/g, '/').replace(/^\.\//, '')
|
|
765
|
+
const segs = raw.split('/').filter(Boolean)
|
|
766
|
+
let runId = ''
|
|
767
|
+
let attemptDir = null
|
|
768
|
+
if (segs[0] === 'Computation') {
|
|
769
|
+
runId = segs[1] || ''
|
|
770
|
+
if (segs[2] === 'attempts' && segs[3]) attemptDir = 'Computation/' + runId + '/attempts/' + segs[3]
|
|
771
|
+
} else {
|
|
772
|
+
runId = segs[0] || ''
|
|
773
|
+
}
|
|
774
|
+
if (!runId) return fail('MATH_INVALID_ARGUMENT', null, 'op=receipt requires a receipt id or path')
|
|
775
|
+
const tried = attemptDir ? [attemptDir, 'Computation/' + runId] : ['Computation/' + runId]
|
|
776
|
+
let dir = null
|
|
777
|
+
let json
|
|
778
|
+
for (const d of tried) {
|
|
779
|
+
json = await H.readText(d + '/receipt.json')
|
|
780
|
+
if (json !== undefined) { dir = d; break }
|
|
781
|
+
}
|
|
782
|
+
// Round-2 lens-1 fix: a MISSING archive directory is a refusal with an explicit reason (a
|
|
783
|
+
// fail-closed state, not a malformed call). A receipt whose JSON cannot be parsed stays
|
|
784
|
+
// MATH_INVALID_ARGUMENT (that IS a malformed artifact).
|
|
785
|
+
if (json === undefined) return fail('MATH_REFUSED', null, '没有找到回执归档:Computation/' + runId + '(目录或 receipt.json 不存在)', { next: next('reason', { reason: 'archive-missing' }) })
|
|
786
|
+
let parsed
|
|
787
|
+
try { parsed = JSON.parse(json) } catch (e) { return fail('MATH_INVALID_ARGUMENT', null, '回执无法解析:' + dir, { next: next('reason', { reason: 'receipt-unparsable' }) }) }
|
|
788
|
+
const recordedHash = parsed.scriptHash || (parsed.script && parsed.script.sha256) || null
|
|
789
|
+
const scriptRel = parsed.scriptPath || (parsed.script && parsed.script.path) || (dir + '/script')
|
|
790
|
+
const currentText = await H.readText(scriptRel)
|
|
791
|
+
const currentHash = currentText === undefined ? null : sha256(currentText)
|
|
792
|
+
// AUDIT-A FIX: a missing archive script is not "unchanged". Reconciliation is fail-closed: if the
|
|
793
|
+
// script cannot be read, the receipt cannot be trusted for any code, so report scriptChanged.
|
|
794
|
+
const scriptMissing = currentText === undefined
|
|
795
|
+
const scriptChanged = scriptMissing || (currentHash !== null && recordedHash !== null && currentHash !== recordedHash)
|
|
796
|
+
const warnings = []
|
|
797
|
+
if (scriptMissing) {
|
|
798
|
+
warnings.push(warning(MATH_SCRIPT_CHANGED_WARNING, 'scriptChanged:归档脚本 ' + scriptRel + ' 已不存在(被删除或移动)——**该回执不能作为任何代码的证据**,请重跑。'))
|
|
799
|
+
} else if (scriptChanged) {
|
|
800
|
+
warnings.push(warning(MATH_SCRIPT_CHANGED_WARNING, 'scriptChanged:归档脚本 ' + scriptRel + ' 的当前哈希与回执记录不一致——**这份回执不再代表当前代码**,请用 mode:\'file\' 重跑并引用新回执。'))
|
|
801
|
+
}
|
|
802
|
+
const mdRel = dir + '/receipt.md'
|
|
803
|
+
let rendered = false
|
|
804
|
+
if (!(await H.exists(mdRel))) {
|
|
805
|
+
const out = await H.readText(dir + '/stdout.txt')
|
|
806
|
+
const err = await H.readText(dir + '/stderr.txt')
|
|
807
|
+
await H.writeText(mdRel, renderReceiptMd(parsed, out || '', err || ''))
|
|
808
|
+
rendered = true
|
|
809
|
+
}
|
|
810
|
+
return {
|
|
811
|
+
ok: true, op: 'receipt', engine: parsed.engine ? parsed.engine.name : null,
|
|
812
|
+
scriptPath: scriptRel, scriptHash: recordedHash, currentScriptHash: currentHash,
|
|
813
|
+
scriptChanged: scriptChanged, attempt: parsed.attempt || 1, attemptDir: dir,
|
|
814
|
+
receipt: { dir: dir, json: dir + '/receipt.json', md: mdRel },
|
|
815
|
+
warnings: warnings,
|
|
816
|
+
message: (scriptChanged ? '⚠ 归档脚本已改变:旧回执不再代表当前代码;' : '') + (rendered ? '缺失的 receipt.md 已补写(未改写既有数据)' : '回执只读返回(既有文件未改写)'),
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
// ── op: install ────────────────────────────────────────────────────────────────────────────────
|
|
821
|
+
function substInstall(tmpl, engineName, exe, pkg) {
|
|
822
|
+
return tmpl.map((a) => String(a).replace(/<exe>/g, exe).replace(/<pkg>/g, pkg).replace(/__PKG__/g, pkg))
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
async function opInstall(H, args, params) {
|
|
826
|
+
const engineName = (args.engine && args.engine !== 'auto') ? args.engine : (params.mathEngines[0] || 'python')
|
|
827
|
+
const d = MATH_ENGINES[engineName]
|
|
828
|
+
if (!d) return fail('MATH_INVALID_ARGUMENT', engineName, 'unknown engine: ' + engineName)
|
|
829
|
+
if (d.license === 'commercial' || !d.install) {
|
|
830
|
+
return fail('MATH_REFUSED', engineName, engineName + ' 永不代装(商业引擎只给厂商指引)', {
|
|
831
|
+
next: next('vendor', { engine: engineName, url: d.vendor || '' }),
|
|
832
|
+
})
|
|
833
|
+
}
|
|
834
|
+
const scope = args.scope || params.mathInstallScope || 'user' // per-call only; never persisted anywhere
|
|
835
|
+
const tmpl = scope === 'system' ? d.install.systemArgv : d.install.userArgv
|
|
836
|
+
if (!tmpl) return fail('MATH_REFUSED', engineName, engineName + ' 不支持 system 作用域(只提供用户级安装)', { next: next('reason', { reason: 'system-scope-unsupported' }) })
|
|
837
|
+
let exe = engineName
|
|
838
|
+
try { exe = (await H.resolveExecutable(engineName === 'r' ? 'Rscript' : engineName)) || engineName } catch (e) { exe = engineName }
|
|
839
|
+
const commands = args.packages.map((p) => ({ argv: substInstall(tmpl, engineName, exe, p), why: '缺少 ' + p }))
|
|
840
|
+
const plan = { engine: engineName, scope: scope, manager: d.install.manager, commands: commands, note: scope === 'user' ? '将安装到用户级目录' : '仅本次系统作用域(不会被记住)' }
|
|
841
|
+
const planToken = sha256(JSON.stringify({ engine: engineName, packages: args.packages, scope: scope, commands: commands }) + '|planVersion=1').slice(0, 32)
|
|
842
|
+
if (!args.confirm) {
|
|
843
|
+
return { ok: true, op: 'install', engine: engineName, plan: plan, planToken: planToken, next: next('agent-install', { dryRun: true }), message: '安装计划(尚未执行):' + commands.map((c) => c.argv.join(' ')).join(' ; ') }
|
|
844
|
+
}
|
|
845
|
+
if (args.confirm !== planToken) {
|
|
846
|
+
return fail('MATH_REFUSED', engineName, 'planToken 不匹配(计划可能已变),请重新出计划', { next: next('reason', { reason: 'plan-token-mismatch' }) })
|
|
847
|
+
}
|
|
848
|
+
const timeoutMs = args.timeoutMs || params.mathTimeoutMs
|
|
849
|
+
const results = []
|
|
850
|
+
for (const c of commands) {
|
|
851
|
+
const r = await H.spawn({ argv: c.argv, cwd: await H.projectRoot(), timeoutMs: timeoutMs, stdoutCap: MATH_CAPS.file, stderrCap: MATH_CAPS.file })
|
|
852
|
+
results.push({ argv: c.argv, exit: r ? r.exit : null, timedOut: !!(r && r.timedOut), ms: r ? r.ms : 0, stdoutTail: String((r && r.stdout) || '').slice(-2000), stderrTail: String((r && r.stderr) || '').slice(-2000) })
|
|
853
|
+
if (!r || r.timedOut || r.exit !== 0) {
|
|
854
|
+
const audit0 = { schema: 'vibe-math/math-computation-install@1', planToken: planToken, scope: scope, manager: d.install.manager, commands: commands, results: results, exit: r ? r.exit : null, timedOut: !!(r && r.timedOut), installed: args.packages, rollback: rollbackFor(d, exe, args.packages), network: 'not-enforced-by-plugin' }
|
|
855
|
+
await H.writeText('Computation/installs/' + planToken + '.json', JSON.stringify(audit0, null, 2))
|
|
856
|
+
const code = (r && r.timedOut) ? 'MATH_TIMEOUT' : 'MATH_NONZERO_EXIT'
|
|
857
|
+
const out = fail(code, engineName, '安装失败(' + c.argv.join(' ') + '):' + (r ? ('exit=' + r.exit) : 'no subprocess'), { next: next('note', { audit: 'Computation/installs/' + planToken + '.json' }) })
|
|
858
|
+
out.audit = 'Computation/installs/' + planToken + '.json'
|
|
859
|
+
return out
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
const audit = { schema: 'vibe-math/math-computation-install@1', planToken: planToken, scope: scope, manager: d.install.manager, commands: commands, results: results, exit: 0, timedOut: false, installed: args.packages, before: {}, after: {}, rollback: rollbackFor(d, exe, args.packages), network: 'not-enforced-by-plugin' }
|
|
863
|
+
await H.writeText('Computation/installs/' + planToken + '.json', JSON.stringify(audit, null, 2))
|
|
864
|
+
return { ok: true, op: 'install', engine: engineName, executed: true, scope: scope, audit: 'Computation/installs/' + planToken + '.json', message: '已安装:' + args.packages.join(', ') + '(审计:Computation/installs/' + planToken + '.json)' }
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function rollbackFor(d, exe, packages) {
|
|
868
|
+
const tmpl = d.install && d.install.uninstallArgv
|
|
869
|
+
if (!tmpl) return { supported: 'partial', commands: [], note: '该管理器未提供卸载模板;本工具不做自动回滚' }
|
|
870
|
+
return { supported: 'partial', commands: packages.map((p) => substInstall(tmpl, d.name, exe, p)), note: '包管理器各自支持卸载;本工具不做自动回滚' }
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
// ── dispatch + registration ────────────────────────────────────────────────────────────────────
|
|
874
|
+
async function dispatch(H, rawArgs) {
|
|
875
|
+
const params = effectiveMathParams(typeof H.params === 'function' ? H.params() : H.params)
|
|
876
|
+
if (params.mathComputation === 'off') {
|
|
877
|
+
return fail('MATH_NOT_AVAILABLE', null, '该预设已关闭数学计算(mathComputation=off)', { next: next('enable', { param: 'mathComputation', value: 'auto' }) })
|
|
878
|
+
}
|
|
879
|
+
// Optional host capability flag: a host that KNOWS it has no subprocess service can say so, and
|
|
880
|
+
// then "no engine resolvable" is reported as MATH_NO_SUBPROCESS instead of a misleading
|
|
881
|
+
// ENGINE_NOT_FOUND + "install python" guide. Hosts that do not provide the flag keep the
|
|
882
|
+
// resolve-throw => ENGINE_NOT_FOUND / spawn-null => MATH_NO_SUBPROCESS mapping.
|
|
883
|
+
if (typeof H.hasSubprocess === 'function' && H.hasSubprocess() === false) {
|
|
884
|
+
const out = fail('MATH_NO_SUBPROCESS', null, '宿主不提供 subprocess 服务,无法执行计算', { next: next('note', { reason: 'no-subprocess' }) })
|
|
885
|
+
out.op = isObj(rawArgs) ? (rawArgs.op || null) : null
|
|
886
|
+
return out
|
|
887
|
+
}
|
|
888
|
+
const v = validateMathArgs(rawArgs, params)
|
|
889
|
+
if (!v.ok) {
|
|
890
|
+
const out = fail(v.code, null, v.reason)
|
|
891
|
+
if (v.next) out.next = v.next
|
|
892
|
+
out.op = isObj(rawArgs) ? (rawArgs.op || null) : null
|
|
893
|
+
return out
|
|
894
|
+
}
|
|
895
|
+
const args = v.args
|
|
896
|
+
if (args.op === 'probe') { const out = await opProbe(H, args, params); out.op = 'probe'; return out }
|
|
897
|
+
if (args.op === 'run') { const out = await opRun(H, args, params); if (out && out.op === null) out.op = 'run'; return out }
|
|
898
|
+
if (args.op === 'receipt') { const out = await opReceipt(H, args); out.op = 'receipt'; return out }
|
|
899
|
+
const out = await opInstall(H, args, params)
|
|
900
|
+
if (out && out.op === null) out.op = 'install'
|
|
901
|
+
return out
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
export function registerMathComputation(host) {
|
|
905
|
+
const H = adaptHost(host)
|
|
906
|
+
H.__mathHost = true
|
|
907
|
+
const handler = async function (args) {
|
|
908
|
+
try {
|
|
909
|
+
return await dispatch(H, args)
|
|
910
|
+
} catch (e) {
|
|
911
|
+
return fail('MATH_INVALID_ARGUMENT', null, 'math_computation 内部错误:' + String((e && e.message) || e))
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
H.register(MATH_TOOL_NAME, MATH_TOOL_DESCRIPTION, MATH_TOOL_SCHEMA, handler)
|
|
915
|
+
const probe = async function (opts) {
|
|
916
|
+
const h = await probeMathEngines(H, opts)
|
|
917
|
+
return h
|
|
918
|
+
}
|
|
919
|
+
return { toolName: MATH_TOOL_NAME, description: MATH_TOOL_DESCRIPTION, parameters: MATH_TOOL_SCHEMA, handler: handler, probe: probe, host: H }
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
export function mathAvailabilityLine(probe, lang, mathMode) {
|
|
923
|
+
const mode = mathMode || MATH_PARAM_DEFAULTS.mathMode
|
|
924
|
+
const list = (probe && probe.engines ? probe.engines : []).map((e) => e.name + ' ' + (e.version || '?')).join('、')
|
|
925
|
+
if (lang === 'en') {
|
|
926
|
+
const head = '- math_computation: available ' + (list || '(none)') + '. Probe first, then run'
|
|
927
|
+
+ ' (the tool path leaves a re-runnable receipt - cite it). If a package is missing, say so and offer a fallback or an install plan;'
|
|
928
|
+
+ ' installing requires a plan plus confirmation.'
|
|
929
|
+
const shell = mode === 'typed+shell' ? '\n' + MATH_SHELL_RULE_LINE_EN : ''
|
|
930
|
+
return head + shell + '\n' + MATH_ARCHIVE_WORKFLOW_LINE_EN + '\n' + MATH_RULE_LINES_EN.join('\n')
|
|
931
|
+
}
|
|
932
|
+
const head = '- math_computation:本机可用 ' + (list || '(无)') + '。需要数值/符号/统计计算时先 probe 再 run'
|
|
933
|
+
+ '(工具路径会留下可复核回执,结论请引用回执路径);缺包时如实说明并给替代方案或安装计划(不要假装),安装需先出计划并征得确认。'
|
|
934
|
+
const shell = mode === 'typed+shell' ? '\n' + MATH_SHELL_RULE_LINE : ''
|
|
935
|
+
return head + shell + '\n' + MATH_ARCHIVE_WORKFLOW_LINE + '\n' + MATH_RULE_LINES.join('\n')
|
|
936
|
+
}
|