@twinsearth/dsh-fang 3.1.0 → 3.1.3

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 (38) hide show
  1. package/client.js +1511 -1
  2. package/cordis.patch.yml +9 -0
  3. package/package.json +7 -3
  4. package/src/compose.mjs +4 -1
  5. package/src/kernel/paths.mjs +9 -1
  6. package/src/kernel/role.mjs +1 -0
  7. package/src/kernel/types.mjs +5 -1
  8. package/src/lib/ai-secret-store.mjs +202 -0
  9. package/src/lib/boot-guard.mjs +182 -0
  10. package/src/lib/business-producers.mjs +109 -0
  11. package/src/lib/compat.mjs +1 -1
  12. package/src/lib/composer-journal.mjs +8 -0
  13. package/src/lib/decision-events.mjs +129 -0
  14. package/src/lib/decision-ingest-client.mjs +41 -0
  15. package/src/lib/decision-outbox.mjs +129 -0
  16. package/src/lib/desktop-launch.mjs +138 -0
  17. package/src/lib/fork-supervision-settings.mjs +58 -0
  18. package/src/lib/mirror-official-source.mjs +93 -0
  19. package/src/lib/mirror.mjs +10 -3
  20. package/src/lib/producer-contract.mjs +162 -0
  21. package/src/lib/restart-contract.mjs +650 -0
  22. package/src/lib/rule-registry.mjs +69 -0
  23. package/src/lib/ssrf-guard.mjs +170 -0
  24. package/src/lib/umbrella.mjs +143 -18
  25. package/src/plugins/adapter.mjs +31 -2
  26. package/src/plugins/approver.mjs +423 -40
  27. package/src/plugins/decision-center.mjs +2255 -0
  28. package/src/plugins/forker.mjs +20 -1
  29. package/src/plugins/healer.mjs +53 -20
  30. package/src/plugins/imports.mjs +48 -0
  31. package/src/plugins/orchestrator.mjs +844 -46
  32. package/src/plugins/restart-guard.mjs +645 -52
  33. package/src/plugins/scorer.mjs +227 -15
  34. package/src/plugins/umbrella.mjs +18 -14
  35. package/tools/boot-guard.mjs +95 -0
  36. package/tools/decision-ingest.mjs +53 -0
  37. package/tools/desktop-launch.mjs +71 -0
  38. package/tools/fangctl.mjs +229 -1
@@ -4,8 +4,10 @@
4
4
  //
5
5
  // 职责(四件能力,契约见 docs/CONTRACTS.md §5.7 与 §6;v2 增量见 CONTRACTS-V2.md §5.7):
6
6
  // 1) 待批队列:request() 返回 Promise,只有 decide() 或 TTL 到期(fail-closed → 'timeout')才 resolve;
7
- // 2) A/B 双备:snapshot() 把目录内容复制到 <dataDir>/snapshots/<tag>/A(新)与 /B(上一代),
7
+ // 2) 多代快照:snapshot() 把目录内容复制到 <dataDir>/snapshots/<tag>/A(新)与 /B、/C…(历史代),
8
8
  // 对复制出的内容做内容寻址 sha256 digest;rollback() 用快照覆盖回目标目录并校验 digest;
9
+ // 1a) 崩溃 journal:dsh-approval-journal.jsonl 只增记录 request/settled/orphaned;
10
+ // 重启后未 settled 的 request 只标记 orphaned,绝不复活已死的 Promise;
9
11
  // 3) 监控:monitor({label,value,threshold}) 采样,越阈值返回 alert:true 并留痕;
10
12
  // 4) 回滚 + 保留文件桥:dataDir 下的 command/answer/pending/status json 供 CLI 驱动(轮询式)。
11
13
  //
@@ -23,10 +25,13 @@
23
25
  //
24
26
  // 明确降级(NOT ESTABLISHED):
25
27
  // * authMode='timed' 的 grants(限时授权/临时授权)未实现,按 manual 处理(fail-closed);
26
- // * 快照只保留一代 B(A=最新,B=上一次),不做多代历史;不跟随 junction(copyTree 只重建链接);
28
+ // * 快照保留 snapshotGenerations 代(默认 3,A 最新);不跟随 junction(copyTree 只重建链接);
27
29
  // * monitor 为单点采样(不做内部定时 getter 轮询),轮询由调用方/CLI 决定;
28
- // * requestPromotion/requestRestart 不做"仅母体可调用"的硬拒绝(语义约定,非门禁)。
30
+ // * requestPromotion/requestRestart 只在 mother scope 接受;fork 调用立即 denied/by:'scope'。
31
+ import fs from 'node:fs'
29
32
  import path from 'node:path'
