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
@@ -0,0 +1,259 @@
1
+ /**
2
+ * 端到端优化作业演示(真实平台 + PLC 模拟器孪生,modbus-tcp):
3
+ *
4
+ * 观测 → DoE 计划(真实线,HITL 单卡) → 未批准被拒 → 批准 → 随机化执行(3 步)
5
+ * → 引擎判读回填台账 → 判定回灌本体证据 → 由实测增益计算目标 SP → 下发生效
6
+ * → 重量进入目标窗(控得好)
7
+ *
8
+ * 前置:平台实例已开线、模拟器孪生已接入(provision-line 完成)。
9
+ * 用法:
10
+ * node scripts/demo/e2e-optimization-demo.mjs \
11
+ * --base http://127.0.0.1:3960 --home D:/tmp/aw-demo-home \
12
+ * --line ln-xxx --dcw dw-xxx --daq dn-xxx --email .. --pass .. \
13
+ * [--out docs/audit/evidence/2026-11-02-e2e-optimization-demo/report.json]
14
+ *
15
+ * 目标窗:32.00–32.30 g(演示设定);基线 SP=50 → ≈31.78 g(低于窗)。
16
+ */
17
+ import { DatabaseSync } from 'node:sqlite'
18
+ import { join } from 'node:path'
19
+ import { writeFileSync, mkdirSync } from 'node:fs'
20
+
21
+ const args = process.argv.slice(2)
22
+ const argOf = (k, d = '') => {
23
+ const i = args.indexOf(k)
24
+ return i >= 0 && args[i + 1] && !args[i + 1].startsWith('--') ? args[i + 1] : d
25
+ }
26
+ const BASE = argOf('--base', 'http://127.0.0.1:3960')
27
+ const HOME = argOf('--home')
28
+ const LINE = argOf('--line')
29
+ const DCW = argOf('--dcw')
30
+ const DAQ = argOf('--daq')
31
+ const OUT = argOf('--out', 'docs/audit/evidence/2026-11-02-e2e-optimization-demo/report.json')
32
+ const WINDOW = { lo: 32.0, hi: 32.3 }
33
+ const LEVELS = [50, 55, 60]
34
+ process.env.NO_PROXY = '127.0.0.1,localhost'
35
+
36
+ let pass = 0
37
+ const failures = []
38
+ const checks = []
39
+ function check(id, name, cond, detail = '') {
40
+ if (cond) {
41
+ pass++
42
+ checks.push({ id, name, detail })
43
+ console.log(` PASS ${id} ${name}${detail ? ` — ${detail}` : ''}`)
44
+ }
45
+ else {
46
+ failures.push(`${id} ${name}: ${detail}`)
47
+ console.log(` FAIL ${id} ${name} — ${detail}`)
48
+ }
49
+ }
50
+ const sleep = ms => new Promise(r => setTimeout(r, ms))
51
+
52
+ let token = process.env.AW_TOKEN ?? ''
53
+ async function login() {
54
+ if (token) return
55
+ const r = await fetch(`${BASE}/api/users/login`, {
56
+ method: 'POST',
57
+ headers: { 'content-type': 'application/json' },
58
+ body: JSON.stringify({ email: argOf('--email'), password: argOf('--pass') }),
59
+ })
60
+ const j = await r.json()
61
+ token = j?.data?.token
62
+ if (!token) throw new Error(`登录失败:${JSON.stringify(j).slice(0, 200)}`)
63
+ }
64
+ async function api(method, path, body) {
65
+ const r = await fetch(`${BASE}${path}`, {
66
+ method,
67
+ headers: { 'content-type': 'application/json', 'authorization': `Bearer ${token}` },
68
+ body: body === undefined ? undefined : JSON.stringify(body),
69
+ signal: AbortSignal.timeout(600000),
70
+ })
71
+ return r.json()
72
+ }
73
+
74
+ /**
75
+ * 最近 N 个采样桶的制品重量均值(平台 DAQ REST)。
76
+ * 采集节拍 5s,所以取"最后 N 桶"而不是"最后 N 秒",避免把稳态前的过渡值混进来。
77
+ */
78
+ async function weightMean(buckets = 6) {
79
+ const j = await api('GET', `/api/workshop/daq/${DAQ}/samples?minutes=3`)
80
+ const pts = (j?.data?.samples ?? j?.data?.points ?? []).map(p => Number(p.avg ?? p.value)).filter(Number.isFinite)
81
+ if (!pts.length) return null
82
+ const take = pts.slice(-Math.max(1, Math.min(pts.length, buckets)))
83
+ return take.reduce((a, b) => a + b, 0) / take.length
84
+ }
85
+
86
+ /** 单节点没有 GET 路由:从聚合列表里取该 DCW 节点(含 value/lastChangeAt)。 */
87
+ async function nodeView() {
88
+ const j = await api('GET', '/api/workshop/dcw')
89
+ return (j?.data?.nodes ?? []).find(n => n.id === DCW) ?? null
90
+ }
91
+ function ledgerRows(planId) {
92
+ const db = new DatabaseSync(join(HOME, 'data', 'workshop.sqlite'), { readOnly: true })
93
+ try {
94
+ const rows = db.prepare(`SELECT * FROM intervention_events WHERE node_id = ? AND hypothesis LIKE ? ORDER BY ts ASC`).all(DCW, `[pexp:${planId}]%`)
95
+ return rows.map(r => ({
96
+ id: r.id,
97
+ from: r.from_value,
98
+ to: r.to_value,
99
+ effect: r.effect,
100
+ verdict: r.verdict,
101
+ mde: r.mde,
102
+ ts: r.ts,
103
+ }))
104
+ }
105
+ finally {
106
+ db.close()
107
+ }
108
+ }
109
+ function evidenceRows() {
110
+ const db = new DatabaseSync(join(HOME, 'data', 'workshop.sqlite'), { readOnly: true })
111
+ try {
112
+ return db.prepare(`SELECT id, target_key, level, source_type, source_ref, detail_json FROM ontology_evidence ORDER BY created_at DESC LIMIT 20`).all()
113
+ }
114
+ finally {
115
+ db.close()
116
+ }
117
+ }
118
+
119
+ /** 写设定值,遇写间隔/保持窗按"还需 Ns"等待后重试(安全联锁,不绕过) */
120
+ async function writeWithRetry(value, hypothesis) {
121
+ let wrote = await api('POST', `/api/workshop/dcw/${DCW}/write`, { value, hypothesis })
122
+ for (let i = 0; i < 4 && wrote?.code === 'WRITE_INTERVAL_NOT_ELAPSED'; i++) {
123
+ const txt = String(wrote.message ?? '')
124
+ const at = txt.indexOf('还需')
125
+ let digits = ''
126
+ for (const ch of txt.slice(at + 2, at + 14)) {
127
+ if (ch >= '0' && ch <= '9') digits += ch
128
+ else if (digits) break
129
+ }
130
+ const need = Number(digits || 60)
131
+ console.log(` · 写入间隔未到,等待 ${need + 2}s 后重试(安全联锁,不绕过)`)
132
+ await sleep((need + 2) * 1000)
133
+ wrote = await api('POST', `/api/workshop/dcw/${DCW}/write`, { value, hypothesis })
134
+ }
135
+ return wrote
136
+ }
137
+
138
+ console.log(`\n[端到端优化作业演示] base=${BASE} line=${LINE}`)
139
+ await login()
140
+
141
+ // ---------- D0 复位到基线(幂等:上次演示可能把 SP 留在别的档位) ----------
142
+ {
143
+ const nodeNow = await nodeView()
144
+ const cur = Number(nodeNow?.value ?? Number.NaN)
145
+ if (Number.isFinite(cur) && Math.abs(cur - LEVELS[0]) > 1e-9) {
146
+ const r = await writeWithRetry(LEVELS[0], '演示前置:复位到基线设定值')
147
+ console.log(` · 复位基线 SP ${cur} → ${LEVELS[0]}:${r?.code === 0 ? 'ok' : JSON.stringify(r).slice(0, 100)}`)
148
+ await sleep(22000)
149
+ }
150
+ else {
151
+ console.log(` · 已在基线 SP=${LEVELS[0]}`)
152
+ }
153
+ }
154
+
155
+ // ---------- D1 基线观测 ----------
156
+ console.log('\nD1 基线观测(SP=50,目标窗 32.00–32.30g)')
157
+ const baseline = await weightMean(6)
158
+ check('D1a', '基线重量可观测', baseline != null, `mean=${baseline?.toFixed(3)}g`)
159
+ check('D1b', '基线低于目标窗下界(需要优化)', baseline != null && baseline < WINDOW.lo, `baseline=${baseline?.toFixed(3)} < ${WINDOW.lo}`)
160
+
161
+ // ---------- D2 DoE 计划(HITL) ----------
162
+ console.log('\nD2 DoE 计划(真实线 → 单卡 HITL)')
163
+ const created = await api('POST', '/api/workshop/process-model/experiments', {
164
+ lineId: LINE,
165
+ levels: { [DCW]: LEVELS },
166
+ repeats: 1,
167
+ settleMs: 60000,
168
+ observeMs: 1000,
169
+ targets: { [DCW]: DAQ },
170
+ })
171
+ const plan = created?.data?.plan
172
+ check('D2a', '计划创建成功且待批准', created?.code === 0 && plan?.status === 'awaiting_approval', `status=${plan?.status}`)
173
+ const body = JSON.parse(plan?.planJson ?? '{}')
174
+ check('D2b', '成本核算前置(3 步,真实线 60s 下限)', body?.cost?.steps === 3 && /60s/.test(body?.cost?.summary ?? ''), body?.cost?.summary ?? '')
175
+
176
+ // ---------- D3 未批准被拒 ----------
177
+ console.log('\nD3 未批准执行必须被拒')
178
+ const denied = await api('POST', '/api/workshop/process-model/experiments', { action: 'run', planId: plan.id })
179
+ check('D3', '未批准执行被拒(APPROVAL_REQUIRED)', denied?.code !== 0 && /APPROVAL_REQUIRED|批准/.test(JSON.stringify(denied)), JSON.stringify(denied).slice(0, 120))
180
+
181
+ // ---------- D4 批准 + 执行 ----------
182
+ console.log('\nD4 人工批准 + 随机化执行(3 步 × 60s)')
183
+ const approved = await api('POST', '/api/workshop/process-model/experiments', { action: 'approve', planId: plan.id })
184
+ check('D4a', '批准后转 planned', approved?.data?.plan?.status === 'planned', approved?.data?.plan?.status)
185
+ const t0 = Date.now()
186
+ const runRes = await api('POST', '/api/workshop/process-model/experiments', { action: 'run', planId: plan.id })
187
+ const run = runRes?.data?.result
188
+ check('D4b', '计划执行完成 3/3', run?.status === 'done' && run?.executedSteps === 3, `${run?.status} ${run?.executedSteps}/${run?.totalSteps} 用时 ${Math.round((Date.now() - t0) / 1000)}s ${run?.failedReason ?? ''}`)
189
+
190
+ // ---------- D5 台账 + 判读 + 证据 ----------
191
+ console.log('\nD5 台账判定与本体证据')
192
+ const rows = ledgerRows(plan.id)
193
+ check('D5a', '台账 3 行且全部判定(非 pending)', rows.length === 3 && rows.every(r => r.verdict !== 'pending'), rows.map(r => r.verdict).join(','))
194
+ const ev = evidenceRows()
195
+ const linked = ev.filter(e => rows.some(r => e.source_ref === r.id))
196
+ check('D5b', '判定回灌本体证据(逐干预可追溯)', linked.length >= 1, `${linked.length} 条`)
197
+
198
+ // ---------- D6 学习:由实测响应估增益 ----------
199
+ console.log('\nD6 从实验数据估计动作增益')
200
+ const gains = []
201
+ for (const r of rows) {
202
+ if (r.effect == null || r.from == null || r.to == null) continue
203
+ const dsp = Number(r.to) - Number(r.from)
204
+ if (Math.abs(dsp) > 1e-9) gains.push(Number(r.effect) / dsp)
205
+ }
206
+ const gain = gains.length ? gains.sort((a, b) => a - b)[Math.floor(gains.length / 2)] : null
207
+ check('D6a', '可从台账效应量估出增益', gain != null && Number.isFinite(gain), `gain=${gain?.toFixed(5)} g/bar(样本 ${gains.length})`)
208
+ check('D6b', '增益方向正确(压力↑→重量↑)', gain != null && gain > 0, `gain=${gain?.toFixed(5)}`)
209
+
210
+ // ---------- D7 计算并下发目标 SP ----------
211
+ console.log('\nD7 计算目标 SP 并下发')
212
+ const lastSp = Number(rows.at(-1)?.to ?? LEVELS[0])
213
+ const currentWeight = await weightMean(6)
214
+ const targetWeight = (WINDOW.lo + WINDOW.hi) / 2
215
+ const proposed = gain != null ? lastSp + (targetWeight - currentWeight) / gain : lastSp
216
+ const targetSp = Math.round(Math.min(90, Math.max(50, proposed)) * 10) / 10
217
+ check('D7a', '目标 SP 在安全量程内', targetSp >= 50 && targetSp <= 90, `SP=${targetSp}bar(当前 ${lastSp},重量 ${currentWeight?.toFixed(3)}g)`)
218
+ // 写完 DoE 最后一步后有 60s 保持窗:等到窗口结束再下发
219
+ const sinceLastWrite = rows.length ? Date.now() - Date.parse(rows.at(-1).ts) : 60000
220
+ if (sinceLastWrite < 62000) await sleep(62000 - sinceLastWrite)
221
+ const writeHypothesis = `按 DoE 实测增益 ${gain?.toFixed(5)} g/bar 计算:目标重量 ${targetWeight}g`
222
+ const wrote = await writeWithRetry(targetSp, writeHypothesis)
223
+ check('D7b', '参数下发受理', wrote?.code === 0, JSON.stringify(wrote?.data ?? wrote).slice(0, 160))
224
+ const readback = await nodeView()
225
+ const rb = Number(readback?.value ?? Number.NaN)
226
+ check('D7c', '回读一致', Math.abs(rb - targetSp) < 0.11, `readback=${rb} target=${targetSp}`)
227
+
228
+ // ---------- D8 控得好:重量进入目标窗 ----------
229
+ console.log('\nD8 效果验证(等待工艺跟随)')
230
+ await sleep(25000)
231
+ const after = await weightMean(6)
232
+ const inWindow = after != null && after >= WINDOW.lo && after <= WINDOW.hi
233
+ check('D8', '制品重量进入目标窗', inWindow, `after=${after?.toFixed(3)}g window=[${WINDOW.lo},${WINDOW.hi}] Δ=${((after ?? 0) - (baseline ?? 0)).toFixed(3)}g`)
234
+
235
+ // ---------- 证据 ----------
236
+ const report = {
237
+ at: new Date().toISOString(),
238
+ scope: { platform: 'isolated-instance', simulator: 'plc-node-simulator(modbus-tcp)', deviceLayer: 'simulated-twin', realPlant: false },
239
+ lineId: LINE,
240
+ dof: { levels: LEVELS, planId: plan.id, controller: DCW, target: DAQ },
241
+ baseline: { weight: baseline, sp: LEVELS[0] },
242
+ ledger: rows,
243
+ estimatedGain: gain,
244
+ dispatch: { targetSp, readback: rb, targetWeight },
245
+ final: { weight: after, window: WINDOW, delta: after != null && baseline != null ? after - baseline : null },
246
+ pass,
247
+ fail: failures.length,
248
+ failures,
249
+ checks,
250
+ }
251
+ mkdirSync(join(OUT, '..'), { recursive: true })
252
+ writeFileSync(OUT, JSON.stringify(report, null, 2))
253
+ console.log(`\n[结果] PASS=${pass} FAIL=${failures.length}`)
254
+ console.log(`[证据] ${OUT}`)
255
+ if (failures.length) {
256
+ for (const f of failures) console.error(` - ${f}`)
257
+ process.exit(1)
258
+ }
259
+ console.log('[端到端优化作业] ALL PASS\n')