dsh-chief 1.0.0 → 1.2.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/index.js CHANGED
@@ -34,38 +34,68 @@ import {
34
34
  } from './idle-guard.js'
35
35
  import {
36
36
  loadChiefState,
37
+ resolveWorkspaceConfig,
37
38
  getLinkedCluster,
38
39
  setPeerLink,
40
+ collectClusterPeerProgress,
39
41
  invalidateChiefModelCatalog,
40
42
  listChiefModels,
41
43
  listPeerDirectory,
44
+ buildMessageEnvelope,
42
45
  deliverCrossMessage,
43
46
  consumePreStepDelta,
44
47
  getChiefView,
48
+ recommendAndSetCompactThreshold,
45
49
  askOrCommandChief,
46
50
  consolidateBoundsWithChief,
47
51
  organizeArchivesWithChief,
52
+ harvestTurnDetailsToArchive,
53
+ precipitateExperienceWithChief,
54
+ distillSessionArchivesToGlobal,
55
+ deployChiefWorkspaceState,
56
+ updateWorkspaceFlippedIds,
57
+ requestSmartCompactFromLead,
58
+ maybeRunPreCompaction,
59
+ runTurnReview,
48
60
  proposeBoundToChief,
49
61
  scheduleChiefTurnReview,
50
62
  handleSuggestionDecision,
51
63
  updateChiefConfig,
64
+ suggestCoreObjectiveWithChief,
65
+ relayArchivesWithChief,
52
66
  mutateChiefFact,
53
67
  readMailboxForAgent,
54
68
  } from './chief.js'
69
+ import { createAutoContinueEngine } from './auto-continue.js'
55
70
  import {
56
71
  bootstrapArchivesFromSharedBoard,
72
+ resolveProjectKey,
73
+ listProjectCabinets,
57
74
  getArchiveMeta,
75
+ getThreeTierArchiveCounts,
58
76
  listArchiveHeaders,
59
77
  getArchiveDetail,
60
78
  searchArchives,
61
79
  mutateArchive,
80
+ copyArchivesBetweenSessionsOrCabinets,
62
81
  getTakenOutArchivesForSession,
82
+ getTakenOutGlobalForSession,
83
+ getFlippedOutPrecipitatedForSession,
84
+ listPrecipitatedHeaders,
85
+ getPrecipitatedDetail,
86
+ mutatePrecipitated,
87
+ copyPrecipitatedToVault,
63
88
  } from './archives.js'
89
+ import {
90
+ DEFAULT_CHIEF_PERMISSION_MODE,
91
+ normalizePermissionMode,
92
+ } from './chief-executor.js'
64
93
 
65
94
  const API = '/api/dsh-chief'
95
+ const BACKEND_BUILD = '1.2.0-r7'
66
96
  const BOARD_VERSION = 1
67
97
  const LOG_CAP = 60
68
- const BODY_LIMIT = 128 * 1024
98
+ const BODY_LIMIT = 24 * 1024 * 1024
69
99
  // How many anchor notes the shared board keeps. Anchors are what a fresh
70
100
  // Session reads before it has any context, so this is a budget, not a list.
71
101
  /**
@@ -144,6 +174,35 @@ function clearPending() {
144
174
  } catch {}
145
175
  }
146
176
 
177
+ function pendingDeployFile() {
178
+ return path.join(path.dirname(boardFile()), 'pending-chief-deploy.json')
179
+ }
180
+
181
+ function readPendingDeploy() {
182
+ try {
183
+ const raw = JSON.parse(fs.readFileSync(pendingDeployFile(), 'utf8'))
184
+ return raw && typeof raw.fromSessionId === 'string' && raw.fromSessionId ? raw : null
185
+ } catch {
186
+ return null
187
+ }
188
+ }
189
+
190
+ function writePendingDeploy(value) {
191
+ try {
192
+ fs.mkdirSync(path.dirname(pendingDeployFile()), { recursive: true })
193
+ fs.writeFileSync(pendingDeployFile(), JSON.stringify(value, null, 2), 'utf8')
194
+ return true
195
+ } catch {
196
+ return false
197
+ }
198
+ }
199
+
200
+ function clearPendingDeploy() {
201
+ try {
202
+ fs.unlinkSync(pendingDeployFile())
203
+ } catch {}
204
+ }
205
+
147
206
  function boardFile() {
148
207
  const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
149
208
  return path.join(home, 'chief', 'board.json')
@@ -152,6 +211,8 @@ function boardFile() {
152
211
  /** Active runtime reference for resolving subagent tree lineage and live status. */
153
212
  let activeRuntime = null
154
213
  let activeLlm = null
214
+ let activeAutoContinue = null
215
+ const autoSteeredTurns = new Map()
155
216
  const subagentRootMap = new Map()
156
217
  const subagentTreeCache = new Map()
157
218
 
