dsh-chief 1.1.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
@@ -37,46 +37,62 @@ import {
37
37
  resolveWorkspaceConfig,
38
38
  getLinkedCluster,
39
39
  setPeerLink,
40
+ collectClusterPeerProgress,
40
41
  invalidateChiefModelCatalog,
41
42
  listChiefModels,
42
43
  listPeerDirectory,
44
+ buildMessageEnvelope,
43
45
  deliverCrossMessage,
44
46
  consumePreStepDelta,
45
47
  getChiefView,
48
+ recommendAndSetCompactThreshold,
46
49
  askOrCommandChief,
47
50
  consolidateBoundsWithChief,
48
51
  organizeArchivesWithChief,
49
52
  harvestTurnDetailsToArchive,
50
53
  precipitateExperienceWithChief,
54
+ distillSessionArchivesToGlobal,
51
55
  deployChiefWorkspaceState,
52
56
  updateWorkspaceFlippedIds,
57
+ requestSmartCompactFromLead,
53
58
  maybeRunPreCompaction,
54
59
  runTurnReview,
55
60
  proposeBoundToChief,
56
61
  scheduleChiefTurnReview,
57
62
  handleSuggestionDecision,
58
63
  updateChiefConfig,
64
+ suggestCoreObjectiveWithChief,
65
+ relayArchivesWithChief,
59
66
  mutateChiefFact,
60
67
  readMailboxForAgent,
61
68
  } from './chief.js'
69
+ import { createAutoContinueEngine } from './auto-continue.js'
62
70
  import {
63
71
  bootstrapArchivesFromSharedBoard,
64
72
  resolveProjectKey,
65
73
  listProjectCabinets,
66
74
  getArchiveMeta,
75
+ getThreeTierArchiveCounts,
67
76
  listArchiveHeaders,
68
77
  getArchiveDetail,
69
78
  searchArchives,
70
79
  mutateArchive,
71
80
  copyArchivesBetweenSessionsOrCabinets,
72
81
  getTakenOutArchivesForSession,
82
+ getTakenOutGlobalForSession,
73
83
  getFlippedOutPrecipitatedForSession,
74
84
  listPrecipitatedHeaders,
75
85
  getPrecipitatedDetail,
76
86
  mutatePrecipitated,
87
+ copyPrecipitatedToVault,
77
88
  } from './archives.js'
89
+ import {
90
+ DEFAULT_CHIEF_PERMISSION_MODE,
91
+ normalizePermissionMode,
92
+ } from './chief-executor.js'
78
93
 
79
94
  const API = '/api/dsh-chief'
95
+ const BACKEND_BUILD = '1.2.0-r7'
80
96
  const BOARD_VERSION = 1
81
97
  const LOG_CAP = 60
82
98
  const BODY_LIMIT = 24 * 1024 * 1024