33
+ import crypto from 'node:crypto'
34
+ import { execFileSync } from 'node:child_process'
30
35
  import {
31
36
  AUDIT,
32
37
  SERVICE,
@@ -39,6 +44,7 @@ import {
39
44
  iso,
40
45
  newId,
41
46
  nowMs,
47
+ readJsonl,
42
48
  readTextSafe,
43
49
  removeTree,
44
50
  resolveFangLayout,
@@ -65,8 +71,14 @@ export const Config = z.object({
65
71
  .description('红灯必须人工显式 decide;即使 authMode=auto'),
66
72
  backupRoot: z.string().default('')
67
73
  .description('快照根目录;留空 = <dataDir>/snapshots(默认布局)'),
74
+ snapshotGenerations: z.number().min(2).max(10).default(3)
75
+ .description('每个 tag 保留的快照代数(A 最新,依次 B/C…;默认 3)'),
68
76
  fileBridgePollMs: z.number().min(10).default(300)
69
77
  .description('文件桥(command/answer json)轮询间隔(毫秒)'),
78
+ bridgeAclCheck: z.boolean().default(true)
79
+ .description('启动时校验 dataDir ACL;不通过则停用文件桥'),
80
+ bridgeSecret: z.string().default('')
81
+ .description('可选文件桥 HMAC 密钥;设置后 command/answer 必须带 signature'),
70
82
  role: z.union([z.const('mother'), z.const('fork')]).default('mother')
71
83
  .description('部署角色(v2 §1);DSH_FANG_ROLE 环境变量优先级更高(forker 启动分身时注入)'),
72
84
  }).description('dsh-Fang 审批子插件配置(契约 §5.7)')
@@ -78,7 +90,10 @@ const DEFAULTS = Object.freeze({
78
90
  authMode: 'manual',
79
91
  strictRedLine: true,
80
92
  backupRoot: '',
93
+ snapshotGenerations: 3,
81
94
  fileBridgePollMs: 300,
95
+ bridgeAclCheck: true,
96
+ bridgeSecret: '',
82
97
  role: 'mother',
83
98
  })
84
99
 
@@ -100,6 +115,8 @@ const BRIDGE = Object.freeze({
100
115
  })
101
116
  /** 决策流水(appendJsonl,只增不改;status() 的 decisions 计数从内存历史来)。 */
102
117
  const DECISIONS_FILE = 'dsh-approval-decisions.jsonl'
118
+ /** 崩溃 journal:request/settled/orphaned 生命周期只增日志,供重启恢复未结请求。 */
119
+ const JOURNAL_FILE = 'dsh-approval-journal.jsonl'
103
120
 
104
121
  function clamp01(n) {
105
122
  const v = Number(n)
@@ -122,7 +139,10 @@ function normalizeConfig(config) {
122
139
  authMode: AUTH_MODES.includes(String(input.authMode)) ? String(input.authMode) : DEFAULTS.authMode,
123
140
  strictRedLine: input.strictRedLine === undefined ? DEFAULTS.strictRedLine : input.strictRedLine !== false,
124
141
  backupRoot: typeof input.backupRoot === 'string' ? input.backupRoot : DEFAULTS.backupRoot,
142
+ snapshotGenerations: Math.max(2, Math.min(10, Math.floor(Number(input.snapshotGenerations) || DEFAULTS.snapshotGenerations))),
125
143
  fileBridgePollMs: positiveNumber(input.fileBridgePollMs, DEFAULTS.fileBridgePollMs),
144
+ bridgeAclCheck: input.bridgeAclCheck === undefined ? DEFAULTS.bridgeAclCheck : input.bridgeAclCheck !== false,
145
+ bridgeSecret: typeof input.bridgeSecret === 'string' ? input.bridgeSecret : DEFAULTS.bridgeSecret,
126
146
  role: input.role === 'fork' ? 'fork' : 'mother',
127
147
  }
128
148
  }
@@ -131,7 +151,10 @@ function normalizeConfig(config) {
131
151
  function safeTag(raw) {
132
152
  const s = String(raw ?? '').trim()
133
153
  const cleaned = s.replace(/[^A-Za-z0-9._-]+/g, '_').replace(/^[.]+/, '').slice(0, 64)
134
- return cleaned || 'snap'
154
+ const base = cleaned || 'snap'
155
+ // Distinct raw tags must not collapse onto one directory (a/b vs a_b).
156
+ if (base === s) return base
157
+ return `${base.slice(0, 55)}-${sha256(s).slice(0, 8)}`
135
158
  }
136
159
 
137
160
  /** 内容寻址 digest:按相对路径排序后对 (rel\0contentHash) 串做 sha256,跨平台稳定。 */
@@ -142,6 +165,41 @@ function digestOf(dir) {
142
165
  return { digest: sha256(lines.join('\n')), files: keys.length }
143
166
  }
144
167
 
168
+ /** Restore a snapshot without deleting the live target first. */
169
+ function atomicRestoreDir(sourceDir, targetDir, expectedDigest) {
170
+ const suffix = newId('rollback')
171
+ const tmp = `${targetDir}.restore-${suffix}`
172
+ const old = `${targetDir}.rollback-${suffix}`
173
+ try {
174
+ removeTree(tmp)
175
+ removeTree(old)
176
+ copyTree(sourceDir, tmp)
177
+ const copied = digestOf(tmp)
178
+ if (copied.digest !== expectedDigest) {
179
+ removeTree(tmp)
180
+ return { ok: false, reason: 'digest-mismatch', digest: copied.digest, files: copied.files }
181
+ }
182
+ const hadOld = exists(targetDir)
183
+ if (hadOld) fs.renameSync(targetDir, old)
184
+ try {
185
+ fs.renameSync(tmp, targetDir)
186
+ } catch (error) {
187
+ if (hadOld && !exists(targetDir)) {
188
+ try { fs.renameSync(old, targetDir) } catch { /* best effort restore */ }
189
+ }
190
+ throw error
191
+ }
192
+ if (hadOld) removeTree(old)
193
+ return { ok: true, digest: copied.digest, files: copied.files }
194
+ } catch (error) {
195
+ removeTree(tmp)
196
+ if (exists(old) && !exists(targetDir)) {
197
+ try { fs.renameSync(old, targetDir) } catch { /* best effort restore */ }
198
+ }
199
+ throw error
200
+ }
201
+ }
202
+
145
203
  function normalizeThreshold(threshold) {
146
204
  if (typeof threshold === 'number') {
147
205
  return Number.isFinite(threshold) ? { op: '>', value: threshold } : null
@@ -163,8 +221,65 @@ function thresholdHit(value, threshold) {
163
221
  return value <= threshold.value
164
222
  }
165
223
 
166
- export function apply(ctx, config) {
224
+ /**
225
+ * Best-effort platform ACL check for the file-bridge directory. The bridge is a
226
+ * local-only compatibility path; if the directory is writable by broad principals
227
+ * we disable it rather than expose command execution to any local process.
228
+ */
229
+ function checkBridgeAcl(dir) {
230
+ try {
231
+ const st = fs.statSync(dir)
232
+ if (process.platform !== 'win32') {
233
+ if (typeof process.getuid === 'function' && st.uid !== process.getuid()) {
234
+ return { ok: false, reason: 'bridge-dir-not-owned' }
235
+ }
236
+ if ((st.mode & 0o022) !== 0) return { ok: false, reason: 'bridge-dir-group-or-world-writable' }
237
+ return { ok: true, platform: 'posix', mode: st.mode & 0o777 }
238
+ }
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
241
+ const resolved = path.resolve(dir).toLowerCase()
242
+ let checked = 0
243
+ for (const rawLine of String(output).split(/\r?\n/)) {
244
+ let line = rawLine.trim()
245
+ if (!line) continue
246
+ if (line.toLowerCase().startsWith(resolved)) line = line.slice(path.resolve(dir).length).trim()
247
+ if (!line.includes(':')) continue
248
+ checked += 1
249
+ if (dangerous.test(line)) return { ok: false, reason: 'bridge-dir-world-accessible', detail: line }
250
+ }
251
+ if (checked === 0) return { ok: false, reason: 'bridge-acl-unreadable' }
252
+ return { ok: true, platform: 'win32' }
253
+ } catch (error) {
254
+ return { ok: false, reason: 'bridge-acl-check-failed', error: String(error?.message ?? error) }
255
+ }
256
+ }
257
+
258
+ function stableStringify(value) {
259
+ if (value === null || typeof value !== 'object') return JSON.stringify(value)
260
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`
261
+ return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`
262
+ }
263
+
264
+ function verifyBridgeSignature(payload, secret) {
265
+ if (!secret) return true
266
+ if (!payload || typeof payload !== 'object') return false
267
+ const signature = String(payload.signature ?? '')
268
+ if (!/^[0-9a-f]{64}$/i.test(signature)) return false
269
+ const copy = { ...payload }
270
+ delete copy.signature
271
+ const expected = crypto.createHmac('sha256', secret).update(stableStringify(copy)).digest('hex')
272
+ try {
273
+ return crypto.timingSafeEqual(Buffer.from(signature.toLowerCase(), 'hex'), Buffer.from(expected, 'hex'))
274
+ } catch {
275
+ return false
276
+ }
277
+ }
278
+
279
+
167
280
  // v2 §1:角色门禁必须是 apply 的第一件事;未部署到该角色时不注册服务/定时器/文件桥。
281
+ export function apply(ctx, config) {
282
+ // v2 role gate: must be the first thing apply does.
168
283
  const gate = roleGate('approver', {
169
284
  cfgRole: config && typeof config === 'object' ? config.role : '',
170
285
  logger: ctx.logger,
@@ -182,6 +297,23 @@ export function apply(ctx, config) {
182
297
  status: path.join(dataDir, BRIDGE.status),
183
298
  }
184
299
  const decisionsFile = path.join(dataDir, DECISIONS_FILE)
300
+ const journalFile = path.join(dataDir, JOURNAL_FILE)
301
+ const snapshotsIndexFile = path.join(snapshotsRoot, 'index.json')
302
+ const bridgeSecret = String(process.env.FANG_BRIDGE_SECRET ?? cfg.bridgeSecret ?? '').trim()
303
+ let bridgeAcl = null
304
+ let bridgeSecurityChecked = false
305
+ const ensureBridgeSecurity = () => {
306
+ if (bridgeSecurityChecked) return bridgeAcl?.ok === true
307
+ bridgeSecurityChecked = true
308
+ if (!cfg.bridgeAclCheck) {
309
+ bridgeAcl = { ok: true, skipped: true }
310
+ return true
311
+ }
312
+ try { ensureDir(dataDir) } catch { /* check will fail closed below */ }
313
+ bridgeAcl = checkBridgeAcl(dataDir)
314
+ if (!bridgeAcl.ok) logger('warn', `[fang-approver] file bridge disabled: ${bridgeAcl.reason}`)
315
+ return bridgeAcl.ok === true
316
+ }
185
317
 
186
318
  /** id → item(结案后保留一小段用于幂等判定,超过上限再修剪)。 */
187
319
  const queue = new Map()
@@ -191,6 +323,60 @@ export function apply(ctx, config) {
191
323
  const snapshots = new Map()
192
324
  /** label → {label, samples:[{at,value}], min, max, last, alerts:[], threshold} */
193
325
  const monitors = new Map()
326
+
327
+ // Snapshot generation directories outlive the process, but digest metadata used to
328
+ // live only in this Map. Persist it so rollback still works after a restart.
329
+ const persistSnapshotIndex = () => {
330
+ try {
331
+ ensureDir(snapshotsRoot)
332
+ writeJsonAtomic(snapshotsIndexFile, {
333
+ version: 2,
334
+ snapshots: [...snapshots.values()].map((record) => ({
335
+ tag: record.tag,
336
+ A: record.A ? { digest: record.A.digest, at: record.A.at, files: record.A.files } : null,
337
+ B: record.B ? { digest: record.B.digest, at: record.B.at, files: record.B.files } : null,
338
+ generations: (record.generations ?? []).map((generation) => ({
339
+ slot: generation.slot, digest: generation.digest, at: generation.at, files: generation.files,
340
+ })),
341
+ })),
342
+ })
343
+ } catch (error) {
344
+ logger('warn', `[fang-approver] snapshot index write failed: ${String(error?.message ?? error)}`)
345
+ }
346
+ }
347
+
348
+ const loadSnapshotIndex = () => {
349
+ const raw = readTextSafe(snapshotsIndexFile, '')
350
+ if (!raw) return
351
+ let parsed = null
352
+ try { parsed = JSON.parse(raw) } catch { return }
353
+ for (const entry of Array.isArray(parsed?.snapshots) ? parsed.snapshots : []) {
354
+ const tag = safeTag(entry?.tag)
355
+ const base = path.join(snapshotsRoot, tag)
356
+ const slot = (name, explicitSource) => {
357
+ const source = explicitSource ?? entry?.[name]
358
+ if (!source || typeof source.digest !== 'string') return null
359
+ const dir = path.join(base, name)
360
+ if (!exists(dir)) return null
361
+ return { slot: name, dir, digest: source.digest, at: Number(source.at) || 0, files: Number(source.files) || 0 }
362
+ }
363
+ let generations = []
364
+ if (Array.isArray(entry?.generations)) {
365
+ for (const rawGen of entry.generations) {
366
+ const name = String(rawGen?.slot ?? '').toUpperCase()
367
+ if (!/^[A-J]$/.test(name)) continue
368
+ const loaded = slot(name, rawGen)
369
+ if (loaded) generations.push(loaded)
370
+ }
371
+ }
372
+ if (!generations.length) generations = [slot('A'), slot('B')].filter(Boolean)
373
+ generations.sort((a, b) => a.slot.localeCompare(b.slot))
374
+ const A = generations[0] ?? null
375
+ if (!A) continue
376
+ snapshots.set(tag, { tag, A, B: generations[1] ?? null, generations })
377
+ }
378
+ }
379
+ loadSnapshotIndex()
194
380
  /** 所有 TTL/提醒定时器,dispose 时统一清理。 */
195
381
  const timers = new Set()
196
382
  let disposed = false
@@ -227,6 +413,10 @@ export function apply(ctx, config) {
227
413
  createdAt: item.createdAt,
228
414
  deadlineAt: item.deadlineAt,
229
415
  state: item.state,
416
+ by: item.by ?? null,
417
+ note: item.note ?? null,
418
+ resolvedAt: item.resolvedAt ?? null,
419
+ orphanedAt: item.orphanedAt ?? null,
230
420
  reminded: item.reminded === true,
231
421
  })
232
422
 
@@ -249,6 +439,117 @@ export function apply(ctx, config) {
249
439
  }
250
440
 
251
441
  const pendingItems = () => [...queue.values()].filter(item => item.state === 'pending').map(publicItem)
442
+ const orphanedItems = () => [...queue.values()].filter(item => item.state === 'orphaned').map(publicItem)
443
+
444
+ /**
445
+ * A previous process may have left pending.json behind. Those Promises died with
446
+ * that process, so restoring them as "pending" would be a lie. Mark them orphaned,
447
+ * keep them visible for the UI/CLI, and never resolve a Promise that no longer exists.
448
+ */
449
+ const recoverOrphaned = () => {
450
+ const raw = readTextSafe(bridgePaths.pending, '')
451
+ if (!raw) return
452
+ let list = null
453
+ try { list = JSON.parse(raw) } catch { return }
454
+ let recovered = 0
455
+ for (const entry of Array.isArray(list) ? list : []) {
456
+ const id = String(entry?.id ?? '').trim()
457
+ if (!id || queue.has(id)) continue
458
+ const at = nowMs()
459
+ const item = {
460
+ id,
461
+ kind: String(entry?.kind ?? 'unknown'),
462
+ risk: RISK_VALUES.includes(String(entry?.risk)) ? String(entry.risk) : 'red',
463
+ title: String(entry?.title ?? ''),
464
+ detail: String(entry?.detail ?? ''),
465
+ impact: entry?.impact ?? null,
466
+ taskId: entry?.taskId === undefined || entry?.taskId === null ? null : String(entry.taskId),
467
+ pluginId: entry?.pluginId === undefined || entry?.pluginId === null ? null : String(entry.pluginId),
468
+ createdAt: Number(entry?.createdAt) || at,
469
+ deadlineAt: Number(entry?.deadlineAt) || at,
470
+ ttlMs: Number(entry?.ttlMs) || cfg.defaultTtlMs,
471
+ state: 'orphaned',
472
+ by: 'restart',
473
+ note: 'process-restarted',
474
+ reminded: entry?.reminded === true,
475
+ resolvedAt: at,
476
+ orphanedAt: at,
477
+ resolve: null,
478
+ timers: new Set(),
479
+ }
480
+ queue.set(id, item)
481
+ touched = true
482
+ recovered += 1
483
+ audit('approval-interrupted', {
484
+ id, kind: item.kind, risk: item.risk, title: item.title,
485
+ taskId: item.taskId, pluginId: item.pluginId,
486
+ previousState: 'pending', state: 'orphaned', by: 'restart',
487
+ })
488
+ }
489
+ if (recovered > 0) persist()
490
+ }
491
+
492
+ // ───────── 1a) 崩溃 journal ─────────
493
+ let journalWrites = 0
494
+ const appendJournal = (entry) => {
495
+ try {
496
+ appendJsonl(journalFile, { at: iso(), ...entry })
497
+ journalWrites += 1
498
+ } catch (error) {
499
+ logger('warn', `[fang-approver] journal append failed: ${String(error?.message ?? error)}`)
500
+ }
501
+ }
502
+
503
+ /** Journal 里 request 未出现 settled/timeout → 进程在 pending 期间崩溃;恢复为 orphaned,绝不复活 Promise。 */
504
+ const recoverJournal = () => {
505
+ const entries = readJsonl(journalFile)
506
+ if (!entries.length) return
507
+ const requests = new Map()
508
+ const terminal = new Set()
509
+ for (const entry of entries) {
510
+ const id = String(entry?.id ?? '').trim()
511
+ if (!id) continue
512
+ const type = String(entry?.type ?? '')
513
+ if (type === 'request') requests.set(id, entry)
514
+ else if (type === 'settled' || type === 'timeout' || type === 'orphaned') terminal.add(id)
515
+ }
516
+ let recovered = 0
517
+ const at = nowMs()
518
+ for (const [id, entry] of requests) {
519
+ if (terminal.has(id) || queue.has(id)) continue
520
+ const item = {
521
+ id,
522
+ kind: String(entry.kind ?? 'unknown'),
523
+ risk: RISK_VALUES.includes(String(entry.risk)) ? String(entry.risk) : 'red',
524
+ title: String(entry.title ?? ''),
525
+ detail: String(entry.detail ?? ''),
526
+ impact: entry.impact ?? null,
527
+ taskId: entry.taskId === undefined || entry.taskId === null ? null : String(entry.taskId),
528
+ pluginId: entry.pluginId === undefined || entry.pluginId === null ? null : String(entry.pluginId),
529
+ createdAt: Number(entry.createdAt) || at,
530
+ deadlineAt: Number(entry.deadlineAt) || at,
531
+ ttlMs: Number(entry.ttlMs) || cfg.defaultTtlMs,
532
+ state: 'orphaned',
533
+ by: 'restart',
534
+ note: 'process-restarted(journal)',
535
+ reminded: entry.reminded === true,
536
+ resolvedAt: at,
537
+ orphanedAt: at,
538
+ resolve: null,
539
+ timers: new Set(),
540
+ }
541
+ queue.set(id, item)
542
+ touched = true
543
+ recovered += 1
544
+ appendJournal({ type: 'orphaned', id, by: 'restart', source: 'journal' })
545
+ audit('approval-interrupted', {
546
+ id, kind: item.kind, risk: item.risk, title: item.title,
547
+ taskId: item.taskId, pluginId: item.pluginId,
548
+ previousState: 'pending', state: 'orphaned', by: 'restart', source: 'journal',
549
+ })
550
+ }
551
+ if (recovered > 0) persist()
552
+ }
252
553
 
253
554
  /** 把状态同步到 dataDir 的 pending/status 文件(文件桥)。任何异常都只记日志。 */
254
555
  const persist = () => {
@@ -262,11 +563,13 @@ export function apply(ctx, config) {
262
563
  snapshotsRoot,
263
564
  counts: {
264
565
  pending: pending.length,
566
+ orphaned: orphanedItems().length,
265
567
  snapshots: snapshots.size,
266
568
  monitors: monitors.size,
267
569
  decisions: decisions.length,
268
570
  },
269
571
  pending,
572
+ orphaned: orphanedItems(),
270
573
  decided,
271
574
  snapshots: [...snapshots.values()].map(rec => snapshotView(rec, { short: true })),
272
575
  monitors: [...monitors.values()].map(rec => monitorView(rec, { sampleLimit: 5 })),
@@ -330,6 +633,7 @@ export function apply(ctx, config) {
330
633
  clearItemTimers(item)
331
634
  const result = { id: item.id, outcome, by: item.by, at: iso() }
332
635
  recordDecision(item, outcome, item.by, note)
636
+ appendJournal({ type: 'settled', id: item.id, outcome, by: item.by, note })
333
637
  try { item.resolve(result) } catch (e) {
334
638
  logger('debug', `[fang-approver] resolve failed: ${String(e?.message ?? e)}`)
335
639
  }
@@ -366,6 +670,16 @@ export function apply(ctx, config) {
366
670
  }
367
671
  // 未知风险按红处理(fail-closed);未知 kind 记 unknown。
368
672
  const risk = RISK_VALUES.includes(String(raw.risk)) ? String(raw.risk) : 'red'
673
+ const kind = String(raw.kind ?? 'unknown')
674
+ const kindKey = kind.trim().toLowerCase()
675
+ // Mother-only semantic kinds must be blocked at the generic request() layer too:
676
+ // requestPromotion/requestRestart already gate themselves, but a caller can call
677
+ // request({kind:'promotion'}) directly.
678
+ if ((kindKey === 'promotion' || kindKey === 'restart') && scope !== 'mother') {
679
+ const denied = { id, outcome: 'denied', by: 'scope', reason: 'mother-only', at: iso() }
680
+ audit(AUDIT.APPROVAL_DECIDED, { id, kind, risk, outcome: 'denied', by: 'scope', reason: 'mother-only' })
681
+ return Promise.resolve(denied)
682
+ }
369
683
  const ttl = positiveNumber(raw.ttlMs, cfg.defaultTtlMs)
370
684
  const createdAt = nowMs()
371
685
 
@@ -406,6 +720,11 @@ export function apply(ctx, config) {
406
720
  deadlineAt: item.deadlineAt,
407
721
  authMode: cfg.authMode,
408
722
  })
723
+ appendJournal({
724
+ type: 'request', id, kind: item.kind, risk, title: item.title,
725
+ detail: item.detail, impact: item.impact, taskId: item.taskId, pluginId: item.pluginId,
726
+ createdAt: item.createdAt, deadlineAt: item.deadlineAt, ttlMs: ttl,
727
+ })
409
728
 
410
729
  const autoBypass = cfg.authMode === 'auto' && (risk !== 'red' || cfg.strictRedLine === false)
411
730
  if (autoBypass) {
@@ -467,6 +786,11 @@ export function apply(ctx, config) {
467
786
  * risk 固定红灯(晋升母体不可降级),pluginId/taskId 透传到 pending()/summary()。
468
787
  */
469
788
  const requestPromotion = (input = {}) => {
789
+ if (scope !== 'mother') {
790
+ const denied = { id: newId('apr'), outcome: 'denied', by: 'scope', at: iso(), reason: 'mother-only' }
791
+ audit(AUDIT.APPROVAL_DECIDED, { kind: 'promotion', outcome: 'denied', by: 'scope', reason: 'mother-only' })
792
+ return Promise.resolve(denied)
793
+ }
470
794
  const raw = input && typeof input === 'object' ? input : {}
471
795
  const pluginId = raw.pluginId === undefined || raw.pluginId === null ? '' : String(raw.pluginId).trim()
472
796
  const detail = raw.detail === undefined || raw.detail === null
@@ -488,6 +812,11 @@ export function apply(ctx, config) {
488
812
 
489
813
  /** v2 §5.7 母体语义:母体重启审批 == request({kind:'restart', risk:'red'});risk 由服务强制红灯。 */
490
814
  const requestRestart = (input = {}) => {
815
+ if (scope !== 'mother') {
816
+ const denied = { id: newId('apr'), outcome: 'denied', by: 'scope', at: iso(), reason: 'mother-only' }
817
+ audit(AUDIT.APPROVAL_DECIDED, { kind: 'restart', outcome: 'denied', by: 'scope', reason: 'mother-only' })
818
+ return Promise.resolve(denied)
819
+ }
491
820
  const raw = input && typeof input === 'object' ? input : {}
492
821
  const reason = raw.reason === undefined || raw.reason === null ? '' : String(raw.reason)
493
822
  const detail = raw.detail === undefined || raw.detail === null ? reason : String(raw.detail)
@@ -546,15 +875,22 @@ export function apply(ctx, config) {
546
875
  const remote = await Promise.all(remotes.map(fetchRemoteApprovals))
547
876
  const failed = remote.filter(entry => entry.ok === false).length
548
877
  const total = local.length + remote.reduce((sum, entry) => sum + (entry.ok ? entry.items.length : 0), 0)
549
- return { ok: true, scope, local, remote, total, failed, degraded: failed > 0 }
878
+ return { ok: true, scope, local, remote, total, failed, degraded: failed > 0, complete: failed === 0 }
550
879
  }
551
880
 
552
- // ───────── 2) A/B 双备 ─────────
881
+ // ───────── 2) 多代快照(A 最新,B/C… 历史;默认 3 代)─────────
882
+
883
+ const GENERATION_SLOTS = Object.freeze(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'])
884
+ const generationSlots = () => GENERATION_SLOTS.slice(0, cfg.snapshotGenerations)
885
+
886
+ const publicGeneration = (generation) => generation
887
+ ? { slot: generation.slot, digest: generation.digest, at: generation.at, files: generation.files }
888
+ : null
553
889
 
554
890
  /**
555
- * 契约:snapshot({tag, dir}) -> {tag, A:{digest,at}, B:null|{digest,at}}
556
- * A = 本次快照(当前内容),B = 上一次快照(上一代)。落盘位置:
557
- * <snapshotsRoot>/<tag>/A 和 <snapshotsRoot>/<tag>/B
891
+ * 契约扩展:snapshot({tag, dir}) -> {tag, A, B, generations}
892
+ * A = 本次快照(当前内容),B/C… = 历史代;保留代数由 snapshotGenerations 控制。
893
+ * 落盘位置:<snapshotsRoot>/<tag>/A、/B、/C…
558
894
  */
559
895
  const snapshot = (options = {}) => {
560
896
  const sourceDir = options?.dir ? path.resolve(String(options.dir)) : ''
@@ -563,34 +899,51 @@ export function apply(ctx, config) {
563
899
  }
564
900
  const tag = safeTag(options?.tag ?? path.basename(sourceDir))
565
901
  const baseDir = path.join(snapshotsRoot, tag)
566
- const aDir = path.join(baseDir, 'A')
567
- const bDir = path.join(baseDir, 'B')
568
902
  const previous = snapshots.get(tag) ?? null
903
+ const slots = generationSlots()
904
+ const slotDir = (name) => path.join(baseDir, name)
569
905
  touched = true
570
906
  try {
571
907
  ensureDir(baseDir)
572
- // 旧 A 滚到 B(只保留一代);否则上一代就被新快照覆盖丢弃。
573
- if (previous?.A && exists(aDir)) {
574
- removeTree(bDir)
575
- copyTree(aDir, bDir)
576
- removeTree(aDir)
908
+ // 先把新内容复制到 staging,成功后再轮换,避免 copy 失败破坏旧代。
909
+ const staging = path.join(baseDir, `.staging-${newId('snap')}`)
910
+ removeTree(staging)
911
+ copyTree(sourceDir, staging)
912
+ const { digest, files } = digestOf(staging)
913
+ // 从最老一代往前轮换:删除最老,B→C…,A→B。
914
+ for (let index = slots.length - 1; index >= 1; index -= 1) {
915
+ removeTree(slotDir(slots[index]))
916
+ if (exists(slotDir(slots[index - 1]))) fs.renameSync(slotDir(slots[index - 1]), slotDir(slots[index]))
577
917
  }
578
- copyTree(sourceDir, aDir)
579
- const { digest, files } = digestOf(aDir)
918
+ removeTree(slotDir('A'))
919
+ fs.renameSync(staging, slotDir('A'))
920
+ const previousGenerations = Array.isArray(previous?.generations)
921
+ ? previous.generations
922
+ : [previous?.A, previous?.B].filter(Boolean)
923
+ const generations = [
924
+ { slot: 'A', dir: slotDir('A'), digest, at: nowMs(), files },
925
+ ...previousGenerations.slice(0, slots.length - 1).map((generation, index) => ({
926
+ slot: slots[index + 1], dir: slotDir(slots[index + 1]),
927
+ digest: generation.digest, at: generation.at, files: generation.files,
928
+ })),
929
+ ]
580
930
  const record = {
581
931
  tag,
582
- A: { dir: aDir, digest, at: nowMs(), files },
583
- B: previous?.A
584
- ? { dir: bDir, digest: previous.A.digest, at: previous.A.at, files: previous.A.files }
585
- : null,
932
+ A: generations[0],
933
+ B: generations[1] ?? null,
934
+ generations,
586
935
  }
936
+ for (const generation of generations) record[generation.slot] = generation
587
937
  snapshots.set(tag, record)
588
- audit(AUDIT_SNAPSHOT_CREATED, { tag, dir: sourceDir, digest, files, hasB: record.B !== null })
938
+ persistSnapshotIndex()
939
+ audit(AUDIT_SNAPSHOT_CREATED, { tag, dir: sourceDir, digest, files, generations: generations.length })
589
940
  persist()
590
941
  return {
591
942
  tag,
592
943
  A: { digest: record.A.digest, at: record.A.at },
593
944
  B: record.B ? { digest: record.B.digest, at: record.B.at } : null,
945
+ C: record.C ? { digest: record.C.digest, at: record.C.at } : null,
946
+ generations: generations.map(publicGeneration),
594
947
  }
595
948
  } catch (e) {
596
949
  logger('warn', `[fang-approver] snapshot failed: ${String(e?.message ?? e)}`)
@@ -599,8 +952,8 @@ export function apply(ctx, config) {
599
952
  }
600
953
 
601
954
  /**
602
- * 契约:rollback({tag, dir}) -> {ok, restored}
603
- * 默认从 A(最近一次快照)恢复;可传 to:'B' 恢复上一代。恢复后重算 digest 并校验。
955
+ * 契约扩展:rollback({tag, dir, to?}) -> {ok, restored}
956
+ * to 支持 A…J(默认 A);恢复后重算 digest 并校验。
604
957
  */
605
958
  const rollback = (options = {}) => {
606
959
  const rawTag = String(options?.tag ?? '').trim()
@@ -610,23 +963,24 @@ export function apply(ctx, config) {
610
963
  if (!record) return { ok: false, reason: 'no-snapshot', tag }
611
964
  const targetDir = options?.dir ? path.resolve(String(options.dir)) : ''
612
965
  if (!targetDir) return { ok: false, reason: 'no-target-dir', tag }
613
- const slotName = String(options?.to ?? 'A').toUpperCase() === 'B' ? 'B' : 'A'
614
- const slot = record[slotName]
966
+ const requested = String(options?.to ?? 'A').toUpperCase()
967
+ const slotName = /^[A-J]$/.test(requested) ? requested : 'A'
968
+ const slot = record[slotName] ?? (record.generations ?? []).find((generation) => generation.slot === slotName) ?? null
615
969
  if (!slot || !exists(slot.dir)) return { ok: false, reason: 'slot-empty', tag, slot: slotName }
616
970
  touched = true
617
971
  try {
618
- removeTree(targetDir)
619
- ensureDir(targetDir)
620
- copyTree(slot.dir, targetDir)
621
- const { digest, files } = digestOf(targetDir)
622
- const matched = digest === slot.digest
623
- const restored = { tag, slot: slotName, dir: targetDir, digest, files, expected: slot.digest, matches: matched, at: iso() }
624
- if (!matched) {
625
- audit(AUDIT.ROLLBACK, { tag, slot: slotName, dir: targetDir, digest, expected: slot.digest, ok: false, reason: 'digest-mismatch' })
972
+ const copy = atomicRestoreDir(slot.dir, targetDir, slot.digest)
973
+ const restored = {
974
+ tag, slot: slotName, dir: targetDir,
975
+ digest: copy.digest, files: copy.files ?? null,
976
+ expected: slot.digest, matches: copy.ok === true, at: iso(),
977
+ }
978
+ if (!copy.ok) {
979
+ audit(AUDIT.ROLLBACK, { tag, slot: slotName, dir: targetDir, digest: copy.digest, expected: slot.digest, ok: false, reason: copy.reason })
626
980
  persist()
627
- return { ok: false, reason: 'digest-mismatch', tag, slot: slotName, restored }
981
+ return { ok: false, reason: copy.reason, tag, slot: slotName, restored }
628
982
  }
629
- audit(AUDIT.ROLLBACK, { tag, slot: slotName, dir: targetDir, digest, files, ok: true })
983
+ audit(AUDIT.ROLLBACK, { tag, slot: slotName, dir: targetDir, digest: copy.digest, files: copy.files, ok: true })
630
984
  persist()
631
985
  return { ok: true, restored }
632
986
  } catch (e) {
@@ -691,14 +1045,17 @@ export function apply(ctx, config) {
691
1045
  const status = () => ({
692
1046
  scope,
693
1047
  pending: pendingItems().length,
1048
+ orphaned: orphanedItems().length,
694
1049
  snapshots: snapshots.size,
695
1050
  monitors: monitors.size,
696
1051
  decisions: decisions.length,
697
1052
  pendingItems: pendingItems(),
698
1053
  snapshotsList: [...snapshots.values()].map(rec => snapshotView(rec)),
1054
+ orphanedList: orphanedItems(),
699
1055
  monitorsList: [...monitors.values()].map(rec => monitorView(rec)),
700
1056
  lastDecisions: decisions.slice(-10),
701
1057
  policy: { authMode: cfg.authMode, strictRedLine: cfg.strictRedLine, defaultTtlMs: cfg.defaultTtlMs },
1058
+ bridge: { enabled: bridgeAcl ? bridgeAcl.ok === true : null, checked: bridgeSecurityChecked, acl: bridgeAcl, signed: bridgeSecret.length > 0 },
702
1059
  dataDir,
703
1060
  snapshotsRoot,
704
1061
  })
@@ -726,6 +1083,7 @@ export function apply(ctx, config) {
726
1083
 
727
1084
  /** command 文件:读取后立即消费(先删再执行,避免重复执行)。 */
728
1085
  const pollCommandFile = () => {
1086
+ if (!ensureBridgeSecurity()) return
729
1087
  const raw = readTextSafe(bridgePaths.command, '')
730
1088
  if (!raw) return
731
1089
  removeTree(bridgePaths.command)
@@ -734,6 +1092,11 @@ export function apply(ctx, config) {
734
1092
  logger('warn', '[fang-approver] command file is not valid JSON; ignored')
735
1093
  return
736
1094
  }
1095
+ if (!verifyBridgeSignature(command, bridgeSecret)) {
1096
+ logger('warn', '[fang-approver] command rejected: missing or invalid bridge signature')
1097
+ audit('approval-bridge-rejected', { bridge: 'command', reason: 'bad-signature' })
1098
+ return
1099
+ }
737
1100
  try { runBridgeCommand(command) } catch (e) {
738
1101
  logger('warn', `[fang-approver] bridge command failed: ${String(e?.message ?? e)}`)
739
1102
  }
@@ -741,21 +1104,41 @@ export function apply(ctx, config) {
741
1104
 
742
1105
  /** answer 文件:兼容老 CLI 的 {id, decision:'approve'|'deny'} 写法。 */
743
1106
  const pollAnswerFile = () => {
1107
+ if (!ensureBridgeSecurity()) return
744
1108
  const raw = readTextSafe(bridgePaths.answer, '')
745
1109
  if (!raw) return
746
1110
  let answer = null
747
- try { answer = JSON.parse(String(raw).replace(/^\uFEFF/, '')) } catch { return }
1111
+ try { answer = JSON.parse(String(raw).replace(/^\uFEFF/, '')) } catch {
1112
+ logger('warn', '[fang-approver] answer file is not valid JSON; consumed')
1113
+ removeTree(bridgePaths.answer)
1114
+ return
1115
+ }
1116
+ if (!verifyBridgeSignature(answer, bridgeSecret)) {
1117
+ logger('warn', '[fang-approver] answer rejected: missing or invalid bridge signature')
1118
+ audit('approval-bridge-rejected', { bridge: 'answer', reason: 'bad-signature' })
1119
+ removeTree(bridgePaths.answer)
1120
+ return
1121
+ }
748
1122
  const id = String(answer?.id ?? '')
749
1123
  const item = queue.get(id)
750
- if (!item || item.state !== 'pending') return
1124
+ if (!item || item.state !== 'pending') {
1125
+ // Do not leave an unusable answer on disk for every 300ms poll.
1126
+ logger('warn', `[fang-approver] answer for unknown/non-pending item ${id || '(empty)'}; consumed`)
1127
+ removeTree(bridgePaths.answer)
1128
+ return
1129
+ }
751
1130
  decide(id, bridgeOutcome(answer), { by: String(answer?.by ?? 'file'), note: answer?.note })
752
1131
  removeTree(bridgePaths.answer)
753
1132
  }
754
1133
 
1134
+ recoverOrphaned()
1135
+ recoverJournal()
1136
+
755
1137
  const service = {
756
1138
  scope,
757
1139
  request,
758
1140
  pending,
1141
+ orphaned: orphanedItems,
759
1142
  decide,
760
1143
  requestPromotion,
761
1144
  requestRestart,