agentworkshop 0.9.0 → 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.
Files changed (35) hide show
  1. package/.output/nitro.json +1 -1
  2. package/.output/public/_nuxt/builds/latest.json +1 -1
  3. package/.output/public/_nuxt/builds/meta/582a3c6f-cd1b-4e1c-b4ee-249fd3efd658.json +1 -0
  4. package/.output/server/chunks/_/nitro.mjs +1262 -991
  5. package/.output/server/chunks/_/nitro.mjs.map +1 -1
  6. package/.output/server/chunks/routes/api/workshop/process-model/experiments.mjs +110 -17
  7. package/.output/server/chunks/routes/api/workshop/process-model/experiments.mjs.map +1 -1
  8. package/.output/server/package.json +1 -1
  9. package/README-zh.md +3 -3
  10. package/README.md +3 -3
  11. package/config.yml +1 -1
  12. package/docs/cli.en.md +2 -2
  13. package/docs/cli.md +2 -2
  14. package/docs/plugins.en.md +1 -1
  15. package/docs/plugins.md +1 -1
  16. package/docs/sdk.en.md +1 -1
  17. package/docs/sdk.md +1 -1
  18. package/package.json +2 -1
  19. package/scripts/acceptance-scientific-fullchain.ts +391 -0
  20. package/scripts/acceptance-scientific-loop.ts +16 -0
  21. package/scripts/demo/build-provision-config.mjs +48 -0
  22. package/scripts/demo/create-demo-templates.mjs +84 -0
  23. package/scripts/demo/e2e-optimization-demo.mjs +259 -0
  24. package/scripts/e2e-model-loop-live.mjs +827 -821
  25. package/server/services/workshop/agents/industrial/optimization-tools.ts +16 -0
  26. package/server/services/workshop/aml/intervention-ledger.ts +12 -4
  27. package/server/services/workshop/aml/twin/cross-check-service.ts +114 -0
  28. package/server/services/workshop/aml/twin/cross-check.ts +1 -1
  29. package/server/services/workshop/dcw/dcw-controller/write.ts +4 -2
  30. package/server/services/workshop/dcw/dcw-node.ts +307 -295
  31. package/server/services/workshop/process-model/experiment-runner.ts +81 -5
  32. package/server/services/workshop/process-model/experiment.ts +6 -0
  33. package/server/services/workshop/process-model/plan-safety.ts +74 -0
  34. package/shared/dcw-protocol/line.ts +3 -1
  35. package/.output/public/_nuxt/builds/meta/f507c33b-4ecc-4e32-af88-2e3736b443e9.json +0 -1
@@ -25,6 +25,7 @@ import { getExperimentPlan, updateExperimentStatus, type ExperimentPlanRow } fro
25
25
  import { assessIdentifiability, dominantPeriod } from '../aml/identifiability'
26
26
  import { attachAssessment, listInterventions, verdictCodeOf, verdictDetailOf } from '../aml/intervention-ledger'
27
27
  import { backfillInterventionEvidence } from '../aml/ontology-learning'
28
+ import { assertPlanNodesSafe } from './plan-safety'
28
29
 