@@ -195,6 +211,8 @@ function boardFile() {
195
211
  /** Active runtime reference for resolving subagent tree lineage and live status. */
196
212
  let activeRuntime = null
197
213
  let activeLlm = null
214
+ let activeAutoContinue = null
215
+ const autoSteeredTurns = new Map()
198
216
  const subagentRootMap = new Map()
199
217
  const subagentTreeCache = new Map()
200
218
 
@@ -416,7 +434,18 @@ function emptyBoard() {
416
434
  // is, and what is blocking it. Long tasks die from losing that one line, so
417
435
  // it is a first-class field and the digest leads with it.
418
436
  cursor: { at: 0, step: '', next: '', blocked: '', by: '', session: '' },
419
- 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
+ },
420
449
  plan: [],
421
450
  tasks: [],
422
451
  notes: [],
@@ -624,6 +653,13 @@ function normalizeNote(raw) {
624
653
 
625
654
  const BOUND_FIELDS = ['allowed', 'forbidden', 'notes']
626
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
+
627
663
  // Hard cap on one bounds column. Two different jobs read this number: loading
628
664
  // clamps to it (an old or hand-edited board file must never be able to throw
629
665
  // while being read), and every write path checks it BEFORE storing anything.
@@ -733,6 +769,14 @@ function normalizeBoard(raw) {
733
769
  at: board.handoff && typeof board.handoff.at === 'number' ? board.handoff.at : 0,
734
770
  by: str(board.handoff && board.handoff.by, ''),
735
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,
736
780
  },
737
781
  cursor: {
738
782
  at: board.cursor && typeof board.cursor.at === 'number' ? board.cursor.at : 0,
@@ -941,6 +985,19 @@ function forcesShared(action, args) {
941
985
  return action === 'note.write' && asBool(args.pinned) === true
942
986
  }
943
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
+
944
1001
  function runAction(input) {
945
1002
  const args = input && typeof input === 'object' ? input : {}
946
1003
  const action = str(args.action, 'snapshot')
@@ -972,12 +1029,19 @@ function runActionUnlocked(input) {
972
1029
  const shared = forcesShared(action, args)
973
1030
  const file = shared ? boardFile() : boardFileFor(session)
974
1031
 
975
- // 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!).
976
1033
  if (action === 'archive.search') {
977
1034
  const q = str(args.query !== undefined ? args.query : (args.question !== undefined ? args.question : args.text), '')
978
1035
  const folder = str(args.folder, '')
979
1036
  const rootSid = resolveRootSessionId(session) || session
980
- const res = searchArchives(q, { folder, limit: 10 }, archiveTarget(activeRuntime, rootSid, str(args.cabinetId, '')))
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' }))
981
1045
  return {
982
1046
  ok: true,
983
1047
  archiveSearch: res,
@@ -989,7 +1053,8 @@ function runActionUnlocked(input) {
989
1053
  const target = str(args.archiveId !== undefined ? args.archiveId : (args.id !== undefined ? args.id : args.title), '').trim()
990
1054
  if (!target) return { ok: false, error: 'archive.read requires archiveId, id, or title' }
991
1055
  const rootSid = resolveRootSessionId(session) || session
992
- const res = getArchiveDetail(target, rootSid, archiveTarget(activeRuntime, rootSid, str(args.cabinetId, '')))
1056
+ if (!rootSid) return { ok: false, error: '当前未绑定对话会话,无法读取本会话档案柜' }
1057
+ const res = getArchiveDetail(target, rootSid, archiveTarget(activeRuntime, rootSid, { cabinetId: str(args.cabinetId, ''), vaultScope: 'session' }))
993
1058
  if (!res.ok) return { ok: false, error: res.error }
994
1059
  return {
995
1060
  ok: true,
@@ -1000,8 +1065,10 @@ function runActionUnlocked(input) {
1000
1065
 
1001
1066
  if (action === 'archive.save') {
1002
1067
  const rootSid = resolveRootSessionId(session) || session
1068
+ if (!rootSid) return { ok: false, error: '当前未绑定对话会话,无法保存到本会话档案柜' }
1003
1069
  const res = mutateArchive({
1004
1070
  op: 'save',
1071
+ vaultScope: 'session',
1005
1072
  archiveId: str(args.archiveId !== undefined ? args.archiveId : args.id, ''),
1006
1073
  title: str(args.title, ''),
1007
1074
  body: typeof args.body === 'string' ? args.body : undefined,
@@ -1012,7 +1079,7 @@ function runActionUnlocked(input) {
1012
1079
  points: Array.isArray(args.points) ? args.points : undefined,
1013
1080
  by,
1014
1081
  rootSessionId: rootSid,
1015
- }, archiveTarget(activeRuntime, rootSid, str(args.cabinetId, '')))
1082
+ }, archiveTarget(activeRuntime, rootSid, { cabinetId: str(args.cabinetId, ''), vaultScope: 'session' }))
1016
1083
  if (!res.ok) return { ok: false, error: res.error }
1017
1084
  if (session) {
1018
1085
  withBoardLock(file, () => {
@@ -1041,6 +1108,29 @@ function runActionUnlocked(input) {
1041
1108
 
1042
1109
  const board = loadBoard(file)
1043
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
+
1044
1134
  if (action === 'task.add') {
1045
1135
  const title = str(args.title, '').trim()
1046
1136
  if (!title) return { ok: false, error: 'title required' }
@@ -1073,9 +1163,15 @@ function runActionUnlocked(input) {
1073
1163
  if (action === 'graph.plan' || action === 'task.batch') {
1074
1164
  const clips = []
1075
1165
  if (typeof args.objective === 'string' && args.objective.trim()) {
1076
- board.objective = clipInto(clips, 'objective', args.objective.trim(), CAP_OBJECTIVE)
1077
- board.objectiveBy = session
1078
- 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
+ }
1079
1175
  }
1080
1176
  const rawList = Array.isArray(args.tasks) ? args.tasks : (Array.isArray(args.nodes) ? args.nodes : [])
1081
1177
  if (!rawList.length) return { ok: false, error: 'graph.plan requires a non-empty tasks array' }
@@ -1265,17 +1361,23 @@ function runActionUnlocked(input) {
1265
1361
  if (action === 'plan.set') {
1266
1362
  const clips = []
1267
1363
  if (typeof args.objective === 'string') {
1268
- board.objective = clipInto(clips, 'objective', args.objective, CAP_OBJECTIVE)
1269
- // Whoever writes the objective owns it. Leaving the previous owner in
1270
- // place made the panel header name the Session that set the *old* text,
1271
- // so a fresh save looked like it came from somebody else.
1272
- board.objectiveBy = session
1273
- board.objectiveAt = nowMs()
1274
- // objective.set logged this write and plan.set did not, so retargeting a
1275
- // board through plan.set left no trace in the log: the objective page
1276
- // said the goal had changed and the log page said nothing had happened.
1277
- // One action, two entry points, one line either way.
1278
- 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
+ }
1279
1381
  }
1280
1382
  const steps = asList(args.steps)
1281
1383
  if (steps) {
@@ -1407,6 +1509,13 @@ function runActionUnlocked(input) {
1407
1509
  }
1408
1510
 
1409
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
+ }
1410
1519
  const objective = str(args.objective, '').trim()
1411
1520
  if (!objective) return { ok: false, error: 'objective required' }
1412
1521
  const clips = []
@@ -1450,17 +1559,18 @@ function runActionUnlocked(input) {
1450
1559
  // Naming the column makes "this list is now empty" and "I did not touch
1451
1560
  // that list" two different sentences.
1452
1561
  const items = asList(args.items)
1453
- if (BOUND_FIELDS.indexOf(str(args.field, '')) >= 0 && items) {
1562
+ const explicitCol = normalizeBoundFieldName(args.field)
1563
+ if (explicitCol && items) {
1454
1564
  if (overCap(items)) return { ok: false, error: tooLongNote(items.length) }
1455
- current[str(args.field, '')] = normalizeList(items)
1565
+ current[explicitCol] = normalizeList(items)
1456
1566
  board.bounds = current
1457
- 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)
1458
1568
  return { ok: true, bounds: current, board: saveBoard(board, file) }
1459
1569
  }
1460
1570
  // The whole-table form checks every list it was handed before touching
1461
1571
  // any of them: a refusal must leave the two valid columns alone as well,
1462
1572
  // otherwise the error message and the board disagree about what happened.
1463
- 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) }
1464
1574
  const tooLong = BOUND_FIELDS.filter(name => overCap(given[name]))
1465
1575
  if (tooLong.length) {
1466
1576
  return {
@@ -1473,14 +1583,14 @@ function runActionUnlocked(input) {
1473
1583
  if (given.forbidden) current.forbidden = normalizeList(given.forbidden)
1474
1584
  if (given.notes) current.notes = normalizeList(given.notes)
1475
1585
  board.bounds = current
1476
- 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)
1477
1587
  return { ok: true, bounds: current, board: saveBoard(board, file) }
1478
1588
  }
1479
1589
 
1480
1590
  if (action === 'bounds.add' || action === 'bounds.pin' || action === 'bounds.remove' || action === 'bounds.edit' || action === 'bounds.consolidate') {
1481
- const col = str(args.field, '').trim()
1482
- if (!BOUND_FIELDS.includes(col)) {
1483
- 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 (注意)' }
1484
1594
  }
1485
1595
  const sharedFile = boardFile()
1486
1596
  const isSameFile = file === sharedFile
@@ -1758,11 +1868,118 @@ function runActionUnlocked(input) {
1758
1868
  }
1759
1869
 
1760
1870
  if (action === 'handoff.mark') {
1761
- board.handoff = { at: nowMs(), by, session }
1871
+ const prev = board.handoff || {}
1872
+ board.handoff = { ...prev, at: nowMs(), by, session }
1762
1873
  pushLog(board, '生成并交接给参谋看板:交接单已更新', by, session)
1763
1874
  return { ok: true, handoff: board.handoff, board: saveBoard(board, file) }
1764
1875
  }
1765
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
+
1766
1983
  if (action === 'log.add' || action === 'note.add') {
1767
1984
  // pushLog appends whatever it is given, but the very next load clamps one
1768
1985
  // entry to 400 characters — so a long handoff line was stored, then silently
@@ -2382,7 +2599,11 @@ function buildTaskDispatchBrief(board, task, extraPrompt) {
2382
2599
  return lines.join('\n')
2383
2600
  }
2384
2601
 
2385
- function getSessionCwd(runtime, sessionId) {
2602
+ function isInternalProfileCwd(dirPath) {
2603
+ return /[\\/]\.dsh[\\/]+profiles(?:$|[\\/])/i.test(String(dirPath || '').trim())
2604
+ }
2605
+
2606
+ export function getSessionCwd(runtime, sessionId) {
2386
2607
  const sid = String(sessionId || '').trim()
2387
2608
  const rootId = sid ? (resolveRootSessionId(sid) || sid) : ''
2388
2609
  const rt = runtime || activeRuntime
@@ -2404,46 +2625,474 @@ function getSessionCwd(runtime, sessionId) {
2404
2625
  try {
2405
2626
  const b = loadBoard(boardFileFor(probeId))
2406
2627
  const row = b && b.sessions && (b.sessions[probeId] || b.sessions[sid])
2407
- if (row && typeof row.cwd === 'string' && row.cwd.trim()) return row.cwd.trim()
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()
2408
2651
  } catch {}
2409
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 {}
2410
2675
  return process.cwd()
2411
2676
  }
2412
2677
 
2413
- function archiveTarget(runtime, sessionId, explicitCabinetId = '') {
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'
2414
2697
  const sid = String(sessionId || '').trim()
2415
- const rootSid = sid ? (resolveRootSessionId(sid) || sid) : ''
2416
- let cabinetId = typeof explicitCabinetId === 'string' ? explicitCabinetId.trim() : ''
2417
- if (!cabinetId && rootSid) {
2698
+ const rootSid = resolveBoundRootSid(sid)
2699
+ let cabinetId = vaultScope !== 'global' && typeof opts.cabinetId === 'string' ? opts.cabinetId.trim() : ''
2700
+ if (vaultScope !== 'global' && !cabinetId && rootSid) {
2418
2701
  try {
2419
2702
  cabinetId = loadBoard(boardFileFor(rootSid)).activeCabinetId || ''
2420
2703
  } catch {}
2421
2704
  }
2422
2705
  return {
2423
2706
  customSharedBoardFile: boardFile(),
2424
- cwd: getSessionCwd(runtime, rootSid || sid),
2425
- ...(cabinetId ? { cabinetId } : {}),
2707
+ cwd: getSessionCwd(runtime, rootSid || (sid !== 'global' ? sid : '')),
2708
+ vaultScope,
2709
+ ...(vaultScope !== 'global' && rootSid ? { rootSessionId: rootSid } : {}),
2710
+ ...(vaultScope !== 'global' && cabinetId ? { cabinetId } : {}),
2426
2711
  }
2427
2712
  }
2428
2713
 
2429
- /** Combine working-cabinet mounted items with explicitly flipped precipitated entries (0 disk reads when empty!). */
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!). */
2430
2955
  function collectTakenOutAndFlipped(runtime, rootId, cabinetId = '') {
2431
2956
  if (!rootId) return []
2432
- const targetOpt = archiveTarget(runtime, rootId, cabinetId)
2433
- const working = getTakenOutArchivesForSession(rootId, targetOpt)
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
+ }))
2434
2971
  const state = loadChiefState()
2435
2972
  const ws = state && state.workspaces && state.workspaces[rootId]
2436
2973
  const flippedIds = ws && Array.isArray(ws.flippedPrecipitatedIds) ? ws.flippedPrecipitatedIds : []
2437
- if (!flippedIds.length) return working
2438
- const projectKey = resolveProjectKey(targetOpt.cwd)
2439
- const flippedEntries = getFlippedOutPrecipitatedForSession(projectKey, rootId, true, targetOpt)
2440
- const mapped = flippedEntries.map(e => ({
2441
- ...e,
2442
- folder: e.category || 'contracts',
2443
- folderLabel: `沉淀冷库/${e.category || '经验'}`,
2444
- title: `[已翻出沉淀] ${e.title}`,
2445
- }))
2446
- return [...working, ...mapped]
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')
2447
3096
  }
2448
3097
 
2449
3098
  function makeChiefDeps(runtime) {
@@ -2459,44 +3108,24 @@ function makeChiefDeps(runtime) {
2459
3108
  return (ag && ag.status) || 'idle'
2460
3109
  },
2461
3110
  async measureSessionTokens(sid, agentArg) {
2462
- const agents = rt ? rt.get('agents') : null
2463
- const ag = agentArg || (agents && typeof agents.get === 'function' ? agents.get(sid) : null)
2464
- if (!ag || !ag.session) return null
2465
- try {
2466
- let totalTokens = 0
2467
- let seq = 0
2468
- let contextWindow = 128_000
2469
- if (typeof ag.session.ownEvents === 'function') {
2470
- const events = ag.session.ownEvents() || []
2471
- seq = events.length
2472
- for (let i = events.length - 1; i >= 0; i -= 1) {
2473
- const ev = events[i]
2474
- const usage = ev && (ev.usage || (ev.message && ev.message.usage) || (ev.data && ev.data.usage))
2475
- if (usage && typeof usage === 'object') {
2476
- const calc = (Number(usage.inputTokens) || 0)
2477
- + (Number(usage.cacheReadTokens) || 0)
2478
- + (Number(usage.outputTokens) || 0)
2479
- totalTokens = Number(usage.totalTokens) || calc
2480
- if (Number(usage.contextWindow) > 0) contextWindow = Number(usage.contextWindow)
2481
- if (totalTokens > 0) break
2482
- }
2483
- }
2484
- }
2485
- return totalTokens > 0 ? { totalTokens, contextWindow, seq } : null
2486
- } catch {
2487
- return null
2488
- }
3111
+ return getSessionContextBreakdown(rt, sid, agentArg)
3112
+ },
3113
+ composeHandoffFromNarrative(opts) {
3114
+ return composeHandoffFromNarrative(opts)
2489
3115
  },
2490
3116
  async compactSessionNow(sid, cmdId) {
2491
- const agents = rt ? rt.get('agents') : null
2492
- const ag = agents && typeof agents.get === 'function' ? agents.get(sid) : null
2493
- if (!ag) throw new Error('target session agent not found for compaction')
2494
- if (ag.status === 'running') throw new Error('agent is busy running; refusing compaction')
2495
- const compSvc = rt ? rt.get('compaction') : null
2496
- if (!compSvc || typeof compSvc.compactNow !== 'function') {
2497
- throw new Error('dsh-compaction service unavailable')
2498
- }
2499
- return compSvc.compactNow(ag, AbortSignal.timeout(60_000), cmdId || ('chief-compact-' + Date.now().toString(36)))
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
+ })
2500
3129
  },
2501
3130
  resolveRootSessionId,
2502
3131
  resolveAgentIdentity,
@@ -2518,6 +3147,15 @@ function makeChiefDeps(runtime) {
2518
3147
  saveBoard(board, file)
2519
3148
  })
2520
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
+ },
2521
3159
  }
2522
3160
  }
2523
3161
 
@@ -2598,7 +3236,7 @@ async function executeSubagentAction(runtime, input, callerAgent, signal) {
2598
3236
  dispatchMode = 'session-inject'
2599
3237
  }
2600
3238
  } else if (subagents && liveCaller) {
2601
- // Case 2: Use DSH native subagent service (requires post-rc.2 named subagent API)
3239
+ // Case 2: Use DSH native subagent service (continue existing subagent or spawn/fork a new one)
2602
3240
  if (typeof subagents.resolveName !== 'function' || typeof subagents.startActivation !== 'function') {
2603
3241
  return {
2604
3242
  ok: false,
@@ -2856,6 +3494,13 @@ function routeTable(runtime) {
2856
3494
  }
2857
3495
  const rootWs = secState.workspaces && secState.workspaces[rootSid]
2858
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
+ }
2859
3504
  const hostCompat = probeSubagentSupport(runtime)
2860
3505
  sendJson(res, 200, {
2861
3506
  ok: true,
@@ -2866,11 +3511,15 @@ function routeTable(runtime) {
2866
3511
  boundaries: boundaries(runtime, sessionId),
2867
3512
  hostCompat,
2868
3513
  chiefMeta: {
3514
+ backendBuild: BACKEND_BUILD,
3515
+ hostCompat,
2869
3516
  paceMode: effCfg.paceMode || 'manual',
3517
+ stopped: Boolean(effCfg.stopped || effCfg.paceMode === 'stopped'),
3518
+ permissionMode: effCfg.permissionMode || 'danger-full-access',
2870
3519
  autoPilot: Boolean(effCfg.autoPilot),
2871
3520
  tacticalModes,
2872
3521
  runtimeGuard: (rootWs && rootWs.runtimeGuard) || {},
2873
- flippedCount: (rootWs && Array.isArray(rootWs.flippedPrecipitatedIds)) ? rootWs.flippedPrecipitatedIds.length : 0,
3522
+ flippedCount: flippedIds.length,
2874
3523
  modelRef: pinnedModelRef,
2875
3524
  followModelRef,
2876
3525
  resolvedModelRef: pinnedModelRef || followModelRef || '',
@@ -2878,9 +3527,9 @@ function routeTable(runtime) {
2878
3527
  factsCount,
2879
3528
  mailboxCount,
2880
3529
  linkedPeersCount: Math.max(0, cluster.length - 1),
2881
- hostCompat,
3530
+ contextUsage: sessionId ? getSessionContextBreakdown(runtime, sessionId) : null,
2882
3531
  },
2883
- archiveMeta: getArchiveMeta(rootSid, archiveTarget(runtime, rootSid, board.activeCabinetId)),
3532
+ archiveMeta,
2884
3533
  })
2885
3534
  } catch (error) {
2886
3535
  sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
@@ -2901,13 +3550,20 @@ function routeTable(runtime) {
2901
3550
  const subagents = sessionId ? await refreshSubagentTree(runtime, sessionId, fullBoard) : []
2902
3551
  const agentIdentity = sessionId ? resolveAgentIdentity(runtime, sessionId) : null
2903
3552
  const rootSid = resolveRootSessionId(sessionId) || sessionId
3553
+ const linked = linkedPeersForSession(runtime, rootSid)
3554
+ const archCtx = collectDigestArchiveContext(runtime, rootSid, fullBoard.activeCabinetId)
2904
3555
  sendJson(res, 200, {
2905
3556
  ok: true,
2906
3557
  digest: renderDigest(fullBoard, {
2907
3558
  subagents,
2908
3559
  agentIdentity,
2909
3560
  teamTasks: sessionId ? fetchTeamTasks(runtime, { id: sessionId }) : undefined,
2910
- takenOutArchives: rootSid ? collectTakenOutAndFlipped(runtime, rootSid, fullBoard.activeCabinetId) : [],
3561
+ takenOutArchives: archCtx.takenOutArchives,
3562
+ sessionArchiveBriefs: archCtx.sessionArchiveBriefs,
3563
+ smartCompactActive: archCtx.smartCompactActive,
3564
+ chiefPermissionMode: archCtx.chiefPermissionMode,
3565
+ linkedPeersCount: linked.linkedPeersCount,
3566
+ linkedPeersProgress: linked.linkedPeersProgress,
2911
3567
  }),
2912
3568
  sessions: board.sessions || {},
2913
3569
  updatedAt: board.updatedAt,
@@ -3007,14 +3663,22 @@ function routeTable(runtime) {
3007
3663
  } catch {}
3008
3664
  const board = sessionId ? boardForSession(boardFileFor(sessionId)) : emptyBoard()
3009
3665
  const pending = readPending()
3010
- const rootSid = resolveRootSessionId(sessionId) || sessionId
3666
+ const hInfo = resolveEffectiveHandoff(runtime, sessionId, board)
3011
3667
  sendJson(res, 200, {
3012
3668
  ok: true,
3013
- text: renderHandoff(board, boundaries(runtime, sessionId), 5200, sessionId, {
3014
- teamTasks: fetchTeamTasks(runtime, sessionId ? { id: sessionId } : null),
3015
- takenOutArchives: rootSid ? collectTakenOutAndFlipped(runtime, rootSid, board.activeCabinetId) : [],
3016
- }),
3017
- 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,
3018
3682
  autoInject: !((board.settings || {}).autoInject === false),
3019
3683
  guardIdle: !((board.settings || {}).guardIdle === false),
3020
3684
  pending: pending ? { at: pending.at, by: pending.by, failedTarget: pending.failedTarget || '' } : null,
@@ -3033,7 +3697,7 @@ function routeTable(runtime) {
3033
3697
  const propRes = proposeBoundToChief(makeChiefDeps(runtime), {
3034
3698
  sessionId,
3035
3699
  by: typeof body.by === 'string' ? body.by : 'operator',
3036
- field: typeof body.field === 'string' ? body.field : 'forbidden',
3700
+ field: normalizeBoundFieldName(body.field) || 'forbidden',
3037
3701
  item: typeof body.item === 'string' ? body.item : (typeof body.text === 'string' ? body.text : ''),
3038
3702
  items: Array.isArray(body.items) ? body.items : undefined,
3039
3703
  reason: typeof body.reason === 'string' ? body.reason : '',
@@ -3080,12 +3744,19 @@ function routeTable(runtime) {
3080
3744
  const url = new URL(req.url || '/', 'http://127.0.0.1')
3081
3745
  let sessionId = url.searchParams.get('session') || ''
3082
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)
3083
3749
  if (req.method === 'POST') {
3084
3750
  const body = await readBody(req).catch(() => ({}))
3085
3751
  if (typeof body.session === 'string' && body.session) sessionId = body.session
3086
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
3087
3759
  }
3088
- const view = await getChiefView(makeChiefDeps(runtime), sessionId, { regenerate, autoSummarize: !regenerate })
3089
3760
  sendJson(res, 200, view)
3090
3761
  } catch (error) {
3091
3762
  sendJson(res, 500, { ok: false, error: String(error && error.message ? error.message : error) })
@@ -3113,6 +3784,28 @@ function routeTable(runtime) {
3113
3784
  }
3114
3785
  },
3115
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
+ },
3116
3809
  {
3117
3810
  path: API + '/chief/relay',
3118
3811
  handler: async (req, res) => {
@@ -3158,10 +3851,66 @@ function routeTable(runtime) {
3158
3851
  try {
3159
3852
  const body = await readBody(req)
3160
3853
  const sessionId = typeof body?.session === 'string' ? body.session : ''
3161
- const rootSid = resolveRootSessionId(sessionId) || sessionId
3162
- const updated = updateChiefConfig({ ...(body || {}), ...(rootSid ? { sessionId: rootSid } : {}) })
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
+ }
3163
3874
  const view = await getChiefView(makeChiefDeps(runtime), sessionId, { autoSummarize: false })
3164
- sendJson(res, updated && updated.ok === false ? 400 : 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)
3165
3914
  } catch (error) {
3166
3915
  sendJson(res, 400, { ok: false, error: String(error && error.message ? error.message : error) })
3167
3916
  }
@@ -3266,18 +4015,31 @@ function routeTable(runtime) {
3266
4015
  const url = new URL(req.url || '/', 'http://127.0.0.1')
3267
4016
  if (req.method === 'GET' || !req.method) {
3268
4017
  const sessionId = url.searchParams.get('session') || ''
3269
- const rootSid = resolveRootSessionId(sessionId) || sessionId
4018
+ const rootSid = resolveBoundRootSid(sessionId)
3270
4019
  const query = url.searchParams.get('q') || ''
3271
4020
  const folder = url.searchParams.get('folder') || ''
3272
4021
  const paperclip = url.searchParams.get('paperclip') || ''
3273
- const cabinetId = url.searchParams.get('cabinetId') || ''
3274
- const targetOpt = archiveTarget(runtime, rootSid || sessionId, cabinetId)
3275
- const out = listArchiveHeaders(rootSid, { query, folder, paperclip, includePrecipitated: true }, targetOpt)
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 })
3276
4026
  const st = loadChiefState()
3277
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)
3278
4037
  sendJson(res, 200, {
3279
4038
  ...out,
3280
- flippedPrecipitatedIds: (ws && Array.isArray(ws.flippedPrecipitatedIds)) ? ws.flippedPrecipitatedIds.slice() : [],
4039
+ requestedScope: reqScope,
4040
+ flippedPrecipitatedIds: flippedIds,
4041
+ deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
4042
+ counts: out.counts || getThreeTierArchiveCounts(rootSid, flippedIds, targetOpt),
3281
4043
  archiveMeta: getArchiveMeta(rootSid, targetOpt),
3282
4044
  })
3283
4045
  return
@@ -3285,10 +4047,12 @@ function routeTable(runtime) {
3285
4047
 
3286
4048
  const body = await readBody(req)
3287
4049
  const sessionId = typeof body.session === 'string' ? body.session : ''
3288
- const rootSid = resolveRootSessionId(sessionId) || sessionId
4050
+ const rootSid = resolveBoundRootSid(sessionId)
3289
4051
  const op = typeof body.op === 'string' ? body.op : 'save'
3290
- const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
3291
- const targetOpt = archiveTarget(runtime, rootSid || sessionId, cabinetId)
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 })
3292
4056
  const projectKey = resolveProjectKey(targetOpt.cwd)
3293
4057
 
3294
4058
  if (['flipOut', 'sealBack', 'deletePrecipitated', 'updatePrecipitated'].includes(op)) {
@@ -3310,18 +4074,50 @@ function routeTable(runtime) {
3310
4074
  }
3311
4075
  const stAfter = loadChiefState()
3312
4076
  const wsAfter = rootSid && stAfter.workspaces ? stAfter.workspaces[rootSid] : null
3313
- const archives = listArchiveHeaders(rootSid, { includePrecipitated: true }, targetOpt)
4077
+ const flippedAfter = (wsAfter && Array.isArray(wsAfter.flippedPrecipitatedIds)) ? wsAfter.flippedPrecipitatedIds.slice() : []
4078
+ const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedAfter }, targetOpt)
3314
4079
  sendJson(res, 200, {
3315
4080
  ...pRes,
3316
4081
  archives,
3317
- flippedPrecipitatedIds: (wsAfter && Array.isArray(wsAfter.flippedPrecipitatedIds)) ? wsAfter.flippedPrecipitatedIds.slice() : [],
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,
3318
4114
  archiveMeta: getArchiveMeta(rootSid, targetOpt),
3319
4115
  })
3320
4116
  return
3321
4117
  }
3322
4118
 
3323
4119
  if (op === 'precipitateNotes') {
3324
- // Sweep active board.notes (session and/or shared) into active working cabinet
4120
+ // Sweep active board.notes (session and/or shared) into active working cabinet (defaults to current session cabinet if bound)
3325
4121
  const noteIds = Array.isArray(body.noteIds) ? new Set(body.noteIds.map(String)) : null
3326
4122
  let sweptCount = 0
3327
4123
  const sweepFromFile = (targetFile) => {
@@ -3337,6 +4133,7 @@ function routeTable(runtime) {
3337
4133
  }
3338
4134
  const saved = mutateArchive({
3339
4135
  op: 'save',
4136
+ vaultScope: workingScope,
3340
4137
  sourceNoteId: note.id,
3341
4138
  title: note.title,
3342
4139
  body: note.body,
@@ -3350,20 +4147,24 @@ function routeTable(runtime) {
3350
4147
  }
3351
4148
  if (keep.length !== b.notes.length) {
3352
4149
  b.notes = keep
3353
- pushLog(b, `🗄️ 已将 ${sweptCount} 篇便签收纳进「档案」工作柜`, 'operator', sessionId)
4150
+ pushLog(b, `🗄️ 已将 ${sweptCount} 篇便签收纳进「${workingScope === 'global' ? '全局' : '本会话'}档案柜」`, 'operator', sessionId)
3354
4151
  saveBoard(b, targetFile)
3355
4152
  }
3356
4153
  })
3357
4154
  }
3358
4155
  if (sessionId) sweepFromFile(boardFileFor(sessionId))
3359
- 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() : []
3360
4160
  const board = sessionId ? boardForSession(boardFileFor(sessionId)) : emptyBoard()
3361
- const archives = listArchiveHeaders(rootSid, { includePrecipitated: true }, targetOpt)
4161
+ const archives = listArchiveHeaders(rootSid, { vaultScope: workingScope, includePrecipitated: true, flippedIds: flippedNow }, targetOpt)
3362
4162
  sendJson(res, 200, {
3363
4163
  ok: true,
3364
4164
  sweptCount,
3365
4165
  board,
3366
4166
  archives,
4167
+ counts: archives.counts || getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
3367
4168
  archiveMeta: getArchiveMeta(rootSid, targetOpt),
3368
4169
  })
3369
4170
  return
@@ -3371,6 +4172,7 @@ function routeTable(runtime) {
3371
4172
 
3372
4173
  const out = mutateArchive({
3373
4174
  ...body,
4175
+ vaultScope: workingScope,
3374
4176
  op,
3375
4177
  rootSessionId: rootSid,
3376
4178
  }, targetOpt)
@@ -3378,8 +4180,9 @@ function routeTable(runtime) {
3378
4180
  sendJson(res, 400, out)
3379
4181
  return
3380
4182
  }
4183
+ const isCrossCopy = op === 'copyToGlobal' || op === 'copyToSession'
3381
4184
  const usedCabId = out.activeCabinetId || out.cabinetId || ''
3382
- if (rootSid && usedCabId && op !== 'listCabinets') {
4185
+ if (rootSid && workingScope !== 'global' && !isCrossCopy && usedCabId && op !== 'listCabinets') {
3383
4186
  const bFile = boardFileFor(rootSid)
3384
4187
  withBoardLock(bFile, () => {
3385
4188
  const b = loadBoard(bFile)
@@ -3389,12 +4192,20 @@ function routeTable(runtime) {
3389
4192
  }
3390
4193
  })
3391
4194
  }
3392
- const finalOpt = archiveTarget(runtime, rootSid || sessionId, out.activeCabinetId || cabinetId || out.cabinetId)
3393
- const archives = listArchiveHeaders(rootSid, { includePrecipitated: true }, finalOpt)
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)
3394
4202
  const board = sessionId ? boardForSession(boardFileFor(sessionId)) : undefined
3395
4203
  sendJson(res, 200, {
3396
4204
  ...out,
3397
4205
  archives,
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),
3398
4209
  ...(board ? { board } : {}),
3399
4210
  archiveMeta: getArchiveMeta(rootSid, finalOpt),
3400
4211
  })
@@ -3411,10 +4222,11 @@ function routeTable(runtime) {
3411
4222
  const url = new URL(req.url || '/', 'http://127.0.0.1')
3412
4223
  const id = url.searchParams.get('id') || ''
3413
4224
  const sessionId = url.searchParams.get('session') || ''
3414
- const cabinetId = url.searchParams.get('cabinetId') || ''
3415
- const isPrecip = url.searchParams.get('precipitated') === '1' || url.searchParams.get('precipitated') === 'true'
3416
- const rootSid = resolveRootSessionId(sessionId) || sessionId
3417
- const targetOpt = archiveTarget(runtime, rootSid || sessionId, cabinetId)
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' })
3418
4230
  const out = isPrecip
3419
4231
  ? getPrecipitatedDetail(resolveProjectKey(targetOpt.cwd), id, rootSid, targetOpt)
3420
4232
  : getArchiveDetail(id, rootSid, targetOpt)
@@ -3431,19 +4243,61 @@ function routeTable(runtime) {
3431
4243
  try {
3432
4244
  const body = await readBody(req)
3433
4245
  const sessionId = typeof body.session === 'string' ? body.session : ''
3434
- const rootSid = resolveRootSessionId(sessionId) || sessionId
3435
- const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
3436
- const targetOpt = archiveTarget(runtime, rootSid || sessionId, cabinetId)
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 })
3437
4250
  const out = await organizeArchivesWithChief(makeChiefDeps(runtime), {
3438
- sessionId: rootSid,
4251
+ sessionId: rootSid || 'global',
4252
+ vaultScope,
3439
4253
  cabinetId,
3440
4254
  ids: Array.isArray(body.ids) ? body.ids : [],
3441
4255
  folder: typeof body.folder === 'string' ? body.folder : '',
3442
4256
  scope: typeof body.scope === 'string' ? body.scope : 'unorganized',
3443
4257
  instruction: typeof body.instruction === 'string' ? body.instruction : '',
3444
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() : []
3445
4297
  sendJson(res, out.ok ? 200 : 400, {
3446
4298
  ...out,
4299
+ deskItems: collectDeskItemsForUi(runtime, rootSid, cabinetId),
4300
+ counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
3447
4301
  archiveMeta: getArchiveMeta(rootSid, targetOpt),
3448
4302
  })
3449
4303
  } catch (error) {
@@ -3458,17 +4312,23 @@ function routeTable(runtime) {
3458
4312
  try {
3459
4313
  const body = await readBody(req)
3460
4314
  const sessionId = typeof body.session === 'string' ? body.session : ''
3461
- const rootSid = resolveRootSessionId(sessionId) || sessionId
4315
+ const rootSid = resolveBoundRootSid(sessionId)
3462
4316
  const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
3463
- const targetOpt = archiveTarget(runtime, rootSid || sessionId, cabinetId)
4317
+ const vaultScope = 'session'
4318
+ const targetOpt = archiveTarget(runtime, rootSid, { cabinetId, vaultScope })
3464
4319
  const out = await harvestTurnDetailsToArchive(makeChiefDeps(runtime), {
3465
4320
  sessionId: rootSid,
4321
+ vaultScope,
3466
4322
  cabinetId,
3467
4323
  trigger: 'manual',
3468
4324
  focusHint: typeof body.focusHint === 'string' ? body.focusHint : '',
3469
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() : []
3470
4329
  sendJson(res, out.ok ? 200 : 400, {
3471
4330
  ...out,
4331
+ counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
3472
4332
  archiveMeta: getArchiveMeta(rootSid, targetOpt),
3473
4333
  })
3474
4334
  } catch (error) {
@@ -3485,16 +4345,27 @@ function routeTable(runtime) {
3485
4345
  const sessionId = typeof body.session === 'string' ? body.session : ''
3486
4346
  const rootSid = resolveRootSessionId(sessionId) || sessionId
3487
4347
  const cabinetId = typeof body.cabinetId === 'string' ? body.cabinetId : ''
3488
- const targetOpt = archiveTarget(runtime, rootSid || sessionId, 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 })
3489
4354
  const out = await precipitateExperienceWithChief(makeChiefDeps(runtime), {
3490
4355
  sessionId: rootSid,
4356
+ vaultScope,
3491
4357
  op: typeof body.op === 'string' ? body.op : 'cabinet',
3492
4358
  cabinetId,
3493
4359
  folder: typeof body.folder === 'string' ? body.folder : '',
4360
+ ids: Array.isArray(body.ids) ? body.ids : [],
3494
4361
  clearSource: Boolean(body.clearSource),
3495
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() : []
3496
4366
  sendJson(res, out.ok ? 200 : 400, {
3497
4367
  ...out,
4368
+ counts: getThreeTierArchiveCounts(rootSid, flippedNow, targetOpt),
3498
4369
  archiveMeta: getArchiveMeta(rootSid, targetOpt),
3499
4370
  })
3500
4371
  } catch (error) {
@@ -3522,6 +4393,7 @@ function syncPlanFromTodos(args, sessionId) {
3522
4393
 
3523
4394
  /** create_goal / update_goal → objective. */
3524
4395
  function syncObjective(name, args, sessionId) {
4396
+ if (isObjectiveLockedByIntervention(sessionId)) return
3525
4397
  const objective = objectiveFromGoal(name, args)
3526
4398
  if (!objective) return
3527
4399
  const file = boardFileFor(sessionId)
@@ -3696,6 +4568,7 @@ const BOARD_PARAMETERS = {
3696
4568
  'archive.search',
3697
4569
  'archive.read',
3698
4570
  'archive.save',
4571
+ 'context.compact',
3699
4572
  'memory.add',
3700
4573
  'memory.remove',
3701
4574
  'memory.ask',
@@ -3704,8 +4577,9 @@ const BOARD_PARAMETERS = {
3704
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). '
3705
4578
  + 'Use "graph.plan" (or "task.batch") to plan a hierarchical/DAG task graph in one call (supports parentId, blockedBy, owner/subagent, intent, evidence). '
3706
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. '
3707
- + '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. '
3708
- + '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.',
3709
4583
  },
3710
4584
  tasks: {
3711
4585
  type: 'array',
@@ -3821,15 +4695,15 @@ const BOARD_PARAMETERS = {
3821
4695
  priority: { type: 'string', enum: PRIORITIES, description: 'Task priority.' },
3822
4696
  field: {
3823
4697
  type: 'string',
3824
- enum: ['allowed', 'forbidden', 'notes'],
3825
- 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" = 注意事项).',
3826
4700
  },
3827
4701
  item: { type: 'string', description: 'bounds.propose / bounds.add / bounds.pin / bounds.remove / bounds.edit / bounds.consolidate: boundary rule text.' },
3828
4702
  oldItem: { type: 'string', description: 'bounds.edit: existing boundary rule text to replace.' },
3829
4703
  removeItems: { type: 'array', items: { type: 'string' }, description: 'bounds.consolidate: scattered boundary rules to remove and replace with item.' },
3830
4704
  reason: { type: 'string', description: 'bounds.propose: brief context on why this boundary is needed (e.g. wall hit, permission block, or user request).' },
3831
4705
  items: { type: 'array', items: { type: 'string' }, description: 'bounds.propose (multiple rules) or bounds.set (new contents of column named by field).' },
3832
- 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.' },
3833
4707
  forbidden: { type: 'array', items: { type: 'string' }, description: 'bounds.set: the whole 禁止 column.' },
3834
4708
  notes: { type: 'array', items: { type: 'string' }, description: 'bounds.set: the whole 注意 column.' },
3835
4709
  autoInject: { type: 'boolean', description: 'settings.set: hand the digest to every turn of this machine.' },
@@ -3934,7 +4808,7 @@ function boardTool(runtime) {
3934
4808
  'Shared task graph, subagent team controller, cross-session communication bus, plan, and anchor chief (参谋看板, coordinated by DSH 参谋长). '
3935
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. '
3936
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. '
3937
- + '(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.',
3938
4812
  parameters: BOARD_PARAMETERS,
3939
4813
  output: {
3940
4814
  schema: { type: 'object', description: 'The board summary after the operation.' },
@@ -4075,7 +4949,7 @@ function boardTool(runtime) {
4075
4949
  sessionId: rawSession,
4076
4950
  callerAgent,
4077
4951
  by: byDefault,
4078
- field: str(passed.field, 'forbidden'),
4952
+ field: normalizeBoundFieldName(passed.field) || 'forbidden',
4079
4953
  item: str(passed.item || passed.text || passed.note || passed.body, ''),
4080
4954
  items: Array.isArray(passed.items) ? passed.items : undefined,
4081
4955
  reason: str(passed.reason || passed.intent || passed.subject, ''),
@@ -4132,6 +5006,24 @@ function boardTool(runtime) {
4132
5006
  }
4133
5007
  }
4134
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
+
4135
5027
  if (passed.action === 'task.dispatch' || passed.action === 'team.steer' || passed.action === 'team.interrupt') {
4136
5028
  const subRes = await executeSubagentAction(runtime, { ...passed, by: byDefault, session }, callerAgent, exec && exec.signal)
4137
5029
  if (!subRes.ok) return { ok: false, error: subRes.error }
@@ -4340,7 +5232,7 @@ function handoffTool(runtime) {
4340
5232
  // dropped by whichever rename finished second.
4341
5233
  withBoardLock(selfFile, () => {
4342
5234
  const marked = loadBoard(selfFile)
4343
- marked.handoff = { at: nowMs(), by: 'agent', session }
5235
+ marked.handoff = { ...(marked.handoff || {}), at: nowMs(), by: 'agent', session }
4344
5236
  pushLog(marked, '交接单已生成并交出', 'agent', session)
4345
5237
  saveBoard(marked, selfFile)
4346
5238
  })
@@ -4349,14 +5241,17 @@ function handoffTool(runtime) {
4349
5241
  // wrote bounds/objective must still tell the successor what the operator
4350
5242
  // forbade and what the machine is working on.
4351
5243
  const board = boardForSession(selfFile)
4352
- const limits = boundaries(runtime, session)
4353
- 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
+ )
4354
5250
  return {
4355
5251
  ok: true,
4356
- text: renderHandoff(board, limits, 5200, session, {
4357
- teamTasks: fetchTeamTasks(runtime, exec && exec.agent ? exec.agent : null),
4358
- takenOutArchives: rootSid ? getTakenOutArchivesForSession(rootSid, boardFile()) : [],
4359
- }),
5252
+ text: hInfo.text,
5253
+ pinned: hInfo.pinned,
5254
+ source: hInfo.source,
4360
5255
  counts: {
4361
5256
  plan: (board.plan || []).length,
4362
5257
  openSteps: (board.plan || []).filter(step => !step.done).length,
@@ -4496,7 +5391,18 @@ export function deployStateToTargetChief(runtime, {
4496
5391
  dest.bounds = destBounds
4497
5392
 
4498
5393
  // Carry non-anchor handoff context notes selectively if target has room
4499
- dest.handoff = { at: nowMs(), by: 'deploy', session: fromRoot }
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
+ }
4500
5406
  pushLog(
4501
5407
  dest,
4502
5408
  `🚀 已系统级移交部署自会话 ${fromRoot.slice(0, 12)}:计划 ${copiedStepCount} 步、未完任务 ${copiedTaskCount} 项`,
@@ -4556,10 +5462,7 @@ export async function transferChief(runtime, args, sessionId) {
4556
5462
 
4557
5463
  const board = boardForSession(boardFileFor(sessionId))
4558
5464
  const rootSid = resolveRootSessionId(sessionId) || sessionId
4559
- const packet = renderHandoff(board, boundaries(runtime, sessionId), 5200, sessionId, {
4560
- teamTasks: fetchTeamTasks(runtime, sessionId ? { id: sessionId } : null),
4561
- takenOutArchives: rootSid ? collectTakenOutAndFlipped(runtime, rootSid, board.activeCabinetId) : [],
4562
- })
5465
+ const packet = resolveEffectiveHandoff(runtime, sessionId, board).text
4563
5466
  const by = typeof passed.by === 'string' && passed.by ? passed.by : 'user'
4564
5467
 
4565
5468
  if (!target || target === 'new' || target === 'latest') {
@@ -4784,6 +5687,55 @@ export function apply(ctx) {
4784
5687
  pushLog,
4785
5688
  })
4786
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
+
4787
5739
  ctx.inject(['llm'], llmCtx => {
4788
5740
  const ownLlm = (llmCtx && llmCtx.llm) || (llmCtx && llmCtx.get ? llmCtx.get('llm') : null)
4789
5741
  if (ownLlm) activeLlm = ownLlm
@@ -4837,11 +5789,20 @@ export function apply(ctx) {
4837
5789
  const board = boardForSession(boardFileFor(rootId))
4838
5790
  const agentIdentity = resolveAgentIdentity(runtime, curId, liveAgent)
4839
5791
  const subagents = getSubagentRoster(runtime, rootId, board)
4840
- const secState = loadChiefState()
4841
- const linkedPeersCount = Math.max(0, getLinkedCluster(secState, rootId || 'global').length - 1)
4842
- const takenOutArchives = rootId ? collectTakenOutAndFlipped(runtime, rootId, board.activeCabinetId) : []
5792
+ const linked = linkedPeersForSession(runtime, rootId || 'global')
5793
+ const archCtx = collectDigestArchiveContext(runtime, rootId, board.activeCabinetId)
4843
5794
  if (rootId) refreshSubagentTree(runtime, rootId, board).catch(() => {})
4844
- 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
+ })
4845
5806
  },
4846
5807
  }), 'dsh-chief: prompt digest')
4847
5808
  })
@@ -4917,24 +5878,42 @@ export function apply(ctx) {
4917
5878
  } catch {}
4918
5879
  }), 'dsh-chief: deliver pending transfer')
4919
5880
 
4920
- // 2c) Incremental record of what each turn actually did: which turns called a
4921
- // tool at all, and which of them moved the plan. The idle guard reads both
4922
- // first and falls back to the Session log, so a dropped event cannot make it
4923
- // cry wolf about work that did happen — and, more importantly, a turn that ran
4924
- // 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).
4925
5883
  ctx.effect(() => ctx.on('session/event', (session, event) => {
4926
5884
  try {
4927
- if (!event || event.type !== 'tool/call') return
4928
- if (!event.data || !session || !session.id) return
5885
+ if (!event || !session || !session.id) return
4929
5886
  const id = String(session.id)
4930
- const turn = event.data.turn
4931
- noteToolCall(id, turn)
4932
- if (isPlanWrite(event.data.name, event.data.arguments)) notePlanWrite(id, turn)
4933
- // The loop shape needs the call itself, not just the turn: same tool with
4934
- // the same arguments N times is the tell that nothing is moving.
4935
- 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
+ }
4936
5915
  } catch {}
4937
- }), 'dsh-chief: tool call ledger')
5916
+ }), 'dsh-chief: tool call ledger & auto-continue')
4938
5917
 
4939
5918
  // 3) One heartbeat per finished turn: which Sessions are still warm — and the
4940
5919
  // idle guard: a turn that closes with a short answer, no tool call, and open
@@ -5012,7 +5991,16 @@ export function apply(ctx) {
5012
5991
  reconcileTaskDependencies(board, identity.self, id)
5013
5992
  }
5014
5993
  saveBoard(board, file)
5015
- 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)
5016
6004
  return
5017
6005
  }
5018
6006
 
@@ -5028,8 +6016,9 @@ export function apply(ctx) {
5028
6016
  }
5029
6017
 
5030
6018
  if (typeof agent.steer !== 'function') {
5031
- pushLog(board, '空转拦截:这个 agent 没有 steer 方法,无法补一步', 'guard', id)
6019
+ pushLog(board, '空转拦截:这个 agent 没有 steer 方法,转由断线续跑模块跟进', 'guard', id)
5032
6020
  saveBoard(board, file)
6021
+ autoContinue.notifyIdleOrInterrupt(id, { kind: 'idle-stall', reason: verdict.reason || '' })
5033
6022
  return
5034
6023
  }
5035
6024
 
@@ -5037,6 +6026,11 @@ export function apply(ctx) {
5037
6026
  // observe a board that claims an intervention that never happened.
5038
6027
  const notice = buildNotice({ ...verdict, board })
5039
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
+ }
5040
6034
  noteIntervention(id, turn)
5041
6035
  // Clear the trail only once the steer landed: a loop that survived a
5042
6036
  // failed steer deserves the next nudge, not a silent reset.
@@ -5051,10 +6045,7 @@ export function apply(ctx) {
5051
6045
  // tells the model to wrap up; this packet is what the next one reads.
5052
6046
  if (remainingInterventions(id, settings) === 0) {
5053
6047
  try {
5054
- const rootForHandoff = resolveRootSessionId(id) || id
5055
- const packet = renderHandoff(board, boundaries(runtime, id), 5200, id, {
5056
- takenOutArchives: rootForHandoff ? getTakenOutArchivesForSession(rootForHandoff, boardFile()) : [],
5057
- })
6048
+ const packet = resolveEffectiveHandoff(runtime, id, board).text
5058
6049
  const pendingFile_ = pendingFile()
5059
6050
  fs.writeFileSync(pendingFile_, JSON.stringify({ text: packet, at: nowMs(), from: id }))
5060
6051
  pushLog(board, '上下文压力:干预计数耗尽,交接单已自动生成并放入待领取', 'handoff', id)