@twinsearth/dsh-fang 3.3.1 → 3.7.6

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 (58) hide show
  1. package/README.md +3 -3
  2. package/client.js +709 -61
  3. package/cordis.patch.yml +26 -20
  4. package/docs/APPROVAL-DRILL.md +42 -0
  5. package/docs/AUTO-WATCHDOG.md +46 -0
  6. package/docs/DECISION-LOSSLESS.md +36 -0
  7. package/docs/ESSENCE-AUTO-SYNC.md +32 -0
  8. package/docs/INBOX-SCROLL.md +33 -0
  9. package/docs/OVERLAY-MASTER-SWITCH.md +35 -0
  10. package/docs/PACKAGE-RENAME-v3.3.3.md +40 -0
  11. package/docs/RESTART-CONFIRMATION.md +29 -0
  12. package/docs/TEST-STABILITY-v3.4.0.md +30 -0
  13. package/package.json +9 -5
  14. package/src/compose.mjs +4 -1
  15. package/src/contract/VENDOR.json +6 -5
  16. package/src/contract/constants.js +16 -1
  17. package/src/contract/relay.js +12 -6
  18. package/src/kernel/types.mjs +3 -1
  19. package/src/lib/accelerated-fork.mjs +813 -0
  20. package/src/lib/accelerated-install.mjs +295 -0
  21. package/src/lib/accelerated-web.mjs +103 -0
  22. package/src/lib/approval-drill.mjs +111 -0
  23. package/src/lib/boot-guard.mjs +6 -2
  24. package/src/lib/chat-import-delegation.mjs +47 -0
  25. package/src/lib/compat.mjs +5 -1
  26. package/src/lib/contract-delegation.mjs +161 -0
  27. package/src/lib/default-essence.mjs +7 -4
  28. package/src/lib/essence.mjs +113 -7
  29. package/src/lib/fork-config-lock.mjs +2 -2
  30. package/src/lib/fork-core-settings.mjs +95 -0
  31. package/src/lib/fork-export.mjs +85 -0
  32. package/src/lib/global-redline.mjs +164 -0
  33. package/src/lib/http-auth.mjs +36 -0
  34. package/src/lib/install-snapshot.mjs +77 -0
  35. package/src/lib/lsp-delegation.mjs +70 -0
  36. package/src/lib/lsp-provider.mjs +250 -0
  37. package/src/lib/main-gate.mjs +34 -28
  38. package/src/lib/mirror.mjs +115 -4
  39. package/src/lib/node-compat.mjs +24 -0
  40. package/src/lib/pro-delegation.mjs +185 -0
  41. package/src/lib/runtime-capture.mjs +11 -3
  42. package/src/lib/watch-guard.mjs +51 -0
  43. package/src/plugins/approver.mjs +5 -2
  44. package/src/plugins/auditor.mjs +125 -18
  45. package/src/plugins/decision-center.mjs +77 -34
  46. package/src/plugins/forker.mjs +258 -33
  47. package/src/plugins/orchestrator.mjs +1508 -65
  48. package/src/plugins/restart-guard.mjs +79 -2
  49. package/src/plugins/session-catalog.mjs +127 -40
  50. package/tools/approval-drill.mjs +21 -0
  51. package/tools/fangctl.mjs +21 -4
  52. package/tools/gate/main-city.mjs +1 -1
  53. package/tools/restart-supervisor.mjs +425 -0
  54. package/tools/restart-watchdog.mjs +568 -0
  55. package/vault/client.js +49 -0
  56. package/vault/cordis.patch.yml +3 -0
  57. package/vault/lib/vault.mjs +219 -0
  58. package/vault/package.json +29 -0
@@ -237,7 +237,10 @@ function checkBridgeAcl(dir) {
237
237
  return { ok: true, platform: 'posix', mode: st.mode & 0o777 }
238
238
  }
239
239
  const output = execFileSync('icacls', [dir], { encoding: 'utf8', timeout: 5000, windowsHide: true })
