@twinsearth/dsh-fang 3.3.2 → 3.7.7
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.
- package/README.md +5 -5
- package/client.js +674 -60
- package/cordis.patch.yml +26 -20
- package/docs/APPROVAL-DRILL.md +42 -0
- package/docs/AUTO-WATCHDOG.md +46 -0
- package/docs/DECISION-LOSSLESS.md +36 -0
- package/docs/ESSENCE-AUTO-SYNC.md +32 -0
- package/docs/INBOX-SCROLL.md +33 -0
- package/docs/PACKAGE-RENAME-v3.3.3.md +40 -0
- package/docs/RESTART-CONFIRMATION.md +29 -0
- package/docs/TEST-STABILITY-v3.4.0.md +30 -0
- package/package.json +11 -7
- package/src/compose.mjs +4 -1
- package/src/contract/VENDOR.json +6 -5
- package/src/contract/constants.js +16 -1
- package/src/contract/relay.js +12 -6
- package/src/kernel/types.mjs +3 -1
- package/src/lib/accelerated-fork.mjs +813 -0
- package/src/lib/accelerated-install.mjs +295 -0
- package/src/lib/accelerated-web.mjs +103 -0
- package/src/lib/approval-drill.mjs +111 -0
- package/src/lib/boot-guard.mjs +6 -2
- package/src/lib/chat-import-delegation.mjs +47 -0
- package/src/lib/compat.mjs +5 -1
- package/src/lib/contract-delegation.mjs +161 -0
- package/src/lib/default-essence.mjs +7 -4
- package/src/lib/essence.mjs +113 -7
- package/src/lib/fork-config-lock.mjs +2 -2
- package/src/lib/fork-core-settings.mjs +95 -0
- package/src/lib/fork-export.mjs +85 -0
- package/src/lib/global-redline.mjs +164 -0
- package/src/lib/http-auth.mjs +36 -0
- package/src/lib/install-snapshot.mjs +77 -0
- package/src/lib/lsp-delegation.mjs +70 -0
- package/src/lib/lsp-provider.mjs +250 -0
- package/src/lib/main-gate.mjs +33 -28
- package/src/lib/mirror.mjs +115 -4
- package/src/lib/node-compat.mjs +24 -0
- package/src/lib/pro-delegation.mjs +185 -0
- package/src/lib/runtime-capture.mjs +11 -3
- package/src/lib/watch-guard.mjs +51 -0
- package/src/plugins/approver.mjs +5 -2
- package/src/plugins/auditor.mjs +125 -18
- package/src/plugins/decision-center.mjs +77 -34
- package/src/plugins/forker.mjs +258 -33
- package/src/plugins/orchestrator.mjs +1508 -65
- package/src/plugins/restart-guard.mjs +79 -2
- package/src/plugins/session-catalog.mjs +127 -40
- package/tools/approval-drill.mjs +21 -0
- package/tools/fangctl.mjs +21 -4
- package/tools/gate/main-city.mjs +1 -1
- package/tools/restart-supervisor.mjs +425 -0
- package/tools/restart-watchdog.mjs +568 -0
- package/vault/client.js +49 -0
- package/vault/cordis.patch.yml +3 -0
- package/vault/lib/vault.mjs +219 -0
- package/vault/package.json +29 -0
|
@@ -16,6 +16,8 @@
|
|
|
16
16
|
// * needs-approval 时通过 ctx.get(SERVICE.approver)?.request(...) 走审批;审批服务缺失或抛错 => fail-closed。
|
|
17
17
|
import path from 'node:path'
|
|
18
18
|
import fs from 'node:fs'
|
|
19
|
+
import { spawn } from 'node:child_process'
|
|
20
|
+
import { fileURLToPath } from 'node:url'
|
|
19
21
|
import { AUDIT, EXIT, GUARD_STATE, RISK, SERVICE, bus, newId, newUuid, riskAtLeast, z } from '../kernel/index.mjs'
|
|
20
22
|
import {
|
|
21
23
|
appendJsonl,
|
|
@@ -57,6 +59,8 @@ const DEFAULTS = Object.freeze({
|
|
|
57
59
|
strictRedLine: true,
|
|
58
60
|
approvalTimeoutMs: 300000,
|
|
59
61
|
allowProcessRestart: false,
|
|
62
|
+
autoWatchdog: false,
|
|
63
|
+
autoWatchdogTimeoutMs: 4000,
|
|
60
64
|
autoPromoteAfterHours: 24,
|
|
61
65
|
dataRoot: '',
|
|
62
66
|
manifestTtlMs: 60000,
|
|
@@ -73,6 +77,10 @@ export const Config = z.object({
|
|
|
73
77
|
.description('审批等待上限(毫秒);审批服务本身也会收到 ttlMs'),
|
|
74
78
|
allowProcessRestart: z.boolean().default(false)
|
|
75
79
|
.description('第二把钥匙:默认 false。只有 enforce + true + supervisor 在位时才在批准后 exit(75) 交接执行权'),
|
|
80
|
+
autoWatchdog: z.boolean().default(false)
|
|
81
|
+
.description('v3.3.7:批准后若没有 supervisor,自动启动 restart-watchdog 作为看护并再次检查三重门禁;只在 enforce + allowProcessRestart 下生效'),
|
|
82
|
+
autoWatchdogTimeoutMs: z.number().min(500).max(30000).default(4000)
|
|
83
|
+
.description('等待 watchdog 写出 supervisor.present 的上限(毫秒)'),
|
|
76
84
|
autoPromoteAfterHours: z.union([6, 12, 24]).default(24)
|
|
77
85
|
.description('保留字段(bundle 配置兼容):自动晋升归属编排器/晋升流程,本插件不消费'),
|
|
78
86
|
dataRoot: z.string().default('')
|
|
@@ -489,14 +497,73 @@ export function apply(ctx, config) {
|
|
|
489
497
|
return manifest
|
|
490
498
|
}
|
|
491
499
|
|
|
500
|
+
/**
|
|
501
|
+
* v3.3.7:用户选择「自动看护」。批准后若没有 supervisor,由本进程启动
|
|
502
|
+
* restart-watchdog(独立进程),等它写出 supervisor.present 后再检查三重门禁。
|
|
503
|
+
* 只有 enforce + allowProcessRestart + 两次确认才允许走到这里;任何一步失败都
|
|
504
|
+
* fail-closed,不写授权清单、不退出。
|
|
505
|
+
*/
|
|
506
|
+
const startAutoWatchdog = async (req) => {
|
|
507
|
+
const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
|
|
508
|
+
const tool = path.join(packageRoot, 'tools', 'restart-watchdog.mjs')
|
|
509
|
+
if (!fs.existsSync(tool)) return { ok: false, error: 'auto-watchdog-tool-missing', detail: tool }
|
|
510
|
+
if (req?.confirmation?.forkChecked !== true || req?.confirmation?.finalConfirm !== true) {
|
|
511
|
+
return { ok: false, error: 'auto-watchdog-confirmation-required' }
|
|
512
|
+
}
|
|
513
|
+
const relaunch = [process.execPath, ...process.argv.slice(1)]
|
|
514
|
+
if (!relaunch[0]) return { ok: false, error: 'auto-watchdog-relaunch-missing' }
|
|
515
|
+
const node = String(process.env.DSH_NODE_EXECUTABLE ?? '').trim() || process.execPath
|
|
516
|
+
const env = { ...process.env }
|
|
517
|
+
if (String(node).toLowerCase().endsWith('.exe')) env.ELECTRON_RUN_AS_NODE = '1'
|
|
518
|
+
const args = [
|
|
519
|
+
tool, '--execute',
|
|
520
|
+
'--data-root', layout.dataDir,
|
|
521
|
+
'--state-dir', stateDir,
|
|
522
|
+
'--pid-file', layout.pidFile || path.join(layout.dataDir, 'fang.pid'),
|
|
523
|
+
'--poll-ms', '500',
|
|
524
|
+
]
|
|
525
|
+
const profileDir = String(process.env.DSH_PROFILE_DIR ?? '').trim()
|
|
526
|
+
if (profileDir) args.push('--profile-dir', profileDir)
|
|
527
|
+
args.push('--', ...relaunch)
|
|
528
|
+
let child
|
|
529
|
+
try {
|
|
530
|
+
child = spawn(node, args, { cwd: packageRoot, detached: true, stdio: 'ignore', windowsHide: true, env })
|
|
531
|
+
child.unref()
|
|
532
|
+
} catch (error) {
|
|
533
|
+
return { ok: false, error: 'auto-watchdog-spawn-failed', detail: errText(error) }
|
|
534
|
+
}
|
|
535
|
+
const deadline = Date.now() + Number(cfg.autoWatchdogTimeoutMs) || 4000
|
|
536
|
+
while (Date.now() < deadline) {
|
|
537
|
+
const supervisor = detectSupervisor()
|
|
538
|
+
if (supervisor.present) {
|
|
539
|
+
audit('restart-auto-watchdog', { id: req.id, pid: child.pid, supervisor: supervisor.id, via: supervisor.via, relaunch })
|
|
540
|
+
return { ok: true, pid: child.pid, supervisor, relaunch }
|
|
541
|
+
}
|
|
542
|
+
await new Promise((resolve) => setTimeout(resolve, 80))
|
|
543
|
+
}
|
|
544
|
+
try { process.kill(Number(child.pid), 'SIGTERM') } catch { /* best effort */ }
|
|
545
|
+
return { ok: false, error: 'auto-watchdog-timeout', pid: child.pid }
|
|
546
|
+
}
|
|
547
|
+
|
|
492
548
|
/**
|
|
493
549
|
* executing 阶段:默认只记录状态(不退出/不重启)。
|
|
494
550
|
* 批准必须落盘授权清单;写不进去 => fail-closed,按拒绝处理。
|
|
495
551
|
* 三重门禁(enforce + allowProcessRestart + supervisor 在位)齐了才把执行权交出去:
|
|
496
552
|
* 清单/审计/事件落盘后 exit(75),由 watchdog 拉起新宿主并写回执。
|
|
497
553
|
*/
|
|
498
|
-
const finishApproved = (req, { decision, by = null, outcome, approvalId = null, t0 }) => {
|
|
554
|
+
const finishApproved = async (req, { decision, by = null, outcome, approvalId = null, t0 }) => {
|
|
499
555
|
const approvedAt = Date.now()
|
|
556
|
+
let autoWatchdog = null
|
|
557
|
+
let gateState = executionArmed()
|
|
558
|
+
// 用户选择 auto-watchdog:没有 supervisor 时先启动看护,再重新计算三重门禁。
|
|
559
|
+
// 只有明确开启且 enforce + allowProcessRestart 才尝试;否则仍按原 observe 语义。
|
|
560
|
+
if (cfg.autoWatchdog === true && cfg.mode === 'enforce' && cfg.allowProcessRestart === true && gateState.supervisor.present !== true) {
|
|
561
|
+
autoWatchdog = await startAutoWatchdog(req)
|
|
562
|
+
if (autoWatchdog.ok !== true) {
|
|
563
|
+
return finishDenied(req, autoWatchdog.error ?? 'auto-watchdog-failed', 'denied', { by, approvalId, error: autoWatchdog.detail ?? null, ms: Date.now() - t0 })
|
|
564
|
+
}
|
|
565
|
+
gateState = executionArmed()
|
|
566
|
+
}
|
|
500
567
|
let manifest
|
|
501
568
|
try {
|
|
502
569
|
manifest = writeApprovalManifest(req, { by, outcome, approvalId, approvedAt })
|
|
@@ -508,7 +575,6 @@ export function apply(ctx, config) {
|
|
|
508
575
|
}
|
|
509
576
|
machine.state = GUARD_STATE.EXECUTING
|
|
510
577
|
if (machine.pending) machine.pending.phase = GUARD_STATE.EXECUTING
|
|
511
|
-
const gateState = executionArmed()
|
|
512
578
|
const handoff = gateState.armed === true
|
|
513
579
|
persistState(handoff ? {
|
|
514
580
|
handoff: { to: 'supervisor', via: gateState.supervisor.via, at: Date.now(), exitCode: EXIT.RESTART },
|
|
@@ -521,6 +587,7 @@ export function apply(ctx, config) {
|
|
|
521
587
|
plannedExitCode: EXIT.RESTART, // 与 forker.classifyExit 的 restart-request 契约对齐
|
|
522
588
|
manifestDigest: manifest.digest,
|
|
523
589
|
manifestExpiresAt: manifest.expiresAt,
|
|
590
|
+
autoWatchdog,
|
|
524
591
|
handoff: handoff ? {
|
|
525
592
|
requested: true, to: 'supervisor', via: gateState.supervisor.via,
|
|
526
593
|
id: gateState.supervisor.id, exitCode: EXIT.RESTART,
|
|
@@ -549,6 +616,7 @@ export function apply(ctx, config) {
|
|
|
549
616
|
impactSource: req.impactSource ?? null, ms: result.ms,
|
|
550
617
|
manifestDigest: manifest.digest, manifestExpiresAt: manifest.expiresAt,
|
|
551
618
|
manifestPath: authorization.manifestPath,
|
|
619
|
+
autoWatchdog: autoWatchdog ? { ok: autoWatchdog.ok === true, pid: autoWatchdog.pid ?? null, error: autoWatchdog.error ?? null } : null,
|
|
552
620
|
handoff: handoff ? { to: 'supervisor', via: gateState.supervisor.via, exitCode: EXIT.RESTART } : null,
|
|
553
621
|
})
|
|
554
622
|
emit(RESOLVED_TOPIC, { id: req.id, outcome, reason: req.reason, risk: req.risk, approvalId })
|
|
@@ -641,6 +709,14 @@ export function apply(ctx, config) {
|
|
|
641
709
|
risk, reason, scope, origin,
|
|
642
710
|
digests: Array.isArray(input.digests) ? input.digests.map(String) : [],
|
|
643
711
|
forcedApproval: input.forcedApproval === true,
|
|
712
|
+
confirmation: input.confirmation && typeof input.confirmation === 'object'
|
|
713
|
+
? {
|
|
714
|
+
forkChecked: input.confirmation.forkChecked === true,
|
|
715
|
+
finalConfirm: input.confirmation.finalConfirm === true,
|
|
716
|
+
forkId: input.confirmation.forkId ? String(input.confirmation.forkId).slice(0, 200) : null,
|
|
717
|
+
at: Number(input.confirmation.at) || null,
|
|
718
|
+
}
|
|
719
|
+
: null,
|
|
644
720
|
impactSource,
|
|
645
721
|
requestedAt: t0,
|
|
646
722
|
deadlineAt: t0 + cfg.approvalTimeoutMs,
|
|
@@ -666,6 +742,7 @@ export function apply(ctx, config) {
|
|
|
666
742
|
id: req.id, risk: req.risk, reason, scope, origin, digests: req.digests,
|
|
667
743
|
forcedApproval: req.forcedApproval, guardMode: cfg.mode, authMode: cfg.authMode,
|
|
668
744
|
strictRedLine: cfg.strictRedLine, tempEffectiveManual,
|
|
745
|
+
confirmation: req.confirmation,
|
|
669
746
|
impactSource, impact: impactReport,
|
|
670
747
|
})
|
|
671
748
|
emit(REQUESTED_TOPIC, { id: req.id, risk: req.risk })
|
|
@@ -207,23 +207,58 @@ export function apply(ctx, config) {
|
|
|
207
207
|
pinnedSessionIds: index.global.pinnedSessionIds,
|
|
208
208
|
fsApi,
|
|
209
209
|
})
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
workspaceTitle: workspace ? workspace.title : row.workspaceId,
|
|
218
|
-
workspaceKnown: Boolean(workspace),
|
|
219
|
-
updatedAt: row.updatedAt,
|
|
220
|
-
bytes: row.bytes,
|
|
221
|
-
archived: row.archived,
|
|
222
|
-
pinned: row.pinned,
|
|
223
|
-
relPath: row.relPath,
|
|
210
|
+
// 2026-11-21:与 DSH 侧栏对齐 —— 母体会话目录 = 工作区注册表里的**根会话**。
|
|
211
|
+
// 目录扫描会把子代理会话(裸 UUID 目录)和未登记目录也扫出来,它们不是 DSH 会话,
|
|
212
|
+
// 不进入目录/派生弹窗;标题由 DSH 投影缓存提供,保证三方(宿主侧栏/母体面板/派生弹窗)一致。
|
|
213
|
+
const registry = new Map()
|
|
214
|
+
for (const workspace of index.workspaces) {
|
|
215
|
+
for (const sessionId of workspace.sessionIds) {
|
|
216
|
+
if (typeof sessionId === 'string' && !registry.has(sessionId)) registry.set(sessionId, workspace)
|
|
224
217
|
}
|
|
225
|
-
}
|
|
226
|
-
|
|
218
|
+
}
|
|
219
|
+
const degraded = [...index.degraded]
|
|
220
|
+
let sessions = []
|
|
221
|
+
if (registry.size > 0) {
|
|
222
|
+
// 注册表有成员清单 → 与 DSH 侧栏对齐:只列登记过的根会话(排除子代理/未登记目录)。
|
|
223
|
+
const archivedSet = new Set(index.global.archivedSessionIds)
|
|
224
|
+
const pinnedSet = new Set(index.global.pinnedSessionIds)
|
|
225
|
+
for (const row of rows) {
|
|
226
|
+
const workspace = registry.get(row.sessionId)
|
|
227
|
+
if (!workspace) continue // 子代理 / 未登记会话:不进入母体会话目录
|
|
228
|
+
sessions.push({
|
|
229
|
+
sessionId: row.sessionId,
|
|
230
|
+
workspaceId: workspace.id,
|
|
231
|
+
workspaceKey: row.workspaceId,
|
|
232
|
+
workspacePath: workspace.path,
|
|
233
|
+
workspaceTitle: workspace.title,
|
|
234
|
+
workspaceKnown: true,
|
|
235
|
+
updatedAt: row.updatedAt,
|
|
236
|
+
bytes: row.bytes,
|
|
237
|
+
archived: archivedSet.has(row.sessionId),
|
|
238
|
+
pinned: pinnedSet.has(row.sessionId),
|
|
239
|
+
relPath: row.relPath,
|
|
240
|
+
})
|
|
241
|
+
}
|
|
242
|
+
} else {
|
|
243
|
+
// 注册表没有成员清单(旧 home / 手搓测试):保持目录扫描的兼容行为。
|
|
244
|
+
sessions = rows.map((row) => {
|
|
245
|
+
const workspace = keyMap.get(row.workspaceId) ?? null
|
|
246
|
+
return {
|
|
247
|
+
sessionId: row.sessionId,
|
|
248
|
+
workspaceId: workspace ? workspace.id : null,
|
|
249
|
+
workspaceKey: row.workspaceId,
|
|
250
|
+
workspacePath: workspace ? workspace.path : null,
|
|
251
|
+
workspaceTitle: workspace ? workspace.title : row.workspaceId,
|
|
252
|
+
workspaceKnown: Boolean(workspace),
|
|
253
|
+
updatedAt: row.updatedAt,
|
|
254
|
+
bytes: row.bytes,
|
|
255
|
+
archived: row.archived,
|
|
256
|
+
pinned: row.pinned,
|
|
257
|
+
relPath: row.relPath,
|
|
258
|
+
}
|
|
259
|
+
})
|
|
260
|
+
}
|
|
261
|
+
return { ok: true, index, sessions, degraded }
|
|
227
262
|
}
|
|
228
263
|
|
|
229
264
|
/** 对外视图:只给前端展示/选择所需字段(不暴露绝对日志路径)。 */
|
|
@@ -246,9 +281,36 @@ export function apply(ctx, config) {
|
|
|
246
281
|
return isInside(sessionsRoot, file) ? file : null
|
|
247
282
|
}
|
|
248
283
|
|
|
249
|
-
// ──
|
|
284
|
+
// ── 会话标题(DSH 投影缓存优先;日志有界读取兜底)────────────────────
|
|
250
285
|
/** sessionId → { mtimeMs, size, value };日志没变就不重复解帧。 */
|
|
251
286
|
const titleCache = new Map()
|
|
287
|
+
const projectionCacheDir = path.join(storagesRoot, 'session_projcache', 'sessions')
|
|
288
|
+
const projectionCache = new Map()
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* 2026-11-21:DSH 宿主侧栏标题来自 storages/session_projcache;母体面板与派生弹窗
|
|
292
|
+
* 读同一份投影缓存,保证「宿主侧栏 / 母体面板 / 派生弹窗」三方标题一致。
|
|
293
|
+
*/
|
|
294
|
+
const projectionTitleOf = (sessionId) => {
|
|
295
|
+
const file = path.join(projectionCacheDir, `${sessionId}.json`)
|
|
296
|
+
let stat = null
|
|
297
|
+
try { stat = fs.statSync(file) } catch { return null }
|
|
298
|
+
const cached = projectionCache.get(sessionId)
|
|
299
|
+
if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.value
|
|
300
|
+
let value = null
|
|
301
|
+
try {
|
|
302
|
+
const doc = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
303
|
+
const rows = doc?.record?.rows ?? {}
|
|
304
|
+
const title = typeof rows?.title?.val === 'string' ? rows.title.val.trim() : ''
|
|
305
|
+
const blank = rows?.sessionListMetadata?.val?.blank === true
|
|
306
|
+
const createdAt = Number(doc?.record?.identity?.createdAt)
|
|
307
|
+
value = { title: title || null, blank, createdAt: Number.isFinite(createdAt) ? createdAt : null }
|
|
308
|
+
} catch {
|
|
309
|
+
value = null
|
|
310
|
+
}
|
|
311
|
+
projectionCache.set(sessionId, { mtimeMs: stat.mtimeMs, size: stat.size, value })
|
|
312
|
+
return value
|
|
313
|
+
}
|
|
252
314
|
|
|
253
315
|
const titleOf = (session) => {
|
|
254
316
|
const file = logFileFor(session)
|
|
@@ -257,6 +319,7 @@ export function apply(ctx, config) {
|
|
|
257
319
|
try { stat = fs.statSync(file) } catch { /* 读不到就走解帧降级 */ }
|
|
258
320
|
const cached = titleCache.get(session.sessionId)
|
|
259
321
|
if (cached && stat && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.value
|
|
322
|
+
const projection = projectionTitleOf(session.sessionId)
|
|
260
323
|
const decoded = readBoundedEvents({
|
|
261
324
|
file,
|
|
262
325
|
maxFrames: titleMaxFrames,
|
|
@@ -268,13 +331,13 @@ export function apply(ctx, config) {
|
|
|
268
331
|
const header = decoded.events.find((event) => event?.type === 'session')
|
|
269
332
|
const userMessages = decoded.events.filter((event) => event?.type === 'user/message').length
|
|
270
333
|
const value = {
|
|
271
|
-
title: extracted.title,
|
|
272
|
-
titleSource: extracted.titleSource,
|
|
334
|
+
title: projection?.title ?? extracted.title,
|
|
335
|
+
titleSource: projection?.title ? 'projection' : extracted.titleSource,
|
|
273
336
|
preview: extracted.preview,
|
|
274
337
|
messageSeq: extracted.messageSeq,
|
|
275
|
-
createdAt: Number.isFinite(header?.createdAt) ? header.createdAt : null,
|
|
338
|
+
createdAt: Number.isFinite(projection?.createdAt) ? projection.createdAt : (Number.isFinite(header?.createdAt) ? header.createdAt : null),
|
|
276
339
|
userMessages,
|
|
277
|
-
empty: userMessages === 0,
|
|
340
|
+
empty: projection ? projection.blank : userMessages === 0,
|
|
278
341
|
framesDecoded: decoded.framesDecoded,
|
|
279
342
|
degraded: decoded.degraded,
|
|
280
343
|
}
|
|
@@ -282,16 +345,31 @@ export function apply(ctx, config) {
|
|
|
282
345
|
return value
|
|
283
346
|
}
|
|
284
347
|
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
348
|
+
/**
|
|
349
|
+
* R14:目录对外的文本字段必须脱敏(自述契约:「返回的文本一律脱敏」)。
|
|
350
|
+
* 旧实现只对 head 行做了 redact,title/preview/seed/digest 仍会泄漏 token/邮箱/绝对路径。
|
|
351
|
+
*/
|
|
352
|
+
const redactText = (value) => {
|
|
353
|
+
if (typeof value !== 'string') return { text: value, redactions: 0 }
|
|
354
|
+
const result = redact(value)
|
|
355
|
+
return { text: result.text, redactions: result.redactions ?? 0 }
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const titleFields = (info, fallbackTitle = null) => {
|
|
359
|
+
const title = redactText(info.title ?? fallbackTitle ?? null)
|
|
360
|
+
const preview = redactText(info.preview ?? null)
|
|
361
|
+
return {
|
|
362
|
+
title: title.text,
|
|
363
|
+
titleSource: info.title ? (info.titleSource ?? 'unknown') : 'workspace',
|
|
364
|
+
preview: preview.text,
|
|
365
|
+
redactions: title.redactions + preview.redactions,
|
|
366
|
+
titleDegraded: info.degraded ?? [],
|
|
367
|
+
createdAt: info.createdAt ?? null,
|
|
368
|
+
createdAtIso: isIsoFromMs(info.createdAt),
|
|
369
|
+
userMessages: info.userMessages ?? 0,
|
|
370
|
+
empty: info.empty === true,
|
|
371
|
+
}
|
|
372
|
+
}
|
|
295
373
|
|
|
296
374
|
/** 按 sessionId 定位(前端只传 id;路径永远由扫描结果推出)。 */
|
|
297
375
|
const findSession = (sessionId) => {
|
|
@@ -530,7 +608,9 @@ export function apply(ctx, config) {
|
|
|
530
608
|
...(head.ok ? head.degraded : [head.code ?? 'head-failed']),
|
|
531
609
|
])]
|
|
532
610
|
const markdown = buildDigest(session, lines, degraded)
|
|
533
|
-
|
|
611
|
+
// R14:digest 文本会被 derive() 当作 lineage seed 写入分身,兜底再脱敏一次。
|
|
612
|
+
const safeDigest = redactText(markdown)
|
|
613
|
+
const bytes = Buffer.byteLength(safeDigest.text, 'utf8')
|
|
534
614
|
if (bytes > DIGEST_MAX_BYTES) {
|
|
535
615
|
// 契约:超限 halt,不静默截断(调用方要么收紧 previewMaxChars,要么只读 head)。
|
|
536
616
|
return {
|
|
@@ -547,11 +627,11 @@ export function apply(ctx, config) {
|
|
|
547
627
|
ok: true,
|
|
548
628
|
sessionId: session.sessionId,
|
|
549
629
|
// `markdown` 是 orchestrator.derive() 读取的字段(lineage seed);`digest` 为等价别名。
|
|
550
|
-
markdown,
|
|
551
|
-
digest:
|
|
630
|
+
markdown: safeDigest.text,
|
|
631
|
+
digest: safeDigest.text,
|
|
552
632
|
bytes,
|
|
553
633
|
limit: DIGEST_MAX_BYTES,
|
|
554
|
-
redactions: lines.redactions ?? 0,
|
|
634
|
+
redactions: (lines.redactions ?? 0) + safeDigest.redactions,
|
|
555
635
|
degraded,
|
|
556
636
|
}
|
|
557
637
|
}
|
|
@@ -601,12 +681,16 @@ export function apply(ctx, config) {
|
|
|
601
681
|
lines.push(`> degraded: ${decoded.degraded.join(', ')}`)
|
|
602
682
|
}
|
|
603
683
|
const markdown = lines.join('\n')
|
|
684
|
+
// R14:交接种子会写入分身/文件,必须与 head 一样脱敏(title/正文/路径/cwd)。
|
|
685
|
+
const safeTitle = redactText(title)
|
|
686
|
+
const safeMarkdown = redactText(markdown)
|
|
604
687
|
return {
|
|
605
688
|
ok: true,
|
|
606
689
|
sessionId: session.sessionId,
|
|
607
|
-
title,
|
|
608
|
-
markdown,
|
|
609
|
-
|
|
690
|
+
title: safeTitle.text,
|
|
691
|
+
markdown: safeMarkdown.text,
|
|
692
|
+
redactions: safeTitle.redactions + safeMarkdown.redactions,
|
|
693
|
+
bytes: Buffer.byteLength(safeMarkdown.text, 'utf8'),
|
|
610
694
|
messages: conv.messages,
|
|
611
695
|
truncated: conv.truncated,
|
|
612
696
|
framesDecoded: decoded.framesDecoded,
|
|
@@ -618,8 +702,8 @@ export function apply(ctx, config) {
|
|
|
618
702
|
workspaceTitle: session.workspaceTitle,
|
|
619
703
|
createdAt: Number.isFinite(header?.createdAt) ? header.createdAt : null,
|
|
620
704
|
updatedAt: session.updatedAt,
|
|
621
|
-
cwd: typeof header?.cwd === 'string' ? header.cwd : null,
|
|
622
|
-
agentPreset: typeof header?.agentPreset === 'string' ? header.agentPreset : null,
|
|
705
|
+
cwd: typeof header?.cwd === 'string' ? redactText(header.cwd).text : null,
|
|
706
|
+
agentPreset: typeof header?.agentPreset === 'string' ? redactText(header.agentPreset).text : null,
|
|
623
707
|
}
|
|
624
708
|
}
|
|
625
709
|
|
|
@@ -634,7 +718,10 @@ export function apply(ctx, config) {
|
|
|
634
718
|
|
|
635
719
|
status,
|
|
636
720
|
listSessions,
|
|
721
|
+
/** R14:契约/编排器/adapter 读取的是 `.list`,补别名避免“服务形状不匹配”。 */
|
|
722
|
+
list: listSessions,
|
|
637
723
|
getSession,
|
|
724
|
+
get: getSession,
|
|
638
725
|
readHead,
|
|
639
726
|
digest,
|
|
640
727
|
seed,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
3
|
+
// tools/approval-drill.mjs — 隔离审批 drill:真实 request→decide→snapshot→rollback。
|
|
4
|
+
// 用法:node tools/approval-drill.mjs [--json]
|
|
5
|
+
import { cleanupApprovalDrill, runApprovalDrill } from '../src/lib/approval-drill.mjs'
|
|
6
|
+
|
|
7
|
+
const json = process.argv.slice(2).includes('--json')
|
|
8
|
+
const result = await runApprovalDrill()
|
|
9
|
+
const cleanup = cleanupApprovalDrill(result)
|
|
10
|
+
result.cleanup = cleanup
|
|
11
|
+
if (json) console.log(JSON.stringify(result, null, 2))
|
|
12
|
+
else {
|
|
13
|
+
console.log(`${result.ok ? 'GREEN' : 'RED'} approval drill`)
|
|
14
|
+
console.log(` request : ${result.request?.id ?? '-'} kind=${result.request?.kind ?? '-'} risk=${result.request?.risk ?? '-'} outcome=${result.request?.outcome ?? '-'}`)
|
|
15
|
+
console.log(` pending : before=${result.pendingBefore ?? '-'} after=${result.pendingAfter ?? '-'}`)
|
|
16
|
+
console.log(` snapshot : ${result.snapshot?.ok === false ? 'FAIL' : 'ok'}`)
|
|
17
|
+
console.log(` rollback : ${result.rollback?.ok === true ? 'ok' : 'FAIL'} restored=${result.restored === true}`)
|
|
18
|
+
console.log(` residue : ${cleanup ? 'clean' : 'kept ' + (result.dataRoot ?? '')}`)
|
|
19
|
+
if (result.error) console.log(` error : ${result.error}`)
|
|
20
|
+
}
|
|
21
|
+
process.exitCode = result.ok && cleanup ? 0 : 1
|
package/tools/fangctl.mjs
CHANGED
|
@@ -334,8 +334,8 @@ function cmdDoctor(layout) {
|
|
|
334
334
|
let pkg = null
|
|
335
335
|
try { pkg = JSON.parse(fs.readFileSync(path.join(profileDir, 'package.json'), 'utf8')) } catch { /* ignore */ }
|
|
336
336
|
const bundles = Array.isArray(pkg?.dsh?.profile?.bundles) ? pkg.dsh.profile.bundles : []
|
|
337
|
-
const installed = bundles.includes('@twinsearth/dsh-
|
|
338
|
-
check('bundle-installed', installed, installed ? `profiles/${layout.profileTag} 的 bundles 含 @twinsearth/dsh-
|
|
337
|
+
const installed = bundles.includes('@twinsearth/fang-dsh-plugin') || Boolean(pkg?.dependencies?.['@twinsearth/fang-dsh-plugin'])
|
|
338
|
+
check('bundle-installed', installed, installed ? `profiles/${layout.profileTag} 的 bundles 含 @twinsearth/fang-dsh-plugin` : 'profile package.json 未列出 @twinsearth/fang-dsh-plugin(bundle 未安装)')
|
|
339
339
|
|
|
340
340
|
const template = resolveProfileDir(layout.profileTag)
|
|
341
341
|
check('fork-template', exists(template), `${template}(分身 profile 模板;可用 config.profileTemplate 覆盖)`)
|
|
@@ -387,7 +387,24 @@ switch (cmd) {
|
|
|
387
387
|
case 'tail': code = cmdTail(layout, Number(args._[1] ?? 20)); break
|
|
388
388
|
case 'doctor': code = cmdDoctor(layout); break
|
|
389
389
|
case 'approvals': {
|
|
390
|
-
try {
|
|
390
|
+
try {
|
|
391
|
+
if (args._[1] === 'drill') {
|
|
392
|
+
const out = await approvalRequest(args, '/fang/api/approvals/drill', { method: 'POST', body: {} })
|
|
393
|
+
if (args.json) console.log(JSON.stringify(out.body, null, 2))
|
|
394
|
+
else if (out.status === 200 && out.body?.ok) {
|
|
395
|
+
console.log('approval drill: GREEN')
|
|
396
|
+
console.log(` request : ${out.body.drill?.request?.id ?? '-'} ${out.body.drill?.request?.kind ?? '-'}/${out.body.drill?.request?.risk ?? '-'} → ${out.body.drill?.request?.outcome ?? '-'}`)
|
|
397
|
+
console.log(` pending : ${out.body.drill?.pendingBefore ?? '-'} → ${out.body.drill?.pendingAfter ?? '-'}`)
|
|
398
|
+
console.log(` rollback : ${out.body.drill?.rollback?.ok === true ? 'ok' : 'FAIL'} restored=${out.body.drill?.rollback?.restored === true}`)
|
|
399
|
+
console.log(` residue : ${out.body.drill?.cleanup === true ? 'clean' : 'kept'}`)
|
|
400
|
+
} else {
|
|
401
|
+
console.error(`FAIL approval drill: HTTP ${out.status} ${out.text.slice(0, 300)}`)
|
|
402
|
+
}
|
|
403
|
+
code = out.status === 200 && out.body?.ok === true ? 0 : 1
|
|
404
|
+
break
|
|
405
|
+
}
|
|
406
|
+
code = await cmdApprovals(args)
|
|
407
|
+
} catch (error) { console.error(String(error?.message ?? error)); code = 1 }
|
|
391
408
|
break
|
|
392
409
|
}
|
|
393
410
|
case 'approve':
|
|
@@ -402,7 +419,7 @@ switch (cmd) {
|
|
|
402
419
|
break
|
|
403
420
|
}
|
|
404
421
|
default:
|
|
405
|
-
console.log('usage: fangctl.mjs <status|forks|verify|tail [n]|doctor|restart-status [limit]|restart-safe [status|clear]|parse-url <line>|approvals|approve <source:id>|deny <source:id>> [--profile name] [--data-root dir] [--url url] [--token token] [--note text] [--by who] [--json]')
|
|
422
|
+
console.log('usage: fangctl.mjs <status|forks|verify|tail [n]|doctor|restart-status [limit]|restart-safe [status|clear]|parse-url <line>|approvals [drill]|approve <source:id>|deny <source:id>> [--profile name] [--data-root dir] [--url url] [--token token] [--note text] [--by who] [--json]')
|
|
406
423
|
code = 64
|
|
407
424
|
}
|
|
408
425
|
process.exitCode = code
|
package/tools/gate/main-city.mjs
CHANGED
|
@@ -104,7 +104,7 @@ options:
|
|
|
104
104
|
|
|
105
105
|
async function npmLatest(version) {
|
|
106
106
|
try {
|
|
107
|
-
const res = await fetch('https://registry.npmjs.org/@twinsearth%
|
|
107
|
+
const res = await fetch('https://registry.npmjs.org/@twinsearth%2Ffang-dsh-plugin', { signal: AbortSignal.timeout(15000) })
|
|
108
108
|
if (!res.ok) return { ok: false, detail: `registry HTTP ${res.status}` }
|
|
109
109
|
const body = await res.json()
|
|
110
110
|
return { ok: true, latest: String(body?.['dist-tags']?.latest ?? '') }
|