agentworkshop 0.9.1 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,821 +1,827 @@
1
- #!/usr/bin/env node
2
- /* eslint-disable @stylistic/max-statements-per-line */
3
- /**
4
- * 模型层闭环真机 E2E(2026-10-24)—— 三层模型的「创建→使用→迭代进化」全链。
5
- *
6
- * 目标:验证 Agent 经工具面真正控制/迭代模型(不止参数优化),人类作为管理者
7
- * 查看/修正,Agent 在持续迭代中把新模型反馈进求解器(模型进化闭环)。
8
- *
9
- * M0 hybrid_twin 全功能频道(训练面+孪生面+优化器面同面注入)+ Agent 节点绑定 + 过程 spec
10
- * M1 本体层:起草→批准→发布 v1;管理者修正规则窗→v2(人类按意愿修正模型)
11
- * M2 孪生层(虚拟模型创建,全经 Agent 工具):场景发现→SceneContract 编译→冻结(人批准)
12
- * →PhysicsSpec 骨架→校验→编译候选→频道谱系重链→真采快照→虚拟试验(recommendation-only)
13
- * M3 模型进化第 1 轮:训练 A → Profile v1(A)+发布+绑定 → 基线求解 → 训练 B →
14
- * optimizer_profile_propose(工具)→ HITL 批准 → 发布 v2+自动重绑 → 新模型 solve optimal
15
- * M4 模型进化第 2 轮:训练 C → 再采纳 → v3+重绑 → solve optimal(持续进化证据+零设备写入)
16
- * M5 管理者面 REST:本体版本/四段 diff、Profile 版本、孪生谱系、审计三态留痕
17
- * M6 前端渲染走查(管理者查看:/optimizer /aml /ontology)
18
- *
19
- * 运行:node scripts/e2e-model-loop-live.mjs
20
- * 证据:docs/audit/evidence/2026-10-24-model-loop-live/{report.json,*.png}
21
- */
22
- import { spawn } from 'node:child_process'
23
- import { mkdirSync, writeFileSync, existsSync, symlinkSync, openSync, readFileSync } from 'node:fs'
24
- import { join, resolve, dirname } from 'node:path'
25
- import { fileURLToPath } from 'node:url'
26
- import { tmpdir, homedir } from 'node:os'
27
- import { DatabaseSync } from 'node:sqlite'
28
-
29
- const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '..')
30
- const ROOT = join(tmpdir(), `aw-model-loop-live-${Date.now()}`)
31
- const HOME = join(ROOT, 'home')
32
- const EVID = resolve(process.env.AW_E2E_EVIDENCE_DIR || join(REPO, 'docs', 'audit', 'evidence', '2026-10-24-model-loop-live'))
33
- mkdirSync(HOME, { recursive: true })
34
- mkdirSync(EVID, { recursive: true })
35
-
36
- const TAG = `mlp${Date.now().toString(36).slice(-4)}`
37
- const BEAT = 5000
38
- const H = 24
39
- const F = 6
40
- const N_STEPS = 160
41
- const N_RUNS = 6
42
- const DELAY_STEPS = 2
43
-
44
- process.env.AW_MODE = 'home'
45
- process.env.AW_HOME = HOME
46
- process.env.AW_AML_DIR = join(HOME, 'aml')
47
- process.env.NO_PROXY = '127.0.0.1,localhost'
48
-
49
- mkdirSync(join(HOME, 'aml'), { recursive: true })
50
- const realVenv = join(homedir(), '.AgentWorkShop', 'aml', '.venv')
51
- let venvLinked = false
52
- if (existsSync(join(realVenv, 'Scripts', 'python.exe'))) {
53
- symlinkSync(realVenv, join(HOME, 'aml', '.venv'), 'junction')
54
- venvLinked = true
55
- }
56
-
57
- const results = []
58
- function check(id, name, cond, detail = '') {
59
- const pass = Boolean(cond)
60
- results.push({ id, name, pass, detail: String(detail).slice(0, 600) })
61
- console.log(`${pass ? '✔' : '✘'} [${id}] ${name}${detail ? ` — ${String(detail).slice(0, 200)}` : ''}`)
62
- return pass
63
- }
64
- const sleep = ms => new Promise(r => setTimeout(r, ms))
65
- function killTree(pid) {
66
- try {
67
- spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore' })
68
- }
69
- catch { /* 进程已退 */ }
70
- }
71
-
72
- const { getDcwLineRepo } = await import('../server/services/workshop/dcw/dcw-line.repo')
73
- const { getDcwProductRepo } = await import('../server/services/workshop/dcw/dcw-product.repo')
74
- const { getDcwRecipeRepo } = await import('../server/services/workshop/dcw/dcw-recipe.repo')
75
- const { getDcwNodeRepo } = await import('../server/services/workshop/dcw/dcw-node.repo')
76
- const { DcwNode } = await import('../server/services/workshop/dcw/dcw-node')
77
- const { getDaqNodeRepo } = await import('../server/services/workshop/daq/daq-node.repo')
78
- const { DaqNode } = await import('../server/services/workshop/daq/daq-node')
79
- const { SqliteTimeSeriesAdapter } = await import('../server/services/workshop/daq/storage/sqlite.adapter')
80
- const { getContextSegmentRepo, recipeContentHash } = await import('../server/services/workshop/process-model/context-segments.repo')
81
- const { openWorkshopDb } = await import('../server/services/workshop/db/database/open')
82
- const { configureAmlRuntime } = await import('../server/services/workshop/aml/runtime')
83
- const { bindOpsRepos } = await import('../server/services/workshop/ops/ops')
84
- const { createAuditRepo } = await import('../server/services/workshop/db/ops.repo')
85
-
86
- const seedDb = openWorkshopDb(join(HOME, 'data', 'workshop.sqlite'))
87
- configureAmlRuntime(seedDb)
88
- try {
89
- bindOpsRepos({ audit: createAuditRepo(seedDb) })
90
- }
91
- catch { /* 重复装配无害 */ }
92
-
93
- const line = getDcwLineRepo().create({ name: `模型闭环验收线-${TAG}`, simulated: true })
94
- const product = getDcwProductRepo().create({ name: `模型闭环验收产品-${TAG}`, lineId: line.id })
95
- getDcwNodeRepo().insert(new DcwNode({
96
- id: `dcw-${TAG}-press`, templateRef: 'dcw-temp-sp', driver: 'mock',
97
- name: `熔体压力控制-${TAG}`, lineId: line.id, min: 0, max: 100, unit: 'bar',
98
- }))
99
- getDcwNodeRepo().insert(new DcwNode({
100
- id: `dcw-${TAG}-speed`, templateRef: 'dcw-temp-sp', driver: 'mock',
101
- name: `线速度控制-${TAG}`, lineId: line.id, min: 0, max: 50, unit: 'm/min',
102
- }))
103
- const DCW_PRESS = `dcw-${TAG}-press`
104
- const DCW_SPEED = `dcw-${TAG}-speed`
105
- for (const id of [DCW_PRESS, DCW_SPEED]) {
106
- const node = getDcwNodeRepo().byId(id)
107
- if (node) {
108
- node.readValue = id === DCW_PRESS ? 50 : 10
109
- getDcwNodeRepo().flushNow()
110
- }
111
- }
112
- getDaqNodeRepo().insert(DaqNode.fromRow({
113
- id: `dn-${TAG}-mv`, templateRef: 'tpl-loop-mv', name: `熔体压力-${TAG}`, unit: 'bar',
114
- min: 0, max: 100, lineId: line.id, driver: 'mock',
115
- }))
116
- getDaqNodeRepo().insert(DaqNode.fromRow({
117
- id: `dn-${TAG}-cv`, templateRef: 'tpl-loop-cv', name: `膜厚度-${TAG}`, unit: 'μm',
118
- min: 0, max: 200, lineId: line.id, driver: 'mock',
119
- }))
120
- getDaqNodeRepo().insert(DaqNode.fromRow({
121
- id: `dn-${TAG}-temp`, templateRef: 'tpl-loop-temp', name: `温区温度-${TAG}`, unit: '℃',
122
- min: 0, max: 400, lineId: line.id, driver: 'mock',
123
- }))
124
- const MV_ID = `dn-${TAG}-mv`
125
- const CV_ID = `dn-${TAG}-cv`
126
- const TEMP_ID = `dn-${TAG}-temp`
127
- const recipe = getDcwRecipeRepo().create({
128
- name: `模型闭环验收配方-${TAG}`, productId: product.id,
129
- params: [
130
- { nodeId: DCW_PRESS, value: 50, min: 0, max: 100 },
131
- { nodeId: DCW_SPEED, value: 10, min: 0, max: 50 },
132
- ],
133
- daqWindows: [{ nodeId: MV_ID, min: 0, max: 100 }],
134
- })
135
-
136
- const now0 = Date.now()
137
- const runStartBase = now0 - 3 * 3600_000
138
- const sampleRows = []
139
- const segRepo = getContextSegmentRepo()
140
- const seedHash = recipeContentHash(recipe)
141
- for (let r = 0; r < N_RUNS; r++) {
142
- const start = runStartBase + r * (N_STEPS * BEAT + 120_000)
143
- const end = start + (N_STEPS - 1) * BEAT
144
- const run = getDcwRecipeRepo().createRun(recipe)
145
- run.startedAt = new Date(start).toISOString()
146
- run.endedAt = new Date(end).toISOString()
147
- getDcwRecipeRepo().updateRun(run)
148
- segRepo.insert({ lineId: line.id, runId: run.id, fromTs: start, toTs: end, recipeId: recipe.id, recipeVersion: recipe.version ?? 1, recipeContentHash: seedHash, conditionId: 'c-live', source: 'line_run', confirmed: true })
149
- let y = 52
150
- const uq = []
151
- for (let k = 0; k < N_STEPS; k++) {
152
- const u = 50 + 20 * Math.sin((k + r * 11) / 9) + 6 * Math.sin((k + r * 3) / 4)
153
- uq.push(u)
154
- const delayed = uq[Math.max(0, uq.length - 1 - DELAY_STEPS)]
155
- y = 0.3 * y + 0.7 * delayed + 8 + 0.02 * Math.sin((k + r) / 3)
156
- const ts = start + k * BEAT
157
- const tags = { lineId: line.id, productId: product.id, recipeId: recipe.id, runId: run.id }
158
- sampleRows.push({ nodeId: MV_ID, tsMs: ts, value: u, state: 'ok', ...tags })
159
- sampleRows.push({ nodeId: CV_ID, tsMs: ts, value: y, state: 'ok', ...tags })
160
- sampleRows.push({ nodeId: TEMP_ID, tsMs: ts, value: 190 + 8 * Math.sin((k + r) / 6), state: 'ok', ...tags })
161
- }
162
- }
163
- const seedTsdb = new SqliteTimeSeriesAdapter()
164
- await seedTsdb.init()
165
- await seedTsdb.writeSamples(sampleRows)
166
- await seedTsdb.close()
167
- console.log(`seed: line=${line.id} recipe=${recipe.id} runs=${N_RUNS} samples=${sampleRows.length}`)
168
- console.log(`venv: ${venvLinked ? 'junction ok' : '未复用(训练将失败,先检查)'}`)
169
- if (!venvLinked) console.warn('⚠ 未找到真实 python venv,训练轮会失败')
170
-
171
- function insertSamples(rows) {
172
- if (!rows.length) return
173
- const db = new DatabaseSync(join(HOME, 'data', 'daq-timeseries.sqlite'))
174
- db.exec('PRAGMA busy_timeout=8000')
175
- const ins = db.prepare(`INSERT OR IGNORE INTO daq_samples
176
- (node_id, ts_ms, value, state, line_id, product_id, recipe_id, run_id, ingested_at)
177
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
178
- db.exec('BEGIN')
179
- for (const r of rows) ins.run(r.nodeId, r.tsMs, r.value, r.state ?? 'ok', r.lineId ?? null, r.productId ?? null, r.recipeId ?? null, r.runId ?? null, r.ingestedAt ?? Date.now())
180
- db.exec('COMMIT')
181
- db.close()
182
- }
183
- function writeFreshTail() {
184
- // context 窗口 = H*beat + maxDelay + 5*beat;尾巴必须覆盖整窗,否则网格 NaN
185
- const now = Date.now()
186
- const rows = []
187
- const span = Math.ceil(H + DELAY_STEPS + 6)
188
- for (let k = span; k >= 1; k--) {
189
- const ts = now - k * BEAT
190
- const tags = { lineId: line.id, productId: product.id, recipeId: recipe.id }
191
- const mv = 50 + 6 * Math.sin(k / 5)
192
- rows.push({ nodeId: MV_ID, tsMs: ts, value: mv, state: 'ok', ...tags })
193
- rows.push({ nodeId: CV_ID, tsMs: ts, value: 50 + 0.7 * (mv - 50) + 0.05 * Math.sin(k / 3), state: 'ok', ...tags })
194
- rows.push({ nodeId: TEMP_ID, tsMs: ts, value: 195, state: 'ok', ...tags })
195
- }
196
- insertSamples(rows)
197
- }
198
-
199
- // ════ 启动隔离实例 ════
200
- // 强制 SQLite 时序(宿主 Timescale 在线时插件会切走,看不到预置样本);MQTT 指向关闭端口。
201
- const { saveSettings } = await import('../shared/config/engine.mjs')
202
- saveSettings({
203
- 'daq.timescale.host': '127.0.0.1',
204
- 'daq.timescale.port': 6543,
205
- 'daq.mqtt.host': '127.0.0.1',
206
- 'daq.mqtt.port': 18830,
207
- 'daq.startInfrastructure': 'never',
208
- }, join(HOME, 'runtime-settings.json'))
209
- let port = 0
210
- let BASE = ''
211
- let child = null
212
- let token = ''
213
- // 2026-10-29:固定低段(3993-3997)与并行会话/遗留实例撞车(实测:boot 打到别人实例 →
214
- // 注册 403/needsSetup=false)。改随机高端口 + boot 自愈重试:注册/fresh 校验不过就
215
- // 杀自己子进程换端口重来(最多 3 次),绝不与不明监听者抢端口。
216
- const candidates = Array.from({ length: 8 }, () => 34000 + Math.floor(Math.random() * 5900))
217
- const data = r => r?.data
218
- const errCode = r => r?.code ?? r?.data?.code ?? ''
219
- const email = `mlp-${TAG}@awshop.local`
220
- /** 本轮已试过的端口不再复用(失败后同端口重试只会撞自己正在拆除的旧实例) */
221
- const usedPorts = new Set()
222
-
223
- async function api(method, path, body, tok, timeoutMs = 180_000) {
224
- const res = await fetch(BASE + path, {
225
- method,
226
- headers: { 'content-type': 'application/json', ...(tok ? { authorization: `Bearer ${tok}` } : {}) },
227
- body: body === undefined ? undefined : JSON.stringify(body),
228
- signal: AbortSignal.timeout(timeoutMs),
229
- })
230
- let json = null
231
- try {
232
- json = await res.json()
233
- }
234
- catch { /* 非 JSON */ }
235
- return { status: res.status, ...(json ?? {}) }
236
- }
237
-
238
- async function pickPort() {
239
- const { execSync } = await import('node:child_process')
240
- for (const p of candidates) {
241
- if (usedPorts.has(p)) continue
242
- let occupied = false
243
- try {
244
- await fetch(`http://127.0.0.1:${p}/api/health`, { signal: AbortSignal.timeout(800) })
245
- occupied = true
246
- }
247
- catch { /* 健康探测失败不代表空闲 */ }
248
- if (!occupied) {
249
- // 健康探测失败但 netstat 有 LISTENING = 归属不明的活实例,跳过该端口
250
- let listening = false
251
- try {
252
- const out = execSync(`netstat -ano | findstr :${p} | findstr LISTENING`, { shell: 'cmd.exe' }).toString()
253
- listening = /\s\d+\s*$/m.test(out)
254
- }
255
- catch { /* 无监听 */ }
256
- if (listening) { occupied = true; await sleep(300) }
257
- }
258
- if (!occupied) { usedPorts.add(p); return p }
259
- await sleep(300)
260
- }
261
- return 0
262
- }
263
-
264
- /** 单次 boot:选端口→spawn→health→注册→fresh 校验;返回 {ok, stage, detail};失败已杀自己的子进程 */
265
- async function bootInstance() {
266
- port = await pickPort()
267
- if (!port) return { ok: false, stage: 'port', detail: '无空闲端口' }
268
- BASE = `http://127.0.0.1:${port}`
269
- console.log(`\n=== boot ${BASE} ===`)
270
- const logFd = openSync(join(ROOT, 'dev.log'), 'a')
271
- child = spawn(process.execPath, [join(REPO, 'bin', 'aw.mjs'), 'dev', '--port', String(port)], {
272
- cwd: REPO,
273
- env: { ...process.env, AW_RATE_LIMIT_OFF: '1', NUXT_SESSION_PASSWORD: 'ModelLoopLive#2026-e2e-session', NO_PROXY: '127.0.0.1,localhost' },
274
- stdio: ['ignore', logFd, logFd],
275
- windowsHide: true,
276
- })
277
- let healthy = false
278
- for (let i = 0; i < 120; i++) {
279
- await sleep(1500)
280
- try {
281
- const h = await api('GET', '/api/health', undefined, undefined, 3000)
282
- if (h?.data?.status === 'ok' && h?.data?.workshop === 'ready') { healthy = true; break }
283
- }
284
- catch { /* 未就绪 */ }
285
- }
286
- if (!healthy) { killTree(child.pid); return { ok: false, stage: 'health', detail: '实例未就绪:' + join(ROOT, 'dev.log') } }
287
- // 上面模块级 email = 管理员账号(冻结审批 approvedBy 同源)
288
- let reg = null
289
- for (let attempt = 0; attempt < 3 && !data(reg ?? {})?.token; attempt++) {
290
- try {
291
- reg = await api('POST', '/api/users/register', { name: `模型闭环验收-${TAG}`, email, password: 'ModelLoop#2026' })
292
- }
293
- catch (err) {
294
- console.log(`register attempt ${attempt + 1} failed: ${String(err).slice(0, 120)}`)
295
- await sleep(3000)
296
- }
297
- }
298
- token = data(reg ?? {})?.token ?? ''
299
- if (!token) { killTree(child.pid); return { ok: false, stage: 'register', detail: `注册失败 status=${reg?.status}` } }
300
- // fresh 绑定断言(2026-10-29 修正语义):首注册必须拿到 role=admin(bootstrap)。
301
- // 若端口被别会话实例抢答,要么 403(其注册闸已关),要么拿到 role=user —— 都在此拦截。
302
- const role = data(reg ?? {})?.user?.role
303
- if (role !== 'admin') {
304
- killTree(child.pid)
305
- return { ok: false, stage: 'fresh', detail: `首注册 role=${role ?? '?'}(非 admin=打到别会话实例)` }
306
- }
307
- return { ok: true, stage: 'ready', detail: `port=${port}` }
308
- }
309
-
310
- let boot = { ok: false, stage: 'not-run', detail: '' }
311
- for (let attempt = 1; attempt <= 3 && !boot.ok; attempt++) {
312
- boot = await bootInstance()
313
- if (!boot.ok && attempt < 3) { console.log(` · boot attempt ${attempt} 未独占(${boot.stage}),换端口重试`); await sleep(3000) }
314
- }
315
- check('BOOT', '隔离实例独占启动 + 注册首管理员 + fresh 校验', boot.ok, `${boot.stage}: ${boot.detail}`)
316
- if (!boot.ok) throw new Error(`隔离实例连续 3 次未能独占启动(${boot.stage})`)
317
-
318
- // ════ M0 hybrid_twin 全功能频道 + 绑定三面 ════
319
- console.log('\n=== M0 频道与三面绑定 ===')
320
- const ONT = `ont-${TAG}`
321
- const SPEC = `pms-${TAG}`
322
- const profileId = `optp-${TAG}`
323
- const SCENE_ID = `scn-${TAG}`
324
- let channelIdOuter
325
- let leadAgentIdOuter
326
- let workspaceIdOuter
327
- let bindingId
328
- let trainedAId
329
- let trainedBId
330
- let trainedCId
331
- let trainedAHash
332
- let trainedBHash
333
- let trainedCHash
334
- let spec
335
- {
336
- const inst = await api('POST', '/api/workshop/channel-templates/chtpl-hybrid-twin-mpc-default/instantiate', { name: `模型闭环频道-${TAG}`, bindLineId: line.id }, token)
337
- const instData = data(inst) ?? {}
338
- workspaceIdOuter = data(await api('POST', '/api/workshop/workspaces', { name: `模型闭环工作区-${TAG}` }, token))?.id
339
- channelIdOuter = instData.channelId
340
- leadAgentIdOuter = instData.leadAgentId ?? (instData.agents ?? []).find(a => a.role === 'lead')?.id
341
- if (workspaceIdOuter && channelIdOuter) await api('POST', `/api/workshop/workspaces/${encodeURIComponent(workspaceIdOuter)}/channels/${encodeURIComponent(channelIdOuter)}`, undefined, token)
342
- check('M0.1', 'hybrid_twin 频道实例化(全功能档位)+workspace', Boolean(workspaceIdOuter && channelIdOuter && leadAgentIdOuter), `inst=${inst.status} ch=${channelIdOuter} lead=${leadAgentIdOuter}`)
343
-
344
- // 工具面断言(进程内同判:scopeHostToolsForRole 与线上装配同一函数)
345
- try {
346
- const { scopeHostToolsForRole } = await import('../server/services/workshop/agents/host-tool-bridge/catalog')
347
- const scope = scopeHostToolsForRole('lead', channelIdOuter)
348
- const names = new Set(scope.tools.map(t => t.name))
349
- const need = ['twin_scene_discover', 'twin_scene_compile', 'twin_scene_freeze', 'twin_physics_spec_draft', 'twin_physics_spec_validate', 'twin_physics_spec_compile', 'twin_snapshot_create', 'twin_trial_run', 'aml_dataset_build', 'aml_job_submit', 'optimizer_solve', 'optimizer_profile_propose', 'ontology_draft_create']
350
- const missing = need.filter(n => !names.has(n))
351
- check('M0.2', 'hybrid 档位工具面:训练+孪生+优化器+本体四族同面注入', missing.length === 0, `missing=${missing.join(',')} total=${names.size}`)
352
- }
353
- catch (err) {
354
- check('M0.2', 'hybrid 档位工具面(进程内装配)', false, `err=${String(err).slice(0, 160)}`)
355
- }
356
-
357
- // Agent 节点绑定:daq 读面(MV/CV/TEMP)+ 配方面(参数写面 → 场景控制面)
358
- const bindNode = async (nodeId, kind) => api('POST', '/api/workshop/agent-tools/bindings', { agentId: leadAgentIdOuter, nodeId, kind }, token)
359
- const b1 = await bindNode(MV_ID, 'daq')
360
- const b2 = await bindNode(CV_ID, 'daq')
361
- const b3 = await bindNode(TEMP_ID, 'daq')
362
- const b4 = await bindNode(recipe.id, 'recipe')
363
- check('M0.3', 'Agent 节点绑定:daq×3 + recipe(参数面)', [b1, b2, b3, b4].every(x => x.status === 200), `daq=${[b1.status, b2.status, b3.status]} recipe=${b4.status}/${errCode(b4)}`)
364
-
365
- // 过程 spec 先登记发布(Profile 的 processSpecRef 谱系前置;Profile 本体在 M3 训练出模型后创建)
366
- spec = {
367
- schemaVersion: 2, id: SPEC, version: 1,
368
- lineId: line.id, productId: product.id, recipeId: recipe.id, recipeVersion: recipe.version ?? 1,
369
- conditions: [{ id: 'c1', match: [{ field: 'recipeId', op: 'eq', value: recipe.id }] }],
370
- variables: [
371
- { id: 'mv1', nodeId: MV_ID, role: 'mv', field: 'value', unit: 'bar', scale: 1, offset: 0, delayMs: DELAY_STEPS * BEAT, min: 0, max: 100, maxStep: 20, controlNodeId: DCW_PRESS },
372
- { id: 'cv1', nodeId: CV_ID, role: 'cv', field: 'value', unit: 'μm', scale: 1, offset: 0, min: 0, max: 200 },
373
- ],
374
- timing: { beatMs: BEAT, historySteps: H, horizonSteps: F, fixedDt: true },
375
- trainer: { ref: 'linear_arx@1', config: { arOrder: 1, inputOrder: 1, ridgeLambda: 1e-6, standardize: true } },
376
- datasetPolicy: { split: { valRatio: 0.4, testRatio: 0.4, seed: 42 }, cleaning: { hampelK: 0 } },
377
- gatePolicyRef: 'process-model.gates@1',
378
- modelInterface: { id: 'linear_state_space', version: 1, inputSemantics: 'setpoint', mode: 'state_space' },
379
- effectiveDomain: { mv: { mv1: { min: 0, max: 100, maxStep: 20 } }, cv: { cv1: { min: 0, max: 200 } } },
380
- purpose: 'mpc_surrogate',
381
- }
382
- const specCreated = await api('POST', '/api/workshop/process-model/specs', spec, token)
383
- const specPub = await api('POST', `/api/workshop/process-model/specs/${encodeURIComponent(SPEC)}/publish?version=1`, undefined, token)
384
- check('M0.4', '过程 spec 登记+发布(求解器谱系前置)', specCreated.status === 200 && specPub.status === 200, `create=${specCreated.status}/${errCode(specCreated)} pub=${specPub.status}`)
385
- }
386
-
387
- // ════ M1 本体层:v1 发布 → 管理者修正 → v2 ════
388
- console.log('\n=== M1 本体层(管理者修正路径) ===')
389
- let draftId
390
- const ontologyDoc = (overrides = {}) => ({
391
- schemaVersion: 1,
392
- name: `模型闭环验收-${TAG}`,
393
- description: `膜厚闭环控制本体:压力/线速→膜厚,温区守门(${TAG})`,
394
- lineId: line.id,
395
- entities: [
396
- { key: 'pv.melt_pressure', kind: 'process_variable', name: '熔体压力', description: '', unit: 'bar', dimension: 'pressure', role: 'control', attrs: { dataType: 'number' } },
397
- { key: 'cv.thickness', kind: 'quality_variable', name: '平均膜厚', description: '', unit: 'μm', dimension: 'length', role: 'target', attrs: { dataType: 'number' } },
398
- { key: 'st.line_speed', kind: 'process_variable', name: '线速度', description: '', unit: 'm/min', dimension: '', role: 'control', attrs: { dataType: 'number' } },
399
- { key: 'st.zone_temp', kind: 'process_variable', name: '温区温度', description: '', unit: '℃', dimension: 'temperature', role: 'state', attrs: { dataType: 'number' } },
400
- ],
401
- relations: [
402
- {
403
- id: 'rel-1', kind: 'influences', srcKey: 'pv.melt_pressure', dstKey: 'cv.thickness', status: 'validated',
404
- evidence: [{ id: 'ev-rel', level: 'validated_control', source: { type: 'optimizer_run', runId: 'run-live', problemIrHash: 'ir-live', modelArtifactHash: 'mdl-live' }, sourceRefHash: 'h', createdAt: new Date().toISOString() }],
405
- properties: { sign: 'negative', gainPerUnit: -0.4, lagMs: 2 * DELAY_STEPS * BEAT, evidenceTier: 'validated_control', variabilityChecked: true },
406
- },
407
- ],
408
- rules: [
409
- {
410
- id: 'R-BOUND', key: 'thickness-window', kind: 'bound',
411
- dsl: { type: 'bound', variableKey: 'cv.thickness', min: 45, max: 55, unit: 'μm' },
412
- constraintLevel: 'hard', severity: 'error', status: 'proposed',
413
- evidence: [{ id: 'ev-bound', level: 'validated_control', source: { type: 'optimizer_run', runId: 'run-b', problemIrHash: 'ir', modelArtifactHash: 'mdl' }, sourceRefHash: 'h', createdAt: new Date().toISOString() }],
414
- description: '膜厚工艺窗(μm)', scope: { lineId: line.id, recipeId: recipe.id, conditionId: '' },
415
- },
416
- {
417
- id: 'R-GUARD', key: 'cold-zone-no-speedup', kind: 'state_condition',
418
- dsl: { type: 'state_condition', when: { variableKey: 'st.zone_temp', op: 'lt', value: 180 }, forbid: { kind: 'positive_increment', variableKey: 'st.line_speed' }, message: '温区未达 180℃,禁止提速' },
419
- constraintLevel: 'hard', severity: 'error', status: 'proposed',
420
- evidence: [{ id: 'ev-guard', level: 'validated_control', source: { type: 'optimizer_run', runId: 'run-g', problemIrHash: 'ir', modelArtifactHash: 'mdl' }, sourceRefHash: 'h', createdAt: new Date().toISOString() }],
421
- description: '冷区禁提速', scope: { lineId: line.id, recipeId: recipe.id, conditionId: '' },
422
- },
423
- ],
424
- bindings: [
425
- { id: 'b-press', entityKey: 'pv.melt_pressure', platformKind: 'dcw_node', platformId: DCW_PRESS, targetSub: '', scope: `line:${line.id}`, direction: 'write', unitDeclared: 'bar', unitTarget: 'bar', scale: 1, offset: 0 },
426
- { id: 'b-speed', entityKey: 'st.line_speed', platformKind: 'dcw_node', platformId: DCW_SPEED, targetSub: '', scope: `line:${line.id}`, direction: 'write', unitDeclared: 'm/min', unitTarget: 'm/min', scale: 1, offset: 0 },
427
- { id: 'b-cv', entityKey: 'cv.thickness', platformKind: 'daq_node', platformId: CV_ID, targetSub: '', scope: `line:${line.id}`, direction: 'read', unitDeclared: 'μm', unitTarget: 'μm', scale: 1, offset: 0 },
428
- { id: 'b-temp', entityKey: 'st.zone_temp', platformKind: 'daq_node', platformId: TEMP_ID, targetSub: '', scope: `line:${line.id}`, direction: 'read', unitDeclared: '℃', unitTarget: '℃', scale: 1, offset: 0 },
429
- ],
430
- note: 'model-loop live e2e',
431
- ...overrides,
432
- })
433
- async function approveRule(draft, ruleId) {
434
- await api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draft)}/rules/${ruleId}/transition`, { to: 'reviewed' }, token)
435
- await api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draft)}/rules/${ruleId}/transition`, { to: 'validated' }, token)
436
- const ap = await api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draft)}/rules/${ruleId}/approval`, {}, token)
437
- const apId = data(ap)?.approvalId ?? ''
438
- await api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draft)}/rules/${ruleId}/approval-decision`, { approvalId: apId, approved: true }, token)
439
- return api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draft)}/rules/${ruleId}/transition`, { to: 'approved_for_control', approvalId: apId }, token)
440
- }
441
- {
442
- const created = await api('POST', '/api/workshop/ontology', { ontologyId: ONT, lineId: line.id, name: `模型闭环验收-${TAG}` }, token)
443
- draftId = data(created)?.draft?.id ?? ''
444
- const saved = await api('PATCH', `/api/workshop/ontology/drafts/${encodeURIComponent(draftId)}`, { doc: ontologyDoc(), expectedRev: 1 }, token)
445
- check('M1.1', '本体起草(活体校验+绑定通过)', created.status === 200 && saved.status === 200 && data(saved)?.validation?.ok === true, `saved=${saved.status} issues=${JSON.stringify((data(saved)?.validation?.issues ?? []).filter(i => i.severity === 'error').slice(0, 2))}`)
446
- const detail0 = data(await api('GET', `/api/workshop/ontology/drafts/${encodeURIComponent(draftId)}`, undefined, token))
447
- check('M1.1b', '本体描述可读(用户理解模型代表什么)', String(detail0?.doc?.description ?? '').includes('膜厚闭环控制本体'), String(detail0?.doc?.description ?? '').slice(0, 60))
448
- await approveRule(draftId, 'R-BOUND')
449
- await approveRule(draftId, 'R-GUARD')
450
- const pub1 = await api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draftId)}/publish`, {}, token)
451
- check('M1.2', '本体 v1 发布(contentHash+packHash)', pub1.status === 200 && data(pub1)?.version?.version === 1, `${pub1.status}/${errCode(pub1)}`)
452
-
453
- // 管理者修正:复用草稿(发布不改 rev,草稿仍可编辑;重复发布=新版本不可变语义),
454
- // 把膜厚窗从 [45,55] 收到 [46,54],重走生命周期后发布 v2
455
- const detail = data(await api('GET', `/api/workshop/ontology/drafts/${encodeURIComponent(draftId)}`, undefined, token))
456
- const curRev = detail?.draft?.rev ?? 2
457
- const doc2 = ontologyDoc()
458
- doc2.rules[0].dsl.min = 46
459
- doc2.rules[0].dsl.max = 54
460
- doc2.rules[0].description = '膜厚工艺窗(管理者修正:收窄到 46-54μm)'
461
- const saved2 = await api('PATCH', `/api/workshop/ontology/drafts/${encodeURIComponent(draftId)}`, { doc: doc2, expectedRev: curRev }, token)
462
- await approveRule(draftId, 'R-BOUND')
463
- await approveRule(draftId, 'R-GUARD')
464
- const pub2 = await api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draftId)}/publish`, {}, token)
465
- check('M1.3', '管理者修正规则窗 → v2 发布', pub2.status === 200 && data(pub2)?.version?.version === 2, `saved=${saved2.status}/${errCode(saved2)} pub=${pub2.status}/${errCode(pub2)}`)
466
- const messy = ontologyDoc()
467
- messy.description = ''
468
- for (const e of messy.entities) e.description = ''
469
- for (const r of messy.rules) { r.description = ''; r.scope.lineId = '' }
470
- for (const b of messy.bindings) b.scope = 'global'
471
- const createFix = await invokeTool('ontology_draft_create', { ontology_id: `${ONT}-fix`, line_id: line.id, name: `修复验收-${TAG}` })
472
- const createFixText = String(createFix?.data?.text ?? createFix?.data?.result?.text ?? createFix?.text ?? '')
473
- const draft3 = (createFixText.match(/已创建草稿\s+(\S+?)\(/) ?? [])[1] ?? ''
474
- const savedMessy = createFix ? await api('PATCH', `/api/workshop/ontology/drafts/${encodeURIComponent(draft3)}`, { doc: messy, expectedRev: 1 }, token) : { status: 0 }
475
- const fixRes = await invokeTool('ontology_draft_autofix', { draft_id: draft3 })
476
- const fixText = String(fixRes?.data?.text ?? fixRes?.data?.result?.text ?? fixRes?.text ?? JSON.stringify(fixRes ?? {}))
477
- const fixErr = Boolean(fixRes?.isError ?? fixRes?.data?.isError)
478
- check('M1.5', 'Agent 工具 ontology_draft_autofix:自动修复并落库', !fixErr && /自动修复 \d+ 项/.test(fixText), fixText.slice(0, 180))
479
- const detail3 = data(await api('GET', `/api/workshop/ontology/drafts/${encodeURIComponent(draft3)}`, undefined, token))
480
- check('M1.6', '修复后:描述/作用域已补齐且校验通过', Boolean(detail3?.doc?.description) && detail3?.validation?.ok === true && (detail3?.doc?.bindings ?? []).every(b => String(b.scope).startsWith('line:')), `desc=${String(detail3?.doc?.description ?? '').slice(0, 40)} savedMessy=${savedMessy.status}`)
481
- const cmp = await api('GET', `/api/workshop/ontology/versions/${encodeURIComponent(ONT)}/compare?from=1&to=2`, undefined, token)
482
- const changed = data(cmp)?.rules?.changed ?? []
483
- check('M1.4', '四段 diff 反映管理者意志(R-BOUND changed)', cmp.status === 200 && changed.some(c => String(typeof c === 'string' ? c : (c.id ?? c.ruleId ?? '')).includes('R-BOUND')), JSON.stringify(changed).slice(0, 200))
484
- }
485
-
486
- // ════ M2 孪生层:Agent 工具创建虚拟模型全链 ════
487
- console.log('\n=== M2 孪生层(Agent 工具创建虚拟模型) ===')
488
- async function invokeTool(tool, args, timeoutMs = 180_000) {
489
- return api('POST', '/api/workshop/agent-tools/invoke', { agentId: leadAgentIdOuter, tool, args }, token, timeoutMs)
490
- }
491
- const toolText = r => String(r?.data?.text ?? r?.data?.result?.text ?? r?.text ?? r?.message ?? JSON.stringify(r ?? {}).slice(0, 300))
492
- const toolErr = r => Boolean(r?.isError ?? r?.data?.isError)
493
- const artifactPathOf = (text) => {
494
- const m = String(text).match(/artifact:\s*(\S+)/)
495
- return m ? m[1] : ''
496
- }
497
- {
498
- const disc = await invokeTool('twin_scene_discover', {})
499
- check('M2.1', '工具 twin_scene_discover:从真实绑定发现场景', disc.status === 200 && !toolErr(disc) && toolText(disc).includes('nodeCount'), toolText(disc).slice(0, 160))
500
-
501
- const comp = await invokeTool('twin_scene_compile', { scene_id: SCENE_ID, scene_version: '1.0.0', line_id: line.id, product_id: product.id, recipe_id: recipe.id, prompt: '膜厚闭环验收场景' })
502
- const compText = toolText(comp)
503
- check('M2.2', '工具 twin_scene_compile:SceneContract 草稿(controls+artifact)', comp.status === 200 && !toolErr(comp) && compText.includes('SceneContract Draft'), compText.slice(0, 200))
504
-
505
- const { createTwinRepo } = await import('../server/services/workshop/aml/twin/repo')
506
- const twinRepo = createTwinRepo(seedDb)
507
- const sceneRow = twinRepo.getScene(SCENE_ID, '1.0.0')
508
- const sceneJson = sceneRow ? JSON.parse(sceneRow.contractJson) : null
509
- check('M2.3', '场景草稿持久化(控制面+目标面齐备,谱系可复用)', Boolean(sceneJson) && (sceneJson.controls ?? []).length >= 2 && (sceneJson.observations ?? []).some(v => v.role === 'target'), `controls=${sceneJson?.controls?.length} states=${sceneJson?.states?.length} obs=${sceneJson?.observations?.length}(targets=${(sceneJson?.observations ?? []).filter(v => v.role === 'target').length})`)
510
-
511
- const frz = await invokeTool('twin_scene_freeze', { scene_id: SCENE_ID, scene_version: '1.0.0', approved_by: email, confirmation: 'USER_CONFIRMED_SCENE_CONTRACT' })
512
- check('M2.4', '工具 twin_scene_freeze:人批准冻结(approvedBy=管理者)', frz.status === 200 && !toolErr(frz) && toolText(frz).includes('"status": "frozen"'), toolText(frz).slice(0, 200))
513
- const noConfirm = await invokeTool('twin_scene_freeze', { scene_id: `${SCENE_ID}-x`, scene_version: '1.0.0' })
514
- check('M2.5', '冻结治理红线:缺确认令牌 → 拒绝', toolErr(noConfirm) || toolText(noConfirm).includes('冻结被拒绝'), toolText(noConfirm).slice(0, 120))
515
-
516
- const frozenRow = twinRepo.getScene(SCENE_ID, '1.0.0')
517
- const frozenScene = JSON.parse(frozenRow.contractJson)
518
-
519
- const draft = await invokeTool('twin_physics_spec_draft', { scene_json: frozenScene, dt_sec: BEAT / 1000 })
520
- const draftArtifact = artifactPathOf(toolText(draft))
521
- const physSpec = draftArtifact && existsSync(draftArtifact) ? JSON.parse(readFileSync(draftArtifact, 'utf8')) : null
522
- check('M2.6', '工具 twin_physics_spec_draft:虚拟模型骨架(状态+参数可校准)', draft.status === 200 && !toolErr(draft) && Boolean(physSpec) && (physSpec.states ?? []).length >= 1 && (physSpec.parameters ?? []).length >= 1, toolText(draft).slice(0, 200))
523
-
524
- const val = await invokeTool('twin_physics_spec_validate', { physics_spec: physSpec })
525
- const valData = data(val) ?? {}
526
- const valBody = valData.apiVersion ? valData : (val.data ?? {})
527
- check('M2.7', '工具 twin_physics_spec_validate:valid=true', val.status === 200 && !toolErr(val) && (valBody.valid === true || String(toolText(val)).includes('"valid": true')), String(toolText(val)).slice(0, 160))
528
-
529
- const compiled = await invokeTool('twin_physics_spec_compile', { physics_spec: physSpec, scene_json: frozenScene })
530
- const compBody = data(compiled) ?? {}
531
- check('M2.8', '工具 twin_physics_spec_compile:候选 Provider(candidate_not_registered)', compiled.status === 200 && !toolErr(compiled) && (compBody.status === 'candidate_not_registered' || String(toolText(compiled)).includes('candidate_not_registered')), String(toolText(compiled)).slice(0, 160))
532
-
533
- // 频道谱系重链到真实冻结场景(训练通道冻结、优化通道复用的平台语义;走平台自有服务)。
534
- // providerId 保留已注册的 injection-greybox-v1:声明式 Provider 仅为 candidate(工具明确
535
- // 不直接注册投产),物理 rollout 由注入 greybox 承担;其观测 id 与本场景不映射 →
536
- // 试验约束 fail-closed —— 正是「未注册 provider 不许投产」的治理语义,一并断言。
537
- const { setHybridChannelProfile, getChannelTwinProfile } = await import('../server/services/workshop/aml/twin/channel-profile')
538
- const prevProfile = getChannelTwinProfile(channelIdOuter)
539
- setHybridChannelProfile({
540
- ...prevProfile,
541
- sceneId: SCENE_ID,
542
- sceneVersion: '1.0.0',
543
- sceneContract: frozenScene,
544
- scenePackId: SCENE_ID,
545
- providerId: 'injection-greybox-v1',
546
- providerVersion: undefined,
547
- providerHash: undefined,
548
- // 显式清空代次:意图是「解析当前已注册的 injection-greybox」(见上注释);
549
- // 沿用模板实例化时的旧 generation,dev(watch) 重启使注册代前进后解析会落空(fail-closed)
550
- providerGeneration: undefined,
551
- createdBy: 'e2e',
552
- })
553
- const profAfter = data(await api('GET', `/api/workshop/channels/${encodeURIComponent(channelIdOuter)}/twin-profile`, undefined, token))
554
- check('M2.9', '频道场景谱系重链(REST 可读)', profAfter?.profile?.sceneId === SCENE_ID && profAfter?.profile?.profile === 'hybrid_twin', `sceneId=${profAfter?.profile?.sceneId}`)
555
-
556
- writeFreshTail()
557
- const snap = await invokeTool('twin_snapshot_create', { channel_id: channelIdOuter, auto_daq: true, phase: 'exploration' }, 120_000)
558
- const snapId = (toolText(snap).match(/snapshot_id:\s*(\S+)/) ?? [])[1] ?? ''
559
- check('M2.10', '工具 twin_snapshot_create:服务端真采快照(auto_daq,fresh)', snap.status === 200 && !toolErr(snap) && Boolean(snapId) && toolText(snap).includes('fresh: true'), toolText(snap).slice(0, 200))
560
-
561
- const targetVars = (frozenScene.observations ?? []).filter(v => v.role === 'target')
562
- const targetId = targetVars[0]?.id ?? (frozenScene.observations ?? [])[0]?.id ?? 'cv'
563
- const controlIds = (frozenScene.controls ?? []).map(c => c.id)
564
- const candidate = {}
565
- if (controlIds[0]) candidate[controlIds[0]] = 60
566
- const objective = {
567
- schemaVersion: 1, createdAt: new Date().toISOString(), createdBy: leadAgentIdOuter, objectiveId: 'loop-e2e',
568
- targets: { [targetId]: 50 }, weights: { [targetId]: 1 }, controlCosts: {}, horizonSteps: 4, trustRegion: {},
569
- }
570
- const trial = await invokeTool('twin_trial_run', { snapshot_id: snapId, objective, candidate_controls: [candidate] }, 120_000)
571
- const trialText = toolText(trial)
572
- check('M2.11', '工具 twin_trial_run:虚拟试验完成(模型驱动 rollout)', trial.status === 200 && !toolErr(trial) && trialText.includes('VirtualTrial 已完成'), trialText.slice(0, 220))
573
- check('M2.12', '虚拟试验治理语义:candidateExecuted=false + 约束 fail-closed(候选 provider 未注册不投产)', trialText.includes('candidateExecuted=false') && trialText.includes('constraints_passed: false'), trialText.split('\n').filter(Boolean).slice(0, 4).join(' | '))
574
- }
575
-
576
- // ════ M3/M4 模型进化两轮(训练 → 工具采纳 → HITL → 发布重绑 → 新模型求解) ════
577
- console.log('\n=== M3 模型进化第 1 轮 ===')
578
- async function trainOnce(modelName) {
579
- let ds = await api('POST', '/api/workshop/process-model/datasets', spec, token)
580
- for (const backoff of [3000, 6000]) {
581
- if (ds.status === 200) break
582
- writeFreshTail()
583
- await sleep(backoff)
584
- ds = await api('POST', '/api/workshop/process-model/datasets', spec, token)
585
- }
586
- const datasetId = data(ds)?.datasetId
587
- // 优化资格报告(solve 前置:模型须经资格评估,缺报告 → solve 422 不具备优化资格)
588
- const elig = await api('POST', '/api/workshop/process-model/eligibility', { specId: SPEC, specVersion: 1, datasetId, scope: 'simulation' }, token)
589
- const eligOk = data(elig)?.report?.optimizationEligible === true
590
- const train = await api('POST', '/api/workshop/process-model/train', { spec, datasetId, modelName }, token)
591
- const jobId = data(train)?.job?.id
592
- let job = null
593
- const terminal = new Set(['done', 'failed', 'cancelled', 'timeout', 'interrupted'])
594
- for (let i = 0; i < 240; i++) {
595
- const jr = await api('GET', `/api/workshop/aml/jobs/${encodeURIComponent(jobId)}`, undefined, token)
596
- job = data(jr)?.job
597
- if (job && terminal.has(job.status)) break
598
- await sleep(500)
599
- }
600
- const models = await api('GET', `/api/workshop/aml/models?recipeId=${encodeURIComponent(recipe.id)}`, undefined, token)
601
- const model = (data(models)?.models ?? []).find(m => m.id === (job?.modelId ?? ''))
602
- return { datasetId, rowCount: data(ds)?.rowCount ?? 0, jobId, job, modelId: job?.modelId ?? '', artifactHash: model?.artifactHash ?? '', eligOk }
603
- }
604
- async function adoptRound(modelId, reason, description) {
605
- const adoptInvoke = invokeTool('optimizer_profile_propose', { model_id: modelId, reason, profile_description: description }, 300_000)
606
- let card = null
607
- for (let i = 0; i < 60; i++) {
608
- await sleep(500)
609
- try {
610
- const pending = await api('GET', '/api/workshop/agent-tools/approvals', undefined, token)
611
- card = (data(pending)?.approvals ?? []).find(a => String(a.nodeId).startsWith('optimizer-profile:') && a.agentId === leadAgentIdOuter)
612
- if (card) break
613
- }
614
- catch { /* 未就绪 */ }
615
- }
616
- if (!card) {
617
- const adoptText = await adoptInvoke.catch(err => ({ text: `invoke rejected: ${String(err).slice(0, 120)}` }))
618
- return { card: null, adoptText, dec: { status: 0 } }
619
- }
620
- const dec = await api('POST', `/api/workshop/agent-tools/approvals/${encodeURIComponent(card.id)}/decide`, { approved: true, choice: 0, comment: '模型进化闭环验收批准' }, token)
621
- let adoptText
622
- try {
623
- adoptText = await adoptInvoke
624
- }
625
- catch (err) {
626
- adoptText = { text: `invoke rejected: ${String(err).slice(0, 160)}` }
627
- }
628
- return { card, adoptText, dec }
629
- }
630
- let round1RowCount
631
- {
632
- // ── 第 1 轮:训练 A → Profile v1(A) → 发布 → 绑定 → 基线求解 ──
633
- const ra = await trainOnce(`模型闭环A-${TAG}`)
634
- trainedAId = ra.modelId
635
- trainedAHash = ra.artifactHash
636
- round1RowCount = ra.rowCount
637
- const annotate = await invokeTool('aml_model_annotate', { model_id: ra.modelId, label: `膜厚模型A-${TAG}`, description: '产线A 膜厚预测:线性状态空间,适配保压/线速工况' })
638
- const annotateText = toolText(annotate)
639
- check('M3.0', 'Agent 工具 aml_model_annotate:补模型名称/描述', !toolErr(annotate) && annotateText.includes('人读身份已更新'), annotateText.slice(0, 140))
640
- check('M3.1', '第 1 轮训练 done + 模型登记 + 优化资格(artifactHash)', ra.job?.status === 'done' && ra.eligOk && trainedAId && trainedAHash.length === 64, `status=${ra.job?.status} model=${trainedAId} rows=${ra.rowCount} err=${String(ra.job?.error ?? '').slice(0, 100)}`)
641
-
642
- const profileBody = {
643
- schemaVersion: 1, id: profileId, version: 1,
644
- modelRef: { modelId: trainedAId, artifactKind: 'linear_state_space@1', artifactHash: trainedAHash, modelInterface: 'linear_state_space', stage: 'candidate' },
645
- problemTemplateRef: 'linear_mpc_quadratic@1',
646
- problemConfig: { linear_mpc_quadratic: { cvWeights: { cv1: 1 }, duWeights: { mv1: 0.1 }, terminalWeight: 2, targets: { cv1: 50 } } },
647
- solverRef: 'osqp_mpc@1', solverVersion: '1',
648
- processSpecRef: `${SPEC}@1`, conditionIds: [], status: 'draft',
649
- }
650
- const profCreated = await api('POST', '/api/workshop/optimization/profiles', profileBody, token)
651
- const pub1 = await api('POST', `/api/workshop/optimization/profiles/${encodeURIComponent(profileId)}/publish?version=1`, undefined, token)
652
- check('M3.2', 'Profile v1 创建(模型A 工件回填)+发布', profCreated.status === 200 && pub1.status === 200, `create=${profCreated.status}/${errCode(profCreated)} pub=${pub1.status}/${errCode(pub1)}`)
653
- const bind = await api('POST', '/api/workshop/optimization/bindings', {
654
- workspaceId: workspaceIdOuter, channelId: channelIdOuter, agentInstanceId: leadAgentIdOuter, profileId, profileVersion: 1, mode: 'recommendation',
655
- }, token)
656
- bindingId = data(bind)?.binding?.id ?? ''
657
- check('M3.3', 'Agent↔Profile 绑定(revision=1,推荐模式)', bind.status === 200 && Boolean(bindingId), `id=${bindingId} code=${errCode(bind)}`)
658
- writeFreshTail()
659
- const solve0 = await api('POST', '/api/workshop/optimization/solve', { agentInstanceId: leadAgentIdOuter, bindingId }, token)
660
- check('M3.4', '基线模型 A solve optimal', solve0.status === 200 && data(solve0)?.result?.status === 'optimal', `status=${data(solve0)?.result?.status} http=${solve0.status} msg=${String(solve0.message ?? '').slice(0, 120)}`)
661
-
662
- // ── 第 2 轮:训练 B(反馈数据再积累)→ 工具采纳 → HITL → v2+重绑 → 新模型求解 ──
663
- const rb = await trainOnce(`模型闭环B-${TAG}`)
664
- trainedBId = rb.modelId
665
- trainedBHash = rb.artifactHash
666
- check('M3.5', '第 2 轮训练 done + 资格(数据集不缩水,工件不同)', rb.job?.status === 'done' && rb.eligOk && trainedBId && rb.rowCount >= round1RowCount && trainedBHash !== trainedAHash, `status=${rb.job?.status} rows ${round1RowCount}→${rb.rowCount} hashDiff=${trainedAHash !== trainedBHash}`)
667
-
668
- const adopt1 = await adoptRound(trainedBId, '模型进化第 1 轮采纳:换上新训练模型 B', '产线A 膜厚闭环:线性 MPC(采纳模型B,提升 rollout 精度)')
669
- check('M3.6', '采纳卡挂出(optimizer-profile:<id>@<v>)', Boolean(adopt1.card), `nodeId=${adopt1.card?.nodeId ?? 'none'}`)
670
- check('M3.7', 'HITL 批准 → 单一咽喉发布+重绑', adopt1.dec.status === 200 && (JSON.stringify(adopt1.dec).includes('published') || JSON.stringify(adopt1.dec).includes('已发布')), JSON.stringify(adopt1.dec).slice(0, 300))
671
- const adoptStr1 = String(adopt1.adoptText?.data?.text ?? adopt1.adoptText?.data?.result?.text ?? adopt1.adoptText?.text ?? JSON.stringify(adopt1.adoptText)).slice(0, 240)
672
- check('M3.8', '工具回执:模型采纳完成(诚实汇报)', adoptStr1.includes('模型采纳完成'), adoptStr1)
673
-
674
- const binds1 = (data(await api('GET', `/api/workshop/optimization/bindings?agentInstanceId=${encodeURIComponent(leadAgentIdOuter)}`, undefined, token))?.bindings ?? []).filter(b => b.profileId === profileId)
675
- const cardV1 = Number(String(adopt1.card?.nodeId ?? '').split('@')[1])
676
- const rebound1 = binds1.find(b => Number(b.profileVersionNumber) === cardV1)
677
- check('M3.9', '绑定自动重绑到采纳版本(revision+1)', Boolean(rebound1) && Number(rebound1?.revision) >= 1, `versions=[${binds1.map(b => b.profileVersionNumber).join(',')}] card=v${cardV1} rev=${rebound1?.revision}`)
678
- const profs1 = JSON.stringify(data(await api('GET', `/api/workshop/optimization/profiles?limit=50`, undefined, token)) ?? {})
679
- check('M3.10', '已发布 Profile v2 携带新模型工件 B', profs1.includes(trainedBId), `len=${profs1.length}`)
680
- check('M3.10b', 'Profile 描述由 Agent 提议写入并落版本台账', profs1.includes('产线A 膜厚闭环:线性 MPC(采纳模型B'), '')
681
- writeFreshTail()
682
- const solve1 = await api('POST', '/api/workshop/optimization/solve', { agentInstanceId: leadAgentIdOuter, bindingId: rebound1?.id }, token)
683
- check('M3.11', '新模型 B solve optimal', solve1.status === 200 && data(solve1)?.result?.status === 'optimal', `status=${data(solve1)?.result?.status} http=${solve1.status} msg=${String(solve1.message ?? '').slice(0, 120)}`)
684
- }
685
-
686
- console.log('\n=== M4 模型进化第 2 轮(持续迭代) ===')
687
- {
688
- const rc = await trainOnce(`模型闭环C-${TAG}`)
689
- trainedCId = rc.modelId
690
- trainedCHash = rc.artifactHash
691
- check('M4.1', '第 3 次训练 done + 资格(反馈持续积累)', rc.job?.status === 'done' && rc.eligOk && trainedCId && trainedCHash.length === 64, `status=${rc.job?.status} model=${trainedCId} rows=${rc.rowCount}`)
692
-
693
- const adopt2 = await adoptRound(trainedCId, '模型进化第 2 轮采纳:持续迭代换新模型 C', '产线A 膜厚闭环:线性 MPC(采纳模型C,持续迭代)')
694
- check('M4.2', '第 2 轮采纳卡挂出+HITL 批准', Boolean(adopt2.card) && adopt2.dec.status === 200, `nodeId=${adopt2.card?.nodeId ?? 'none'} dec=${adopt2.dec.status}`)
695
- const adoptStr2 = String(adopt2.adoptText?.data?.text ?? adopt2.adoptText?.data?.result?.text ?? adopt2.adoptText?.text ?? JSON.stringify(adopt2.adoptText)).slice(0, 240)
696
- check('M4.3', '第 2 轮工具回执:采纳完成', adoptStr2.includes('模型采纳完成'), adoptStr2)
697
-
698
- const binds2 = (data(await api('GET', `/api/workshop/optimization/bindings?agentInstanceId=${encodeURIComponent(leadAgentIdOuter)}`, undefined, token))?.bindings ?? []).filter(b => b.profileId === profileId)
699
- const cardV2 = Number(String(adopt2.card?.nodeId ?? '').split('@')[1])
700
- const rebound2 = binds2.find(b => Number(b.profileVersionNumber) === cardV2)
701
- check('M4.4', '持续进化:绑定再次重绑(revision 递增)', Boolean(rebound2) && Number(rebound2?.revision) >= 2, `versions=[${binds2.map(b => b.profileVersionNumber).join(',')}] card=v${cardV2} rev=${rebound2?.revision}`)
702
- writeFreshTail()
703
- const solve2 = await api('POST', '/api/workshop/optimization/solve', { agentInstanceId: leadAgentIdOuter, bindingId: rebound2?.id }, token)
704
- check('M4.5', '第 2 轮新模型 C solve optimal', solve2.status === 200 && data(solve2)?.result?.status === 'optimal', `status=${data(solve2)?.result?.status} http=${solve2.status}`)
705
-
706
- const writesPath = join(HOME, 'data', 'dcw-writes.json')
707
- const writesLen = existsSync(writesPath) ? readFileSync(writesPath, 'utf8').length : 0
708
- check('M4.6', '全闭环零 DCW 写入(三轮训练+两轮采纳+求解)', writesLen === 0, `dcw-writes.json ${writesLen ? '存在' : '不存在'}`)
709
- }
710
-
711
- // ════ M5 管理者面 REST ════
712
- console.log('\n=== M5 管理者面 ===')
713
- {
714
- const versions = await api('GET', `/api/workshop/ontology/versions/${encodeURIComponent(ONT)}`, undefined, token)
715
- check('M5.1', '本体版本台账(v1+v2,管理者可查)', versions.status === 200 && (data(versions)?.versions ?? []).length >= 2, `n=${(data(versions)?.versions ?? []).length}`)
716
-
717
- const profs = await api('GET', `/api/workshop/optimization/profiles?limit=50`, undefined, token)
718
- const profStr = JSON.stringify(data(profs) ?? {})
719
- check('M5.2', 'Profile 版本台账含三轮模型工件(A/B/C 全可查)', profs.status === 200 && [trainedAId, trainedBId, trainedCId].every(id => profStr.includes(id)), `len=${profStr.length}`)
720
-
721
- const twinProf = await api('GET', `/api/workshop/channels/${encodeURIComponent(channelIdOuter)}/twin-profile`, undefined, token)
722
- check('M5.3', '孪生谱系台账(场景/冻结态可查)', twinProf.status === 200 && data(twinProf)?.profile?.sceneId === SCENE_ID, `sceneId=${data(twinProf)?.profile?.sceneId}`)
723
-
724
- const audit = await api('GET', '/api/workshop/audit?limit=500', undefined, token)
725
- const entries = data(audit)?.entries ?? []
726
- const adoptEntries = entries.filter(e => String(e.action).startsWith('optimizer.profile.adopt'))
727
- const kinds = new Set(adoptEntries.map(e => e.actorKind))
728
- check('M5.4', '审计三态留痕:AI 提议 + 人批准(adopt_propose+adopt)', adoptEntries.length >= 2 && kinds.has('agent'), `n=${adoptEntries.length} actions=${adoptEntries.map(e => e.action).join(',')} kinds=${[...kinds].join(',')}`)
729
-
730
- const ontAudit = entries.filter(e => String(e.action).includes('ontology'))
731
- check('M5.5', '本体审计留痕(起草/发布/修正)', ontAudit.length >= 1, `n=${ontAudit.length} sample=${ontAudit[0]?.action ?? '-'}`)
732
- }
733
-
734
- // ════ M6 前端渲染走查(管理者查看) ════
735
- console.log('\n=== M6 前端渲染 ===')
736
- process.env.AW_BASE = BASE
737
- {
738
- const { launch, openPage, gotoReady } = await import('./ui/lib.mjs')
739
- const browser = await launch({ width: 1600, height: 1000 })
740
- const page = await openPage(browser, { token, width: 1600, height: 1000, deviceScaleFactor: 1 })
741
- const pageErrors = []
742
- page.on('pageerror', e => pageErrors.push(String(e.message).slice(0, 200)))
743
- const shot = name => page.screenshot({ path: join(EVID, `${name}.png`), fullPage: true })
744
- try {
745
- const targets = [['/optimizer', 'optimizer'], ['/aml', 'aml'], ['/ontology', 'ontology']]
746
- let allOk = true
747
- const detail = []
748
- const bodies = {}
749
- for (const [path, name] of targets) {
750
- const errsBefore = pageErrors.length
751
- await gotoReady(page, path, { wait: 2500 })
752
- await sleep(800)
753
- const bodyLen = await page.evaluate(() => (document.body.textContent ?? '').length)
754
- bodies[name] = await page.evaluate(() => document.body.textContent ?? '')
755
- const ok = pageErrors.length === errsBefore && bodyLen > 400
756
- detail.push(`${name}:len=${bodyLen},errs=${pageErrors.length - errsBefore}`)
757
- if (!ok) allOk = false
758
- await shot(`page-${name}`)
759
- }
760
- check('M6.1', '管理者三台(/optimizer /aml /ontology)渲染无错', allOk, detail.join(' '))
761
- // 数据异步加载:轮询等待关键文案(最多 10s),并切到 Profile tab
762
- const waitText = async (needle, timeoutMs = 10_000) => {
763
- const t0 = Date.now()
764
- while (Date.now() - t0 < timeoutMs) {
765
- const hit = await page.evaluate(n => (document.body.textContent ?? '').includes(n), needle)
766
- if (hit) return true
767
- await sleep(500)
768
- }
769
- return false
770
- }
771
- await gotoReady(page, '/optimizer', { wait: 2500 })
772
- await page.evaluate(() => {
773
- const btn = Array.from(document.querySelectorAll('button')).find(b => (b.textContent || '').includes('Profile'))
774
- if (btn) btn.click()
775
- })
776
- await sleep(600)
777
- const profileDescVisible = await waitText('产线A 膜厚闭环')
778
- check('M6.3', 'UI:Profile 描述在 /optimizer 台账可见', profileDescVisible)
779
- await shot('page-optimizer-profile')
780
-
781
- await gotoReady(page, '/aml', { wait: 2500 })
782
- const amlDescVisible = await waitText('产线A 膜厚预测', 12_000)
783
- check('M6.4', 'UI:模型描述在 /aml 台账可见', amlDescVisible)
784
- await shot('page-aml-models')
785
-
786
- await gotoReady(page, '/ontology', { wait: 2500 })
787
- const ontoDescVisible = (await waitText('膜厚闭环控制本体', 6000)) || (await waitText('(产线 ln-', 4000))
788
- const fixBtnVisible = await page.evaluate(() => (document.body.textContent ?? '').includes('自动修复'))
789
- check('M6.5', 'UI:本体描述与「自动修复」入口在 /ontology 可见', ontoDescVisible && fixBtnVisible, `desc=${ontoDescVisible} fixBtn=${fixBtnVisible}`)
790
- await shot('page-ontology-desc')
791
- check('M6.2', '全程无未捕获 pageerror', pageErrors.length === 0 || pageErrors.every(e => e.includes('dispose')), pageErrors.slice(0, 2).join(';'))
792
- }
793
- finally {
794
- await browser.close().catch(() => {})
795
- }
796
- }
797
-
798
- // ════ 报告 ════
799
- const pass = results.filter(r => r.pass).length
800
- const report = {
801
- script: 'scripts/e2e-model-loop-live.mjs',
802
- generatedAt: new Date().toISOString(),
803
- base: BASE,
804
- home: HOME,
805
- ontology: ONT,
806
- profileId,
807
- sceneId: SCENE_ID,
808
- lineId: line.id,
809
- modelA: { id: trainedAId, artifactHash: trainedAHash },
810
- modelB: { id: trainedBId, artifactHash: trainedBHash },
811
- modelC: { id: trainedCId, artifactHash: trainedCHash },
812
- total: results.length,
813
- pass,
814
- fail: results.length - pass,
815
- results,
816
- }
817
- writeFileSync(join(EVID, 'report.json'), JSON.stringify(report, null, 2))
818
- console.log(`\nMODEL-LOOP LIVE E2E: ${pass}/${results.length} passed, ${results.length - pass} failed`)
819
- console.log(`evidence: ${EVID}`)
820
- killTree(child.pid)
821
- process.exit(results.some(r => !r.pass) ? 1 : 0)
1
+ #!/usr/bin/env node
2
+ /* eslint-disable @stylistic/max-statements-per-line */
3
+ /**
4
+ * 模型层闭环真机 E2E(2026-10-24)—— 三层模型的「创建→使用→迭代进化」全链。
5
+ *
6
+ * 目标:验证 Agent 经工具面真正控制/迭代模型(不止参数优化),人类作为管理者
7
+ * 查看/修正,Agent 在持续迭代中把新模型反馈进求解器(模型进化闭环)。
8
+ *
9
+ * M0 hybrid_twin 全功能频道(训练面+孪生面+优化器面同面注入)+ Agent 节点绑定 + 过程 spec
10
+ * M1 本体层:起草→批准→发布 v1;管理者修正规则窗→v2(人类按意愿修正模型)
11
+ * M2 孪生层(虚拟模型创建,全经 Agent 工具):场景发现→SceneContract 编译→冻结(人批准)
12
+ * →PhysicsSpec 骨架→校验→编译候选→频道谱系重链→真采快照→虚拟试验(recommendation-only)
13
+ * M3 模型进化第 1 轮:训练 A → Profile v1(A)+发布+绑定 → 基线求解 → 训练 B →
14
+ * optimizer_profile_propose(工具)→ HITL 批准 → 发布 v2+自动重绑 → 新模型 solve optimal
15
+ * M4 模型进化第 2 轮:训练 C → 再采纳 → v3+重绑 → solve optimal(持续进化证据+零设备写入)
16
+ * M5 管理者面 REST:本体版本/四段 diff、Profile 版本、孪生谱系、审计三态留痕
17
+ * M6 前端渲染走查(管理者查看:/optimizer /aml /ontology)
18
+ *
19
+ * 运行:node scripts/e2e-model-loop-live.mjs
20
+ * 证据:docs/audit/evidence/2026-10-24-model-loop-live/{report.json,*.png}
21
+ */
22
+ import { spawn } from 'node:child_process'
23
+ import { mkdirSync, writeFileSync, existsSync, symlinkSync, openSync, readFileSync } from 'node:fs'
24
+ import { join, resolve, dirname } from 'node:path'
25
+ import { fileURLToPath } from 'node:url'
26
+ import { tmpdir, homedir } from 'node:os'
27
+ import { DatabaseSync } from 'node:sqlite'
28
+
29
+ const REPO = resolve(dirname(fileURLToPath(import.meta.url)), '..')
30
+ const ROOT = join(tmpdir(), `aw-model-loop-live-${Date.now()}`)
31
+ const HOME = join(ROOT, 'home')
32
+ const EVID = resolve(process.env.AW_E2E_EVIDENCE_DIR || join(REPO, 'docs', 'audit', 'evidence', '2026-10-24-model-loop-live'))
33
+ mkdirSync(HOME, { recursive: true })
34
+ mkdirSync(EVID, { recursive: true })
35
+
36
+ const TAG = `mlp${Date.now().toString(36).slice(-4)}`
37
+ const BEAT = 5000
38
+ const H = 24
39
+ const F = 6
40
+ const N_STEPS = 160
41
+ const N_RUNS = 6
42
+ const DELAY_STEPS = 2
43
+
44
+ process.env.AW_MODE = 'home'
45
+ process.env.AW_HOME = HOME
46
+ process.env.AW_AML_DIR = join(HOME, 'aml')
47
+ process.env.NO_PROXY = '127.0.0.1,localhost'
48
+
49
+ mkdirSync(join(HOME, 'aml'), { recursive: true })
50
+ const realVenv = join(homedir(), '.AgentWorkShop', 'aml', '.venv')
51
+ let venvLinked = false
52
+ if (existsSync(join(realVenv, 'Scripts', 'python.exe'))) {
53
+ symlinkSync(realVenv, join(HOME, 'aml', '.venv'), 'junction')
54
+ venvLinked = true
55
+ }
56
+
57
+ const results = []
58
+ function check(id, name, cond, detail = '') {
59
+ const pass = Boolean(cond)
60
+ results.push({ id, name, pass, detail: String(detail).slice(0, 600) })
61
+ console.log(`${pass ? '✔' : '✘'} [${id}] ${name}${detail ? ` — ${String(detail).slice(0, 200)}` : ''}`)
62
+ return pass
63
+ }
64
+ const sleep = ms => new Promise(r => setTimeout(r, ms))
65
+ function killTree(pid) {
66
+ try {
67
+ spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore' })
68
+ }
69
+ catch { /* 进程已退 */ }
70
+ }
71
+
72
+ const { getDcwLineRepo } = await import('../server/services/workshop/dcw/dcw-line.repo')
73
+ const { getDcwProductRepo } = await import('../server/services/workshop/dcw/dcw-product.repo')
74
+ const { getDcwRecipeRepo } = await import('../server/services/workshop/dcw/dcw-recipe.repo')
75
+ const { getDcwNodeRepo } = await import('../server/services/workshop/dcw/dcw-node.repo')
76
+ const { DcwNode } = await import('../server/services/workshop/dcw/dcw-node')
77
+ const { getDaqNodeRepo } = await import('../server/services/workshop/daq/daq-node.repo')
78
+ const { DaqNode } = await import('../server/services/workshop/daq/daq-node')
79
+ const { SqliteTimeSeriesAdapter } = await import('../server/services/workshop/daq/storage/sqlite.adapter')
80
+ const { getContextSegmentRepo, recipeContentHash } = await import('../server/services/workshop/process-model/context-segments.repo')
81
+ const { openWorkshopDb } = await import('../server/services/workshop/db/database/open')
82
+ const { configureAmlRuntime } = await import('../server/services/workshop/aml/runtime')
83
+ const { bindOpsRepos } = await import('../server/services/workshop/ops/ops')
84
+ const { createAuditRepo } = await import('../server/services/workshop/db/ops.repo')
85
+
86
+ const seedDb = openWorkshopDb(join(HOME, 'data', 'workshop.sqlite'))
87
+ configureAmlRuntime(seedDb)
88
+ try {
89
+ bindOpsRepos({ audit: createAuditRepo(seedDb) })
90
+ }
91
+ catch { /* 重复装配无害 */ }
92
+
93
+ const line = getDcwLineRepo().create({ name: `模型闭环验收线-${TAG}`, simulated: true })
94
+ const product = getDcwProductRepo().create({ name: `模型闭环验收产品-${TAG}`, lineId: line.id })
95
+ getDcwNodeRepo().insert(new DcwNode({
96
+ id: `dcw-${TAG}-press`, templateRef: 'dcw-temp-sp', driver: 'mock',
97
+ name: `熔体压力控制-${TAG}`, lineId: line.id, min: 0, max: 100, unit: 'bar',
98
+ }))
99
+ getDcwNodeRepo().insert(new DcwNode({
100
+ id: `dcw-${TAG}-speed`, templateRef: 'dcw-temp-sp', driver: 'mock',
101
+ name: `线速度控制-${TAG}`, lineId: line.id, min: 0, max: 50, unit: 'm/min',
102
+ }))
103
+ const DCW_PRESS = `dcw-${TAG}-press`
104
+ const DCW_SPEED = `dcw-${TAG}-speed`
105
+ for (const id of [DCW_PRESS, DCW_SPEED]) {
106
+ const node = getDcwNodeRepo().byId(id)
107
+ if (node) {
108
+ node.readValue = id === DCW_PRESS ? 50 : 10
109
+ getDcwNodeRepo().flushNow()
110
+ }
111
+ }
112
+ getDaqNodeRepo().insert(DaqNode.fromRow({
113
+ id: `dn-${TAG}-mv`, templateRef: 'tpl-loop-mv', name: `熔体压力-${TAG}`, unit: 'bar',
114
+ min: 0, max: 100, lineId: line.id, driver: 'mock',
115
+ }))
116
+ getDaqNodeRepo().insert(DaqNode.fromRow({
117
+ id: `dn-${TAG}-cv`, templateRef: 'tpl-loop-cv', name: `膜厚度-${TAG}`, unit: 'μm',
118
+ min: 0, max: 200, lineId: line.id, driver: 'mock',
119
+ }))
120
+ getDaqNodeRepo().insert(DaqNode.fromRow({
121
+ id: `dn-${TAG}-temp`, templateRef: 'tpl-loop-temp', name: `温区温度-${TAG}`, unit: '℃',
122
+ min: 0, max: 400, lineId: line.id, driver: 'mock',
123
+ }))
124
+ const MV_ID = `dn-${TAG}-mv`
125
+ const CV_ID = `dn-${TAG}-cv`
126
+ const TEMP_ID = `dn-${TAG}-temp`
127
+ const recipe = getDcwRecipeRepo().create({
128
+ name: `模型闭环验收配方-${TAG}`, productId: product.id,
129
+ params: [
130
+ { nodeId: DCW_PRESS, value: 50, min: 0, max: 100 },
131
+ { nodeId: DCW_SPEED, value: 10, min: 0, max: 50 },
132
+ ],
133
+ daqWindows: [{ nodeId: MV_ID, min: 0, max: 100 }],
134
+ })
135
+
136
+ const now0 = Date.now()
137
+ const runStartBase = now0 - 3 * 3600_000
138
+ const sampleRows = []
139
+ const segRepo = getContextSegmentRepo()
140
+ const seedHash = recipeContentHash(recipe)
141
+ for (let r = 0; r < N_RUNS; r++) {
142
+ const start = runStartBase + r * (N_STEPS * BEAT + 120_000)
143
+ const end = start + (N_STEPS - 1) * BEAT
144
+ const run = getDcwRecipeRepo().createRun(recipe)
145
+ run.startedAt = new Date(start).toISOString()
146
+ run.endedAt = new Date(end).toISOString()
147
+ getDcwRecipeRepo().updateRun(run)
148
+ segRepo.insert({ lineId: line.id, runId: run.id, fromTs: start, toTs: end, recipeId: recipe.id, recipeVersion: recipe.version ?? 1, recipeContentHash: seedHash, conditionId: 'c-live', source: 'line_run', confirmed: true })
149
+ let y = 52
150
+ const uq = []
151
+ // G6 动作覆盖门(2026-11 新增):控制序列需离散水平 + 与时间低共线 → 阶跃保持式激励(每 20 拍换水平,拟随机游走)
152
+ let level = 50
153
+ for (let k = 0; k < N_STEPS; k++) {
154
+ if (k % 20 === 19) {
155
+ const jump = ((k + r * 7) % 3) - 1 // {-1,0,1} × 5 → 水平集 {45,50,55}
156
+ level = Math.min(55, Math.max(45, level + jump * 5))
157
+ }
158
+ const u = level + 0.15 * Math.sin((k + r * 11) / 9)
159
+ uq.push(u)
160
+ const delayed = uq[Math.max(0, uq.length - 1 - DELAY_STEPS)]
161
+ y = 0.3 * y + 0.7 * delayed + 8 + 0.02 * Math.sin((k + r) / 3)
162
+ const ts = start + k * BEAT
163
+ const tags = { lineId: line.id, productId: product.id, recipeId: recipe.id, runId: run.id }
164
+ sampleRows.push({ nodeId: MV_ID, tsMs: ts, value: u, state: 'ok', ...tags })
165
+ sampleRows.push({ nodeId: CV_ID, tsMs: ts, value: y, state: 'ok', ...tags })
166
+ sampleRows.push({ nodeId: TEMP_ID, tsMs: ts, value: 190 + 8 * Math.sin((k + r) / 6), state: 'ok', ...tags })
167
+ }
168
+ }
169
+ const seedTsdb = new SqliteTimeSeriesAdapter()
170
+ await seedTsdb.init()
171
+ await seedTsdb.writeSamples(sampleRows)
172
+ await seedTsdb.close()
173
+ console.log(`seed: line=${line.id} recipe=${recipe.id} runs=${N_RUNS} samples=${sampleRows.length}`)
174
+ console.log(`venv: ${venvLinked ? 'junction ok' : '未复用(训练将失败,先检查)'}`)
175
+ if (!venvLinked) console.warn('⚠ 未找到真实 python venv,训练轮会失败')
176
+
177
+ function insertSamples(rows) {
178
+ if (!rows.length) return
179
+ const db = new DatabaseSync(join(HOME, 'data', 'daq-timeseries.sqlite'))
180
+ db.exec('PRAGMA busy_timeout=8000')
181
+ const ins = db.prepare(`INSERT OR IGNORE INTO daq_samples
182
+ (node_id, ts_ms, value, state, line_id, product_id, recipe_id, run_id, ingested_at)
183
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
184
+ db.exec('BEGIN')
185
+ for (const r of rows) ins.run(r.nodeId, r.tsMs, r.value, r.state ?? 'ok', r.lineId ?? null, r.productId ?? null, r.recipeId ?? null, r.runId ?? null, r.ingestedAt ?? Date.now())
186
+ db.exec('COMMIT')
187
+ db.close()
188
+ }
189
+ function writeFreshTail() {
190
+ // context 窗口 = H*beat + maxDelay + 5*beat;尾巴必须覆盖整窗,否则网格 NaN
191
+ const now = Date.now()
192
+ const rows = []
193
+ const span = Math.ceil(H + DELAY_STEPS + 6)
194
+ for (let k = span; k >= 1; k--) {
195
+ const ts = now - k * BEAT
196
+ const tags = { lineId: line.id, productId: product.id, recipeId: recipe.id }
197
+ const mv = 50 + 6 * Math.sin(k / 5)
198
+ rows.push({ nodeId: MV_ID, tsMs: ts, value: mv, state: 'ok', ...tags })
199
+ rows.push({ nodeId: CV_ID, tsMs: ts, value: 50 + 0.7 * (mv - 50) + 0.05 * Math.sin(k / 3), state: 'ok', ...tags })
200
+ rows.push({ nodeId: TEMP_ID, tsMs: ts, value: 195, state: 'ok', ...tags })
201
+ }
202
+ insertSamples(rows)
203
+ }
204
+
205
+ // ════ 启动隔离实例 ════
206
+ // 强制 SQLite 时序(宿主 Timescale 在线时插件会切走,看不到预置样本);MQTT 指向关闭端口。
207
+ const { saveSettings } = await import('../shared/config/engine.mjs')
208
+ saveSettings({
209
+ 'daq.timescale.host': '127.0.0.1',
210
+ 'daq.timescale.port': 6543,
211
+ 'daq.mqtt.host': '127.0.0.1',
212
+ 'daq.mqtt.port': 18830,
213
+ 'daq.startInfrastructure': 'never',
214
+ }, join(HOME, 'runtime-settings.json'))
215
+ let port = 0
216
+ let BASE = ''
217
+ let child = null
218
+ let token = ''
219
+ // 2026-10-29:固定低段(3993-3997)与并行会话/遗留实例撞车(实测:boot 打到别人实例 →
220
+ // 注册 403/needsSetup=false)。改随机高端口 + boot 自愈重试:注册/fresh 校验不过就
221
+ // 杀自己子进程换端口重来(最多 3 次),绝不与不明监听者抢端口。
222
+ const candidates = Array.from({ length: 8 }, () => 34000 + Math.floor(Math.random() * 5900))
223
+ const data = r => r?.data
224
+ const errCode = r => r?.code ?? r?.data?.code ?? ''
225
+ const email = `mlp-${TAG}@awshop.local`
226
+ /** 本轮已试过的端口不再复用(失败后同端口重试只会撞自己正在拆除的旧实例) */
227
+ const usedPorts = new Set()
228
+
229
+ async function api(method, path, body, tok, timeoutMs = 180_000) {
230
+ const res = await fetch(BASE + path, {
231
+ method,
232
+ headers: { 'content-type': 'application/json', ...(tok ? { authorization: `Bearer ${tok}` } : {}) },
233
+ body: body === undefined ? undefined : JSON.stringify(body),
234
+ signal: AbortSignal.timeout(timeoutMs),
235
+ })
236
+ let json = null
237
+ try {
238
+ json = await res.json()
239
+ }
240
+ catch { /* 非 JSON */ }
241
+ return { status: res.status, ...(json ?? {}) }
242
+ }
243
+
244
+ async function pickPort() {
245
+ const { execSync } = await import('node:child_process')
246
+ for (const p of candidates) {
247
+ if (usedPorts.has(p)) continue
248
+ let occupied = false
249
+ try {
250
+ await fetch(`http://127.0.0.1:${p}/api/health`, { signal: AbortSignal.timeout(800) })
251
+ occupied = true
252
+ }
253
+ catch { /* 健康探测失败不代表空闲 */ }
254
+ if (!occupied) {
255
+ // 健康探测失败但 netstat 有 LISTENING = 归属不明的活实例,跳过该端口
256
+ let listening = false
257
+ try {
258
+ const out = execSync(`netstat -ano | findstr :${p} | findstr LISTENING`, { shell: 'cmd.exe' }).toString()
259
+ listening = /\s\d+\s*$/m.test(out)
260
+ }
261
+ catch { /* 无监听 */ }
262
+ if (listening) { occupied = true; await sleep(300) }
263
+ }
264
+ if (!occupied) { usedPorts.add(p); return p }
265
+ await sleep(300)
266
+ }
267
+ return 0
268
+ }
269
+
270
+ /** 单次 boot:选端口→spawn→health→注册→fresh 校验;返回 {ok, stage, detail};失败已杀自己的子进程 */
271
+ async function bootInstance() {
272
+ port = await pickPort()
273
+ if (!port) return { ok: false, stage: 'port', detail: '无空闲端口' }
274
+ BASE = `http://127.0.0.1:${port}`
275
+ console.log(`\n=== boot ${BASE} ===`)
276
+ const logFd = openSync(join(ROOT, 'dev.log'), 'a')
277
+ child = spawn(process.execPath, [join(REPO, 'bin', 'aw.mjs'), 'dev', '--port', String(port)], {
278
+ cwd: REPO,
279
+ env: { ...process.env, AW_RATE_LIMIT_OFF: '1', NUXT_SESSION_PASSWORD: 'ModelLoopLive#2026-e2e-session', NO_PROXY: '127.0.0.1,localhost' },
280
+ stdio: ['ignore', logFd, logFd],
281
+ windowsHide: true,
282
+ })
283
+ let healthy = false
284
+ for (let i = 0; i < 120; i++) {
285
+ await sleep(1500)
286
+ try {
287
+ const h = await api('GET', '/api/health', undefined, undefined, 3000)
288
+ if (h?.data?.status === 'ok' && h?.data?.workshop === 'ready') { healthy = true; break }
289
+ }
290
+ catch { /* 未就绪 */ }
291
+ }
292
+ if (!healthy) { killTree(child.pid); return { ok: false, stage: 'health', detail: '实例未就绪:' + join(ROOT, 'dev.log') } }
293
+ // 上面模块级 email = 管理员账号(冻结审批 approvedBy 同源)
294
+ let reg = null
295
+ for (let attempt = 0; attempt < 3 && !data(reg ?? {})?.token; attempt++) {
296
+ try {
297
+ reg = await api('POST', '/api/users/register', { name: `模型闭环验收-${TAG}`, email, password: 'ModelLoop#2026' })
298
+ }
299
+ catch (err) {
300
+ console.log(`register attempt ${attempt + 1} failed: ${String(err).slice(0, 120)}`)
301
+ await sleep(3000)
302
+ }
303
+ }
304
+ token = data(reg ?? {})?.token ?? ''
305
+ if (!token) { killTree(child.pid); return { ok: false, stage: 'register', detail: `注册失败 status=${reg?.status}` } }
306
+ // fresh 绑定断言(2026-10-29 修正语义):首注册必须拿到 role=admin(bootstrap)。
307
+ // 若端口被别会话实例抢答,要么 403(其注册闸已关),要么拿到 role=user —— 都在此拦截。
308
+ const role = data(reg ?? {})?.user?.role
309
+ if (role !== 'admin') {
310
+ killTree(child.pid)
311
+ return { ok: false, stage: 'fresh', detail: `首注册 role=${role ?? '?'}(非 admin=打到别会话实例)` }
312
+ }
313
+ return { ok: true, stage: 'ready', detail: `port=${port}` }
314
+ }
315
+
316
+ let boot = { ok: false, stage: 'not-run', detail: '' }
317
+ for (let attempt = 1; attempt <= 3 && !boot.ok; attempt++) {
318
+ boot = await bootInstance()
319
+ if (!boot.ok && attempt < 3) { console.log(` · boot attempt ${attempt} 未独占(${boot.stage}),换端口重试`); await sleep(3000) }
320
+ }
321
+ check('BOOT', '隔离实例独占启动 + 注册首管理员 + fresh 校验', boot.ok, `${boot.stage}: ${boot.detail}`)
322
+ if (!boot.ok) throw new Error(`隔离实例连续 3 次未能独占启动(${boot.stage})`)
323
+
324
+ // ════ M0 hybrid_twin 全功能频道 + 绑定三面 ════
325
+ console.log('\n=== M0 频道与三面绑定 ===')
326
+ const ONT = `ont-${TAG}`
327
+ const SPEC = `pms-${TAG}`
328
+ const profileId = `optp-${TAG}`
329
+ const SCENE_ID = `scn-${TAG}`
330
+ let channelIdOuter
331
+ let leadAgentIdOuter
332
+ let workspaceIdOuter
333
+ let bindingId
334
+ let trainedAId
335
+ let trainedBId
336
+ let trainedCId
337
+ let trainedAHash
338
+ let trainedBHash
339
+ let trainedCHash
340
+ let spec
341
+ {
342
+ const inst = await api('POST', '/api/workshop/channel-templates/chtpl-hybrid-twin-mpc-default/instantiate', { name: `模型闭环频道-${TAG}`, bindLineId: line.id }, token)
343
+ const instData = data(inst) ?? {}
344
+ workspaceIdOuter = data(await api('POST', '/api/workshop/workspaces', { name: `模型闭环工作区-${TAG}` }, token))?.id
345
+ channelIdOuter = instData.channelId
346
+ leadAgentIdOuter = instData.leadAgentId ?? (instData.agents ?? []).find(a => a.role === 'lead')?.id
347
+ if (workspaceIdOuter && channelIdOuter) await api('POST', `/api/workshop/workspaces/${encodeURIComponent(workspaceIdOuter)}/channels/${encodeURIComponent(channelIdOuter)}`, undefined, token)
348
+ check('M0.1', 'hybrid_twin 频道实例化(全功能档位)+workspace', Boolean(workspaceIdOuter && channelIdOuter && leadAgentIdOuter), `inst=${inst.status} ch=${channelIdOuter} lead=${leadAgentIdOuter}`)
349
+
350
+ // 工具面断言(进程内同判:scopeHostToolsForRole 与线上装配同一函数)
351
+ try {
352
+ const { scopeHostToolsForRole } = await import('../server/services/workshop/agents/host-tool-bridge/catalog')
353
+ const scope = scopeHostToolsForRole('lead', channelIdOuter)
354
+ const names = new Set(scope.tools.map(t => t.name))
355
+ const need = ['twin_scene_discover', 'twin_scene_compile', 'twin_scene_freeze', 'twin_physics_spec_draft', 'twin_physics_spec_validate', 'twin_physics_spec_compile', 'twin_snapshot_create', 'twin_trial_run', 'aml_dataset_build', 'aml_job_submit', 'optimizer_solve', 'optimizer_profile_propose', 'ontology_draft_create']
356
+ const missing = need.filter(n => !names.has(n))
357
+ check('M0.2', 'hybrid 档位工具面:训练+孪生+优化器+本体四族同面注入', missing.length === 0, `missing=${missing.join(',')} total=${names.size}`)
358
+ }
359
+ catch (err) {
360
+ check('M0.2', 'hybrid 档位工具面(进程内装配)', false, `err=${String(err).slice(0, 160)}`)
361
+ }
362
+
363
+ // Agent 节点绑定:daq 读面(MV/CV/TEMP)+ 配方面(参数写面 → 场景控制面)
364
+ const bindNode = async (nodeId, kind) => api('POST', '/api/workshop/agent-tools/bindings', { agentId: leadAgentIdOuter, nodeId, kind }, token)
365
+ const b1 = await bindNode(MV_ID, 'daq')
366
+ const b2 = await bindNode(CV_ID, 'daq')
367
+ const b3 = await bindNode(TEMP_ID, 'daq')
368
+ const b4 = await bindNode(recipe.id, 'recipe')
369
+ check('M0.3', 'Agent 节点绑定:daq×3 + recipe(参数面)', [b1, b2, b3, b4].every(x => x.status === 200), `daq=${[b1.status, b2.status, b3.status]} recipe=${b4.status}/${errCode(b4)}`)
370
+
371
+ // 过程 spec 先登记发布(Profile 的 processSpecRef 谱系前置;Profile 本体在 M3 训练出模型后创建)
372
+ spec = {
373
+ schemaVersion: 2, id: SPEC, version: 1,
374
+ lineId: line.id, productId: product.id, recipeId: recipe.id, recipeVersion: recipe.version ?? 1,
375
+ conditions: [{ id: 'c1', match: [{ field: 'recipeId', op: 'eq', value: recipe.id }] }],
376
+ variables: [
377
+ { id: 'mv1', nodeId: MV_ID, role: 'mv', field: 'value', unit: 'bar', scale: 1, offset: 0, delayMs: DELAY_STEPS * BEAT, min: 0, max: 100, maxStep: 20, controlNodeId: DCW_PRESS },
378
+ { id: 'cv1', nodeId: CV_ID, role: 'cv', field: 'value', unit: 'μm', scale: 1, offset: 0, min: 0, max: 200 },
379
+ ],
380
+ timing: { beatMs: BEAT, historySteps: H, horizonSteps: F, fixedDt: true },
381
+ trainer: { ref: 'linear_arx@1', config: { arOrder: 1, inputOrder: 1, ridgeLambda: 1e-6, standardize: true } },
382
+ datasetPolicy: { split: { valRatio: 0.4, testRatio: 0.4, seed: 42 }, cleaning: { hampelK: 0 } },
383
+ gatePolicyRef: 'process-model.gates@1',
384
+ modelInterface: { id: 'linear_state_space', version: 1, inputSemantics: 'setpoint', mode: 'state_space' },
385
+ effectiveDomain: { mv: { mv1: { min: 0, max: 100, maxStep: 20 } }, cv: { cv1: { min: 0, max: 200 } } },
386
+ purpose: 'mpc_surrogate',
387
+ }
388
+ const specCreated = await api('POST', '/api/workshop/process-model/specs', spec, token)
389
+ const specPub = await api('POST', `/api/workshop/process-model/specs/${encodeURIComponent(SPEC)}/publish?version=1`, undefined, token)
390
+ check('M0.4', '过程 spec 登记+发布(求解器谱系前置)', specCreated.status === 200 && specPub.status === 200, `create=${specCreated.status}/${errCode(specCreated)} pub=${specPub.status}`)
391
+ }
392
+
393
+ // ════ M1 本体层:v1 发布 → 管理者修正 → v2 ════
394
+ console.log('\n=== M1 本体层(管理者修正路径) ===')
395
+ let draftId
396
+ const ontologyDoc = (overrides = {}) => ({
397
+ schemaVersion: 1,
398
+ name: `模型闭环验收-${TAG}`,
399
+ description: `膜厚闭环控制本体:压力/线速→膜厚,温区守门(${TAG})`,
400
+ lineId: line.id,
401
+ entities: [
402
+ { key: 'pv.melt_pressure', kind: 'process_variable', name: '熔体压力', description: '', unit: 'bar', dimension: 'pressure', role: 'control', attrs: { dataType: 'number' } },
403
+ { key: 'cv.thickness', kind: 'quality_variable', name: '平均膜厚', description: '', unit: 'μm', dimension: 'length', role: 'target', attrs: { dataType: 'number' } },
404
+ { key: 'st.line_speed', kind: 'process_variable', name: '线速度', description: '', unit: 'm/min', dimension: '', role: 'control', attrs: { dataType: 'number' } },
405
+ { key: 'st.zone_temp', kind: 'process_variable', name: '温区温度', description: '', unit: '℃', dimension: 'temperature', role: 'state', attrs: { dataType: 'number' } },
406
+ ],
407
+ relations: [
408
+ {
409
+ id: 'rel-1', kind: 'influences', srcKey: 'pv.melt_pressure', dstKey: 'cv.thickness', status: 'validated',
410
+ evidence: [{ id: 'ev-rel', level: 'validated_control', source: { type: 'optimizer_run', runId: 'run-live', problemIrHash: 'ir-live', modelArtifactHash: 'mdl-live' }, sourceRefHash: 'h', createdAt: new Date().toISOString() }],
411
+ properties: { sign: 'negative', gainPerUnit: -0.4, lagMs: 2 * DELAY_STEPS * BEAT, evidenceTier: 'validated_control', variabilityChecked: true },
412
+ },
413
+ ],
414
+ rules: [
415
+ {
416
+ id: 'R-BOUND', key: 'thickness-window', kind: 'bound',
417
+ dsl: { type: 'bound', variableKey: 'cv.thickness', min: 45, max: 55, unit: 'μm' },
418
+ constraintLevel: 'hard', severity: 'error', status: 'proposed',
419
+ evidence: [{ id: 'ev-bound', level: 'validated_control', source: { type: 'optimizer_run', runId: 'run-b', problemIrHash: 'ir', modelArtifactHash: 'mdl' }, sourceRefHash: 'h', createdAt: new Date().toISOString() }],
420
+ description: '膜厚工艺窗(μm)', scope: { lineId: line.id, recipeId: recipe.id, conditionId: '' },
421
+ },
422
+ {
423
+ id: 'R-GUARD', key: 'cold-zone-no-speedup', kind: 'state_condition',
424
+ dsl: { type: 'state_condition', when: { variableKey: 'st.zone_temp', op: 'lt', value: 180 }, forbid: { kind: 'positive_increment', variableKey: 'st.line_speed' }, message: '温区未达 180℃,禁止提速' },
425
+ constraintLevel: 'hard', severity: 'error', status: 'proposed',
426
+ evidence: [{ id: 'ev-guard', level: 'validated_control', source: { type: 'optimizer_run', runId: 'run-g', problemIrHash: 'ir', modelArtifactHash: 'mdl' }, sourceRefHash: 'h', createdAt: new Date().toISOString() }],
427
+ description: '冷区禁提速', scope: { lineId: line.id, recipeId: recipe.id, conditionId: '' },
428
+ },
429
+ ],
430
+ bindings: [
431
+ { id: 'b-press', entityKey: 'pv.melt_pressure', platformKind: 'dcw_node', platformId: DCW_PRESS, targetSub: '', scope: `line:${line.id}`, direction: 'write', unitDeclared: 'bar', unitTarget: 'bar', scale: 1, offset: 0 },
432
+ { id: 'b-speed', entityKey: 'st.line_speed', platformKind: 'dcw_node', platformId: DCW_SPEED, targetSub: '', scope: `line:${line.id}`, direction: 'write', unitDeclared: 'm/min', unitTarget: 'm/min', scale: 1, offset: 0 },
433
+ { id: 'b-cv', entityKey: 'cv.thickness', platformKind: 'daq_node', platformId: CV_ID, targetSub: '', scope: `line:${line.id}`, direction: 'read', unitDeclared: 'μm', unitTarget: 'μm', scale: 1, offset: 0 },
434
+ { id: 'b-temp', entityKey: 'st.zone_temp', platformKind: 'daq_node', platformId: TEMP_ID, targetSub: '', scope: `line:${line.id}`, direction: 'read', unitDeclared: '℃', unitTarget: '℃', scale: 1, offset: 0 },
435
+ ],
436
+ note: 'model-loop live e2e',
437
+ ...overrides,
438
+ })
439
+ async function approveRule(draft, ruleId) {
440
+ await api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draft)}/rules/${ruleId}/transition`, { to: 'reviewed' }, token)
441
+ await api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draft)}/rules/${ruleId}/transition`, { to: 'validated' }, token)
442
+ const ap = await api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draft)}/rules/${ruleId}/approval`, {}, token)
443
+ const apId = data(ap)?.approvalId ?? ''
444
+ await api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draft)}/rules/${ruleId}/approval-decision`, { approvalId: apId, approved: true }, token)
445
+ return api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draft)}/rules/${ruleId}/transition`, { to: 'approved_for_control', approvalId: apId }, token)
446
+ }
447
+ {
448
+ const created = await api('POST', '/api/workshop/ontology', { ontologyId: ONT, lineId: line.id, name: `模型闭环验收-${TAG}` }, token)
449
+ draftId = data(created)?.draft?.id ?? ''
450
+ const saved = await api('PATCH', `/api/workshop/ontology/drafts/${encodeURIComponent(draftId)}`, { doc: ontologyDoc(), expectedRev: 1 }, token)
451
+ check('M1.1', '本体起草(活体校验+绑定通过)', created.status === 200 && saved.status === 200 && data(saved)?.validation?.ok === true, `saved=${saved.status} issues=${JSON.stringify((data(saved)?.validation?.issues ?? []).filter(i => i.severity === 'error').slice(0, 2))}`)
452
+ const detail0 = data(await api('GET', `/api/workshop/ontology/drafts/${encodeURIComponent(draftId)}`, undefined, token))
453
+ check('M1.1b', '本体描述可读(用户理解模型代表什么)', String(detail0?.doc?.description ?? '').includes('膜厚闭环控制本体'), String(detail0?.doc?.description ?? '').slice(0, 60))
454
+ await approveRule(draftId, 'R-BOUND')
455
+ await approveRule(draftId, 'R-GUARD')
456
+ const pub1 = await api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draftId)}/publish`, {}, token)
457
+ check('M1.2', '本体 v1 发布(contentHash+packHash)', pub1.status === 200 && data(pub1)?.version?.version === 1, `${pub1.status}/${errCode(pub1)}`)
458
+
459
+ // 管理者修正:复用草稿(发布不改 rev,草稿仍可编辑;重复发布=新版本不可变语义),
460
+ // 把膜厚窗从 [45,55] 收到 [46,54],重走生命周期后发布 v2
461
+ const detail = data(await api('GET', `/api/workshop/ontology/drafts/${encodeURIComponent(draftId)}`, undefined, token))
462
+ const curRev = detail?.draft?.rev ?? 2
463
+ const doc2 = ontologyDoc()
464
+ doc2.rules[0].dsl.min = 46
465
+ doc2.rules[0].dsl.max = 54
466
+ doc2.rules[0].description = '膜厚工艺窗(管理者修正:收窄到 46-54μm)'
467
+ const saved2 = await api('PATCH', `/api/workshop/ontology/drafts/${encodeURIComponent(draftId)}`, { doc: doc2, expectedRev: curRev }, token)
468
+ await approveRule(draftId, 'R-BOUND')
469
+ await approveRule(draftId, 'R-GUARD')
470
+ const pub2 = await api('POST', `/api/workshop/ontology/drafts/${encodeURIComponent(draftId)}/publish`, {}, token)
471
+ check('M1.3', '管理者修正规则窗 → v2 发布', pub2.status === 200 && data(pub2)?.version?.version === 2, `saved=${saved2.status}/${errCode(saved2)} pub=${pub2.status}/${errCode(pub2)}`)
472
+ const messy = ontologyDoc()
473
+ messy.description = ''
474
+ for (const e of messy.entities) e.description = ''
475
+ for (const r of messy.rules) { r.description = ''; r.scope.lineId = '' }
476
+ for (const b of messy.bindings) b.scope = 'global'
477
+ const createFix = await invokeTool('ontology_draft_create', { ontology_id: `${ONT}-fix`, line_id: line.id, name: `修复验收-${TAG}` })
478
+ const createFixText = String(createFix?.data?.text ?? createFix?.data?.result?.text ?? createFix?.text ?? '')
479
+ const draft3 = (createFixText.match(/已创建草稿\s+(\S+?)\(/) ?? [])[1] ?? ''
480
+ const savedMessy = createFix ? await api('PATCH', `/api/workshop/ontology/drafts/${encodeURIComponent(draft3)}`, { doc: messy, expectedRev: 1 }, token) : { status: 0 }
481
+ const fixRes = await invokeTool('ontology_draft_autofix', { draft_id: draft3 })
482
+ const fixText = String(fixRes?.data?.text ?? fixRes?.data?.result?.text ?? fixRes?.text ?? JSON.stringify(fixRes ?? {}))
483
+ const fixErr = Boolean(fixRes?.isError ?? fixRes?.data?.isError)
484
+ check('M1.5', 'Agent 工具 ontology_draft_autofix:自动修复并落库', !fixErr && /自动修复 \d+ 项/.test(fixText), fixText.slice(0, 180))
485
+ const detail3 = data(await api('GET', `/api/workshop/ontology/drafts/${encodeURIComponent(draft3)}`, undefined, token))
486
+ check('M1.6', '修复后:描述/作用域已补齐且校验通过', Boolean(detail3?.doc?.description) && detail3?.validation?.ok === true && (detail3?.doc?.bindings ?? []).every(b => String(b.scope).startsWith('line:')), `desc=${String(detail3?.doc?.description ?? '').slice(0, 40)} savedMessy=${savedMessy.status}`)
487
+ const cmp = await api('GET', `/api/workshop/ontology/versions/${encodeURIComponent(ONT)}/compare?from=1&to=2`, undefined, token)
488
+ const changed = data(cmp)?.rules?.changed ?? []
489
+ check('M1.4', '四段 diff 反映管理者意志(R-BOUND changed)', cmp.status === 200 && changed.some(c => String(typeof c === 'string' ? c : (c.id ?? c.ruleId ?? '')).includes('R-BOUND')), JSON.stringify(changed).slice(0, 200))
490
+ }
491
+
492
+ // ════ M2 孪生层:Agent 工具创建虚拟模型全链 ════
493
+ console.log('\n=== M2 孪生层(Agent 工具创建虚拟模型) ===')
494
+ async function invokeTool(tool, args, timeoutMs = 180_000) {
495
+ return api('POST', '/api/workshop/agent-tools/invoke', { agentId: leadAgentIdOuter, tool, args }, token, timeoutMs)
496
+ }
497
+ const toolText = r => String(r?.data?.text ?? r?.data?.result?.text ?? r?.text ?? r?.message ?? JSON.stringify(r ?? {}).slice(0, 300))
498
+ const toolErr = r => Boolean(r?.isError ?? r?.data?.isError)
499
+ const artifactPathOf = (text) => {
500
+ const m = String(text).match(/artifact:\s*(\S+)/)
501
+ return m ? m[1] : ''
502
+ }
503
+ {
504
+ const disc = await invokeTool('twin_scene_discover', {})
505
+ check('M2.1', '工具 twin_scene_discover:从真实绑定发现场景', disc.status === 200 && !toolErr(disc) && toolText(disc).includes('nodeCount'), toolText(disc).slice(0, 160))
506
+
507
+ const comp = await invokeTool('twin_scene_compile', { scene_id: SCENE_ID, scene_version: '1.0.0', line_id: line.id, product_id: product.id, recipe_id: recipe.id, prompt: '膜厚闭环验收场景' })
508
+ const compText = toolText(comp)
509
+ check('M2.2', '工具 twin_scene_compile:SceneContract 草稿(controls+artifact)', comp.status === 200 && !toolErr(comp) && compText.includes('SceneContract Draft'), compText.slice(0, 200))
510
+
511
+ const { createTwinRepo } = await import('../server/services/workshop/aml/twin/repo')
512
+ const twinRepo = createTwinRepo(seedDb)
513
+ const sceneRow = twinRepo.getScene(SCENE_ID, '1.0.0')
514
+ const sceneJson = sceneRow ? JSON.parse(sceneRow.contractJson) : null
515
+ check('M2.3', '场景草稿持久化(控制面+目标面齐备,谱系可复用)', Boolean(sceneJson) && (sceneJson.controls ?? []).length >= 2 && (sceneJson.observations ?? []).some(v => v.role === 'target'), `controls=${sceneJson?.controls?.length} states=${sceneJson?.states?.length} obs=${sceneJson?.observations?.length}(targets=${(sceneJson?.observations ?? []).filter(v => v.role === 'target').length})`)
516
+
517
+ const frz = await invokeTool('twin_scene_freeze', { scene_id: SCENE_ID, scene_version: '1.0.0', approved_by: email, confirmation: 'USER_CONFIRMED_SCENE_CONTRACT' })
518
+ check('M2.4', '工具 twin_scene_freeze:人批准冻结(approvedBy=管理者)', frz.status === 200 && !toolErr(frz) && toolText(frz).includes('"status": "frozen"'), toolText(frz).slice(0, 200))
519
+ const noConfirm = await invokeTool('twin_scene_freeze', { scene_id: `${SCENE_ID}-x`, scene_version: '1.0.0' })
520
+ check('M2.5', '冻结治理红线:缺确认令牌 → 拒绝', toolErr(noConfirm) || toolText(noConfirm).includes('冻结被拒绝'), toolText(noConfirm).slice(0, 120))
521
+
522
+ const frozenRow = twinRepo.getScene(SCENE_ID, '1.0.0')
523
+ const frozenScene = JSON.parse(frozenRow.contractJson)
524
+
525
+ const draft = await invokeTool('twin_physics_spec_draft', { scene_json: frozenScene, dt_sec: BEAT / 1000 })
526
+ const draftArtifact = artifactPathOf(toolText(draft))
527
+ const physSpec = draftArtifact && existsSync(draftArtifact) ? JSON.parse(readFileSync(draftArtifact, 'utf8')) : null
528
+ check('M2.6', '工具 twin_physics_spec_draft:虚拟模型骨架(状态+参数可校准)', draft.status === 200 && !toolErr(draft) && Boolean(physSpec) && (physSpec.states ?? []).length >= 1 && (physSpec.parameters ?? []).length >= 1, toolText(draft).slice(0, 200))
529
+
530
+ const val = await invokeTool('twin_physics_spec_validate', { physics_spec: physSpec })
531
+ const valData = data(val) ?? {}
532
+ const valBody = valData.apiVersion ? valData : (val.data ?? {})
533
+ check('M2.7', '工具 twin_physics_spec_validate:valid=true', val.status === 200 && !toolErr(val) && (valBody.valid === true || String(toolText(val)).includes('"valid": true')), String(toolText(val)).slice(0, 160))
534
+
535
+ const compiled = await invokeTool('twin_physics_spec_compile', { physics_spec: physSpec, scene_json: frozenScene })
536
+ const compBody = data(compiled) ?? {}
537
+ check('M2.8', '工具 twin_physics_spec_compile:候选 Provider(candidate_not_registered)', compiled.status === 200 && !toolErr(compiled) && (compBody.status === 'candidate_not_registered' || String(toolText(compiled)).includes('candidate_not_registered')), String(toolText(compiled)).slice(0, 160))
538
+
539
+ // 频道谱系重链到真实冻结场景(训练通道冻结、优化通道复用的平台语义;走平台自有服务)。
540
+ // providerId 保留已注册的 injection-greybox-v1:声明式 Provider 仅为 candidate(工具明确
541
+ // 不直接注册投产),物理 rollout 由注入 greybox 承担;其观测 id 与本场景不映射 →
542
+ // 试验约束 fail-closed —— 正是「未注册 provider 不许投产」的治理语义,一并断言。
543
+ const { setHybridChannelProfile, getChannelTwinProfile } = await import('../server/services/workshop/aml/twin/channel-profile')
544
+ const prevProfile = getChannelTwinProfile(channelIdOuter)
545
+ setHybridChannelProfile({
546
+ ...prevProfile,
547
+ sceneId: SCENE_ID,
548
+ sceneVersion: '1.0.0',
549
+ sceneContract: frozenScene,
550
+ scenePackId: SCENE_ID,
551
+ providerId: 'injection-greybox-v1',
552
+ providerVersion: undefined,
553
+ providerHash: undefined,
554
+ // 显式清空代次:意图是「解析当前已注册的 injection-greybox」(见上注释);
555
+ // 沿用模板实例化时的旧 generation,dev(watch) 重启使注册代前进后解析会落空(fail-closed)
556
+ providerGeneration: undefined,
557
+ createdBy: 'e2e',
558
+ })
559
+ const profAfter = data(await api('GET', `/api/workshop/channels/${encodeURIComponent(channelIdOuter)}/twin-profile`, undefined, token))
560
+ check('M2.9', '频道场景谱系重链(REST 可读)', profAfter?.profile?.sceneId === SCENE_ID && profAfter?.profile?.profile === 'hybrid_twin', `sceneId=${profAfter?.profile?.sceneId}`)
561
+
562
+ writeFreshTail()
563
+ const snap = await invokeTool('twin_snapshot_create', { channel_id: channelIdOuter, auto_daq: true, phase: 'exploration' }, 120_000)
564
+ const snapId = (toolText(snap).match(/snapshot_id:\s*(\S+)/) ?? [])[1] ?? ''
565
+ check('M2.10', '工具 twin_snapshot_create:服务端真采快照(auto_daq,fresh)', snap.status === 200 && !toolErr(snap) && Boolean(snapId) && toolText(snap).includes('fresh: true'), toolText(snap).slice(0, 200))
566
+
567
+ const targetVars = (frozenScene.observations ?? []).filter(v => v.role === 'target')
568
+ const targetId = targetVars[0]?.id ?? (frozenScene.observations ?? [])[0]?.id ?? 'cv'
569
+ const controlIds = (frozenScene.controls ?? []).map(c => c.id)
570
+ const candidate = {}
571
+ if (controlIds[0]) candidate[controlIds[0]] = 60
572
+ const objective = {
573
+ schemaVersion: 1, createdAt: new Date().toISOString(), createdBy: leadAgentIdOuter, objectiveId: 'loop-e2e',
574
+ targets: { [targetId]: 50 }, weights: { [targetId]: 1 }, controlCosts: {}, horizonSteps: 4, trustRegion: {},
575
+ }
576
+ const trial = await invokeTool('twin_trial_run', { snapshot_id: snapId, objective, candidate_controls: [candidate] }, 120_000)
577
+ const trialText = toolText(trial)
578
+ check('M2.11', '工具 twin_trial_run:虚拟试验完成(模型驱动 rollout)', trial.status === 200 && !toolErr(trial) && trialText.includes('VirtualTrial 已完成'), trialText.slice(0, 220))
579
+ check('M2.12', '虚拟试验治理语义:candidateExecuted=false + 约束 fail-closed(候选 provider 未注册不投产)', trialText.includes('candidateExecuted=false') && trialText.includes('constraints_passed: false'), trialText.split('\n').filter(Boolean).slice(0, 4).join(' | '))
580
+ }
581
+
582
+ // ════ M3/M4 模型进化两轮(训练 → 工具采纳 → HITL → 发布重绑 → 新模型求解) ════
583
+ console.log('\n=== M3 模型进化第 1 轮 ===')
584
+ async function trainOnce(modelName) {
585
+ let ds = await api('POST', '/api/workshop/process-model/datasets', spec, token)
586
+ for (const backoff of [3000, 6000]) {
587
+ if (ds.status === 200) break
588
+ writeFreshTail()
589
+ await sleep(backoff)
590
+ ds = await api('POST', '/api/workshop/process-model/datasets', spec, token)
591
+ }
592
+ const datasetId = data(ds)?.datasetId
593
+ // 优化资格报告(solve 前置:模型须经资格评估,缺报告 → solve 422 不具备优化资格)
594
+ const elig = await api('POST', '/api/workshop/process-model/eligibility', { specId: SPEC, specVersion: 1, datasetId, scope: 'simulation' }, token)
595
+ const eligOk = data(elig)?.report?.optimizationEligible === true
596
+ const train = await api('POST', '/api/workshop/process-model/train', { spec, datasetId, modelName }, token)
597
+ const jobId = data(train)?.job?.id
598
+ let job = null
599
+ const terminal = new Set(['done', 'failed', 'cancelled', 'timeout', 'interrupted'])
600
+ for (let i = 0; i < 240; i++) {
601
+ const jr = await api('GET', `/api/workshop/aml/jobs/${encodeURIComponent(jobId)}`, undefined, token)
602
+ job = data(jr)?.job
603
+ if (job && terminal.has(job.status)) break
604
+ await sleep(500)
605
+ }
606
+ const models = await api('GET', `/api/workshop/aml/models?recipeId=${encodeURIComponent(recipe.id)}`, undefined, token)
607
+ const model = (data(models)?.models ?? []).find(m => m.id === (job?.modelId ?? ''))
608
+ return { datasetId, rowCount: data(ds)?.rowCount ?? 0, jobId, job, modelId: job?.modelId ?? '', artifactHash: model?.artifactHash ?? '', eligOk }
609
+ }
610
+ async function adoptRound(modelId, reason, description) {
611
+ const adoptInvoke = invokeTool('optimizer_profile_propose', { model_id: modelId, reason, profile_description: description }, 300_000)
612
+ let card = null
613
+ for (let i = 0; i < 60; i++) {
614
+ await sleep(500)
615
+ try {
616
+ const pending = await api('GET', '/api/workshop/agent-tools/approvals', undefined, token)
617
+ card = (data(pending)?.approvals ?? []).find(a => String(a.nodeId).startsWith('optimizer-profile:') && a.agentId === leadAgentIdOuter)
618
+ if (card) break
619
+ }
620
+ catch { /* 未就绪 */ }
621
+ }
622
+ if (!card) {
623
+ const adoptText = await adoptInvoke.catch(err => ({ text: `invoke rejected: ${String(err).slice(0, 120)}` }))
624
+ return { card: null, adoptText, dec: { status: 0 } }
625
+ }
626
+ const dec = await api('POST', `/api/workshop/agent-tools/approvals/${encodeURIComponent(card.id)}/decide`, { approved: true, choice: 0, comment: '模型进化闭环验收批准' }, token)
627
+ let adoptText
628
+ try {
629
+ adoptText = await adoptInvoke
630
+ }
631
+ catch (err) {
632
+ adoptText = { text: `invoke rejected: ${String(err).slice(0, 160)}` }
633
+ }
634
+ return { card, adoptText, dec }
635
+ }
636
+ let round1RowCount
637
+ {
638
+ // ── 第 1 轮:训练 A → Profile v1(A) → 发布 → 绑定 → 基线求解 ──
639
+ const ra = await trainOnce(`模型闭环A-${TAG}`)
640
+ trainedAId = ra.modelId
641
+ trainedAHash = ra.artifactHash
642
+ round1RowCount = ra.rowCount
643
+ const annotate = await invokeTool('aml_model_annotate', { model_id: ra.modelId, label: `膜厚模型A-${TAG}`, description: '产线A 膜厚预测:线性状态空间,适配保压/线速工况' })
644
+ const annotateText = toolText(annotate)
645
+ check('M3.0', 'Agent 工具 aml_model_annotate:补模型名称/描述', !toolErr(annotate) && annotateText.includes('人读身份已更新'), annotateText.slice(0, 140))
646
+ check('M3.1', '第 1 轮训练 done + 模型登记 + 优化资格(artifactHash)', ra.job?.status === 'done' && ra.eligOk && trainedAId && trainedAHash.length === 64, `status=${ra.job?.status} model=${trainedAId} rows=${ra.rowCount} err=${String(ra.job?.error ?? '').slice(0, 100)}`)
647
+
648
+ const profileBody = {
649
+ schemaVersion: 1, id: profileId, version: 1,
650
+ modelRef: { modelId: trainedAId, artifactKind: 'linear_state_space@1', artifactHash: trainedAHash, modelInterface: 'linear_state_space', stage: 'candidate' },
651
+ problemTemplateRef: 'linear_mpc_quadratic@1',
652
+ problemConfig: { linear_mpc_quadratic: { cvWeights: { cv1: 1 }, duWeights: { mv1: 0.1 }, terminalWeight: 2, targets: { cv1: 50 } } },
653
+ solverRef: 'osqp_mpc@1', solverVersion: '1',
654
+ processSpecRef: `${SPEC}@1`, conditionIds: [], status: 'draft',
655
+ }
656
+ const profCreated = await api('POST', '/api/workshop/optimization/profiles', profileBody, token)
657
+ const pub1 = await api('POST', `/api/workshop/optimization/profiles/${encodeURIComponent(profileId)}/publish?version=1`, undefined, token)
658
+ check('M3.2', 'Profile v1 创建(模型A 工件回填)+发布', profCreated.status === 200 && pub1.status === 200, `create=${profCreated.status}/${errCode(profCreated)} pub=${pub1.status}/${errCode(pub1)}`)
659
+ const bind = await api('POST', '/api/workshop/optimization/bindings', {
660
+ workspaceId: workspaceIdOuter, channelId: channelIdOuter, agentInstanceId: leadAgentIdOuter, profileId, profileVersion: 1, mode: 'recommendation',
661
+ }, token)
662
+ bindingId = data(bind)?.binding?.id ?? ''
663
+ check('M3.3', 'Agent↔Profile 绑定(revision=1,推荐模式)', bind.status === 200 && Boolean(bindingId), `id=${bindingId} code=${errCode(bind)}`)
664
+ writeFreshTail()
665
+ const solve0 = await api('POST', '/api/workshop/optimization/solve', { agentInstanceId: leadAgentIdOuter, bindingId }, token)
666
+ check('M3.4', '基线模型 A solve optimal', solve0.status === 200 && data(solve0)?.result?.status === 'optimal', `status=${data(solve0)?.result?.status} http=${solve0.status} msg=${String(solve0.message ?? '').slice(0, 120)}`)
667
+
668
+ // ── 第 2 轮:训练 B(反馈数据再积累)→ 工具采纳 → HITL → v2+重绑 → 新模型求解 ──
669
+ const rb = await trainOnce(`模型闭环B-${TAG}`)
670
+ trainedBId = rb.modelId
671
+ trainedBHash = rb.artifactHash
672
+ check('M3.5', '第 2 轮训练 done + 资格(数据集不缩水,工件不同)', rb.job?.status === 'done' && rb.eligOk && trainedBId && rb.rowCount >= round1RowCount && trainedBHash !== trainedAHash, `status=${rb.job?.status} rows ${round1RowCount}→${rb.rowCount} hashDiff=${trainedAHash !== trainedBHash}`)
673
+
674
+ const adopt1 = await adoptRound(trainedBId, '模型进化第 1 轮采纳:换上新训练模型 B', '产线A 膜厚闭环:线性 MPC(采纳模型B,提升 rollout 精度)')
675
+ check('M3.6', '采纳卡挂出(optimizer-profile:<id>@<v>)', Boolean(adopt1.card), `nodeId=${adopt1.card?.nodeId ?? 'none'}`)
676
+ check('M3.7', 'HITL 批准 → 单一咽喉发布+重绑', adopt1.dec.status === 200 && (JSON.stringify(adopt1.dec).includes('published') || JSON.stringify(adopt1.dec).includes('已发布')), JSON.stringify(adopt1.dec).slice(0, 300))
677
+ const adoptStr1 = String(adopt1.adoptText?.data?.text ?? adopt1.adoptText?.data?.result?.text ?? adopt1.adoptText?.text ?? JSON.stringify(adopt1.adoptText)).slice(0, 240)
678
+ check('M3.8', '工具回执:模型采纳完成(诚实汇报)', adoptStr1.includes('模型采纳完成'), adoptStr1)
679
+
680
+ const binds1 = (data(await api('GET', `/api/workshop/optimization/bindings?agentInstanceId=${encodeURIComponent(leadAgentIdOuter)}`, undefined, token))?.bindings ?? []).filter(b => b.profileId === profileId)
681
+ const cardV1 = Number(String(adopt1.card?.nodeId ?? '').split('@')[1])
682
+ const rebound1 = binds1.find(b => Number(b.profileVersionNumber) === cardV1)
683
+ check('M3.9', '绑定自动重绑到采纳版本(revision+1)', Boolean(rebound1) && Number(rebound1?.revision) >= 1, `versions=[${binds1.map(b => b.profileVersionNumber).join(',')}] card=v${cardV1} rev=${rebound1?.revision}`)
684
+ const profs1 = JSON.stringify(data(await api('GET', `/api/workshop/optimization/profiles?limit=50`, undefined, token)) ?? {})
685
+ check('M3.10', '已发布 Profile v2 携带新模型工件 B', profs1.includes(trainedBId), `len=${profs1.length}`)
686
+ check('M3.10b', 'Profile 描述由 Agent 提议写入并落版本台账', profs1.includes('产线A 膜厚闭环:线性 MPC(采纳模型B'), '')
687
+ writeFreshTail()
688
+ const solve1 = await api('POST', '/api/workshop/optimization/solve', { agentInstanceId: leadAgentIdOuter, bindingId: rebound1?.id }, token)
689
+ check('M3.11', '新模型 B solve optimal', solve1.status === 200 && data(solve1)?.result?.status === 'optimal', `status=${data(solve1)?.result?.status} http=${solve1.status} msg=${String(solve1.message ?? '').slice(0, 120)}`)
690
+ }
691
+
692
+ console.log('\n=== M4 模型进化第 2 轮(持续迭代) ===')
693
+ {
694
+ const rc = await trainOnce(`模型闭环C-${TAG}`)
695
+ trainedCId = rc.modelId
696
+ trainedCHash = rc.artifactHash
697
+ check('M4.1', '第 3 次训练 done + 资格(反馈持续积累)', rc.job?.status === 'done' && rc.eligOk && trainedCId && trainedCHash.length === 64, `status=${rc.job?.status} model=${trainedCId} rows=${rc.rowCount}`)
698
+
699
+ const adopt2 = await adoptRound(trainedCId, '模型进化第 2 轮采纳:持续迭代换新模型 C', '产线A 膜厚闭环:线性 MPC(采纳模型C,持续迭代)')
700
+ check('M4.2', '第 2 轮采纳卡挂出+HITL 批准', Boolean(adopt2.card) && adopt2.dec.status === 200, `nodeId=${adopt2.card?.nodeId ?? 'none'} dec=${adopt2.dec.status}`)
701
+ const adoptStr2 = String(adopt2.adoptText?.data?.text ?? adopt2.adoptText?.data?.result?.text ?? adopt2.adoptText?.text ?? JSON.stringify(adopt2.adoptText)).slice(0, 240)
702
+ check('M4.3', '第 2 轮工具回执:采纳完成', adoptStr2.includes('模型采纳完成'), adoptStr2)
703
+
704
+ const binds2 = (data(await api('GET', `/api/workshop/optimization/bindings?agentInstanceId=${encodeURIComponent(leadAgentIdOuter)}`, undefined, token))?.bindings ?? []).filter(b => b.profileId === profileId)
705
+ const cardV2 = Number(String(adopt2.card?.nodeId ?? '').split('@')[1])
706
+ const rebound2 = binds2.find(b => Number(b.profileVersionNumber) === cardV2)
707
+ check('M4.4', '持续进化:绑定再次重绑(revision 递增)', Boolean(rebound2) && Number(rebound2?.revision) >= 2, `versions=[${binds2.map(b => b.profileVersionNumber).join(',')}] card=v${cardV2} rev=${rebound2?.revision}`)
708
+ writeFreshTail()
709
+ const solve2 = await api('POST', '/api/workshop/optimization/solve', { agentInstanceId: leadAgentIdOuter, bindingId: rebound2?.id }, token)
710
+ check('M4.5', '第 2 轮新模型 C solve optimal', solve2.status === 200 && data(solve2)?.result?.status === 'optimal', `status=${data(solve2)?.result?.status} http=${solve2.status}`)
711
+
712
+ const writesPath = join(HOME, 'data', 'dcw-writes.json')
713
+ const writesLen = existsSync(writesPath) ? readFileSync(writesPath, 'utf8').length : 0
714
+ check('M4.6', '全闭环零 DCW 写入(三轮训练+两轮采纳+求解)', writesLen === 0, `dcw-writes.json ${writesLen ? '存在' : '不存在'}`)
715
+ }
716
+
717
+ // ════ M5 管理者面 REST ════
718
+ console.log('\n=== M5 管理者面 ===')
719
+ {
720
+ const versions = await api('GET', `/api/workshop/ontology/versions/${encodeURIComponent(ONT)}`, undefined, token)
721
+ check('M5.1', '本体版本台账(v1+v2,管理者可查)', versions.status === 200 && (data(versions)?.versions ?? []).length >= 2, `n=${(data(versions)?.versions ?? []).length}`)
722
+
723
+ const profs = await api('GET', `/api/workshop/optimization/profiles?limit=50`, undefined, token)
724
+ const profStr = JSON.stringify(data(profs) ?? {})
725
+ check('M5.2', 'Profile 版本台账含三轮模型工件(A/B/C 全可查)', profs.status === 200 && [trainedAId, trainedBId, trainedCId].every(id => profStr.includes(id)), `len=${profStr.length}`)
726
+
727
+ const twinProf = await api('GET', `/api/workshop/channels/${encodeURIComponent(channelIdOuter)}/twin-profile`, undefined, token)
728
+ check('M5.3', '孪生谱系台账(场景/冻结态可查)', twinProf.status === 200 && data(twinProf)?.profile?.sceneId === SCENE_ID, `sceneId=${data(twinProf)?.profile?.sceneId}`)
729
+
730
+ const audit = await api('GET', '/api/workshop/audit?limit=500', undefined, token)
731
+ const entries = data(audit)?.entries ?? []
732
+ const adoptEntries = entries.filter(e => String(e.action).startsWith('optimizer.profile.adopt'))
733
+ const kinds = new Set(adoptEntries.map(e => e.actorKind))
734
+ check('M5.4', '审计三态留痕:AI 提议 + 人批准(adopt_propose+adopt)', adoptEntries.length >= 2 && kinds.has('agent'), `n=${adoptEntries.length} actions=${adoptEntries.map(e => e.action).join(',')} kinds=${[...kinds].join(',')}`)
735
+
736
+ const ontAudit = entries.filter(e => String(e.action).includes('ontology'))
737
+ check('M5.5', '本体审计留痕(起草/发布/修正)', ontAudit.length >= 1, `n=${ontAudit.length} sample=${ontAudit[0]?.action ?? '-'}`)
738
+ }
739
+
740
+ // ════ M6 前端渲染走查(管理者查看) ════
741
+ console.log('\n=== M6 前端渲染 ===')
742
+ process.env.AW_BASE = BASE
743
+ {
744
+ const { launch, openPage, gotoReady } = await import('./ui/lib.mjs')
745
+ const browser = await launch({ width: 1600, height: 1000 })
746
+ const page = await openPage(browser, { token, width: 1600, height: 1000, deviceScaleFactor: 1 })
747
+ const pageErrors = []
748
+ page.on('pageerror', e => pageErrors.push(String(e.message).slice(0, 200)))
749
+ const shot = name => page.screenshot({ path: join(EVID, `${name}.png`), fullPage: true })
750
+ try {
751
+ const targets = [['/optimizer', 'optimizer'], ['/aml', 'aml'], ['/ontology', 'ontology']]
752
+ let allOk = true
753
+ const detail = []
754
+ const bodies = {}
755
+ for (const [path, name] of targets) {
756
+ const errsBefore = pageErrors.length
757
+ await gotoReady(page, path, { wait: 2500 })
758
+ await sleep(800)
759
+ const bodyLen = await page.evaluate(() => (document.body.textContent ?? '').length)
760
+ bodies[name] = await page.evaluate(() => document.body.textContent ?? '')
761
+ const ok = pageErrors.length === errsBefore && bodyLen > 400
762
+ detail.push(`${name}:len=${bodyLen},errs=${pageErrors.length - errsBefore}`)
763
+ if (!ok) allOk = false
764
+ await shot(`page-${name}`)
765
+ }
766
+ check('M6.1', '管理者三台(/optimizer /aml /ontology)渲染无错', allOk, detail.join(' '))
767
+ // 数据异步加载:轮询等待关键文案(最多 10s),并切到 Profile tab
768
+ const waitText = async (needle, timeoutMs = 10_000) => {
769
+ const t0 = Date.now()
770
+ while (Date.now() - t0 < timeoutMs) {
771
+ const hit = await page.evaluate(n => (document.body.textContent ?? '').includes(n), needle)
772
+ if (hit) return true
773
+ await sleep(500)
774
+ }
775
+ return false
776
+ }
777
+ await gotoReady(page, '/optimizer', { wait: 2500 })
778
+ await page.evaluate(() => {
779
+ const btn = Array.from(document.querySelectorAll('button')).find(b => (b.textContent || '').includes('Profile'))
780
+ if (btn) btn.click()
781
+ })
782
+ await sleep(600)
783
+ const profileDescVisible = await waitText('产线A 膜厚闭环')
784
+ check('M6.3', 'UI:Profile 描述在 /optimizer 台账可见', profileDescVisible)
785
+ await shot('page-optimizer-profile')
786
+
787
+ await gotoReady(page, '/aml', { wait: 2500 })
788
+ const amlDescVisible = await waitText('产线A 膜厚预测', 12_000)
789
+ check('M6.4', 'UI:模型描述在 /aml 台账可见', amlDescVisible)
790
+ await shot('page-aml-models')
791
+
792
+ await gotoReady(page, '/ontology', { wait: 2500 })
793
+ const ontoDescVisible = (await waitText('膜厚闭环控制本体', 6000)) || (await waitText('(产线 ln-', 4000))
794
+ const fixBtnVisible = await page.evaluate(() => (document.body.textContent ?? '').includes('自动修复'))
795
+ check('M6.5', 'UI:本体描述与「自动修复」入口在 /ontology 可见', ontoDescVisible && fixBtnVisible, `desc=${ontoDescVisible} fixBtn=${fixBtnVisible}`)
796
+ await shot('page-ontology-desc')
797
+ check('M6.2', '全程无未捕获 pageerror', pageErrors.length === 0 || pageErrors.every(e => e.includes('dispose')), pageErrors.slice(0, 2).join(';'))
798
+ }
799
+ finally {
800
+ await browser.close().catch(() => {})
801
+ }
802
+ }
803
+
804
+ // ════ 报告 ════
805
+ const pass = results.filter(r => r.pass).length
806
+ const report = {
807
+ script: 'scripts/e2e-model-loop-live.mjs',
808
+ generatedAt: new Date().toISOString(),
809
+ base: BASE,
810
+ home: HOME,
811
+ ontology: ONT,
812
+ profileId,
813
+ sceneId: SCENE_ID,
814
+ lineId: line.id,
815
+ modelA: { id: trainedAId, artifactHash: trainedAHash },
816
+ modelB: { id: trainedBId, artifactHash: trainedBHash },
817
+ modelC: { id: trainedCId, artifactHash: trainedCHash },
818
+ total: results.length,
819
+ pass,
820
+ fail: results.length - pass,
821
+ results,
822
+ }
823
+ writeFileSync(join(EVID, 'report.json'), JSON.stringify(report, null, 2))
824
+ console.log(`\nMODEL-LOOP LIVE E2E: ${pass}/${results.length} passed, ${results.length - pass} failed`)
825
+ console.log(`evidence: ${EVID}`)
826
+ killTree(child.pid)
827
+ process.exit(results.some(r => !r.pass) ? 1 : 0)