@@ -354,6 +415,9 @@ function emptyBoard() {
354
415
  objective: '',
355
416
  objectiveBy: '',
356
417
  objectiveAt: 0,
418
+ objectiveUpdatedAt: 0,
419
+ activeCabinetId: '',
420
+ goalApproval: null,
357
421
  // 'plan' or 'goal'. A plan is a list of steps being ticked off; a goal is
358
422
  // one persistent objective steered toward, where rewriting the step list
359
423
  // every turn hides the fact that the objective never moved. The model picks
@@ -370,7 +434,18 @@ function emptyBoard() {
370
434
  // is, and what is blocking it. Long tasks die from losing that one line, so
371
435
  // it is a first-class field and the digest leads with it.
372
436
  cursor: { at: 0, step: '', next: '', blocked: '', by: '', session: '' },
373
- handoff: { at: 0, by: '', session: '' },
437
+ handoff: {
438
+ at: 0,
439
+ by: '',
440
+ session: '',
441
+ customText: '',
442
+ pinned: false,
443
+ pinnedAt: 0,
444
+ pinnedBy: '',
445
+ updatedAt: 0,
446
+ source: 'auto',
447
+ syncOnDigest: false,
448
+ },
374
449
  plan: [],
375
450
  tasks: [],
376
451
  notes: [],
@@ -578,6 +653,13 @@ function normalizeNote(raw) {
578
653
 
579
654
  const BOUND_FIELDS = ['allowed', 'forbidden', 'notes']
580
655
 
656
+ /** Normalize boundary field names, accepting `'must'` as an alias for `'allowed'` (必做事项). */
657
+ function normalizeBoundFieldName(raw) {
658
+ const f = str(raw, '').trim().toLowerCase()
659
+ if (f === 'must' || f === 'must_do' || f === 'mustdo') return 'allowed'
660
+ return BOUND_FIELDS.includes(f) ? f : ''
661
+ }
662
+
581
663
  // Hard cap on one bounds column. Two different jobs read this number: loading
582
664
  // clamps to it (an old or hand-edited board file must never be able to throw
583
665
  // while being read), and every write path checks it BEFORE storing anything.
@@ -635,6 +717,22 @@ function guardCount(value, fallback, min, max) {
635
717
  return Math.min(max, Math.max(min, Math.round(number)))
636
718
  }
637
719
 
720
+ function normalizeGoalApproval(raw) {
721
+ if (!raw || typeof raw !== 'object') return null
722
+ const status = ['pending', 'approved', 'rejected'].includes(raw.status) ? raw.status : ''
723
+ if (!status) return null
724
+ return {
725
+ id: str(raw.id, newId('ga')),
726
+ status,
727
+ objective: str(raw.objective, '').slice(0, 600),
728
+ summary: str(raw.summary, '').slice(0, 600),
729
+ evidence: str(raw.evidence, '').slice(0, 800),
730
+ rejectReason: str(raw.rejectReason, '').slice(0, 300),
731
+ at: typeof raw.at === 'number' ? raw.at : nowMs(),
732
+ decidedAt: typeof raw.decidedAt === 'number' ? raw.decidedAt : 0,
733
+ }
734
+ }
735
+
638
736
  function normalizeBoard(raw) {
639
737
  const board = raw && typeof raw === 'object' ? raw : {}
640
738
  const plan = Array.isArray(board.plan) ? board.plan : []
@@ -647,6 +745,9 @@ function normalizeBoard(raw) {
647
745
  objective: str(board.objective, ''),
648
746
  objectiveBy: str(board.objectiveBy, ''),
649
747
  objectiveAt: typeof board.objectiveAt === 'number' ? board.objectiveAt : 0,
748
+ objectiveUpdatedAt: typeof board.objectiveUpdatedAt === 'number' ? board.objectiveUpdatedAt : (typeof board.objectiveAt === 'number' ? board.objectiveAt : 0),
749
+ activeCabinetId: str(board.activeCabinetId, '').trim(),
750
+ goalApproval: normalizeGoalApproval(board.goalApproval),
650
751
  // Whitelisted, not free-form: an unknown mode would make every consumer
651
752
  // (digest, panel) disagree about which shape the board has.
652
753
  mode: board.mode === 'goal' ? 'goal' : 'plan',
@@ -668,6 +769,14 @@ function normalizeBoard(raw) {
668
769
  at: board.handoff && typeof board.handoff.at === 'number' ? board.handoff.at : 0,
669
770
  by: str(board.handoff && board.handoff.by, ''),
670
771
  session: str(board.handoff && board.handoff.session, ''),
772
+ customText: str(board.handoff && board.handoff.customText, '').slice(0, 16000),
773
+ pinned: board.handoff ? board.handoff.pinned === true : false,
774
+ frozenFromAuto: board.handoff ? board.handoff.frozenFromAuto === true : false,
775
+ pinnedAt: board.handoff && typeof board.handoff.pinnedAt === 'number' ? board.handoff.pinnedAt : 0,
776
+ pinnedBy: str(board.handoff && board.handoff.pinnedBy, ''),
777
+ updatedAt: board.handoff && typeof board.handoff.updatedAt === 'number' ? board.handoff.updatedAt : 0,
778
+ source: ['human', 'chief', 'auto'].includes(str(board.handoff && board.handoff.source, '')) ? board.handoff.source : 'auto',
779
+ syncOnDigest: board.handoff ? board.handoff.syncOnDigest === true : false,
671
780
  },
672
781
  cursor: {
673
782
  at: board.cursor && typeof board.cursor.at === 'number' ? board.cursor.at : 0,
@@ -876,6 +985,19 @@ function forcesShared(action, args) {
876
985
  return action === 'note.write' && asBool(args.pinned) === true
877
986
  }
878
987
 
988
+ /** Check whether Strong Intervention (`主动强介入`) is active and locks `board.objective` for a session tree. */
989
+ function isObjectiveLockedByIntervention(sessionId) {
990
+ const rawSid = str(sessionId, '').trim()
991
+ if (!rawSid) return false
992
+ try {
993
+ const rootSid = resolveRootSessionId(rawSid) || rawSid
994
+ const cfg = resolveWorkspaceConfig(loadChiefState(), rootSid)
995
+ return Boolean(cfg && cfg.tacticalModes && cfg.tacticalModes.intervention === true)
996
+ } catch {
997
+ return false
998
+ }
999
+ }
1000
+
879
1001
  function runAction(input) {
880
1002
  const args = input && typeof input === 'object' ? input : {}
881
1003
  const action = str(args.action, 'snapshot')
@@ -907,11 +1029,19 @@ function runActionUnlocked(input) {
907
1029
  const shared = forcesShared(action, args)
908
1030
  const file = shared ? boardFile() : boardFileFor(session)
909
1031
 
910
- // Cold-storage Engineering Archives: strictly on-demand lookup/save, never auto-loaded.
1032
+ // Session-scoped Engineering Archives: Lead/Subagents may ONLY access THIS session's cabinet (never global or unflipped precipitated!).
911
1033
  if (action === 'archive.search') {
912
1034
  const q = str(args.query !== undefined ? args.query : (args.question !== undefined ? args.question : args.text), '')
913
1035
  const folder = str(args.folder, '')
914
- const res = searchArchives(q, { folder, limit: 10 }, boardFile())
1036
+ const rootSid = resolveRootSessionId(session) || session
1037
+ if (!rootSid) {
1038
+ return {
1039
+ ok: true,
1040
+ archiveSearch: { ok: true, totalArchives: 0, matchCount: 0, hits: [], unboundSession: true },
1041
+ board: emptyBoard(),
1042
+ }
1043
+ }
1044
+ const res = searchArchives(q, { folder, limit: 10, vaultScope: 'session' }, archiveTarget(activeRuntime, rootSid, { cabinetId: str(args.cabinetId, ''), vaultScope: 'session' }))
915
1045
  return {
916
1046
  ok: true,
917
1047
  archiveSearch: res,
@@ -923,7 +1053,8 @@ function runActionUnlocked(input) {
923
1053
  const target = str(args.archiveId !== undefined ? args.archiveId : (args.id !== undefined ? args.id : args.title), '').trim()
924
1054
  if (!target) return { ok: false, error: 'archive.read requires archiveId, id, or title' }
925
1055
  const rootSid = resolveRootSessionId(session) || session
926
- const res = getArchiveDetail(target, rootSid, boardFile())
1056
+ if (!rootSid) return { ok: false, error: '当前未绑定对话会话,无法读取本会话档案柜' }
1057
+ const res = getArchiveDetail(target, rootSid, archiveTarget(activeRuntime, rootSid, { cabinetId: str(args.cabinetId, ''), vaultScope: 'session' }))
927
1058
  if (!res.ok) return { ok: false, error: res.error }
928
1059
  return {
929
1060
  ok: true,
@@ -934,8 +1065,10 @@ function runActionUnlocked(input) {
934
1065
 
935
1066
  if (action === 'archive.save') {
936
1067
  const rootSid = resolveRootSessionId(session) || session
1068
+ if (!rootSid) return { ok: false, error: '当前未绑定对话会话,无法保存到本会话档案柜' }
937
1069
  const res = mutateArchive({
938
1070
  op: 'save',
1071
+ vaultScope: 'session',
939
1072
  archiveId: str(args.archiveId !== undefined ? args.archiveId : args.id, ''),
940
1073
  title: str(args.title, ''),
941
1074
  body: typeof args.body === 'string' ? args.body : undefined,
@@ -946,7 +1079,7 @@ function runActionUnlocked(input) {
946
1079
  points: Array.isArray(args.points) ? args.points : undefined,
947
1080
  by,
948
1081
  rootSessionId: rootSid,
949
- }, boardFile())
1082
+ }, archiveTarget(activeRuntime, rootSid, { cabinetId: str(args.cabinetId, ''), vaultScope: 'session' }))
950
1083
  if (!res.ok) return { ok: false, error: res.error }
951
1084
  if (session) {
952
1085
  withBoardLock(file, () => {
@@ -975,6 +1108,29 @@ function runActionUnlocked(input) {
975
1108
 
976
1109
  const board = loadBoard(file)
977
1110
 
1111
+ if (action === 'task.reset') {
1112
+ const mode = str(args.mode, 'clear').trim().toLowerCase()
1113
+ const hadCount = Array.isArray(board.tasks) ? board.tasks.length : 0
1114
+ if (mode === 'reopen') {
1115
+ board.tasks = (board.tasks || []).map(t => ({
1116
+ ...t,
1117
+ status: 'todo',
1118
+ evidence: '',
1119
+ updatedAt: nowMs(),
1120
+ }))
1121
+ reconcileTaskDependencies(board, by, session)
1122
+ pushLog(board, '已将本会话全部任务重置为待推进(共 ' + board.tasks.length + ' 项)', by, session)
1123
+ } else {
1124
+ board.tasks = []
1125
+ if (asBool(args.alsoResetPlan) === true) {
1126
+ board.plan = []
1127
+ board.cursor = { at: nowMs(), step: '', next: '', blocked: '', by, session }
1128
+ }
1129
+ pushLog(board, '已重设清空本会话任务列表(原 ' + hadCount + ' 项)', by, session)
1130
+ }
1131
+ return { ok: true, clearedTasks: hadCount, mode, board: saveBoard(board, file) }
1132
+ }
1133
+
978
1134
  if (action === 'task.add') {
979
1135
  const title = str(args.title, '').trim()
980
1136
  if (!title) return { ok: false, error: 'title required' }
@@ -1007,9 +1163,15 @@ function runActionUnlocked(input) {
1007
1163
  if (action === 'graph.plan' || action === 'task.batch') {
1008
1164
  const clips = []
1009
1165
  if (typeof args.objective === 'string' && args.objective.trim()) {
1010
- board.objective = clipInto(clips, 'objective', args.objective.trim(), CAP_OBJECTIVE)
1011
- board.objectiveBy = session
1012
- board.objectiveAt = nowMs()
1166
+ if (isObjectiveLockedByIntervention(session) && asBool(args._fromInterventionSetup) !== true) {
1167
+ if (args.objective.trim() !== String(board.objective || '').trim()) {
1168
+ pushLog(board, '🔒 主动强介入已锁定核心目标,忽略本次任务图目标改写', by, session)
1169
+ }
1170
+ } else {
1171
+ board.objective = clipInto(clips, 'objective', args.objective.trim(), CAP_OBJECTIVE)
1172
+ board.objectiveBy = session
1173
+ board.objectiveAt = nowMs()
1174
+ }
1013
1175
  }
1014
1176
  const rawList = Array.isArray(args.tasks) ? args.tasks : (Array.isArray(args.nodes) ? args.nodes : [])
1015
1177
  if (!rawList.length) return { ok: false, error: 'graph.plan requires a non-empty tasks array' }
@@ -1199,17 +1361,23 @@ function runActionUnlocked(input) {
1199
1361
  if (action === 'plan.set') {
1200
1362
  const clips = []
1201
1363
  if (typeof args.objective === 'string') {
1202
- board.objective = clipInto(clips, 'objective', args.objective, CAP_OBJECTIVE)
1203
- // Whoever writes the objective owns it. Leaving the previous owner in
1204
- // place made the panel header name the Session that set the *old* text,
1205
- // so a fresh save looked like it came from somebody else.
1206
- board.objectiveBy = session
1207
- board.objectiveAt = nowMs()
1208
- // objective.set logged this write and plan.set did not, so retargeting a
1209
- // board through plan.set left no trace in the log: the objective page
1210
- // said the goal had changed and the log page said nothing had happened.
1211
- // One action, two entry points, one line either way.
1212
- pushLog(board, '目标改为:' + board.objective.slice(0, 60), by, session)
1364
+ if (isObjectiveLockedByIntervention(session) && asBool(args._fromInterventionSetup) !== true) {
1365
+ if (args.objective.trim() !== String(board.objective || '').trim()) {
1366
+ pushLog(board, '🔒 主动强介入已锁定核心目标,保留原核心目标(仅更新计划步骤)', by, session)
1367
+ }
1368
+ } else {
1369
+ board.objective = clipInto(clips, 'objective', args.objective, CAP_OBJECTIVE)
1370
+ // Whoever writes the objective owns it. Leaving the previous owner in
1371
+ // place made the panel header name the Session that set the *old* text,
1372
+ // so a fresh save looked like it came from somebody else.
1373
+ board.objectiveBy = session
1374
+ board.objectiveAt = nowMs()
1375
+ // objective.set logged this write and plan.set did not, so retargeting a
1376
+ // board through plan.set left no trace in the log: the objective page
1377
+ // said the goal had changed and the log page said nothing had happened.
1378
+ // One action, two entry points, one line either way.
1379
+ pushLog(board, '目标改为:' + board.objective.slice(0, 60), by, session)
1380
+ }
1213
1381
  }
1214
1382
  const steps = asList(args.steps)
1215
1383
  if (steps) {
@@ -1234,12 +1402,17 @@ function runActionUnlocked(input) {
1234
1402
  if (mode !== 'plan' && mode !== 'goal') return { ok: false, error: 'mode must be plan or goal' }
1235
1403
  const before = board.mode === 'goal' ? 'goal' : 'plan'
1236
1404
  board.mode = mode
1237
- // Logged even when unchanged is pointless, but logged when flipped is the
1238
- // only record of *why* the digest suddenly reads differently.
1405
+ if (mode === 'goal') {
1406
+ if (board.goalApproval && board.goalApproval.status !== 'pending') {
1407
+ board.goalApproval = null
1408
+ }
1409
+ } else if (board.goalApproval && board.goalApproval.status === 'pending') {
1410
+ board.goalApproval = null
1411
+ }
1239
1412
  if (before !== mode) {
1240
1413
  pushLog(
1241
1414
  board,
1242
- '模式改为:' + mode + (mode === 'goal' ? '(这活按持续目标推进,不用步骤列表代替)' : '(回到步骤推进)'),
1415
+ '模式改为:' + mode + (mode === 'goal' ? '(开启长期目标持续督导)' : '(回到按步规划推进)'),
1243
1416
  by,
1244
1417
  session,
1245
1418
  )
@@ -1247,6 +1420,74 @@ function runActionUnlocked(input) {
1247
1420
  return { ok: true, mode, board: saveBoard(board, file) }
1248
1421
  }
1249
1422
 
1423
+ if (action === 'plan.resetForGoal') {
1424
+ const hadSteps = Array.isArray(board.plan) ? board.plan.length : 0
1425
+ board.plan = []
1426
+ board.cursor = {
1427
+ at: nowMs(),
1428
+ step: '',
1429
+ next: '',
1430
+ blocked: '',
1431
+ by,
1432
+ session,
1433
+ }
1434
+ pushLog(board, `已清空陈旧计划步骤(原 ${hadSteps} 步),等待按最新总目标重编`, by, session)
1435
+ return { ok: true, clearedSteps: hadSteps, board: saveBoard(board, file) }
1436
+ }
1437
+
1438
+ if (action === 'goal.proposeApproval') {
1439
+ const obj = str(args.objective, board.objective).trim().slice(0, 600)
1440
+ const summary = str(args.summary, '当前总目标要求已全部完成并已核验,请用户批准结项。').trim().slice(0, 600)
1441
+ const evidence = str(args.evidence, '').trim().slice(0, 800)
1442
+ // Crucial: keep board.mode === 'goal' until the user explicitly approves!
1443
+ board.goalApproval = {
1444
+ id: newId('ga'),
1445
+ status: 'pending',
1446
+ objective: obj,
1447
+ summary,
1448
+ evidence,
1449
+ rejectReason: '',
1450
+ at: nowMs(),
1451
+ decidedAt: 0,
1452
+ }
1453
+ pushLog(board, '🎯 参谋长判定目标已达成,呈请用户批准结项:' + summary.slice(0, 60), by, session)
1454
+ return { ok: true, goalApproval: board.goalApproval, board: saveBoard(board, file) }
1455
+ }
1456
+
1457
+ if (action === 'goal.approve') {
1458
+ const prev = board.goalApproval || { id: newId('ga'), objective: board.objective, summary: '', evidence: '', at: nowMs() }
1459
+ board.goalApproval = {
1460
+ ...prev,
1461
+ status: 'approved',
1462
+ rejectReason: '',
1463
+ decidedAt: nowMs(),
1464
+ }
1465
+ board.mode = 'plan'
1466
+ appendMemory(board, {
1467
+ section: '验证结论',
1468
+ title: '🎯 目标结项批准:' + String(prev.objective || board.objective || '阶段目标').slice(0, 60),
1469
+ text: prev.summary || '用户已批准目标结项并切换回按步规划模式',
1470
+ by,
1471
+ session,
1472
+ })
1473
+ pushLog(board, '✅ 用户已批准目标结项,已退出 Goal 督导模式', by, session)
1474
+ return { ok: true, goalApproval: board.goalApproval, mode: board.mode, board: saveBoard(board, file) }
1475
+ }
1476
+
1477
+ if (action === 'goal.reject') {
1478
+ const reason = str(args.reason, '仍需继续推进完善').trim().slice(0, 300)
1479
+ const prev = board.goalApproval || { id: newId('ga'), objective: board.objective, summary: '', evidence: '', at: nowMs() }
1480
+ board.goalApproval = {
1481
+ ...prev,
1482
+ status: 'rejected',
1483
+ rejectReason: reason,
1484
+ decidedAt: nowMs(),
1485
+ }
1486
+ board.mode = 'goal'
1487
+ pushLog(board, '↩ 用户驳回结项批示(继续 Goal 督导):' + reason.slice(0, 60), by, session)
1488
+ return { ok: true, goalApproval: board.goalApproval, mode: board.mode, board: saveBoard(board, file) }
1489
+ }
1490
+
1250
1491
  if (action === 'settings.set') {
1251
1492
  const next = board.settings || { autoInject: true, guardIdle: true }
1252
1493
  const auto = asBool(args.autoInject)
@@ -1268,13 +1509,37 @@ function runActionUnlocked(input) {
1268
1509
  }
1269
1510
 
1270
1511
  if (action === 'objective.set') {
1512
+ if (isObjectiveLockedByIntervention(session) && asBool(args._fromInterventionSetup) !== true) {
1513
+ return {
1514
+ ok: false,
1515
+ locked: true,
1516
+ error: '当前处于「主动强介入」模式,核心目标已锁定;如需修改请先关闭强介入模式。',
1517
+ }
1518
+ }
1271
1519
  const objective = str(args.objective, '').trim()
1272
1520
  if (!objective) return { ok: false, error: 'objective required' }
1273
1521
  const clips = []
1522
+ const changed = board.objective !== objective
1274
1523
  board.objective = clipInto(clips, 'objective', objective, CAP_OBJECTIVE)
1275
1524
  board.objectiveBy = session
1276
1525
  board.objectiveAt = nowMs()
1277
- pushLog(board, '目标改为:' + objective.slice(0, 60), by, session)
1526
+ board.objectiveUpdatedAt = board.objectiveAt
1527
+ if (asBool(args.setGoalMode) === true) {
1528
+ board.mode = 'goal'
1529
+ }
1530
+ if (changed && board.goalApproval && board.goalApproval.status !== 'pending') {
1531
+ board.goalApproval = null
1532
+ }
1533
+ if (asBool(args.resetStalePlan) === true) {
1534
+ board.plan = []
1535
+ board.cursor = { at: nowMs(), step: '', next: '', blocked: '', by, session }
1536
+ }
1537
+ pushLog(
1538
+ board,
1539
+ (asBool(args.setGoalMode) === true ? '🎯 设为督导目标:' : '目标改为:') + objective.slice(0, 60),
1540
+ by,
1541
+ session,
1542
+ )
1278
1543
  return clipped({ ok: true, board: saveBoard(board, file) }, clips)
1279
1544
  }
1280
1545
 
@@ -1294,17 +1559,18 @@ function runActionUnlocked(input) {
1294
1559
  // Naming the column makes "this list is now empty" and "I did not touch
1295
1560
  // that list" two different sentences.
1296
1561
  const items = asList(args.items)
1297
- if (BOUND_FIELDS.indexOf(str(args.field, '')) >= 0 && items) {
1562
+ const explicitCol = normalizeBoundFieldName(args.field)
1563
+ if (explicitCol && items) {
1298
1564
  if (overCap(items)) return { ok: false, error: tooLongNote(items.length) }
1299
- current[str(args.field, '')] = normalizeList(items)
1565
+ current[explicitCol] = normalizeList(items)
1300
1566
  board.bounds = current
1301
- pushLog(board, '更新边界(允许 ' + current.allowed.length + ' / 禁止 ' + current.forbidden.length + ' / 注意 ' + current.notes.length + ')', by, session)
1567
+ pushLog(board, '更新边界(必做 ' + current.allowed.length + ' / 禁止 ' + current.forbidden.length + ' / 注意 ' + current.notes.length + ')', by, session)
1302
1568
  return { ok: true, bounds: current, board: saveBoard(board, file) }
1303
1569
  }
1304
1570
  // The whole-table form checks every list it was handed before touching
1305
1571
  // any of them: a refusal must leave the two valid columns alone as well,
1306
1572
  // otherwise the error message and the board disagree about what happened.
1307
- const given = { allowed: asList(args.allowed), forbidden: asList(args.forbidden), notes: asList(args.notes) }
1573
+ const given = { allowed: asList(args.allowed !== undefined ? args.allowed : args.must), forbidden: asList(args.forbidden), notes: asList(args.notes) }
1308
1574
  const tooLong = BOUND_FIELDS.filter(name => overCap(given[name]))
1309
1575
  if (tooLong.length) {
1310
1576
  return {
@@ -1317,14 +1583,14 @@ function runActionUnlocked(input) {
1317
1583
  if (given.forbidden) current.forbidden = normalizeList(given.forbidden)
1318
1584
  if (given.notes) current.notes = normalizeList(given.notes)
1319
1585
  board.bounds = current
1320
- pushLog(board, '更新边界(允许 ' + current.allowed.length + ' / 禁止 ' + current.forbidden.length + ' / 注意 ' + current.notes.length + ')', by, session)
1586
+ pushLog(board, '更新边界(必做 ' + current.allowed.length + ' / 禁止 ' + current.forbidden.length + ' / 注意 ' + current.notes.length + ')', by, session)
1321
1587
  return { ok: true, bounds: current, board: saveBoard(board, file) }
1322
1588
  }
1323
1589
 
1324
1590
  if (action === 'bounds.add' || action === 'bounds.pin' || action === 'bounds.remove' || action === 'bounds.edit' || action === 'bounds.consolidate') {
1325
- const col = str(args.field, '').trim()
1326
- if (!BOUND_FIELDS.includes(col)) {
1327
- return { ok: false, error: 'bounds operation requires field: allowed | forbidden | notes' }
1591
+ const col = normalizeBoundFieldName(args.field)
1592
+ if (!col) {
1593
+ return { ok: false, error: 'bounds operation requires field: allowed (必做) | forbidden (禁止) | notes (注意)' }
1328
1594
  }
1329
1595
  const sharedFile = boardFile()
1330
1596
  const isSameFile = file === sharedFile
@@ -1602,11 +1868,118 @@ function runActionUnlocked(input) {
1602
1868
  }
1603
1869
 
1604
1870
  if (action === 'handoff.mark') {
1605
- board.handoff = { at: nowMs(), by, session }
1871
+ const prev = board.handoff || {}
1872
+ board.handoff = { ...prev, at: nowMs(), by, session }
1606
1873
  pushLog(board, '生成并交接给参谋看板:交接单已更新', by, session)
1607
1874
  return { ok: true, handoff: board.handoff, board: saveBoard(board, file) }
1608
1875
  }
1609
1876
 
1877
+ if (action === 'handoff.save') {
1878
+ const prev = board.handoff || {}
1879
+ const reqSource = str(args.source, '')
1880
+ const isChief = by === 'chief' || by === 'DSH 参谋长' || reqSource === 'chief'
1881
+ if (prev.pinned && isChief && asBool(args.force) !== true) {
1882
+ return { ok: false, pinned: true, error: '交接单已被人类固定锁定,参谋长不可覆盖' }
1883
+ }
1884
+ const rawText = args.text !== undefined ? args.text : args.customText
1885
+ const customText = str(rawText, '').slice(0, 16000)
1886
+ const now = nowMs()
1887
+ board.handoff = {
1888
+ ...prev,
1889
+ at: now,
1890
+ by,
1891
+ session: session || prev.session || '',
1892
+ customText,
1893
+ frozenFromAuto: false,
1894
+ updatedAt: now,
1895
+ source: isChief ? 'chief' : 'human',
1896
+ }
1897
+ pushLog(board, isChief ? '✦ 参谋长摘要已同步写入交接单' : '✏️ 人类已手动修订并保存交接单', by, session)
1898
+ return { ok: true, handoff: board.handoff, board: saveBoard(board, file) }
1899
+ }
1900
+
1901
+ if (action === 'handoff.pin') {
1902
+ const prev = board.handoff || {}
1903
+ const nextPinned = asBool(args.pinned) !== undefined ? asBool(args.pinned) : !Boolean(prev.pinned)
1904
+ const now = nowMs()
1905
+ let nextCustomText = str(prev.customText, '')
1906
+ let nextSource = prev.source || 'auto'
1907
+ let nextFrozenFromAuto = Boolean(prev.frozenFromAuto)
1908
+ let nextUpdatedAt = Number(prev.updatedAt) || 0
1909
+
1910
+ if (nextPinned && !nextCustomText.trim()) {
1911
+ const providedSnap = str(args.snapshotText, '').trim()
1912
+ let autoSnap = providedSnap
1913
+ if (!autoSnap) {
1914
+ try {
1915
+ const eff = resolveEffectiveHandoff(activeRuntime, session || prev.session || '', board)
1916
+ autoSnap = str((eff && (eff.text || eff.autoText)) || '', '').trim()
1917
+ } catch {}
1918
+ }
1919
+ if (autoSnap) {
1920
+ nextCustomText = autoSnap.slice(0, 16000)
1921
+ nextFrozenFromAuto = true
1922
+ nextSource = prev.source || 'auto'
1923
+ nextUpdatedAt = now
1924
+ }
1925
+ } else if (!nextPinned && prev.frozenFromAuto === true) {
1926
+ nextCustomText = ''
1927
+ nextFrozenFromAuto = false
1928
+ nextSource = 'auto'
1929
+ nextUpdatedAt = now
1930
+ }
1931
+
1932
+ board.handoff = {
1933
+ ...prev,
1934
+ pinned: nextPinned,
1935
+ pinnedAt: nextPinned ? now : 0,
1936
+ pinnedBy: nextPinned ? by : '',
1937
+ customText: nextCustomText,
1938
+ frozenFromAuto: nextFrozenFromAuto,
1939
+ source: nextSource,
1940
+ updatedAt: nextUpdatedAt,
1941
+ }
1942
+ pushLog(
1943
+ board,
1944
+ nextPinned
1945
+ ? (nextFrozenFromAuto ? '📌 交接单已定住锁定(已冻结当前自动渲染快照,禁止参谋长覆写)' : '📌 交接单已定住锁定:参谋长自动更新已禁止覆写')
1946
+ : (prev.frozenFromAuto ? '🔓 交接单已解除定住并恢复自动实时渲染' : '🔓 交接单已解除定住锁定'),
1947
+ by,
1948
+ session,
1949
+ )
1950
+ return { ok: true, handoff: board.handoff, board: saveBoard(board, file) }
1951
+ }
1952
+
1953
+ if (action === 'handoff.reset') {
1954
+ const prev = board.handoff || {}
1955
+ const keepPin = asBool(args.keepPin) === true
1956
+ board.handoff = {
1957
+ ...prev,
1958
+ at: nowMs(),
1959
+ by,
1960
+ session: session || prev.session || '',
1961
+ customText: '',
1962
+ frozenFromAuto: false,
1963
+ updatedAt: nowMs(),
1964
+ source: 'auto',
1965
+ pinned: keepPin ? Boolean(prev.pinned) : false,
1966
+ pinnedAt: keepPin ? (prev.pinnedAt || 0) : 0,
1967
+ pinnedBy: keepPin ? (prev.pinnedBy || '') : '',
1968
+ }
1969
+ pushLog(board, '↺ 已恢复为自动实时渲染的交接单', by, session)
1970
+ return { ok: true, handoff: board.handoff, board: saveBoard(board, file) }
1971
+ }
1972
+
1973
+ if (action === 'handoff.setSyncOnDigest') {
1974
+ const prev = board.handoff || {}
1975
+ const enabled = asBool(args.enabled !== undefined ? args.enabled : args.syncOnDigest) === true
1976
+ board.handoff = {
1977
+ ...prev,
1978
+ syncOnDigest: enabled,
1979
+ }
1980
+ return { ok: true, handoff: board.handoff, board: saveBoard(board, file) }
1981
+ }
1982
+
1610
1983
  if (action === 'log.add' || action === 'note.add') {
1611
1984
  // pushLog appends whatever it is given, but the very next load clamps one
1612
1985
  // entry to 400 characters — so a long handoff line was stored, then silently
@@ -1762,6 +2135,34 @@ function safe(read, fallback) {
1762
2135
  }
1763
2136
  }
1764
2137
 
2138
+ /** Probe whether the DSH host provides the post-rc.2 named subagent tree APIs. */
2139
+ function probeSubagentSupport(rt) {
2140
+ const subagents = rt ? safe(() => rt.get('subagents'), null) : null
2141
+ if (!subagents) {
2142
+ return {
2143
+ present: false,
2144
+ namedSubagentsSupported: false,
2145
+ missingMethods: [],
2146
+ minDshVersion: '0.2.2-rc.2',
2147
+ warning: '',
2148
+ }
2149
+ }
2150
+ const missingMethods = []
2151
+ if (typeof subagents.resolveName !== 'function') missingMethods.push('resolveName')
2152
+ if (typeof subagents.rootOf !== 'function') missingMethods.push('rootOf')
2153
+ if (typeof subagents.namesOf !== 'function') missingMethods.push('namesOf')
2154
+ const ok = missingMethods.length === 0
2155
+ return {
2156
+ present: true,
2157
+ namedSubagentsSupported: ok,
2158
+ missingMethods,
2159
+ minDshVersion: '0.2.2-rc.2',
2160
+ warning: ok
2161
+ ? ''
2162
+ : '当前 DSH 宿主版本不支持命名子代理树接口(缺少 subagents.resolveName / rootOf / namesOf,常见于 0.2.2-rc.1 及更早版本)。面板其余功能可正常使用;如需使用子代理派发 (task.dispatch) 与插话 (team.steer),请将 DSH 升级至 >= 0.2.2-rc.2。',
2163
+ }
2164
+ }
2165
+
1765
2166
  /** The agent a lookup resolves to: the one named, or the one whose turn this is.
1766
2167
  * Kept separate from sessionOf because the boundary report has to NAME the
1767
2168
  * Session it read facts for — the facts were derived from currentInitiator()
@@ -2198,11 +2599,534 @@ function buildTaskDispatchBrief(board, task, extraPrompt) {
2198
2599
  return lines.join('\n')
2199
2600
  }
2200
2601
 
2602
+ function isInternalProfileCwd(dirPath) {
2603
+ return /[\\/]\.dsh[\\/]+profiles(?:$|[\\/])/i.test(String(dirPath || '').trim())
2604
+ }
2605
+
2606
+ export function getSessionCwd(runtime, sessionId) {
2607
+ const sid = String(sessionId || '').trim()
2608
+ const rootId = sid ? (resolveRootSessionId(sid) || sid) : ''
2609
+ const rt = runtime || activeRuntime
2610
+ if (rt) {
2611
+ try {
2612
+ const agents = rt.get('agents')
2613
+ const agent = (agents && typeof agents.get === 'function') ? (agents.get(sid) || agents.get(rootId)) : null
2614
+ const headerCwd = agent && agent.session && agent.session.header && agent.session.header.cwd
2615
+ if (typeof headerCwd === 'string' && headerCwd.trim()) return headerCwd.trim()
2616
+ const sessionObj = agent && agent.session ? agent.session : safe(() => sessionOf(rt, sid || rootId), null)
2617
+ const wd = rt.get('workingDirectory')
2618
+ if (wd && typeof wd.get === 'function' && sessionObj) {
2619
+ const wDir = wd.get(sessionObj)
2620
+ if (typeof wDir === 'string' && wDir.trim()) return wDir.trim()
2621
+ }
2622
+ } catch {}
2623
+ }
2624
+ for (const probeId of [sid, rootId].filter(Boolean)) {
2625
+ try {
2626
+ const b = loadBoard(boardFileFor(probeId))
2627
+ const row = b && b.sessions && (b.sessions[probeId] || b.sessions[sid])
2628
+ if (row && typeof row.cwd === 'string' && row.cwd.trim() && !isInternalProfileCwd(row.cwd)) {
2629
+ return row.cwd.trim()
2630
+ }
2631
+ } catch {}
2632
+ }
2633
+ if (rt) {
2634
+ try {
2635
+ const reg = rt.get('workspaceRegistry')
2636
+ const rawList = reg && typeof reg.list === 'function' ? reg.list() : []
2637
+ const rows = Array.isArray(rawList)
2638
+ ? rawList
2639
+ : (Array.isArray(rawList && rawList.workspaces) ? rawList.workspaces : (Array.isArray(rawList && rawList.items) ? rawList.items : []))
2640
+ const matched = rows.find((w) => {
2641
+ if (!w || typeof w.path !== 'string' || !w.path.trim()) return false
2642
+ const sids = Array.isArray(w.sessionIds) ? w.sessionIds : []
2643
+ return (sid && sids.includes(sid)) || (rootId && sids.includes(rootId))
2644
+ })
2645
+ if (matched) return matched.path.trim()
2646
+ const sorted = rows
2647
+ .filter(w => w && typeof w.path === 'string' && w.path.trim() && !isInternalProfileCwd(w.path))
2648
+ .slice()
2649
+ .sort((a, b) => Number(b.updatedAt || b.createdAt || 0) - Number(a.updatedAt || a.createdAt || 0))
2650
+ if (sorted[0]) return sorted[0].path.trim()
2651
+ } catch {}
2652
+ }
2653
+ try {
2654
+ const boardsDir = path.join(path.dirname(boardFile()), 'boards')
2655
+ if (fs.existsSync(boardsDir)) {
2656
+ const recentFiles = fs.readdirSync(boardsDir)
2657
+ .filter(name => name.endsWith('.json'))
2658
+ .map((name) => {
2659
+ const full = path.join(boardsDir, name)
2660
+ return { full, mtimeMs: safe(() => fs.statSync(full).mtimeMs, 0) }
2661
+ })
2662
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
2663
+ .slice(0, 15)
2664
+ for (const f of recentFiles) {
2665
+ const b = safe(() => loadBoard(f.full), null)
2666
+ const sessMap = b && b.sessions && typeof b.sessions === 'object' ? Object.values(b.sessions) : []
2667
+ for (const row of sessMap) {
2668
+ if (row && typeof row.cwd === 'string' && row.cwd.trim() && !isInternalProfileCwd(row.cwd)) {
2669
+ return row.cwd.trim()
2670
+ }
2671
+ }
2672
+ }
2673
+ }
2674
+ } catch {}
2675
+ return process.cwd()
2676
+ }
2677
+
2678
+ function resolveArchiveHttpScope(raw) {
2679
+ const s = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
2680
+ if (s === 'global') return 'global'
2681
+ if (s === 'precipitated' || s === 'cold' || s === 'vault') return 'precipitated'
2682
+ return 'session'
2683
+ }
2684
+
2685
+ function resolveBoundRootSid(sessionId = '') {
2686
+ const raw = String(sessionId || '').trim()
2687
+ if (!raw || raw === 'global') return ''
2688
+ const root = String(resolveRootSessionId(raw) || raw).trim()
2689
+ return (!root || root === 'global') ? '' : root
2690
+ }
2691
+
2692
+ function archiveTarget(runtime, sessionId, optOrId = '') {
2693
+ const opts = optOrId && typeof optOrId === 'object'
2694
+ ? optOrId
2695
+ : { cabinetId: typeof optOrId === 'string' ? optOrId : '' }
2696
+ const vaultScope = opts.vaultScope === 'global' ? 'global' : 'session'
2697
+ const sid = String(sessionId || '').trim()
2698
+ const rootSid = resolveBoundRootSid(sid)
2699
+ let cabinetId = vaultScope !== 'global' && typeof opts.cabinetId === 'string' ? opts.cabinetId.trim() : ''
2700
+ if (vaultScope !== 'global' && !cabinetId && rootSid) {
2701
+ try {
2702
+ cabinetId = loadBoard(boardFileFor(rootSid)).activeCabinetId || ''
2703
+ } catch {}
2704
+ }
2705
+ return {
2706
+ customSharedBoardFile: boardFile(),
2707
+ cwd: getSessionCwd(runtime, rootSid || (sid !== 'global' ? sid : '')),
2708
+ vaultScope,
2709
+ ...(vaultScope !== 'global' && rootSid ? { rootSessionId: rootSid } : {}),
2710
+ ...(vaultScope !== 'global' && cabinetId ? { cabinetId } : {}),
2711
+ }
2712
+ }
2713
+
2714
+ function getSessionContextBreakdown(runtime, sessionId, agentArg = null) {
2715
+ const rt = runtime || activeRuntime
2716
+ const sid = String(sessionId || (agentArg && agentArg.id) || '').trim()
2717
+ const rootSid = sid ? (resolveRootSessionId(sid, agentArg) || sid) : ''
2718
+ const agents = rt ? rt.get('agents') : null
2719
+ const ag = agentArg
2720
+ || (sid && agents && typeof agents.get === 'function' ? agents.get(sid) : null)
2721
+ || (rootSid && agents && typeof agents.get === 'function' ? agents.get(rootSid) : null)
2722
+
2723
+ let contextWindow = 128_000
2724
+ let totalTokens = 0
2725
+ let seq = 0
2726
+ let systemTokens = 0
2727
+ let toolsTokens = 0
2728
+ let messageTokens = 0
2729
+ let modelRef = ''
2730
+ let source = 'estimate'
2731
+
2732
+ try {
2733
+ const projectionsSvc = rt ? rt.get('sessionProjections') : null
2734
+ if (ag && ag.session && projectionsSvc && typeof projectionsSvc.snapshot === 'function') {
2735
+ const snap = projectionsSvc.snapshot(ag.session, ['contextPressure', 'contextBreakdown', 'contextTimeline'])
2736
+ const values = (snap && snap.values) || {}
2737
+ const bd = values.contextBreakdown
2738
+ const pressure = values.contextPressure
2739
+ const timeline = values.contextTimeline
2740
+ if (bd && typeof bd === 'object') {
2741
+ if (Number(bd.systemTokens) >= 0) systemTokens = Math.round(Number(bd.systemTokens))
2742
+ if (Number(bd.toolsTokens) >= 0) toolsTokens = Math.round(Number(bd.toolsTokens))
2743
+ if (Number(bd.messageTokens) >= 0) messageTokens = Math.round(Number(bd.messageTokens))
2744
+ if (Number(bd.contextWindow) > 0) contextWindow = Math.round(Number(bd.contextWindow))
2745
+ const bdTotal = Number(bd.totalTokens) || (systemTokens + toolsTokens + messageTokens)
2746
+ if (bdTotal > 0) {
2747
+ totalTokens = Math.round(bdTotal)
2748
+ source = 'projection'
2749
+ }
2750
+ }
2751
+ if (pressure && typeof pressure === 'object') {
2752
+ if (Number(pressure.contextWindow) > 0) contextWindow = Math.round(Number(pressure.contextWindow))
2753
+ const pTok = Number(pressure.projectedTokens) || Number(pressure.pressureTokens) || 0
2754
+ if (pTok > totalTokens) {
2755
+ totalTokens = Math.round(pTok)
2756
+ source = 'projection'
2757
+ }
2758
+ }
2759
+ if (timeline && timeline.current && typeof timeline.current === 'object') {
2760
+ const cur = timeline.current
2761
+ if (!systemTokens && Number(cur.system) > 0) systemTokens = Math.round(Number(cur.system))
2762
+ if (!toolsTokens && Number(cur.tools) > 0) toolsTokens = Math.round(Number(cur.tools))
2763
+ if (!totalTokens && Number(cur.total) > 0) totalTokens = Math.round(Number(cur.total))
2764
+ }
2765
+ }
2766
+ } catch {}
2767
+
2768
+ let provider = ''
2769
+ let model = ''
2770
+ try {
2771
+ if (ag && ag.session && typeof ag.session.ownEvents === 'function') {
2772
+ const events = ag.session.ownEvents() || []
2773
+ seq = events.length
2774
+ for (let i = events.length - 1; i >= 0; i -= 1) {
2775
+ const ev = events[i]
2776
+ if (!ev) continue
2777
+ if (!provider && ev.type === 'request/header' && ev.data && ev.data.header && ev.data.header.config) {
2778
+ provider = String(ev.data.header.config.provider || '')
2779
+ model = String(ev.data.header.config.model || '')
2780
+ }
2781
+ const usage = ev.usage || (ev.message && ev.message.usage) || (ev.data && ev.data.usage)
2782
+ if (!totalTokens && usage && typeof usage === 'object') {
2783
+ const calc = (Number(usage.inputTokens) || 0)
2784
+ + (Number(usage.cacheReadTokens) || 0)
2785
+ + (Number(usage.outputTokens) || 0)
2786
+ const uTotal = Number(usage.totalTokens) || calc
2787
+ if (uTotal > 0) {
2788
+ totalTokens = Math.round(uTotal)
2789
+ if (source === 'estimate') source = 'usage'
2790
+ }
2791
+ if (Number(usage.contextWindow) > 0) contextWindow = Math.round(Number(usage.contextWindow))
2792
+ if (!systemTokens && Number(usage.systemTokens) > 0) systemTokens = Math.round(Number(usage.systemTokens))
2793
+ if (!toolsTokens && Number(usage.toolsTokens) > 0) toolsTokens = Math.round(Number(usage.toolsTokens))
2794
+ }
2795
+ if (provider && model && totalTokens > 0) break
2796
+ }
2797
+ }
2798
+ } catch {}
2799
+
2800
+ try {
2801
+ const llm = activeLlm || (rt ? rt.get('llm') : null)
2802
+ if (!provider && ag && ag.session && typeof ag.session.requestHeader === 'function') {
2803
+ const h = ag.session.requestHeader()
2804
+ if (h && h.config) {
2805
+ provider = String(h.config.provider || '')
2806
+ model = String(h.config.model || '')
2807
+ }
2808
+ }
2809
+ if (provider && model) {
2810
+ modelRef = `${provider}/${model}`
2811
+ if (llm && typeof llm.resolveModelInfo === 'function') {
2812
+ const info = llm.resolveModelInfo(provider, model)
2813
+ if (info && Number(info.contextWindow) > 0) contextWindow = Math.round(Number(info.contextWindow))
2814
+ }
2815
+ }
2816
+ } catch {}
2817
+
2818
+ // Fallback rough split only when official projection breakdown isn't populated yet
2819
+ if (totalTokens > 0 && systemTokens === 0 && toolsTokens === 0 && messageTokens === 0) {
2820
+ systemTokens = Math.min(totalTokens, Math.round(Math.min(52_000, Math.max(12_000, contextWindow * 0.04))))
2821
+ toolsTokens = Math.min(Math.max(0, totalTokens - systemTokens), 1500)
2822
+ messageTokens = Math.max(0, totalTokens - systemTokens - toolsTokens)
2823
+ } else if (totalTokens > 0 && messageTokens === 0) {
2824
+ messageTokens = Math.max(0, totalTokens - systemTokens - toolsTokens)
2825
+ }
2826
+
2827
+ const overheadTokens = systemTokens + toolsTokens
2828
+ const usedTokens = Math.max(totalTokens, overheadTokens + messageTokens)
2829
+ const otherTokens = Math.max(0, usedTokens - overheadTokens - messageTokens)
2830
+ const pct = contextWindow > 0 ? Math.min(100, Math.round((usedTokens / contextWindow) * 100)) : 0
2831
+
2832
+ return {
2833
+ totalTokens: usedTokens,
2834
+ usedTokens,
2835
+ contextWindow,
2836
+ pct,
2837
+ systemTokens,
2838
+ toolsTokens,
2839
+ messageTokens,
2840
+ otherTokens,
2841
+ overheadTokens,
2842
+ modelRef,
2843
+ seq,
2844
+ source,
2845
+ }
2846
+ }
2847
+
2848
+ function linkedPeersForSession(runtime, rootId) {
2849
+ if (!rootId) return { linkedPeersCount: 0, linkedPeersProgress: [] }
2850
+ const state = loadChiefState()
2851
+ const cluster = getLinkedCluster(state, rootId)
2852
+ if (!Array.isArray(cluster) || cluster.length <= 1) {
2853
+ return { linkedPeersCount: 0, linkedPeersProgress: [] }
2854
+ }
2855
+ const linkedPeersProgress = collectClusterPeerProgress(makeChiefDeps(runtime), cluster, rootId)
2856
+ return {
2857
+ linkedPeersCount: Math.max(0, cluster.length - 1),
2858
+ linkedPeersProgress,
2859
+ }
2860
+ }
2861
+
2862
+ function composeHandoffFromNarrative({ board, narrativeText = '', cluster = [] } = {}) {
2863
+ const b = board || emptyBoard()
2864
+ const lines = ['# 交接单(参谋长提炼同步版)', '']
2865
+ if (b.objective) {
2866
+ lines.push('## 总目标', `- ${b.objective}`, '')
2867
+ }
2868
+ if (b.cursor && (b.cursor.step || b.cursor.next || b.cursor.blocked)) {
2869
+ lines.push('## 当前断点', `- 当前步骤:${b.cursor.step || '无'}`, b.cursor.next ? `- 下一步:${b.cursor.next}` : '', b.cursor.blocked ? `- 阻塞点:${b.cursor.blocked}` : '', '')
2870
+ }
2871
+ if (narrativeText) {
2872
+ lines.push('## 参谋长态势研判与进展摘要', narrativeText.trim(), '')
2873
+ }
2874
+ const openSteps = (b.plan || []).filter(s => s && !s.done)
2875
+ if (openSteps.length) {
2876
+ lines.push('## 待推进计划', ...openSteps.slice(0, 8).map((s, i) => `${i + 1}. ${s.text}`), '')
2877
+ }
2878
+ const openTasks = (b.tasks || []).filter(t => t && t.status !== 'done')
2879
+ if (openTasks.length) {
2880
+ lines.push('## 未完任务', ...openTasks.slice(0, 8).map(t => `- [${t.status}] #${t.id} ${t.title}${t.note ? `(${String(t.note).slice(0, 100)})` : ''}`), '')
2881
+ }
2882
+ const fb = (b.bounds && b.bounds.forbidden) || []
2883
+ const al = (b.bounds && b.bounds.allowed) || []
2884
+ const nt = (b.bounds && b.bounds.notes) || []
2885
+ if (fb.length || al.length || nt.length) {
2886
+ lines.push('## 生效红线与工作边界')
2887
+ if (fb.length) lines.push(...fb.slice(0, 6).map(x => `- 🚫 禁止:${x}`))
2888
+ if (al.length) lines.push(...al.slice(0, 4).map(x => `- ✅ 必做:${x}`))
2889
+ if (nt.length) lines.push(...nt.slice(0, 4).map(x => `- 📌 注意:${x}`))
2890
+ lines.push('')
2891
+ }
2892
+ if (Array.isArray(cluster) && cluster.length > 1) {
2893
+ lines.push(`## 当前协同网络`, `- 已联通协同群组共 ${cluster.length} 个独立会话。`, '')
2894
+ }
2895
+ return lines.filter((l, i, arr) => !(l === '' && arr[i - 1] === '')).join('\n').slice(0, 12000)
2896
+ }
2897
+
2898
+ function resolveEffectiveHandoff(runtime, sessionId, board, extraTeamTasks = undefined) {
2899
+ const b = board || emptyBoard()
2900
+ const h = b.handoff || {}
2901
+ const rootSid = sessionId ? (resolveRootSessionId(sessionId) || sessionId) : ''
2902
+ const customText = typeof h.customText === 'string' ? h.customText.trim() : ''
2903
+ const pinned = Boolean(h.pinned)
2904
+ const syncOnDigest = Boolean(h.syncOnDigest)
2905
+
2906
+ const teamTasks = extraTeamTasks !== undefined
2907
+ ? extraTeamTasks
2908
+ : fetchTeamTasks(runtime, sessionId ? { id: sessionId } : null)
2909
+ const takenOutArchives = rootSid ? collectTakenOutAndFlipped(runtime, rootSid, b.activeCabinetId) : []
2910
+ const autoText = renderHandoff(b, boundaries(runtime, sessionId), 5200, sessionId, {
2911
+ teamTasks,
2912
+ takenOutArchives,
2913
+ })
2914
+
2915
+ const effectiveText = customText ? h.customText : autoText
2916
+ let chiefNarrativeAt = 0
2917
+ let chiefNarrativeText = ''
2918
+ try {
2919
+ const st = loadChiefState()
2920
+ const ws = st && st.workspaces && st.workspaces[rootSid || 'global']
2921
+ if (ws && ws.narrative && ws.narrative.text) {
2922
+ chiefNarrativeText = ws.narrative.text
2923
+ chiefNarrativeAt = Number(ws.narrative.at) || 0
2924
+ }
2925
+ } catch {}
2926
+
2927
+ const updatedAt = Number(h.updatedAt) || Number(h.at) || 0
2928
+ const hasRichWork = Boolean(b.objective || (b.plan && b.plan.length) || (b.tasks && b.tasks.length) || (b.memory && b.memory.length))
2929
+ const isIncomplete = !effectiveText.trim() || (!customText && !b.objective && !(b.tasks && b.tasks.length) && !(b.plan && b.plan.length))
2930
+ const isStale = !pinned && Boolean(
2931
+ hasRichWork && (
2932
+ (chiefNarrativeText && h.source !== 'human' && chiefNarrativeAt > updatedAt + 2000)
2933
+ || (Number(b.updatedAt) > updatedAt + 60_000 && !customText)
2934
+ ),
2935
+ )
2936
+
2937
+ return {
2938
+ text: effectiveText,
2939
+ autoText,
2940
+ source: customText ? (h.source || 'human') : 'auto',
2941
+ isCustom: Boolean(customText),
2942
+ pinned,
2943
+ pinnedAt: Number(h.pinnedAt) || 0,
2944
+ pinnedBy: h.pinnedBy || '',
2945
+ updatedAt,
2946
+ handoffAt: Number(h.at) || 0,
2947
+ syncOnDigest,
2948
+ isIncomplete,
2949
+ isStale,
2950
+ hasNarrativeUpdate: Boolean(chiefNarrativeText && chiefNarrativeAt > updatedAt + 2000),
2951
+ }
2952
+ }
2953
+
2954
+ /** Combine Session-Cabinet mounted items with explicitly flipped precipitated entries (NEVER reads Global Cabinet!). */
2955
+ function collectTakenOutAndFlipped(runtime, rootId, cabinetId = '') {
2956
+ if (!rootId) return []
2957
+ const targetOpt = archiveTarget(runtime, rootId, { cabinetId, vaultScope: 'session' })
2958
+ const working = getTakenOutArchivesForSession(rootId, targetOpt).map(e => ({
2959
+ ...e,
2960
+ _deskScope: 'session',
2961
+ folderLabel: `本局桌面/${e.folder || '档案'}`,
2962
+ title: `[桌面强调·本局] ${e.title}`,
2963
+ }))
2964
+ const globalTargetOpt = archiveTarget(runtime, rootId, { cabinetId: '', vaultScope: 'global' })
2965
+ const takenGlobal = getTakenOutGlobalForSession(rootId, globalTargetOpt).map(e => ({
2966
+ ...e,
2967
+ _deskScope: 'global',
2968
+ folderLabel: `全局桌面/${e.folder || '经验'}`,
2969
+ title: `[桌面强调·全局] ${e.title}`,
2970
+ }))
2971
+ const state = loadChiefState()
2972
+ const ws = state && state.workspaces && state.workspaces[rootId]
2973
+ const flippedIds = ws && Array.isArray(ws.flippedPrecipitatedIds) ? ws.flippedPrecipitatedIds : []
2974
+ let mappedFlipped = []
2975
+ if (flippedIds.length) {
2976
+ const projectKey = resolveProjectKey(targetOpt.cwd)
2977
+ const flippedEntries = getFlippedOutPrecipitatedForSession(projectKey, rootId, true, targetOpt)
2978
+ mappedFlipped = flippedEntries.map(e => ({
2979
+ ...e,
2980
+ _deskScope: 'precipitated',
2981
+ folder: e.category || 'contracts',
2982
+ folderLabel: `沉淀桌面/${e.category || '经验'}`,
2983
+ title: `[桌面强调·沉淀] ${e.title}`,
2984
+ }))
2985
+ }
2986
+ return [...working, ...takenGlobal, ...mappedFlipped]
2987
+ }
2988
+
2989
+ function collectDeskItemsForUi(runtime, rootId, cabinetId = '') {
2990
+ if (!rootId) return []
2991
+ const targetOpt = archiveTarget(runtime, rootId, { cabinetId, vaultScope: 'session' })
2992
+ const out = []
2993
+ try {
2994
+ for (const it of getTakenOutArchivesForSession(rootId, targetOpt)) {
2995
+ out.push({ id: it.id, scope: 'session', title: it.title, summary: it.summary || '', folder: it.folder || 'inbox', paperclip: it.paperclip || 'silver' })
2996
+ }
2997
+ } catch {}
2998
+ try {
2999
+ const gOpt = archiveTarget(runtime, rootId, { cabinetId: '', vaultScope: 'global' })
3000
+ for (const it of getTakenOutGlobalForSession(rootId, gOpt)) {
3001
+ out.push({ id: it.id, scope: 'global', title: it.title, summary: it.summary || '', folder: it.folder || 'coords', paperclip: it.paperclip || 'silver' })
3002
+ }
3003
+ } catch {}
3004
+ try {
3005
+ const st = loadChiefState()
3006
+ const ws = st && st.workspaces && st.workspaces[rootId]
3007
+ const flippedIds = ws && Array.isArray(ws.flippedPrecipitatedIds) ? ws.flippedPrecipitatedIds : []
3008
+ if (flippedIds.length) {
3009
+ const pk = resolveProjectKey(targetOpt.cwd)
3010
+ for (const it of getFlippedOutPrecipitatedForSession(pk, rootId, true, targetOpt)) {
3011
+ out.push({ id: it.id, scope: 'precipitated', title: it.title, summary: it.summary || '', folder: it.category || 'contracts', paperclip: 'gold' })
3012
+ }
3013
+ }
3014
+ } catch {}
3015
+ return out
3016
+ }
3017
+
3018
+ /** Collect digest-safe archive context for Lead/Subagent prompt: ONLY desk-spotlight items across all 3 vaults (sealed items NEVER leak to Lead), plus Smart Compaction flag & posture. */
3019
+ function collectDigestArchiveContext(runtime, rootId, cabinetId = '') {
3020
+ const takenOutArchives = rootId ? collectTakenOutAndFlipped(runtime, rootId, cabinetId) : []
3021
+ const sessionArchiveBriefs = []
3022
+ let smartCompactActive = false
3023
+ let chiefPermissionMode = DEFAULT_CHIEF_PERMISSION_MODE
3024
+ if (rootId) {
3025
+ try {
3026
+ const cfg = resolveWorkspaceConfig(loadChiefState(), rootId)
3027
+ const tm = (cfg && cfg.tacticalModes) || {}
3028
+ smartCompactActive = Boolean(tm.smartCompact)
3029
+ chiefPermissionMode = normalizePermissionMode(cfg && cfg.permissionMode)
3030
+ } catch {}
3031
+ }
3032
+ return { takenOutArchives, sessionArchiveBriefs, smartCompactActive, chiefPermissionMode }
3033
+ }
3034
+
3035
+ /**
3036
+ * Execute host session compaction across Cordis service isolation:
3037
+ * 1. Resolve live or archived session agent (`agents.get` -> `sessionController.resolveAgent`).
3038
+ * 2. Refuse compaction while the agent is actively running.
3039
+ * 3. Prefer unisolated/direct `compaction.compactNow` if present; otherwise invoke
3040
+ * `commands.execute(ag, '/compact', [], signal)` which crosses into `@deepseek-ai/dsh-command-compact`.
3041
+ */
3042
+ export async function executeHostSessionCompaction(rt, sid, cmdId) {
3043
+ const targetSid = String(sid || '').trim()
3044
+ if (!targetSid) throw new Error('missing target session id for compaction')
3045
+ const agents = rt && typeof rt.get === 'function' ? rt.get('agents') : null
3046
+ let ag = agents && typeof agents.get === 'function' ? agents.get(targetSid) : null
3047
+ if (!ag) {
3048
+ const ctrl = rt && typeof rt.get === 'function' ? rt.get('sessionController') : null
3049
+ if (ctrl && typeof ctrl.resolveAgent === 'function') {
3050
+ try {
3051
+ const resolved = await ctrl.resolveAgent(targetSid)
3052
+ if (resolved && resolved.agent) ag = resolved.agent
3053
+ } catch {}
3054
+ }
3055
+ }
3056
+ if (!ag) throw new Error('target session agent not found for compaction')
3057
+ if (ag.status === 'running') throw new Error('agent is busy running; refusing compaction')
3058
+
3059
+ const signal = AbortSignal.timeout(60_000)
3060
+ const effectiveCmdId = cmdId || ('chief-compact-' + Date.now().toString(36))
3061
+
3062
+ const compSvc = rt && typeof rt.get === 'function' ? rt.get('compaction') : null
3063
+ if (compSvc && typeof compSvc.compactNow === 'function') {
3064
+ const directRes = await compSvc.compactNow(ag, signal, effectiveCmdId)
3065
+ if (directRes === null) {
3066
+ return { ok: true, noop: true, via: 'compaction.compactNow', commandId: effectiveCmdId, text: 'No compactable history yet.' }
3067
+ }
3068
+ return directRes && typeof directRes === 'object'
3069
+ ? { ok: true, noop: false, via: 'compaction.compactNow', ...directRes }
3070
+ : { ok: true, noop: false, via: 'compaction.compactNow', result: directRes }
3071
+ }
3072
+
3073
+ const cmdSvc = rt && typeof rt.get === 'function' ? rt.get('commands') : null
3074
+ if (cmdSvc && typeof cmdSvc.execute === 'function') {
3075
+ const execOut = await cmdSvc.execute(ag, '/compact', [], signal)
3076
+ const cmdRes = execOut && execOut.result ? execOut.result : execOut
3077
+ if (!cmdRes) {
3078
+ throw new Error('dsh-command /compact unavailable in runtime')
3079
+ }
3080
+ if (cmdRes.kind === 'error') {
3081
+ throw new Error(String(cmdRes.text || 'host /compact command failed'))
3082
+ }
3083
+ const text = String(cmdRes.text || '')
3084
+ const noop = /no compactable history/i.test(text)
3085
+ return {
3086
+ ok: true,
3087
+ noop,
3088
+ via: 'commands:/compact',
3089
+ commandId: (execOut && execOut.commandId) || effectiveCmdId,
3090
+ text,
3091
+ sourceEventSeq: cmdRes.sourceEventSeq,
3092
+ }
3093
+ }
3094
+
3095
+ throw new Error('dsh-compaction and /compact command services unavailable')
3096
+ }
3097
+
2201
3098
  function makeChiefDeps(runtime) {
2202
3099
  const rt = runtime || activeRuntime
2203
3100
  return {
2204
3101
  runtime: rt,
2205
3102
  getLlm: () => activeLlm || (rt ? rt.get('llm') : null),
3103
+ getAttachments: () => safe(() => (rt ? rt.get('attachments') : null), null),
3104
+ getSessionCwd: (sid) => getSessionCwd(rt, sid),
3105
+ getAgentStatus(sid) {
3106
+ const agents = rt ? rt.get('agents') : null
3107
+ const ag = agents && typeof agents.get === 'function' ? agents.get(sid) : null
3108
+ return (ag && ag.status) || 'idle'
3109
+ },
3110
+ async measureSessionTokens(sid, agentArg) {
3111
+ return getSessionContextBreakdown(rt, sid, agentArg)
3112
+ },
3113
+ composeHandoffFromNarrative(opts) {
3114
+ return composeHandoffFromNarrative(opts)
3115
+ },
3116
+ async compactSessionNow(sid, cmdId) {
3117
+ return executeHostSessionCompaction(rt, sid, cmdId)
3118
+ },
3119
+ stagePendingTransfer(text, fromSid, extra = {}) {
3120
+ const cleanText = String(text || '').trim()
3121
+ if (!cleanText) return false
3122
+ return writePending({
3123
+ at: nowMs(),
3124
+ by: (extra && extra.by) || 'chief',
3125
+ session: fromSid || 'global',
3126
+ text: cleanText,
3127
+ ...(extra && typeof extra === 'object' ? extra : {}),
3128
+ })
3129
+ },
2206
3130
  resolveRootSessionId,
2207
3131
  resolveAgentIdentity,
2208
3132
  refreshSubagentTree,
@@ -2223,6 +3147,15 @@ function makeChiefDeps(runtime) {
2223
3147
  saveBoard(board, file)
2224
3148
  })
2225
3149
  },
3150
+ executeSubagentAction: (input, callerAgent, signal) => executeSubagentAction(rt, input, callerAgent, signal),
3151
+ cancelAutoContinue(sid, reason) {
3152
+ return Boolean(
3153
+ activeAutoContinue
3154
+ && typeof activeAutoContinue.cancelSession === 'function'
3155
+ && sid
3156
+ && activeAutoContinue.cancelSession(sid, reason || 'chief-halt'),
3157
+ )
3158
+ },
2226
3159
  }
2227
3160
  }
2228
3161
 
@@ -2304,6 +3237,12 @@ async function executeSubagentAction(runtime, input, callerAgent, signal) {
2304
3237
  }
2305
3238
  } else if (subagents && liveCaller) {
2306
3239
  // Case 2: Use DSH native subagent service (continue existing subagent or spawn/fork a new one)
3240
+ if (typeof subagents.resolveName !== 'function' || typeof subagents.startActivation !== 'function') {
3241
+ return {
3242
+ ok: false,
3243
+ error: '当前 DSH 宿主不支持命名子代理 API(缺少 subagents.resolveName / startActivation,例如 0.2.2-rc.1 为重构前旧接口),请将 DSH 升级至 >= 0.2.2-rc.2 后再使用子代理派发与插话。',
3244
+ }
3245
+ }
2307
3246
  const providerName = str(args.provider, targetTask.preset === 'fork' ? 'fork' : 'spawn') || 'spawn'
2308
3247
  const preset = str(args.preset, targetTask.preset && targetTask.preset !== 'fork' && targetTask.preset !== 'spawn' ? targetTask.preset : '')
2309
3248
  const candidateName = sanitizeSubagentName(requestedTarget, targetTask.id)
@@ -2409,6 +3348,12 @@ async function executeSubagentAction(runtime, input, callerAgent, signal) {
2409
3348
  if (!targetName) return { ok: false, error: 'team.steer requires agent name or task id with assigned subagent' }
2410
3349
  if (!text) return { ok: false, error: 'team.steer requires message / prompt text' }
2411
3350
  if (!subagents || !liveCaller) return { ok: false, error: 'subagents service or live caller agent unavailable' }
3351
+ if (typeof subagents.resolveName !== 'function') {
3352
+ return {
3353
+ ok: false,
3354
+ error: '当前 DSH 宿主不支持命名子代理 API(缺少 subagents.resolveName,例如 0.2.2-rc.1 为重构前旧接口),请将 DSH 升级至 >= 0.2.2-rc.2 后再使用子代理派发与插话。',
3355
+ }
3356
+ }
2412
3357
 
2413
3358
  let targetId = ''
2414
3359
  try {
@@ -2440,6 +3385,15 @@ async function executeSubagentAction(runtime, input, callerAgent, signal) {
2440
3385
  const targetName = str(args.agent || args.subagent || args.target || (linkedTask && (linkedTask.subagent || linkedTask.owner)), '').trim()
2441
3386
  if (!targetName) return { ok: false, error: 'team.interrupt requires agent name or task id' }
2442
3387
  if (!subagents || !liveCaller) return { ok: false, error: 'subagents service or live caller agent unavailable' }
3388
+ if (typeof subagents.resolveName !== 'function') {
3389
+ return {
3390
+ ok: false,
3391
+ error: '当前 DSH 宿主不支持命名子代理 API(缺少 subagents.resolveName,例如 0.2.2-rc.1 为重构前旧接口),请将 DSH 升级至 >= 0.2.2-rc.2 后再使用子代理派发与插话。',
3392
+ }
3393
+ }
3394
+ if (typeof subagents.interrupt !== 'function') {
3395
+ return { ok: false, error: '当前 DSH 宿主不支持 subagents.interrupt,请升级至 >= 0.2.2-rc.2' }
3396
+ }
2443
3397
 
2444
3398
  let targetId = ''
2445
3399
  try {
@@ -2526,7 +3480,8 @@ function routeTable(runtime) {
2526
3480
  }
2527
3481
  }
2528
3482
  } catch {}
2529
- let pinnedModelRef = (secState.config && secState.config.modelRef) || ''
3483
+ const effCfg = resolveWorkspaceConfig(secState, rootSid)
3484
+ let pinnedModelRef = effCfg.modelRef || ''
2530
3485
  if (pinnedModelRef) {
2531
3486
  try {
2532
3487
  const llmSvc = runtime && runtime.get('llm')
@@ -2537,6 +3492,16 @@ function routeTable(runtime) {
2537
3492
  }
2538
3493
  } catch {}
2539
3494
  }
3495
+ const rootWs = secState.workspaces && secState.workspaces[rootSid]
3496
+ const tacticalModes = effCfg.tacticalModes || {}
3497
+ const flippedIds = (rootWs && Array.isArray(rootWs.flippedPrecipitatedIds)) ? rootWs.flippedPrecipitatedIds.slice() : []
3498
+ const boundRootSid = resolveBoundRootSid(sessionId)
3499
+ const sessionArchOpt = archiveTarget(runtime, boundRootSid, { cabinetId: board.activeCabinetId, vaultScope: 'session' })
3500
+ const archiveMeta = {
3501
+ ...getArchiveMeta(boundRootSid, sessionArchOpt),
3502
+ counts: getThreeTierArchiveCounts(boundRootSid, flippedIds, sessionArchOpt),
3503
+ }
3504
+ const hostCompat = probeSubagentSupport(runtime)
2540
3505
  sendJson(res, 200, {
2541
3506
  ok: true,
2542
3507
  board,
@@ -2544,9 +3509,17 @@ function routeTable(runtime) {
2544
3509
  agentIdentity,
2545
3510
  teamTasks: sessionId ? fetchTeamTasks(runtime, { id: sessionId }) : undefined,
2546
3511
  boundaries: boundaries(runtime, sessionId),
3512
+ hostCompat,
2547
3513
  chiefMeta: {
2548
- paceMode: (secState.config && secState.config.paceMode) || 'manual',
2549
- autoPilot: Boolean(secState.config && secState.config.autoPilot),
3514
+ backendBuild: BACKEND_BUILD,
3515
+ hostCompat,
3516
+ paceMode: effCfg.paceMode || 'manual',
3517
+ stopped: Boolean(effCfg.stopped || effCfg.paceMode === 'stopped'),
3518
+ permissionMode: effCfg.permissionMode || 'danger-full-access',
3519
+ autoPilot: Boolean(effCfg.autoPilot),
3520
+ tacticalModes,
3521
+ runtimeGuard: (rootWs && rootWs.runtimeGuard) || {},
3522
+ flippedCount: flippedIds.length,
2550
3523
  modelRef: pinnedModelRef,
2551
3524
  followModelRef,
2552
3525
  resolvedModelRef: pinnedModelRef || followModelRef || '',
@@ -2554,8 +3527,9 @@ function routeTable(runtime) {
2554
3527
  factsCount,
2555
3528
  mailboxCount,
2556
3529
  linkedPeersCount: Math.max(0, cluster.length - 1),
3530
+ contextUsage: sessionId ? getSessionContextBreakdown(runtime, sessionId) : null,
2557
3531
  },
2558
- archiveMeta: getArchiveMeta(rootSid, boardFile()),
3532
+ archiveMeta,
2559
3533
  })
2560
3534
  } catch (error) {
2561
3535
  sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
@@ -2576,13 +3550,20 @@ function routeTable(runtime) {
2576
3550
  const subagents = sessionId ? await refreshSubagentTree(runtime, sessionId, fullBoard) : []
2577
3551
  const agentIdentity = sessionId ? resolveAgentIdentity(runtime, sessionId) : null
2578
3552
  const rootSid = resolveRootSessionId(sessionId) || sessionId
3553
+ const linked = linkedPeersForSession(runtime, rootSid)
3554
+ const archCtx = collectDigestArchiveContext(runtime, rootSid, fullBoard.activeCabinetId)
2579
3555
  sendJson(res, 200, {
2580
3556
  ok: true,
2581
3557
  digest: renderDigest(fullBoard, {
2582
3558
  subagents,
2583
3559
  agentIdentity,
2584
3560
  teamTasks: sessionId ? fetchTeamTasks(runtime, { id: sessionId }) : undefined,
2585
- takenOutArchives: rootSid ? getTakenOutArchivesForSession(rootSid, boardFile()) : [],
3561
+ takenOutArchives: archCtx.takenOutArchives,
3562
+ sessionArchiveBriefs: archCtx.sessionArchiveBriefs,
3563
+ smartCompactActive: archCtx.smartCompactActive,
3564
+ chiefPermissionMode: archCtx.chiefPermissionMode,
3565
+ linkedPeersCount: linked.linkedPeersCount,
3566
+ linkedPeersProgress: linked.linkedPeersProgress,
2586
3567
  }),
2587
3568
  sessions: board.sessions || {},
2588
3569
  updatedAt: board.updatedAt,
@@ -2682,14 +3663,22 @@ function routeTable(runtime) {
2682
3663
  } catch {}
2683
3664
  const board = sessionId ? boardForSession(boardFileFor(sessionId)) : emptyBoard()
2684
3665
  const pending = readPending()
2685
- const rootSid = resolveRootSessionId(sessionId) || sessionId
3666
+ const hInfo = resolveEffectiveHandoff(runtime, sessionId, board)
2686
3667
  sendJson(res, 200, {
2687
3668
  ok: true,
2688
- text: renderHandoff(board, boundaries(runtime, sessionId), 5200, sessionId, {
2689
- teamTasks: fetchTeamTasks(runtime, sessionId ? { id: sessionId } : null),
2690
- takenOutArchives: rootSid ? getTakenOutArchivesForSession(rootSid, boardFile()) : [],
2691
- }),
2692
- handoffAt: board.handoff ? board.handoff.at : 0,
3669
+ text: hInfo.text,
3670
+ autoText: hInfo.autoText,
3671
+ source: hInfo.source,
3672
+ isCustom: hInfo.isCustom,
3673
+ pinned: hInfo.pinned,
3674
+ pinnedAt: hInfo.pinnedAt,
3675
+ pinnedBy: hInfo.pinnedBy,
3676
+ updatedAt: hInfo.updatedAt,
3677
+ handoffAt: hInfo.handoffAt,
3678
+ syncOnDigest: hInfo.syncOnDigest,
3679
+ isIncomplete: hInfo.isIncomplete,
3680
+ isStale: hInfo.isStale,
3681
+ hasNarrativeUpdate: hInfo.hasNarrativeUpdate,
2693
3682
  autoInject: !((board.settings || {}).autoInject === false),
2694
3683
  guardIdle: !((board.settings || {}).guardIdle === false),
2695
3684
  pending: pending ? { at: pending.at, by: pending.by, failedTarget: pending.failedTarget || '' } : null,
@@ -2708,7 +3697,7 @@ function routeTable(runtime) {
2708
3697
  const propRes = proposeBoundToChief(makeChiefDeps(runtime), {
2709
3698
  sessionId,
2710
3699
  by: typeof body.by === 'string' ? body.by : 'operator',
2711
- field: typeof body.field === 'string' ? body.field : 'forbidden',
3700
+ field: normalizeBoundFieldName(body.field) || 'forbidden',
2712
3701
  item: typeof body.item === 'string' ? body.item : (typeof body.text === 'string' ? body.text : ''),
2713
3702
  items: Array.isArray(body.items) ? body.items : undefined,
2714
3703
  reason: typeof body.reason === 'string' ? body.reason : '',
@@ -2755,12 +3744,19 @@ function routeTable(runtime) {
2755
3744
  const url = new URL(req.url || '/', 'http://127.0.0.1')
2756
3745
  let sessionId = url.searchParams.get('session') || ''
2757
3746
  let regenerate = url.searchParams.get('regenerate') === '1'
3747
+ const qSync = url.searchParams.get('syncHandoff')
3748
+ let syncHandoff = qSync === '1' || qSync === 'true' ? true : (qSync === '0' || qSync === 'false' ? false : undefined)
2758
3749
  if (req.method === 'POST') {
2759
3750
  const body = await readBody(req).catch(() => ({}))
2760
3751
  if (typeof body.session === 'string' && body.session) sessionId = body.session
2761
3752
  if (body.regenerate === true) regenerate = true
3753
+ if (typeof body.syncHandoff === 'boolean') syncHandoff = body.syncHandoff
3754
+ }
3755
+ const view = await getChiefView(makeChiefDeps(runtime), sessionId, { regenerate, autoSummarize: !regenerate, syncHandoff })
3756
+ if (view && view.handoffSyncResult && view.handoffSyncResult.synced && sessionId) {
3757
+ sendJson(res, 200, { ...view, board: boardForSession(boardFileFor(sessionId)) })
3758
+ return
2762
3759
  }
2763
- const view = await getChiefView(makeChiefDeps(runtime), sessionId, { regenerate, autoSummarize: !regenerate })
2764
3760
  sendJson(res, 200, view)
2765
3761
  } catch (error) {
2766
3762
  sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
@@ -2779,6 +3775,7 @@ function routeTable(runtime) {
2779
3775
  text: typeof body.text === 'string' ? body.text : '',
2780
3776
  forcedTarget: typeof body.target === 'string' ? body.target : '',
2781
3777
  forcedMode: typeof body.mode === 'string' ? body.mode : 'steer',
3778
+ images: Array.isArray(body.images) ? body.images : [],
2782
3779
  })
2783
3780
  const board = out.ok && sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
2784
3781
  sendJson(res, out.ok ? 200 : 400, board ? { ...out, board } : out)
@@ -2787,6 +3784,28 @@ function routeTable(runtime) {
2787
3784
  }
2788
3785
  },
2789
3786
  },
3787
+ {
3788
+ path: API + '/chief/relay-archives',
3789
+ handler: async (req, res) => {
3790
+ if (!guard(req, res)) return
3791
+ try {
3792
+ const body = await readBody(req)
3793
+ const sessionId = typeof body?.session === 'string' ? body.session : ''
3794
+ const rootSid = resolveRootSessionId(sessionId) || sessionId || 'global'
3795
+ const out = await relayArchivesWithChief(makeChiefDeps(runtime), {
3796
+ sessionId: rootSid,
3797
+ items: Array.isArray(body?.items) ? body.items : [],
3798
+ instruction: typeof body?.instruction === 'string' ? body.instruction : '',
3799
+ target: typeof body?.target === 'string' ? body.target : 'lead',
3800
+ mode: typeof body?.mode === 'string' ? body.mode : 'steer',
3801
+ cabinetId: typeof body?.cabinetId === 'string' ? body.cabinetId : '',
3802
+ })
3803
+ sendJson(res, out && out.ok === false ? 400 : 200, out)
3804
+ } catch (error) {
3805
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
3806
+ }
3807
+ },
3808
+ },
2790
3809
  {
2791
3810
  path: API + '/chief/relay',
2792
3811
  handler: async (req, res) => {
@@ -2801,6 +3820,7 @@ function routeTable(runtime) {
2801
3820
  subject: typeof body.subject === 'string' ? body.subject : '',
2802
3821
  text: typeof body.text === 'string' ? body.text : '',
2803
3822
  mode: typeof body.mode === 'string' ? body.mode : 'steer',
3823
+ images: Array.isArray(body.images) ? body.images : [],
2804
3824
  })
2805
3825
  const view = await getChiefView(makeChiefDeps(runtime), sessionId, { autoSummarize: false })
2806
3826
  sendJson(res, out.ok ? 200 : 400, { ...out, view })
@@ -2830,10 +3850,67 @@ function routeTable(runtime) {
2830
3850
  if (!guard(req, res)) return
2831
3851
  try {
2832
3852
  const body = await readBody(req)
2833
- const updated = updateChiefConfig(body || {})
2834
- const sessionId = typeof body.session === 'string' ? body.session : ''
3853
+ const sessionId = typeof body?.session === 'string' ? body.session : ''
3854
+ const rootSid = resolveRootSessionId(sessionId) || sessionId || 'global'
3855
+ const updated = updateChiefConfig({ ...(body || {}), sessionId: rootSid })
3856
+ const wantsInterventionOn = Boolean(body && body.tacticalModes && body.tacticalModes.intervention === true)
3857
+ const coreObjDraft = typeof body?.coreObjective === 'string' ? body.coreObjective.trim() : ''
3858
+ const targetSessionForBoard = sessionId || (rootSid !== 'global' ? rootSid : '')
3859
+ if (updated && updated.ok !== false && wantsInterventionOn && coreObjDraft && targetSessionForBoard) {
3860
+ runAction({
3861
+ action: 'objective.set',
3862
+ objective: coreObjDraft,
3863
+ session: targetSessionForBoard,
3864
+ by: 'operator',
3865
+ _fromInterventionSetup: true,
3866
+ })
3867
+ }
3868
+ if (updated && (updated.emergencyStopped || (updated.config && (updated.config.stopped || updated.config.paceMode === 'stopped')))) {
3869
+ if (activeAutoContinue && typeof activeAutoContinue.cancelSession === 'function') {
3870
+ activeAutoContinue.cancelSession(sessionId, 'chief stopped')
3871
+ if (rootSid && rootSid !== sessionId) activeAutoContinue.cancelSession(rootSid, 'chief stopped')
3872
+ }
3873
+ }
2835
3874
  const view = await getChiefView(makeChiefDeps(runtime), sessionId, { autoSummarize: false })
2836
- sendJson(res, 200, { ...updated, view })
3875
+ const latestBoard = targetSessionForBoard ? boardForSession(boardFileFor(targetSessionForBoard)) : null
3876
+ sendJson(res, updated && updated.ok === false ? 400 : 200, {
3877
+ ...updated,
3878
+ ...(latestBoard ? { board: latestBoard } : {}),
3879
+ view,
3880
+ })
3881
+ } catch (error) {
3882
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
3883
+ }
3884
+ },
3885
+ },
3886
+ {
3887
+ path: API + '/chief/suggest-objective',
3888
+ handler: async (req, res) => {
3889
+ if (!guard(req, res)) return
3890
+ try {
3891
+ const body = await readBody(req).catch(() => ({}))
3892
+ const sessionId = typeof body?.session === 'string' ? body.session : ''
3893
+ const out = await suggestCoreObjectiveWithChief(makeChiefDeps(runtime), {
3894
+ sessionId,
3895
+ draft: typeof body?.draft === 'string' ? body.draft : '',
3896
+ mode: typeof body?.mode === 'string' ? body.mode : 'auto',
3897
+ previousSuggestions: Array.isArray(body?.previousSuggestions) ? body.previousSuggestions : [],
3898
+ })
3899
+ sendJson(res, out && out.ok === false ? 400 : 200, out)
3900
+ } catch (error) {
3901
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
3902
+ }
3903
+ },
3904
+ },
3905
+ {
3906
+ path: API + '/chief/recommend-compact',
3907
+ handler: async (req, res) => {
3908
+ if (!guard(req, res)) return
3909
+ try {
3910
+ const body = await readBody(req).catch(() => ({}))
3911
+ const sessionId = typeof body?.session === 'string' ? body.session : ''
3912
+ const out = await recommendAndSetCompactThreshold(makeChiefDeps(runtime), { sessionId })
3913
+ sendJson(res, out && out.ok === false ? 400 : 200, out)
2837
3914
  } catch (error) {
2838
3915
  sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
2839
3916
  }
@@ -2938,25 +4015,109 @@ function routeTable(runtime) {
2938
4015
  const url = new URL(req.url || '/', 'http://127.0.0.1')
2939
4016
  if (req.method === 'GET' || !req.method) {
2940
4017
  const sessionId = url.searchParams.get('session') || ''
2941
- const rootSid = resolveRootSessionId(sessionId) || sessionId
4018
+ const rootSid = resolveBoundRootSid(sessionId)
2942
4019
  const query = url.searchParams.get('q') || ''
2943
4020
  const folder = url.searchParams.get('folder') || ''
2944
4021
  const paperclip = url.searchParams.get('paperclip') || ''
2945
- const out = listArchiveHeaders(rootSid, { query, folder, paperclip }, boardFile())
4022
+ const reqScope = resolveArchiveHttpScope(url.searchParams.get('scope') || url.searchParams.get('vaultScope') || '')
4023
+ const workingScope = reqScope === 'global' ? 'global' : 'session'
4024
+ const cabinetId = workingScope === 'global' ? '' : (url.searchParams.get('cabinetId') || '')
4025
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope: workingScope })
4026
+ const st = loadChiefState()
4027
+ const ws = rootSid && st.workspaces ? st.workspaces[rootSid] : null
4028
+ const flippedIds = (ws && Array.isArray(ws.flippedPrecipitatedIds)) ? ws.flippedPrecipitatedIds.slice() : []
4029
+ const out = listArchiveHeaders(rootSid, {
4030
+ query,
4031
+ folder,
4032
+ paperclip,
4033
+ vaultScope: workingScope,
4034
+ includePrecipitated: true,
4035
+ flippedIds,
4036
+ }, targetOpt)
2946
4037
  sendJson(res, 200, {
2947
4038
  ...out,
2948
- archiveMeta: getArchiveMeta(rootSid, boardFile()),
4039
+ requestedScope: reqScope,
4040
+ flippedPrecipitatedIds: flippedIds,
4041
+ deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
4042
+ counts: out.counts || getThreeTierArchiveCounts(rootSid, flippedIds, targetOpt),
4043
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
2949
4044
  })
2950
4045
  return
2951
4046
  }
2952
4047
 
2953
4048
  const body = await readBody(req)
2954
4049
  const sessionId = typeof body.session === 'string' ? body.session : ''
2955
- const rootSid = resolveRootSessionId(sessionId) || sessionId
4050
+ const rootSid = resolveBoundRootSid(sessionId)
2956
4051
  const op = typeof body.op === 'string' ? body.op : 'save'
4052
+ const reqScope = resolveArchiveHttpScope(body.vaultScope || body.scope || '')
4053
+ const workingScope = reqScope === 'global' ? 'global' : 'session'
4054
+ const cabinetId = workingScope === 'global' ? '' : (typeof body.cabinetId === 'string' ? body.cabinetId : '')
4055
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope: workingScope })
4056
+ const projectKey = resolveProjectKey(targetOpt.cwd)
4057
+
4058
+ if (['flipOut', 'sealBack', 'deletePrecipitated', 'updatePrecipitated'].includes(op)) {
4059
+ const pid = typeof body.id === 'string' ? body.id : (typeof body.precipitatedId === 'string' ? body.precipitatedId : '')
4060
+ const pRes = mutatePrecipitated(projectKey, {
4061
+ ...body,
4062
+ id: pid,
4063
+ precipitatedId: pid,
4064
+ op,
4065
+ rootSessionId: rootSid,
4066
+ }, targetOpt)
4067
+ if (!pRes.ok) {
4068
+ sendJson(res, 400, pRes)
4069
+ return
4070
+ }
4071
+ if (rootSid) {
4072
+ if (op === 'flipOut' && pid) updateWorkspaceFlippedIds(rootSid, { flippedId: pid })
4073
+ else if ((op === 'sealBack' || op === 'deletePrecipitated') && pid) updateWorkspaceFlippedIds(rootSid, { sealId: pid })
4074
+ }
4075
+ const stAfter = loadChiefState()
4076
+ const wsAfter = rootSid && stAfter.workspaces ? stAfter.workspaces[rootSid] : null
4077
+ const flippedAfter = (wsAfter && Array.isArray(wsAfter.flippedPrecipitatedIds)) ? wsAfter.flippedPrecipitatedIds.slice() : []
4078
+ const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedAfter }, targetOpt)
4079
+ sendJson(res, 200, {
4080
+ ...pRes,
4081
+ archives,
4082
+ deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
4083
+ counts: archives.counts || getThreeTierArchiveCounts(rootSid, flippedAfter, targetOpt),
4084
+ flippedPrecipitatedIds: flippedAfter,
4085
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
4086
+ })
4087
+ return
4088
+ }
4089
+
4090
+ if (op === 'pullPrecipitated') {
4091
+ const pid = typeof body.id === 'string' ? body.id : (typeof body.precipitatedId === 'string' ? body.precipitatedId : '')
4092
+ const targetScope = resolveArchiveHttpScope(body.targetScope || body.toScope || 'session') === 'global' ? 'global' : 'session'
4093
+ const copyRes = copyPrecipitatedToVault(projectKey, {
4094
+ ...body,
4095
+ id: pid,
4096
+ precipitatedId: pid,
4097
+ targetScope,
4098
+ rootSessionId: rootSid,
4099
+ }, targetOpt)
4100
+ if (!copyRes.ok) {
4101
+ sendJson(res, 400, copyRes)
4102
+ return
4103
+ }
4104
+ const stAfter = loadChiefState()
4105
+ const wsAfter = rootSid && stAfter.workspaces ? stAfter.workspaces[rootSid] : null
4106
+ const flippedAfter = (wsAfter && Array.isArray(wsAfter.flippedPrecipitatedIds)) ? wsAfter.flippedPrecipitatedIds.slice() : []
4107
+ const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedAfter }, targetOpt)
4108
+ sendJson(res, 200, {
4109
+ ...copyRes,
4110
+ archives,
4111
+ deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
4112
+ counts: archives.counts || getThreeTierArchiveCounts(rootSid, flippedAfter, targetOpt),
4113
+ flippedPrecipitatedIds: flippedAfter,
4114
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
4115
+ })
4116
+ return
4117
+ }
2957
4118
 
2958
4119
  if (op === 'precipitateNotes') {
2959
- // Sweep active board.notes (session and/or shared) into cold-stored archives.json
4120
+ // Sweep active board.notes (session and/or shared) into active working cabinet (defaults to current session cabinet if bound)
2960
4121
  const noteIds = Array.isArray(body.noteIds) ? new Set(body.noteIds.map(String)) : null
2961
4122
  let sweptCount = 0
2962
4123
  const sweepFromFile = (targetFile) => {
@@ -2972,6 +4133,7 @@ function routeTable(runtime) {
2972
4133
  }
2973
4134
  const saved = mutateArchive({
2974
4135
  op: 'save',
4136
+ vaultScope: workingScope,
2975
4137
  sourceNoteId: note.id,
2976
4138
  title: note.title,
2977
4139
  body: note.body,
@@ -2979,45 +4141,73 @@ function routeTable(runtime) {
2979
4141
  paperclip: (note.pinned || (note.tags || []).includes('anchor')) ? 'gold' : undefined,
2980
4142
  by: note.by || 'user',
2981
4143
  rootSessionId: rootSid,
2982
- }, boardFile())
4144
+ }, targetOpt)
2983
4145
  if (saved.ok) sweptCount += 1
2984
4146
  else keep.push(note)
2985
4147
  }
2986
4148
  if (keep.length !== b.notes.length) {
2987
4149
  b.notes = keep
2988
- pushLog(b, `🗄️ 已将 ${sweptCount} 篇便签沉淀封存入「档案」柜`, 'operator', sessionId)
4150
+ pushLog(b, `🗄️ 已将 ${sweptCount} 篇便签收纳进「${workingScope === 'global' ? '全局' : '本会话'}档案柜」`, 'operator', sessionId)
2989
4151
  saveBoard(b, targetFile)
2990
4152
  }
2991
4153
  })
2992
4154
  }
2993
4155
  if (sessionId) sweepFromFile(boardFileFor(sessionId))
2994
- sweepFromFile(boardFile())
4156
+ else sweepFromFile(boardFile())
4157
+ const stNow = loadChiefState()
4158
+ const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
4159
+ const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
2995
4160
  const board = sessionId ? boardForSession(boardFileFor(sessionId)) : emptyBoard()
2996
- const archives = listArchiveHeaders(rootSid, {}, boardFile())
4161
+ const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedNow }, targetOpt)
2997
4162
  sendJson(res, 200, {
2998
4163
  ok: true,
2999
4164
  sweptCount,
3000
4165
  board,
3001
4166
  archives,
3002
- archiveMeta: getArchiveMeta(rootSid, boardFile()),
4167
+ counts: archives.counts || getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
4168
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
3003
4169
  })
3004
4170
  return
3005
4171
  }
3006
4172
 
3007
4173
  const out = mutateArchive({
3008
4174
  ...body,
4175
+ vaultScope: workingScope,
3009
4176
  op,
3010
4177
  rootSessionId: rootSid,
3011
- }, boardFile())
4178
+ }, targetOpt)
3012
4179
  if (!out.ok) {
3013
4180
  sendJson(res, 400, out)
3014
4181
  return
3015
4182
  }
3016
- const archives = listArchiveHeaders(rootSid, {}, boardFile())
4183
+ const isCrossCopy = op === 'copyToGlobal' || op === 'copyToSession'
4184
+ const usedCabId = out.activeCabinetId || out.cabinetId || ''
4185
+ if (rootSid && workingScope !== 'global' && !isCrossCopy && usedCabId && op !== 'listCabinets') {
4186
+ const bFile = boardFileFor(rootSid)
4187
+ withBoardLock(bFile, () => {
4188
+ const b = loadBoard(bFile)
4189
+ if (op === 'switchCabinet' || op === 'createCabinet' || !b.activeCabinetId) {
4190
+ b.activeCabinetId = usedCabId
4191
+ saveBoard(b, bFile)
4192
+ }
4193
+ })
4194
+ }
4195
+ const stNow = loadChiefState()
4196
+ const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
4197
+ const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
4198
+ const finalOpt = isCrossCopy
4199
+ ? targetOpt
4200
+ : archiveTarget(runtime, rootSid || sessionId, { cabinetId: out.activeCabinetId || cabinetId || out.cabinetId, vaultScope: workingScope })
4201
+ const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedNow }, finalOpt)
4202
+ const board = sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
3017
4203
  sendJson(res, 200, {
3018
4204
  ...out,
3019
4205
  archives,
3020
- archiveMeta: getArchiveMeta(rootSid, boardFile()),
4206
+ deskItems: collectDeskItemsForUi(runtime, rootSid, out.activeCabinetId || cabinetId || out.cabinetId || ''),
4207
+ diffSummary: out.diffSummary || archives.diffSummary,
4208
+ counts: out.counts || archives.counts || getThreeTierArchiveCounts(rootSid, flippedNow, finalOpt),
4209
+ ...(board ? { board } : {}),
4210
+ archiveMeta: getArchiveMeta(rootSid, finalOpt),
3021
4211
  })
3022
4212
  } catch (error) {
3023
4213
  sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
@@ -3032,8 +4222,14 @@ function routeTable(runtime) {
3032
4222
  const url = new URL(req.url || '/', 'http://127.0.0.1')
3033
4223
  const id = url.searchParams.get('id') || ''
3034
4224
  const sessionId = url.searchParams.get('session') || ''
3035
- const rootSid = resolveRootSessionId(sessionId) || sessionId
3036
- const out = getArchiveDetail(id, rootSid, boardFile())
4225
+ const reqScope = resolveArchiveHttpScope(url.searchParams.get('scope') || url.searchParams.get('vaultScope') || '')
4226
+ const cabinetId = reqScope === 'global' ? '' : (url.searchParams.get('cabinetId') || '')
4227
+ const isPrecip = url.searchParams.get('precipitated') === '1' || url.searchParams.get('precipitated') === 'true' || reqScope === 'precipitated'
4228
+ const rootSid = resolveBoundRootSid(sessionId)
4229
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope: reqScope === 'global' ? 'global' : 'session' })
4230
+ const out = isPrecip
4231
+ ? getPrecipitatedDetail(resolveProjectKey(targetOpt.cwd), id, rootSid, targetOpt)
4232
+ : getArchiveDetail(id, rootSid, targetOpt)
3037
4233
  sendJson(res, out.ok ? 200 : 404, out)
3038
4234
  } catch (error) {
3039
4235
  sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
@@ -3047,17 +4243,130 @@ function routeTable(runtime) {
3047
4243
  try {
3048
4244
  const body = await readBody(req)
3049
4245
  const sessionId = typeof body.session === 'string' ? body.session : ''
3050
- const rootSid = resolveRootSessionId(sessionId) || sessionId
4246
+ const rootSid = resolveBoundRootSid(sessionId)
4247
+ const vaultScope = resolveArchiveHttpScope(body.vaultScope || body.scope) === 'global' ? 'global' : 'session'
4248
+ const cabinetId = vaultScope === 'global' ? '' : (typeof body.cabinetId === 'string' ? body.cabinetId : '')
4249
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope })
3051
4250
  const out = await organizeArchivesWithChief(makeChiefDeps(runtime), {
3052
- sessionId: rootSid,
4251
+ sessionId: rootSid || 'global',
4252
+ vaultScope,
4253
+ cabinetId,
3053
4254
  ids: Array.isArray(body.ids) ? body.ids : [],
3054
4255
  folder: typeof body.folder === 'string' ? body.folder : '',
3055
4256
  scope: typeof body.scope === 'string' ? body.scope : 'unorganized',
3056
4257
  instruction: typeof body.instruction === 'string' ? body.instruction : '',
3057
4258
  })
4259
+ const stNow = loadChiefState()
4260
+ const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
4261
+ const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
4262
+ sendJson(res, out.ok ? 200 : 400, {
4263
+ ...out,
4264
+ counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
4265
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
4266
+ })
4267
+ } catch (error) {
4268
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
4269
+ }
4270
+ },
4271
+ },
4272
+ {
4273
+ path: API + '/archives/distill-to-global',
4274
+ handler: async (req, res) => {
4275
+ if (!guard(req, res)) return
4276
+ try {
4277
+ const body = await readBody(req)
4278
+ const sessionId = typeof body.session === 'string' ? body.session : ''
4279
+ const rootSid = resolveBoundRootSid(sessionId)
4280
+ if (!rootSid) {
4281
+ sendJson(res, 400, { ok: false, error: '当前未绑定具体会话,无法从本会话档案柜提炼' })
4282
+ return
4283
+ }
4284
+ const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
4285
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope: 'session' })
4286
+ const out = await distillSessionArchivesToGlobal(makeChiefDeps(runtime), {
4287
+ sessionId: rootSid,
4288
+ cabinetId,
4289
+ ids: Array.isArray(body.ids) ? body.ids : null,
4290
+ folder: typeof body.folder === 'string' ? body.folder : '',
4291
+ clearSource: Boolean(body.clearSource),
4292
+ instruction: typeof body.instruction === 'string' ? body.instruction : '',
4293
+ })
4294
+ const stNow = loadChiefState()
4295
+ const wsNow = stNow.workspaces ? stNow.workspaces[rootSid] : null
4296
+ const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
4297
+ sendJson(res, out.ok ? 200 : 400, {
4298
+ ...out,
4299
+ deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
4300
+ counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
4301
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
4302
+ })
4303
+ } catch (error) {
4304
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
4305
+ }
4306
+ },
4307
+ },
4308
+ {
4309
+ path: API + '/archives/harvest',
4310
+ handler: async (req, res) => {
4311
+ if (!guard(req, res)) return
4312
+ try {
4313
+ const body = await readBody(req)
4314
+ const sessionId = typeof body.session === 'string' ? body.session : ''
4315
+ const rootSid = resolveBoundRootSid(sessionId)
4316
+ const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
4317
+ const vaultScope = 'session'
4318
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope })
4319
+ const out = await harvestTurnDetailsToArchive(makeChiefDeps(runtime), {
4320
+ sessionId: rootSid,
4321
+ vaultScope,
4322
+ cabinetId,
4323
+ trigger: 'manual',
4324
+ focusHint: typeof body.focusHint === 'string' ? body.focusHint : '',
4325
+ })
4326
+ const stNow = loadChiefState()
4327
+ const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
4328
+ const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
4329
+ sendJson(res, out.ok ? 200 : 400, {
4330
+ ...out,
4331
+ counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
4332
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
4333
+ })
4334
+ } catch (error) {
4335
+ sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
4336
+ }
4337
+ },
4338
+ },
4339
+ {
4340
+ path: API + '/archives/precipitate',
4341
+ handler: async (req, res) => {
4342
+ if (!guard(req, res)) return
4343
+ try {
4344
+ const body = await readBody(req)
4345
+ const sessionId = typeof body.session === 'string' ? body.session : ''
4346
+ const rootSid = resolveRootSessionId(sessionId) || sessionId
4347
+ const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
4348
+ const vaultScope = resolveArchiveHttpScope(body.vaultScope || body.scope) === 'global' ? 'global' : 'session'
4349
+ if (vaultScope !== 'global') {
4350
+ sendJson(res, 400, { ok: false, error: '实行三级梯度制度:本会话档案请先升级入「🌐 全局档案柜」,再从全局档案柜沉淀为冷档案' })
4351
+ return
4352
+ }
4353
+ const targetOpt = archiveTarget(runtime, rootSid || sessionId, { cabinetId, vaultScope })
4354
+ const out = await precipitateExperienceWithChief(makeChiefDeps(runtime), {
4355
+ sessionId: rootSid,
4356
+ vaultScope,
4357
+ op: typeof body.op === 'string' ? body.op : 'cabinet',
4358
+ cabinetId,
4359
+ folder: typeof body.folder === 'string' ? body.folder : '',
4360
+ ids: Array.isArray(body.ids) ? body.ids : [],
4361
+ clearSource: Boolean(body.clearSource),
4362
+ })
4363
+ const stNow = loadChiefState()
4364
+ const wsNow = rootSid && stNow.workspaces ? stNow.workspaces[rootSid] : null
4365
+ const flippedNow = (wsNow && Array.isArray(wsNow.flippedPrecipitatedIds)) ? wsNow.flippedPrecipitatedIds.slice() : []
3058
4366
  sendJson(res, out.ok ? 200 : 400, {
3059
4367
  ...out,
3060
- archiveMeta: getArchiveMeta(rootSid, boardFile()),
4368
+ counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
4369
+ archiveMeta: getArchiveMeta(rootSid, targetOpt),
3061
4370
  })
3062
4371
  } catch (error) {
3063
4372
  sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
@@ -3084,6 +4393,7 @@ function syncPlanFromTodos(args, sessionId) {
3084
4393
 
3085
4394
  /** create_goal / update_goal → objective. */
3086
4395
  function syncObjective(name, args, sessionId) {
4396
+ if (isObjectiveLockedByIntervention(sessionId)) return
3087
4397
  const objective = objectiveFromGoal(name, args)
3088
4398
  if (!objective) return
3089
4399
  const file = boardFileFor(sessionId)
@@ -3095,8 +4405,12 @@ function syncObjective(name, args, sessionId) {
3095
4405
  board.objective = objective.slice(0, 2000)
3096
4406
  board.objectiveBy = String(sessionId || '')
3097
4407
  board.objectiveAt = nowMs()
3098
- if (wantGoalMode) board.mode = 'goal'
3099
- pushLog(board, '长期目标(/goal)改为:' + objective.slice(0, 60) + (previous && previous !== objective ? '(原:' + previous.slice(0, 40) + ')' : ''), 'agent', sessionId)
4408
+ if (wantGoalMode) {
4409
+ board.mode = 'goal'
4410
+ if (board.goalApproval && board.goalApproval.status !== 'pending') board.goalApproval = null
4411
+ }
4412
+ board.objectiveUpdatedAt = board.objectiveAt
4413
+ pushLog(board, '长期目标改为:' + objective.slice(0, 60) + (previous && previous !== objective ? '(原:' + previous.slice(0, 40) + ')' : ''), 'agent', sessionId)
3100
4414
  saveBoard(board, file)
3101
4415
  })
3102
4416
  }
@@ -3254,6 +4568,7 @@ const BOARD_PARAMETERS = {
3254
4568
  'archive.search',
3255
4569
  'archive.read',
3256
4570
  'archive.save',
4571
+ 'context.compact',
3257
4572
  'memory.add',
3258
4573
  'memory.remove',
3259
4574
  'memory.ask',
@@ -3262,8 +4577,9 @@ const BOARD_PARAMETERS = {
3262
4577
  'Board operation (MUST be called whenever recording tasks/status/conclusions or relaying messages; plain text alone does NOT update the board or notify peers). '
3263
4578
  + 'Use "graph.plan" (or "task.batch") to plan a hierarchical/DAG task graph in one call (supports parentId, blockedBy, owner/subagent, intent, evidence). '
3264
4579
  + '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. '
3265
- + 'Use "bounds.propose" (field: "forbidden"|"allowed"|"notes", item, reason) when hitting a permission/sandbox/environment wall or summarizing boundaries so DSH Chief can request user approval. '
3266
- + 'Cold Engineering Archives ("archive.search", "archive.read", "archive.save") store precipitated long-term engineering memories lazily and are NEVER auto-injected: call archive.search / archive.read ONLY when the user explicitly requests historical archive lookup, or archive.save when asked to precipitate a durable engineering lesson.',
4580
+ + '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. '
4581
+ + '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). '
4582
+ + 'When Smart Co-Managed Compaction ("✦ 智选") is enabled, call "context.compact" with a concise phase-summary in "text" at clean phase boundaries to ask DSH Chief to harvest details into this session\'s cabinet and compact.',
3267
4583
  },
3268
4584
  tasks: {
3269
4585
  type: 'array',
@@ -3379,15 +4695,15 @@ const BOARD_PARAMETERS = {
3379
4695
  priority: { type: 'string', enum: PRIORITIES, description: 'Task priority.' },
3380
4696
  field: {
3381
4697
  type: 'string',
3382
- enum: ['allowed', 'forbidden', 'notes'],
3383
- description: 'bounds.propose / bounds.set: target boundary column ("forbidden", "allowed", or "notes").',
4698
+ enum: ['allowed', 'must', 'forbidden', 'notes'],
4699
+ description: 'bounds.propose / bounds.set: target boundary column ("forbidden" = 禁止红线, "allowed"/"must" = 必做事项, or "notes" = 注意事项).',
3384
4700
  },
3385
4701
  item: { type: 'string', description: 'bounds.propose / bounds.add / bounds.pin / bounds.remove / bounds.edit / bounds.consolidate: boundary rule text.' },
3386
4702
  oldItem: { type: 'string', description: 'bounds.edit: existing boundary rule text to replace.' },
3387
4703
  removeItems: { type: 'array', items: { type: 'string' }, description: 'bounds.consolidate: scattered boundary rules to remove and replace with item.' },
3388
4704
  reason: { type: 'string', description: 'bounds.propose: brief context on why this boundary is needed (e.g. wall hit, permission block, or user request).' },
3389
4705
  items: { type: 'array', items: { type: 'string' }, description: 'bounds.propose (multiple rules) or bounds.set (new contents of column named by field).' },
3390
- allowed: { type: 'array', items: { type: 'string' }, description: 'bounds.set: the whole 允许 column.' },
4706
+ allowed: { type: 'array', items: { type: 'string' }, description: 'bounds.set: the whole 必做 (allowed) column.' },
3391
4707
  forbidden: { type: 'array', items: { type: 'string' }, description: 'bounds.set: the whole 禁止 column.' },
3392
4708
  notes: { type: 'array', items: { type: 'string' }, description: 'bounds.set: the whole 注意 column.' },
3393
4709
  autoInject: { type: 'boolean', description: 'settings.set: hand the digest to every turn of this machine.' },
@@ -3492,7 +4808,7 @@ function boardTool(runtime) {
3492
4808
  'Shared task graph, subagent team controller, cross-session communication bus, plan, and anchor chief (参谋看板, coordinated by DSH 参谋长). '
3493
4809
  + 'MANDATORY DISCIPLINE: (1) Always call this tool to record objectives, task status changes (doing/blocked/done + evidence), or pinned conclusions — oral text alone counts as NOT recorded. '
3494
4810
  + '(2) Always call "mail.send", "task.dispatch", or "team.steer" when relaying information or delegating across lead/subagents/sessions — oral @mentions do NOT reach peers. '
3495
- + '(3) When you hit a permission/sandbox/environment wall or are asked to summarize boundaries, call action="bounds.propose" (field="forbidden"|"allowed"|"notes", item, reason) to submit to DSH Chief (宰相), who requests user approval before injecting into global bounds.',
4811
+ + '(3) When you hit a permission/sandbox/environment wall or are asked to summarize boundaries, call action="bounds.propose" (field="forbidden"|"allowed"|"notes", item, reason; note "allowed" represents 必做事项) to submit to DSH Chief (宰相), who requests user approval before injecting into global bounds.',
3496
4812
  parameters: BOARD_PARAMETERS,
3497
4813
  output: {
3498
4814
  schema: { type: 'object', description: 'The board summary after the operation.' },
@@ -3633,7 +4949,7 @@ function boardTool(runtime) {
3633
4949
  sessionId: rawSession,
3634
4950
  callerAgent,
3635
4951
  by: byDefault,
3636
- field: str(passed.field, 'forbidden'),
4952
+ field: normalizeBoundFieldName(passed.field) || 'forbidden',
3637
4953
  item: str(passed.item || passed.text || passed.note || passed.body, ''),
3638
4954
  items: Array.isArray(passed.items) ? passed.items : undefined,
3639
4955
  reason: str(passed.reason || passed.intent || passed.subject, ''),
@@ -3690,6 +5006,24 @@ function boardTool(runtime) {
3690
5006
  }
3691
5007
  }
3692
5008
 
5009
+ if (passed.action === 'context.compact') {
5010
+ const scRes = await requestSmartCompactFromLead(makeChiefDeps(runtime), {
5011
+ sessionId: rawSession || session,
5012
+ reason: str(passed.text || passed.summary || passed.body || passed.note, ''),
5013
+ by: byDefault,
5014
+ })
5015
+ if (!scRes || scRes.ok === false) {
5016
+ return { ok: false, error: (scRes && scRes.error) || '智选压缩请求未能执行' }
5017
+ }
5018
+ const board = session ? boardForSession(boardFileFor(session)) : emptyBoard()
5019
+ const roster = session ? await refreshSubagentTree(runtime, session, board) : []
5020
+ return {
5021
+ ok: true,
5022
+ smartCompact: scRes,
5023
+ ...summary(board, roster),
5024
+ }
5025
+ }
5026
+
3693
5027
  if (passed.action === 'task.dispatch' || passed.action === 'team.steer' || passed.action === 'team.interrupt') {
3694
5028
  const subRes = await executeSubagentAction(runtime, { ...passed, by: byDefault, session }, callerAgent, exec && exec.signal)
3695
5029
  if (!subRes.ok) return { ok: false, error: subRes.error }
@@ -3898,7 +5232,7 @@ function handoffTool(runtime) {
3898
5232
  // dropped by whichever rename finished second.
3899
5233
  withBoardLock(selfFile, () => {
3900
5234
  const marked = loadBoard(selfFile)
3901
- marked.handoff = { at: nowMs(), by: 'agent', session }
5235
+ marked.handoff = { ...(marked.handoff || {}), at: nowMs(), by: 'agent', session }
3902
5236
  pushLog(marked, '交接单已生成并交出', 'agent', session)
3903
5237
  saveBoard(marked, selfFile)
3904
5238
  })
@@ -3907,14 +5241,17 @@ function handoffTool(runtime) {
3907
5241
  // wrote bounds/objective must still tell the successor what the operator
3908
5242
  // forbade and what the machine is working on.
3909
5243
  const board = boardForSession(selfFile)
3910
- const limits = boundaries(runtime, session)
3911
- const rootSid = resolveRootSessionId(session) || session
5244
+ const hInfo = resolveEffectiveHandoff(
5245
+ runtime,
5246
+ session,
5247
+ board,
5248
+ fetchTeamTasks(runtime, exec && exec.agent ? exec.agent : null),
5249
+ )
3912
5250
  return {
3913
5251
  ok: true,
3914
- text: renderHandoff(board, limits, 5200, session, {
3915
- teamTasks: fetchTeamTasks(runtime, exec && exec.agent ? exec.agent : null),
3916
- takenOutArchives: rootSid ? getTakenOutArchivesForSession(rootSid, boardFile()) : [],
3917
- }),
5252
+ text: hInfo.text,
5253
+ pinned: hInfo.pinned,
5254
+ source: hInfo.source,
3918
5255
  counts: {
3919
5256
  plan: (board.plan || []).length,
3920
5257
  openSteps: (board.plan || []).filter(step => !step.done).length,
@@ -3967,44 +5304,206 @@ async function injectInto(agent, text) {
3967
5304
  return { ok: false, error: 'inject 不接受完整消息形状(纯文本会写坏会话日志,不试)' }
3968
5305
  }
3969
5306
 
5307
+ /**
5308
+ * System-level handover & state deployment to a target Chief workspace (`一键部署参谋`).
5309
+ * Copies active objective, mode, plan steps, unfinished tasks (scrubbing stale `doing` / child handles),
5310
+ * cursor, bounds, and Chief facts/narrative/chat — while optionally copying working cabinet archives
5311
+ * per `archiveTransferPolicy` ('none' | 'mounted' | 'drawer' | 'all') and strictly NEVER leaking precipitated cold vault.
5312
+ */
5313
+ export function deployStateToTargetChief(runtime, {
5314
+ fromSessionId = '',
5315
+ toSessionId = '',
5316
+ archiveTransferPolicy = 'none',
5317
+ archiveDrawer = '',
5318
+ toCabinetId = '',
5319
+ customNote = '',
5320
+ } = {}) {
5321
+ const fromRoot = resolveRootSessionId(fromSessionId) || String(fromSessionId || '').trim()
5322
+ const toRoot = resolveRootSessionId(toSessionId) || String(toSessionId || '').trim()
5323
+ if (!fromRoot || !toRoot || fromRoot === toRoot) {
5324
+ return { ok: false, error: '跨会话移交需要两个不同的会话 ID' }
5325
+ }
5326
+
5327
+ const srcBoard = boardForSession(boardFileFor(fromRoot))
5328
+ const destFile = boardFileFor(toRoot)
5329
+ let copiedTaskCount = 0
5330
+ let copiedStepCount = 0
5331
+
5332
+ withBoardLock(destFile, () => {
5333
+ const dest = loadBoard(destFile)
5334
+ if (srcBoard.objective) {
5335
+ dest.objective = srcBoard.objective
5336
+ dest.objectiveBy = srcBoard.objectiveBy || fromRoot
5337
+ dest.objectiveAt = srcBoard.objectiveAt || nowMs()
5338
+ dest.objectiveUpdatedAt = nowMs()
5339
+ }
5340
+ dest.mode = srcBoard.mode === 'goal' ? 'goal' : 'plan'
5341
+ dest.goalApproval = null
5342
+
5343
+ if (Array.isArray(srcBoard.plan) && srcBoard.plan.length > 0) {
5344
+ dest.plan = srcBoard.plan.map(step => ({
5345
+ id: step.id || newId('s'),
5346
+ text: step.text,
5347
+ done: Boolean(step.done),
5348
+ }))
5349
+ copiedStepCount = dest.plan.length
5350
+ }
5351
+
5352
+ const srcTasks = Array.isArray(srcBoard.tasks) ? srcBoard.tasks : []
5353
+ const unfinished = srcTasks.filter(t => t && t.status !== 'done')
5354
+ const unfinishedIds = new Set(unfinished.map(t => t.id))
5355
+ const existingIds = new Set((dest.tasks || []).map(t => t.id))
5356
+ for (const rawTask of unfinished) {
5357
+ if (existingIds.has(rawTask.id)) continue
5358
+ const remainingBlockers = (rawTask.blockedBy || []).filter(bid => unfinishedIds.has(bid))
5359
+ const droppedDoneCount = (rawTask.blockedBy || []).length - remainingBlockers.length
5360
+ dest.tasks.push(normalizeTask({
5361
+ ...rawTask,
5362
+ status: rawTask.status === 'doing' ? 'todo' : rawTask.status,
5363
+ session: '',
5364
+ subagent: '',
5365
+ blockedBy: remainingBlockers,
5366
+ note: droppedDoneCount > 0
5367
+ ? [rawTask.note, `[接力已自动解除 ${droppedDoneCount} 项已完成前置依赖]`].filter(Boolean).join(' ')
5368
+ : rawTask.note,
5369
+ updatedAt: nowMs(),
5370
+ }))
5371
+ copiedTaskCount += 1
5372
+ }
5373
+
5374
+ if (srcBoard.cursor && (srcBoard.cursor.step || srcBoard.cursor.next || srcBoard.cursor.blocked)) {
5375
+ dest.cursor = {
5376
+ ...srcBoard.cursor,
5377
+ at: nowMs(),
5378
+ by: 'deploy',
5379
+ session: fromRoot,
5380
+ }
5381
+ }
5382
+
5383
+ // Merge local non-pinned bounds from source session board into destination session board
5384
+ const srcLocal = srcBoard.localBounds || { allowed: [], forbidden: [], notes: [] }
5385
+ const destBounds = normalizeBounds(dest.bounds)
5386
+ for (const col of BOUND_FIELDS) {
5387
+ const merged = new Set(destBounds[col] || [])
5388
+ for (const item of (srcLocal[col] || [])) merged.add(item)
5389
+ destBounds[col] = [...merged].slice(0, BOUND_CAP)
5390
+ }
5391
+ dest.bounds = destBounds
5392
+
5393
+ // Carry non-anchor handoff context notes selectively if target has room
5394
+ dest.handoff = {
5395
+ at: nowMs(),
5396
+ by: 'deploy',
5397
+ session: fromRoot,
5398
+ customText: '',
5399
+ pinned: false,
5400
+ pinnedAt: 0,
5401
+ pinnedBy: '',
5402
+ updatedAt: 0,
5403
+ source: 'auto',
5404
+ syncOnDigest: false,
5405
+ }
5406
+ pushLog(
5407
+ dest,
5408
+ `🚀 已系统级移交部署自会话 ${fromRoot.slice(0, 12)}:计划 ${copiedStepCount} 步、未完任务 ${copiedTaskCount} 项`,
5409
+ 'deploy',
5410
+ toRoot,
5411
+ )
5412
+ saveBoard(dest, destFile)
5413
+ })
5414
+
5415
+ const chiefRes = deployChiefWorkspaceState(makeChiefDeps(runtime), {
5416
+ fromRootId: fromRoot,
5417
+ toRootId: toRoot,
5418
+ fromTitle: sessionName(runtime, fromRoot) || fromRoot,
5419
+ customText: customNote,
5420
+ objective: srcBoard.objective || '',
5421
+ })
5422
+
5423
+ let archiveCopyRes = { ok: true, policy: 'none', copiedCount: 0 }
5424
+ const policy = ['none', 'mounted', 'drawer', 'all'].includes(archiveTransferPolicy)
5425
+ ? archiveTransferPolicy
5426
+ : 'none'
5427
+ if (policy !== 'none') {
5428
+ archiveCopyRes = copyArchivesBetweenSessionsOrCabinets({
5429
+ fromRootSessionId: fromRoot,
5430
+ toRootSessionId: toRoot,
5431
+ fromCwd: getSessionCwd(runtime, fromRoot),
5432
+ toCwd: getSessionCwd(runtime, toRoot),
5433
+ fromCabinetId: srcBoard.activeCabinetId || '',
5434
+ toCabinetId: toCabinetId || loadBoard(boardFileFor(toRoot)).activeCabinetId || '',
5435
+ policy,
5436
+ drawer: archiveDrawer,
5437
+ customSharedBoardFile: boardFile(),
5438
+ })
5439
+ }
5440
+
5441
+ return {
5442
+ ok: true,
5443
+ fromSessionId: fromRoot,
5444
+ toSessionId: toRoot,
5445
+ copiedTaskCount,
5446
+ copiedStepCount,
5447
+ chiefDeployed: chiefRes,
5448
+ archiveTransfer: archiveCopyRes,
5449
+ }
5450
+ }
5451
+
3970
5452
  export async function transferChief(runtime, args, sessionId) {
3971
5453
  const passed = args && typeof args === 'object' ? args : {}
3972
5454
  const target = typeof passed.target === 'string' ? passed.target.trim() : 'new'
3973
- // The packet is rendered from the sender's own board — the receiving board
3974
- // stays untouched (per-session isolation; the transfer text is what moves).
3975
- // Read through boardForSession so the packet still carries the operator's
3976
- // bounds and the machine objective when this session never wrote its own.
5455
+ const deployChief = asBool(passed.deployChief) !== false
5456
+ const archiveTransferPolicy = ['none', 'mounted', 'drawer', 'all'].includes(str(passed.archiveTransferPolicy, 'none'))
5457
+ ? str(passed.archiveTransferPolicy, 'none')
5458
+ : 'none'
5459
+ const archiveDrawer = str(passed.archiveDrawer, '')
5460
+ const toCabinetId = str(passed.toCabinetId, '')
5461
+ const customNote = str(passed.customNote, '')
5462
+
3977
5463
  const board = boardForSession(boardFileFor(sessionId))
3978
5464
  const rootSid = resolveRootSessionId(sessionId) || sessionId
3979
- const packet = renderHandoff(board, boundaries(runtime, sessionId), 5200, sessionId, {
3980
- teamTasks: fetchTeamTasks(runtime, sessionId ? { id: sessionId } : null),
3981
- takenOutArchives: rootSid ? getTakenOutArchivesForSession(rootSid, boardFile()) : [],
3982
- })
5465
+ const packet = resolveEffectiveHandoff(runtime, sessionId, board).text
3983
5466
  const by = typeof passed.by === 'string' && passed.by ? passed.by : 'user'
3984
5467
 
3985
5468
  if (!target || target === 'new' || target === 'latest') {
3986
5469
  if (!writePending({ at: nowMs(), by, session: sessionId, text: packet })) {
3987
5470
  return { ok: false, error: '待领取文件写入失败' }
3988
5471
  }
5472
+ if (deployChief && rootSid) {
5473
+ writePendingDeploy({
5474
+ at: nowMs(),
5475
+ by,
5476
+ fromSessionId: rootSid,
5477
+ archiveTransferPolicy,
5478
+ archiveDrawer,
5479
+ toCabinetId,
5480
+ customNote,
5481
+ })
5482
+ }
3989
5483
  const owner = boardFileFor(sessionId)
3990
5484
  withBoardLock(owner, () => {
3991
5485
  const next = loadBoard(owner)
3992
- pushLog(next, '交接单已投放:等下一个新会话领取', by, sessionId)
5486
+ pushLog(next, '交接单与参谋接力包已投放:等下一个新会话自动部署领取', by, sessionId)
3993
5487
  saveBoard(next, owner)
3994
5488
  })
3995
- return { ok: true, mode: 'pending', text: packet }
5489
+ return { ok: true, mode: 'pending', deployQueued: deployChief, text: packet }
3996
5490
  }
3997
5491
 
3998
- // One-click handover: open the successor conversation here instead of
3999
- // asking the operator to create one by hand and then find it in a picker.
4000
- // The packet is parked BEFORE the create call: if creation dies half way the
4001
- // next conversation still picks it up, and if it succeeds the
4002
- // agent/created listener races us for the file — whoever clears it wins,
4003
- // so the packet is never injected twice.
4004
5492
  if (target === 'create') {
4005
5493
  const controller = runtime.get('sessionController')
4006
5494
  const parked = writePending({ at: nowMs(), by, session: sessionId, text: packet })
4007
5495
  if (!parked) return { ok: false, error: '待领取文件写入失败' }
5496
+ if (deployChief && rootSid) {
5497
+ writePendingDeploy({
5498
+ at: nowMs(),
5499
+ by,
5500
+ fromSessionId: rootSid,
5501
+ archiveTransferPolicy,
5502
+ archiveDrawer,
5503
+ toCabinetId,
5504
+ customNote,
5505
+ })
5506
+ }
4008
5507
  if (!controller || typeof controller.create !== 'function') {
4009
5508
  return { ok: false, error: '这个部署没有 sessionController,交接单已放进待领取', mode: 'pending', text: packet }
4010
5509
  }
@@ -4021,16 +5520,28 @@ export async function transferChief(runtime, args, sessionId) {
4021
5520
  }
4022
5521
  const createdId = str(created && created.sessionId, '')
4023
5522
  if (!createdId) return { ok: false, error: '新会话没有返回 id', mode: 'pending', text: packet }
5523
+
5524
+ let deployResult = null
5525
+ if (deployChief && rootSid && readPendingDeploy()) {
5526
+ clearPendingDeploy()
5527
+ deployResult = deployStateToTargetChief(runtime, {
5528
+ fromSessionId: rootSid,
5529
+ toSessionId: createdId,
5530
+ archiveTransferPolicy,
5531
+ archiveDrawer,
5532
+ toCabinetId,
5533
+ customNote,
5534
+ })
5535
+ }
5536
+
4024
5537
  const owner = boardFileFor(sessionId)
4025
- // The listener got there first: the packet is gone and that conversation
4026
- // already carries it.
4027
5538
  if (!readPending()) {
4028
5539
  withBoardLock(owner, () => {
4029
5540
  const next = loadBoard(owner)
4030
- pushLog(next, '交接单已由新会话 ' + createdId.replace(/^session-/, '').slice(0, 8) + ' 领取', by, sessionId)
5541
+ pushLog(next, '交接单与参谋已由新会话 ' + createdId.replace(/^session-/, '').slice(0, 8) + ' 领取部署', by, sessionId)
4031
5542
  saveBoard(next, owner)
4032
5543
  })
4033
- return { ok: true, mode: 'created', sessionId: createdId, delivered: true, text: packet }
5544
+ return { ok: true, mode: 'created', sessionId: createdId, delivered: true, deployResult, text: packet }
4034
5545
  }
4035
5546
  const agents = runtime.get('agents')
4036
5547
  const fresh = agents && typeof agents.get === 'function' ? agents.get(createdId) : undefined
@@ -4040,20 +5551,38 @@ export async function transferChief(runtime, args, sessionId) {
4040
5551
  const next = loadBoard(owner)
4041
5552
  pushLog(
4042
5553
  next,
4043
- (delivered.ok ? '交接单已交给新会话 ' : '新会话已建(交接单仍待领取):') + createdId.replace(/^session-/, '').slice(0, 8),
5554
+ (delivered.ok ? '交接单与参谋已部署至新会话 ' : '新会话已建(交接单仍待领取):') + createdId.replace(/^session-/, '').slice(0, 8),
4044
5555
  by,
4045
5556
  sessionId,
4046
5557
  )
4047
5558
  saveBoard(next, owner)
4048
5559
  })
4049
- return { ok: delivered.ok, mode: delivered.ok ? 'created' : 'pending', sessionId: createdId, text: packet }
5560
+ return { ok: delivered.ok, mode: delivered.ok ? 'created' : 'pending', sessionId: createdId, deployResult, text: packet }
5561
+ }
5562
+
5563
+ let deployResult = null
5564
+ if (deployChief && rootSid && target !== rootSid) {
5565
+ deployResult = deployStateToTargetChief(runtime, {
5566
+ fromSessionId: rootSid,
5567
+ toSessionId: target,
5568
+ archiveTransferPolicy,
5569
+ archiveDrawer,
5570
+ toCabinetId,
5571
+ customNote,
5572
+ })
4050
5573
  }
4051
5574
 
4052
5575
  const agents = runtime.get('agents')
4053
5576
  const agent = agents && typeof agents.get === 'function' ? agents.get(target) : undefined
4054
5577
  if (!agent) {
4055
5578
  writePending({ at: nowMs(), by, session: sessionId, text: packet, failedTarget: target })
4056
- return { ok: false, error: '目标会话没有活的 agent:已改成待领取,下次新会话可取', mode: 'pending', text: packet }
5579
+ return {
5580
+ ok: Boolean(deployResult && deployResult.ok),
5581
+ error: deployResult && deployResult.ok ? '' : '目标会话没有活的 agent:已改成待领取,下次新会话可取',
5582
+ mode: 'pending',
5583
+ deployResult,
5584
+ text: packet,
5585
+ }
4057
5586
  }
4058
5587
  const delivered = await injectInto(agent, packet)
4059
5588
  const owner = boardFileFor(sessionId)
@@ -4061,7 +5590,7 @@ export async function transferChief(runtime, args, sessionId) {
4061
5590
  const next = loadBoard(owner)
4062
5591
  pushLog(
4063
5592
  next,
4064
- (delivered.ok ? '交接单已投放到会话 ' : '投放失败(' + delivered.error + '):') + String(target).replace(/^session-/, '').slice(0, 8),
5593
+ (delivered.ok ? '交接单与参谋已投放到会话 ' : '投放失败(' + delivered.error + '):') + String(target).replace(/^session-/, '').slice(0, 8),
4065
5594
  by,
4066
5595
  sessionId,
4067
5596
  )
@@ -4069,9 +5598,9 @@ export async function transferChief(runtime, args, sessionId) {
4069
5598
  })
4070
5599
  if (!delivered.ok) {
4071
5600
  writePending({ at: nowMs(), by, session: sessionId, text: packet, failedTarget: target })
4072
- return { ok: false, error: delivered.error, mode: 'pending', text: packet }
5601
+ return { ok: false, error: delivered.error, mode: 'pending', deployResult, text: packet }
4073
5602
  }
4074
- return { ok: true, mode: 'injected', target, text: packet }
5603
+ return { ok: true, mode: 'injected', target, deployResult, text: packet }
4075
5604
  }
4076
5605
 
4077
5606
  /* ------------------------------------------------------------------------ apply */
@@ -4158,6 +5687,55 @@ export function apply(ctx) {
4158
5687
  pushLog,
4159
5688
  })
4160
5689
 
5690
+ const isRootStopped = (rootKey, sid) => {
5691
+ try {
5692
+ const st = loadChiefState()
5693
+ const rk = resolveRootSessionId(rootKey || sid) || rootKey || sid
5694
+ const cfg = resolveWorkspaceConfig(st, rk)
5695
+ return Boolean(cfg.stopped || cfg.paceMode === 'stopped')
5696
+ } catch {
5697
+ return false
5698
+ }
5699
+ }
5700
+
5701
+ const autoContinue = createAutoContinueEngine({
5702
+ createMessage: (text, sourceKind) => buildMessageEnvelope(text, sourceKind),
5703
+ getAgent: async (sid) => {
5704
+ try {
5705
+ const agents = runtime && runtime.get ? runtime.get('agents') : null
5706
+ const direct = agents && typeof agents.get === 'function' ? agents.get(sid) : null
5707
+ if (direct) return direct
5708
+ const ctrl = runtime && runtime.get ? runtime.get('sessionController') : null
5709
+ if (ctrl && typeof ctrl.resolveAgent === 'function') {
5710
+ const resolved = await ctrl.resolveAgent(sid)
5711
+ if (resolved && resolved.agent) return resolved.agent
5712
+ }
5713
+ return null
5714
+ } catch {
5715
+ return null
5716
+ }
5717
+ },
5718
+ isChiefStopped: (rootId, sid) => isRootStopped(rootId, sid),
5719
+ resolveRootSessionId: (sid) => resolveRootSessionId(sid) || sid,
5720
+ onLog: (sid, msg) => {
5721
+ try {
5722
+ const rootId = resolveRootSessionId(sid) || sid
5723
+ if (!rootId) return
5724
+ const file = boardFileFor(rootId)
5725
+ withBoardLock(file, () => {
5726
+ const board = loadBoard(file)
5727
+ pushLog(board, `🔄 断线续跑:${msg}`, 'chief', sid)
5728
+ saveBoard(board, file)
5729
+ })
5730
+ } catch {}
5731
+ },
5732
+ })
5733
+ activeAutoContinue = autoContinue
5734
+ ctx.effect(() => () => {
5735
+ if (activeAutoContinue === autoContinue) activeAutoContinue = null
5736
+ autoContinue.dispose()
5737
+ }, 'dsh-chief: auto-continue cleanup')
5738
+
4161
5739
  ctx.inject(['llm'], llmCtx => {
4162
5740
  const ownLlm = (llmCtx && llmCtx.llm) || (llmCtx && llmCtx.get ? llmCtx.get('llm') : null)
4163
5741
  if (ownLlm) activeLlm = ownLlm
@@ -4211,11 +5789,20 @@ export function apply(ctx) {
4211
5789
  const board = boardForSession(boardFileFor(rootId))
4212
5790
  const agentIdentity = resolveAgentIdentity(runtime, curId, liveAgent)
4213
5791
  const subagents = getSubagentRoster(runtime, rootId, board)
4214
- const secState = loadChiefState()
4215
- const linkedPeersCount = Math.max(0, getLinkedCluster(secState, rootId || 'global').length - 1)
4216
- const takenOutArchives = rootId ? getTakenOutArchivesForSession(rootId, boardFile()) : []
5792
+ const linked = linkedPeersForSession(runtime, rootId || 'global')
5793
+ const archCtx = collectDigestArchiveContext(runtime, rootId, board.activeCabinetId)
4217
5794
  if (rootId) refreshSubagentTree(runtime, rootId, board).catch(() => {})
4218
- return renderDigest(board, { teamTasks, agentIdentity, subagents, linkedPeersCount, takenOutArchives })
5795
+ return renderDigest(board, {
5796
+ teamTasks,
5797
+ agentIdentity,
5798
+ subagents,
5799
+ linkedPeersCount: linked.linkedPeersCount,
5800
+ linkedPeersProgress: linked.linkedPeersProgress,
5801
+ takenOutArchives: archCtx.takenOutArchives,
5802
+ sessionArchiveBriefs: archCtx.sessionArchiveBriefs,
5803
+ smartCompactActive: archCtx.smartCompactActive,
5804
+ chiefPermissionMode: archCtx.chiefPermissionMode,
5805
+ })
4219
5806
  },
4220
5807
  }), 'dsh-chief: prompt digest')
4221
5808
  })
@@ -4235,19 +5822,32 @@ export function apply(ctx) {
4235
5822
  } catch {}
4236
5823
  }), 'dsh-chief: plan & subagent mirror')
4237
5824
 
4238
- // 2b) A transferred packet waits for exactly one new Session.
5825
+ // 2b) A transferred packet + staged Chief deployment waits for one new Session.
4239
5826
  ctx.effect(() => ctx.on('agent/created', async payload => {
4240
5827
  try {
4241
5828
  const agent = payload && payload.agent
4242
5829
  if (!agent || !agent.id) return
5830
+ const id = String(agent.id)
5831
+
5832
+ const pendingDeploy = readPendingDeploy()
5833
+ if (pendingDeploy && pendingDeploy.fromSessionId && pendingDeploy.fromSessionId !== id) {
5834
+ clearPendingDeploy()
5835
+ try {
5836
+ deployStateToTargetChief(runtime, {
5837
+ fromSessionId: pendingDeploy.fromSessionId,
5838
+ toSessionId: id,
5839
+ archiveTransferPolicy: pendingDeploy.archiveTransferPolicy || 'none',
5840
+ archiveDrawer: pendingDeploy.archiveDrawer || '',
5841
+ toCabinetId: pendingDeploy.toCabinetId || '',
5842
+ customNote: pendingDeploy.customNote || '',
5843
+ })
5844
+ } catch {}
5845
+ }
5846
+
4243
5847
  const pending = readPending()
4244
5848
  if (!pending) return
4245
5849
  const delivered = await injectInto(agent, pending.text)
4246
5850
  if (delivered.ok) clearPending()
4247
- // The claim is logged on the NEW session's own board, not the sender's.
4248
- // A brand-new Session's turn-stopping write can land while this runs, so
4249
- // the claim re-reads under the lock and keeps whatever else got there.
4250
- const id = String(agent.id)
4251
5851
  const file = boardFileFor(id)
4252
5852
  const short = id.replace(/^session-/, '').slice(0, 8)
4253
5853
  withBoardLock(file, () => {
@@ -4278,24 +5878,42 @@ export function apply(ctx) {
4278
5878
  } catch {}
4279
5879
  }), 'dsh-chief: deliver pending transfer')
4280
5880
 
4281
- // 2c) Incremental record of what each turn actually did: which turns called a
4282
- // tool at all, and which of them moved the plan. The idle guard reads both
4283
- // first and falls back to the Session log, so a dropped event cannot make it
4284
- // cry wolf about work that did happen — and, more importantly, a turn that ran
4285
- // commands without touching the plan is recorded as exactly that.
5881
+ // 2c) Incremental record of what each turn actually did + Auto-Continue detection
5882
+ // on interruptions / transient failures / empty outputs (unless Chief is stopped).
4286
5883
  ctx.effect(() => ctx.on('session/event', (session, event) => {
4287
5884
  try {
4288
- if (!event || event.type !== 'tool/call') return
4289
- if (!event.data || !session || !session.id) return
5885
+ if (!event || !session || !session.id) return
4290
5886
  const id = String(session.id)
4291
- const turn = event.data.turn
4292
- noteToolCall(id, turn)
4293
- if (isPlanWrite(event.data.name, event.data.arguments)) notePlanWrite(id, turn)
4294
- // The loop shape needs the call itself, not just the turn: same tool with
4295
- // the same arguments N times is the tell that nothing is moving.
4296
- noteCallTrail(id, event.data.name, event.data.arguments)
5887
+ if (event.type === 'tool/call' && event.data) {
5888
+ const turn = event.data.turn
5889
+ noteToolCall(id, turn)
5890
+ if (isPlanWrite(event.data.name, event.data.arguments)) notePlanWrite(id, turn)
5891
+ noteCallTrail(id, event.data.name, event.data.arguments)
5892
+ }
5893
+ autoContinue.onSessionEvent(session, event)
5894
+
5895
+ if (event.type === 'turn/end') {
5896
+ const rawReason = event.data && event.data.reason
5897
+ const reason = String(rawReason && typeof rawReason === 'object' ? (rawReason.kind || '') : (rawReason || '')).toLowerCase()
5898
+ const nestedReason = String(rawReason && typeof rawReason === 'object' && rawReason.reason && typeof rawReason.reason === 'object' ? (rawReason.reason.kind || '') : '').toLowerCase()
5899
+ const isStoppedByUserOrPolicy = reason === 'aborted' || reason === 'blocked' || nestedReason === 'aborted' || nestedReason === 'blocked'
5900
+ const turnNum = Number(event.data && event.data.turn)
5901
+ const steerKey = `${id}:${turnNum}`
5902
+ const steeredAt = autoSteeredTurns.get(steerKey) || 0
5903
+ if (steeredAt) autoSteeredTurns.delete(steerKey)
5904
+ if (!isStoppedByUserOrPolicy && !(steeredAt && Date.now() - steeredAt < 30_000)) {
5905
+ const rootId = resolveRootSessionId(id) || id
5906
+ if (!isRootStopped(rootId, id)) {
5907
+ const agents = runtime && runtime.get ? runtime.get('agents') : null
5908
+ const liveAgent = agents && typeof agents.get === 'function' ? agents.get(id) : null
5909
+ if (liveAgent) {
5910
+ scheduleChiefTurnReview(makeChiefDeps(runtime), { agent: liveAgent, sessionId: id, turn: event.data && event.data.turn })
5911
+ }
5912
+ }
5913
+ }
5914
+ }
4297
5915
  } catch {}
4298
- }), 'dsh-chief: tool call ledger')
5916
+ }), 'dsh-chief: tool call ledger & auto-continue')
4299
5917
 
4300
5918
  // 3) One heartbeat per finished turn: which Sessions are still warm — and the
4301
5919
  // idle guard: a turn that closes with a short answer, no tool call, and open
@@ -4321,6 +5939,8 @@ export function apply(ctx) {
4321
5939
  const entry = board.sessions[id] || { lastSeen: 0, cwd: '', turns: 0 }
4322
5940
  entry.lastSeen = nowMs()
4323
5941
  entry.turns = (entry.turns || 0) + 1
5942
+ const resolvedCwd = getSessionCwd(runtime, id)
5943
+ if (resolvedCwd) entry.cwd = resolvedCwd
4324
5944
  board.sessions[id] = entry
4325
5945
  const ids = Object.keys(board.sessions)
4326
5946
  if (ids.length > 40) {
@@ -4371,7 +5991,16 @@ export function apply(ctx) {
4371
5991
  reconcileTaskDependencies(board, identity.self, id)
4372
5992
  }
4373
5993
  saveBoard(board, file)
4374
- scheduleChiefTurnReview(makeChiefDeps(runtime), { agent, sessionId: id, turn })
5994
+ const childRoot = resolveRootSessionId(id, agent) || id
5995
+ if (!isRootStopped(childRoot, id)) {
5996
+ scheduleChiefTurnReview(makeChiefDeps(runtime), { agent, sessionId: id, turn })
5997
+ }
5998
+ return
5999
+ }
6000
+
6001
+ const rootId = resolveRootSessionId(id, agent) || id
6002
+ if (isRootStopped(rootId, id)) {
6003
+ saveBoard(board, file)
4375
6004
  return
4376
6005
  }
4377
6006
 
@@ -4387,8 +6016,9 @@ export function apply(ctx) {
4387
6016
  }
4388
6017
 
4389
6018
  if (typeof agent.steer !== 'function') {
4390
- pushLog(board, '空转拦截:这个 agent 没有 steer 方法,无法补一步', 'guard', id)
6019
+ pushLog(board, '空转拦截:这个 agent 没有 steer 方法,转由断线续跑模块跟进', 'guard', id)
4391
6020
  saveBoard(board, file)
6021
+ autoContinue.notifyIdleOrInterrupt(id, { kind: 'idle-stall', reason: verdict.reason || '' })
4392
6022
  return
4393
6023
  }
4394
6024
 
@@ -4396,6 +6026,11 @@ export function apply(ctx) {
4396
6026
  // observe a board that claims an intervention that never happened.
4397
6027
  const notice = buildNotice({ ...verdict, board })
4398
6028
  agent.steer(notice)
6029
+ autoSteeredTurns.set(`${id}:${turn}`, Date.now())
6030
+ if (autoSteeredTurns.size > 120) {
6031
+ const oldest = autoSteeredTurns.keys().next().value
6032
+ if (oldest) autoSteeredTurns.delete(oldest)
6033
+ }
4399
6034
  noteIntervention(id, turn)
4400
6035
  // Clear the trail only once the steer landed: a loop that survived a
4401
6036
  // failed steer deserves the next nudge, not a silent reset.
@@ -4410,10 +6045,7 @@ export function apply(ctx) {
4410
6045
  // tells the model to wrap up; this packet is what the next one reads.
4411
6046
  if (remainingInterventions(id, settings) === 0) {
4412
6047
  try {
4413
- const rootForHandoff = resolveRootSessionId(id) || id
4414
- const packet = renderHandoff(board, boundaries(runtime, id), 5200, id, {
4415
- takenOutArchives: rootForHandoff ? getTakenOutArchivesForSession(rootForHandoff, boardFile()) : [],
4416
- })
6048
+ const packet = resolveEffectiveHandoff(runtime, id, board).text
4417
6049
  const pendingFile_ = pendingFile()
4418
6050
  fs.writeFileSync(pendingFile_, JSON.stringify({ text: packet, at: nowMs(), from: id }))
4419
6051
  pushLog(board, '上下文压力:干预计数耗尽,交接单已自动生成并放入待领取', 'handoff', id)
@@ -4450,4 +6082,14 @@ export function apply(ctx) {
4450
6082
  toolCtx.effect(() => toolCtx.tools.register(tool), 'dsh-chief: tool ' + tool.name)
4451
6083
  }
4452
6084
  })
6085
+
6086
+ // Runtime capability probe for DSH >= 0.2.2-rc.2 named subagent APIs
6087
+ ctx.inject(['subagents'], () => {
6088
+ const compat = probeSubagentSupport(runtime)
6089
+ if (compat.present && !compat.namedSubagentsSupported) {
6090
+ try {
6091
+ console.warn('[dsh-chief] ' + compat.warning)
6092
+ } catch {}
6093
+ }
6094
+ })
4453
6095
  }