dsh-chief 1.3.0 → 1.4.0
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/CHANGELOG.md +42 -12
- package/README.en.md +143 -116
- package/README.md +134 -142
- package/api-routes.js +19 -2
- package/board-actions.js +72 -1
- package/board-schema.js +1 -1
- package/chief-approvals.js +241 -81
- package/chief-archives.js +35 -0
- package/chief-commands.js +615 -108
- package/chief-executor.js +279 -555
- package/chief-network.js +157 -8
- package/chief-review.js +33 -1
- package/chief-state.js +497 -81
- package/chief-view.js +21 -6
- package/client.js +1953 -506
- package/model-tools.js +78 -2
- package/package.json +35 -24
- package/runtime-hooks.js +108 -2
- package/safety/audit-log.js +95 -0
- package/safety/command-analyzer.js +339 -0
- package/safety/guard-walls.js +993 -0
- package/safety/index.js +78 -0
- package/safety/invariant-guards.js +280 -0
- package/safety/path-guard.js +227 -0
- package/safety/policy-engine.js +387 -0
- package/safety/policy-plugin.js +391 -0
- package/safety/tool-gate.js +278 -0
- package/subagent-runtime.js +9 -2
package/model-tools.js
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
proposeBoundToChief,
|
|
13
13
|
readMailboxForAgent,
|
|
14
14
|
requestChiefElevation,
|
|
15
|
+
appendChiefAuditLog,
|
|
15
16
|
CHIEF_PERMISSION_META,
|
|
16
17
|
} from './chief.js'
|
|
17
18
|
import { normalizePermissionMode } from './chief-executor.js'
|
|
@@ -94,6 +95,9 @@ export function createModelTools(deps) {
|
|
|
94
95
|
'archive.save',
|
|
95
96
|
'context.compact',
|
|
96
97
|
'permission.request',
|
|
98
|
+
'inquiry.reply',
|
|
99
|
+
'chief.request',
|
|
100
|
+
'wall.list',
|
|
97
101
|
'memory.add',
|
|
98
102
|
'memory.remove',
|
|
99
103
|
'memory.ask',
|
|
@@ -102,6 +106,9 @@ export function createModelTools(deps) {
|
|
|
102
106
|
'Board operation (MUST be called whenever recording tasks/status/conclusions or relaying messages; plain text alone does NOT update the board or notify peers). '
|
|
103
107
|
+ 'Use "graph.plan" (or "task.batch") to plan a hierarchical/DAG task graph in one call (supports parentId, blockedBy, owner/subagent, intent, evidence). '
|
|
104
108
|
+ 'Use "task.dispatch" to spawn or message a subagent, "team.steer" to steer a subagent, and "mail.send" to relay messages across lead/subagents/sessions. '
|
|
109
|
+
+ 'Use "inquiry.reply" (inquiryId, text) whenever you see a priority [INQUIRY #id] from DSH Chief — answer accurately and continue your current work immediately without stopping. '
|
|
110
|
+
+ 'Use "chief.request" (subject, text) to ask DSH Chief for cross-session coordination, permission elevation, or to report exploration & planning results. '
|
|
111
|
+
+ 'Use "wall.list" (read-only) to inspect currently active persistent guard walls defending high-risk paths/commands. '
|
|
105
112
|
+ 'Use "bounds.propose" (field: "forbidden"|"allowed"|"notes", item, reason) when hitting a permission/sandbox/environment wall or summarizing boundaries ("allowed" = 必做事项, "forbidden" = 禁止红线, "notes" = 注意事项) so DSH Chief can request user approval. '
|
|
106
113
|
+ 'Use "permission.request" (targetMode: "assistant"|"strategist"|"chief", reason) when requesting higher DSH Chief permission tier from the user. '
|
|
107
114
|
+ 'Session Engineering Archives ("archive.search", "archive.read", "archive.save") access ONLY the current conversation\'s Session Cabinet (never Global Cabinet or unflipped Precipitated cold vault). '
|
|
@@ -170,6 +177,7 @@ export function createModelTools(deps) {
|
|
|
170
177
|
description: 'mode.set: how this board is run. plan = a list of steps being ticked off. goal = one persistent objective steered toward.',
|
|
171
178
|
},
|
|
172
179
|
id: { type: 'string', description: 'Task id for update/claim/release/remove/dispatch/verify, or archive id for archive.read / archive.save.' },
|
|
180
|
+
inquiryId: { type: 'string', description: 'Inquiry id (e.g. inq_xxx) when action is "inquiry.reply".' },
|
|
173
181
|
noteId: { type: 'string', description: 'Note id for note.write / note.pin / note.unpin / note.remove; omit to create a new note.' },
|
|
174
182
|
archiveId: { type: 'string', description: 'Archive dossier id for archive.read / archive.save (on-demand cold archive lookup/update).' },
|
|
175
183
|
query: { type: 'string', description: 'Keyword query for archive.search (searched only on explicit user demand).' },
|
|
@@ -438,6 +446,55 @@ export function createModelTools(deps) {
|
|
|
438
446
|
}
|
|
439
447
|
}
|
|
440
448
|
|
|
449
|
+
if (passed.action === 'inquiry.reply') {
|
|
450
|
+
const replyBody = str(passed.text || passed.body || passed.message || passed.note, '').trim()
|
|
451
|
+
if (!replyBody) return { ok: false, error: 'inquiry.reply 需要非空 text 参数' }
|
|
452
|
+
const deliv = await deliverCrossMessage(makeChiefDeps(runtime), {
|
|
453
|
+
fromSession: rawSession || session,
|
|
454
|
+
fromLabel: byDefault,
|
|
455
|
+
target: 'chief',
|
|
456
|
+
subject: '优先问询答复',
|
|
457
|
+
text: replyBody,
|
|
458
|
+
envelopeKind: 'inquiry_reply',
|
|
459
|
+
inquiryId: str(passed.inquiryId || passed.id || passed.taskId, ''),
|
|
460
|
+
})
|
|
461
|
+
if (!deliv.ok) return { ok: false, error: deliv.error }
|
|
462
|
+
const board = session ? loadBoard(boardFileFor(session)) : emptyBoard()
|
|
463
|
+
const roster = session ? await refreshSubagentTree(runtime, session, board) : []
|
|
464
|
+
return {
|
|
465
|
+
ok: true,
|
|
466
|
+
inquiryAnswered: deliv.inquiryAnswered || null,
|
|
467
|
+
continueOwnWork: true,
|
|
468
|
+
...summary(board, roster),
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
if (passed.action === 'chief.request') {
|
|
473
|
+
const reqBody = str(passed.text || passed.body || passed.message || passed.note, '').trim()
|
|
474
|
+
if (!reqBody) return { ok: false, error: 'chief.request 需要非空 text 参数' }
|
|
475
|
+
const deliv = await deliverCrossMessage(makeChiefDeps(runtime), {
|
|
476
|
+
fromSession: rawSession || session,
|
|
477
|
+
fromLabel: byDefault,
|
|
478
|
+
target: 'chief',
|
|
479
|
+
subject: str(passed.subject || passed.title, '') || '主对话协同请求',
|
|
480
|
+
text: reqBody,
|
|
481
|
+
mode: 'followup',
|
|
482
|
+
})
|
|
483
|
+
if (!deliv.ok) return { ok: false, error: deliv.error }
|
|
484
|
+
const board = session ? boardForSession(boardFileFor(session)) : emptyBoard()
|
|
485
|
+
const roster = session ? await refreshSubagentTree(runtime, session, board) : []
|
|
486
|
+
return {
|
|
487
|
+
ok: true,
|
|
488
|
+
chiefRequest: {
|
|
489
|
+
mode: deliv.mode || deliv.deliveryMode || 'handled',
|
|
490
|
+
actionTaken: deliv.actionTaken || '',
|
|
491
|
+
taskId: deliv.taskId || '',
|
|
492
|
+
reply: deliv.reply || '',
|
|
493
|
+
},
|
|
494
|
+
...summary(board, roster),
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
441
498
|
if (passed.action === 'mail.send') {
|
|
442
499
|
const target = str(passed.target || passed.agent || passed.subagent, 'lead').trim() || 'lead'
|
|
443
500
|
const msgText = str(passed.text || passed.message || passed.prompt || passed.body || passed.note, '').trim()
|
|
@@ -531,8 +588,26 @@ export function createModelTools(deps) {
|
|
|
531
588
|
}
|
|
532
589
|
}
|
|
533
590
|
|
|
534
|
-
const
|
|
535
|
-
|
|
591
|
+
const actionArgs = session
|
|
592
|
+
? { ...passed, by: byDefault, session, _callerOrigin: 'model_tool' }
|
|
593
|
+
: { ...passed, by: byDefault, _callerOrigin: 'model_tool' }
|
|
594
|
+
const result = runAction(actionArgs)
|
|
595
|
+
if (!result.ok) {
|
|
596
|
+
if (result.blockedBySafetyGuard) {
|
|
597
|
+
appendChiefAuditLog(session || rawSession || 'global', {
|
|
598
|
+
mode: 'advisor',
|
|
599
|
+
stage: 'safety_guard',
|
|
600
|
+
rule: result.rule || 'bounds_human_only',
|
|
601
|
+
decision: 'blocked',
|
|
602
|
+
operation: String(passed.action || 'bounds'),
|
|
603
|
+
target: String(passed.field || 'bounds'),
|
|
604
|
+
reason: result.error,
|
|
605
|
+
outcome: 'blocked',
|
|
606
|
+
by: byDefault,
|
|
607
|
+
})
|
|
608
|
+
}
|
|
609
|
+
return { ok: false, error: result.error }
|
|
610
|
+
}
|
|
536
611
|
const mergedBoard = session && result.board ? boardForSession(boardFileFor(session)) : result.board
|
|
537
612
|
const roster = session ? await refreshSubagentTree(runtime, session, mergedBoard) : []
|
|
538
613
|
return {
|
|
@@ -541,6 +616,7 @@ export function createModelTools(deps) {
|
|
|
541
616
|
...(result.archiveSearch ? { archiveSearch: result.archiveSearch } : {}),
|
|
542
617
|
...(result.archiveItem ? { archiveItem: result.archiveItem } : {}),
|
|
543
618
|
...(result.archiveSaved ? { archiveSaved: result.archiveSaved } : {}),
|
|
619
|
+
...(result.walls ? { guardWalls: result.walls } : {}),
|
|
544
620
|
...(result.truncated ? { truncated: result.truncated } : {}),
|
|
545
621
|
}
|
|
546
622
|
},
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-chief",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"icon": "icon.svg",
|
|
5
5
|
"type": "module",
|
|
6
|
-
"description": "
|
|
6
|
+
"description": "Right-sidebar supervisor for DeepSeek Harness (DSH): prevents context-compaction amnesia, monitors subagent DAGs, gates file edits and shell commands behind per-action approvals, breaks runaway loops, and hands off long sessions without bloating prompt tokens.",
|
|
7
7
|
"author": "gluztm",
|
|
8
8
|
"license": "AGPL-3.0-only",
|
|
9
9
|
"repository": {
|
|
@@ -19,27 +19,37 @@
|
|
|
19
19
|
"deepseek-harness",
|
|
20
20
|
"dsh",
|
|
21
21
|
"dsh-plugin",
|
|
22
|
-
"ai-manager",
|
|
23
|
-
"ai管家",
|
|
24
|
-
"ai-orchestrator",
|
|
25
|
-
"ai-supervisor",
|
|
26
|
-
"no-babysitting",
|
|
27
|
-
"免监工",
|
|
28
|
-
"autonomous-agents",
|
|
29
|
-
"agent-orchestration",
|
|
30
|
-
"multi-agent",
|
|
31
|
-
"subagent",
|
|
32
|
-
"dag",
|
|
33
|
-
"session-management",
|
|
34
|
-
"long-session",
|
|
35
|
-
"workflow-automation",
|
|
36
22
|
"context-compaction",
|
|
23
|
+
"compaction-amnesia",
|
|
24
|
+
"context-loss",
|
|
25
|
+
"context-window",
|
|
26
|
+
"token-saving",
|
|
27
|
+
"agent-loop",
|
|
28
|
+
"infinite-loop",
|
|
29
|
+
"unattended-agent",
|
|
30
|
+
"overnight-coding",
|
|
31
|
+
"auto-continue",
|
|
32
|
+
"stop-babysitting",
|
|
33
|
+
"session-handoff",
|
|
34
|
+
"chat-too-long",
|
|
37
35
|
"cross-session-memory",
|
|
38
|
-
"
|
|
39
|
-
"
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"
|
|
36
|
+
"subagent-monitor",
|
|
37
|
+
"multi-agent",
|
|
38
|
+
"task-dag",
|
|
39
|
+
"approval-gate",
|
|
40
|
+
"human-in-the-loop",
|
|
41
|
+
"read-only-mode",
|
|
42
|
+
"command-guardrails",
|
|
43
|
+
"workspace-safety",
|
|
44
|
+
"guard-walls",
|
|
45
|
+
"pre-execute-guard",
|
|
46
|
+
"事前拦截",
|
|
47
|
+
"压缩失忆",
|
|
48
|
+
"挂机跑任务",
|
|
49
|
+
"跨窗口交接",
|
|
50
|
+
"防死循环",
|
|
51
|
+
"只读护栏",
|
|
52
|
+
"ai-manager",
|
|
43
53
|
"superagent"
|
|
44
54
|
],
|
|
45
55
|
"engines": {
|
|
@@ -50,9 +60,9 @@
|
|
|
50
60
|
"scripts": {
|
|
51
61
|
"build:client": "node ./scripts/build-client.mjs",
|
|
52
62
|
"check:client": "node ./scripts/build-client.mjs --check",
|
|
53
|
-
"check:syntax": "node -e \"const fs=require('fs'),cp=require('child_process');for(const
|
|
54
|
-
"test:ci": "npm run check:client && npm run check:syntax && node ./tests/verify-v130-release-gate.mjs",
|
|
55
|
-
"test": "node ./tests/verify-v130-release-gate.mjs && node -e \"const fs=require('fs'),path=require('path'),cp=require('child_process');if(fs.existsSync('../tools')){for(const s of ['verify-chief-facade-split.mjs','verify-index-modular-split.mjs','verify-archives-modular-split.mjs','verify-client-modular-build.mjs','verify-v121-permissions-and-ui.mjs','verify-compaction-and-blank-chat.mjs','check-action-surface.mjs','verify-v130-four-chains.mjs']){cp.execFileSync(process.execPath,[path.resolve('..','tools',s)],{stdio:'inherit'});}}\""
|
|
63
|
+
"check:syntax": "node -e \"const fs=require('fs'),path=require('path'),cp=require('child_process');const walk=d=>{for(const e of fs.readdirSync(d,{withFileTypes:true})){const p=path.join(d,e.name);if(e.isDirectory()&&(e.name==='safety'||e.name==='src'||e.name==='client'))walk(p);else if(e.isFile()&&e.name.endsWith('.js'))cp.execFileSync(process.execPath,['--check',p]);}};walk('.');\"",
|
|
64
|
+
"test:ci": "npm run check:client && npm run check:syntax && node ./tests/verify-v130-release-gate.mjs && node ./tests/verify-v140-safety-gate.mjs && node ./tests/verify-v140-collab-gate.mjs",
|
|
65
|
+
"test": "node ./tests/verify-v130-release-gate.mjs && node ./tests/verify-v140-safety-gate.mjs && node ./tests/verify-v140-collab-gate.mjs && node -e \"const fs=require('fs'),path=require('path'),cp=require('child_process');if(fs.existsSync('../tools')){for(const s of ['verify-chief-facade-split.mjs','verify-index-modular-split.mjs','verify-archives-modular-split.mjs','verify-client-modular-build.mjs','verify-v121-permissions-and-ui.mjs','verify-compaction-and-blank-chat.mjs','check-action-surface.mjs','verify-v130-four-chains.mjs']){cp.execFileSync(process.execPath,[path.resolve('..','tools',s)],{stdio:'inherit'});}}\""
|
|
56
66
|
},
|
|
57
67
|
"exports": {
|
|
58
68
|
".": "./index.js",
|
|
@@ -83,6 +93,7 @@
|
|
|
83
93
|
"chief-review.js",
|
|
84
94
|
"chief-approvals.js",
|
|
85
95
|
"chief-executor.js",
|
|
96
|
+
"safety/*.js",
|
|
86
97
|
"auto-continue.js",
|
|
87
98
|
"archives.js",
|
|
88
99
|
"archive-core.js",
|
package/runtime-hooks.js
CHANGED
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
} from './idle-guard.js'
|
|
22
22
|
import {
|
|
23
23
|
loadChiefState,
|
|
24
|
+
mutateChiefState,
|
|
24
25
|
resolveWorkspaceConfig,
|
|
25
26
|
invalidateChiefModelCatalog,
|
|
26
27
|
buildMessageEnvelope,
|
|
@@ -32,7 +33,7 @@ import {
|
|
|
32
33
|
} from './chief.js'
|
|
33
34
|
import { createAutoContinueEngine } from './auto-continue.js'
|
|
34
35
|
import { bootstrapArchivesFromSharedBoard } from './archives.js'
|
|
35
|
-
import { normalizePermissionMode } from './chief-executor.js'
|
|
36
|
+
import { normalizePermissionMode, evaluatePreExecuteDefense } from './chief-executor.js'
|
|
36
37
|
import {
|
|
37
38
|
newId,
|
|
38
39
|
nowMs,
|
|
@@ -605,11 +606,107 @@ export function createRuntimeHooks(deps) {
|
|
|
605
606
|
}
|
|
606
607
|
})
|
|
607
608
|
|
|
608
|
-
// Model tools: the cross-Session half of the same operations.
|
|
609
|
+
// Model tools: the cross-Session half of the same operations + whole-session pre-execute physical defense.
|
|
609
610
|
ctx.inject(['tools'], toolCtx => {
|
|
610
611
|
for (const tool of [boardTool(runtime), boundariesTool(runtime), handoffTool(runtime), memoryTool(runtime)]) {
|
|
611
612
|
toolCtx.effect(() => toolCtx.tools.register(tool), 'dsh-chief: tool ' + tool.name)
|
|
612
613
|
}
|
|
614
|
+
const hookOn = typeof toolCtx.on === 'function'
|
|
615
|
+
? toolCtx.on.bind(toolCtx)
|
|
616
|
+
: (typeof ctx.on === 'function' ? ctx.on.bind(ctx) : null)
|
|
617
|
+
if (hookOn) {
|
|
618
|
+
toolCtx.effect(() => hookOn('tools/pre-execute', async (exec, next) => {
|
|
619
|
+
try {
|
|
620
|
+
if (!exec || !exec.name) return next()
|
|
621
|
+
const caller = exec.agent || null
|
|
622
|
+
const sid = caller && caller.id ? String(caller.id) : ''
|
|
623
|
+
const rootId = resolveRootSessionId(sid, caller) || sid || 'global'
|
|
624
|
+
const cwd = (sid && getSessionCwd(runtime, sid)) || (rootId !== 'global' && getSessionCwd(runtime, rootId)) || process.cwd()
|
|
625
|
+
const board = rootId && rootId !== 'global' ? boardForSession(boardFileFor(rootId)) : loadBoard(boardFile())
|
|
626
|
+
const verdict = evaluatePreExecuteDefense({
|
|
627
|
+
tool: String(exec.name),
|
|
628
|
+
args: exec.arguments && typeof exec.arguments === 'object' ? exec.arguments : {},
|
|
629
|
+
cwd,
|
|
630
|
+
board,
|
|
631
|
+
})
|
|
632
|
+
if (verdict && verdict.decision === 'deny') {
|
|
633
|
+
const st = loadChiefState()
|
|
634
|
+
const effCfg = resolveWorkspaceConfig(st, rootId)
|
|
635
|
+
const ident = resolveAgentIdentity(runtime, sid, caller)
|
|
636
|
+
const actorName = (ident && ident.self) || 'lead'
|
|
637
|
+
const targetPreview = String(
|
|
638
|
+
(exec.arguments && (exec.arguments.path || exec.arguments.file_path || exec.arguments.command || exec.arguments.cmd))
|
|
639
|
+
|| exec.name,
|
|
640
|
+
).slice(0, 120)
|
|
641
|
+
appendChiefAuditLog(rootId, {
|
|
642
|
+
mode: effCfg.permissionMode || 'advisor',
|
|
643
|
+
stage: verdict.stage || 'guard_wall',
|
|
644
|
+
rule: verdict.rule || 'pre_execute_denied',
|
|
645
|
+
decision: 'blocked',
|
|
646
|
+
operation: String(exec.name),
|
|
647
|
+
target: targetPreview,
|
|
648
|
+
reason: verdict.reason,
|
|
649
|
+
outcome: 'blocked',
|
|
650
|
+
by: actorName,
|
|
651
|
+
})
|
|
652
|
+
try {
|
|
653
|
+
const bFile = rootId !== 'global' ? boardFileFor(rootId) : boardFile()
|
|
654
|
+
withBoardLock(bFile, () => {
|
|
655
|
+
const b = loadBoard(bFile)
|
|
656
|
+
pushLog(b, `🧱 事前物理防线已拦截 @${actorName} 调用 ${exec.name}:${String(verdict.reason || '').slice(0, 110)}`, 'guard', sid || rootId)
|
|
657
|
+
saveBoard(b, bFile)
|
|
658
|
+
})
|
|
659
|
+
} catch {}
|
|
660
|
+
if (effCfg.tacticalModes && effCfg.tacticalModes.redlineSentinel) {
|
|
661
|
+
mutateChiefState((s) => {
|
|
662
|
+
if (!s.workspaces || !s.workspaces[rootId]) return
|
|
663
|
+
const ws = s.workspaces[rootId]
|
|
664
|
+
if (!Array.isArray(ws.chat)) ws.chat = []
|
|
665
|
+
ws.chat.push({
|
|
666
|
+
id: 'chat-' + Date.now().toString(36),
|
|
667
|
+
role: 'chief',
|
|
668
|
+
kind: 'receipt',
|
|
669
|
+
text: `- 【🧱 红线哨兵 · 事前物理拦截】已当场阻断 \`@${actorName}\` 的越界调用 \`${exec.name}\`\n- 【拦截原因】${verdict.reason}`,
|
|
670
|
+
actions: [verdict.badge || '🧱 事前物理拦截'],
|
|
671
|
+
at: Date.now(),
|
|
672
|
+
})
|
|
673
|
+
})
|
|
674
|
+
}
|
|
675
|
+
return {
|
|
676
|
+
kind: 'deny',
|
|
677
|
+
reason: `[DSH 安全卫兵事前物理拦截] ${verdict.reason}`,
|
|
678
|
+
info: { stage: verdict.stage, rule: verdict.rule, wallId: verdict.wallId || '' },
|
|
679
|
+
}
|
|
680
|
+
} else if (verdict && verdict.decision === 'ask') {
|
|
681
|
+
const st = loadChiefState()
|
|
682
|
+
const effCfg = resolveWorkspaceConfig(st, rootId)
|
|
683
|
+
const ident = resolveAgentIdentity(runtime, sid, caller)
|
|
684
|
+
const actorName = (ident && ident.self) || 'lead'
|
|
685
|
+
const targetPreview = String(
|
|
686
|
+
(exec.arguments && (exec.arguments.path || exec.arguments.file_path || exec.arguments.command || exec.arguments.cmd))
|
|
687
|
+
|| exec.name,
|
|
688
|
+
).slice(0, 120)
|
|
689
|
+
appendChiefAuditLog(rootId, {
|
|
690
|
+
mode: effCfg.permissionMode || 'advisor',
|
|
691
|
+
stage: verdict.stage || 'guard_wall',
|
|
692
|
+
rule: verdict.rule || 'guard_wall_require_approval_cmd',
|
|
693
|
+
decision: 'pending_approval',
|
|
694
|
+
operation: String(exec.name),
|
|
695
|
+
target: targetPreview,
|
|
696
|
+
reason: verdict.reason,
|
|
697
|
+
outcome: 'pending',
|
|
698
|
+
by: actorName,
|
|
699
|
+
})
|
|
700
|
+
return {
|
|
701
|
+
kind: 'ask',
|
|
702
|
+
reason: `[DSH 物理驻墙审批] ${verdict.reason}`,
|
|
703
|
+
displayReason: verdict.displayReason || verdict.reason,
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
} catch {}
|
|
707
|
+
return next()
|
|
708
|
+
}), 'dsh-chief: pre-execute physical defense')
|
|
709
|
+
}
|
|
613
710
|
})
|
|
614
711
|
|
|
615
712
|
// Runtime capability probe for DSH >= 0.2.2-rc.2 named subagent APIs
|
|
@@ -621,6 +718,15 @@ export function createRuntimeHooks(deps) {
|
|
|
621
718
|
} catch {}
|
|
622
719
|
}
|
|
623
720
|
})
|
|
721
|
+
|
|
722
|
+
// Cold-start safety reconciliation for persistent TaskLedger (stale running/resuming -> interrupted; past TTL -> expired)
|
|
723
|
+
try {
|
|
724
|
+
const bootSt = loadChiefState({ forceDisk: true })
|
|
725
|
+
const hasNeedReconcile = Object.values((bootSt && bootSt.workspaces) || {}).some(
|
|
726
|
+
ws => Array.isArray(ws && ws.taskLedger) && ws.taskLedger.some(t => t && (t.status === 'interrupted' || t.status === 'expired')),
|
|
727
|
+
)
|
|
728
|
+
if (hasNeedReconcile) mutateChiefState(() => {})
|
|
729
|
+
} catch {}
|
|
624
730
|
}
|
|
625
731
|
|
|
626
732
|
return {
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* safety/audit-log.js
|
|
3
|
+
*
|
|
4
|
+
* Independent append-only audit ledger (`chief-audit.jsonl`), secret redaction,
|
|
5
|
+
* and structured audit record normalization for DSH Chief.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs'
|
|
9
|
+
import os from 'node:os'
|
|
10
|
+
import path from 'node:path'
|
|
11
|
+
|
|
12
|
+
export const SECRET_REDACT_PATTERN = /(?:sk-[a-zA-Z0-9_-]{16,}|ghp_[a-zA-Z0-9]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|Bearer\s+[A-Za-z0-9._~+/=-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$))/g
|
|
13
|
+
|
|
14
|
+
let auditIdSeq = 0
|
|
15
|
+
|
|
16
|
+
function nextAuditId() {
|
|
17
|
+
auditIdSeq = (auditIdSeq + 1) % 1_000_000
|
|
18
|
+
return 'aud-' + Date.now().toString(36) + '-' + auditIdSeq.toString(36)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function clampSingleLine(value, max) {
|
|
22
|
+
const text = String(value == null ? '' : value).replace(/\s+/g, ' ').trim()
|
|
23
|
+
if (text.length <= max) return text
|
|
24
|
+
return text.slice(0, Math.max(0, max - 1)) + '…'
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function redactAuditText(text, maxLen = 220) {
|
|
28
|
+
const raw = String(text == null ? '' : text)
|
|
29
|
+
if (!raw) return ''
|
|
30
|
+
const redacted = raw.replace(SECRET_REDACT_PATTERN, '[REDACTED]')
|
|
31
|
+
return clampSingleLine(redacted, maxLen)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function auditJsonlPath() {
|
|
35
|
+
const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
36
|
+
return path.join(home, 'chief', 'chief-audit.jsonl')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function normalizeAuditRecord(raw, defaultMode = 'advisor') {
|
|
40
|
+
if (!raw || typeof raw !== 'object') return null
|
|
41
|
+
const op = clampSingleLine(raw.operation || raw.tool || '', 80)
|
|
42
|
+
if (!op) return null
|
|
43
|
+
const modeRaw = String(raw.mode || defaultMode || 'advisor').trim().toLowerCase()
|
|
44
|
+
const mode = ['advisor', 'assistant', 'strategist', 'chief'].includes(modeRaw) ? modeRaw : 'advisor'
|
|
45
|
+
const rawDuration = Number(raw.durationMs)
|
|
46
|
+
const durationMs = Number.isFinite(rawDuration) && rawDuration >= 0 ? Math.round(rawDuration) : 0
|
|
47
|
+
const reason = redactAuditText(raw.reason || '', 220)
|
|
48
|
+
const summary = redactAuditText(raw.summary || raw.reason || '', 220)
|
|
49
|
+
return {
|
|
50
|
+
id: typeof raw.id === 'string' && raw.id ? raw.id : nextAuditId(),
|
|
51
|
+
at: Number(raw.at) || Date.now(),
|
|
52
|
+
mode,
|
|
53
|
+
stage: clampSingleLine(raw.stage || 'executor', 40),
|
|
54
|
+
rule: clampSingleLine(raw.rule || '', 80),
|
|
55
|
+
decision: clampSingleLine(raw.decision || 'executed', 40),
|
|
56
|
+
operation: op,
|
|
57
|
+
target: redactAuditText(raw.target || '', 140),
|
|
58
|
+
summary,
|
|
59
|
+
reason,
|
|
60
|
+
outcome: clampSingleLine(raw.outcome || 'ok', 40),
|
|
61
|
+
durationMs,
|
|
62
|
+
by: clampSingleLine(raw.by || 'chief', 40),
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function appendAuditJsonlRecord(record, sessionId = '') {
|
|
67
|
+
try {
|
|
68
|
+
const file = auditJsonlPath()
|
|
69
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
70
|
+
const payload = sessionId ? { sessionId: String(sessionId), ...record } : record
|
|
71
|
+
fs.appendFileSync(file, JSON.stringify(payload) + '\n', 'utf8')
|
|
72
|
+
} catch {}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function readRecentAuditJsonl({ sessionId = '', limit = 80 } = {}) {
|
|
76
|
+
const file = auditJsonlPath()
|
|
77
|
+
if (!fs.existsSync(file)) return []
|
|
78
|
+
try {
|
|
79
|
+
const raw = fs.readFileSync(file, 'utf8')
|
|
80
|
+
const lines = raw.split(/\r?\n/).filter(Boolean)
|
|
81
|
+
const cap = Math.max(1, Math.min(500, Number(limit) || 80))
|
|
82
|
+
const out = []
|
|
83
|
+
for (let i = lines.length - 1; i >= 0 && out.length < cap; i -= 1) {
|
|
84
|
+
try {
|
|
85
|
+
const parsed = JSON.parse(lines[i])
|
|
86
|
+
if (!parsed || typeof parsed !== 'object') continue
|
|
87
|
+
if (sessionId && parsed.sessionId && parsed.sessionId !== sessionId) continue
|
|
88
|
+
out.push(parsed)
|
|
89
|
+
} catch {}
|
|
90
|
+
}
|
|
91
|
+
return out.reverse()
|
|
92
|
+
} catch {
|
|
93
|
+
return []
|
|
94
|
+
}
|
|
95
|
+
}
|