240
- const dangerous = /(everyone|builtin\\users|authenticated users|interactive|iusr|iis_iusrs)/i
240
+ const broadPrincipal = /(everyone|builtin\\users|authenticated users|interactive|iusr|iis_iusrs)/i
241
+ // Only a write-capable grant from a broad principal is dangerous; inherited read-only
242
+ // entries (e.g. `(I)(OI)(CI)(RX)` on a temp dir) must not disable the bridge.
243
+ const writeGrant = /\((?:F|M|W|WD|AD|WO|GA)\)/i
241
244
  const resolved = path.resolve(dir).toLowerCase()
242
245
  let checked = 0
243
246
  for (const rawLine of String(output).split(/\r?\n/)) {
@@ -246,7 +249,7 @@ function checkBridgeAcl(dir) {
246
249
  if (line.toLowerCase().startsWith(resolved)) line = line.slice(path.resolve(dir).length).trim()
247
250
  if (!line.includes(':')) continue
248
251
  checked += 1
249
- if (dangerous.test(line)) return { ok: false, reason: 'bridge-dir-world-accessible', detail: line }
252
+ if (broadPrincipal.test(line) && writeGrant.test(line)) return { ok: false, reason: 'bridge-dir-world-writable', detail: line }
250
253
  }
251
254
  if (checked === 0) return { ok: false, reason: 'bridge-acl-unreadable' }
252
255
  return { ok: true, platform: 'win32' }
@@ -28,6 +28,7 @@ import {
28
28
  AUDIT,
29
29
  SERVICE,
30
30
  appendChained,
31
+ bus,
31
32
  ensureDir,
32
33
  iso,
33
34
  newId,
@@ -63,6 +64,17 @@ export const Config = z
63
64
 
64
65
  const msgOf = (e) => String(e && e.message ? e.message : e)
65
66
 
67
+ // ───────── R15:append 失败的可观测面 ─────────
68
+ // append() 失败在过去只把原因存进 lastError 并返回 null,调用方几乎都忽略,
69
+ // 于是审计链断掉既没有告警也没有健康面。现在失败会:
70
+ // * 累加 failureCount / 记录 lastFailureAt(lastError 保留原 string 语义);
71
+ // * 通过 logger.warn 告警(60s 限频,避免连续失败刷屏);
72
+ // * 发出 AUDIT_APPEND_FAILED_EVENT 事件(ctx.bus 优先,缺失时回落 kernel 进程级 bus)。
73
+ // append() 的返回语义仍是“记录或 null”;安全关键调用点改用 appendStrict()(失败即 throw)。
74
+ export const AUDIT_APPEND_FAILED_EVENT = 'fang/audit-append-failed'
75
+ /** 告警限频窗口:失败可能成串发生,60s 内最多一条 warn。 */
76
+ const FAILURE_WARN_INTERVAL_MS = 60_000
77
+
66
78
  /** A restart was opened by the guard (requested or already committed). */
67
79
  function isRestartOpen(rec) {
68
80
  if (!rec || typeof rec !== 'object') return false
@@ -99,6 +111,10 @@ export function apply(ctx, config) {
99
111
  // Fail-closed after a chain check failed: appending on top of a broken chain would
100
112
  // launder the tampering (the kernel appendChained only refuses an unparsable TAIL).
101
113
  let integrityBroken = false
114
+ // R15 失败状态(累积):次数、最后失败时间;lastError 语义保持不变。
115
+ let failureCount = 0
116
+ let lastFailureAt = null
117
+ let lastWarnAt = 0 // 0 = 第一次失败必定告警
102
118
 
103
119
  /** Tolerant JSONL read: bad lines are skipped here and reported by verify(). */
104
120
  const readAll = () => {
@@ -116,33 +132,103 @@ export function apply(ctx, config) {
116
132
  return out
117
133
  }
118
134
 
135
+ /**
136
+ * R15:发出“审计追加失败”事件。ctx.bus 优先(隔离/测试可注入);真实 cordis 上下文
137
+ * 没有 ctx.bus(其他插件都直接 import kernel 的进程级 bus),因此缺失时回落到同一个
138
+ * kernel bus —— 事件才能真正到达 orchestrator / 健康面。任何异常都不得影响 append 语义。
139
+ */
140
+ const emitAppendFailed = (kind, message, at) => {
141
+ const payload = { kind: typeof kind === 'string' ? kind.trim() : null, error: message, at }
142
+ try {
143
+ if (ctx.bus && typeof ctx.bus.emit === 'function') {
144
+ ctx.bus.emit(AUDIT_APPEND_FAILED_EVENT, payload)
145
+ return
146
+ }
147
+ } catch {
148
+ /* ctx.bus 只做通知:监听器/实现抛错不得影响 append() 的返回语义 */
149
+ }
150
+ try {
151
+ bus.emit(AUDIT_APPEND_FAILED_EVENT, payload)
152
+ } catch {
153
+ /* bus 缺失(极端隔离环境)时跳过:可观测性永远不能反噬审计写入 */
154
+ }
155
+ }
156
+
157
+ /**
158
+ * 记录一次失败的 append(R15):累加失败状态、限频告警、发事件,然后返回 null,
159
+ * 让 append() 保持“记录或 null”的旧返回语义。
160
+ */
161
+ const recordFailure = (kind, error) => {
162
+ const message = msgOf(error)
163
+ const at = iso(nowMs())
164
+ failureCount += 1
165
+ lastError = message
166
+ lastFailureAt = at
167
+ const now = nowMs()
168
+ if (now - lastWarnAt >= FAILURE_WARN_INTERVAL_MS) {
169
+ lastWarnAt = now
170
+ try {
171
+ ctx.logger?.warn?.(`[fang-auditor] 审计追加失败(kind=${String(kind)}):${message}`)
172
+ } catch {
173
+ /* logger 失败不得影响审计返回语义 */
174
+ }
175
+ }
176
+ emitAppendFailed(kind, message, at)
177
+ return null
178
+ }
179
+
180
+ /**
181
+ * 真正写一条链式记录:失败一律 throw(由 append / appendStrict 决定吞还是抛)。
182
+ * `at` / `seq` 自动填充;`data` 在冲突时优先(调用方可记录分身自己的 pid)。
183
+ * @returns {object} the appended record (including hash/prevHash/seq).
184
+ */
185
+ const writeRecord = (kind, data) => {
186
+ if (typeof kind !== 'string' || !kind.trim()) {
187
+ throw new Error('invalid-kind: audit kind must be a non-empty string')
188
+ }
189
+ if (integrityBroken) {
190
+ // An unparsable/篡改过的链不允许续写(否则等于帮着掩盖篡改)。
191
+ throw new Error('ledger-integrity-broken: refusing to append on top of a broken chain')
192
+ }
193
+ ensureDir(path.dirname(ledgerFile))
194
+ const body = {
195
+ kind: kind.trim(),
196
+ pid: process.pid,
197
+ at: iso(nowMs()),
198
+ ...(data ?? {}),
199
+ inst: (data && data.inst) || instanceId,
200
+ }
201
+ const chain = appendChained(ledgerFile, body)
202
+ lastError = null
203
+ return { ...body, ...chain }
204
+ }
205
+
119
206
  /**
120
207
  * Append one chained record. `at` and `seq` are filled automatically; `data` wins on
121
208
  * collision (so callers can record a fork's own pid via data.pid).
209
+ * 失败仍然返回 null(兼容所有旧调用方),但失败状态/告警/事件不再是静默的(R15)。
122
210
  * @returns {object|null} the appended record, or null when the ledger tail is unusable.
123
211
  */
124
212
  const append = (kind, data) => {
125
- if (typeof kind !== 'string' || !kind.trim()) return null
126
- if (integrityBroken) {
127
- lastError = 'ledger-integrity-broken: refusing to append on top of a broken chain'
128
- return null
129
- }
130
213
  try {
131
- ensureDir(path.dirname(ledgerFile))
132
- const body = {
133
- kind: kind.trim(),
134
- pid: process.pid,
135
- at: iso(nowMs()),
136
- ...(data ?? {}),
137
- inst: (data && data.inst) || instanceId,
138
- }
139
- const chain = appendChained(ledgerFile, body)
140
- lastError = null
141
- return { ...body, ...chain }
214
+ return writeRecord(kind, data)
142
215
  } catch (e) {
143
216
  // An unparsable tail is deliberately NOT overwritten (that would hide tampering).
144
- lastError = msgOf(e)
145
- return null
217
+ return recordFailure(kind, e)
218
+ }
219
+ }
220
+
221
+ /**
222
+ * R15:同 append(),但失败时 throw 而不是返回 null —— 供安全关键路径使用,
223
+ * 保证“审计写不进去”不会被调用方无声吞掉。
224
+ * @returns {object} the appended record; throws on any failure (also counted in status()).
225
+ */
226
+ const appendStrict = (kind, data) => {
227
+ try {
228
+ return writeRecord(kind, data)
229
+ } catch (e) {
230
+ recordFailure(kind, e)
231
+ throw e instanceof Error ? e : new Error(msgOf(e))
146
232
  }
147
233
  }
148
234
 
@@ -231,6 +317,23 @@ export function apply(ctx, config) {
231
317
  return { ok: findings.length === 0, findings, records: recs.length, previous: previous.length, pid: process.pid }
232
318
  }
233
319
 
320
+ /**
321
+ * R15 健康面:一次只读快照,供 orchestrator 状态路由 / UI / 测试使用。
322
+ * ok = 本进程没有失败记录 && 链没被判坏 && 最近一次 bootCheck 不是坏结论。
323
+ * 只读:不刷新 integrityBroken(需要重新判链请显式调用 verify())。
324
+ * @returns {{ok:boolean, ledgerFile:string, records:number, integrityBroken:boolean, failures:number, lastError:string|null, lastFailureAt:string|null, lastBoot:object|null}}
325
+ */
326
+ const status = () => ({
327
+ ok: failureCount === 0 && !integrityBroken && !(lastBoot && lastBoot.ok === false),
328
+ ledgerFile,
329
+ records: readAll().length,
330
+ integrityBroken,
331
+ failures: failureCount,
332
+ lastError,
333
+ lastFailureAt,
334
+ lastBoot,
335
+ })
336
+
234
337
  // ───────── v2 §5.7 汇总 / 商用钩子 ─────────
235
338
 
236
339
  const atMsOf = (rec) => {
@@ -293,6 +396,8 @@ export function apply(ctx, config) {
293
396
  const service = {
294
397
  scope,
295
398
  append,
399
+ /** R15:安全关键路径使用;失败会 throw(而不是返回 null)。 */
400
+ appendStrict,
296
401
  read,
297
402
  verify,
298
403
  bootCheck,
@@ -300,6 +405,8 @@ export function apply(ctx, config) {
300
405
  bootAudit: bootCheck,
301
406
  aggregate,
302
407
  cloudSink,
408
+ /** R15 健康面:失败次数/最后失败/链完整性,供 orchestrator status 与 UI 展示。 */
409
+ status,
303
410
  get ledgerFile() {
304
411
  return ledgerFile
305
412
  },
@@ -65,6 +65,26 @@ const SOURCE_ROLES = Object.freeze(['pm', 'pjm', 'worker', 'system'])
65
65
  * - red(阻塞)必须由人显式选择,任何情况下都不允许 AI 自选;
66
66
  * - 低风险且可回滚的推进不必开票(否则会变成注意力噪音)。
67
67
  */
68
+ /**
69
+ * v3.3.9 P0: DSH validates a tool result as lossless JSON. `undefined`
70
+ * properties (e.g. selectedValue when a ticket resolves without a value) are
71
+ * not lossless and make the whole tool call fail after the ticket was already
72
+ * created. Project every tool result through this lossless value.
73
+ */
74
+ export function toLosslessJson(value) {
75
+ try {
76
+ const text = JSON.stringify(value, (_key, item) => {
77
+ if (typeof item === 'bigint') return item.toString()
78
+ if (typeof item === 'number' && !Number.isFinite(item)) return null
79
+ if (typeof item === 'function' || typeof item === 'symbol') return undefined
80
+ return item
81
+ })
82
+ return text === undefined ? null : JSON.parse(text)
83
+ } catch {
84
+ return { ok: false, error: 'non-lossless-json-result' }
85
+ }
86
+ }
87
+
68
88
  export const PM_DECISION_POLICY = Object.freeze({
69
89
  version: 1,
70
90
  mustAsk: [
@@ -439,7 +459,7 @@ function applyForkDecisionCenter(ctx, config, gate) {
439
459
  taskId,
440
460
  })
441
461
  if (submitted.queued) {
442
- return { queued: true, status: 'queued', ticketId: null, level: input.level ?? 'yellow', reason: submitted.reason ?? null }
462
+ return toLosslessJson({ queued: true, status: 'queued', ticketId: null, level: input.level ?? 'yellow', reason: submitted.reason ?? null })
443
463
  }
444
464
  const ticket = submitted.ticket
445
465
  if (!ticket?.id) throw new Error('母体未返回 ticket')
@@ -456,29 +476,29 @@ function applyForkDecisionCenter(ctx, config, gate) {
456
476
  if (!settled.ok) {
457
477
  // 黄色轮询超时仍允许流程继续;母体定时器会把 ticket 标成 deferred。
458
478
  if (ticket.level === 'yellow' && settled.reason === 'timeout') {
459
- return {
479
+ return toLosslessJson({
460
480
  ticketId: ticket.id, level: ticket.level, blocking: false,
461
481
  status: 'pending', outcome: 'deferred', deferred: true,
462
482
  continueWithoutDecision: true, canAnswerLater: true, queued: false,
463
483
  priority: ticket.priority, risk: ticket.risk,
464
- }
484
+ })
465
485
  }
466
486
  throw new Error(`fork 决策未在时限内完成(${settled.reason})`)
467
487
  }
468
488
  const resolved = settled.ticket
469
489
  if (resolved.status === 'pending' && resolved.level === 'yellow') {
470
- return {
490
+ return toLosslessJson({
471
491
  ticketId: resolved.id, level: resolved.level, blocking: false,
472
492
  status: 'pending', outcome: 'deferred', deferred: true,
473
493
  continueWithoutDecision: true, canAnswerLater: true,
474
494
  deferredAt: resolved.deferredAt ?? undefined, queued: false,
475
495
  priority: resolved.priority, risk: resolved.risk,
476
- }
496
+ })
477
497
  }
478
498
  if (resolved.status !== 'resolved' && resolved.status !== 'abandoned' && resolved.status !== 'expired' && resolved.status !== 'acked') {
479
499
  throw new Error(`fork 决策状态异常:${resolved.status}`)
480
500
  }
481
- return {
501
+ return toLosslessJson({
482
502
  ticketId: resolved.id, level: resolved.level, blocking: resolved.level === 'red',
483
503
  status: resolved.status, outcome: resolved.outcome,
484
504
  selectedValue: resolved.resolvedOption ?? undefined,
@@ -487,16 +507,16 @@ function applyForkDecisionCenter(ctx, config, gate) {
487
507
  autoReason: resolved.autoReason ?? undefined,
488
508
  priority: resolved.priority, risk: resolved.risk,
489
509
  queued: false,
490
- }
510
+ })
491
511
  }
492
- return {
512
+ return toLosslessJson({
493
513
  ticketId: ticket.id, level: ticket.level, blocking: false,
494
514
  status: ticket.status, outcome: ticket.outcome ?? ticket.status,
495
515
  autoResolved: ticket.autoResolved === true,
496
516
  selectedValue: ticket.resolvedOption ?? undefined,
497
517
  selectedActionId: ticket.selectedActionId ?? undefined,
498
518
  queued: false,
499
- }
519
+ })
500
520
  },
501
521
  })
502
522
  child.effect(() => () => { try { unregister?.() } catch { /* ignore */ } })
@@ -1012,12 +1032,24 @@ export function apply(ctx, config) {
1012
1032
  if (ticket.level !== 'yellow' && ticket.level !== 'blue') return
1013
1033
  const deadline = Number(ticket.waitDeadlineAt)
1014
1034
  if (!Number.isFinite(deadline)) return
1015
- const timer = setTimeout(() => {
1016
- timers.delete(timer)
1017
- try { settlePolicy(ticket.id) } catch { /* policy timers must not crash the host */ }
1018
- }, Math.max(0, deadline - nowMs()))
1019
- timer.unref?.()
1020
- timers.add(timer)
1035
+ // Windows 计时器可能提前 1–15ms 触发(CI 上实测把 walk 窗口打成“永远不结算”)。
1036
+ // settlePolicy 对“窗口还没到”会拒绝推进;此时必须按剩余时间重排,否则 waiter 永远悬挂。
1037
+ const arm = () => {
1038
+ const timer = setTimeout(() => {
1039
+ timers.delete(timer)
1040
+ let settled = false
1041
+ try { settled = settlePolicy(ticket.id) } catch { /* policy timers must not crash the host */ }
1042
+ if (settled) return
1043
+ const current = tickets.get(ticket.id)
1044
+ if (!current || current.status !== 'pending' || disposed) return
1045
+ if (Number(current.waitDeadlineAt) - nowMs() > 0) { arm(); return }
1046
+ // 截止已过仍未结算:再试一次(幂等);仍失败则交给 waiters 的兜底,绝不无限挂起。
1047
+ try { settlePolicy(ticket.id) } catch { /* ignore */ }
1048
+ }, Math.max(1, deadline - nowMs()))
1049
+ timer.unref?.()
1050
+ timers.add(timer)
1051
+ }
1052
+ arm()
1021
1053
  }
1022
1054
 
1023
1055
  const create = (input = {}) => {
@@ -1238,13 +1270,24 @@ export function apply(ctx, config) {
1238
1270
  }
1239
1271
  const policyDeadline = ticket.level === 'red' ? ticket.expiresAt : ticket.waitDeadlineAt
1240
1272
  if (policyDeadline && Number.isFinite(policyDeadline)) {
1241
- const delay = Math.max(1, policyDeadline - nowMs())
1242
- waiter.timer = setTimeout(() => {
1243
- const current = tickets.get(ticketId)
1244
- if (!current || current.status !== 'pending') return
1245
- if (current.level === 'red') expire(ticketId)
1246
- else settlePolicy(ticketId)
1247
- }, delay)
1273
+ // 计时器提前触发时状态机不会推进(窗口未到),必须重排到截止点;截止已过仍未推进则
1274
+ // 把当前状态交还调用方,保证任何情况下 wait 都不会无限挂起(CI 曾因此整文件挂 24min)。
1275
+ const arm = () => {
1276
+ waiter.timer = setTimeout(() => {
1277
+ const current = tickets.get(ticketId)
1278
+ if (!current || current.status !== 'pending') return
1279
+ let settled = false
1280
+ try {
1281
+ settled = current.level === 'red' ? expire(ticketId) : settlePolicy(ticketId)
1282
+ } catch { /* timers must never crash the host */ }
1283
+ if (settled) return
1284
+ const still = tickets.get(ticketId)
1285
+ if (!still || still.status !== 'pending') return
1286
+ if (policyDeadline - nowMs() > 0) { arm(); return }
1287
+ waiter.resolve({ ...publicTicket(still), outcome: still.deferredAt ? 'deferred' : 'timeout' })
1288
+ }, Math.max(1, policyDeadline - nowMs()))
1289
+ }
1290
+ arm()
1248
1291
  }
1249
1292
  let set = waiters.get(ticketId)
1250
1293
  if (!set) { set = new Set(); waiters.set(ticketId, set) }
@@ -2396,18 +2439,18 @@ export function apply(ctx, config) {
2396
2439
  const result = await wait(ticket.id, exec?.signal)
2397
2440
  const outcome = String(result?.outcome ?? (result.status === 'pending' ? 'deferred' : 'expired'))
2398
2441
  if (result.status === 'pending' && result.level === 'yellow') {
2399
- return {
2442
+ return toLosslessJson({
2400
2443
  ticketId: result.id, level: result.level, blocking: false,
2401
2444
  status: 'pending', outcome: 'deferred', deferred: true,
2402
2445
  continueWithoutDecision: true, canAnswerLater: true,
2403
2446
  deferredAt: result.deferredAt ?? undefined,
2404
2447
  priority: result.priority, risk: result.risk,
2405
- }
2448
+ })
2406
2449
  }
2407
2450
  if (outcome !== 'resolved' && outcome !== 'acked') {
2408
2451
  throw new Error(`用户未处理该决策(outcome=${outcome})`)
2409
2452
  }
2410
- return {
2453
+ return toLosslessJson({
2411
2454
  ticketId: result.id, level: result.level, blocking: result.level === 'red',
2412
2455
  status: 'resolved', outcome,
2413
2456
  selectedValue: result.resolvedOption ?? undefined,
@@ -2417,16 +2460,16 @@ export function apply(ctx, config) {
2417
2460
  autoReason: result.autoReason ?? undefined,
2418
2461
  lateResponse: result.lateResponse === true,
2419
2462
  priority: result.priority, risk: result.risk,
2420
- }
2463
+ })
2421
2464
  }
2422
- return {
2465
+ return toLosslessJson({
2423
2466
  ticketId: ticket.id, level: ticket.level, blocking: false,
2424
2467
  status: ticket.status, outcome: ticket.outcome ?? ticket.status,
2425
2468
  autoResolved: ticket.autoResolved === true,
2426
2469
  selectedValue: ticket.resolvedOption ?? undefined,
2427
2470
  selectedActionId: ticket.selectedActionId ?? undefined,
2428
2471
  priority: ticket.priority, risk: ticket.risk,
2429
- }
2472
+ })
2430
2473
  },
2431
2474
  })
2432
2475
  // PM 交互式选择:独立工具名,语义 = 红色决策 ticket(默认红、阻塞等待选择)。
@@ -2499,34 +2542,34 @@ export function apply(ctx, config) {
2499
2542
  if (!created.ok) throw new Error(`decision center rejected choice: ${created.reason}`)
2500
2543
  const ticket = created.ticket
2501
2544
  if (ticket.status !== 'pending') {
2502
- return {
2545
+ return toLosslessJson({
2503
2546
  ticketId: ticket.id, level: ticket.level, blocking: false,
2504
2547
  status: ticket.status, outcome: ticket.outcome,
2505
2548
  autoResolved: ticket.autoResolved === true,
2506
2549
  selectedValue: ticket.resolvedOption ?? undefined,
2507
2550
  priority: ticket.priority, risk: ticket.risk,
2508
- }
2551
+ })
2509
2552
  }
2510
2553
  const result = await wait(ticket.id, exec?.signal)
2511
2554
  const outcome = String(result?.outcome ?? (result.status === 'pending' ? 'deferred' : 'expired'))
2512
2555
  if (result.status === 'pending' && result.level === 'yellow') {
2513
- return {
2556
+ return toLosslessJson({
2514
2557
  ticketId: result.id, level: result.level, blocking: false,
2515
2558
  status: 'pending', outcome: 'deferred', deferred: true,
2516
2559
  continueWithoutDecision: true, canAnswerLater: true,
2517
2560
  priority: result.priority, risk: result.risk,
2518
- }
2561
+ })
2519
2562
  }
2520
2563
  if (outcome !== 'resolved' && outcome !== 'acked') {
2521
2564
  throw new Error(`用户未处理该选择(outcome=${outcome})`)
2522
2565
  }
2523
- return {
2566
+ return toLosslessJson({
2524
2567
  ticketId: result.id, level: result.level, blocking: result.level === 'red',
2525
2568
  outcome, selectedValue: result.resolvedOption ?? undefined,
2526
2569
  autoResolved: result.autoResolved === true,
2527
2570
  lateResponse: result.lateResponse === true,
2528
2571
  priority: result.priority, risk: result.risk,
2529
- }
2572
+ })
2530
2573
  },
2531
2574
  })
2532
2575
  child.effect(() => () => { try { unregister?.() } catch { /* ignore */ } })