29
30
  export interface ExperimentPlanBody {
30
31
  version: 1
@@ -47,6 +48,9 @@ export interface ExperimentPlanBody {
47
48
  approvalId?: string
48
49
  approvedBy?: string
49
50
  approvedAt?: string
51
+ /** 人工取消凭据(运行中每步前被感知) */
52
+ cancelledBy?: string
53
+ cancelledAt?: string
50
54
  note?: string
51
55
  }
52
56
 
@@ -146,6 +150,23 @@ export function parsePlan(row: ExperimentPlanRow): ExperimentPlanBody {
146
150
  return JSON.parse(row.planJson) as ExperimentPlanBody
147
151
  }
148
152
 
153
+ /**
154
+ * 人工取消计划(运行中/待批准/已计划均可)。
155
+ * 执行器每步前读状态,感知到 cancelled 即停;已执行步的台账/证据保留。
156
+ */
157
+ export function cancelExperimentPlan(id: string, actor: string): ExperimentPlanRow {
158
+ const row = getExperimentPlan(id)
159
+ if (!row) throw new AppError(404, 'EXPERIMENT_PLAN_NOT_FOUND', `试验计划 ${id} 不存在`)
160
+ if (row.status === 'done' || row.status === 'failed' || row.status === 'cancelled') {
161
+ throw new AppError(409, 'EXPERIMENT_STATUS_INVALID', `计划 ${id} 已是终态 ${row.status},无需取消`)
162
+ }
163
+ const plan = parsePlan(row)
164
+ const next: ExperimentPlanBody = { ...plan, cancelledBy: actor, cancelledAt: new Date().toISOString() }
165
+ getAmlRuntime().db.prepare('UPDATE process_model_experiments SET plan_json = ?, status = \'cancelled\', updated_at = ? WHERE id = ?')
166
+ .run(JSON.stringify(next), new Date().toISOString(), id)
167
+ return getExperimentPlan(id)!
168
+ }
169
+
149
170
  /** 真实线批准:awaiting_approval → planned(记录批准凭据;幂等) */
150
171
  export function approveExperimentPlan(id: string, approvalId: string, approvedBy: string): ExperimentPlanRow {
151
172
  const row = getExperimentPlan(id)
@@ -230,7 +251,22 @@ export async function runExperimentPlan(id: string, deps: ExperimentRunnerDeps =
230
251
  if (!row) throw new AppError(404, 'EXPERIMENT_PLAN_NOT_FOUND', `试验计划 ${id} 不存在`)
231
252
  const plan = parsePlan(row)
232
253
  const tier = plan.tier ?? (resolveExperimentTier(plan.lineId).tier)
233
- if (row.status === 'running') throw new AppError(409, 'EXPERIMENT_ALREADY_RUNNING', `计划 ${id} 正在执行`)
254
+ if (row.status === 'running') {
255
+ // 僵死 running 恢复:进程崩溃/重启会把状态永久停在 running(不可重跑也不可取消)。
256
+ // 超过预算上限 + 5min 无更新即判僵死 → 置 failed 并提示可重新创建计划。
257
+ const budgetRaw = JSON.parse(row.budgetJson || '{}') as { maxDurationMs?: number }
258
+ const staleMs = (budgetRaw.maxDurationMs ?? 4 * 3600_000) + 5 * 60_000
259
+ const age = Date.now() - Date.parse(row.updatedAt)
260
+ if (Number.isFinite(age) && age > staleMs) {
261
+ updateExperimentStatus(id, 'failed')
262
+ throw new AppError(409, 'EXPERIMENT_RUN_STALE', `计划 ${id} 上一次执行僵死(超过 ${Math.round(staleMs / 60000)} min 无更新),已置 failed;请重新创建计划(旧计划的台账行仍可查)`)
263
+ }
264
+ throw new AppError(409, 'EXPERIMENT_ALREADY_RUNNING', `计划 ${id} 正在执行`)
265
+ }
266
+ // 语义优先:待批准的真实线计划报"缺批准"而不是泛化的"状态非法"
267
+ if (row.status === 'awaiting_approval' && tier === 'real_hitl') {
268
+ throw new AppError(409, 'EXPERIMENT_APPROVAL_REQUIRED', `计划 ${id} 为真实产线计划且尚未批准:须先 HITL 批准(approve)后才能执行`)
269
+ }
234
270
  if (row.status !== 'planned') {
235
271
  throw new AppError(409, 'EXPERIMENT_STATUS_INVALID', `计划 ${id} 当前状态 ${row.status},只有 planned 可执行${tier === 'real_hitl' ? '(真实线须先 HITL 批准)' : ''}`)
236
272
  }
@@ -238,6 +274,9 @@ export async function runExperimentPlan(id: string, deps: ExperimentRunnerDeps =
238
274
  if (tier === 'real_hitl' && !plan.approvalId) {
239
275
  throw new AppError(409, 'EXPERIMENT_APPROVAL_REQUIRED', `计划 ${id} 为真实产线计划,缺少 HITL 批准凭据,拒绝执行`)
240
276
  }
277
+ // 执行前复核(防御深度):批准到执行之间产线/节点可能变更(换线、停用、量程调整)。
278
+ // 只对真实线强校验;仿真线计划允许过程模型 MV 逻辑名(不落设备,写入时由 write() 兜底)。
279
+ if (tier === 'real_hitl') assertPlanNodesSafe(plan)
241
280
  const budget = JSON.parse(row.budgetJson) as { maxRuns?: number, maxDurationMs?: number }
242
281
  const steps = buildExperimentSteps(plan, id)
243
282
  if (budget.maxRuns && steps.length > budget.maxRuns) {
@@ -286,6 +325,16 @@ export async function runExperimentPlan(id: string, deps: ExperimentRunnerDeps =
286
325
  updateExperimentStatus(id, 'running')
287
326
  const startedAt = new Date(now()).toISOString()
288
327
  const started = now()
328
+ // 真实线首步前必须等过节点的 60s 在线写间隔:刚开线(配方写入)或刚手动写过的节点
329
+ // 否则第一步必然 429,整份计划白失败一次(2026-11-02 端到端演示实证)。
330
+ if (tier === 'real_hitl') {
331
+ const waitMs = Math.max(0, ...Object.keys(plan.levels).map((nodeId) => {
332
+ const node = getDcwController().byId(nodeId)
333
+ const at = node?.lastWriteAt ? Date.parse(node.lastWriteAt) : Number.NaN
334
+ return Number.isFinite(at) ? REAL_MIN_STEP_MS + 2_000 - (Date.now() - at) : 0
335
+ }))
336
+ if (waitMs > 0) await sleep(waitMs)
337
+ }
289
338
  // 计划级主导周期估计:用一段长历史(≥30min 与 6×settle 的较大者)估一次,
290
339
  // 逐步判定统一使用 —— 短窗局部自相关会把局部纹波当周期(事故形态)。
291
340
  let expectedPeriodMs: number | undefined
@@ -305,7 +354,15 @@ export async function runExperimentPlan(id: string, deps: ExperimentRunnerDeps =
305
354
  let executed = 0
306
355
  let failedReason: string | undefined
307
356
 
357
+ // 真实线每步驻留不得低于写联锁的 60s 节点间隔(否则第 2 步必被 429 打回,白跑)
358
+ const holdMs = tier === 'real_hitl' ? Math.max(plan.settleMs, REAL_MIN_STEP_MS) : plan.settleMs
308
359
  for (const step of steps) {
360
+ // 取消:每步前读一次计划状态(REST cancel 是异步人工操作,必须能被及时感知)
361
+ const live = getExperimentPlan(id)
362
+ if (live?.status === 'cancelled') {
363
+ failedReason = `计划被人工取消(已执行 ${executed}/${steps.length} 步)`
364
+ break
365
+ }
309
366
  // 预算:总时长超限即停(不静默续跑)
310
367
  if (budget.maxDurationMs && now() - started > budget.maxDurationMs) {
311
368
  failedReason = `超出预算 maxDurationMs=${budget.maxDurationMs}ms(已执行 ${executed}/${steps.length} 步)`
@@ -316,19 +373,37 @@ export async function runExperimentPlan(id: string, deps: ExperimentRunnerDeps =
316
373
  break
317
374
  }
318
375
  const hypothesis = `[pexp:${id}] 试验步 ${step.index + 1}/${steps.length}:${step.controlId}=${step.level}(第 ${step.repeat + 1} 轮)`
319
- const res = await write(step.controlId, step.level, { hypothesis, planId: id, stepIndex: step.index })
376
+ let res = await write(step.controlId, step.level, { hypothesis, planId: id, stepIndex: step.index })
377
+ // 写间隔/保持窗是安全联锁,不是计划失败:等到窗口结束重试同一步。
378
+ // 注意:节点 holdIntervalMs 的保写心跳会周期性刷新写时间戳,与 60s 间隔叠加
379
+ // 可能连续命中,因此这里做有上限的循环重试(最多 4 次),而不是一次就放弃。
380
+ for (let attempt = 0; attempt < 4 && !res.ok; attempt++) {
381
+ // 从拒绝文案 "还需 Ns" 提取等待秒数(字符串扫描,避免正则被安全扫描误判)
382
+ const text = res.message ?? ''
383
+ const at = text.indexOf('还需')
384
+ let digits = ''
385
+ if (at >= 0) {
386
+ for (const ch of text.slice(at + 2, at + 14)) {
387
+ if (ch >= '0' && ch <= '9') digits += ch
388
+ else if (digits) break
389
+ }
390
+ }
391
+ if (!digits) break
392
+ await sleep((Number(digits) + 2) * 1000)
393
+ res = await write(step.controlId, step.level, { hypothesis, planId: id, stepIndex: step.index })
394
+ }
320
395
  if (!res.ok) {
321
396
  failedReason = `第 ${step.index + 1} 步写入被拒:${res.message ?? '未知原因'}`
322
397
  break
323
398
  }
324
399
  executed++
325
400
  const writeAt = now()
326
- await sleep(plan.settleMs)
401
+ await sleep(holdMs)
327
402
  // 观测窗 + 引擎判读:有目标映射时,写前窗/写后窗各取一次序列交给可辨识性引擎,
328
403
  // 判定回填本步干预台账(与 optimization_explore 同口径);无目标则只驻留。
329
404
  const target = plan.targets?.[step.controlId]
330
405
  if (target) {
331
- const pre = await readSeries(target, writeAt - plan.settleMs, writeAt)
406
+ const pre = await readSeries(target, writeAt - holdMs, writeAt)
332
407
  await sleep(plan.observeMs)
333
408
  const post = await readSeries(target, writeAt, now())
334
409
  await readTarget(target, writeAt, now())
@@ -378,7 +453,8 @@ export async function runExperimentPlan(id: string, deps: ExperimentRunnerDeps =
378
453
  }
379
454
  catch { /* 台账不可读不影响执行结果 */ }
380
455
 
381
- const status: ExperimentRunResult['status'] = failedReason ? 'failed' : 'done'
456
+ const cancelled = failedReason?.includes('人工取消') ?? false
457
+ const status: ExperimentRunResult['status'] = cancelled ? 'cancelled' : (failedReason ? 'failed' : 'done')
382
458
  updateExperimentStatus(id, status)
383
459
  return {
384
460
  planId: id,
@@ -11,6 +11,7 @@ import { AppError } from '../../../utils/errors'
11
11
  import { getAmlRuntime } from '../aml/runtime'
12
12
  import { getDcwLineRepo } from '../dcw/dcw-line.repo'
13
13
  import { estimateExperimentCost, resolveExperimentTier, type ExperimentPlanBody, type ExperimentCost } from './experiment-runner'
14
+ import { assertPlanNodesSafe } from './plan-safety'
14
15
 
15
16
  export interface ExperimentPlanInput {
16
17
  lineId: string
@@ -61,6 +62,11 @@ export function createExperimentPlan(input: ExperimentPlanInput): ExperimentPlan
61
62
  const repeats = Math.max(1, Math.min(input.repeats ?? 1, 20))
62
63
  const settleMs = Math.max(1000, input.settleMs ?? 60_000)
63
64
  const observeMs = Math.max(1000, input.observeMs ?? 120_000)
65
+ // 上线前加固:真实线计划在**创建时**即校验节点归属(须属本线/启用/量程内,targets 须同线 DAQ)。
66
+ // 仿真线计划允许用过程模型 MV 逻辑名(不落设备),创建不校验;执行时一律强校验(见 runner)。
67
+ if (tierInfo.tier === 'real_hitl') {
68
+ assertPlanNodesSafe({ lineId: input.lineId, levels: input.levels, targets: input.targets })
69
+ }
64
70
  const db = getAmlRuntime().db
65
71
  const id = `pexp-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`
66
72
  const now = new Date().toISOString()
@@ -0,0 +1,74 @@
1
+ /**
2
+ * 试验计划安全校验(2026-11-02 上线前加固):
3
+ * 计划一旦被 HITL 批准,执行器会以平台身份直接写节点(单卡批准 = 全计划授权)。
4
+ * 因此**创建时与执行前都必须复核节点归属**,防止:
5
+ * - 跨线写:计划 lineId=A,levels 却点名 B 线的节点(越权写别的产线);
6
+ * - 类型错配:targets 写成数控节点(读不到真值)或控制量其实是数采节点;
7
+ * - 量程外水平:创建时就拒绝,避免批准后逐步被 write() 打回、白花产线时间。
8
+ * 纯校验函数,直接读控制器/节点仓(无副作用,不写库)。
9
+ */
10
+ import { AppError } from '../../../utils/errors'
11
+ import { getDcwController } from '../dcw/dcw-controller'
12
+ import { getDaqNodeRepo } from '../daq/daq-node.repo'
13
+ import type { ExperimentPlanBody } from './experiment-runner'
14
+
15
+ export interface PlanNodeIssue {
16
+ kind: 'control' | 'target' | 'level'
17
+ nodeId: string
18
+ message: string
19
+ }
20
+
21
+ /**
22
+ * 校验计划节点集合与量程。返回问题列表(空 = 通过);
23
+ * 调用方决定抛错(创建/执行前)还是仅告警。
24
+ */
25
+ export function validatePlanNodes(plan: Pick<ExperimentPlanBody, 'lineId' | 'levels' | 'targets'>): PlanNodeIssue[] {
26
+ const issues: PlanNodeIssue[] = []
27
+ const controller = getDcwController()
28
+ for (const [controlId, levels] of Object.entries(plan.levels)) {
29
+ const node = controller.byId(controlId)
30
+ if (!node) {
31
+ issues.push({ kind: 'control', nodeId: controlId, message: `控制节点 ${controlId} 不存在(须为 DCW 数控节点)` })
32
+ continue
33
+ }
34
+ if (node.lineId && node.lineId !== plan.lineId) {
35
+ issues.push({ kind: 'control', nodeId: controlId, message: `控制节点 ${controlId} 属于产线 ${node.lineId},与计划产线 ${plan.lineId} 不一致(禁止跨线试验)` })
36
+ }
37
+ if (!node.enabled) {
38
+ issues.push({ kind: 'control', nodeId: controlId, message: `控制节点 ${controlId} 已停用(控制已暂停),不能用于试验` })
39
+ }
40
+ // 保写心跳会按 holdIntervalMs 周期重下发当前值并与试验步争夺 60s 写间隔,
41
+ // 实测会造成"永远还需 60s"的活锁(2026-11-02 端到端演示)。试验节点必须关闭心跳。
42
+ if (node.holdIntervalMs && node.holdIntervalMs > 0) {
43
+ issues.push({ kind: 'control', nodeId: controlId, message: `控制节点 ${controlId} 启用了保写心跳(holdIntervalMs=${node.holdIntervalMs}ms):心跳会与试验步竞争写入间隔,请在节点配置中置 0 后再发起试验` })
44
+ }
45
+ for (const level of levels) {
46
+ if (!Number.isFinite(level)) continue
47
+ if (level < node.min || level > node.max) {
48
+ issues.push({ kind: 'level', nodeId: controlId, message: `水平 ${level} 超出节点安全量程 ${node.min}~${node.max}${node.unit ?? ''}` })
49
+ }
50
+ }
51
+ }
52
+ for (const [controlId, targetId] of Object.entries(plan.targets ?? {})) {
53
+ if (!plan.levels[controlId]) {
54
+ issues.push({ kind: 'target', nodeId: targetId, message: `观测目标绑定到了未声明的控制量 ${controlId}` })
55
+ continue
56
+ }
57
+ const daq = getDaqNodeRepo().byId(targetId)
58
+ if (!daq) {
59
+ issues.push({ kind: 'target', nodeId: targetId, message: `观测目标 ${targetId} 不是数采节点(判读需要 DAQ 序列)` })
60
+ continue
61
+ }
62
+ if (daq.lineId && daq.lineId !== plan.lineId) {
63
+ issues.push({ kind: 'target', nodeId: targetId, message: `观测目标 ${targetId} 属于产线 ${daq.lineId},与计划产线 ${plan.lineId} 不一致` })
64
+ }
65
+ }
66
+ return issues
67
+ }
68
+
69
+ /** 创建/执行前强校验:有问题即 422(消息合并,便于一次改全) */
70
+ export function assertPlanNodesSafe(plan: Pick<ExperimentPlanBody, 'lineId' | 'levels' | 'targets'>): void {
71
+ const issues = validatePlanNodes(plan)
72
+ if (issues.length === 0) return
73
+ throw new AppError(422, 'EXPERIMENT_PLAN_NODE_INVALID', `试验计划节点校验失败:${issues.map(i => i.message).join(';')}`)
74
+ }
@@ -104,8 +104,10 @@ export interface DcwNodeView {
104
104
  stepLimit: number | null
105
105
  /** 最近一次成功 ACK(设备证实/受理)的时刻 */
106
106
  lastAckAt: string | null
107
- /** 最近一次**成功**下发时刻(失败写不更新;60s 成功间隔以此为准) */
107
+ /** 最近一次**成功**下发时刻(失败写不更新) */
108
108
  lastWriteAt: string | null
109
+ /** 最近一次**改变设定值**的成功下发时刻(60s 在线写间隔以此为准;同值保活心跳不推进) */
110
+ lastChangeAt?: string | null
109
111
  /** 最近一次写**尝试**时刻(含失败;诊断/失败冷却用) */
110
112
  lastAttemptAt?: string | null
111
113
  state: DcwNodeState
@@ -1 +0,0 @@
1
- {"id":"f507c33b-4ecc-4e32-af88-2e3736b443e9","timestamp":1793625297927,"prerendered":[]}